Example of Camunda HTTP Connector to obtain array - camunda

I need to call REST-service which returns JSON like
{"listA":["A1","A2"], listB:["B1","B2","B3"]}
I want to do it using standard Camunda Service-task with http-connector
Can you give me an example of groovy|JS script for connectors Output Parameter that will than create some array variable in process instance (it further needs to be used in SubProcess collection variable)

The answer is:
import static org.camunda.spin.Spin.*;
import static org.camunda.spin.DataFormats.*;
resp = connector.getVariable("response");
org.camunda.spin.json.SpinJsonNode json = JSON(resp);
l = json.prop("List_A").elements();
ArrayList <String> ar = new ArrayList<String> ();
for (org.camunda.spin.json.SpinJsonNode n: l) {
ar.add(n.stringValue());
}
ar

Related

Load bayesian network based on BIF-file WEKA

I want to load a bayesian network that is stored in a BIF-file in WEKA to validate it against a specific test-set.
However it keeps crashing with a null-pointer because m_MissinValuesFilter is null.
How do I set this filter correctly?
My current code looks as follows:
BayesNet network = new BayesNet()
BIFReader reader = new BIFReader()
network reader.processFile(path)
Evaluation eval = new Evaluation(testData)
eval.evaluatemodel(network,testData)
Despite loading the network from a BIF XML file, you still need to call the buildClassifier method to initialize all the data structures.
Here is a minimal code example:
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.BayesNet;
import weka.classifiers.bayes.net.search.fixed.FromFile;
import weka.core.Instances;
import weka.core.converters.ConverterUtils;
public class Bif {
public static void main(String[] args) throws Exception {
// load data
Instances data = ConverterUtils.DataSource.read("/somewhere/data.arff");
data.setClassIndex(data.numAttributes() - 1);
// configure classifier
FromFile fromFile = new FromFile();
fromFile.setBIFFile("/somewhere/model.bif");
BayesNet bayesNet = new BayesNet();
bayesNet.setSearchAlgorithm(fromFile);
// build classifier to initialize data structures
// NB: this won't change the model itself, as it is fixed
bayesNet.buildClassifier(data);
// evaluate it
Evaluation eval = new Evaluation(data);
eval.evaluateModel(bayesNet, data);
System.out.println(eval.toSummaryString());
// you can output the BIF XML like this
//System.out.println(bayesNet.graph());
}
}
This approach will, however, only use the structure of the network stored in the BIF file and not the CPDs. The training process will reinitialize the CPDs.
If you also want to use the CPDs from the BIF file, you need to use this slightly hacky approach:
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.net.BIFReader;
import weka.core.Instances;
import weka.core.converters.ConverterUtils;
public class Bif {
public static void main(String[] args) throws Exception {
Instances test = ConverterUtils.DataSource.read("/somewhere/data.arff");
test.setClassIndex(test.numAttributes() - 1);
String bifFile = "/somewhere/model.bif";
BIFReader reader = new BIFReader();
// initialize internal filters etc
reader.buildClassifier(test);
// override data structures using BIF file
reader.processFile(bifFile);
// output graph to confirm correct model
//System.out.println(reader.graph());
// evaluate the model against the test set
Evaluation eval = new Evaluation(test);
eval.evaluateModel(reader, test);
System.out.println(eval.toSummaryString());
}
}

grails - how do you pass non string variables to taglib attrs map using testing with applyTemplate?

grails 3.3.9, + tag libs
I create a new taglib like this
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class JavaDateTimeTagLib {
static defaultEncodeAs = [taglib:'html']
//static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
static encodeAsForTags = [testCall: [taglib:'none']]
static namespace = "jdt" //java8 date time name space for tags
def testCall = { attrs ->
def p1 = attrs.p1
def p2 = attrs.p2
out << "p1:'$p1' with class ${p1.getClass()}"
out << "p2:'$p2' with class ${p2.getClass()}"
}
}
where i want to pass a non string variable to the attrs map.
i then setup the test like this
class JavaDateTimeTagLibSpec extends Specification implements TagLibUnitTest<JavaDateTimeTagLib> {
def setup() {
}
def cleanup() {
}
/**
* restriction params must be quoted values - esentially strings
* taglib has to take that and do any conversions in the taglib
* output by defaults is encoded html using std codec
*/
void "call displayDateTime tag "() {
given:
String result = applyTemplate('<jdt:testCall p1="p1-string" p2="$now" />' , [now:LocalDateTime.now()])
when :
println "$result "
then:
result
}
}
What i'm trying to do is pass a LocalDateTime variable to the attrs map.
if you use applyTemplate and pass p2=ldt, and test map [ldt:LocalDateTime.now()]
the test fails saying the variable must be 'quoted
[Byte array resource [test_1549319950845]:1] Attribute value must be quoted (p1="p1-string" p2=now).
if you quote the p2 variable using p2="$ldt" and test map the sname as [ldt:LocalDateTime.now()], then the test will work - However the type passed to the attrs map is GStringImpl
however reading the OCI guide oci tag lib guide
it implies on page 4 that you can pass attrs.employees as a list of domainobjects and use that in you markup
but theres no way to invoke this using the testing as everything has to be string quoted - which makes it GStringImpl
how do you pass non string variable to a taglibs attrs map from appyTemplate (.. i presume the same restiction applies in live gsp and not just the testing framework )
hah! its such a small thing
if you change the test and write this
String result = applyTemplate('<jdt:testCall p1="p1-string" p2="${now}" />' , [now:LocalDateTime.now()])
with braces round the variable key name from the map - then the actual value of the typed variable is passed into the taglib. so if you look in the attrs.p2 value it has the actual LocalDateTime instance.
now quite sure how applytemplate is working not sure, but expecting its trying to do soemthing like groovy shell evaluate the string - hence the need to use single '' like '
Hope that makes sense
blimey enough to make your head explode sometimes

Class for storing `GeoPoint` in GCP Datastore (Java)

I am trying to store a geo_point type data in datastore via GCP Java client library. I figured out how to do for a Date type data, but could not get a clue which GeoPoint class I use for this.
import com.google.datastore.v1.Entity;
import static com.google.datastore.v1.client.DatastoreHelper.makeValue;
import java.util.Date;
...
public class WriteToDatastoreFromTwitter {
private static Value dValue(Date k) {
return makeValue(k).setExcludeFromIndexes(true).build();
}
public static void main(String[] args) throws TwitterException {
final Builder builder = Entity.newBuilder().
setKey(key).
putProperties("timestamp", dValue(tweet.getCreatedAt()));
// How can I add a `geo_point` data?
I am simply not sure if I should use classes outside of the datastore package, such as this: https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/search/GeoPoint
I figured out by myself. There is a class LatLng in a dependent package com.google.type to the datastore package and I could use this to successfully store geo_point data. Here's how you initialize the object:
import com.google.type.LatLng;
...
LatLng x = LatLng.
newBuilder().
setLatitude(loc.getLatitude()).
setLongitude(loc.getLongitude()).
build();
and in my case, I stored it by doing
private static Value gValue(LatLng k) {
return makeValue(k).setExcludeFromIndexes(true).build();
}
builder.putProperties("geo_point", gValue(x));

call back (reinstantiation) of a module through another module at run time with change of parameter

I am using this module hierarchy :
Node: {udpApp[0]<->udp<->networkLayer->wlan[0]} and wlan[0]: {CNPCBeacon<->mac<->radio}
With some ini parameter for udpApp as:
I have given some initial parameter in the ini file for udpApp as :
**.host*.numUdpApps = 2
**.host*.udpApp[0].typename = "UDPBasicApp"
**.host*.udpApp[0].destAddresses = "gw1"
**.host*.udpApp[0].startTime = 1.32s
**.host*.udpApp[0].stopTime = 1.48s
But at run time I want to change the startTime and stopTime for udpAPP[0] through CNPCBeacon module.
Hence I changed CNPCBeacon.cc as:-
cModule* parentmod = getParentModule();
cModule* grantParentmod = parentmod->getParentModule();
cModule* udpmod = grantParentmod->getSubmodule("udpApp",0);
double varHoldingStartTime = udpmod->par("startTime").doubleValue();
double varGoldingStopTime = udpmod->par("stopTime").doubleValue();
varHoldingStartTime = SIMTIME_DBL(4.2);
varGoldingStopTime = SIMTIME_DBL(4.5);
udpmod->par("startTime").setDoubleValue(varHoldingStartTime);
udpmod->par("stopTime").setDoubleValue(varGoldingStopTime);
EV<<"New start and stop time is "<<udpmod->par("startTime").str()<<"\t"<<udpmod->par("stopTime").str()<<endl;`
Which successfully change the parameters. However it doesn't initiate the udpApp[0] module again. So I try to use dynamic casting of this module as:
UDPBasicApp* udpBasicMod = dynamic_cast<UDPBasicApp*>(udpmod);
sendTimer = new cMessage("sendTimer");
scheduleAt(iniSchduleTime, sendTimer);
and it resulted in following error:-
error in module (CNPCBeacon) BSoneNode.gw1.wlan[0].CNPCBeacon (id=23) at event #1496, t=4: scheduleAt() of module (UDPBasicApp)BSoneNode.gw1.udpApp[0] called in the context of module (CNPCBeacon)BSoneNode.gw1.wlan[0].CNPCBeacon: method called from the latter module lacks Enter_Method() or Enter_Method_Silent()?.
Is there also any other way to instantiate a module through other sub module.
Thanks for this help.
The solution for reinitializing a module (target module) through another module (requesting module) is creating handleParamterChange() function in target module. handleParameterChange() is used to reread the changed parameter at tun time. However it won't start scheduleAt() event to reinitialize the event for the target module. So I just added the scheduleAt() event in this function as :
void UDPBasicApp:: handleParameterChange(const char* parname)
{
if(parname)
{
if((strcmp(parname, "startTime")==0) &&
(startTime != par("startTime").doubleValue())
startTime = par("startTime").doubleValue();
if(strcmp(parname,"stopTime")==0)&&
(stopTime != par("stopTime").doubleValue())
{
stopTime = par("stopTime").doubleValue();
selfMsg->setKind(START);
scheduleAt((simtime_t)(startTime), selfMsg);
}
}
Note here that selfMsg is defined in the initialize function of UdpBasciApp.cc in INET framework.
I am a bit lost in the hierarchy and relation between your modules and sub-modules, however I think if your want to create (or re-create) a module dynamically you could use the built-in approach suggested by OMNeT++: https://omnetpp.org/doc/omnetpp/manual/usman.html#sec186
Maybe you could use the one-liner directly once you have (re-)defined the parameter values:
cModuleType *moduleType = cModuleType::get("foo.nodes.WirelessNode");
cModule *mod = moduleType->createScheduleInit("node", this);
On the other hand you error message complains about: Enter_Method() and/or Enter_Method_Silent()
These macros should be used in case that you try to call a function of a module (example X::get()) from within another module:
Y::doSmthWithXsGet()
{
x->get();
}
For this to work Enter_Method() (or Enter_Method_Silent()) has to be written in the beginning of X::get()
X::get()
{
Enter_Method();
/* rest of the code */
}
You can read Direct Method Calls section of the OMNeT++ userman to see what that means.
The weird thing is that you are getting this error for the scheduleAt() method, which is a method which belongs to the fundamental OMNeT++ class cSimpleModule. That means, in order to use this method in your class you will have to inherit from cSimpleModule in your class definition.
Maybe simply doing something like:
class MyCurrentClass: public cSimpleModule
{
/* further class definition */
};
... could solve your prob.

Playframework 1.2.4: get the results of render() as a String?

In a play framework 1.2.4 Controller, is it possible to get the contents of a template or tag as a String before output to the browser?
I want to be able to do this:
String json = renderAsString("/path/to/template.json", var1, var2);
//then use json as the body of a Play.WS request body.
The solution is based on the assumption that you are talking about PlayFramework 1.x
If you are using Groovy template engine:
Map<String, Object> args = ...
Template template = TemplateLoader.load("path/to/template.suffix");
String s = template.render(args);
And you have a shortcut way if you are using Rythm template engine:
String s = Rythm.render("path/to/template.suffix", param1, param3...);
Or you can also use named arguments:
Map<String, Object> args = ...
String s = Rythm.render("path/to/template.suffix", args);
Note the Groovy way also works for Rythm if your template file is put under app/rythm folder.
In addition to green answer.
If creating a json is what you want you would better use gson rather than building your own string with groovy templates. Gson is included in Play Framework 1.2.X.
You can find more information here. Example from Gson doc:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
//json is {"value1":1,"value2":"abc"}
You can also use Flexjson instead of gson.