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);
}}
Related
Error shown:
java.lang.IllegalArgumentException: wrong number of arguments: 4 expected: 2.
In my source program, I have given an array as input and array as output. I have difficulty in writing parameterized JUnit test cases. I am using JUnit4.
Here is my source code.
package BasicTesting;
import java.io.*;
import java.lang.reflect.Array;
import java.util.Scanner;
public class Swap_Array
{
public static void main(String args[])throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i;
int [] array=new int[2];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the two numbers");
for(i=0;i<2;i++) {
array[i] =sc.nextInt();
}
int [] p = swap(array);
System.out.println("after swapping first number"+" "+p[0]+" "+" and second number are"+" " +p[1]);
}
public static int[] swap(int array[]) {
int[] c=new int[2];
int i = array[0];
int j = array[1];
i=i+j;
j=i-j;
i=i-j;
c[0]=i;
c[1]=j;
return c;
}
}
Here is my Parameterized JUnit test case.
package BasicTesting;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
#RunWith(Parameterized.class)
public class Swap_Parameterized_testcase {
public Swap_Parameterized_testcase(int[] input, int[] expected) {
super();
this.input= input;
this.expected = expected;
}
Swap_Array ob=new Swap_Array();
private int input[];
private int [] expected;
#Parameters
public static Collection<Object[]> testPrime() {
return Arrays.asList(new Object[][]{{1,2,2,1},{23,44,44,23}});
}
#Test
public void Swap_test() {
assertArrayEquals(expected,ob.swap(input));
}
}
How to rewrite this JUnit Parameterized test cases into the correct one?
How can we write JUnit parameterized test cases, If we give input to swap two numbers as two numbers instead of an array?
Here is my source code, if the input is given as two numbers instead of an array.
package BasicTesting;
import java.io.*;
import java.lang.reflect.Array;
import java.util.Scanner;
public class Swap_Numbers
{
public static void main(String args[])throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i,j;
System.out.println("enter first number..");
i=Integer.parseInt(br.readLine());
System.out.println("enter second number..");
j=Integer.parseInt(br.readLine());
int[] p=swap1(i,j);
System.out.println("after swapping first number"+" "+p[0]+" "+" and second number are"+" " +p[1]);
}
public static int[] swap1(int i,int j) {
int[] c=new int[2];
i=i+j;
j=i-j;
i=i-j;
c[0]=i;
c[1]=j;
return c;
}
}
Kindly help me to rewrite JUnit parameterized test cases for both. It would be more helpful you rewrite this code.
I'd urge you to upgrade from Junit 4.x to 5.x. The way they do parameterized tests is slightly different.
The runtime tells you the offending line number, but you don't tell us in your question. That information would help a great deal.
Believe the JVM. Look at the line it cites and fix it.
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.
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.
So basically what I am trying to do is make it so every player has their own extra storage bag that they can upgrade(starting on that later), but at the moment I am stuck with this. I am making it so if the Hashmap "storage" does not contain a value, to create a new inventory and set it a value. The only problem is I cannot then use the inventory "bag" in another if statement to open it when the value is set. Here is my code :
package me.impatheimpaler.aqw;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
public class Storage implements Listener{
public me.impatheimpaler.aqw.Main plugin;
public HashMap<String, Inventory> storage = new HashMap<String, Inventory>();
public Storage(Main main) {
plugin = main;
}
#EventHandler
public void onInteract(PlayerInteractEvent e) {
if (!(e.getItem().getType() == Material.CHEST)) return;
if (!(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK)) return;
if (e.getItem().getItemMeta().hasLore() &&
e.getItem().getItemMeta().getLore().contains(ChatColor.GREEN + "A bag for extra storage.")) {
if (storage.containsKey(null) && storage.containsValue(null)) {
Inventory bag = Bukkit.getServer().createInventory(e.getPlayer(), 9, "Storage");
storage.put(e.getPlayer().getName(), bag);
}
if (storage.contains(e.getPlayer().getName(), bag)) {
//Here is the error, as I cannot use the value "bag", because it cannot be
accessed from another if statement.
}
}
}
}
You could just declare bag outside of the if statement, then set it inside of the statement:
Inventory bag;
if(storage.containsKey(null) && storage.containsValue(null)){
//code
}
So, it could look something like this:
Inventory bag;
if (storage.containsKey(null) && storage.containsValue(null)) {
bag = Bukkit.getServer().createInventory(e.getPlayer(), 9, "Storage");
storage.put(e.getPlayer().getName(), bag);
}
if (storage.contains(e.getPlayer().getName(), bag)) {
//use "bag" however you want
}
Also, instead of checking if storage.containsKey(null), to check if the player's name NOT is in the HashMap, you should use:
if(!storage.containsKey(e.getPlayer().getName()){
Doing storage.containsKey(null) will check if the map has null as a key, it won't find anything out about the player
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...