JavaScript Reflection to Find Where a Function Is Defined - javascript

I'm working on a large JavaScript project where a lot of external scripts are included. How can I find where a function is defined without having to resort to searching every file on the server?
PHP, for example, has a class named "ReflectionFunction" which is able to return information about a function:
$function_name = 'array_orderby';
$function_info = new ReflectionFunction( $function_name );
echo "The $function_name function is located in: " . $function_info->getFileName() . ' on line: ' . $function_info->getStartLine() . '.';
Sample Output
The array_orderby function is located in: /var/www/mysite.com/inc/script.php on line: 49.
Is there something like that in JavaScript?

Related

adding php stops my javascript init() working

I have a file written in html and javascript. I have an init function that I used to initialise some variables in javascript. To make this happen I have the following tag in the body statement:
<body onload="init()">
and then later I have the function itself. All seems to work well.
function init() {
// initialisation stuff here
var arr = ["happy", "winter", "hot", "cold", "male", "female", "summer", "spring", "autumn"];
document.getElementById('word').innerHTML = arr[Math.floor(Math.random() * arr.length)];
flag = 0;
}
However, I now want to load some data from a file so that I can replace the arr variable in my init() function with a much longer list of words. So just below the body statement I put the following:
<?php
$words = file('data.txt');
?>
I changed the file extension from html to php so that the php script would run before the page loads. When I change the extension to php it works fine. But as soon as I add those php lines I get an error. When I look using Develops Tools it says - Uncaught Reference Error: Init not defined.
But my init function is still there. Why would adding those php lines affect the javascript init function?
EDIT
I had the following two lines in my init function
// var words = <?php echo '["' . implode('", "', $words) . '"]' ?>;
// alert(words);
I thought they were commented out. But obviously not. If I remove them the code works fine.
However, although it is evident from the run-time inspection that
var words = <?php echo '["' . implode('", "', $words) . '"]' ?>;
alert(words);
is bringing the data into the init function, somehow it is still producing an error.

How to run javascript with no filename

I am new to coding so I have a question regarding Jupyter Notebook and the use of Javascript. A snippet of my current code is as follows (trueName is defined prior to this code and pickle.dump is usually tabbed, but isn't here due to stack overflow's formatting):
%%javascript
var kernel = Jupyter.notebook.kernel;
console.log(kernel);
var command = "import pickle" + "\n" + "file_name = 'testfile'" + "\n" + "with open(file_name, 'wb') as my_file_obj:" + "\n" + "pickle.dump(trueName,my_file_obj)";
kernel.execute(command);
This works fine but for some reason when I place it into the following format:
from IPython.core.display import Javascript
Javascript("""
var kernel = Jupyter.notebook.kernel;
console.log(kernel);
var command = "import pickle" + "\n" + "file_name = 'testfile'" + "\n" + "with open(file_name, 'wb') as my_file_obj:" + "\n" + " "pickle.dump(trueName,my_file_obj)";
kernel.execute(command);""")
I obtain the following error even though the code is the same:
Javascript error adding output!
SyntaxError: Invalid or unexpected token
See your browser Javascript console for more details.
I had hoped to use the second method in order to bypass the magic command barrier in using something similar to !ipython somefile.ipy
to read the javascript, but for some reason the second method really doesn't like the var command something I discovered after much testing. I have a few questions that I would greatly appreciate if I received some feedback on:
Why does the second method provide an error due to my var command? I cannot figure out why this happens.(Is it true that I have to use 'textarea'? If so, how do I do this? I became lost when trying to do so myself: How to force a line break on a Javascript concatenated string?)
Is there a method for me to run Javascript magic when not directly in the notebook? I have tried running ipython on the code in a separate file with the .ipy ending as seen above, but it does not like running the cell magic nor the import from IPython.core.display. (This method does not work for me: How to run an IPython magic from a script (or timing a Python script))
Is there a way for me to execute Javascript code directly (not via a file) when using a function such as def run_javascript(code):? Executing a cell in Jupyter gives back the code within under the argument code, but I cannot find out how to run it. I have been looking around but the only answers I have found are about !node somefile.js and other similar filename based Javascript codes.
I would appreciate any help! I did have a few suggestions as to how to run python code as I would like to, but since IPython doesn't work with the Javascript I am at a loss (Python Tips: run a python script in terminal without the python command Execute python commands passed as strings in command line using python -c)
This should work, when you use from IPython.core.display import Javascript this is a class that when evaluated stores the data returned in scopes and once returned the data is no longer available. Use window.variable to assign in to a window object to make it available globally.
from IPython.core.display import Javascript
Javascript("""
var kernel = Jupyter.notebook.kernel;
window.variable = kernel;
var command = "list";
window.variable = command;
console.log(kernel.execute(command));""")
I got the idea from here
Understanding namespace when using Javascript from Ipython.core.display in Jupyter Notebook

How to parse javascript variable array embedded in http://up-for-grabs.net/#/?

I am trying to parse http://up-for-grabs.net/#/ to get its content in CSV file using powershell. I have written below code till now
$URL = "http://up-for-grabs.net/#/"
$HTML = Invoke-WebRequest -Uri $URL
$script_blocks = $HTML.ParsedHtml.getElementsByTagName("script") | Where{ $_.type -eq ‘text/javascript’ }
$content = ""
foreach ($script_block in $script_blocks)
{
if($script_block.innerHTML -ne $null -and `
$script_block.innerHTML.trim().StartsWith("var files"))
{
$content = $script_block.innerHTML.trim()
}
}
Looking further in the content, it seems like a variable array embedded in JavaScript whose initial lines are formatted as follows. Its array with no spaces or new lines which are my creation to improve readability.
<script type="text/javascript">
var files = {
"aspnet-razor-4":{"name":"ASP.NET Razor 4","desc":"Parser and code generator for CSHTML files used in view pages for MVC web apps.","site":"https://github.com/aspnet/Razor","tags":["Microsoft","ASP.NET","Razor","MVC"], "upforgrabs":{"name":"up-for-grabs","link":"https://github.com/aspnet/Razor/labels/up-for-grabs"}},
"fsharpdatadbpedia":{"name":"FSharp.Data.DbPedia","desc":"FSharp.Data.DbPedia - An F# type provider for DBpedia","site":"https://github.com/fsprojects/FSharp.Data.DbPedia","tags":[".NET","DbPedia","F#"],"upforgrabs":{"name":"up-for-grabs","link":"https://github.com/fsprojects/FSharp.Data.DbPedia/labels/up-for-grabs"}},
"makesharp":{"name":"Make#","desc":"Use C# scripts to automate the building process","site":"https://github.com/sapiens/MakeSharp","tags":[".Net","C#","make","build","automation","tools"],"upforgrabs":{"name":"up-for-grabs","link":"https://github.com/sapiens/MakeSharp/labels/up-for-grabs"}},
"stateprinter":{"name":"StatePrinter","desc":"Automating unittest asserts and ToString() coding.","site":"https://github.com/kbilsted/StatePrinter","tags":["TDD","Unit Testing","TDD",".NET","C#","ToString","Debugging"],"upforgrabs":{"name":"Help wanted","link":"https://github.com/kbilsted/StatePrinter/labels/Help%20wanted"}}
</script>
This immediately is followed by
var projects = new Array();
for (var fileName in files) {
projects.push(files[fileName]);
}
How can I achieve similar quick parsing in powershell without writing big code with string tokenization.
After some research, I figured out that this is a JSON content for which powershell cmdlet ConvertFrom-Json needs to be used. I do not want to copy the whole script here. Please look at this GitHub location to see how to use this cmdlet effectively. Basically, you need to remember that object returned by this cmdlet is a custom object which need to be enumerated to get various properties. Its not an array, so only foreach will work to uncover the content. A small code sample is below
$file_json = $file_string | ConvertFrom-Json
$delim = " ; "
foreach ($item in $file_json | gm)
{
$props = $file_json.$($item.Name)
if($props.MemberType) {continue}
$row = $props.name.ToString()
$row += $delim + $props.desc.ToString()
$row += $delim + $props.site.ToString()
}
Searching for this cmdlet on web will give you more details on how to deal with this conversion.

I am getting error when I am using Beanshell Sampler with script in jmeter

I am getting error when I am using Beanshell Sampler with script in jmeter as:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: //my beanshell script log.info("Example Sample"); String maVariable = vars.get( . . . '' Encountered ";" at line 8, column 22. and
WARN - jmeter.protocol.java.sampler.BeanShellSampler: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of://my beanshell script log.info("Example Sample"); String maVariable = vars.get( . . . '' Encountered ";" at line 8, column 22.
and my code is
//my beanshell script
log.info("Example Sample");
String maVariable = vars.get("VARIABLE_NAME");
if (maVariable.equals("1")
{
ResponseCode = 2*100 ;
ResponseMessage= "Okey" ;
vars.put("NAME" , "VALUE") ;
}
return "Beanshell wrote this message";
I searched for it, I think I need some plugins for this to complete. I downloaded one of it i.e. bsh-2.0b2.jar but I unable to complete my task.
I don't no where I went wrong, If anyone have any idea please share it. Thanks In advance for any help.
You are missing the ending ) on the if statement.
if (maVariable.equals("1")
should be
if (maVariable.equals("1") )
To verify I ran the test with 50 users looping 500 times on 2 servers. Here is the Load Test and the JMX File.

Run script in wkhtmltopdf process

I use wkhtmltopdf to create pdf(s) from html(s)
I have next function :
private void CreateTempPdf(string htmlPath, string pdfPathTemp)
{
var processorInfo = new System.Diagnostics.ProcessStartInfo
{
Arguments =
"--margin-top 27 \"" + htmlPath + "\" \"" + pdfPathTemp +
"\" ",
FileName = PublisherConfigurationManager.Pdf2HtmlConverter,
UseShellExecute = true
};
using (var proc = new System.Diagnostics.Process())
{
proc.StartInfo = processorInfo;
proc.Start();
proc.WaitForExit();
}
}
in which i pass paths of html file and destination file.
I want to add some js script to run, before pdf will be generated.
I add my code : --run-script <js> into Arguments after pdfPathTemp but script isn't applied to pdf. I also add it before --margin but this case also doesn't help me.
How correctly add scripts into wkhtmltopdf process?
I would simply add the script directly into the HTML page. In this case I would load the HTML from the path into a string, inject the script, then write a tempfile for the process duration.
As for why --run-script does not work, I have no idea. Have you tried it directly in the command line with a very simple script and HTML to see if a minimal example works for you?
If that is not an option, you might have to play around with different files for differnt js arguments, if you require such things.

Categories

Resources