In my hard drive I have follow source:
package DAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CountDownLatch;
public abstract class A {
public class A4{
public String teste4(int i){
return (new String("teste"));
}
}
public class A3{
public String teste3(int i){
return (new String("teste"));
}
public A4 teste33(int i){
return (new A4());
}
}
public class A2{
public A3 teste2(int i){
return (new A3());
}
}
public class A1{
public A2 teste1(int i){
return (new A2());
}
}
public int[] toIntArray(List<Integer> list) {
A1 q=new A1();
Integer t=q.teste1(
(new A1()).
teste1(0).
teste2(0).
teste33(0).
teste4(0).
length() ).
teste2(0).
teste3(0).
length();
}
}
Note that in this file (A.java) we have many blank lines and one command not necessarily was written in the same line, in others words, it's maybe spread in many lines (See last line of method "toIntArray").
When I parse this source code with AST, the "toString" of "CompilationUnit"show the follow struct (AST Struct):
package DAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CountDownLatch;
public abstract class A {
public class A4 {
public String teste4( int i){
return (new String("teste"));
}
}
public class A3 {
public String teste3( int i){
return (new String("teste"));
}
public A4 teste33( int i){
return (new A4());
}
}
public class A2 {
public A3 teste2( int i){
return (new A3());
}
}
public class A1 {
public A2 teste1( int i){
return (new A2());
}
}
public int[] toIntArray( List<Integer> list){
A1 q=new A1();
Integer t=q.teste1((new A1()).teste1(0).teste2(0).teste33(0).teste4(0).length()).teste2(0).teste3(0).length();
}
}
Note that in this case, all blank lines was removed and the command "Integer t=q.teste1...." was write in the same line. It's fine to me. Thus, in visit "MethodInvocation", I want to get line number of these invocations. To do this, I make follow source in my astVisitors:
public boolean visit(final CompilationUnit node) {
this.CompilationUnit=node;
}
public boolean visit(final MethodInvocation node) {
Integer LineInFile=this.CompilationUnit.getLineNumber(node.getStartPosition());
}
But the command "getLineNumber" return Line Number in source file in my hard drive, not in AST Struct. In this case, to the line "q.teste1((new.....", the command "getLineNumber" return the lines 44 and 45, but want that this return only the line 44.
So, How get de line number in "AST Struct"?
The CompilationUnit.toString method is just doing a rough format of the internal AST using the NaiveASTFlattener class.
The actual internal structure of the AST is just a large number of class instances of things like Block, Comment, Statement, ... As such the AST itself does not have line numbers. The only line numbers the AST knows about are the lines in the original source code.
We may start by expanding AST to "abstract syntax tree", which emphasizes that we have no (direct) connection to the source level (=concrete) syntax. You may call it a "model", which captures the semantically relevant aspects, while omitting accidental details like white space. A language could even rename its keywords without any changes to the abstract syntax etc.
It's a convenience for users, that a CompilationUnit additionally stores the positions of line ends, so it can map an AST node back to its original location in the source code.
Related
I am trying to add sentiment analysis program to Spark pipeline. When doing it, I have class which extends org.apache.spark.ml.PredictionModel. When extending this PredictionModel class, I have to override predict() method which predicts the label for given feature. But, I get either 0 or 1 all the time when I execute this code.For example, if there are 10 movie reviews, five are negative reviews and other five are negative, it classifies all reviews as negative. I have attached the code below.
import org.apache.spark.ml.PredictionModel;
import org.apache.spark.ml.param.ParamMap;
import org.apache.spark.mllib.linalg.DenseVector;
import org.apache.spark.mllib.linalg.Vector;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import java.io.*;
//Model produced by a ProbabilisticClassifier
public class MovieReviewClassifierModel extends PredictionModel<Object, MovieReviewClassifierModel> implements Serializable{
private static final long serialVersionUID = 1L;
private MultiLayerNetwork net;
MovieReviewClassifierModel (MultiLayerNetwork net) throws Exception {
this.net=net;
}
#Override
public MovieReviewClassifierModel copy(ParamMap args0) {
return null;
}
#Override
public String uid() {
return "MovieReviewClassifierModel";
}
public double raw2prediction(Vector rawPrediction) {//Given a vector of raw predictions, select the predicted label
return rawPrediction.toArray()[0];
}
#Override
public double predict(Object o) {
int prediction=0;
DenseVector v=(DenseVector)o;
double[] a=v.toArray();
INDArray arr=Nd4j.create(a);
INDArray array= net.output(arr,false);
DataBuffer ob = array.data();
double[] d=ob.asDouble();
double zeroProbability=d[0];
double oneProbability=d[1];
if (zeroProbability > oneProbability) {
prediction=0;
}
else{
prediction=1;
}
return prediction;
}
}
Can you give me reasons for the wrong predictions?
In public double predict(Object o) you have a following if statement:
if (zeroProbability > oneProbability) {
prediction=0;
}
else{
prediction=1;
}
which causes the return of 0 or 1. Change this method in order to have some other prediction values.
I have a function in R which returns a data frame of different data types.
I am calling the R function from java.
But I am not getting how to call a R function which will return a data frame.
I use the below code to return an array of string.
What to do for a data frame.
String[] output_f1= c.eval("fun1(x)").asStrings();
package java_r_dataframe;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPGenericVector;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.RList;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class mymainclass {
public static void main(String[] args) throws RserveException, REXPMismatchException {
RConnection c = new RConnection();
c.eval("source(\"/home/Jayshree/Desktop/return_data2.R\")");
RList a = c.eval("return_dataframe_2()").asList();
REXPGenericVector v = new REXPGenericVector(a);
c.eval("source(\"/home/Jayshree/Desktop/return_data2.R\")");
c.assign("x", v);
String b = c.eval("return_dataframe_3(x)").asString();
System.out.println(b);
}}
I am trying to eliminate all the memory allocation during gameplay on my game and I have stuck to something strange that I never saw in the past, for some reason the use of instanceof is doing memory allocation on android, why is that?
This is the full code of OrangeFollower.java:
package enemies;
import game.ConcreteBodySystem;
import game.Tags;
import main.MainGame;
import player.Player;
import tools.Director;
import tools.FastMath;
import tools.Vector;
import tools.gColor;
import worldsystem.BlockCollitionSystem;
import worldsystem.Entity;
import worldsystem.IntervalSystem;
import worldsystem.SoundSystem;
import worldsystem.SpriteSystem;
import worldsystem.gWorld;
import com.badlogic.gdx.Gdx;
public class OrangeFollower extends Enemy {
public static int TAG=gWorld.getNextTag();
public OrangeFollower(final gWorld world) {
super(world);
this.tag =TAG;
initScale(0.8f,0.8f);
initColor(1,0.6f,0, 1);
initColScale(0.4f, 0.4f);
initSpeed(0.018f);
setGroups(Tags.GROUP_CONCRETE_ENEMIES,Tags.GROUP_DESTRACTABLE,Tags.GROUP_ENEMIE,Tags.GROUP_GREEN_ENEMIES,Tags.GROUP_MOVING);
SpriteSystem sm=(SpriteSystem) addSystem(new SpriteSystem(this, "sprites/sprites2.png",896,256,1,128,128,pos,scale,rotation,new gColor(1,1,1,1)));
addSystem(new ConcreteBodySystem(this));
addSystem(new EnemieSystem(this,2,20,false,true,false,false,Tags.GROUP_GREEN_ENEMIES){{multis=2;}});
addSystem(new BlockCollitionSystem(this,256,true){
#Override
public void colliding(Entity e) {
super.colliding(e);
if(e instanceof Generator)return;
Vector.vector.set(e.pos.x-pos.x, e.pos.y-pos.y);
float length = FastMath.sqrtBlazingFast(Vector.vector.x*Vector.vector.x + Vector.vector.y*Vector.vector.y);
if (length != 0) {
Vector.vector.x = Vector.vector.x / length;
Vector.vector.y = Vector.vector.y / length;
vel.x-=Vector.vector.x;
vel.y-=Vector.vector.y;
}
}
});
}
#Override
public void init() {
super.init();
speed=realSpeed;
}
#Override
public void update() {
super.update();
pos.x += (vel.x * speed) * Director.delta;
pos.y += (vel.y * speed) * Director.delta;
}
}
The class is initialized for the first time.
An inner class is not necessarily initialized when the outer class is. Again the java reference says: first use.
Memory allocation not only happens with new at the object instantiations, but also at the ClassLoaders.
What happens on Android is yet another affair, but fortunately Google still keeps close to processing model of the official JVMs.
As extracted from comments by #VinceEmigh, #SteveL, #fge.
From what i read on the Net: PDG or SDG can give me a tree of dependecies i tried with a simple exemple but i have no result
what i did :
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.objectweb.asm.tree.analysis.AnalyzerException;
import com.graph.element.Node;
import com.graph.internal.NodeNotFoundException;
import com.graph.sdg.SystemDependenceGraph;;
public class A {
public static void main(String[] args) throws FileNotFoundException, IOException, AnalyzerException, NodeNotFoundException {
SystemDependenceGraph lvSystemDependenceGraph
=new SystemDependenceGraph("C:\\Users\\amina\\workspace\\SDG\\fact","C:\\Users\\amina\\workspace\\SDG\\fact\\bin\\Fact.class");
Iterator<Node> lvIterator =lvSystemDependenceGraph.controlDependenceBFSIterator();
while (lvIterator.hasNext()) {
Node lvNode = lvIterator.next();
}
}
}
class fact :
public class Fact {
public static void main(String[] args) {
int f;
int n;
n=4;
f=1;
while(n!=0){
f=f*n;
n=n-1;
}
System.out.println("f= "+f+" n= "+n);
}
}
when i run class A there is no result
SDG is a java library for analyzing java code. It processes the java sources/byte code, converts into a graph. If you iterate with either BFS or DFS, it gives you series of instruction(code) including the callee method instructions.
In the above example, Class A is iterating over the instructions. Every Node is a instruction there. After retrieving node, you are not printing it so there is no output for the above class.
If you add below line, then it works.
System.out.println("Instruction is " + node.getName());
There are other methods in the Node class like sourceline(getLine()), source is a caller or not (getCaller), what is the instruction type (getType()) etc...
//Example 1:
package com.practice;
import java.util.ArrayList;
public class Testing1{
public Testing1()
{
super();
}
public ArrayList getFruits()
{
Arraylist <fruits> = new ArrayList <fruits>();
fruits.add("Orange");
fruits.add("Apple");
fruits.add("grape");
return fruits;
}
}
//Example 2:
package com.practice;
import java.util.ArrayList;
import java.util.List;
public class Testing1{
public Testing1()
{
super();
}
public List getFruits()
{
List <fruits> = new ArrayList<fruits>();
fruits.add("Orange");
fruits.add("Apple");
fruits.add("grape");
return fruits;
}
}
//I made typos on my original code
//contain mycontain; should have been a package name. I corrected that as //well.
//Corrected import java.util.Array.List; to import java.util.Array.List;
//I tried adding a string after List and ArrayList and still does not work //well
//I still don't understand.
//No, this is not a school assignment
//Maybe some can explain which one is correct or the two examples or both //need work? Thank you.
//
All programs need a main method. So no.