Using OpenCPU to access custom R function - javascript

I have an R code which loads the RandomForest model, I am looking to create a function which
load(model)
randomforest_func = function(data)
{
data$pred = predict(model,data,type="prob")
output = data.frame(data$customerid,data$pred[,2])
return(output)
}
I need to make this function enabled in webserver, where an external application feeds data and retrieves the output.
The problem is, the model needs to be preloaded and cannot load into R env for each request.
The function needs to support parallel connections.
I tried installing opencpu in R.
The above code should be running in R and available at
http://localhost:1234/ocpu/
I now made changes to the opencpu.js to point to this URL and used the function in jquery to below. ocpu.r_fun_call("randomforest_func",parameters)
However this is seems to be not working..
ocpu.r_fun_call does not seem to be accessing the R script.
My question is how to correctly configure the opencpu to be able access the randomforest_func

The above code should be running in R and available at
http://localhost:1234/ocpu/
No. You need to create a package in which you put your custom functions. If the package is called foo, then the app will be available at
http://localhost:xxxx/ocpu/library/foo/www
(where xxxx is a random value for the port, given when you run opencpu$browse()).
Also, you have to use ocpu.call, not ocpu.r_fun_call.

This should help with deploying it as an app, making it easier for any external application to consume the services.
This should help with including the model.

Related

How to use the npm module gs1-barcode-parser?

I want to extract the price value from the GS1 data martix QR code value using Nodejs.
Using the module
npm i gs1-barcode-parser
Tried the below throwing "parseBarcode" is not a function
const { parseBarcode } = require('gs1-barcode-parser');
let barcode = '\u001d01093393871222863922001405\u001d1522030631030006691095751410';
console.log(parseBarcode(barcode));
I would use the modded module gs1-barcode-parser-mod2
const parser = require("gs1-barcode-parser-mod2")
let barcode = ']C101040123456789011715012910ABC1233932978471131030005253922471142127649716';
console.log(parser.parseBarcode(barcode));
Unfortunately your barcode seems to be invalid. You will need to decode from UTF-8 as that would result in ∞01093393871222863922001405∞1522030631030006691095751410 even then your barcode seems to have a missing prefix, called an Application Identifier or for short, AI (]xxxxx..).
A valid barcode example is given in the code snippet above.
More info about application identifiers
So your trying to import a module to a CJS environment, but the module is written to resolve as a front end JavaScript Module.
Fortunatly the package contains a single source file, with a single IIFE function.
THIS WILL MAKE IT AN EASY FIX!
Please note though, it is only one file & one function, but the file, and the function are really big for being a single file & a single function, so big, that it wouldn't be impracticable to add them as a snippet in a Stack Overflow answer, consequently; I have created a repository, and added the source code, that works as a solution for this problem, to the repository. I have outlined the changes that one needs to make to the module, to get it to work on the backend (in the Node REPL).
The files I added to my REPO should work for your current needs though. Continue Reading
To Convert The Module you Need to do the Following...
What you need to do is convert the package single source file into a Node module, which is very easy. The file is far to long to add to a Stack Overflow answer. So what I have done, is I have added the file into a public GitHub repository located HERE.
Go to the link to the file I rewrote
The file is a module conversion of this file.
Look at both files so you can see how I made the change.
In a nutshell, the author of the module wrote it using whats called an
IIFE: Immediately Invoked Function Execution
Its a type of function that is invoked immediately. The purpose of the function is to invoke at the very start of a script being loaded. IFFE's load before anything else, which is why he was using it to load his frontend module.
 
The Entire Module is One function, and the whole thing is wrapped like the example below:
(function (){
// Function Logic Here.
})();
Basically, what I did, is I unwrapped it, and appended a module.export.BarcodeParser assignment to the function.
To reiterate: Go Get the new File (or technically its written as a CJS module) from the Repo I Created
At This Point, Just Follow the Steps Below.
Create a new Node.js project, and make sure you execute npm init to generate a properly formatted package.json file.
Test the converted module: To test the file w/ the changes JayD3V implemented: Create a file in the same directory as the barcode parser, and add the following script to it.
const BarCodeParser = require('./BarcodeParser.js');
let barcode = ']C101040123456789011715012910ABC123�39329784711�310300052539224711�42127649716';
console.log(BarCodeParser.parseBarcode(barcode));
Then execute the file using the node command.
The README.md document in the repository has much of the information I added here in it.
Here is what it looked like when I ran it:
you're using it on server-side (backend)
https://www.npmjs.com/package/gs1-barcode-parser?msclkid=bb2e3c05cf5111ecabd6ce6b8aeb965a
as its documentation says it is a library
it also says that in order to use gs1-barcode-parser you have to add it in your application (on client side / frontend) as below:
<script src="./src/BarcodeParser.js"></script>
then you can use single function provided by it (parseBarcode) as follow :
try {
var barcode = document.getElementById("barcode").value,
answer = parseBarcode(barcode);
// do something ...
} catch (e) {
alert(e);
}

Execute R code on server via node

I made a website where I can write code into a textfield and I want to send this code to my nodes.js server and call R, which is installed on my server, and make it process the written R code.
What I have trouble with is, how can I start R on my server and input code into it via Javascript?
The security aspects are not relevant for this because it will never go live and will always stay localhost.
Any ideas on how to approach this problem?
If you use an R web framework, you can then use the eval function to run the contents of the text box as code.
Obviously, this is very risky, but you've said you only want this to run locally.
You could use other languages with an exec function to spawn a child process. Write the code to file, compile with exec, then run with the exec function.
In node you could use a child process to achieve this
https://nodejs.org/api/child_process.html
In PHP you could use exec to the same end
http://php.net/manual/en/function.exec.php
All of these options carry the same risk.
If you want to safely execute R code on the server, you could implement an RPC mechanism, a simple one would consist of the name of the command and the parameters to be passed. This way, you can effectively whitelist what is allowed to execute, but it does mean you can't excecute arbitrary R code.

How can I access functions defined in Google Script Editor outside of it?

If I have a function written in Google Spreadsheets script editor that retrieves the data in the spreadsheet in JSON format, how can I access that function outside of the script editor in my own code? I want to access that JSON and manipulate it in my own code. Is there a way to do that using the Spreadsheets API? I format it in a specific way inside script editor so I can't just use the json-in-script provided. In the call (http://spreadsheets.google.com/feeds/feed/key/worksheet/public/basic?alt=json-in-script&callback=myFunc) there's a callback function for myFunc. Can I use the function I defined in the script editor to replace myFunc?
Following your comment that brings some details on your use case, there is a Google-Apps-Script feature specially designed to give access to some functions you wrote from within another script : is is called libraries and is fully described in the documentation.
EDIT, following 2cond comment:
Calling a GS function from a javascript (or any other language) script that is not a Google Script (GS) is not possible if you consider using it as a function...
but
what you can eventually do - depending on the data this function must handle - is to deploy a script as a webApp running as a service and call this service from your external app using the equivalent of an urlFetch (that's the service doing that in GS).
The service will have an url to which you can add parameters and it will return a result that you can use in your local app.
Of course this workflow has a few limitations and might quickly become complex but in many cases it is fully workable.
Note that the url you will have to use in the "versioned" one ending with .exec (Not sure this word is correct but I mean the published url that corresponds to a version of your script and not the ".dev" one that one can use to test a script in GS).
You'll find details about that in the documentation and on many other ressources, including SO. The url is typically something like this :
https://script.google.com/macros/s/AKfycbyw-2WtmF7wsd__________azjImbMWm5YrxB8/exec?someParameter=someValue&otherParam=otherVal // etc...

How to combine node.js modules/source into one .js file, to execute inside node

I have a need where I need to execute node code/modules in a node app (in a sandbox) with vm.createScript / script.runInNewContext. The host node app runs on heroku, so there is no local filesystem to speak of. I am able to download and run code that has no outside dependencies just fine, however the requirement is to be able to include other node modules as well. (as a build/packaging step would be ideal)
There are many existing solutions (browserify is one I've spent the most time with) which get close... but they inevitably generate a single blob of code (yeah!), meant to execute in a browser (boo!). Browserify for example generates dependencies on window., etc.
Does anyone know of a tool that will either read a package.json dependencies{} (or look at all require()'s in the source) and generate a single monolithic blob suitable for node's runInNewContext?
I don't think the solution you're looking for is the right solution. Basically you want to grab a bunch of require('lib')'s, mush them together into a single Javascript context, serialize that context into source code, then pass that serialized form into the runInNewContext function to deserialize and rebuild into a Javascript context, then deserialize your custom, sandboxed code, and finally run the whole thing.
Wouldn't it make much more sense to just create a context Object that includes the needed require('lib')'s and pass that object directly into your VM? Based on code from the documentation:
var vm = require('vm'),
initSandbox = {
async: require('async'),
http: require('http')
},
context = vm.createContext(initSandbox);
vm.runInContext("async.forEach([0, 1, 2], function(element) { console.log(element); });", context);
Now you have the required libraries accessible via the context without going through a costly serialization/deserialization process.

JavaScript Glib.spawn_async stdout file descriptor

I want to spawn a process using spawn_async in the GLib bindings in javascript in a gnome3 shell-extension.
I need something like the "standard_output=True" parameter in the python doc http://developer.gnome.org/pygobject/stable/glib-functions.html which, when enabled, returns a filedescriptor to stdout of the process. The python API and C API differ heavily in this point.
Unfortunately, I cannot find any precise documentation of the JS API to GTK anywhere, the official page doesn't even list it though the shell is written in js to big parts...
The background of my question is that I call a python script doing serial communication, since I saw no other way to let JS get its data from such a script but through spawning a process.
Do you have any guess how to get the stdout of a process started like this?
The pygobject documentation you referenced is for the static libraries. Since Seed works through GObject introspection, you're safer trusting the C documentation. (Seed is the GObject introspecting Java Script library)
Perhaps you can roll your own function that does what you want in C and expose it to Seed: http://developer.gnome.org/seed/stable/seed-Native-Functions.html
This page includes info about http://developer.gnome.org/seed/3.0/seed-Modules.html embedding/utilizing your "c-module" in the javascript. An example taken from the page:
hello = imports.hello;
hello.say_hello_to("Tim");

Categories