I am using the sklearn-weka-plugin and want to run the JRip classifier. When I try to run it with the python-weka-wrapper:
import weka.core.jvm as jvm
from weka.classifiers import Classifier
jvm.start()
jrip = Classifier("weka.classifiers.rules.JRip")
jvm.stop()
everything works fine, but if I try to do the same with the sklearn-weka-plugin:
import sklweka.jvm as jvm
from sklweka.classifiers import WekaEstimator
jvm.start()
jrip = WekaEstimator("weka.classifiers.rules.JRip")
jvm.stop()
I get the following error message:
Failed to get class weka.classifiers.rules.JRip
Exception in thread "Thread-0" java.lang.NoClassDefFoundError: weka.classifiers.rules.JRip
Traceback (most recent call last):
File "sklearn_weka_test.py", line 21, in <module>
jrip = WekaEstimator("weka.classifiers.rules.JRip")
File "/home/andreas/.local/lib/python3.8/site-packages/sklweka/classifiers.py", line 45, in __init__
if not is_instance_of(_jobject, "weka.classifiers.Classifier"):
File "/home/andreas/.local/lib/python3.8/site-packages/weka/core/classes.py", line 285, in is_instance_of
if is_array(obj):
File "/home/andreas/.local/lib/python3.8/site-packages/weka/core/classes.py", line 309, in is_array
cls = javabridge.call(obj, "getClass", "()Ljava/lang/Class;")
File "/home/andreas/.local/lib/python3.8/site-packages/javabridge/jutil.py", line 888, in call
fn = make_call(o, method_name, sig)
File "/home/andreas/.local/lib/python3.8/site-packages/javabridge/jutil.py", line 846, in make_call
raise JavaException(jexception)
javabridge.jutil.JavaException: weka.classifiers.rules.JRip
In both cases, you should use classname= as all parameters of these classes are optional. The difference is that the first parameter of Classifier is classname and for WekaEstimator it is the JavaBridge object. That is why it works in the first case, but fails with an Exception in the second case.
Your code should look like this:
import weka.core.jvm as jvm
from weka.classifiers import Classifier
jvm.start()
jrip = Classifier(classname="weka.classifiers.rules.JRip")
jvm.stop()
And:
import sklweka.jvm as jvm
from sklweka.classifiers import WekaEstimator
jvm.start()
jrip = WekaEstimator(classname="weka.classifiers.rules.JRip")
jvm.stop()
Related
I have a simple Java app that does an addition by passing 2 arguments when running it. Here is the code:
package test_python;
import java.util.concurrent.TimeUnit;
public class Test_python {
public int addition(int first, int second) {
return first + second;
}
public static void main(String[] args) {
Test_python a = new Test_python();
System.out.println(a.addition(Integer.parseInt(args[0]), Integer.parseInt(args[1])));
}
}
And I have a python script :
import subprocess
import sys
first_arg = subprocess.check_output([sys.argv])
second_arg = subprocess.check_output([sys.argv])
subprocess.call(['java', '-jar', 'test_python.jar ',first_arg,second_arg])
I would like to pass two arguments like 2 and 3 to the python script and the to send the arguments to the jar and return the response. I get this error when I try:
Traceback (most recent call last):
File "C:\Certificat python\start-stop.py", line 5, in <module>
first_arg = subprocess.check_output([sys.argv])
File "C:\Users\40723\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line
424, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "C:\Users\40723\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line
505, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\40723\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line
951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\40723\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line
1360, in _execute_child
args = list2cmdline(args)
File "C:\Users\40723\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line
565, in list2cmdline
for arg in map(os.fsdecode, seq):
File "C:\Users\40723\AppData\Local\Programs\Python\Python39\lib\os.py", line 822, in
fsdecode
filename = fspath(filename) # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not list
Can you please give me a solution ?
Thanks in advance
The cause of the error is because sys.argv is already a list e.g. ["script.py", "2", "3"] and you are wrapping it in another list thus making it [["script.py", "2", "3"]].
first_arg = subprocess.check_output([sys.argv])
Removing the outer list-wrapper and also removing the first item which is the script itself would remove the error.
first_arg = subprocess.check_output(sys.argv[1:])
But I doubt that is what you need, because subprocess.check_output runs the command, it doesn't get the arguments as what you are trying to do.
$ python script.py cat script.py # <cat> is a linux command that prints the file
b'#!/usr/bin/env python\n\nimport subprocess\nimport sys\n\n\nresult = subprocess.check_output(sys.argv[1:])\nprint(result)\n'
If what you want is to just get the values of the first and second argument e.g. 2 and 3 if invoked as python script.py 2 3, you can just do:
first_arg = sys.argv[1]
second_arg = sys.argv[2]
I am working on a Selenium Project where the Workspace name I was using had a space because of which I was getting following error:
Exception in thread "main" java.lang.IllegalArgumentException: C:/Users/xyz/eclipse-workspace ValveAware/TestProject/src/test/resources/features/Administration/Export.feature is not valid. Try URI[:LINE]*
at io.cucumber.core.model.FeatureWithLines.parse(FeatureWithLines.java:56)
at cucumber.runtime.RuntimeOptions.parse(RuntimeOptions.java:189)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:107)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:100)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:96)
at cucumber.runtime.Runtime$Builder.withArgs(Runtime.java:131)
at cucumber.runtime.Runtime$Builder.withArgs(Runtime.java:127)
at cucumber.api.cli.Main.run(Main.java:22)
at cucumber.api.cli.Main.main(Main.java:8)
Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 36: C:/Users/xyz/eclipse-workspace ValveAware/TestProject/src/test/resources/features/Administration/Export.feature
at java.base/java.net.URI.create(URI.java:883)
at io.cucumber.core.model.FeaturePath.parseProbableURI(FeaturePath.java:44)
at io.cucumber.core.model.FeaturePath.parse(FeaturePath.java:37)
at io.cucumber.core.model.FeatureWithLines.parseFeaturePath(FeatureWithLines.java:77)
at io.cucumber.core.model.FeatureWithLines.parse(FeatureWithLines.java:53)
... 8 more
Caused by: java.net.URISyntaxException: Illegal character in path at index 36: C:/Users/xyz/eclipse-workspace ValveAware/TestProject/src/test/resources/features/Administration/Export.feature
at java.base/java.net.URI$Parser.fail(URI.java:2915)
at java.base/java.net.URI$Parser.checkChars(URI.java:3086)
at java.base/java.net.URI$Parser.parseHierarchical(URI.java:3168)
at java.base/java.net.URI$Parser.parse(URI.java:3116)
at java.base/java.net.URI.<init>(URI.java:600)
at java.base/java.net.URI.create(URI.java:881)
... 12 more
I changed the name of the workspace and removed the space. I checked the path of the file Export.feature and the space is not there. But when I execute this file, I am still getting the same error.
Runner File:
package valveAware.port.localhost.tests;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
#CucumberOptions(
features = { "src/test/resources/features/Administration/Export.feature" },
monochrome = true,
plugin = { "pretty","html:target/Destination" },
glue = { "valveAware.port.localhost.tests" }
)
public class ValveAwareRunnerTest extends AbstractTestNGCucumberTests{
}
I created a new workspace and imported the projects, then it worked
Using Java 8, it is easy to debug a Doclet: How can I debug a Doclet in Eclipse?
But how to achieve this in Java 10 and subsequent versions? Calling
jdk.javadoc.internal.tool.Main.execute(javadocArgs);
throws an Exception:
Exception in thread "main" java.lang.IllegalAccessError: class my.BDoclet (in unnamed module #0x1f36e637) cannot access class jdk.javadoc.internal.tool.Main (in module jdk.javadoc) because module jdk.javadoc does not export jdk.javadoc.internal.tool to unnamed module #0x1f36e637
The javadocArgs is an array containing each argument as a single entry:
String[] docletArgs = new String[]{
"-doclet", LatexDoclet.class.getName(),
"-docletpath", "target/classes/",
"-sourcepath", "src/test/java/",
LatexDoclet.class.getPackageName()
};
DocumentationTool docTool = ToolProvider.getSystemDocumentationTool();
docTool.run(System.in, System.out, System.err, docletArgs);
Example based on Slaw's comment:
String[] javadocArgs = new String[] {...}
ServiceLoader<Tool> toolService = ServiceLoader.load(Tool.class);
Optional<Tool> javadocOpt = toolService.stream().map(p -> p.get()).filter(t -> t.name().equals("javadoc")).findFirst();
javadocOpt.orElseThrow().run(System.in, System.out, System.err, javadocArgs);
The same, a bit more elegantly:
//import javax.tools.*;
String[] args = new String[]{"-doclet " + MyDoclet.class.getName()};
DocumentationTool docTool = ToolProvider.getSystemDocumentationTool();
docTool.run(System.in, System.out, System.err, args);
However, it's not clear to me what the "args" should be because it doesn't work and produces:
javadoc: error - invalid flag: -doclet ...MyDoclet
I have a child java project which has groovy files added in classpath using eclipse. Parent java project triggers some functionality in child which uses Groovy library to run the scripts. So import works fine in eclipse environment with opened child project but if I run it from command line or if I close child project then I get groovy compilation error at import statement. How can I resolve this ? I want to avoid using evaluate() method.
Following is my master groovy:
package strides_business_script
abstract class Business_Script extends Script {
//some stuff
}
Following is the another groovy:
import static strides_business_script.StridesBusiness_Script.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
String Key = Part_Product_PartDetails
boolean containsData = checkIncomingMessage(Key)
if(containsData) {
def edgeKeyList = [PPR]
JSONArray partDetails = appendEdgeValueToMsg(edgeKeyList,Key,vertex,messageIterator);
//deleteMessages(Key);
JSONObject jsonObject = constructInfoWithPropertyJSON("NAME,PRODUCTTYPE,FGTYPE,UOM,ITEMCLASSIFICATIONBYMARKET");
jsonObject.put("PARTS",partDetails);
send(Product_AggPO_ProductDetails,convertJSONToString(jsonObject));
}
Edit:
My master script Business_Script.groovy resides in scripts/strides_business_script/ folder. All other scripts are in scripts/StridesComputationScripts/ folder and they import the Business_Script.groovy.
I run the application with remote debugging enabled like this:
java -cp "./lib/*:./scripts/strides_business_script/Business_Script.groovy" -Xdebug -Xrunjdwp:transport=dt_socket,address=6969,server=y -Dhibernate.cfg.xml.path=./conf/hibernate.cfg.xml -Dlog4j.configuration=file:./conf/log4j.properties com.biglabs.dataExtractor.dataDump.DataDumpDriver 7
and here I am trying to parse all computation scripts.
for (String scriptName : files) {
Script script = groovyShell.parse(new File(
SCRIPT_PLACED_AT + Constants.SLASH
+ SCRIPT_FILE_FOLDER + Constants.SLASH
+ scriptName));
scriptMping.put(scriptName, script);
}
It throws following exception while parsing using groovy shell:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/home/manoj/strides/release/strides/scripts/StridesComputationScripts/PRODUCT-script.groovy: 2: unable to resolve class strides_business_script.StridesBusiness_Script
# line 2, column 1.
import static strides_business_script.Business_Script.*;
^
/home/manoj/strides/release/strides/scripts/StridesComputationScripts/PRODUCT-script.groovy: 2: unable to resolve class strides_business_script.StridesBusiness_Script
# line 2, column 1.
import static strides_business_script.Business_Script.*;
^
2 errors
Fixed it by adding script path in comiler configuration:
CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
String path = SCRIPT_PLACED_AT;
if(!SCRIPT_PLACED_AT.endsWith("/")){
path = path+ "/";
}
compilerConfiguration.setClasspath(path);
GroovyShell groovyShell = new GroovyShell(
compilerConfiguration);
for (String scriptName : files) {
Script script = groovyShell.parse(new File(
SCRIPT_PLACED_AT + Constants.SLASH
+ SCRIPT_FILE_FOLDER + Constants.SLASH
+ scriptName));
scriptMping.put(scriptName, script);
}
So i made this little program that's supposed to tell you the java version but i got this error :
QLineEdit.setText(QString): argument 1 has unexpected type 'int'
while trying to run it
the code :
import sys
import os
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
class java(QtGui.QMainWindow):
def s(self):
g = os.system("java -version")
self.version.setText(g)
def __init__(self, parent=None):
super(java, self).__init__(parent)
self.setMinimumSize(201, 82)
self.setMaximumSize(201, 82)
self.version = QLineEdit(self)
self.version.setMinimumSize(181, 21)
self.version.setMaximumSize(181, 21)
self.version.setGeometry(QRect(10 ,10, self.width(), self.height()))
self.fetch = QPushButton(self)
self.fetch.setMinimumSize(181, 23)
self.fetch.setMaximumSize(181, 23)
self.fetch.setGeometry(QRect(10, 50, self.width(), self.height()))
self.fetch.setText("Fetch version")
self.fetch.clicked.connect(self.s)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main = java()
main.show()
sys.exit(app.exec_())
The problem is with your method s, wherein you execute the os.system call.
def s(self):
g = os.system("java -version")
self.version.setText(g)
The variable g here stores True or False, which is the output of the system call, and not the version of java
To capture the outputted version, use subprocess module, as described here