Setting properties to an object in coffee script - syntax

Say I have an object alphabets and I want to set a couple of properties from another object like-
alphabets.a = data.a
alphabets.b = data.b
alphabets.c = data.c
Is there a way to remove the redundant usage of the variable alphabets and data?
UPDATE:
Assume that the properties have the same name. Now to remove the over use of property the variable reference data I can do the following
alphabets = (-> {aa, bb,cc}).call data
But the problem is that this will create a new object alphabets and what I want is that it should just add the properties to an already available object.

All you need to do is use the bracket notation of javascript, coupled with coffescript's for/of comprehension:
coffee> alphabets
{ a: '1', b: '2', c: '3' }
coffee> data = {}
{}
------> for k,v of alphabets # use Ctrl-V to get the multiline prompt
....... data["#{k}#{k}"] = v
[ '1', '2', '3' ]
coffee> data
{ aa: '1', bb: '2', cc: '3' }
coffee>

Related

Perl: Using data from an anonymous hash

I am adding on to another developers code, we are both new to perl I am trying to take a list of IPs and run it through whois. I am unsure how to access the data in the anonymous hash, how do I use it?
He told me the data was stored inside one. This is the only instance I could find mentioning a hash:
## Instantiate a reference to an anonymous hash (key value pair)
my $addr = {};
The anonymous hash is the {} part. It returns a reference which can be stored in a scalar variable, like in your example:
my $addr = {};
To see the structure, you can print it with Data::Dumper:
use Data::Dumper;
print Dumper $addr;
It might show you something like:
$VAR1 = {
'c' => 1,
'a' => 2
};
You access the hash keys using the arrow operator:
print $addr->{"a"}
Like how you would access a regular hash, but with the arrow operator in between.
You can dereference the reference by putting a hash sigil in front
%$addr
# compare %addr %$addr
# hash hashref dereferenced
Here is an anonymous hash:
my $anon_hash = {
key1 => 'Value 1',
key2 => 'Value 2',
key3 => 'Value 3',
}
If you want to access an individual value:
my $value = $anon_hash->{key1};
say $anon_hash->{key2};
If you want to update an individual value:
$anon_hash->{key3} = 'New value 3';
If you want to add a new key/value pair:
$anon_hash->{key4} = 'Value 4';
You can also use all of the standard hash functions (e.g. keys()). You just need to "deference" your hash reference - which means putting a '%' in front of it.
So, for example, to print all the key/value pairs:
foreach my $key (keys %$anon_hash) {
say "$key : $anon_hash->{$_}";
}

How to use StartsWith with an array of string?

Suppose I have an array of strings:
var array = new string[] {"A", "B"}.
Then I want check if the following string: "boca" starts with the letter included in the array.
What I did is:
var result = "boca".StartsWith(array);
but the method doesn't not accept an arra as argument but a single string
You have to loop the array and check if the word starts with anything in the array. Something like this:
var result = array.Any(s => "boca".StartsWith(s));
Assuming your array is {"A", "B"}, then result will be false, because StartsWith is case-sensitive by default.
If you want it case-insensitive, then this will work:
var result = array.Any(s => "boca".StartsWith(s, StringComparison.CurrentCultureIgnoreCase));
In this case, result will be true.

d3 tickFormat, remove comma as thousands separator

In a d3 graph, we get comma as thousands separator as default and I would like to remove them and have the x-axis ticks displayed as for example "2 000 000" instead of "2,000,000"
This is what I've tried:
private scaleX: ScaleLinear<number, number>;
private xAxisComponent: any;
// Define an x Axis
const axisNumberFormat: FormatLocaleDefinition = {
'decimal': '.',
'thousands': ' ',
'grouping': [3],
'currency': ['', ''],
};
const axisFormatLocale: FormatLocaleObject = this.d3.formatDefaultLocale(axisNumberFormat);
this.xAxisComponent = this.d3.axisBottom(this.scaleX).tickFormat(axisFormatLocale);
However, the assignment on the last line does not work, it says "Argument of type 'FormatLocaleObject' is not assignable to parameter of type 'null'." Any tips? Or am I doing this the wrong way, is there another way to put together a format string to send to the tickFormat() method?
The last line will work if .format('') is added to axisFormatLocale:
this.xAxisComponent = this.d3.axisBottom(this.scaleX).tickFormat(axisFormatLocale.format(''));

Sort a table with UTF-8 encoded values alphabetically

I am storing dictionary entries in a Lua table, using it as an array. I want to sort the entries from Lua, so that I can add new ones without having to move to the correct position myself (which gets quite tedious soon). However, I am facing several problems:
Many words contain non-ASCII characters, which makes the built-in comparison operator for strings unsuitable for the task (for instance, it makes amputar come before ámbito).
There are words from various languages (all Western, though), namely Spanish, German and English. The problem here is that, probably, different languages have different notions of the alphabetical order. Since the main language is Spanish, I would like to use its rules, although I'm unsure as to whether that will work with characters not contained in the Spanish alphabet.
Some words contain capital letters, or, even worse, start with them. For example, all German nouns start with upper-case letters. By the built-in comparison operator, the capital letters come before their lower-case siblings, which is not my desired behaviour; I would like upper-case letters to be treated exactly as their lower-case counterparts.
Take, for example, the following table:
local entries =
{
'amputar',
'Volksgeist',
'ámbito'
}
Those entries should be ordered like this:
ámbito
amputar
Volksgeist
However, with my current code, the output is wrong:
local function compare_utf8_strings( o1 , o2 )
-- Using the built-in non-UTF-8-aware non-locale-aware string comparison operator
return o1 < o2
end
table.sort( entries , function ( a , b ) return compare_utf8_strings( a , b ) end )
for i, entry in ipairs(entries) do
print( entry )
end
That outputs:
Volksgeist
amputar
ámbito
Could you please take the following code, and hack it to fulfill my requirements?
local entries =
{
'amputar',
'Volksgeist',
'ámbito'
}
local function compare_utf8_strings( o1 , o2 )
-- Hack here, please, accomplishing my requirements
end
table.sort( entries , function ( a , b ) return compare_utf8_strings( a , b ) end )
for i, entry in ipairs(entries) do
print( entry )
end
It should output this:
ámbito
amputar
Volksgeist
As an additional requirement, this Lua code is all inside LuaTeX, which currently supports 5.2 version of the language. As for external libraries, I guess it's possible to use them.
I am a novice in the Lua camp, so, please, forgive any error I have made, and feel free to notify it, so I fix it.
After some time searching to no avail, I found this article by Joseph Wright. Although it touched my issue, it didn't provide a clear solution to follow. I asked him, and it turned out that there's currently no direct way to do what I want. He pointed out, however, that slnunicode comes built-in with LuaTeX (albeit it will be replaced in the future).
I developed a 'crude' solution using the facilities provided in the LuaTeX environment. It isn't elegant, but it works, and it doesn't pull any external dependencies. About its efficiency, I have not perceived any difference in the document build time.
-- Make the facilities available
unicode = require( 'unicode' )
utf8 = unicode.utf8
--[[
Each character's position in this array-like table determines its 'priority'.
Several characters in the same slot have the same 'priority'.
]]
local alphabet =
{
-- The space is here because of other requirements of my project
{ ' ' },
{ 'a', 'á', 'à', 'ä' },
{ 'b' },
{ 'c' },
{ 'd' },
{ 'e', 'é', 'è', 'ë' },
{ 'f' },
{ 'g' },
{ 'h' },
{ 'i', 'í', 'ì', 'ï' },
{ 'j' },
{ 'k' },
{ 'l' },
{ 'm' },
{ 'n' },
{ 'ñ' },
{ 'o', 'ó', 'ò', 'ö' },
{ 'p' },
{ 'q' },
{ 'r' },
{ 's' },
{ 't' },
{ 'u', 'ú', 'ù', 'ü' },
{ 'v' },
{ 'w' },
{ 'x' },
{ 'y' },
{ 'z' }
}
-- Looks up the character `character´ in the alphabet and returns its 'priority'
local function get_pos_in_alphabet( character )
for i, alphabet_entry in ipairs(alphabet) do
for _, alphabet_char in ipairs(alphabet_entry) do
if character == alphabet_char then
return i
end
end
end
--[[
If it isn't in the alphabet, abort: it's better than silently outputting some
random garbage, and, thanks to the message, allows to add the character to
the table.
]]
assert( false , "'" .. character .. "' was not in alphabet" )
end
-- Returns the characters in the UTF-8-encoded string `s´ in an array-like table
local function get_utf8_string_characters( s )
--[[
I saw this variable being used in several code snippets around the Web, but
it isn't provided in my LuaTeX environment; I use this form of initialization
to be safe if it's defined in the future.
]]
utf8.charpattern = utf8.charpattern or "([%z\1-\127\194-\244][\128-\191]*)"
local characters = {}
for character in s:gmatch(utf8.charpattern) do
table.insert( characters , character )
end
return characters
end
local function compare_utf8_strings( _o1 , _o2 )
--[[
`o1_chars´ and `o2_chars´ are array-like tables containing all of the
characters of each string, which are all made lower-case using the
slnunicode facilities that come built-in with LuaTeX.
]]
local o1_chars = get_utf8_string_characters( utf8.lower(_o1) )
local o2_chars = get_utf8_string_characters( utf8.lower(_o2) )
local o1_len = utf8.len(o1)
local o2_len = utf8.len(o2)
for i = 1, math.min( o1_len , o2_len ) do
o1_pos = get_pos_in_alphabet( o1_chars[i] )
o2_pos = get_pos_in_alphabet( o2_chars[i] )
if o1_pos > o2_pos then
return false
elseif o1_pos < o2_pos then
return true
end
end
return o1_len < o2_len
end
I cannot integrate this solution in the question's framework because my test environment, the ZeroBrane Studio Lua IDE, doesn't come with slnunicode and I don't know how to add it.
That was it. If anyone has any doubt or would like further explanations, please, use the comments. I hope it's useful to someone else.

Why does '////'.split('/') produce []?

The code '////'.split('/') results in []. While I expected it to be ['', '', '', '', '']. If this is a feature of ruby, why is it designed like so?
You can't split string of delimiters by delimiter.
You should pass limit as second parameter to split function to achieve this behaviour
'////'.split('/',-1)
=>
["", "", "", "", ""]
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed
Investigation of behaviour of split method show that it is result of optimization, it simply crops empty array elements after last match as it is shewn below:
'////'.split('/')
=> []
'//a//'.split('/')
=> ["", "", "a"]
This design provides a convenience for parsing strings with trailing delimiters. For example:
'1␣2␣3␣␣'.split('␣') will now give ['1', '2', '3'] rather than ['1', '2', '3', '', ''].
This feature is just for simplification of workflow.
However, I don't like this feature because it breaks the purity of this method. To achieve the effect above, you just need an extra rstrip('␣') between '1␣2␣3␣␣' and split('␣').

Resources