I've got a complex directions URL and embed URL that I would like to get polylines for. Once I can get them into polylines or something similar I can convert to final format: GeoJSON.
Direction Link
-or-
Embed Link
I have looked at the API's and I can't find anything that accepts or would decode the PB (what is this? it's not a protocol buffer). So far this is as far as I've got:
//php
$pb_array = explode('!', $pb);
foreach($pb_array as $key => $value){
echo "$key - $value<br/>";
}
===
1 - 1m73
2 - 1m12
3 - 1m3
4 - 1d1472548.9575794793
5 - 2d-72.8191002664707
6 - 3d43.87505426780168
7 - 2m3
8 - 1f0
9 - 2f0
10 - 3f0
11 - 3m2
12 - 1i1024
13 - 2i768
14 - 4f13.1
15 - 4m58
16 - 3e0
17 - 4m5
18 - 1s0x0%3A0xa58b3d6041ba69f8
19 - 2sGuilford+Welcome+Center
20 - 3m2
21 - 1d42.8120069
22 - 2d-72.56614689999999
23 - 4m3
24 - 3m2
25 - 1d43.3893165
26 - 2d-72.40772249999999
27 - 4m5
28 - 1s0x4cb52e78df455c83%3A0xb6946ec850907db8
29 - 2s130+Lower+Michigan+Road%2C+Pittsfield%2C+VT+05762
30 - 3m2
31 - 1d43.76898
32 - 2d-72.815214
33 - 4m4
34 - 1s0x0%3A0xea2de48bba82cc86
35 - 3m2
36 - 1d44.042544
37 - 2d-72.6046997
38 - 4m5
39 - 1s0x0%3A0x6bb602ed58bf4413
40 - 2sJay+Peak+Resort
41 - 3m2
42 - 1d44.9379515
43 - 2d-72.5045433
44 - 4m5
45 - 1s0x4cb392aaa4333a07%3A0x160aef1559868340
46 - 2sDolly+Copp+Campground+Rd%2C+Gorham%2C+NH+03581
47 - 3m2
48 - 1d44.335842199999995
49 - 2d-71.21837339999999
50 - 4m5
51 - 1s0x4cb392684201a94d%3A0xfa4a6f490a05429d
52 - 2sMt+Washington+Auto+Road%2C+1+Mount+Washington+Auto+Road%2C+Gorham%2C+NH+03581
53 - 3m2
54 - 1d44.288384099999995
55 - 2d-71.22459599999999
56 - 4m5
57 - 1s0x4cb38e798f42c3d9%3A0xc3b88e4dac01db12
58 - 2sMt+Washington
59 - 3m2
60 - 1d44.270585399999995
61 - 2d-71.3032723
62 - 4m5
63 - 1s0x89e2a7fa444124d5%3A0xe3ed24b6f864eba0
64 - 2sWells%2C+ME
65 - 3m2
66 - 1d43.322232899999996
67 - 2d-70.5805209
68 - 4m5
69 - 1s0x89e2ba813e828c71%3A0x8cdf74380f6a933d
70 - 2sLibby's+Oceanside+Camp%2C+York+Street%2C+York%2C+ME
71 - 3m2
72 - 1d43.147162
73 - 2d-70.626173
74 - 5e1
75 - 3m2
76 - 1sen
77 - 2sus
78 - 4v1472497940601
The closest hints I could find are from this thread. I will keep looking but I'm stuck.
I'm trying to create an API based solution that has an input of one of these URL's and returns a GeoJSON.
would decode the PB (what is this? it's not a protocol buffer)
For the record, because this overflow question keeps popping up on google results: it is a protocol buffer. PB litteraly stands for protocol buffer.
It's just a different ASCII encoding (a compact URL encoding reminiscent of the binary encoding, not the usual JSON-like text encoding. When you squint at it it's not that much different than torrent's structure encoding), and Google doesn't provide us the .proto file.
For each field:
first character is the id (identifies the field according to the corresponding .proto file)
second character is the type of the field
m is for message
s is for string
i, j, u, v are for various type of ints
f, d are for floating points
e is for enum
the rest is the payload
So to unpack the fields you're seeing (even if we don't have the .proto file):
1m73 message of type 1, containing 73 elements (the whole message set)
1m12 submessage of type 1, contains 12 elements (probably information about the view box in the map box)
1m3 sub-sub-message type 1, contains 3 elements (probably map coordinates)
1d1472548.9575794793 first double field (probably zoom level)
2d-72.8191002664707 second double field (probably longitude)
3d43.87505426780168 third double field (probably latitude)
2m3 second sub-sub-sub message (no idea given that it's not filled. Maybe a starting point if you code a route instead of a single point ?)
1f0, 2f0, 3f0 the three members, currently just zero
3m2 third block (looks like a screen resolution)
1i1024, 2i768 : 1024x768 ? (and probably the omited field 3 would have been the color depth if present ??)
4f13.1 no idea, but it's a float
4m58 next message with 58 elements (to me it looks like a bunch of POI that we need to display in the box)
3e0 an enum, set to zero (this one would be completely impossible to interpret without a proto or without experimenting, as you need the list of enums)
4m5 five more elements probably a map poi
- 1s0x0%3A0xa58b3d6041ba69f8 string '0x0:0xa58b3d6041ba69f8', note the use of Url_encoded character. In turn it looks like a pair of hex numbers, maybe a GUID ?
- 2sGuilford+Welcome+Center string, the name with plus instead of blank (like most URLs)
- 3m2 two elements to come
- 1d42.8120069 and 2d-72.56614689999999 doubles probably map coordinates
4m3 again a message of type 4 in this level, so probably another poi
- 3m2, 1d43.3893165, 2d-72.40772249999999 but this one only specifies coordinates, and nothing else
4m5 another poi
- 1s0x4cb52e78df455c83%3A0xb6946ec850907db8 different pair of hex, GUID
...you got the idea...
5e1 another bunch of information probably general settings
3m2 this setting is a message (and looks like a locale)
1sen, 2sus locale is en_US
4v1472497940601 some other large number...
Note: the original proto that Google doesn't show us, is probably a single multi level structure. Thus, the sub-sub-message ID don't have always the same meaning: they aren't global ID, but ID within the parent message.
inside a sub message ID 1 (view box ?), the sub-sub message 3 seems to be resolution.
inside a sub message ID 4 (POIs ?), the sub-ID 3 isn't even a message but some enum
inside a sub message ID 5 (parameters), the sub-sub message 3 is a locale
Well, here's my sloppy but working solution. My needs required GeoJSON, but others can use the google maps service to get the desired output once you have the lat/lng array.
$embed = '<iframe src="https://www.google.com/maps/embed?pb=!1m73!1m12!1m3!1d1472548.9575794793!2d-72.8191002664707!3d43.87505426780168!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m58!3e0!4m5!1s0x0%3A0xa58b3d6041ba69f8!2sGuilford+Welcome+Center!3m2!1d42.8120069!2d-72.56614689999999!4m3!3m2!1d43.3893165!2d-72.40772249999999!4m5!1s0x4cb52e78df455c83%3A0xb6946ec850907db8!2s130+Lower+Michigan+Road%2C+Pittsfield%2C+VT+05762!3m2!1d43.76898!2d-72.815214!4m4!1s0x0%3A0xea2de48bba82cc86!3m2!1d44.042544!2d-72.6046997!4m5!1s0x0%3A0x6bb602ed58bf4413!2sJay+Peak+Resort!3m2!1d44.9379515!2d-72.5045433!4m5!1s0x4cb392aaa4333a07%3A0x160aef1559868340!2sDolly+Copp+Campground+Rd%2C+Gorham%2C+NH+03581!3m2!1d44.335842199999995!2d-71.21837339999999!4m5!1s0x4cb392684201a94d%3A0xfa4a6f490a05429d!2sMt+Washington+Auto+Road%2C+1+Mount+Washington+Auto+Road%2C+Gorham%2C+NH+03581!3m2!1d44.288384099999995!2d-71.22459599999999!4m5!1s0x4cb38e798f42c3d9%3A0xc3b88e4dac01db12!2sMt+Washington!3m2!1d44.270585399999995!2d-71.3032723!4m5!1s0x89e2a7fa444124d5%3A0xe3ed24b6f864eba0!2sWells%2C+ME!3m2!1d43.322232899999996!2d-70.5805209!4m5!1s0x89e2ba813e828c71%3A0x8cdf74380f6a933d!2sLibby's+Oceanside+Camp%2C+York+Street%2C+York%2C+ME!3m2!1d43.147162!2d-70.626173!5e1!3m2!1sen!2sus!4v1472497940601" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>';
$array = array();
preg_match( '/src="([^"]*)"/i', $embed, $array ) ;
list($pre, $pb) = split("pb=", $array[1]);
if($pb == "" || strpos($pb, "!") === false)
die(json_encode(array("success"=>false)));
//echo "PB Extracted:<br>";
//echo $pb;
///echo "<br><br>Decode:<br/>";
$pb_array = explode('!', $pb);
$coords = array();
$address;$addressHex;
$results = array();
foreach($pb_array as $key => $value){
//uncomment to debug output
//echo "$key - $value<br/>";
if($value == "3m2" || $value == "2m2"){
//3m2 seems to be the divider of these 'places'
if(count($coords) != 3) //don't add the center of map data (3 coordinates [height, lng, lat])
array_push($results, array("coords"=>$coords,"address"=>$address,"addressHex"=>$addressHex));
$coords = array(); //reset array
}else{
$type = substr($value, 1, 1);
$stype = substr($value, 0, 2);
$value = substr($value, 2);
//echo "$type - $value<br/>";
if($type == "d"){
//Found Lat,Lng
array_push($coords, $value);
}else if($stype == "2s"){
//Address
$address = $value;
}else if($stype == "1s"){
//Address Encoded in some way
$addressHex = $value;
}
}
}
//echo "<br><br>Google Result<br/>";
//echo json_encode($results);
//echo "<br><br>Mapbox API:<br/>";
$waypoints = array();
for($i=0;$i<count($results);$i++){
if(count($results[$i]["coords"])){
$lat = $results[$i]["coords"][0];
$lng = $results[$i]["coords"][1];
array_push($waypoints, "$lng%2C$lat");
}
}
$waypoints = implode("%3B", $waypoints); //convert to string
$mapbox_api_key = "pk.eyJ1I.....";
$url = "https://api.mapbox.com/directions/v5/mapbox/driving/$waypoints.json?steps=false&alternatives=false&overview=full&geometries=geojson&access_token=$mapbox_api_key";
//echo "<br><br>Mapbox Response:<br/>";
$response = file_get_contents($url);
$json = json_decode($response,true);
//echo "<br><br>Mapbox Geometry:<br/>";
$coordinates = $json["routes"][0]["geometry"]["coordinates"];
$geojson = (array("type"=>"FeatureCollection","features"=>array(array("type"=>"Feature","geometry"=>array("type"=>"LineString","coordinates"=>$coordinates),"properties"=>array()))));
echo json_encode(array("success"=>true, "geojson"=>$geojson));
Related
I am calculating the number that falls into a specific percentile. However, the problem with my equation is that if multiple elements in the array having the same value, this code will assign a different percentile number to each of those elements.
$percentile_50 = $array[round((50/100) * $count_array -.5)];
For example, first column is the percentile, and second is the score. You can see that same second gets different percentile, but in fact it should be the same.
How can I avoid this?
5-1
10-1
15-1
20-1
25-2
30-2
35-3
40-4
45-4
50-5
55-6
60-7
65-9
70-11
75-14
80-17
85-23
90-32
95-53
To calculate the kth percentile, you should :
Order all the values in the data set from smallest to largest.
Multiply k percent by the total number of values, n.
This number is called the index.
If the index obtained in Step 2 is not a whole number, round it up to the nearest whole number and go to Step 4. If the index obtained in Step 2 is a whole number, go to Step 5.
Count the values in your data set from left to right (from the smallest to the largest value) until you reach the number indicated by Step 3.
The corresponding value in your data set is the kth percentile
Count the values in your data set from left to right until you reach the number indicated by Step 2.
The kth percentile is the average of that corresponding value in your data set and the value that directly follows it.
( from here)
Translated to PHP:
$sData = sort($data);
$percentile = 50/100;
$index = ceil($percentile * count($sData));
$value = $sData[$index-1];
Or shorter:
$sData = sort($data);
$value = $sData[ceil((50/100) * count($sData)) - 1]
However, in a small dataset, sometimes the percentiles end up the same. For example, the following code produces the following output.
Code
$data = array(74, 15, 25, 62, 45, 9, 16, 63, 60, 76, 7, 20, 67, 30, 12);
sort($data);
for($i=5;$i<100;$i+=5){
echo $i . " - " . $data[ceil(($i/100) * count($data)) - 1];
echo PHP_EOL;
}
Output
5 - 7
10 - 9
15 - 12
20 - 12 //same as aboce
25 - 15
30 - 16
35 - 20
40 - 20 //same as above
45 - 25
50 - 30
55 - 45
60 - 45 //same as above
65 - 60
70 - 62
75 - 63
80 - 63 //same as above
85 - 67
90 - 74
95 - 76
I'm running simple PHP code
$myVariable = 1;
$myVariable2 = str_replace(array(1, 2, 3), array('do 25 lat', 'od 26 do 35 lat', 'pow. 35 r.z.'), $myVariable);
echo $myVariable2;
And result is:
do od 26 do pow. 35 r.z.5 lat5 lat
I checked on different PHP versions. Any ideas?
You're falling victim to the gotcha specified in the documentation - look under "notes" on the str_replace documentation
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
Essentially what's happening is the sequential replacements, as you passed an array as the second parameter:
1 is replaced with do 25 lat
In that string, 2 is replaced with od 26 do 35 lat, giving you do od 26 do 35 lat5 lat
In that string, 3 is replaced with pow. 35 r.z. giving you the final result you're seeing.
This is because str_replace array pairs are applied one after the other.
Try strtr:
$myVariable = 1;
$replacePairs = array(
1 => "do 25 lat",
2 => "od 26 do 35 lat",
3 => "pow. 35 r.z."
);
$myVariable2 = strtr($myVariable,$replacePairs);
echo $myVariable2;
It's not a bug, this is the normal behavior of str_replace. What happens is the function iterates through your search array and each time it finds an occurrence, it replaces it with relevant replace.
Thus:
(search and match 1) 1 -> "do 25 lat"
(search and match 2) "do 25 lat" -> "do od 26 do 35 lat5 lat"
(search and match 3) "do od 26 do 35 lat5 lat" -> "do od 26 do pow. 35 r.z.5 lat5 lat"
My testcase as follows:
echo crypt('string', '_....salt');//error
echo crypt('string', '_A...salt');//fast
echo crypt('string', '_AAAAsalt');//slow
Explanation as stated at http://www.php.net/manual/en/function.crypt.php:
CRYPT_EXT_DES - Extended DES-based hash. The "salt" is a 9-character
string consisting of an underscore followed by 4 bytes of iteration
count and 4 bytes of salt. These are encoded as printable characters,
6 bits per character, least significant character first. The values 0
to 63 are encoded as "./0-9A-Za-z". Using invalid characters in the
salt will cause crypt() to fail.
A dot is a printable character so why does it return an error? And which "order" applies on the used characters resulting "AAAA" more iterations than "A..."?
It says all in the quoted paragraph:
- least significant character first
- The values 0 to 63 are encoded as "./0-9A-Za-z"
So in your example "_....salt" would mean 0 rounds which obviously can't work.
and "_A...salt" is less than "_AAAAsalt" considering the least significant character comes first.
"_...Asalt" would also be more than "_A...salt"
This question is a bit old, however i found this when trying to wrap my head around how to create a hashing class for internal use here, and i came up with this little function which will base64 encode an integer with the appropriate characters/significance to be used as the 4 character 'iteration count'. Possible values are from 1 to 16,777,215
private function base64_int_encode($num){
$alphabet_raw = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$alphabet = str_split($alphabet_raw);
$arr = array();
$base = sizeof($alphabet);
while($num){
$rem = $num % $base;
$num = (int)($num / $base);
$arr[]=$alphabet[$rem];
}
$arr = array_reverse($arr);
$string = implode($arr);
return str_pad($string, 4, '.', STR_PAD_LEFT);
}
Hope it helps someone!
The code of Klathmon is nice but has some mistakes:
First - alphabet
It is:
./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Should be:
./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
Second - order of characters/digits
It generates for example: ...z
But it should generate: z...
The improved code:
function base64_int_encode($num) {
$alphabet_raw='./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$alphabet=str_split($alphabet_raw);
$arr=array();
$base=sizeof($alphabet);
while($num) {
$rem=$num % $base;
$num=(int)($num / $base);
$arr[]=$alphabet[$rem];
}
$string=implode($arr);
return str_pad($string, 4, '.', STR_PAD_RIGHT);
}
A number system used in Extended DES:
.... - 0 (Extended DES error)
/... - 1
0... - 2
1... - 3
2... - 4
3... - 5
4... - 6
5... - 7
6... - 8
7... - 9
8... - 10
z... - 63
./.. - 64
//.. - 65
0/.. - 66
1/.. - 67
Y/.. - 100
61.. - 200
g2.. - 300
E4.. - 400
o5.. - 500
M7.. - 600
w8.. - 700
UA.. - 800
2C.. - 900
cD.. - 1000
zz.. - 4095
../. - 4096
/./. - 4097
0./. - 4098
1./. - 4099
xzzz - 16 777 213
yzzz - 16 777 214
zzzz - 16 777 215
And in connection with salt:
_/...salt - 1
_0...salt - 2
_1...salt - 3
_2...salt - 4
_3...salt - 5
_4...salt - 6
_5...salt - 7
_6...salt - 8
_7...salt - 9
_8...salt - 10
_z...salt - 63
_./..salt - 64
_//..salt - 65
_0/..salt - 66
_1/..salt - 67
_Y/..salt - 100
_61..salt - 200
_g2..salt - 300
_E4..salt - 400
_o5..salt - 500
_M7..salt - 600
_w8..salt - 700
_UA..salt - 800
_2C..salt - 900
_cD..salt - 1000
_zz..salt - 4095
_../.salt - 4096
_/./.salt - 4097
_0./.salt - 4098
_1./.salt - 4099
_xzzzsalt - 16 777 213
_yzzzsalt - 16 777 214
_zzzzsalt - 16 777 215
I merged two arrays together that both contained a string(url) and int(score). the following is a sample of the outome. Whenever a string is duplicated, i need to remove that string and its corresponding int. For example, on the 4th line (www.thebeatles.com/ - 30) should be removed. The 5th and 6th lines should also be removed as they appear already with a different score.
http://www.thebeatles.com/ - 55
http://en.wikipedia.org/wiki/The_Beatles - 49
http://www.beatlesstory.com/ - 45
http://www.thebeatles.com/ - 30
http://en.wikipedia.org/wiki/The_Beatles - 28
http://www.beatlesstory.com/ - 26
http://www.beatlesagain.com/ - 24
http://www.thebeatlesrockband.com/ - 23
http://www.last.fm/music/The+Beatles - 22
http://itunes.apple.com/us/artist/the-beatles/id136975 - 20
http://www.youtube.com/watch?v=U6tV11acSRk - 18
http://blekko.com/ws/http://www.thebeatles.com/+/seo - 17
http://www.adriandenning.co.uk/beatles.html - 16
http://www.npr.org/artists/15229570/the-beatles - 15
http://mp3.com/artist/The%2BBeatles - 14
http://www.beatles.com/ - 13
http://www.youtube.com/watch?v=TU7JjJJZi1Q - 12
http://www.guardian.co.uk/music/thebeatles - 11
http://www.cirquedusoleil.com/en/shows/love/default.aspx - 9
http://www.recordingthebeatles.com/ - 7
http://www.beatlesbible.com/ - 5
I'm new to PHP and my best efforts to get array_unique() to work have failed. Really appreciate some help guys!
Here is a function that merges two arrays and discards any duplications, hopes it helps:
function merge_links($arr_l, $arr_r) {
$new_links = array();
$links = array_merge($arr_l, $arr_r); //the big list with every links
foreach($links as $link) {
$found = false; //did we found a duplicate?
//check if we already have it
foreach($new_links as $new_link) {
if($new_link['url'] == $link['url']) {
//duplicate
$found = true;
break;
}
}
//not found, so insert it
if(!$found) {
$new_links[] = $link;
}
}
return $new_links;
}
$arr1[0]['url'] = 'http://test.nl';
$arr1[0]['score'] = 30;
$arr1[1]['url'] = 'http://www.google.nl';
$arr1[1]['score'] = 30;
$arr2[0]['url'] = 'http://www.tres.nl';
$arr2[0]['score'] = 30;
$arr2[1]['url'] = 'http://test.nl';
$arr2[1]['score'] = 30;
print_r(merge_links($arr1, $arr2));
You can make link as key of the array which contains link and score. Corresponding to key there will always be one value. But the one which is added in the last will be there in your final array.
Well, even technically, those strings are not unique. i.e. They are completely different.
http://www.thebeatles.com/ - 55
http://www.thebeatles.com/ - 30
So, array_unique() will not give you the required output. One way of solving this issue is by defining a separate array and storing the URI and the number separately. A manageable form would be this.
array(
array("http://www.thebeatles.com", 55),
array("http://www.thebeatles.com", 30)
);
I have a special strings to check with a PHP script. This is the format :
XX - XX:XX:XX - Somethings
such as :
each XX must be ?? or a pair of digit;
first XX can take every kind of digit;
second XX must be from 00 and 10;
third and fourth XX must be from 00 to 59;
somethings can be everything, it doesnt matter;
These are some example :
00 - ??:??:?? - Blablabla // OK
99 - ??:99:?? - Blablabla // NO (99 is too high)
99 - 12:50:40 - Blablabla // NO (12 is too high)
?? - AA:50:40 - Blablabla // NO (AA is not a pair of digit)
99 - 2:50:40 - Blablabla // NO (2 is not a pair of digit; I need 02)
99 -08:49:40 - Blablabla // NO (-08 need a space)
How can I do it? I think the best way is Regex, but I really don't know how to do it :) Any help is appreciated
You can do it like this
$subj = '00 - 04:38:27 - Hi';
preg_match('/^(\?\?|\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)/', $subj, $matches);
Then you can access the fields in matches:
$matches[1] = 00
$matches[2] = 04
$matches[3] = 38
$matches[4] = 27
$matches[5] = Hi
This seems to do the job (tested at http://www.spaweditor.com/scripts/regex/index.php)
/([0-9\?]{2} - (0[0-9]|10|\?\?):([0-5][0-9]|\?\?):([0-5][0-9]|\?\?) - .*)/