Document variable in python - javascript

If in the middle of my software, i have this variable that i need explain what it is and what is used for, i need document the variable.
I have a background in JS, so that's how i do:
/**
* Explain what the variable is, and what is for.
* #variable {Object} nameOfVariable
*/
var nameOfVariable = []
In the case of python:
# ??
name_of_variable = []
Is there conventions for this type of thing?
Thanks a lot.

Yes there is - this is what I can find
https://www.python.org/dev/peps/pep-0257/
For functions you can add a docstring e.g.
def some_function():
""" Write here a one line summary.
If wanted, then leave a line and write a more detailed one"""
The """ need to be indented correctly to work
However, for hashes #, which is more common after single variables, they don't need to be indented correctly. E.g.
some_variable = Something # This variable is doing this...
Hope that is somewhat helpful.

PEP257 documents so called docstrings which is a string literal which appears as first statement in the definition of a module, class, function or a method. As far as I know if you want to leave some information about a variable you leave regular comments near it. For example:
# This is some variable ...
some_variable = ...

You might find that people document parameters, what a function returns, and so on, but usually variables are not documented in python libraries.
The names should generally be self-explanatory.

Related

In JavaScript, how do I get the URL of the JavaScript file, not the location URL?

I would like to use a query string parameter so that way I can specify the name of a DOM element.
I have some code that requires the height of the header and I would like that code to work for any theme. Only at times the header uses the <header> tag, at times it has a specific identifier, at times it is a specific class... to be able to reuse that code over and over again, I'd like to include it in a way such as:
<script src="https://www.example.com/js/my-script.js?c=header"></script>
What I want to be able to do is get the "?c=header" part from that JavaScript URL to send search a DOM object with jQuery(".header"). Do we have a way to know the URL of the JavaScript itself from the JavaScript being executed?
Obviously, I know of window.location.href and that's not the URL I'm looking for.
As mentioned by #Kaiido in a comment, there is the document.currentScript parameter that gives you access to the <script> tag which is currently running. Only there is a small trick to it, that parameter is defined on the first pass, not when executing functions within your script.
So what one can do is save that information, or at least what you need from that object, in the global scope or a static in your object.
In my case, I just did the following:
// Script to tweak things on many websites
var this_script_url = document.currentScript.src;
jQuery(document).ready(function()
{
// at this point: "document.currentScript === null"
var qs = this_script_url.split("?", 2);
if(qs && 2 == qs.length)
{
... // handle qs[1] which is the query string (a=1&b=3&...)
}
});
Please make sure you don't use a global name that's too generic. It should include the name of your script or abbreviation thereof. Otherwise you are likely to clash with another script's global.
Now if you have a prototype object, I would suggest you use a static member instead of a global.
var my_class = {};
my_class.script_url = document.currentScript.src;
// and later you can reference it directly as in:
url = my_class.script_url;
This way you are more likely to avoid clashing problems (the only thing that needs to be changing in case of a clash is the name my_class).
At this point, the ES5 or ES6 class keyword does not offer you to create variables.

Can $parse or $eval be used to evaluate a stingified boolean equation?

I'm trying to understand $parse and $eval better and figure out if they are (or can be) used in a manner that I thought possible. I've created a plnkr to show my issue/question and reference their lines
I have an object with a boolean expression as a string value, which will be served to me from an external source (script.js line 6-10):
$scope.input123456abcdefg;
$scope.object123456abcdefg = {
disabled: "input123456abcdefg == 'hello'"
};
I have tried a few code walkthroughs, all of which have basically boiled down to (my understanding) of these 2 types of operations/functions (script.js line 12-15):
var template_v1 = $parse('object123456abcdefg.disabled');
$scope.expression_v1 = template_v1($scope);
$scope.expression_v2 = $scope.$eval('object123456abcdefg.disabled');
What I'm expecting (hoping) for either $parse or $eval to do is create an equivalent to (script.js line 17):
$scope.expression_v3 = $scope.input123456abcdefg == 'hello';
However, I'm only returned the same string as when I started, which you can see evaluated on the DOM (index.html lines 24 & 28).
Can $parse or $eval be used in this fashion, and if so where am I dropping the ball at? Or is there another option in Angular that is correct for performing this type of action?
As suggested by #dandavis I'd avoid eval() altogether if possible.Here a small explanation from MDN
Why do you require the value of object123456abcdefg.disabled to be passed in?
EDIT: If you really could not find another way of doing so, this is how you make your code work:
$scope.expression_v2 = $scope.$eval($scope.object123456abcdefg.disabled);

JavaScript - case sensitivity issue within an object/property

I have an issue with JavaScript case sensitivity and I will need your valuable piece of advice here. I have the following object created:
var foo = function () {
this.myColor1 = '#000000';
this.MyColor2 = '#FF2000';
this.MyCOLOR3 = '#FFFFFF';
}
as you can see, each property may come in any case form, lowercase, uppcase, mixed, etc. These values are coming from a database and I don't have control onto them.
I want to be able to call them ignoring the case sensitivity. For example, I would like to be able to call them like this:
console.log(foo.mycolor1);
// or
console.log(foo.myColor1);
I guess my only approach to achieve this, would be to convert everything in, let's say, lowercase when I define those, and then, when I call them back to convert my request into lowercase again.
A little piece of background here; my aim is to provide an SDK to a few developers that they will write their own code for a platform I am working on. These values will be saved by the developers themselves into a database. For some reason, all those values are stored in lowercase. So, I either have to tell them 'no matter how you set them, you should request everything in lowercase', or, ideally, I should find a way to convert everything before their request is post.
An idea would be to write a method, and tell them to make the request like this
foo('mycolor1');
foo, is going to be a function that would handle the case sensitivity easily. But, I would prefer to use the foo.mycolor1 notation, so ... your help is needed :)
FYI, jQuery is available!
Thank you,
Giorgoc
when you render the javascript from DB use toLower() to set the variables names... and then reference them in lower case...

In JMeter and BeanShell, how can I make a variable lowercase?

In JMeter's User Parameters, how can I make a variable lowercase?
Left column
my_lowercase_variable
Right column
${__BeanShell('${my_variable}'.toLowerCase())} //fails
or
${__javaScript('${my_variable}'.toLowerCase())} //fails
Such that ${my_lowercase_variable} is lowercase of ${my_variable}. Tried with quote and without and escaping and such. No luck. Any tricks or tips welcome.
Note to self.
It turns out to be a two liner in BeanShell Sampler rather than a __BeanShell command. Not exactly in the examples unfortunately.
I added the BeanShell Sampler under the Thread Group, then made a variable. No parameters in the form were required only the two liner script below. As long as I don't change the variable I can copy the data to another variable, change that instead, and then make a Value reference to that wherever needed.
First define a variable in some User Parameters or such
ie:
Name: my_initial_reference
Value: ITS IN CAPS
Add a Bean Sampler under the User Preferences or definition list (just next, it's not a child process)
Put in:
String blah = "${my_initial_reference}"; //
vars.put("blah", blah.toLowerCase()); //${blah} = "its in caps" now available
Now under that with Name/Value pairs I can map ${blah} as the value to whatever process name requires it.
Note that the Debug response will still show the initial value in caps but you'll also see blah=its in caps which is what I wanted to use.
Simply can add a function
${__lowercase(${VAL},VALUE)}
${__uppercase(${VAL},VALUE)}
Note: VAL can be correlated or paramiterized value (e.r VAL= TO LOWER or VAL= TO UPPER). We can use this function in beanshell (pre-processor/post-processor/sampler). Jmeter version using (2.6).
Can use it where ever we want in the script as ${VALUE}.
${__javaScript('${foobar}'.toLowerCase())} does work. If the output is ${foobar} instead of desired value, it means that the variable has not been declared
Note that variables are defined only after the "User Defined Variable" component has been parsed. Variables cannot be reused within a single "User Defined Variable" component e.g.:
The second row in that image will not be able to refer to the variable my_variable in the first row. To be able to refer to the first variable, two "User Defined Variable" components is needed. The first variable will be in the first component and the second variable in the second one, e.g.:
With that, ${my_lower_case_variable} will successfully be converted into some value.
${__BeanShell("${my_variable}".toLowerCase())} works too. (Note that Bean Shell requires double quotes. The code in your question uses single quotes.)
Another way is to use vars.get:
${__javaScript(vars.get('my_variable').toLowerCase())}
${__BeanShell(vars.get("my_variable").toLowerCase())}
Hmmmm, your bean shell code didn't work for me. The bean shell sampler returned:
Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``String blah = AAP; vars.put("blah", blah.toLowerCase()); //${blah} now availab . . . '' : Typed variable declaration : Void initializer
I added two double quotes to solve it:
String blah = "${my_initial_reference}";
vars.put("blah", blah.toLowerCase()); //${blah} now available
The beanshell and JavaScript functions in this use will fail, because they don't import the packages you need in order to use .toLowerCase.
If you really need to use a function to convert case (rather then declaring them as lowercase in the first place), you may need to write a full beanshell post-processor script in order to import the needed packages.
http://jmeter.apache.org/usermanual/functions.html#__BeanShell
http://jmeter.apache.org/usermanual/functions.html#__javaScript
http://www.javadocexamples.com/java_examples/org/apache/jmeter/
var blah = "${my_initial_reference}";
blah.toLowerCase();

Javascript getVariableName

This is my first post.
I'm trying to do some basic meta-programming with javascript, and I was wondering if there is a way of get the id of a particular object and with that id, access to the variable name, or get simply the variable name of a particular object. I wanna recreate a situation in which you first create every single html in a web page, and append to some of the html tags events associated to a particular class -example class Person-. for example: Supposed the next code:
var someFunction = function(someText){alert(someText);}
function SomeClassFunction(){
this.aClassFunction = someFunction;
}
var aVariableName = new SomeClassFunction();
and in the HTML code suppose I have the next piece of code.
<html>
<head>
<title></title>
</head>
<body>
<div onclick="aVariableName.aClassFunction('Some text to show in alert');">
</div>
</body>
</html>
Then, as you may notice the onclick event uses the aVariableName I created before, but because I first create the name of the variable and then append the name in the code cause I knew aVariableName was the name of that object. What I wanna do or implement is to create the text above in html without know the variable name of an specific object. I have surfed on the net but, unfortunately I haven't found anything about it.
i dont know how to get the name of a variable from the code its self without doing a whole load of work parsing stuff, which will get messy, and i'd shoot someone for this.
var someValue;
var foo = function() { someValue; }
alert((foo + '')); // this is now a string, use substr to extract variable name
You know you can set events like this in javascript someElement.onclick = someFunction so you dont really need to know the name of the variable if all you're doing is setting an event handler.
In general, no — you can't get the name of a particular variable or its "id" either.
If you really want to, it may be possible to do Bad Things with exceptions and stack traces to get that information… But I don't know off the top of my head how to do that.
Edit: I assume that, by “variable ID”, you mean “a unique identifier for the object referenced by that variable”, like Python's id builtin:
>>> x = {}
>>> y = z = {}
>>> (id(x), id(y), id(z))
(123, 567, 567)
I'm not 100% sure that I understand your question correctly in regards to meta-programming, but typically you would attach an event handler to the click event of the DOM element, then you can examine properties of the element within the handler.
There are a couple things in JavaScript that facilitate meta-programming: eval will let you interpret arbitrary code, so you can build a string of code and eval it. The security concerns are numerous. You can also access properties of an object by index or by name, e.g.
aVariableName.aClassFunction
is the same as
aVariableName["aClassFunction"]
Hope that helps.

Categories

Resources