Wrong double to float precision loss with Groovy on Android - java

I am experiencing a problem which eventually is a bug. I am programming an Android app in Groovy on Android Studio. It gives me weird compilation errors with respect to the following code:
def foo(float s) {
s = s / 2 // compilation error with pointer at '/' position
s = s.toFloat() / 254 // no error
}
The compilation error occurs even if the first line within the function is swapped with the last line.
I also tried the code on my local Groovy 1.8.6 environment outside of Android Studio on the command line. It doesn't give any error.
Who can explain me this irregular behavior? Is this normal? Are there more clever ways to circumvent this? Should I send a bug ticket to Groovy?
I am using Android Studio 2.1.2 with Oracle JVM 1.8.0_92 and the following gradle dependencies:
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.10'
compile 'org.codehaus.groovy:groovy:2.4.6:grooid'
Edit: Here comes the compilation error from Android Studio:
/path/to/androidproject/Bar.groovy: 199: [Static type checking] - Possible loss of precision from double to float
# line 199, column 19.
s = s / 2
^
Edit 2: The following code compiles even on Android:
def foo(float s) {
s = s * 2
}

Try:
s = s / 2.0f
or
s = (float) (s / 2)

Related

R code in Java working in Linux but not in Windows

What am I doing?
I am writing a data analysis program in Java which relies on R´s arulesViz library to mine association rules.
What do I want?
My purpose is to store the rules in a String variable in Java so that I can process them later.
How does it work?
The code works using a combination of String.format and eval Java and RJava instructions respectively, being its behavior summarized as:
Given properly formatted Java data structures, creates a data frame in R.
Formats the recently created data frame into a transaction list using the arules library.
Runs the apriori algorithm with the transaction list and some necessary values passed as parameter.
Reorders the generated association rules.
Given that the association rules cannot be printed, they are written to the standard output with R´s write method, capture the output and store it in a variable. We have converted the association rules into a string variable.
We return the string.
The code is the following:
// Step 1
Rutils.rengine.eval("dataFrame <- data.frame(as.factor(c(\"Red\", \"Blue\", \"Yellow\", \"Blue\", \"Yellow\")), as.factor(c(\"Big\", \"Small\", \"Small\", \"Big\", \"Tiny\")), as.factor(c(\"Heavy\", \"Light\", \"Light\", \"Heavy\", \"Heavy\")))");
//Step 2
Rutils.rengine.eval("transList <- as(dataFrame, 'transactions')");
//Step 3
Rutils.rengine.eval(String.format("info <- apriori(transList, parameter = list(supp = %f, conf = %f, maxlen = 2))", supportThreshold, confidenceThreshold));
// Step 4
Rutils.rengine.eval("orderedRules <- sort(info, by = c('count', 'lift'), order = FALSE)");
// Step 5
REXP res = Rutils.rengine.eval("rulesAsString <- paste(capture.output(write(orderedRules, file = stdout(), sep = ',', quote = TRUE, row.names = FALSE, col.names = FALSE)), collapse='\n')");
// Step 6
return res.asString().replaceAll("'", "");
What´s wrong?
Running the code in Linux Will work perfectly, but when I try to run it in Windows, I get the following error referring to the return line:
Exception in thread "main" java.lang.NullPointerException
This is a common error I have whenever the R code generates a null result and passes it to Java. There´s no way to syntax check the R code inside Java, so whenever it´s wrong, this error message appears.
However, when I run the R code in brackets in the R command line in Windows, it works flawlessly, so both the syntax and the data flow are OK.
Technical information
In Linux, I am using R with OpenJDK 10.
In Windows, I am currently using Oracle´s latest JDK release, but trying to run the program with OpenJDK 12 for Windows does not solve anything.
Everything is 64 bits.
The IDE used in both operating systems is IntelliJ IDEA 2019.
Screenshots
Linux run configuration:
Windows run configuration:

Z3 Java Possible Memory Leak?

I have a strange memory problem with Java library of Z3 which I couldn't figure where the problem is. Oddly, I can't reproduce the problem on a Windows machine where I have Java 7 (I most probably have slightly older version of Z3 there though). The problem occurs on a MacOSx 10.6.8 with Java 6 and Z3 v4.3.2. I have an application that uses Z3 for analysis. I tracked the following piece of code as the (initial) source of the problem:
Symbol eNames = con.mkSymbol(domainName);
Symbol[] symbols = new Symbol[values.length];
for (int i = 0; i < values.length; i++) symbols[i] = con.mkSymbol(values[i]);
System.out.println("Before ENUMSORT");
//EnumSort eSort = con.mkEnumSort(domainName, values);
EnumSort eSort = con.mkEnumSort(eNames,symbols);
System.out.println("After ENUM SORT ...");
When I run the application I get the following after "Before ENUMSORT" is printed:
java(55938,0x100501000) malloc: *** error for object 0x10200f1b8: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
I know this is not a good way of debugging especially when there is a memory problem but it is very difficult to debug the code since it originates from JNI. When I look at the Z3 code here (https://github.com/Z3Prover/z3/blob/master/src/api/api_datatype.cpp) I couldn't figure what the source of the problem is. I assume that the method Z3_mk_enumeration_sort is called from mkEnumSort method in Java. When I change the call of mkEnumSort in my code to a form like
EnumSort eSort = con.mkEnumSort(domainName,new String[]{"X","Y"});
the problem seems gone. What do you think, what could be the source of the problem?
Any help is highly appreciated.

Eigen - Levenberg Marquardt algorithm: invalid template arguments on definition of permutation

I'm trying to use the Eigen implementation of Levenberg Marquardt algorithm on a Android application. In order to use Eigen, I'm using Android NDK and jni. I've already tested Eigen with simple calculations (like matrix creation and vector sums) and it works perfectly. However, when I tried to use the Levenberg Marquardt algorithm I got some errors on the LevenbergMarquardt.h file from Eigen's library.
First, here is my code. I based on this code:
Eigen::MatrixXd matrix(count, 3);
for (int i = 0; i < count; i++) {
Eigen::VectorXd t(3);
t << x[i], y[i], accuracy[i];
matrix.row(i) = t;
}
distance_functor functor(matrix, count);
Eigen::NumericalDiff<distance_functor> numDiff(functor);
Eigen::LevenbergMarquardt<Eigen::NumericalDiff<distance_functor>,double> lm(numDiff);
lm.parameters.maxfev = 2000;
lm.parameters.xtol = 1.49012e-08;
lm.parameters.ftol = 1.49012e-08;
lm.parameters.gtol = 0;
lm.parameters.epsfcn = 0;
Eigen::LevenbergMarquardtSpace::Status ret = lm.minimize(poseResult);
And those are the error that I got. The first two errors are in Eigen's library, and the last one is on the LevenbergMarquardt object creation. I've also included the respective line of code of the error, following the message:
Invalid template
arguments LevenbergMarquardt.h /jnimath/jni/unsupported/Eigen/src/LevenbergMarquardt line
121 Semantic Error
typedef PermutationMatrix<Dynamic,Dynamic> PermutationType;
Invalid template
arguments LevenbergMarquardt.h /jnimath/jni/unsupported/Eigen/src/NonLinearOptimization line
103 Semantic Error
PermutationMatrix<Dynamic,Dynamic> permutation;
Invalid template arguments test.cpp /jnimath/jni line 47 Semantic
Error
Eigen::LevenbergMarquardt,double> lm(numDiff);
The first two errors are really strange because there are some other typedefs using Dynamic and they are not throwing errors.
Also, I noticed that I got some symbol errors on the compilation, which are:
Symbol
'YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY'
could not be resolved Matrix.h /jnimath/jni/Eigen/src/Core line
277 Semantic Error
Symbol 'YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX' could not be
resolved Matrix.h /jnimath/jni/Eigen/src/Core line 224 Semantic Error
So, I have two questions:
Why am I getting errors on those lines?
Does anyone know how to fix that problem?
Thank you

Groovy Syntax Checking in Java

I'm implementing a Web-based Groovy code editor and need to check the code for syntax errors. The Java implementation below works OK but the resulting message contains some undesired elements (in bold). I'm looking for a way to list warnings and errors individually.
I'm using this maven dependency: groovy-all 2.1.1
try {
new GroovyShell().parse(groovyCode);
} catch(CompilationFailedException cfe) {
System.out.println(cfe.getMessage());
}
Output:
startup failed:
Script1.groovy: 1: unexpected token: n # line 1, column 19.
def factorial(n) n == 1 ? 1 : n * factorial(n - 1) }
^
1 error
Would not make much sense to parse the error message. Try to look into
CompilationFailedException.getUnit()
ProcessingUnit.getErrorCollector()
ErrorCollector.getWarnings() & getErrors()
EDIT
Ok, looks like unit is null on the CompilationFailedException. Try catching MultipleCompilationErrorsException instead:
try {
new GroovyShell().parse(groovyCode);
} catch(MultipleCompilationErrorsException cfe) {
ErrorCollector errorCollector = cfe.getErrorCollector();
System.out.println("Errors: "+errorCollector.getErrorCount());
}
Btw, take a look at the ErrorCollector sources, you might find write method useful to output the info about compilation errors.

J2ME error - the method nextInt() in the type Random is not applicable for the arguments (int)

I just started to learn J2ME and right from the bat I got this error when using Random class. Arg, it's so frustrating. Anyone got the same problem before? I already tried to restart Eclipse, write only the code for the random generator to isolate it but to no avail.
I'm using CLDC 1.1 and MIDP 2.1 by the way.
Seems you are pointing out the wrong CLDC and MIDP libraries. new Random().nextInt(x) exists in CLDC 1.1.
If you are using CLDC 1.0 you can create your own implementation of nextInt(int):
public static int random(Random r, int n) {
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)r.nextInt()) >> 31);
int bits, val;
do {
bits = r.nextInt();
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
(Same implementation as nextInt(int) in the CLDC 1.1.)
nextInt(int) is only available since CLDC 1.1, so you have to specify CLDC 1.1 instead of 1.0
if you specified cldc 1.1 an still get this error its most likely an error of eclipse. took me hours to find:
in Eclipse go to Windows -> Preferences -> Java ME -> Device Management -> choose your Default Device -> Edit -> Libraries -> There you have to remove the cldc_1.0.jar
I had the same problem in netbeans, and solved it.
Right click on your project, go to properties.
Go To Libraries & Resources under build
Add Library
scroll for JMUnit for CLDC11
click OK
and build. all problems solved.
I just left JMUnit for CLDC11 there. not really sure if I need it. maybe I'll test without it once I have made up for lost time.

Categories

Resources