Rails: if statement in .map() - ruby-on-rails-3

I want to map some values from a table to an array. Works fine, except for the fact that the database has some nil values in it, which creates invalid JSON. So far I have this:
#markers = ExtendedProfile.all.map{|u|[u.city, u.latitude, u.longitude]}
Now what I want to do is check if the fields are filled in, and if not, enter a default value. So for example if u.latitude == nil I want to enter 0.0 in the array, instead of nil. Any idea about how to accomplish this?

For better understanding, you can extend to the map block syntax like this:
#markers = ExtendedProfile.all.map do |u|
if u.latitude.nil?
[0, 0]
else
[u.city, u.latitude, u.longitude]
end
end

Use u.latitude || 0.0:
#markers = ExtendedProfile.all.map{|u|[u.city, u.latitude || 0.0, u.longitude || 0.0]}

Related

how to put in a param even if the value of param is null

so my code is as follows:
* def value = newMP.response.data[randomizer].phoneNumber
* def nullvalue = 'null'
* def filter = (value == '#null' ? nullvalue : value)
* print filter
And param filter[phoneNumber] = filter
The result of this code is
Thing is that my application allows a search for null as well. therefore im looking if its possible to put in a filter that is null based on the conditional logic
Additionally if i go like this
And param filter[phoneNumber] = 'null'
the null value is in the GET call
Yes by default Karate ignores null-valued params and this is what most users expect.
You have not been clear as to what you are expecting but I'm guessing you need a param with an empty value.
Try this:
And param filter = ''
Also read this example for more ideas: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/search/dynamic-params.feature
What i required was to put in the value of the parameter as either null or "null", and the validate in response that the value is null, not the string form of it. below is the workaround for it.
And def value = newMP.response.data[randomizer].phoneNumber
And eval if (value == null) karate.set('value', 'null')
And param filter[phoneNumber] = value
When method GET
Then status 200
* eval if (value == 'null') karate.set('value', null)
Then match response.data[0].attributes.phoneNumber contains value

Matlab's arrayfun for uniform output of class objects

I need to build an array of objects of class ID using arrayfun:
% ID.m
classdef ID < handle
properties
id
end
methods
function obj = ID(id)
obj.id = id;
end
end
end
But get an error:
>> ids = 1:5;
>> s = arrayfun(#(id) ID(id), ids)
??? Error using ==> arrayfun
ID output type is not currently implemented.
I can build it alternatively in a loop:
s = [];
for k = 1 : length(ids)
s = cat(1, s, ID(ids(k)));
end
but what is wrong with this usage of arrayfun?
Edit (clarification of the question): The question is not how to workaround the problem (there are several solutions), but why the simple syntax s = arrayfun(#(id) ID(id), ids); doesn't work. Thanks.
Perhaps the easiest is to use cellfun, or force arrayfun to return a cell array by setting the 'UniformOutput' option. Then you can convert this cell array to an array of obects (same as using cat above).
s = arrayfun(#(x) ID(x), ids, 'UniformOutput', false);
s = [s{:}];
You are asking arrayfun to do something it isn't built to do.
The output from arrayfun must be:
scalar values (numeric, logical, character, or structure) or cell
arrays.
Objects don't count as any of the scalar types, which is why the "workarounds" all involve using a cell array as the output. One thing to try is using cell2mat to convert the output to your desired form; it can be done in one line. (I haven't tested it though.)
s = cell2mat(arrayfun(#(id) ID(id), ids,'UniformOutput',false));
This is how I would create an array of objects:
s = ID.empty(0,5);
for i=5:-1:1
s(i) = ID(i);
end
It is always a good idea to provide a "default constructor" with no arguments, or at least use default values:
classdef ID < handle
properties
id
end
methods
function obj = ID(id)
if nargin<1, id = 0; end
obj.id = id;
end
end
end

Eager Loading by Setting Variable

Sorry in advance for this incredibly simple question, but what is the best way to set a variable while also checking a condition. For example, I have:
#friends = []
#user.facebook_friends.each do |key,value|
if test = Authorization.includes(:user).find_by_uid(key) != nil
#friends << {"name" => test.user.name, "facebook_image_url" => test.user.facebook_image_url}
end
end
I am trying to pull in the user records when I pull in the authorization record, so as to minimize my database queries. I know that I can't write
test = Authorization.includes(:user).find_by_uid(key) != nil
in order to set the test variable. What is the best way to write this code so that it is functional?
You just need parens:
(test = Authorization.includes(:user).find_by_uid(key)) != nil
Also here is a more rails way to do it:
unless (test = Authorization.includes(:user).find_by_uid(key)).nil?
#friends << {"name" => test.user.name, "facebook_image_url" => test.user.facebook_image_url}
end

.NET 4 - Using nullable operator (??) to simplify if statements

I have this piece of code, that checks whether a returned object is null. If so, it will return 0, or else it will return a property inside the object.
var userPoints = (from Point p in entities.Point
where p.UserName == userName
select p).SingleOrDefault();
if (userPoints == null)
{
return 0;
}
else
{
return userPoints.Points;
}
Is it possible to simplify the if statements with the nullable operator? I've tried this, but the system throws an exception when attempting to read the property
return userPoints.Points ?? 0;
No, unfortunately there's nothing which will do exactly that. Options:
Use the conditional operator:
return userPoints == null ? 0 : userPoints.Points;
Change your query to make that do the defaulting:
return (from Point p in entities.Point
where p.UserName == userName
select p.Points).SingleOrDefault();
Personally I'd go for the latter approach :) If you wanted a default other than 0, you'd need something like:
return (from Point p in entities.Point
where p.UserName == userName
select (int?) p.Points).SingleOrDefault() ?? -1;
You can do this:
var userPoints = (from Point p in entities.Point
where p.UserName == userName
select p.Point).SingleOrDefault();
return userPoints;
If there are no results then userPoints will be 0, otherwise it will be the value of Points.
You can't use it in your context.
Explanation:
You want to check whether userPoints is null, but want to return userPoints.Points if it is not null.
The ?? operator checks the first operand for null and returns it, if it is not null. It doesn't work if what you want to check and what you want to return are two different things.
Hover over var with the mouse and see what type it is.

lua call function from a string with function name

Is it possible in lua to execute a function from a string representing its name?
i.e: I have the string x = "foo", is it possible to do x() ?
If yes what is the syntax ?
To call a function in the global namespace (as mentioned by #THC4k) is easily done, and does not require loadstring().
x='foo'
_G[x]() -- calls foo from the global namespace
You would need to use loadstring() (or walk each table) if the function in another table, such as if x='math.sqrt'.
If loadstring() is used you would want to not only append parenthesis with ellipse (...) to allow for parameters, but also add return to the front.
x='math.sqrt'
print(assert(loadstring('return '..x..'(...)'))(25)) --> 5
or walk the tables:
function findfunction(x)
assert(type(x) == "string")
local f=_G
for v in x:gmatch("[^%.]+") do
if type(f) ~= "table" then
return nil, "looking for '"..v.."' expected table, not "..type(f)
end
f=f[v]
end
if type(f) == "function" then
return f
else
return nil, "expected function, not "..type(f)
end
end
x='math.sqrt'
print(assert(findfunction(x))(121)) -->11
I frequently put a bunch of functions in a table:
functions = {
f1 = function(arg) print("function one: "..arg) end,
f2 = function(arg) print("function two: "..arg..arg) end,
...,
fn = function(arg) print("function N: argh") end,
}
Then you can use a string as an table index and run your function like this
print(functions["f1"]("blabla"))
print(functions["f2"]("blabla"))
This is the result:
function one: blabla
function two: blablablabla
I find this to be cleaner than using loadstring(). If you don't want to create a special function table you can use _G['foo'].
loadstring is not the answer here. For starters you would need a return in the string, and other details I won't go into.
THC4k has the right idea; if you have the function name in the variable x, then the call you want is
_G[x](arg1, arg2, ...)
Names are not unique, there can be many functions names foo in different namespaces. But _G['foo'] is foo in the global namespace.
It sounds like you want to do an 'eval', which is supported in Lua like so:
assert(loadstring(x))()
You'll probably want to concatenate the "()" onto x first, though.