Is there a way to disable SCPSolver's output? - java

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.

Related

Jython: "no viable alternative at input" when i try to append to list of strings

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!

Unexpected results from Metaphone algorithm

I am using phonetic matching for different words in Java. i used Soundex but its too crude. i switched to Metaphone and realized it was better. However, when i rigorously tested it. i found weird behaviour. i was to ask whether thats the way metaphone works or am i using it in wrong way. In following example its works fine:-
Metaphone meta = new Metaphone();
if (meta.isMetaphoneEqual("cricket","criket")) System.out.prinlnt("Match 1");
if (meta.isMetaphoneEqual("cricket","criketgame")) System.out.prinlnt("Match 2");
This would Print
Match 1
Mathc 2
Now "cricket" does sound like "criket" but how come "cricket" and "criketgame" are the same. If some one would explain this. it would be of great help.
Your usage is slightly incorrect. A quick investigation of the encoded strings and default maximum code length shows that it is 4, which truncates the end of the longer "criketgame":
System.out.println(meta.getMaxCodeLen());
System.out.println(meta.encode("cricket"));
System.out.println(meta.encode("criket"));
System.out.println(meta.encode("criketgame"));
Output (note "criketgame" is truncated from "KRKTKM" to "KRKT", which matches "cricket"):
4
KRKT
KRKT
KRKT
Solution: Set the maximum code length to something appropriate for your application and the expected input. For example:
meta.setMaxCodeLen(8);
System.out.println(meta.encode("cricket"));
System.out.println(meta.encode("criket"));
System.out.println(meta.encode("criketgame"));
Now outputs:
KRKT
KRKT
KRKTKM
And now your original test gives the expected results:
Metaphone meta = new Metaphone();
meta.setMaxCodeLen(8);
System.out.println(meta.isMetaphoneEqual("cricket","criket"));
System.out.println(meta.isMetaphoneEqual("cricket","criketgame"));
Printing:
true
false
As an aside, you may also want to experiment with DoubleMetaphone, which is an improved version of the algorithm.
By the way, note the caveat from the documentation regarding thread-safety:
The instance field maxCodeLen is mutable but is not volatile, and accesses are not synchronized. If an instance of the class is shared between threads, the caller needs to ensure that suitable synchronization is used to ensure safe publication of the value between threads, and must not invoke setMaxCodeLen(int) after initial setup.

Compare Code Submissions with Previous Submissions?

Users submit code (mainly java) on my site to solve simple programming challenges, but sending the code to a server to compile and execute it can sometimes take more than 10 seconds.
To speed up this process, I plan to first check the submissions database to see if equivalent code has been submitted before. I realize this will cause Random methods to always return the same result, but that doesn't matter much. Is there any other potential problem that could be caused by not running the code?
To find matches, I remove comments and whitespace when comparing code. However, the same code can still be written in different ways, such as with different variable names. Is there a way to compare code that will find more equivalent code?
You could store a SHA1 hash of the code to compare with a previous submission. You are right that different variable names would give different hashes. Try running the code through a minifier or obfuscator. That way, variable cat and dog will both end up like a1, then you could see if they are unique. The only other way would be to actually compile it into bytecode, but then it's too late.
Instead of analyzing the source code, why not speed up the compilation? Try having a servlet container always running with a custom ClassLoader, and use the JDK tools.jar to compile on the fly. You could even submit the code via AJAX REST and get the results back the same way.
Consider how Eclipse compiles your files in the background.
Also, consider how http://ideone.com implements their online compiler.
FYI It is a big security risk to allow random code execution. You have to be very careful about hackers.
Variable names:
You can write code to match variable names in one file with the variable names in the other, then you can replace both sets with a consistent variable name.
File 1:
var1 += this(var1 - 1);
File 2:
sum += this(sum - 1);
After you read File 1, you look for what variable name File 2 is using in the place of sum, then make the variable names the same across both files.
*Note, if variables are used in similar ways you may get incorrect substitutions. This is most likely when variables are being declared. To help mitigate this, you can start searching for variable names at the bottom of the file and work up.
Short hands:
Force {} and () braces into each if/else/for/while/etc...
rewrite operations like "i+=..." as "i=i+..."
Functions:
In cases where function order doesn't matter, you can make sure functions are equivalent and then ignore them.
Operator precedence:
"3 + (2 * 4)" is usually equivalent to "2 * 4 + 3"
A way around this could be by determining the precedence of each operation and then matching it to an operation of the same precedence in the other set of code. Once a set of operations have been matched, you can replace them with a variable to represent them.
Ex.
(2+4) * 3 + (2+6) * 5 == someotherequation
//substitute most precedent: (2+4) and (2+6) for a and b
... a * 3 + b * 5
//substitute most precedent: (a*3) and (b*5) for c and d
... c + d
//substitute most precedent....
These are just a couple ways I could think of. If you do it this way, it'll end up being quite a big project... especially if you're working with multiple languages.

Race between System.out and System.err in java [duplicate]

This question already has answers here:
System.out.println and System.err.println out of order
(7 answers)
Closed 9 years ago.
Please consider this java code:
public class CMain {
public static void main(String[] args){
for (int i = 0; i < 10; i++) {
System.out.println("A");
System.err.println("B");
}
}
}
By a quick look at the code, some of us may think the output has to be the print of As and Bs alternatively. However is not! It is a random appearance of 10 A characters and 10 B ones. Something like this:
Why is that? and what is the solution for it so that the As and Bs gets displayed alternatively ( A B A B A B ...)
Before I ask this question, I checked several other similar questions for solution and non worked for my case! I have brought some of them here:
Synchronization and System.out.println
Java: synchronizing standard out and standard error
Java: System.out.println and System.err.println out of order
PS. I am using Eclipse as my IDE
Why does this happen?
This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Moreover, when you do out.println(), it is not guaranteed that you will see the output on the console as soon as the statement gets executed. Instead, the strings are usually(depends on the system) stored in an output buffer (if you will) which is processed later by the system to put the output from the buffer onto the screen.
Solution :(
Although, as Eng.Fouad pointed out that you can use setOut(System.err) or setErr(System.out) to make them ordered, I would still not suggest doing that when you are actually putting this in an application (only use it for debugging purposes).
What the proposed solution does is that it will end up using only one stream for both the standard output and the standard error, which I do not think is a good thing to do.
They are different OutputStreams. If you really need to guarantee the order of printing them, use:
System.setErr(System.out);
or
System.setOut(System.err);
Since there are two separate streams, the output you are giving is possible.

asterisk in arithmetic output

When computing 2 doubles, 1/81 on the android platform, 0.01234567* was returned. What does the asterisk mean and how can I avoid such an output?
a=Double.parseDouble(subexp.substring(ss, i));
b=Double.parseDouble(subexp.substring(i+1, se+1));
subexp=subexp.substring(0,ss).concat(Double.toString(a/b))
.concat(subexp.substring(se+1,subexp.length()));
so basically the piece of offending code is above, with the following values grabbed from the debugger:
subexp="1+1/81" (before code)
"1+0.01234567*" (after code)
ss=2, se=5, i=3, a=1.0, b=81.0
Not to be a smartass, but if you just don't want the asterisk, try this immediately before you output your string:
subexp = subexp.replaceAll("\\*", "");
If your result requires something more elaborate than this, please provide more information and/or more complete source code, and I'll try to adapt my answer.
I made a simple project to test your code as posted. I printed the string out in the console as well as putting it in a TextView. In both places I get "1+0.012345689012345678", so I can't seem to replicate your results with the asterisk. Perhaps the problem is somewhere else in your code.

Categories

Resources