rJava JRI Error R is already initialized (R Call java(new Rengine in Java )) - rjava

I could call R from Java and call Java function from R successfully both.
However, when I'm trying to use rJava JRI to call Java from R, and Java code instance new REngine. It failed reports
R is already initialized
and then quit R directly.
My class:
public class testRJava {
public void testOK(){
System.out.println("test this funciton could be called OK");
}
public void callSample(){
Rengine re = Rengine.getMainEngine();
if(re == null){
re=new Rengine (new String [] {"--vanilla"}, false, null);
if (!re.waitForR())
{
System.out.println ("Cannot load R");
return;
}
}
// print a random number from uniform distribution
System.out.println (re.eval ("runif(100)").asDouble());
re.end();
}
}
then, I call the Jar from R
> b <- .jnew("testRJava")
> b$testOK()
test this funciton could be called OK
> b$
b$callSample() b$main( b$wait() b$toString() b$getClass() b$notifyAll()
b$testOK() b$wait( b$equals( b$hashCode() b$notify()
> b$callSample()
R is already initialized
[root# home]#
Any one know why? Any solution about this error ?

library(rJava)
.jinit(".")
.jengine(TRUE)
[1] "Java-Object{Thread[Thread-0,5,main]}"
b <- .jnew("testRJava")
b$callSample()

Related

Ban command not working JDA please help debuged and everything

Hello so i am making a bot in JDA and i just made a ban command but it aint banning anyone the code is
i mention the user and also put a reason and put the user id and still make no difference
package me.programmer.CodeDevelopment.Commands;
import me.programmer.CodeDevelopment.Bot;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import java.util.List;
public class Ban extends ListenerAdapter {
public void onMessageGuildReceived(List<String> args, GuildMessageReceivedEvent e){
String msg = e.getMessage().getContentRaw();
if(msg.equalsIgnoreCase(Bot.PREFIX + "ban")){
TextChannel channel = e.getChannel();
Member member = e.getMember();
List<Member> mentionedMembers = e.getMessage().getMentionedMembers();
if (mentionedMembers.isEmpty() || args.size() < 2) {
channel.sendMessage("Missing Arguments").queue();
return;
}
Member target = mentionedMembers.get(0);
String reason = String.join(" ", args.subList(1, args.size()));
if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)){
channel.sendMessage("You dont have pmerission to run this command").queue();
return;
}
target.ban(1)
.reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
}
}
}
Please help i have been stuck on this for a little while.
Like Minn mentioned, You didn't override the method from ListenerAdapter properly. The name and parameter list have to match.
Also, You're checking if the entire message is equal to {PREFIX}ban yet your ban command is structured like so {PREFIX}ban (user) so your code always stops on this line:
if(msg.equalsIgnoreCase(Bot.PREFIX + "ban"))
Because that is never true when using the command correctly.
This should work instead (I've changed the msg check to starts with from equals, I've changed the method name to the right one with the right parameters from ListenerAdapter and I've then kept your usage of args by splitting the msg string and putting that into a list):
public class Ban extends ListenerAdapter {
#Override
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String msg = e.getMessage().getContentRaw();
if (msg.startsWith(Bot.PREFIX + "ban")) {
TextChannel channel = e.getChannel();
Member member = e.getMember();
List<Member> mentionedMembers = e.getMessage().getMentionedMembers();
List<String> args = Arrays.asList(msg.split(" "));
if (mentionedMembers.isEmpty() || args.size() < 2) {
channel.sendMessage("Missing Arguments").queue();
return;
}
Member target = mentionedMembers.get(0);
String reason = String.join(" ", args.subList(1, args.size()));
if (!member.hasPermission(Permission.BAN_MEMBERS) && !member.canInteract(target)) {
channel.sendMessage("You dont have pmerission to run this command").queue();
return;
}
target.ban(1)
.reason(String.format("Ban by: %#s, with reason: %s", e.getAuthor(), reason)).queue();
}
}
}

Breaking on exception: String expected

When I run my code I get:
Breaking on exception: String expected
What I am trying to do is connect to my server using a websocket. However, it seems that no matter if my server is online or not the client still crashes.
My code:
import 'dart:html';
WebSocket serverConn;
int connectionAttempts;
TextAreaElement inputField = querySelector("#inputField");
String key;
void submitMessage(Event e) {
if (serverConn.readyState == WebSocket.OPEN) {
querySelector("#chatLog").text = inputField.value;
inputField.value = "";
}
}
void recreateConnection(Event e) {
connectionAttempts++;
if (connectionAttempts <= 5) {
inputField.value = "Connection failed, reconnecting. Attempt" + connectionAttempts.toString() + "out of 5";
serverConn = new WebSocket("ws://127.0.0.1:8887");
serverConn.onClose.listen(recreateConnection);
serverConn.onError.listen(recreateConnection);
} else {
inputField.value = "Connections ran out, please refresh site";
}
}
void connected(Event e) {
serverConn.sendString(key);
if (serverConn.readyState == WebSocket.OPEN) {
inputField.value = "CONNECTED!";
inputField.readOnly = false;
}
}
void main() {
serverConn = new WebSocket("ws://127.0.0.1:8887");
serverConn.onClose.listen(recreateConnection);
serverConn.onError.listen(recreateConnection);
serverConn.onOpen.listen(connected);
//querySelector("#inputField").onInput.listen(submitMessage);
querySelector("#sendInput").onClick.listen(submitMessage);
}
My Dart Editor says nothing about where the problem comes from nor does it give any warning until run-time.
You need to initialize int connectionAttempts; with a valid value;
connectionAttempts++; fails with an exception on null.
You also need an onMessage handler to receive messages.
serverConn.onMessage.listen((MessageEvent e) {
recreateConnection should register an onOpen handler as well.
After serverConn = new WebSocket the listener registered in main() will not work
If you register a listener where only one single event is expected you can use first instead of listen
serverConn.onOpen.first.then(connected);
According to #JAre s comment.
Try to use a hardcoded string
querySelector("#chatLog").text = 'someValue';
to ensure this is not the culprit.

ObjectSave causes java.io.UTFDataFormatException

Raised as bug with Railo https://issues.jboss.org/browse/RAILO-2698 - this question should be closed
I am currently attempting to ObjectSave() on a rather complex Struct which contains instances of some CFCs among other data using the following cfscript (this is a test script I put together to reproduce the issue)
<cfscript>
thisState = session.objBasket.getState();
writedump(thisState); // dumps the object successfully
ObjectSave(thisState); // causes java.io.UTFDataFormatException
</cfscript>
I am getting the following error java.io.UTFDataFormatException (stack trace follows). Does anyone know of a way to fix this, or is it a matter of simply trying to use the wrong tool for the job?
Railo versions the error occurs on
Railo 4.1.1.009 final (Java 1.7.0_45)
Railo 4.1.1.009 final (Java 1.7.0_17)
Railo 4.1.2.001 final (Java 1.7.0_45) (Preview release)
Railo versions the error does not occur on
Railo 4.0.4.001 final (Java 1.7.0_45)
Stack trace of the error
java.io.UTFDataFormatException at
java.io.ObjectOutputStream$BlockDataOutputStream.writeUTF(ObjectOutputStream.java:2163):2163
at
java.io.ObjectOutputStream$BlockDataOutputStream.writeUTF(ObjectOutputStream.java:2006):2006
at
java.io.ObjectOutputStream.writeUTF(ObjectOutputStream.java:868):868
at
railo.runtime.ComponentImpl.writeExternal(ComponentImpl.java:1975):1975
at
java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java:1458):1458
at
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429):1429
at
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177):1177
at
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347):347
at java.util.HashMap.writeObject(HashMap.java:1133):1133 at
sun.reflect.GeneratedMethodAccessor62.invoke(Unknown Source):-1 at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43):43
at java.lang.reflect.Method.invoke(Method.java:606):606 at
java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988):988
at
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495):1495
at
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431):1431
at
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177):1177
at
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347):347
at
railo.commons.collection.AbstractMapPro.writeExternal(AbstractMapPro.java:49):49
at
java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java:1458):1458
at
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429):1429
at
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177):1177
at
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547):1547
at
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508):1508
at
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431):1431
at
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177):1177
at
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347):347
at java.util.HashMap.writeObject(HashMap.java:1133):1133 at
sun.reflect.GeneratedMethodAccessor62.invoke(Unknown Source):-1 at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43):43
at java.lang.reflect.Method.invoke(Method.java:606):606 at
java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988):988
at
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495):1495
at
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431):1431
at
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177):1177
at
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347):347
at
railo.commons.collection.AbstractMapPro.writeExternal(AbstractMapPro.java:49):49
at
java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java:1458):1458
at
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429):1429
at
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177):1177
at
java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547):1547
at
java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508):1508
at
java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431):1431
at
java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177):1177
at
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347):347
at
railo.runtime.converter.JavaConverter.serialize(JavaConverter.java:67):67
at
railo.runtime.functions.other.ObjectSave.call(ObjectSave.java:31):31
at
railo.runtime.functions.other.ObjectSave.call(ObjectSave.java:22):22
at
mso.clientobject_cfc$cf._3(/var/www/html/www/www.simon.test/mso/ClientObject.cfc:476):476
at
mso.clientobject_cfc$cf.udfCall(/var/www/html/www/www.simon.test/mso/ClientObject.cfc):-1
at railo.runtime.type.UDFImpl.implementation(UDFImpl.java:94):94 at
railo.runtime.type.UDFImpl._call(UDFImpl.java:307):307 at
railo.runtime.type.UDFImpl.callWithNamedValues(UDFImpl.java:198):198
at
railo.runtime.type.scope.UndefinedImpl.callWithNamedValues(UndefinedImpl.java:709):709
at
railo.runtime.util.VariableUtilImpl.callFunctionWithNamedValues(VariableUtilImpl.java:738):738
at
railo.runtime.PageContextImpl.getFunctionWithNamedValues(PageContextImpl.java:1513):1513
at
mso.clientobject_cfc$cf._3(/var/www/html/www/www.simon.test/mso/ClientObject.cfc:437):437
at
mso.clientobject_cfc$cf.udfCall(/var/www/html/www/www.simon.test/mso/ClientObject.cfc):-1
at railo.runtime.type.UDFImpl.implementation(UDFImpl.java:94):94 at
railo.runtime.type.UDFImpl._call(UDFImpl.java:307):307 at
railo.runtime.type.UDFImpl.callWithNamedValues(UDFImpl.java:198):198
at railo.runtime.ComponentImpl._call(ComponentImpl.java:617):617 at
railo.runtime.ComponentImpl._call(ComponentImpl.java:499):499 at
railo.runtime.ComponentImpl.callWithNamedValues(ComponentImpl.java:1732):1732
at
railo.runtime.util.VariableUtilImpl.callFunctionWithNamedValues(VariableUtilImpl.java:738):738
at
railo.runtime.PageContextImpl.getFunctionWithNamedValues(PageContextImpl.java:1513):1513
at
mso.proxyclientobject_cfm$cf._1(/var/www/html/www/www.simon.test/mso/proxyClientObject.cfm:19):19
at
mso.proxyclientobject_cfm$cf.udfCall(/var/www/html/www/www.simon.test/mso/proxyClientObject.cfm):-1
at railo.runtime.type.UDFImpl.implementation(UDFImpl.java:94):94 at
railo.runtime.type.UDFImpl._call(UDFImpl.java:307):307 at
railo.runtime.type.UDFImpl.call(UDFImpl.java:211):211 at
railo.runtime.ComponentImpl._call(ComponentImpl.java:616):616 at
railo.runtime.ComponentImpl._call(ComponentImpl.java:499):499 at
railo.runtime.ComponentImpl.call(ComponentImpl.java:1715):1715 at
railo.runtime.util.VariableUtilImpl.callFunctionWithoutNamedValues(VariableUtilImpl.java:712):712
at
railo.runtime.PageContextImpl.getFunction(PageContextImpl.java:1503):1503
at
preparecosting_cfm$cf.call(/var/www/html/www/www.simon.test/prepareCosting.cfm:24):24
at
railo.runtime.PageContextImpl.doInclude(PageContextImpl.java:834):834
at
railo.runtime.PageContextImpl.doInclude(PageContextImpl.java:781):781
at
application_cfc$cf._1(/var/www/html/www/www.simon.test/Application.cfc:177):177
at
application_cfc$cf.udfCall(/var/www/html/www/www.simon.test/Application.cfc):-1
at railo.runtime.type.UDFImpl.implementation(UDFImpl.java:94):94 at
railo.runtime.type.UDFImpl._call(UDFImpl.java:307):307 at
railo.runtime.type.UDFImpl.call(UDFImpl.java:211):211 at
railo.runtime.ComponentImpl._call(ComponentImpl.java:616):616 at
railo.runtime.ComponentImpl._call(ComponentImpl.java:499):499 at
railo.runtime.ComponentImpl.call(ComponentImpl.java:1715):1715 at
railo.runtime.listener.ModernAppListener.call(ModernAppListener.java:388):388
at
railo.runtime.listener.ModernAppListener._onRequest(ModernAppListener.java:204):204
at
railo.runtime.listener.MixedAppListener.onRequest(MixedAppListener.java:18):18
at
railo.runtime.PageContextImpl.execute(PageContextImpl.java:2167):2167
at
railo.runtime.PageContextImpl.execute(PageContextImpl.java:2134):2134
at
railo.runtime.engine.CFMLEngineImpl.serviceCFML(CFMLEngineImpl.java:335):335
at railo.loader.servlet.CFMLServlet.service(CFMLServlet.java:29):29 at
javax.servlet.http.HttpServlet.service(HttpServlet.java:728):728 at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305):305
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210):210
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222):222
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123):123
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472):472
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171):171
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99):99
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118):118
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407):407
at
org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200):200
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589):589
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310):310
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145):1145
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615):615
at java.lang.Thread.run(Thread.java:744):744
Unit test + accompanying cfc that can be used to reproduce
javaErrorTest.cfc (Unit test)
component extends='mxunit.framework.TestCase' {
public void function trySavingLargeNestedStruct() {
// Prove that it doesn't happen with nested structures
var nestedStruct = {};
var nestInMe = nestedStruct;
// Make a big struct
var nestedStruct = {};
var v = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
for (var i in v) {
for (var j in v) {
for (var k in v) {
for (var l in v) {
nestedStruct[i][j][k][l] = {};
}
}
}
}
debug('Nested struct len = '&len(serialize(nestedStruct)));
ObjectSave(nestedStruct);
debug('Nested struct saved without error');
}
public void function triggerUTFDataFormatException() {
// Prove that it happens with objects nested deeply
var previousLength = 0;
for (var i=600;i<700;i++) {
objTest = new TestObject( levels = i );
var strSerialized = serialize(objTest);
try {
ObjectSave(objTest);
} catch (java.io.UTFDataFormatException e) {
// Expected place of java.io.UTFDataFormatException
debug('Levels = '&i-1&' has serialize() length = '&previousLength);
debug('Levels = '&i&' has serialize() length = '&Len(strSerialized));
debug(strSerialized);
debug(e);
fail('java.io.UTFDataFormatException (expected) error thrown');
} catch (any e) {
debug(e);
fail('Error thrown, not not the expected one');
}
previousLength = Len(strSerialized);
}
}
}
TestObject.cfc (Used within the failing test)
component {
public TestObject function init(
required numeric levels = 0
) {
variables.a = (arguments.levels > 0)?new TestObject( levels = arguments.levels - 1 ):{};
return this;
}
}
Look at the stack trace. It answers all your questions.
java.io.UTFDataFormatException at java.io.ObjectOutputStream$BlockDataOutputStream.writeUTF(ObjectOutputStream.java:2163):2163 at java.io.ObjectOutputStream$BlockDataOutputStream.writeUTF(ObjectOutputStream.java:2006):2006
A glance at the Javadoc shows that this exception is thrown by writeUTF() if the data to be written is longer than 65535 bytes.
railo.runtime.ComponentImpl.writeExternal(ComponentImpl.java:1975):1975
This is the code that calls writeUTF(). So it appears to be a bug in the railo.runtime.ComponentImpl class. It shouldn't be calling writeUTF() for such a long string.
The following 2 methods are what I am using in place of ObjectSave and ObjectLoad until the Railo bug is corrected. It seems to function up to a decent level of complexity.
// Replaces ObjectSave
private binary function serializeState(
required struct inState
) {
var strSerialized = serialize(arguments.inState);
return strSerialized.GetBytes();
}
// Replaces ObjectLoad
private struct function deserializeState(
required binary inState
) {
var strSerialized = ToString(arguments.inState);
var stcDeserialized = evaluate(strSerialized);
return stcDeserialized;
}

Haxe - sending enum as flags to a function

I'm just trying to convert my code from C# to Haxe NME. I use enums as flags.
[Flags]
enum State
{
StateOne = 1,
StateTwo = 2,
StateThree = 4
}
And use it
if (someObj.HasState(State.StateOne | State.StateTwo))
{
// Contains both the states. Do something now.
}
I had no idea on how to do this in Haxe NME.
Thanks.
In Haxe 3, there is haxe.EnumFlags. This uses Haxe 3 Abstract Types which basically wrap an underlying type, in this case, it uses an Int, just like you have done - but then it wraps it up in a pretty API so you don't have to worry about the details.
Here is some sample code:
import haxe.EnumFlags;
class EnumFlagTest
{
static function main()
{
var flags = new EnumFlags<State>();
flags.set(StateOne);
flags.set(StateTwo);
flags.set(StateThree);
flags.unset(StateTwo);
if (flags.has(StateOne)) trace ("State One active");
if (flags.has(StateTwo)) trace ("State Two active");
if (flags.has(StateThree)) trace ("State Three active");
if (flags.has(StateOne) && flags.has(StateTwo)) trace ("One and Two both active");
if (flags.has(StateOne) && flags.has(StateThree)) trace ("One and Three both active");
}
}
enum State
{
StateOne;
StateTwo;
StateThree;
}
All of this works is stored as a standard Int, and uses integer operators like you have done, so it should be pretty fast (no wrapping in an external object). If you want to see how it works under the box, the source code for EnumFlags can be viewed here.
If you're still on Haxe 2, then you could create an object that is really similar, but of course, it has to create an object as well as the integer, so if you're doing thousands (millions?) of them then you might get a slow down. The equivalent code, that should work with Haxe 2 (though I haven't checked):
class MyEnumFlags<T:EnumValue>
{
var i:Int;
public function new(?i=0)
{
this.i = i;
}
public inline function has( v : T ) : Bool {
return i & (1 << Type.enumIndex(v)) != 0;
}
public inline function set( v : T ) : Void {
i |= 1 << Type.enumIndex(v);
}
public inline function unset( v : T ) : Void {
i &= 0xFFFFFFF - (1 << Type.enumIndex(v));
}
public inline static function ofInt<T:EnumValue>( i : Int ) : MyEnumFlags<T> {
return new MyEnumFlags<T>(i);
}
public inline function toInt() : Int {
return i;
}
}
I've managed to find it. I had trouble using enums but I had been successful using constants. This is the simple test file I used.
package ;
class FlagsTest
{
static inline var FLG_1:Int = 1;
static inline var FLG_2:Int = 2;
public static function main() : Void
{
var flag:Int = FLG_1;
if (hasFlag(flag, FLG_1))
{
trace ("Test 1 passed");
}
flag |= FLG_2;
if (hasFlag(flag, FLG_2))
{
trace ("Test 2 passed");
}
}
public static function hasFlag( flags:Int, flag:Int ) : Bool
{
return ((flags & flag) == flag) ? true : false;
}
}
Output:
FlagsTest.hx line 14: Test 1 passed
FlagsTest.hx line 19: Test 2 passed

antlr - C target : how to use vector

I am using antlr v3.4 C target, here is how I add the data into a vector:
options
{
language = 'C';
}
scope Common_Param_Vec {
pANTLR3_VECTOR common_params;
}
bus
#init
{
printf("In bus init");
$Common_Param_Vec::common_params = antlr3VectorNew(10);
printf("In bus init 2");
$Common_Param_Vec::common_params->factoryMade = false;
}
: common_param+
EOF
;
The program crashes at the line "$Common_Param_Vec::common_params = antlr3VectorNew(10);", the statement is so simple, I am not sure what could be wrong.
Change to pointer ..
pANTLR3_VECTOR *common_params;

Resources