Is there a difference between the two Map Assignments [] and putifabsent? - dart

Is there any performance or any other difference between defining [] or put if absent
map["x"] = 123;
map.putifabsent("z", ()=> 123);

Aside from map['x'] = 123 will overwrite the value for key'x' if it is already in the map whereas map.putifAbsent('x', ()=> 123) will not ?
Note that putifAbsent returns the value corresponding to the provided key. You can use it to get the value for a key, generating and inserting a value 'on the fly' if the key in missing from the map (which is why its second argument is a function, not a straight value).
It strikes me that this was the use case for the method, but the name getValuePutIfAbsent was deemed too long.

Related

Having different count per key in jsonb

I have values in a table called Translation, that contains for every values per example:
=> {"fr"=>"Jaune", "de"=>"", "en"=>"", "bg"=>"", "hr"=>"", "es"=>"", "hu"=>"", "it"=>"", "lt"=>"", "lv"=>"", "nl"=>"", "pl"=>"", "pt"=>"", "ro"=>"", "cs"=>""}
and I'm looking to get the the number of the translation for each language:
I'm trying :
Translation.where("values->>'fr' IS NOT NULL").count
but it giving me 0, which is not correct, do anyone knows how to do it correctly?
The problem that you have is that the keys that don't have values, still exist in the json, so "is not null" will return all of them because the key exist. you have two options here, you can remove the empty keys from the database, so not null will work, or, change it to see if the key is empty
You can do it like this
Translation.where("values->>'fr' <> ''").count
and it will work with the structure that you have right now.

Need help in understanding the Erlang code and what exactly it is doing

I am finding it difficult to decipher this code. I could understand that there is an instance of a data structure; is it a record or map?
The query is regarding the last two line of the code does it update the record with Response or does it check message_code?
Response =
#{header =>
#{message_code => 'CONN_ESTABLISH_REQUEST',
protocol_instance => ?MGMT_PROTOCOL_IDENTIFIER,
transaction_identifier => 1},
content => #{revision_list => [0]}
},
#{header := #{message_code := 'CONN_ESTABLISH_CONFIRM'},
content := Confirmation} = Response
It's a map, not a record. (If it were a record, the record name would be between the # and the {.)
The last two lines perform a pattern match on the variable Response. The code asserts that Response is a map containing at least two keys, header and content. The value for header must be a map containing at least one key, message_code, whose value is 'CONN_ESTABLISH_CONFIRM'. The value for content will be stored in the variable Confirmation.
If the value of Response doesn't conform to all those requirements, this code will signal a badmatch error.
Note that the behaviour is different depending on whether the right hand side of := contains:
a constant
an unbound variable
a bound variable (a variable that already has a value)
If it is an unbound variable, the value for that key is simply stored in that variable. If it is a bound variable, the value for that key must match the value of that variable, otherwise you get a badmatch error just like for a non-matching constant.
As you see, there are two different delimiters used, => and :=. When constructing a new map (such as the first expression in your example), you can only use =>, and when pattern matching, you can only use :=. The idea is that they do different things: => stores a key-value pair in the map, while := extracts an existing key-value pair.
There is another case: updating an existing map. In that case you can use both. => can be used to add a new key to the map, while := can only be used to update an existing key, otherwise it signals a badarg error. For example, if you wanted to add a "footer" to Response, you have to use =>:
NewResponse = Response#{footer => [some,data]},
%% this signals a badarg error:
NewResponse = Response#{footer := [some,data]},
while if you want to change the content, you can use either:
NewResponse = Response#{content := 42},
NewResponse = Response#{content => 42},

Is there a way to tell `next` to start at specific key?

My understanding is that pairs(t) simply returns next, t, nil.
If I change that to next, t, someKey (where someKey is a valid key in my table) will next start at/after that key?
I tried this on the Lua Demo page:
t = { foo = "foo", bar = "bar", goo = "goo" }
for k,v in next, t, t.bar do
print(k);
end
And got varying results each time I ran the code. So specifying a starting key has an effect, unfortunately the effect seems somewhat random. Any suggestions?
Every time you run a program that traverses a Lua table the order will be different because Lua internally uses a random salt in hash tables.
This was introduced in Lua 5.2. See luai_makeseed.
From the lua documentation:
The order in which the indices are enumerated is not specified, even
for numeric indices. (To traverse a table in numeric order, use a
numerical for.)

ActiveRecord Integer Column won't accept some Integer assignments

I'm seeing some genuinely bizarre behavior w/ ActiveRecord as it relates to assignment. I have an ActiveRecord model named Venue that includes the measurements of the Venue, all integers less than 1K. We add Venues via an XML feed. On the model itself, I have a Venue.from_xml_feed method takes the XML, parses, and creates Venues.
The problem comes from the measurements. Using Nokogiri, I'm parsing out the measurements like so:
elems = xml.xpath("//*[#id]")
elems.each do |node|
distance = node.css("distances")
rs = distance.attr("rs")
// get the rest of the sides
# using new instead of create to print right_side, behavior is the same
venue = Venue.new right_side: rs # etc
venue.save
puts venue.right_side
end
The problem is that venue.right_side ALWAYS evaluates to nil, even though distance.attr("rs") contains a legal value, say 400. So this code:
rs = distance.attr("rs")
puts rs
Venue.new right_side: rs
Will print 400, then save rs as nil. If I try any type of Type Conversions, like so:
content = distance.attr("rs").content
str = content.to_s
int = Integer(str)
puts "Is int and Integer? #{int.is_a? Integer}"
Venue.new right_side: int
It will print Is int an Integer? true, then again save again save Venue.right_side as nil.
However, if I just explicitly create a random integer like so:
int = 400
Venue.new right_side: int
It will save Venue.right_side as 400. Can anyone tell me what's going on with this?
Well, you failed to include the prerequisite sample XML to confirm this, so you get a fairly generic answer.
In your code you're using:
distance = node.css("distances")
rs = distance.attr("rs")
css doesn't return what you think it does. It returns a NodeSet, which is similar to an Array. When you try to use attr on a NodeSet, you're going to set the value, not retrieve it. From the documentation:
#attr(key, value = nil, &blk) ⇒ Object (also: #set, #attribute)
Set the attribute key to value or the return value of blk on all Node objects in the NodeSet.
Because you're not using a value, the resulting action is to remove the attribute from the tag, which will then return nil and Ruby will assign nil to rs.
If you want to get the attribute of a node, you need to point to the node itself, so use at, or at_css, either of which returns a Node. Once you have the node, you can use attribute to retrieve the value, or use the [] shortcut similar to this untested code:
rs = node.at('distances')['rs']
Again though, because you didn't supply XML it's not possible to tell what else you might be trying to do, or whether this code is entirely accurate.

Rawset function in lua

Rawset function in lua generally is passed table, index and value but I came across this code:
rawset(tbl,name,{})
and
rawset(tbl,name, function() end)
Rawset function returns a table, so what does it mean to have a table or function in rawset function in place for value ?
Lua tables can hold values of all types, including tables and functions, and they can be heterogeneous: not all values need to be of the same type.
See http://www.lua.org/manual/5.2/manual.html#2.1.
From reference manual:
rawset (table, index, value): Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value.
What this means:
table's metatable is not used: that's why it is "raw" set, the field is added directly; without raw, the table's metatable will be used to handle the "set" action;
index any value different from nil: in Lua, this really means any type of Lua object other than nil: a number, a function, another table, etc (Lua ref manual lists all types);
value any Lua value: same as previous, but can even be nil: if set to nil, effectively removes item from table.
So index being name just indicates the table is an associative array (unless name is a number but that would be misleading), in first case the associated value is another table, in the second case it is a Lua function.

Resources