I am trying to call a constructor for a custom collection object. This custom object takes in a parameter of type Class.
In java, this is done like this:
ICollection col = new PersistentCollection(ContentX.class);
This is my first dive into rhino, and I haven't been able to figure out quite how to pass this parameter. I figured out that "class" is a reserved word and therefor not usable.
I figured that I could get the Class from Class.forName like this:
importPackage(Packages.something.collections);
importPackage(Packages.something.content4);
var col = new PersistentCollection(Class.forName(ContentX));
But it just tosses ClassNotFoundException - with the fully qualified path something.content4.ContentX! So obviously it found the class or it wouldn't have known the path to it.
Am I doing it wrong? Sadly, I'm not in any position to change the java library right now, I need to fix the data without a new deploy.
Googling for javascript class just yields DOM/CSS problems.
I think you simply need to do:
var col = new PersistentCollection(ContentX);
Or, if your class name is a string:
var col = new PersistentCollection(
java.lang.Class.forName('something.content4.ContentX'));
Related
Anyone know how to efficiently set json in groovy with variable paths?
Context: I am working with soapui, a testing tool. Some tests are candidates to be data-driven. I have alot of variables. To make something sustainable that is easily implementable in similar circumstances, I would like a Groovy script that enables me to set variables.
I would name the variables 'parent.subParent.child'.
What I found:
http://groovy-lang.org/json.html
Referencing groovy variable as part of JSON path
I did find other things, but did not record them all.
The straight-forward thing I found was evaluation. With evaluation it was possible to get the values, but not the set them.
Eval.x(jsonbuilder, 'x.content.' + path) = 'newValue'
will return an error. But like I said, no problem retrieving the values in the json this way.
What I tried:
I have got an implementation which works for one level.
I can say:
jsonbuilder.content.parent.subParent[child] = 'newValue'
This will set the value of the requested entity.
Then I tried to expand this to an undefined number of levels.
//Assuming there is a jsonbuilder initialized
def jsonString = "{"parent":{"subParent":{"child":"oldValue"}}}"
def json = new JsonSlurper().parseText(jsonString)
def jsonbuilder = new JsonBuilder(json)
def path = 'parent.subParent.child'
def listPath = path.split("\\.")
def element = jsonbuilder.content
for(int i = 0; i < listPath.size(); i++) {
element = element[listPath[i]]
}
element = 'newValue'
assert jsonbuilder.toString() == "{"parent":{"subParent":{"child":"newValue"}}}"
The issue: the value in the original json is not updated. Likely because I leave the jsonbuilder variable once I assign it to 'element' and continue with that entity.
That leaves me with two questions:
How do I get the element value in the original json?
More general: How do I update json with a variable path?
The rudimentary JSON assign function with jsonbuilder like this: jsonbuilder.content.parent.subParent.child = 'newValue' as given in one of the answers below is not what I am eyeing for. I am looking for a way to make the entire thing dynamic. I don't want to build a simple assignment, that already exists and works well. I am looking to build a machine that does the assignment for me, with the variable names parsed as the paths. Preferably within the groovy.json.* environment, but if I have to involve external libraries, so be it.
I was staring myself blind on a specific implementation of Eval. My solution was actually simple if I would have read the docs from the start.
You can find the docs for Eval here: http://docs.groovy-lang.org/2.4.7/html/api/groovy/util/Eval.html
Instead of trying to assign a value to an evaluated method/function, which is not logical now I think of if, you need to integrate everything into the evaluated expression. For what I find, you can have up to three variables you can use in you Eval function.
I only need two. I need the jsonbuilder object to be able to get the source of information. And I need to get the value to set. The path itself can be used as it exists because it is already what it needs to be with respect to the evaluation: a String.
The code:
import groovy.json.*
def jsonString = '{"parent":{"child":"oldValue"}}'
def newValue = 'newValue'
def stringPath = 'parent.child'
def json = new JsonSlurper().parseText(jsonString)
def jsonbuilder = new JsonBuilder(json)
Eval.xy(jsonbuilder, newValue, 'x.content.' + stringPath + '= y')
System.out.println(jsonbuilder.toString()=='{"parent":{"child":"newValue"}}')
System.out.println(jsonbuilder.content.parent.child == 'newValue')
By using Eval.xy(objectOne, objectTwo, StringExpression), I am telling that I am passing a string to be evaluated as an expression, in which x represents objectOne and y represents objectTwo.
The code can be viewed in an online groovy script engine here: https://groovyconsole.appspot.com/edit/5202721384693760
Small disclaimer: I can't imagine using an evaluated expression in a code base that lets variables be randomly manipulated by the outside world. This expression, if used, will sit comfortably inside the context of my SoapUI project.
Since you are willing to use library, json-path does that.
Credits to #kalle from here
Download the zip files from here
Extract the libraries and its dependencies from above zip
Copy them under SOAPUI_HOME/bin/ext directory
Restart SoapUI
Here you go:
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build()
//You need to prepend $. before the path which becomes valid jsonpath
def path = '$.parent.subParent.child'
def originalJson = """{
"parent": {
"subParent": {
"child": "oldValue"
}
}
}"""
def updatedJson = JsonPath.using(configuration).parse(originalJson).set(path, 'newValue').json()
println(updatedJson.toString())
Here you go:
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
def jsonString = """{ "parent": {
"subParent": {
"child": "oldValue"
}
}
}"""
def json = new JsonSlurper().parseText(jsonString)
def jsonbuilder = new JsonBuilder(json)
//Assign the value for child with new value
jsonbuilder.content.parent.subParent.child = 'newValue'
println jsonbuilder.toPrettyString()
You can try online Demo
I have a BDP function that looks like this.
BDP("Glen Ln Equity","NAME_CHINESE_SIMPLIFIED")
It is to update the Chinese name of a security.
I have to translate it to Java blpapi but I am not sure how.
Since this is a BDP function, I think I should use Reference Data Request but you can only specify the ticker and field mnemonic when creating a Reference Data Request. I also know I can use override but to use an override, based on my understanding, I will need a fieldID so that I can set that fieldID's value to be "NAME_CHINESE_SIMPLIFIED".
However, I am not sure what fieldID to use.
What fieldID should I use for the override?
Also, where can I find a list of fieldIDs that can set for overrides?
It should work fine with a reference data request - you don't need to override anything here:
Element security = request.getElement("securities");
security.appendValue("GLEN LN Equity");
Element field = request.getElement("fields");
field.appendValue("NAME_CHINESE_SIMPLIFIED ");
How can I call the following Scala method from Java?
def mult[A,B: ClassTag,C: ClassTag](rdd1:RDD[A], rdd2:RDD[B])(implicit multiplier: Multiplier[A,B,C]): RDD[C] =
rdd1.zip(rdd2).map(p => multiplier.multiply(p._1, p._2))
Is it possible? Eclipse isn't giving me any help from its autocomplete.
Ugh. Must you? The B and C ClassTags are added to the list of implicit parameters (before the explicit ones), so you can add appropriate ones generated with the scala.reflect.ClassTag object. But it's going to be ugly.
Something like (untested):
mult(rdd1, rdd2, scala.reflect.ClassTag.apply(B.class), scala.reflect.ClassTag.apply(C.class), myMult);
protected static void attSelection_w(Instances data) throws Exception {
AttributeSelection fs = new AttributeSelection();
WrapperSubsetEval wrapper = new WrapperSubsetEval();
wrapper.buildEvaluator(data);
wrapper.setClassifier(new RandomForest());
wrapper.setFolds(10);
wrapper.setThreshold(0.001);
fs.SelectAttributes(data);
fs.setEvaluator(wrapper);
fs.setSearch(new BestFirst());
System.out.println(fs.toResultsString());
}
Above is my code for wrapper based attribute selection using random forest + bestfirst search. However, this somehow spits out a result using cfs, like below.
Search Method:
Greedy Stepwise (forwards).
Start set: no attributes
Merit of best subset found: 0.287
Attribute Subset Evaluator (supervised, Class (nominal): 9 class):
CFS Subset Evaluator
Including locally predictive attributes
There is no other code using CFS in the whole class, and I'm pretty much stuck.. I would appreciate any help. Thanks!
You just inverted the order and get the default method, the correct order is to set the parameter first, then call the selection:
//first
fs.setEvaluator(wrapper);
fs.setSearch(new BestFirst());
//then
fs.SelectAttributes(data);
Just set class Index and add this line after creating instance data
data.setClassIndex(data.numAttributes() - 1);
I checked and it worked fine.
Should be a relatively easy question, but as I am a newbie to java, I dont know the answer!
I have the following code:
String FTSE = "http://www.bloomberg.com/quote/UKX:IND/members";
doc = Jsoup.connect(FTSE).get();
Elements trs = doc.select("tr:has(a[href='/quote/III:LN'])");
Elements values = trs.select("td.value");
link = values.get(0);
System.out.println("text : " + link.text());
However, there are red squiggly lines in eclipse under the word 'link' in the penultimate and final line, and when I hover over it, it says this- link cannot be resolved to a variable.
How do I fix this?
Cheers
You are trying to assign values.get(0) to a variable link, which, as Eclipse thinks, was not defined or defined elsewhere. There are two problems and two possible solutions:
You never defined link. Define it and assign it the type of what values.get returns:
SomeType link = values.get(0);
You defined link in another method. Since it's not in the same scope, you must define it for the global scope and then use it with this keyword:
this.link = values.get(0);
It seems that link is not defined. Try:
YourClass link = (YourClass)values.get(0);
Instead of YourClass use the class that values.get returns.