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.
Related
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 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.
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.
So I have an odd little problem with the hashing function in PHP. It only happens some of the time, which is what is confusing me. Essentially, I have a Java app and a PHP page, both of which calculate the SHA256 of the same string. There hasn't been any issues across the two, as they calculate the same hash (generally). The one exception is that every once in a while, PHP's output is one character longer than Java's.
I have this code in PHP:
$token = $_GET["token"];
$token = hash("sha256", $token."<salt>");
echo "Your token is " . $token;
99% of the time, I get the right hash. But every once in a while, I get something like this (space added to show the difference):
26be60ec9a36f217df83834939cbefa33ac798776977c1970f6c38ba1cf92e92 # PHP
26be60ec9a36f217df83834939cbefa33ac798776977c197 f6c38ba1cf92e92 # Java
As you can see, they're nearly identical. But the top one (computed by PHP) has one more 0 for some reason. I haven't really noticed a rhyme or reason to it, but it's certainly stumped me. I've tried thinking of things like the wrong encoding, or wrong return value, but none of them really explain why they're almost identical except for that one character.
Any help on this issue would be much appreciated.
EDIT: The space is only in the bottom one to highlight where the extra 0 is. The actual hash has no space, and is indeed a valid hash, as it's the same one that Java produces.
EDIT2: Sorry about that. I checked the lengths with Notepad++, and since it's different than my normal text editor, I misread the length by 1. So yes, the top one is indeed right. Which means that it's a bug in my Java code. I'm going to explore Ignacio's answer and get back to you.
The top hash is the correct length; the bottom hash is output because the hexadecimal values were not zero-filled on output (note that it's the MSn of a byte). So, a bug in the Java program unrelated to the hash algorithm.
>>> '%04x %02x%02x %x%x' % (0x1201, 0x12, 0x01, 0x12, 0x01)
'1201 1201 121'
Actually it's the SECOND hash which seems to have an incorrect length (63). Could it be that it is generated by assembling two different tokens, and maybe the last one - which should be 16 characters - gets the initial zero removed?
Sorry for the unclear title but I don't even know what to call it, I'll just go ahead and explain what's happening.
I'm using a Stringbuffer to build an URL. It looks like this:
http://maps.googleapis.com/maps/api/geocode/json?latlng=49.0516736,8.38891840&sensor=false
I encountered this behavious when comparing this string in a Unit-test to the actual result of the method.
And this is the assertion-error I'm getting:
latlng=49.0516736[,8.38891840]&sensor=false> but was:<...on?latlng=49.0516736[,8.3889184]&sensor=false
The emphasis is on the character sequence 0]& and 4]& right before sensor=false
IF I remove the zero before the & the test goes green.
then the created string looks like this:
latlng=49.0516736,8.3889184&sensor=false
so ... just as expected.
It's not the problem, that the 0 itself gets truncated and test would fail - I've proved that my code is doing what it's supposed to (when I remove the zero), but I want to know what is happening here.
0& must be some kind of indication for array-access or some kind of escaping. I don't know.
Anyone any idea what's causing this behaviour?
Edit:
Here's the code I'm using
StringBuffer s = new StringBuffer( grailsApplication.config.geocodingurl.toString() )
s.append(coordinates.latitude)
s.append(",")
s.append(coordinates.longitude)
s.append("&sensor=false")
return s.toString()
There is a formatting/padding issue when converting double into String.
What you are doing is probably using StringBuilder#append(double) which in the end calls Double#toString().
See the javadoc of those methods and find out how double values are converted to String.
Alternatively, if you want to have control over your code, use NumberFormat or it's subclasses.