I was following the example Blockly Code Generators and was able to generate Python codes. But when I run the Python code, I get an error. It seems the error is 'eval(code)' below, what should I do if I want to execute the Python code right inside the browser? Thanks for any help!
Blockly.JavaScript.addReservedWords('code');
var code = Blockly.JavaScript.workspaceToCode(workspace);
try {
eval(code);
} catch (e) {
alert(e);
}
here is the snapshot Unfortunately i dont have enough points to post the image here
Can you try this with a simple code , like - print('Hello World!')
According to the image , the issue could be with indentation , and indentation is very important in python, othewise it can cause syntax errors .
You should have also changed the code to -
Blockly.Python.addReservedWords('code');
var code = Blockly.JavaScript.workspaceToCode(workspace);
try {
eval(code);
} catch (e) {
alert(e);
}
Try to eval with a Python interp written is JS, like http://brython.info/.
as you using eval function of javascript you are actually saying to print the page as print() means to print the page in javascript.
The solution to this is there in the Blockly itself as to rn the code they call this function.
function() {
Blockly.JavaScript.INFINITE_LOOP_TRAP = 'checkTimeout();\n';
var timeouts = 0;
var checkTimeout = function() {
if (timeouts++ > 1000000) {
throw MSG['timeout'];
}
};
var code = Blockly.JavaScript.workspaceToCode(Code.workspace);
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
try {
eval(code);
} catch (e) {
alert(MSG['badCode'].replace('%1', e));
}
The above code is from code.js in demos/code/code.js line 553.
Related
I have been working on a problem for a while now which I cannot seem to resolve so I need some help! The problem is that I am writing a program in C# but I require a function from a Python file I created. This in itself is no problem:
...Usual Stuff
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace Program
{
public partial class Form1 : Form
{
Microsoft.Scripting.Hosting.ScriptEngine py;
Microsoft.Scripting.Hosting.ScriptScope s;
public Form1()
{
InitializeComponent();
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
}
private void doPython()
{
//Step 1:
//Creating a new script runtime
var ironPythonRuntime = Python.CreateRuntime();
//Step 2:
//Load the Iron Python file/script into the memory
//Should be resolve at runtime
dynamic loadIPython = ironPythonRuntime.;
//Step 3:
//Invoke the method and print the result
double n = loadIPython.add(100, 200);
numericUpDown1.Value = (decimal)n;
}
}
}
However, this requires for the file 'first.py' to be wherever the program is once compiled. So if I wanted to share my program I would have to send both the executable and the python files which is very inconvenient. One way I thought to resolve this is by adding the 'first.py' file to the resources and running from there... but I don't know how to do this or even if it is possible.
Naturally the above code will not work for this as .UseFile method takes string arguments not byte[]. Does anyone know how I may progress?
Lets start with the simplest thing that could possibly work, you've got some code that looks a little like the following:
// ...
py = Python.CreateEngine(); // allow us to run ironpython programs
s = py.CreateScope(); // you need this to get the variables
var ironPythonRuntime = Python.CreateRuntime();
var x = py.CreateScriptSourceFromFile("SomeCode.py");
x.Execute(s);
var myFoo = s.GetVariable("myFoo");
var n = (double)myFoo.add(100, 200);
// ...
and we'd like to replace the line var x = py.CreateScriptSourceFromFile(... with something else; If we could get the embedded resource as a string, we could use ScriptingEngine.CreateScriptSourceFromString().
Cribbing this fine answer, we can get something that looks a bit like this:
string pySrc;
var resourceName = "ConsoleApplication1.SomeCode.py";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName))
using (var reader = new System.IO.StreamReader(stream))
{
pySrc = reader.ReadToEnd();
}
var x = py.CreateScriptSourceFromString(pySrc);
I'm trying to spawn a child process to run a python script from Node. I have the following request that comes in:
/webcrawler?source=http://www.pygamers.com&method=BFS&nodeCount=3&depth=0&keyword=game
I have verified that my params are coming in correctly. Here is my code set up to handle the request in app.js:
app.get('/webcrawler', function(req, res){
var python = require('child_process').spawn(
'python',
["WebCrawler/Webcrawler.py"
, req.query.source
, req.query.method
, req.query.nodeCount
, req.query.depth
, req.query.keyword]
);
var output = "";
python.stdout.on('data', function(data){ output += data });
python.on('close', function(code){
if (code !== 0) {
return res.send(500, code);
}
return res.send(200, output);
});
});
I am calling my Python script, Webcrawler.py which is in the WebCrawler directory. The WebCrawler directory is in the same directory as app.js.
However, this request is giving me a 500, and I haven't been able to figure out why. It seems like I must be generating the child process incorrectly. I used this answer as a model for doing so.
It needs to be an absolute path, like /home/username/Webcrawler/webcrawler.py
Sounds like a path problem.
Also checkout python-shell package. Makes your life so much easier.
you can check this package on npm- native-python
it provides a very simple and powerful way to run python functions from node
might solve your problem.
import { runFunction } from '#guydev/native-python'
const example = async () => {
const input = [1,[1,2,3],{'foo':'bar'}]
const { error, data } = await runFunction('/path/to/file.py','hello_world', '/path/to/python', input)
// error will be null if no error occured.
if (error) {
console.log('Error: ', error)
}
else {
console.log('Success: ', data)
// prints data or null if function has no return value
}
}
python module
# module: file.py
def hello_world(a,b,c):
print( type(a), a)
# <class 'int'>, 1
print(type(b),b)
# <class 'list'>, [1,2,3]
print(type(c),c)
# <class 'dict'>, {'foo':'bar'}
I am trying to create and execute a JavaScript function with Selenium. I am doing it like this:
js_func = """
function blah(a, b, c) {
.
.
.
};
"""
self.selenium.execute_script(js_script)
self.selenium.execute_script("blah", 1,2,3)
I don't get any errors from the first one (creating the function), but the second one gives me:
WebDriverException: Message: u'blah is not defined'
Is what I'm doing valid? How I can tell if the function was successfully created? How can I see the errors (assuming there are errors)?
It's just how Selenium executes JavaScript:
The script fragment provided will be executed as the body of an anonymous function.
In effect, your code is:
(function() {
function blah(a, b, c) {
...
}
})();
(function() {
blah(1, 2, 3);
});
And due to JavaScript's scoping rules, blah doesn't exist outside of that anonymous function. You'll have to make it a global function:
window.blah = function(a, b, c) {
...
}
Or execute both scripts in the same function call.
Update 2
I upgraded from 0.6.1 to 1.0.9 which fixed the issue. It appears as thought there were two fixes in versions 0.8.7 and 0.8.8 that were needed to make this work. In 0.8.7 it does make the call to the reourceExtractor, but still errors out w/ this trace:
Error: $digest already in progress
at Error ()
at beginPhase (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8334:15)
at Object.$get.Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8136:11)
at HTMLDivElement.ngEventDirectives.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:12986:17)
at event.preventDefault (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:1992:10)
at Array.forEach (native)
at forEach (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:130:11)
at eventHandler (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:1991:5)
at HTMLDivElement.forEach.bind.events.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2067:15)
at event.preventDefault (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:1992:10)
however 0.8.8 seems to have cleared all that up. I am going to continue to poke around and see if there are any other oddities.
I don't know how I ended up with such an old version of restangular.
Update:
so tracing through the javascript
angular-resource.js::ResourceFactory
is being called the success variable is the anonymous function from
restangular.js::fetchFunction
where the responseExtractor is the function I set up in my app. So this all looks good??? in
angular-resource.js::ResourceFactory
the REST call is made and the data variable contains the correct REST response. It is falling apart here in the same function:
if (data) {
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
copy(data, value);
}
}
the error is occurring # value.push(new Resource(item)); where value is essentially the JSON rest response.
I read that angular resource requires you to define the rest resource and response and part of the definition is defining the array portions. I don't know if that is the root cause - but I thought restangular took care of that for me. Still more digging to do. Any help is -still- appreciated.
Thx
So I am learning Angular and Django simultaneously. I have used Django rest services to build a service to return some simple JSON. That part is working fine, but I cannot seem to get it hooked up with /restangular. The REST call is happening, and json is being returned - but the responseExtractor doesn't seem to be getting called. I have been fidgeting around and can't seem to put my finger on it.
Thank you in advance
adding the call stack:
TypeError: Object # has no method 'push'
at U (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:10:257)
at new Resource (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:350:9)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:407:32
at m (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:6:494)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:406:19
at h (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:78:33)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:78:266
at Object.e.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:88:347)
at Object.e.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:86:198)
at Object.e.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:88:506)
non min stack
TypeError: Object # has no method 'push'
at copy (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:593:21)
at new Resource (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:350:9)
at angular.module.factory.Resource.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:407:32)
at forEach (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:137:20)
at angular.module.factory.Resource.(anonymous function) (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js:406:19)
at deferred.promise.then.wrappedCallback (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:6846:59)
at ref.then (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:6883:26)
at Object.$get.Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8057:28)
at Object.$get.Scope.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:7922:25)
at Object.$get.Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8143:24)
looking at the code, the responseExtractor method is stored in the variable "a" which I don't see in the stack.
JSON
{
"count": 2
, "next": null
, "previous": null
, "results": [{"file": "tb.png", "caption": "dfsdffs", "id": 1}
, {"file": "tannin_tasting.jpg", "caption": "tannin tasting", "id": 2}
]
}
Javascript (edit: fixed cut paste error mentioned by sza)
angular.module('spaceJam', ['ui.bootstrap', 'restangular'])
.config(function(RestangularProvider) {
RestangularProvider.setResponseExtractor(function(response, operation) {
alert('here')
if (operation === "getList") {
var newResponse = response.results;
newResponse._resultmeta = {
"count": response.count,
"next": response.next,
"previous": response.previous
};
return newResponse;
}
return response;
});
});
var CarouselCtrl = function ($scope, Restangular) {
Restangular.all('images/?format=json').getList().then(function(images) {
alert(1)
$scope.items = images;
});
$scope.myInterval = 3000;
$scope.template = "/resources/angularViews/carousel.html"
var slides = $scope.slides = [
{'type': 'image', 'name': '/resources/img/pinot_noir_glass.jpg'}
, {'type': 'image', 'name': '/resources/img/toast1.jpg'}
, {'type': 'image', 'name': '/resources/img/vinyard1.jpg'}
, {'type': 'image', 'name': '/resources/img/tannin_tasting.jpg'}
]
}
Basically you were having that problem because Restangular was using $resource underneath. Since version 0.8.7 and 0.8.8 I ditched $resource and started using $http below as $resource was bringing a lot of problems. Once of them was the one you were facing.
If you find any other issue, please add an issue at Github.
Thanks!
See original post. Upgrade solved the problem.
I am trying to set up an autocomplete feature for Codemirror for the Python language. Unfortunately, it seems that Codemirror only includes the files necessary for Javascript key term completion.
Has anyone built Python hint file for CodeMirror similar to the JavaScript Version?
(Edit for future reference: link to similar question on CodeMirror Google Group)
I'm the original author of the Python parser for Codemirror (1 and 2). You are correct that the Python parser does not offer enough information for autocomplete. I tried to build it into the parser when Codemirror 2 came around but it proved too difficult for my JS skills at the time.
I have far more skills now but far less time. Perhaps someday I'll get back to it. Or if someone wants to take it up, I would be glad to help.
Add python-hint.js, show-hint.js, show-hint.css. Then
var editor = CodeMirror.fromTextArea(your editor instance codes here;
editor.on('inputRead', function onChange(editor, input) {
if (input.text[0] === ';' || input.text[0] === ' ' || input.text[0] === ":") {
return;
}
editor.showHint({
hint: CodeMirror.pythonHint
});
});
< script >
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: {
name: "python",
version: 3,
singleLineStringErrors: false
},
lineNumbers: true,
indentUnit: 4,
extraKeys: {
"Ctrl-Space": "autocomplete"
},
matchBrackets: true
});
CodeMirror.commands.autocomplete = function (cm) {
CodeMirror.simpleHint(cm, CodeMirror.pythonHint);
}
</script>
I start the python autocomplete with a js based on pig-hint from codemirror 3.
You can get the python-hint.js from here.
to work, you need in your html:
include simple-hint,js and python-hint.js, simple-hint.css plus codemirror.js
add this script:
<script>
CodeMirror.commands.autocomplete = function(cm) {
CodeMirror.simpleHint(cm, CodeMirror.pythonHint);
}
</script>
python-hint.js is a basic js I have created today and not reviewed in depth.
You can initialize this way also, adding extraKeys parameter to CodeMirror initialization:
CodeMirror(function(elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {
mode: "python",
lineNumbers: true,
autofocus: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});