Google Closure Compiler returning in different encoding? - javascript

Google Closure Compiler returns the following code:
{"compiledCode":"vaporize\u003dfunction(){var a\u003d12+Math.random()*10;a\u003e9\u0026\u0026console.log(\"wow, k is bigger than j\");return 9+3*a};compilation_level\u003dADVANCED_OPTIMIZATIONS;vaporize\u003dfunction(){var a\u003d12+Math.random()*10;a\u003e9\u0026\u0026console.log(\"wow, k is bigger than j\");return 9+3*a};"}
It replaced (I think) equal signs with \u003d and some other stuff. What's wrong ?
My post variables are:
'compilation_level' :
'ADVANCED_OPTIMIZATIONS',
'output_format': 'json',
'warning_level' : 'QUIET',
'output_info' : 'compiled_code',
'js_code' : code
Edit1: Only if I set 'output_format' : 'text' the encoding comes out right.

It replaced (I think) equal signs with \u003d and some other stuff. What's wrong ?
Nothing. "\u003d" is a valid JavaScript (or, here, JSON) representation of a string containing an equals character; it is completely equivalent to "=".
What are you doing with the output to make it matter? If you don't want JSON output, you should indeed ask for raw ‘text’.

Related

Google Earth Engine ee.Number to integer

This is probably a simple question for people familiarized with the Code Editor of Google Earth Engine (https://code.earthengine.google.com/) or generally Javascript.
In my code, I need to use the size of an object for a boolean conditional (e.g. n>0). However, the output of .size() which I would store in n does not return a plain integer, but a ee.Number structure and I am not being able to transform it into an integer to properly evaluate the conditional.
Example with the structure ee.Number of Earth Engine:
var n=ee.Number(1)
print(n)
print(n.int())
print(n==1)
print(n===1)
print(n.int()==1)
print(n.int()===1)
print(n.int()== parseInt(1))
This outputs these evaluate as false, even when I try to tast the number structure into an int.
1
1
false
false
false
false
false
note:
print(typeof n)
returns an object (JSON):
object
Any help very much appreciated. Thanks
This is due to how GEE works. Processing steps are constructed locally as objects and then only evaluated by the server once another function requires it.
print is one of the functions that requires execution, this is why it shows as integer in your console.
You can force evaluation with .getInfo()... this however should be used with caution, because everything is pulled to the client side, which can be problematic with big objects.
So this works:
var n=ee.Number(1)
print(n)
print(n.getInfo()==1)
giving
1
true
This section of the documentation explains the background.
If the value of n indeed is JSON, try to parse it:
n = JSON.parse(n);
Then convert it into an integer:
n = parseInt(n);

jQuery / Javascript substitution 'Syntax error, unrecognized expression'

I am implementing jQuery chaining - using Mika Tuupola's Chained plugin - in my rails project (using nested form_for partials) and need to dynamically change the chaining attribute:
The code that works without substitution:
$(".employee_title_2").remoteChained({
parents : ".employee_title_1",
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
The attributes being substituted are .employee_title_1 and .employee_title_2:
var t2 = new Date().getTime();
var A1 = ".employee_title_1A_" + t2;
var B2 = ".employee_title_2B_" + t2;
In ruby speak, I'm namespacing the variables by adding datetime.
Here's the code I'm using for on-the-fly substitution:
$(`"${B2}"`).remoteChained({
parents : `"${A1}"`,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
Which throws this error:
Uncaught Error: Syntax error, unrecognized expression:
".employee_title_2B_1462463848339"
The issue appears to be the leading '.' How do I escape it, assuming that's the issue? Researching the error message Syntax error, unrecognized expression lead to SO question #14347611 - which suggests "a string is only considered to be HTML if it starts with a less-than ('<) character" Unfortunately, I don't understand how to implement the solution. My javascript skills are weak!
Incidentally, while new Date().getTime(); isn't in date format, it works for my purpose, i.e., it increments as new nested form fields are added to the page
Thanks in advance for your assistance.
$(`"${B2b}"`).remoteChained({
// ^ ^
// These quotes should not be here
As it is evaluated to a string containing something like:
".my_class"
and to tie it together:
$('".my_class"')...
Same goes for the other place you use backtick notation. In your case you could simply use:
$(B2).remoteChained({
parents : A1,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
The back tick (``) syntax is new for Javascript, and provides a templating feature, similar to the way that Ruby provides interpolated strings. For instance, this Javascript code:
var who = "men";
var what = "country";
var famous_quote = `Now is the time for all good ${who} to come to the aid of their #{what}`;
is interpolated in exactly the same way as this Ruby code:
who = "men"
what = "country"
famous_quote = "Now is the time for all good #{who} to come to the aid of their #{what}"
In both cases, the quote ends up reading, "Now is the time for all good men to come to the aid of their country". Similar feature, slightly different syntax.
Moving on to jQuery selectors, you have some flexibility in how you specify them. For instance, this code:
$(".my_class").show();
is functionally equivalent to this code:
var my_class_name = ".my_class";
$(my_class_name).show();
This is a great thing, because that means that you can store the name of jQuery selectors in variables and use them instead of requiring string literals. You can also build them from components, as you will find in this example:
var mine_or_yours = (user_selection == "me") ? "my" : "your";
var my_class_name = "." + mine_or_yours + "_class";
$(my_class_name).show();
This is essentially the behavior that you're trying to get working. Using the two features together (interpolation and dynamic jQuery selectors), you have this:
$(`"${B2}"`).remote_chained(...);
which produces this code through string interpolation:
$("\".employee_title_2B_1462463848339\"").remote_chained(...);
which is not correct. and is actually the cause of the error message from jQuery, because of the embedded double quotes in the value of the string. jQuery is specifically complaining about the extra double quotes surrounding the value that you're passing to the selector.
What you actually want is the equivalent of this:
$(".employee_title_2B_1462463848339").remote_chained(...);
which could either be written this way:
$(`${B2}`).remote_chained(...);
or, much more simply and portably, like so:
$(B2).remote_chained(...);
Try this little sample code to prove the equivalence it to yourself:
if (`${B2}` == B2) {
alert("The world continues to spin on its axis...");
} else if (`"${B2}"` == B2) {
alert("Lucy, you've got some 'splain' to do!");
} else {
alert("Well, back to the drawing board...");
}
So, we've established the equivalency of interpolation to the original strings. We've also established the equivalency of literal jQuery selectors to dynamic selectors. Now, it's time to put the techniques together in the original code context.
Try this instead of the interpolation version:
$(B2).remoteChained({
parents : A1,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
We already know that $(B2) is a perfectly acceptable dynamic jQuery selector, so that works. The value passed to the parents key in the remoteChained hash simply requires a string, and A1 already fits the bill, so there's no need to introduce interpolation in that case, either.
Realistically, nothing about this issue is related to Chained; it just happens to be included in the statement that's failing. So, that means that you can easily isolate the failing code (building and using the jQuery selectors), which makes it far easier to debug.
Note that the Javascript syntax was codified just last year with ECMAScript version 6, so the support for it is still a mixed bag. Check your browser support to make sure that you can use it reliably.

Get the value of confused Javascript code

I got a piece of code like this:
var password = eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('9 5$=["\\8\\3\\4\\3\\2\\2\\1\\3\\2\\3\\3\\2\\2\\7\\3\\1\\4\\1\\3\\2\\1\\3\\1\\3\\2\\2\\2\\1\\3\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\2\\1\\3\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\2\\1\\3\\1\\3\\2\\2"];6 c(){e["\\f\\g\\d\\a\\b"](5$[0])}',17,17,'|x2b|x5d|x5b|x21|_|function|x29|x28|var|x72|x74|O0|x65|window|x61|x6c'.split('|'),0,{}));
And I unpacked the following code(except 'var password = '):
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('9 5$=["\\8\\3\\4\\3\\2\\2\\1\\3\\2\\3\\3\\2\\2\\7\\3\\1\\4\\1\\3\\2\\1\\3\\1\\3\\2\\2\\2\\1\\3\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\2\\1\\3\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\1\\4\\1\\3\\2\\2\\1\\3\\1\\3\\2\\2"];6 c(){e["\\f\\g\\d\\a\\b"](5$[0])}',17,17,'|x2b|x5d|x5b|x21|_|function|x29|x28|var|x72|x74|O0|x65|window|x61|x6c'.split('|'),0,{}));
Then I got:
var _$ = ["\x28\x5b\x21\x5b\x5d\x5d\x2b\x5b\x5d\x5b\x5b\x5d\x5d\x29\x5b\x2b\x21\x2b\x5b\x5d\x2b\x5b\x2b\x5b\x5d\x5d\x5d\x2b\x5b\x21\x2b\x5b\x5d\x2b\x21\x2b\x5b\x5d\x2b\x21\x2b\x5b\x5d\x5d\x2b\x5b\x21\x2b\x5b\x5d\x2b\x21\x2b\x5b\x5d\x2b\x21\x2b\x5b\x5d\x2b\x21\x2b\x5b\x5d\x2b\x21\x2b\x5b\x5d\x2b\x21\x2b\x5b\x5d\x5d\x2b\x5b\x2b\x5b\x5d\x5d"];
function O0() {
window["\x61\x6c\x65\x72\x74"](_$[0])
}
And after decoding:
var _$ = ["([![]]+[][[]])[+!+[]+[+[]]]+[!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[+[]]"];
function O0() {
window["alert"](_$[0])
}
Now I wonder how the codes execute and what is the value of password ?
Thanks so much.
The code is obfuscated and intended to permit execution of arbitrary code even if the script text is passed through filters.
The approach is often used for tracking, phishing and other undesirable activities, so I would suggest you don't try running it.
All you need to do is run this code -- not the 'window' stuff, but only the 'decode' part -- and you'll see the solution.
Here are some pointers on decoding:
the outer array brackets are a decoy
an empty array [] evaluates to 0 when used in a calculation such as +[]
!0 = 1
!+0 evaluates to true or 1, !+1 to false or 0 (this surely must be a loophole in Javascript)
.. so !+[] is simply 1.
[1]+[1] is not a valid math sum, so both arrays are converted to strings before being added up.
The above takes care of the numbers. Where does the first character come from? The first part ([![]]+[][[]]) evaluates directly to a string two constants, which add together as a string again, and the array index after it picks up a single character.

Java Script equivalent to Excel Formula

Hi hope someone can assist.
I have the following formula in a excel spreadsheet. It calculates the difference between T40 and AB40, if it returns a negative value, it recalculates AB40 - T40 to return a positive value.
=IF(T40 > AB40, + T40 - AB40, AB40 - T40)
I have imported the spreadsheet to a PDF document, and cannot find an equivalent java script to match above.
Can anyone assist, I am now desperate and in urgent need of the information.
You don't need an if statement you can just do:
Math.abs(T40-AB40)
To clarify this will return the absolute value of a mathematical operation so:
Math.abs(10 - 2) //returns 8
Math.abs(2 - 10) //returns 8
If'm not familiar with the specifics of javascript in pdf, but something like this should work:
if(T40>AB40){
return T40-AB40;
}else{
return AB40-T40;
}
Or use a ternary operator like user1161318 suggested.
It can be done with an if as another response shows, but if you want to treat it as an expression, you could do it this way:
T40 > AB40 ? T40-AB40 : AB40-T40;
In Javascript:
cond ? ifTrue : ifFalse
Is an alternate way of posing an if statement that allows the whole thing to be treated as an expression, and thus be part of a formula, assigned to a variable, put in the parameter list of a function, etc... unlike if. So it's perfectly legal to do things like:
alert( cond ? ifTrue : ifFalse );
var x = cond ? ifTrue : ifFalse;
And so on, whereas you can't do that with an if block. Of course, include the expression within parenthesis if there's any chance of ambiguity (eg: it's part of a bigger formula, etc...)
I think this is closer to preserving the meaning of IF in Excel.

Changing a string into an integer

This is a follow up question to this:
Google Analytics Event Tracking via a jQuery plugin
Matt Austin was correct. I was passing a string of the integer for the GA value parm when I should have been passing the int value itself. Evidently Google Analytics is sensitive like that :)
So I changed: parmValidatedObject[key] = val;
to: parmValidatedObject[key] = val.valueOf();
But that doesn't seem to be working as expected. GA doesn't seem to pick this up as an int. What am I not understanding about valueOf()?
btw, I might also run into something similar with one of the other parms that's a boolean. I'm translating those strings to the value or 0 or 1 but I'm wondering (out loud and in advance) if that's the right approach.
parseInt(val,10); will convert your string to an integer. It is a JavaScript function, not jQuery.
!!val converts a value to a boolean. Note that "0" is considered a truthy value and so !!"0" returns true, unlike the false you might expect. In this case, you may be better off using
(""+val == "0") ? false : true;

Categories