I'm a beginner to Python trying to decode this javascript sequence. I'm not only a beginner in Python, I understand javascript even less :) I know i could put it into an online decoder such as this: http://coderstoolbox.net/string/ but I want to deal with it myself - more for practice than anything else... Im using Beautiful Soup to get the data, so I have its functions available for decoding.
If anyone can point me to equivalent functions in python I would appreciate it.
function encode(str){
var t=''; var s=unescape(str);
var x=Math.round(Math.sqrt(49));
for(var i=0;i<s.length;i++) t+=
String.fromCharCode(s.charCodeAt(i)^(i%2?x:0));
print(t);
}
This is my understanding of it so far:
i think I can use 'HTML entities in BS to unescape..?
the second one just seems to be a constant number ? square root of 49 rounded...
sets up the loop
this is the one i dont get. 1 i dont know what the fromCharCode function does. 2 not sure what the bit at the end is. looks like its getting a character code from i to the power something. i understand i is being modulo'd with 2 but what is the '?x:0' bit ? - how would you replicate this in Python ?
thanks for reading !
EDIT: is there a python library that can just run this code ? I've done this before with bash and used rhino, but the alternatives in Python seem a bit scary for a beginner, eg spidermonkey, etc...
1) the python equivalent to unescape is urllib.unquote() in python 2.x series and urllib.parse.unquote() in python 3.x series
2) you guess the simplest way to do it is to do x = 7
3) the simplest way to loop on string charters is to do for c in string: but to have the index you should do for i,c in enumerate(string):
4) the string.charChodeAt(c) is the same than chr(c)
finally I would duplicate the loop part as follow:
result = []
for i,c in enumerate(string):
result.append(chr(ord(c)^(x if i%2 else 0)))
print("".join(result))
in fact using a temporary array to make the appends is more efficient than happening to strings as the strings don't mutate
I don't know Python, but I can explain what is happening here so that you can rewrite in Python.
1) function encode is declared and not assigned, so in JavaScript it will get hoisted to the top of its parent function, if there is one.
2) Inside function encode there are 4 variables that will get hoisted to the top of function encode:
t, which is assigned to an empty string, which means 0 length but type is string
s, which is assigned of a value of the argument "str" that is passed through the unencode function. unencode just reverses a URI reserved character encoding.
x, which is of type number with a value of 7
i, which is assigned 0 and used as your loop iterator
3) The loop index starts at 0 and breaks no later than the index is the same size as the character length on variable s.
4) The loop is written in a sloppy manner without curly braces, so it terminates at the first line break, which means variable t is performing a string concat in reflection of variable s.
5) The next line beginning with the string object looks like it is supposed to be in loop, but its not, because this code is sloppy. It doesn't matter anyways because variable s is not really used for anything further.
6) A print function is used with variable t as its argument. Variable t should look identical to variable s, which is probably not what the original author of this code intended.
7) I have no idea what print is. Perhaps the original author meant something like alert or console.log instead of print.
Related
I have developed a large number (>1000) strings that are intended to be fed into eval. I am trying to migrate away from using eval, as "eval is evil" and I'm generally trying to make things more secure. However, migrating from eval into a properly defined function is a little tricky, as eval() returns the value of the last expression evaluated. This means that a string that was previously evaled like this:
const stringToEvaluate = "x = 1; x + 1"
is difficult to migrate directly into a function, because the last expression in the statement does not explicitly return anything.
With regards to the string above, I might use eval in this way:
const y = eval(stringToEvaluate)
console.log(y) // 2
However, I can't use:
const y = (function safeFunction() {
x = 1;
x
})()
console.log(y) // undefined
as safeFunction does not return anything.
Importantly, I am looking for a way to migrate these eval strings without needing to modify each individual string to include return statements in appropriate places. This is because the large number of scripts would make this quite inconvenient. Also, the scripts can be more complicated than this, but this is a nice, minimal example.
Does anyone happen to know of any way to migrate these scripts into functions without needing to manually edit each of them? Also, this is one my first times posting to StackOverflow, so I welcome any feedback about ambiguity in my question! Thanks!
Edit:
Apologies for the ambiguity, another example of a "string" to be converted into a script is:
const stringToEvaluate = """
let x;
if (
$('.itemToFind').length > 0 &&
$('.itemToFind').html().trim() != ''
)
$('.itemToFind del').html().trim(); <<< eval wraps either this
else if ($('.price h4.offer-price').length > 0)
$('.itemToFind').html().trim(); <<< or this
"""
(note that I have included the string across multiple lines to aid readability).
Can't figure out why exactly a variable can't be used to help call a value in an array with JS/Jade. This is being called inside a script on a .jade file.
The array contains roughly 400 entries and one of the entries is as follows:
myFood[10]['Cake'] = 50
When using the variable i instead of directly putting in the number 10 an error occurs.
Works:
alert (i) // 10
alert (#{myFood[10]['Cake']}) // 50
Error:
alert (#{myFood[i]['Cake']}) // Error, Cannot read property 'Cake' of undefined.
First of all, know that Jade recently was renamed to "pugjs".
I'm assuming that i is a javascript variable as you stated in the comments.
The pug (jade) context and the browser Javascript context are two very different things, so if you define i in browser Javascript, jade will not see it as a variable, just plaintext waiting to be interpreted by the browser. That's why myFood[i] is undefined and thus resulting in this error.
The correct way to define a jade variable is by prefixing your line by a dash (-), as described here.
The full code is:
- var i = 10;
alert (#{i}) // 10
alert (#{myFood[10]['Cake']}) // 50
You note that I also changed the first alert to tell pug to replace the #{i} part by the actual value of i.
If you want to access each value I would highly suggest that you use loops instead of using an i to access the array.
Mixing pug and javascript is a bit tricky, so good luck!
I have been wondering if is possible to use a HTML <input id="in"> (which I could enter lets say 25 / 6 * 3) and output the mathematical evaluation with Javascript, I have written up something which very understandably did not work, would there be any way to make it work?
function go() {
var x = $("#in").val();
alert(parseInt(x))
}
Your answers are much appreciated
Yes you can using the eval() function. Assuming you're input is going to take a value then you can simply call eval(myString) which should return the result.
For example if you execute the following:
alert(eval('3 + 4')); // alerts 7
Be wary though in that anything you do really shouldn't be saved as this could lead to javascript attacks if someone is able to submit some javascript that will run on someone elses browser.
Yes, it is possible to do what you're asking; you just have to use eval(). However, using eval() is not very safe. since this means that any JavasScript code inside #in will be evaluated, which is probably not what you want.
A better way to do this would be to write a parser to parse the mathematical expression and build a syntax tree and then evaluate that.
You can use the expression parser of math.js
alert(math.eval('3 + 4'));
Is there any max length for a JavaScript function() parameter?
I created a function which had a long parameter, but it didn't work. When I shortened the parameter of the same function, it worked. Does that mean that there is a maximum length for a function argument? If so, please recommend alternatives to my current method.
JavaScript
function example(idnum) {
alert(idnum);
}
HTML
<div onclick='example(*php variable,no special character included*)'></div>
When the PHP variable is long, such as "17b6f557969619544eb1e6cd58c3f341", it does not work. But if I change the variable to something like "203", the function works successfully.
"Douglas Crockford" wrote in message
news:9a027$3fa7c56d$44a4aebc$9152#msgid.meganewsse rvers.com...
[color=blue]
... . The maximum length with will be implementation-specific. ...[/color]
In microsoft.public.scripting.jscript, Michael Harris
(Microsoft.MVP.Scripting), who might be expected to know, quoted:-
In JScript,
variant string variables have the same limit as in VBScript, up to
2^31 characters.
String literals (as in "this is a literal") have (IIRC) a limit
~2^10 (1024) characters.
for the JScript implementation.
Blockquote
Sounds like you actually want to pass the PHP variable's value literally to the function, not as a variable name.
example(17b6f557969619544eb1e6cd58c3f341)
tries to call the function with that variable (likely causing an exception, or even being a syntax error), while
example(203)
calls the function with the number literal for the integer 203. If you want to pass the value as a string, use json_encode!
Also notice that you will need to escape everything for use in a HTML attribute (i.e. escape quotes, < and >), as you have
<div onclick=" [some code here] ">
Every time i pass some parameters to a JavasScript or jQuery functon, i use some random letters. What are the correct letters for the corresponding variable types?
function(o){} for example is for a object. But what are the other letters? Do someone have a list of those?
I advise you not to assign names according to types but according to the data that the variable contain. If you pass an object that contains the configuration for a function call the variable configuration if you pass a variable that contains a name call it name and so on. In this way the code is more readable and understandable.
Any letter will do, there is no such thing as a standard for using letters as parameters.
However, using letters for parameters is bad practise, because a letter does not describe what the parameter is intended for.
Consider this example:
function ShowBusyCursor(s) {
//...
}
If you look at the function header, you cannot guess what the parameter s stands for. But if you change the code to this:
function ShowBusyCursor(cursorIsDisplayed) {
//...
}
The parameter cursorIsDisplayed is a lot more developer-friendly and tells you it's a boolean that can be set to true to display the cursor. If you used s, you would have to look into the code to figure that out.
Here is a good list of letters I could think of:
o - object
a - array
s - string
d - date
n - number
r - regexp
b - boolean
But seriously, jokes apart, I think you might be mixing up the packed/minified source with the actual source that developers write. For example, this little function looked like this originally:
function myFunction(personName) {
this.name = personName;
}
But after minifying, it becomes:
function myFunction(a){this.name=a}
packer is one such utility by Dean Edwards that will minify your Javascript. Play with your source code at this website and see the compressed output. Check the Shrink variables option on the right to see how parameters and other variables get renamed.
This however shouldn't affect how you write your code at all. Be it Javascript, or any other language, all identifiers - variables, function names, class names, etc. should be named after what they represent or do rather than obscure shorthands.
Re-iterating what mck89 said, it's better to go with explanatory variable names rather than just a letter for the type. What if you have more than one parameter of the same time, do you start appending numbers?
I have often seen explanatory variable names which include the type, for instance sFirstName would be a string denoted by the "s", bForce would be a boolean, oConfig would be an object and nSubTotal would be a number.
This is a variation of Hungarian notation, and I'd advise against using single-letter variable names. What if you need to pass in 2 of any one data type? Like others have said, it also doesn't represent the meaning of the variable very well. I think this is much better:
function foo(sFirstName, sLastName)
{
alert("Hi, my name is " + sFirstName + " " + sLastName);
}