I am working on a large scale project that involves giving a python script a first name and getting back a result as to what kind of gender it belongs to. My current program is written in Java and using Jython to interact with a Python script called "sex machine." It works great in most cases and I've tested it with smaller groups of users. However, when I attempt to test it with a large group of users the program gets about halfway in and then gives me the following error:
"Exception in thread "main" SyntaxError: No viable alternative to input '\\n'", ('<string>', 1, 22, "result = d.get_gender('Christinewazonek'')\n")
I am more accustomed to Java and have limited knowledge of Python so at the moment I don't know how to solve this problem. I tried to trim the string that I'm giving the get_gender method but that didn't help any. I am not sure what the numbers 1, 22 even mean.
Like I said since I'm using Jython my code would be the following:
static PythonInterpreter interp = new PythonInterpreter();
interp.exec("import sys, os.path");
interp.exec("sys.path.append('/Users/myname/Desktop/')");
interp.exec("import sexmachine.detector as gender");
interp.exec("d = gender.Detector()");
interp.exec("result = d.get_gender('"+WordUtils.capitalize(name).trim()
+"')");
PyObject gendAnswer = interp.get("result");
And this is pretty much the extent of Jython/Python interaction in my Java code. If someone sees something that's wrong or not right I would certainly appreciate if you could help me. As this is a large project it takes time to run the whole program again only to run into the same issue, so because of this I really need to fix this problem.
I don't know if it helps but this is what I did and it works for me.
public static void main(String[] args){
PythonInterpreter pI = new PythonInterpreter();
pI.exec("x = 3");
PyObject result = pI.get("x");
System.out.println(result);
}
Not sure if you sorted this out, but have an extra apostrophe on
d.get_gender('Christinewazonek'')
Just like in Java, everything you open you need to close, and in this case you opened a string containing )\n") which was not closed.
Depending on the interpreter you are using, this can be flagged easily. Perhaps you might try different interpreter.
Related
I am learning Java through an introductory course using the textbook, Java Programming 9th Edition by Joyce Farrel. The examples and exercises are written for Java 9e, however, I am using Java SE 14.
I've successfully navigated Java API and found updates as well as useful explanations as to what errors I have been encountering between the two versions and what is the best way to make corrections to get the examples and exercises to work.
However, in this case, I have been having a really hard time. I'm pretty sure it's due to the lack of experience, but I can't find anything I can understand using the Java API that has given me an idea on how to resolve this issue. Google and Stackoverflow posts have not been that much more successful as I am assuming people are using a much more streamlined method or approach.
Code with the comment on the line in question:
...
Path rafTest = Paths.get("raf.txt");
String addIn = "abc";
byte[] data = addIn.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
FileChannel fc = null;
try {
fc = (FileChannel)Files.newByteChannel(file, READ, WRITE); // Error READ and Write is ambiguous?
...
} catch (Exception e){
System.out.println("Error message: " + e);
}
...
What is the best way to go about finding an approach to figuring out what exactly is going here?
#Bradley: Found the answer by trying to rewrite my question. The compiler returned 3 specific errors dealing with StandardOpenOption. Using that and Java API, I found the solution. Thank you.
#NomadMaker: First thought was that I did not include the package correctly for newByteChannel. The second options were that the arguments needed a more specific reference.
Answer: newByteChannel(...); requires the open options argument to reference the StandardOpenOption.READ and WRITE. So that:
...newByteChannel(raf, StandardOpenOption.READ, StandardOpenOption.WRITE);
This change was implemented in Java SE 11. The program now works correctly.
I'm writing an application in Java that uses the following external library: SCPSolver (link: http://scpsolver.org/).
The library appears to be a wrapper for a c library and prints some information on the standard out. My problem is I'd like my application to have a clean output: I'm looking for a way to either
a. clear the console, which might be either a system (windows) console or eclipse's console; or
b. straight up prevent the library from printing on the output.
Regarding point a:
I've tried both using
Runtime.getRuntime().exec("cls");
and
System.out.print("\033[H\033[2J");
and neither work.
I've tried printing "\b" characters but to no avail. In all these cases, I get gibberish in the output.
Regarding point b:
I've tried redirecting System.out to a new PrintStream, but it doesn't work. That's most likely because the library is a wrapper to a c library, and the c library prints bypass java's System.out. Thus I'm not really sure this approach would work, as I have no control over what the library does. I've looked in the documentation for a way to disable the output, and haven't found anything useful yet.
A possibly useful note:
Calling
System.out.close();
before asking the solver to solve an LP problem prevents the output from being displayed. Of course, the problem then is: I have no more stream to stdout to print to. Maybe a solution could be getting another stream to the same console? Though I have no idea how to do this.
In short:
The call to lpw.solve() is what prints the undesired output:
LPWizard lpw = new LPWizard();
// ...
LPSolution solution = lpw.solve();
Current output is:
GLPK Simplex Optimizer, v4.65 4 rows, 4 columns, 8 non-zeros
0: obj = 0.000000000e+000 inf = 2.700e+001 (4)
3: obj = 1.350000000e+001 inf = 0.000e+000 (0) OPTIMAL LP SOLUTION FOUND x1: 4.0 x2: 2.5 x3: 7.0 x4: 0.0
I'd expect it to instead be none.
I want to read python dictionary string using java. Example string:
{'name': u'Shivam', 'otherInfo': [[0], [1]], 'isMale': True}
This is not a valid JSON. I want it to convert into proper JSON using java code.
well, the best way would be to pass it through a python script that reads that data and outputs valid json:
>>> json.dumps(ast.literal_eval("{'name': u'Shivam', 'otherInfo': [[0], [1]], 'isMale': True}"))
'{"name": "Shivam", "otherInfo": [[0], [1]], "isMale": true}'
so you could create a script that only contains:
import json, ast; print(json.dumps(ast.literal_eval(sys.argv[1])))
then you can make it a python oneliner like so:
python -c "import sys, ast, json ; print(json.dumps(ast.literal_eval(sys.argv[1])))" "{'name': u'Shivam', 'otherInfo': [[0], [1]], 'isMale': True}"
that you can run from your shell, meaning you can run it from within java the same way:
String PythonData = "{'name': u'Shivam', 'otherInfo': [[0], [1]], 'isMale': True}";
String[] cmd = {
"python", "-c", "import sys, ast, json ; print(json.dumps(ast.literal_eval(sys.argv[1])))",
python_data
};
Runtime.getRuntime().exec(cmd);
and as output you'll have a proper JSON string.
This solution is the most reliable way I can think of, as it's going to parse safely any python syntax without issue (as it's using the python parser to do so), without opening a window for code injection.
But I wouldn't recommend using it, because you'd be spawning a python process for each string you parse, which would be a performance killer.
As an improvement on top of that first answer, you could use some jython to run that python code in the JVM for a bit more performance.
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.eval("to_json = lambda d: json.dumps(ast.literal_eval(d))")
PyObject ToJson = interpreter.get("to_json");
PyObject result = ToJson.__call__(new PyString(PythonData));
String realResult = (String) result.__tojava__(String.class);
The above is untested (so it's likely to fail and spawn dragons 👹) and I'm pretty sure you can make it more elegant. It's loosely adapted from this answer. I'll leave up to you as an exercise to see how you can include the jython environment in your Java runtime ☺.
P.S.: Another solution would be to try and fix every pattern you can think of using a gigantic regexp or multiple ones. But even if on simpler cases that might work, I would advise against that, because regex is the wrong tool for the job, as it won't be expressive enough and you'll never be comprehensive. It's only a good way to plant a seed for a bug that'll kill you at some point in the future.
P.S.2: Whenever you need to parse code from an external source, always make sure that data is sanitized and safe. Never forget about little bobby tables
In conjunction to the other answer: it is straight forward to simply invoke that python one-liner statement to "translate" a python-dict-string into a standard JSON string.
But doing a new Process for each row in your database might turn into a performance killer quickly.
Thus there are two options that you should consider on top of that:
establish some small "python server" that keeps running; its only job is to do that translation for JVMs that can connect to it
you can look into jython. Meaning: simply enable your JVM to run python code. In other words: instead of writing your own python-dict-string parser; you simply add "python powers" to your JVM; and rely on existing components to that translation for you.
Attempting to re-write the Minecraft Launcher in jython as i have a rather basic knowledge of java but i believe im competent enough with python to undertake this task. I've been translating the decompiled classes as best as i can, but i'm encountering this SyntaxError whenever i try to append strings to my list launchParameters.
The reason why i'm puzzled as to why this is happening is because the first .append() worked for my list, but after that i get the mentioned SyntaxError thrown at me from the console.
#classmethod
def main(cls, paramArrayofString):
maxHeap = 1024
minHeap = 511
runtimeMemory = float(Runtime.getRuntime().maxMemory() / maxHeap / maxHeap)
if (runtimeMemory > minHeap):
LauncherFrame.main(paramArrayofString)
else:
try:
someString = CraftiLauncher.__class__.getProtectionDomain().getCodeSource().toURI().getPath()
launchParameters = []
if (Util.getPlatform() == "Windows"):
launchParameters.append("javaw")
else:
launchParameters.append("java")
launchParameters.append("-Xmx1024m") #This one appears to work
launchParameters.append("-Dsun.java2d.noddraw=true") #This is where i get my first error
launchParameters.append("-Dsun.java2d.d3d=false")
launchParameters.append("-Dsun.java2d.opengl=false")
launchParameters.append("-Dsun.java2d.pmoffscreen=false")
launchParameters.append("-classpath")
launchParameters.append(someString)
launchParameters.append("net.Crafti.LauncherFrame")
localProcessBuilder = ProcessBuilder(launchParameters)
localProcess = localProcessBuilder.start()
if (localProcess == None):
sys.exit()
if there's anything i need to elaborate on, please ask; if you think there's a page that might help me, feel free to link it!
Thanks in advance!
Well, i'm not entirely sure why i was getting the error, but it seems that just a simple fix of code indentation was the answer the whole time.
I didn't even change the indentation at all; i just simply dedented and indented everything again and now it works!
I am currently using an online system running in Google App Engine to enable students to practice coding in python. The system is inspired by codingbat by Nick Parlante and the public version of Beanshell running on appengine.
I would like to extend our system to support Java. In our current system, the Python doctest feature makes it very easy for instructors to type out a series of variable declarations and doctests which can then be executed against student-submitted code. It is very intuitive for the instructors which is important to ensure lots of people are writing tests.
How do I replace the following comments with Java code to eval and execute tests in Java?
String solution = “a=1;”;
solution += “b=1;”;
String problem = “self.assertEqual(a,1);”;
problem += “c=3;”;
problem += “self.assertEqual(b,2);”;
//eval the solution string
//eval the problem string possibly wrapped by additional junit or other Java code.
//results = Run all the tests
System.out.println(“Test expected received result”);
//For result in results
// print test, expected, received, result(pass/fail)
Desired output:
Test expected received result
self.assertEqual(a,1) 1 1 pass
self.assertEqual(b,2) 2 1 fail
Ideally any number of tests could be included in the problem string above and any number of Java statements could be included in the solution string in order to pass the tests included in the problem string.
To the best of my knowledge, you can't. Compiling Java code at runtime requires access to APIs that aren't available on App Engine; that's why things like BeanShell and LOTRepls don't support Java.