convert php to javascript #1 - php

I'm trying to convert this awesome pathfinding php function from http://granularreverb.com/a_star.php to javascript.
PHP function
function path_float(&$heap, &$values, $i, $index) {
for (; $i; $i = $j) {
$j = ($i + $i%2)/2 - 1;
if ($values[$heap[$j]] < $values[$index])
break;
$heap[$i] = $heap[$j];
}
$heap[$i] = $index;
}
JAVASCRIPT function
var $path_f;
var $path_h;
var $path_g;
var $path_open_heap;
function path_float($path_open_heap, $path_f, i, index) { // return heap & values
var j;
for (; i; i = j) {
j = (parseInt(i) + parseInt(i)%2)/2 - 1;
if($path_f[$path_open_heap[j]] < $path_f[index] ){
break;
}
$path_open_heap[i] = $path_open_heap[j];
}
$path_open_heap[i] = index;
}
I'm not sure if javascript understands for() without all elements? If i try to execute javascript function my browser freezes.
P.s. i'm not interested in pre-written js pathdindings, because i need identical php and js function.
Thanks in advance

You can use for without all the elements in javascript similar to PHP. So that is not the problem.
I think the problem is the float that is returned to J. it could be that it never realy is 0 but might be some large float like 0.00000000001 or something and thus never evaluates to false. Unfortunately I cannot test it as You did not provide any input values.
Try the following:
var $path_f;
var $path_h;
var $path_g;
var $path_open_heap;
function path_float($path_open_heap, $path_f, i, index) { // return heap & values
var j;
for (; i; i = parseInt(j)) {
j = (parseInt(i) + parseInt(i)%2)/2 - 1;
if($path_f[$path_open_heap[j]] < $path_f[index] ){
break;
}
$path_open_heap[i] = $path_open_heap[j];
}
$path_open_heap[i] = index;
}

Related

Fatal error: Uncaught Error: Class 'Func' not found php

My Questions is Find a 7 letter string of characters that contains only letters from
acegikoprs
such that the gen_hash(the_string) is
675217408078
if hash is defined by the following pseudo-code:
Int64 gen_hash (String s) {
Int64 h = 7
String letters = "acegikoprs"
for(Int32 i = 0; i < s.length; i++) {
h = (h * 37 + letters.indexOf(s[i]))
}
return h
}
For example, if we were trying to find the 7 letter string where gen_hash(the_string) was 677850704066, the answer would be "kppracg".
Solution
test1.php
I did that question solve in php, I am unable to run this code I am in php i don't have that much knowledge regarding php class and their function, Can any one solve this code and describe me. thanks in advance i will be very great full if anyone help me.
<?php
$set = "acdegilmnoprstuw";
$CONST_HASH = 7.0;
$CONST_MULT = 37.0;
$hash = new Func(function($string = null) use (&$CONST_HASH, &$CONST_MULT, &$set) {
$_hash = $CONST_HASH;
for ($i = 0.0; $i < get($string, "length"); $i++) {
$_hash = _plus(to_number($_hash) * to_number($CONST_MULT), call_method($set, "indexOf", get($string, $i)));
}
return $_hash;
});
$decode = new Func(function($_hash = null) use (&$CONST_MULT, &$Math, &$set) {
$decoded = ""; $positionsInSet = new Arr();
for ($i = 0.0; $_hash > $CONST_MULT; $i++) {
set($positionsInSet, $i, call_method($Math, "floor", (float)(to_number($_hash) % to_number($CONST_MULT))));
$_hash /= 37.0;
}
for ($i = to_number(get($positionsInSet, "length")) - 1.0; $i >= 0.0; $i--) {
$decoded = _plus($decoded, get($set, get($positionsInSet, $i)));
}
return $decoded;
});
I realize that this question was asked well over a year ago and I'm only just stumbling on it right now but seeing as there hasn't been an answer I figured I'd answer it.
You used a third party JavaScript to PHP converter utility and expected the demo to work out of the box. You should have read up on it's usage as it clearly states in the ReadMe.md that, ...this tool is using esprima JavaScript parser with rocambole to walk the AST and escope to figure out the variable scope, hoist function declarations and so on...
The developer goes on to say, After AST manipulation tools/codegen.js generates the PHP code by walking the tree. Now here's where it gets good. Pay attention now..
Various constructs get wrapped in helper functions, for instance,
property access, method calls and + operator. The runtime helpers
can be found in php/helper and there are a bunch of classes in
php/classes for Array, RegExp and such. All this PHP gets packaged
into your output file, or you can save it to a standalone runtime and
reference that from your output file like so:
js2php --runtime-only > runtime.php
js2php --runtime runtime.php example.js > example.php
You can also specify the output file using -o or --out and you can
compile multiple input files into one output file like so:
js2php -o example.php file1.js file2.js
So as you can see my friend, to get your code to work you merely need to include the runtime helpers functions so your converted script can be interpreted. I'm not sure as to which files it'll take to get your script to parse correctly, however now that I've pointed you in the right direction I'm confident you'll be able work it out yourself.
Happy coding..
=)
Instead of assigning the inline function with new operator to variable, create a separate functions encode and decode where you can do the hashing and matching the hash code.
Let me give you the snippet of how to do it. I am assuming that your using plain PHP.
/* Call to function encode which returns you the encoded value and store in $encode variable */
$encode = encode($par1, $par2);
/* Call to function decode which returns you the decoded value and store in $decode variable */
$decode = decode($par1, $par2);
/* Function to encode your code */
function encode($par1, $par2){
return $encode_value
}
/* Function to decode your code */
function decode($par1, $par2){
return $decode_value
}
I have written this in Javascript to generate both Hash String and Number
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var gen = gen_hash('kppracg');
document.write("kppracg hash value is ", gen);
document.write('<br><br>');
var gen = gen_hash('iorocks');
document.write("iorocks hash value is ", gen);
var hash = 675217408078;
var gen_rev = gen_hash_rev(hash);
document.write('<br><br>');
document.write("675217408078 hash value is ", gen_rev);
function gen_hash(s) {
var h = 7;
var acegikoprs = "acegikoprs";
for(var i = 0; i < s.length; i++) {
h = (h * 37 + acegikoprs.indexOf(s[i]));
}
return h;
}
function gen_hash_rev(hash) {
var arr_values = ['a','c','e','g','i','k','o','p','r','s'];
var min = 0;
var max = 99999999;
while (min <= max) {
var final_result = "";
var tempInt = parseInt(((max - min) / 2) + min);
var arr_tempInt = num_array(tempInt);
for(var i = 0; i < arr_tempInt.length; i++) {
final_result = final_result + arr_values[arr_tempInt[i]];
}
var result = gen_hash(final_result);
if(result < hash) {
min = tempInt + 1;
}
else if( result > hash) {
max = tempInt - 1;
}
else {
return final_result;
}
}
}
function num_array(num){
var output = [],
sNumber = num.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
return output;
}
</script>
</body>
</html>

compare image similarity using php

I am searching for a way to identify similar png images with same size. The images are not the exact duplicates. For example If one image has a clip art of a bird, and another image has the same clip art but it is rotated, I want to identify both of them are similar. I want to write an algorithm do this using php.I have tried out this using javasript. What i am doing is convert the image into base64 and compare both the values using hamming distance. But as far I know this will not identify advanced techniques such as scaling, rotating. So what I want it to write an algorithm to do those things in php.Any ideas? This is what I have tried out using javascript and html5 canvas.
function newFunction()
{
var imageHeight = image.naturalHeight;
var imageWidth = image.naturalWidth;
var image2Height = image2.naturalHeight;
var image2Width = image2.naturalWidth;
var data3=[];
var imageData = context.getImageData(0,0,imageWidth,imageHeight);
var image2Data = context2.getImageData(0,0,image2Width,image2Height);
var data = imageData.data;
var data2 = image2Data.data;
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
//str = String.fromCharCode.apply(null, data); // "ÿ8É"
// str2 = String.fromCharCode.apply(null, data2); // "ÿ8É"
// to Base64
b64 = _arrayBufferToBase64(data);
b64_2 = _arrayBufferToBase64(data2 );
console.log("64 base"+b64_2);
//
var toReturn = 0;
var firstBytes =new Uint8Array(1024);
var secondBytes=new Uint8Array(1024);
var different=new Uint8Array(1024);
// firstBytes = Convert.FromBase64String(first64);
// secondBytes = Convert.FromBase64String(second64);
different = 0;
var mylength;
if(b64.length>b64_2.length)
{
mylength=b64.length;
}
else
{
mylength=b64_2.length;
}
for (var index = 0; index < mylength; index++) {
different = (b64[index] ^ b64_2[index]);
while (different != 0) {
toReturn++;
different &= different - 1;
}
}
var percentage=(toReturn/((image2Height*image2Width)*2))*100;
if(percentage >=100)
{
percentage=100;
}
alert("Difference is "+percentage+" to return" +toReturn + " data1 length"+data.length+ " data2 length"+data2.length);
}
This function works well without any errors. But it won't recognized advanced features like scaling and rotating. Give me some ideas how to do this using php.

javascript error with php variable passing in codeigniter

function something(frm,i){
//var ch=frm.outof1.value;
for(var j=1;j<=i;j++)
{
//var b="outof" + j;
alert(frm.outof+j.value);
}
//alert("outof" + i);
return false;
}
$js='onClick="something(this.form,\''. $ii .'\')"';
echo form_button('mybutton', 'Click Me', $js);
and getting output NAN
where in html this is // echo form_input('outof'.$i,''); // the form input.
First, you will want to make sure the passed $ii is made into the correct type (not a string) by using parseInt. Then you construct the form input name by concatenating 'outof' and the number before evaluating .value.
function something(frm, i)
{
for(var j = 1; j <= parseInt(i); ++j) {
alert(frm['outof' + j].value);
}
}
alert(parseInt(frm.outof) + parseInt(j.value))
Most likely, you're trying to sum up strings, and not integers

undefined value single checkbox javascript to another page

i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltbody>
&lta href="addevent.php" rel="facebox" &gtlink&lt/a&gt
&lt/body>
addevent.php
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltscript language="javascript" type="text/javascript"&gt
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i&ltelemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i &lt len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i&ltformNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i &lt max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
&lt/script&gt
&ltscript type="text/javascript"&gt
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i &lt lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") &gt -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j &lt labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
&lt/script&gt
&lt/head&gt
&ltform name="eventAgendaForm" id="eventAgendaForm" &gt
&ltul class="checklist cl3"&gt
&ltli &gt&ltlabel for="c1"&gt
&ltinput id="checkId" name="checkName" value="1" type="checkbox" &gt
&lt/label&gt&lt/li&gt&lt/ul&gt
&ltinput class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" /&gt
&lt/form&gt
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.

Creating an element and insertBefore is not working

Ok, I've been banging my head up against the wall on this and I have no clue why it isn't creating the element. Maybe something very small that I overlooked here. Basically, there is this Javascript code that is in a PHP document being outputted, like somewhere in the middle of when the page gets loaded, NOW, unfortunately it can't go into the header. Though I'm not sure that that is the problem anyways, but perhaps it is... hmmmmm.
// Setting the variables needed to be set.
echo '
<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/shoutbox.js"></script>';
echo '
<script type="text/javascript">
var refreshRate = ', $params['refresh_rate'], ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName(\'div\');
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
var is_counted = 0;
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
else
{
if (divName.indexOf(\'dp_Reserved_Counted\') == 0)
{
is_counted = 0;
shoutCount++;
continue;
}
else
{
shoutCount++;
is_counted = 1;
}
}
// Empty out the name attr.
alldivs[i].name = \'dp_Reserved_Counted\';
var shoutId = \'shoutbox_area\' + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement(\'div\');
shoutHolder.setAttribute(\'id\', [shoutId]);
shoutHolder.setAttribute(\'class\', \'dp_control_flow\');
shoutHolder.style.cssText = \'padding-right: 6px;\';
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
if (is_counted == 1)
{
startShouts(refreshRate, shoutId);
break;
}
}
}
</script>';
Also, I'm sure the other functions that I'm linking to within these functions work just fine. The problem here is that within this function, the div never gets created at all and I can't understand why? Furthermore Firefox, FireBug is telling me that the variable divName is undefined, even though I have attempted to take care of this within the function, though not sure why.
Anyways, I need the created div element to be inserted just before the following HTML:
echo '
<div name="dp_Reserved_Shoutbox" style="padding-bottom: 9px;"></div>';
I'm using name here instead of id because I don't want duplicate id values which is why I'm changing the name value and incrementing, since this function may be called more than 1 time. For example if there are 3 shoutboxes on the same page (Don't ask why...lol), I need to skip the other names that I already changed to "dp_Reserved_Counted", which I believe I am doing correctly. In any case, if I could I would place this into the header and have it called just once, but this isn't possible as these are loaded and no way of telling which one's they are, so it's directly hard-coded into the actual output on the page of where the shoutbox is within the HTML. Basically, not sure if that is the problem or not, but there must be some sort of work-around, unless the problem is within my code above... arrg
Please help me. Really what I need is a second set of eyes on this.
Thanks :)
When you're testing divName, switch the order of your conditions from this
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
to this:
var divName = alldivs[i].getAttribute(\'name\');
if (!divName) // this is sufficient, by the way
continue;
else if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
The problem is that when the script finds a div without a name, it tries to call the indexOf property of a non-existent value and therefore throws an error.
There were a number of issues in the loadShouts method. First being the comparison of a string "undefined" instead of a straight boolean check, which will match. I also removed a bunch of un-needed logic. Beyond this, the id attribute being assigned to the new shoutHolder was being passed in as an array, instead of a direct property assignment.. See if the following works better.
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
Ok, just wanted to let you know how it went. And I thank both you greatly Tracker1 and Casey Hope. Especially Tracker for the excellent rewrite of the function. You all ROCK. Here's the final function that I'm using bytheway, just a tiny bit of editing to Tracker1's Answer, which is why you got my vote hands down!
echo '
<script type="text/javascript">
var refreshRate = ' . $params['refresh_rate'] . ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
</script>';
Thanks Again, you are the BEST!

Categories