geocode function removes special chracters - r

Hi I am using the geocode function to get lat and lng data for some cities, but for some special alphabet character cities such as: "Marcos Juárez Argentina" or "Perú Argentina" it creates mistakes in generating the inquiry:
https://maps.googleapis.com/maps/api/geocode/json?address=Per%FA%20Argentina&key=[**my api key**]
is there a way to fix that?

We can use the enc2utf8() function to read or set the declared encodings for a character vector:
> geocode(enc2utf8("Marcos Juárez Argentina"), output = 'more')
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=Marcos%20Ju%C3%A1rez%20Argentina&sensor=false
lon lat type loctype address north south east west locality
1 -62.1058 -32.69786 locality approximate marcos juárez, cordoba, argentina -32.67304 -32.71417 -62.07497 -62.1302 Marcos Juárez
administrative_area_level_2 administrative_area_level_1 country
1 Marcos Juárez Department Cordoba Argentina

Or you can use a geocoding service that does not transliterate inputs: example
In Json:
https://geocode.xyz/Marcos%20Ju%C3%A1rez%20Argentina?json=1
{ "standard" : { "addresst" : {}, "city" : "Marcos Juárez", "prov" : "AR", "countryname" : "Argentina", "postal" : {}, "confidence" : "0.9" }, "longt" : "-62.10158", "alt" : {}, "elevation" : {}, "latt" : "-32.69679"}

Related

Is there a convenient way to replicate R's concept of 'named vectors' in Raku, possibly using Mixins?

Recent questions on StackOverflow pertaining to Mixins in Raku have piqued my interest as to whether Mixins can be applied to replicate features present in other programming languages.
For example, in the R-programming language, elements of a vector can be given a name (i.e. an attribute), which is very convenient for data analysis. For an excellent example see: "How to Name the Values in Your Vectors in R" by Andrie de Vries and Joris Meys, who illustrate this feature using R's built-in islands dataset. Below is a more prosaic example (code run in the R-REPL):
> #R-code
> x <- 1:4
> names(x) <- LETTERS[1:4]
> str(x)
Named int [1:4] 1 2 3 4
- attr(*, "names")= chr [1:4] "A" "B" "C" "D"
> x
A B C D
1 2 3 4
> x[1]
A
1
> sum(x)
[1] 10
Below I try to replicate R's 'named-vectors' using the same islands dataset used by de Vries and Meys. While the script below runs and (generally, see #3 below) produces the desired/expected output, I'm left with three main questions, at bottom:
#Raku-script below;
put "Read in data.";
my $islands_A = <11506,5500,16988,2968,16,184,23,280,84,73,25,43,21,82,3745,840,13,30,30,89,40,33,49,14,42,227,16,36,29,15,306,44,58,43,9390,32,13,29,6795,16,15,183,14,26,19,13,12,82>.split(","); #Area
my $islands_N = <<"Africa" "Antarctica" "Asia" "Australia" "Axel Heiberg" "Baffin" "Banks" "Borneo" "Britain" "Celebes" "Celon" "Cuba" "Devon" "Ellesmere" "Europe" "Greenland" "Hainan" "Hispaniola" "Hokkaido" "Honshu" "Iceland" "Ireland" "Java" "Kyushu" "Luzon" "Madagascar" "Melville" "Mindanao" "Moluccas" "New Britain" "New Guinea" "New Zealand (N)" "New Zealand (S)" "Newfoundland" "North America" "Novaya Zemlya" "Prince of Wales" "Sakhalin" "South America" "Southampton" "Spitsbergen" "Sumatra" "Taiwan" "Tasmania" "Tierra del Fuego" "Timor" "Vancouver" "Victoria">>; #Name
"----".say;
put "Count elements (Area): ", $islands_A.elems; #OUTPUT 48
put "Count elements (Name): ", $islands_N.elems; #OUTPUT 48
"----".say;
put "Create 'named vector' array (and output):\n";
my #islands;
my $i=0;
for (1..$islands_A.elems) {
#islands[$i] := $islands_A[$i] but $islands_N[$i].Str;
$i++;
};
say "All islands (returns Area): ", #islands; #OUTPUT: returns 48 areas (above)
say "All islands (returns Name): ", #islands>>.Str; #OUTPUT: returns 48 names (above)
say "Islands--slice (returns Area): ", #islands[0..3]; #OUTPUT: (11506 5500 16988 2968)
say "Islands--slice (returns Name): ", #islands[0..3]>>.Str; #OUTPUT: (Africa Antarctica Asia Australia)
say "Islands--first (returns Area): ", #islands[0]; #OUTPUT: 11506
say "Islands--first (returns Name): ", #islands[0]>>.Str; #OUTPUT: (Africa)
put "Islands--first (returns Name): ", #islands[0]; #OUTPUT: Africa
put "Islands--first (returns Name): ", #islands[0]>>.Str; #OUTPUT: Africa
Is there a simpler way to write the Mixin loop ...$islands_A[$i] but $islands_N[$i].Str;? Can the loop be obviated entirely?
Can a named-vector or nvec wrapper be written around put that will return (name)\n(value) in the same manner that R does, even for single elements? Might Raku's Pair method be useful here?
Related to #2 above, calling put on the single-element #islands[0] returns the name Africa not the Area value 11506. [Note this doesn't happen with the call to say]. Is there any simple code that can be implemented to ensure that put always returns (numeric) value or always returns (Mixin) name for all-lengthed slices of an array?
Is there a simpler way?
Yes using the zip meta operator Z combined with infix but
my #islands = $islands_A[] Z[but] $islands_N[];
Why don't you modify the array to change the format?
put calls .Str on the value it gets, say calls .gist
If you want put to output some specific text, make sure that the .Str method outputs that text.
I don't think you actually want put to output that format though. I think you want say to output that format.
That is because say is for humans to understand, and you want it nicer for humans.
When you have a question of “Can Raku do X” the answer is invariable yes, it's just a matter of how much work would it be, and if you would still call it Raku at that point.
The question you really want to ask is how easy it is to do X.
I went and implemented something like that link you provided talks about.
Note that this was just a quick implementation that I created right before bed. So think of this as a first rough draft.
If I were actually going to do this for-real, I would probably throw this away and start over after spending days learning enough R to figure out what it is actually doing.
class NamedVec does Positional does Associative {
has #.names is List;
has #.nums is List handles <sum>;
has %!kv is Map;
class Partial {
has $.name;
has $.num;
}
submethod TWEAK {
%!kv := %!kv.new: #!names Z=> #!nums;
}
method from-pairlist ( +#pairs ) {
my #names;
my #nums;
for #pairs -> (:$key, :$value) {
push #names, $key;
push #nums, $value;
}
self.new: :#names, :#nums
}
method from-list ( +#list ){
my #names;
my #nums;
for #list -> (:$name, :$num) {
push #names, $name;
push #nums, $num;
}
self.new: :#names, :#nums
}
method gist () {
my #widths = #!names».chars Zmax #!nums».chars;
sub infix:<fmt> ( $str, $width is copy ){
$width -= $str.chars;
my $l = $width div 2;
my $r = $width - $l;
(' ' x $l) ~ $str ~ (' ' x $r)
}
(#!names Zfmt #widths) ~ "\n" ~ (#!nums Zfmt #widths)
}
method R-str () {
chomp qq :to/END/
Named num [1:#!nums.elems()] #!nums[]
- attr(*, "names")= chr [1:#!names.elems()] #!names.map(*.raku)
END
}
method of () {}
method AT-POS ( $i ){
Partial.new: name => #!names[$i], num => #!nums[$i]
}
method AT-KEY ( $name ){
Partial.new: :$name, num => %!kv{$name}
}
}
multi sub postcircumfix:<{ }> (NamedVec:D $v, Str:D $name){
$v.from-list: callsame
}
multi sub postcircumfix:<{ }> (NamedVec:D $v, List \l){
$v.from-list: callsame
}
my $islands_A = <11506,5500,16988,2968,16,184,23,280,84,73,25,43,21,82,3745,840,13,30,30,89,40,33,49,14,42,227,16,36,29,15,306,44,58,43,9390,32,13,29,6795,16,15,183,14,26,19,13,12,82>.split(","); #Area
my $islands_N = <<"Africa" "Antarctica" "Asia" "Australia" "Axel Heiberg" "Baffin" "Banks" "Borneo" "Britain" "Celebes" "Celon" "Cuba" "Devon" "Ellesmere" "Europe" "Greenland" "Hainan" "Hispaniola" "Hokkaido" "Honshu" "Iceland" "Ireland" "Java" "Kyushu" "Luzon" "Madagascar" "Melville" "Mindanao" "Moluccas" "New Britain" "New Guinea" "New Zealand (N)" "New Zealand (S)" "Newfoundland" "North America" "Novaya Zemlya" "Prince of Wales" "Sakhalin" "South America" "Southampton" "Spitsbergen" "Sumatra" "Taiwan" "Tasmania" "Tierra del Fuego" "Timor" "Vancouver" "Victoria">>;
# either will work
#my $islands = NamedVec.from-pairlist( $islands_N[] Z=> $islands_A[] );
my $islands = NamedVec.new( names => $islands_N, nums => $islands_A );
put $islands.R-str;
say $islands<Asia Africa Antarctica>;
say $islands.sum;
A named vector essentially combines a vector with a map from names to integer positions and allows you to address elements by name. Naming a vector alters the behavior of the vector, not that of its elements. So in Raku we need to define a role for an array:
role Named does Associative {
has $.names;
has %!index;
submethod TWEAK {
my $i = 0;
%!index = map { $_ => $i++ }, $!names.list;
}
method AT-KEY($key) {
with %!index{$key} { return-rw self.AT-POS($_) }
else { self.default }
}
method EXISTS-KEY($key) {
%!index{$key}:exists;
}
method gist() {
join "\n", $!names.join("\t"), map(*.gist, self).join("\t");
}
}
multi sub postcircumfix:<[ ]>(Named:D \list, \index, Bool() :$named!) {
my \slice = list[index];
$named ?? slice but Named(list.names[index]) !! slice;
}
multi sub postcircumfix:<{ }>(Named:D \list, \names, Bool() :$named!) {
my \slice = list{names};
$named ?? slice but Named(names) !! slice;
}
Mixing in this role gives you most of the functionality of an R named vector:
my $named = [1, 2, 3] but Named<first second last>;
say $named; # OUTPUT: «first␉second␉last␤1␉2␉3␤»
say $named[0, 1]:named; # OUTPUT: «first␉second␤1␉2␤»
say $named<last> = Inf; # OUTPUT: «Inf␤»
say $named<end>:exists; # OUTPUT: «False␤»
say $named<last end>:named; # OUTPUT: «last␉end␤Inf␉(Any)␤»
As this is just a proof of concept, the Named role doesn't handle the naming of non-existing elements well. It also doesn't support modifying a slice of names. It probably does support creating a pun that can be mixed into more than one list.
Note that this implementation relies on the undocumented fact that the subscript operators are multis. If you want to put the role and operators in a separate file, you probably want to apply the is export trait to the operators.
It might not be the most optimal way of doing it (or what you're specifically looking for) but as soon as I saw this particular problem's statement, the first thing that came to mind were Raku's allomorphs, which are types with two related values that are accessible separately depending on context.
my $areas = (11506,5500,16988,2968,16,184,23,280,84,73,25,43,21,82,3745,840,13,30,30,89,40,33,49,14,42,227,16,36,29,15,306,44,58,43,9390,32,13,29,6795,16,15,183,14,26,19,13,12,82);
my $names = <"Africa" "Antarctica" "Asia" "Australia" "Axel Heiberg" "Baffin" "Banks" "Borneo" "Britain" "Celebes" "Celon" "Cuba" "Devon" "Ellesmere" "Europe" "Greenland" "Hainan" "Hispaniola" "Hokkaido" "Honshu" "Iceland" "Ireland" "Java" "Kyushu" "Luzon" "Madagascar" "Melville" "Mindanao" "Moluccas" "New Britain" "New Guinea" "New Zealand (N)" "New Zealand (S)" "Newfoundland" "North America" "Novaya Zemlya" "Prince of Wales" "Sakhalin" "South America" "Southampton" "Spitsbergen" "Sumatra" "Taiwan" "Tasmania" "Tierra del Fuego" "Timor" "Vancouver" "Victoria">;
my #islands;
for (0..^$areas) -> \i {
#islands[i] := IntStr.new($areas[i], $names[i]);
}
say "Areas: ", #islands>>.Int;
say "Names: ", #islands>>.Str;
say "Areas slice: ", (#islands>>.Int)[0..3];
say "Names slice: ", (#islands>>.Str)[0..3];
say "Areas first: ", (#islands>>.Int)[0];
say "Names first: ", (#islands>>.Str)[0];
I think I would just do something like this:
class MyRow {
has Str $.island is rw;
has Numeric $.area is rw;
method Str {
$!island;
}
method Numeric {
+$!area;
}
# does Cool coercion of strings that look numeric
submethod BUILD ( Numeric(Cool) :$!area, :$!island ) {
};
}
class MyTable {
has #.data;
has MyRow #.rows is rw;
has %!lookup;
submethod TWEAK {
#!rows = gather
for #!data -> ( $island, $area ) {
my $row = MyRow.new( :$island, :$area );
%!lookup{ $island } = $row;
take $row;
}
}
method find_island( $island ) {
return %!lookup{ $island };
}
}
To set up a table:
my #raw = #island_names Z #island_areas;
my $table = MyTable.new( data => #raw );
Accessing the rows of the table by name:
my $row = $table.find_island('Africa');
say $row; # MyRow.new(island => "Africa", area => 11506)
Using the row element like a string gets you the name,
using it like a number gets you the area:
say ~$row; # Africa
say +$row; # 11506
One of the features here is that you can add more fields to your
rows, you're not constrained to just a value and a name.
The "find_island" method uses an internal %lookup hash to index
the rows by island name, but unlike a simple hash solution
there's no uniqueness constraint: if you have a duplicate island
name, "find_island" will locate the latest row in the set, but
the other row would still be there.
Caveat: I haven't thought much about how well this supports
dynamically adding more rows to the table.

get all possible keys / key paths in a json string in r

How can I get all the different possible json paths in a json string? Often I get huge
For example, I would like to get something back like:
result = data.frame(paths = c('name',
'name.first'
,'name.last'
,'address'
,'address.city'
,'address.state'
,'age'
,'income'
,'block'))
result
given something like this...
myjson='{
"name": {
"first": "jack",
"last": "smith"
},
"address": {"city": "bigtown", "state": "texas"},
"age": "21",
"income": "123",
"block" :["abc","xyz"]
}'
I've tried experimenting with jsonlite::fromJson but that doesn't seem to get me to what I'm after exactly.
This will get you the full paths:
data.frame(result = names(as.data.frame(jsonlite::fromJSON(myjson))))
result
1 name.first
2 name.last
3 address.city
4 address.state
5 age
6 income
7 block
If you need all partial paths along with all full paths:
data.frame(
result = sort(unique(
c(names(fromJSON(myjson)),
names(as.data.frame(jsonlite::fromJSON(myjson))))))
)
result
1 address
2 address.city
3 address.state
4 age
5 block
6 income
7 name
8 name.first
9 name.last

how to I add where clause or constraint to my xquery

I have been given a station in london - warren street station, euston, and i have to return the stations which have the same bike availability as warren street station and at least as many empty docs. I have written a small query to return warren street station and its availability but how to I return a list of all other stations that have the same availability/ as many empty docks as my warren street station?
<results>{ for $b in doc("http://tinyurl.com/TFLStationsXMLFile")
/stations/station
where $b/name = "Warren Street Station, Euston"
order by $b
return
<result>
{ $b/name }
{ $b/nb_bikes }
{ $b/nb_empty_docks }
</result>}
</results>
let $warren-station := doc("http://tinyurl.com/TFLStationsXMLFile")/stations/station[name eq "Warren Street Station, Euston"]
return
<results>{ for $b in doc("http://tinyurl.com/TFLStationsXMLFile")/stations/station
where $b/nb_bikes eq $warren-station/nb_bikes and $b/nb_empty_docks ge $warren-station/nb_empty_docks
order by $b
return
<result>
{ $b/name }
{ $b/nb_bikes }
{ $b/nb_empty_docks }
</result>}
</results>
Something like that. HTH!

How to get the original word from trans() Symfony 2

The user should give his country name, the problem is that all countries name are translated to different languages, and I must re-trans to englisch to compare the name with the name in my database.
I did like that but it doesn't work :
$translated_country = $this->get('translator')->trans($q_country, array(), null, 'en_US');
$countries = array("A, B, C");
if( in_array($translated_country, $countries))
{}
For example I have messages.de.yml
Germany : Deutschland
I want that when the user enters Deutschland , In my code I get Germany
You need to have a match in the EN locale for each country translated into the other languages you support.
# messages.en.yml
deutschland: germany
Германия: germany
russland: russia
Россия: russia
# messages.de.yml
germany: deutschland
russia: russland
# messages.ru.yml
russia: Россия
germany: Германия
$toTranslate = 'deutschland';
$translator = $this->get('translator');
$translation = $translator->trans($toTranslate, array(), null, 'en_US');
/** $translation should be 'germany' */

Getting different latitude and longitude for same address line

I am using Google API for getting latitude and longitude of address,
geocoder.geocode({ 'address': address
, bounds: map.getBounds() },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Lat = results[0].geometry.location.lat();
Long = results[0].geometry.location.lng();
});
but for same address some times I get value : Latitude=33.189967 and longitude=-96.7333 which is more correct,
and other times I get array of Latitude and Longitude from which I pick up the first and the value I get is Latitude=41.920 and Longitude=83.41.
The address that I am currently using is '1550 South Custer Rd'.
Please help me some one.
I get 4 results for that string:
Found 4 results
[ 0 ]: 1550 South Custer Road, Monroe Charter Township, MI 48161, USA (41.9200564, -83.41902479999999)
[ 1 ]: 1550 South Custer Road, McKinney, TX 75070, USA (33.189967, -96.73350699999997)
[ 2 ]: 1550 South Custer Road, Spokane, WA 99223, USA (47.6389694, -117.34156009999998)
[ 3 ]: 1550 South Custer Road, Custer, MI 49405, USA (43.9296513, -86.21892639999999)
I don't know how you expect the Geocoder to know which of the answers is "more correct" as they all contain that exact string. Perhaps you need to include more information (like the town or the state), or process the results to determine the one that is in your area of interest.

Resources