How to get solution X prolog in java - java

I use jpl libraries to connect prolog and java. In prolog, I can execute query :
?- meaning_forms([apple,is,fruit],X).
output is : X = [is_a(x1, x2), objectx(x1, apple), objectx(x2, fruit)].
But in java, I can’t see output of this query. I tried some code in java :
Variable X = new Variable("X");
Query q4 = new Query("meaning_forms", new Term[]{new Atom("apple,is,fruit"),X});
while ( q4.hasMoreElements() ) {
java.util.Hashtable solution = (Hashtable) q4.nextElement();
System.out.println( "X = " + (Term) solution.get("X"));
}
There is no output in java . Any solution to this case?

Hashtable[] solutions = q4.allSolutions();
for (int i = 0 ; i < solutions.length; ++i) {
System.out.println("X = " + solutions[i].get(X));
}
See also http://www.swi-prolog.org/packages/jpl/java_api/getting_started.html

Related

For Loop to iterate over JSON objects inside an Array

How do I get and show each and every JSON's Object's value those I have inside an Array called learning
Here is how JSON Array looks like:
"learning": [
{
"code":"2K14 - 2",
"os":"Windows - 2"
},
{
"code":"2K15 - 2",
"os":"Linux - 2"
},
{
"code":"2K16 - 2",
"os":"Mac - 2"
}
]
Code
List<Learning> learning = value.getLearning();
for(Learning m : learning) {
// I guess, here I am missing something, which is really useful
String code = m.getCode();
String os = m.getOs();
viewHolder.learning.setText("Code: "+code+" OS: "+os);
}
When I execute my program, getting this:
Code: 2k16, OS: Mac - 2
Whereas I want to get something like this:
Code: 2k14 OS: Windows - 2, Code: 2k15 OS: Linux - 2, Code: 2k16 OS: Mac - 2
Do it as, if want to show all data in single TextView:
viewHolder.learning.append("Code: "+code+" OS: "+os + ", ");
Use TextView.append instead of TextView.setText
Can you post your Retrofit interface and all the model classes related to that?
and then you will have something like this to read it.
String text = "";
List<Learning> learning = value.getLearning();
for(Learning m : learning) {
// I guess, here I am missing something, which is really useful
String code = m.getCode();
String os = m.getOs();
text = text + "Code: " + code + " OS: " + os + ", ";
}
viewHolder.learning.setText(text);
JSONArray jsonArray = jsonObj.getJSONArray("learning");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
String code = obj.getString("code");
String os = obj.getString("os");
Log.i("MyClass", "Code -> " + code);
Log.i("MyClass", OS -> " + os);
}

Translating functionality between java and python

Hi I have the following function in java which seems to work as anticipated in calculating the maximum drawdown.
The function is the following:
DecimalFormat df = new DecimalFormat("########");
double max_dd = 100;
for(double t0:returns.keySet()){
for(double t1:returns.keySet()){
if(t1>t0){
double r = returns.get(t1)/returns.get(t0)-1;
if(r<max_dd){
max_dd = r;
System.out.println(df.format(t1) +"," +df.format( t0) + "," + max_dd + "," +returns.get(t1) + "," + returns.get(t0));
}
}
}
}
I get one result here.
Then I run the following function in python:
pd below is pandas, as is common notation.
def max_dd_(ser):
max2here = pd.expanding_max(ser)
dd2here = ser - max2here
return dd2here.min()
And the result is a much different number.
The data is coming from the same source file, and is of the format: Date,Wealth (Eg: 2014-01-1,12.5)
I trust the java code due to the simplicity and transparency, but prefer python due to its conciseness.
Any pointers on what I may be missing here?
The math was different. Py function should be:
def max_dd_(ser):
max2here = pd.expanding_max(ser)
dd2here = ser / max2here - 1
return dd2here.min()

Display Stanford NER confidence score

I'm extracting named-entities from news articles with the use of Stanford NER CRFClassifier and in order to implement active learning, I would like to know what are the confidence scores of the classes for each labelled entity.
Exemple of display :
LOCATION(0.20) PERSON(0.10) ORGANIZATION(0.60) MISC(0.10)
Here is my code for extracting named-entities from a text :
AbstractSequenceClassifier<CoreLabel> classifier = CRFClassifier.getClassifierNoExceptions(classifier_path);
String annnotatedText = classifier.classifyWithInlineXML(text);
Is there a workaround to get thoses values along with the annotations ?
I've found it out by myself, in CRFClassifier's doc it is written :
Probabilities assigned by the CRF can be interrogated using either the
printProbsDocument() or getCliqueTrees() methods.
The first method is not useful since it only prints what I want on the console, but I want to be able to access this data, so I have read how this method is coded and copied a bit its behaviour like this :
List<CoreLabel> classifiedLabels = classifier.classify(sentences);
CRFCliqueTree<String> cliqueTree = classifier.getCliqueTree(classifiedLabels);
for (int i = 0; i < cliqueTree.length(); i++) {
CoreLabel wi = classifiedLabels.get(i);
for (Iterator<String> iter = classifier.classIndex.iterator(); iter.hasNext();) {
String label = iter.next();
int index = classifier.classIndex.indexOf(label);
double prob = cliqueTree.prob(i, index);
System.out.println("\t" + label + "(" + prob + ")");
}
String tag = StringUtils.getNotNullString(wi.get(CoreAnnotations.AnswerAnnotation.class));
System.out.println("Class : " + tag);
}

How can I make the numbers that I print in this code right adjusted?

How can I make the numbers that I print in this code right adjusted?
Since the numbers in the code are variables do I need to do something different than normally adjusting it?
a = 4 ;
b = 4 ;
c = 1 ;
x = 2 ;
Root = (-1*b + Math.sqrt( Math.pow(b,2) - 4*a*c)/ 2*a );
CoefficientOfXSquared = (-(b*x+c)/(Math.pow(x,2)) );
CoefficientOfX = (-(a*x+c)-c/x );
Constant = (-(a*Math.pow(x,2)+b*x) );
System.out.println("\n\n\t Given that: \n\t CoefficientOfXSquared = " +a );
System.out.println("\n\t CoefficientOfX = " +b );
System.out.println("\n\t Constant = " +c );
System.out.println("\n\t Root = " +x );
System.out.println("\n\n\t x = " + Root );
System.out.println("\n\t a = " + CoefficientOfXSquared );
System.out.println("\n\t b = " + CoefficientOfX );
System.out.println("\n\t c = " + Constant );
System.out.println("\n\n\n" );
I would appreciate it if someone could explain how to make it right adjusted.
Try using string format method to print them. Like this:
double x=1234.56;
double y=78.678;
System.out.printf("%n\t Root = %12.4f", x);
System.out.printf("%n\t Constant = %12.4f%n", y);
which gives:
Root = 1234.5600
Constant = 78.6780
I am assuming that these are doubles. Look up printf for more info.
Cliff
I think the docs are about the best for this, shows how to format numerics outputs using printf() here is also a great tutorial on formatting numbers in java
You can do this to right justify the text.
String.format("%50s", "Root = " + root);
Try String format function, format arguments provide many options to customize the printing.

How to use Rhino library to use javascript code in Java?

I am working on a GPS app and I want to convert my latitudes and longitudes into x-y coordinates based on WGS84 datum. I found this js page to do this: http://www.uwgb.edu/dutchs/usefuldata/ConvertUTMNoOZ.HTM. I also had a look at other calculators but this one is more accurate. Now if you see the source, functions to perform conversion is being provided. I googled how can I use js code in Java and found out that this library can be used to do this: http://www.mozilla.org/rhino/. I added jar to my eclipse project and ran examples from here (http://www.mozilla.org/rhino/examples.html) but an not able to figure out how can I use functions from the source code of that page.
function GeogToUTM(){
//Convert Latitude and Longitude to UTM
Declarations();
k0 = 0.9996;//scale on central meridian
b = a*(1-f);//polar axis.
//alert(a+" "+b);
//alert(1-(b/a)*(b/a));
e = Math.sqrt(1 - (b/a)*(b/a));//eccentricity
//alert(e);
//Input Geographic Coordinates
//Decimal Degree Option
latd0 = parseFloat(document.getElementById("DDLatBox0").value);
lngd0 = parseFloat(document.getElementById("DDLonBox0").value);
latd1 = Math.abs(parseFloat(document.getElementById("DLatBox0").value));
latd1 = latd1 + parseFloat(document.getElementById("MLatBox0").value)/60;
latd1 = latd1 + parseFloat(document.getElementById("SLatBox0").value)/3600;
if (parseFloat(document.getElementById("DLatBox0").value)<0){latd1=-latd1;}
lngd1 = Math.abs(parseFloat(document.getElementById("DLonBox0").value));
lngd1 = lngd1 + parseFloat(document.getElementById("MLonBox0").value)/60;
lngd1 = lngd1 + parseFloat(document.getElementById("SLonBox0").value)/3600;
if (parseFloat(document.getElementById("DLonBox0").value)<0){lngd1=-lngd1;}
lngd=lngd0;
latd=latd0;
if(isNaN(latd)){
latd = latd1;
document.getElementById("DDLatBox0").value = Math.floor(1000000*latd)/1000000;
lngd=lngd1;
document.getElementById("DDLonBox0").value = Math.floor(1000000*lngd)/1000000;
}
if(isNaN(lngd)){lngd = latd1;}
if(isNaN(latd)|| isNaN(lngd)){
alert("Non-Numeric Input Value");
}
if(latd <-90 || latd> 90){
alert("Latitude must be between -90 and 90");
}
if(lngd <-180 || lngd > 180){
alert("Latitude must be between -180 and 180");
}
xd = lngd;
yd = latd;
DDtoDMS();
//Read Input from DMS Boxes
document.getElementById("DLatBox0").value = Math.floor(ydd);
document.getElementById("MLatBox0").value = ym;
document.getElementById("SLatBox0").value = Math.floor(1000*ys)/1000;
document.getElementById("DLonBox0").value = Math.floor(xdd);
document.getElementById("MLonBox0").value = xm;
document.getElementById("SLonBox0").value = Math.floor(1000*xs)/1000;
phi = latd*drad;//Convert latitude to radians
lng = lngd*drad;//Convert longitude to radians
utmz = 1 + Math.floor((lngd+180)/6);//calculate utm zone
latz = 0;//Latitude zone: A-B S of -80, C-W -80 to +72, X 72-84, Y,Z N of 84
if (latd > -80 && latd < 72){latz = Math.floor((latd + 80)/8)+2;}
if (latd > 72 && latd < 84){latz = 21;}
if (latd > 84){latz = 23;}
zcm = 3 + 6*(utmz-1) - 180;//Central meridian of zone
//alert(utmz + " " + zcm);
//Calculate Intermediate Terms
e0 = e/Math.sqrt(1 - e*e);//Called e prime in reference
esq = (1 - (b/a)*(b/a));//e squared for use in expansions
e0sq = e*e/(1-e*e);// e0 squared - always even powers
//alert(esq+" "+e0sq)
N = a/Math.sqrt(1-Math.pow(e*Math.sin(phi),2));
//alert(1-Math.pow(e*Math.sin(phi),2));
//alert("N= "+N);
T = Math.pow(Math.tan(phi),2);
//alert("T= "+T);
C = e0sq*Math.pow(Math.cos(phi),2);
//alert("C= "+C);
A = (lngd-zcm)*drad*Math.cos(phi);
//alert("A= "+A);
//Calculate M
M = phi*(1 - esq*(1/4 + esq*(3/64 + 5*esq/256)));
M = M - Math.sin(2*phi)*(esq*(3/8 + esq*(3/32 + 45*esq/1024)));
M = M + Math.sin(4*phi)*(esq*esq*(15/256 + esq*45/1024));
M = M - Math.sin(6*phi)*(esq*esq*esq*(35/3072));
M = M*a;//Arc length along standard meridian
//alert(a*(1 - esq*(1/4 + esq*(3/64 + 5*esq/256))));
//alert(a*(esq*(3/8 + esq*(3/32 + 45*esq/1024))));
//alert(a*(esq*esq*(15/256 + esq*45/1024)));
//alert(a*esq*esq*esq*(35/3072));
//alert(M);
M0 = 0;//M0 is M for some origin latitude other than zero. Not needed for standard UTM
//alert("M ="+M);
//Calculate UTM Values
x = k0*N*A*(1 + A*A*((1-T+C)/6 + A*A*(5 - 18*T + T*T + 72*C -58*e0sq)/120));//Easting relative to CM
x=x+500000;//Easting standard
y = k0*(M - M0 + N*Math.tan(phi)*(A*A*(1/2 + A*A*((5 - T + 9*C + 4*C*C)/24 + A*A*(61 - 58*T + T*T + 600*C - 330*e0sq)/720))));//Northing from equator
yg = y + 10000000;//yg = y global, from S. Pole
if (y < 0){y = 10000000+y;}
//Output into UTM Boxes
document.getElementById("UTMzBox1").value = utmz;
document.getElementById("UTMeBox1").value = Math.round(10*(x))/10;
document.getElementById("UTMnBox1").value = Math.round(10*y)/10;
if (phi<0){document.getElementById("SHemBox").checked=true;}
//document.getElementById("UTMzBox1").value = utmz;
//document.getElementById("UTMeBox1").value = Math.round(10*(500000+x))/10;
document.getElementById("UTMLonZoneBox2").value = utmz;
document.getElementById("UTMLatZoneBox2").value = DigraphLetrsE[latz];
document.getElementById("UTMeBox2").value = Math.round(10*(x-100000*Math.floor(x/100000)))/10;
document.getElementById("UTMnBox2").value = Math.round(10*(y-100000*Math.floor(y/100000)))/10;
//Generate Digraph
MakeDigraph();
document.getElementById("UTMDgBox2").value = Digraph;
}//close Geog to UTM
///////////////////////////////////////////////////////////////////////
I know I can't use this function as is as it is embedded within HTML. But I have never worked on js so it would be easier for me if I am needed to do minimum changes to the code.
If you just want to run JavaScript and you don't particularly care about using Rhino versus the more generic Java Scripting API, please see the following blog post I wrote:
http://springinpractice.com/2012/05/13/how-to-run-javascript-from-java/
If in fact you want actual Rhino code for whatever reason, here's some sample code that uses Rhino:
https://github.com/springinpractice/sip09/blob/03/src/main/java/com/springinpractice/ch09/comment/service/impl/RichTextFilter.java
You will have to ask if you can use it first - but he says he's generally happy to give people permission to use his work.
All the calls to document.getElementById refer to inputs on the html page.
You'll have to rewrite the function so that you pass these variables to it - as you won't have access to the javascript dom when you run it.
You'll have to work out what you want it to return too, it looks like it displays calculated values across a few fields so you'll probably have to return a map of the fieldname to the calculated value - then you will be to use the results in your java program.
The script you posted also refers to these functions that are missing, so you'll have to find them too, and include them in your script:
MakeDigraph();
DDtoDMS();
Declarations();
I'd recommend that you remove the validation bit of the code with the alerts and just handle this is your java code
It's not going to be very efficient but if that doesn't matter then good luck!

Categories