Delphi XE5 - Android - Save file in server windows (shared folder) - java

Good morning,
I developed an application on Android through the Delphi XE5 which tries to save a text file in a shared folder on the server (windows) but I received the message I / O error 30. I've tried several ways in Assign File as describe in the code. Could help?
function gravar_registro():integer;
var NomeArqTxt: TextFile;
begin
try
begin
// AssignFile(NomeArqTxt, '/storage/sdcard1/FolderTEST/xxx.txt'); // Test1 OK = This is possible = OK = SDCARD
// AssignFile(NomeArqTxt, '/sdcard/FolderTEST/gerados/xxx.txt'); // Test2 OK = This is possible = OK = memória interna;
// AssignFile(NomeArqTxt, '\\192.168.1.152\FolderSHARED\xxx.txt'); // Test3 = ERROR = I've done testing, but I / O error 30
// AssignFile(NomeArqTxt, 'smb://192.168.1.152/FolderSHARED/xxx.txt'); // Test4 = ERROR = I've done testing, but I / O error 30
// AssignFile(NomeArqTxt, '192.168.1.152\FolderSHARED\xxx.txt'); // Test5 = ERROR = I've done testing, but I / O error 30
//. Observation: a) I've done testing with FolderSHARED folder and it has access to read / write
// b) The IP 192.168.1.152 is valid and active a personal computer on the internal network
{$I-}
Reset(NomeArqTxt);
{$I+}
if (IOResult <> 0) then
ReWrite(NomeArqTxt)
else
begin
CloseFile(NomeArqTxt);
Append(NomeArqTxt);
end;
Writeln(NomeArqTxt, 'TEST TEST TEST');
CloseFile(NomeArqTxt);
showmessage('File Saved...');
end
except
On Erro: Exception Do
begin
showmessage(Erro.Message);
end;
end;
end;

Use the TStringList object and then use it's TStringList.SaveToFile() function.

This is not possible without support for the network protocol used on the server side. For Windows, there is an Android library to support the SMB protocol. Some questions on Stackoverflow included source code which explain its usage and authentication with the server, for example:
Write/upload a file using Samba/JCIFS issue (SmbAuthException: Access is denied)
For an introduction see
http://durgemeister.wordpress.com/2014/04/26/mapping-a-network-with-jcifs-and-android/

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:

Stopping RServe printing json on the console

I'm running into a very curious problem. I've an R code which doesn't contain any print statement (except my explicit calls to log the time taken) and yet the entire json gets dumped on to the "R console". This is causing a serious performance issue with our module and I need your help to track down the problem.
Here is just a part of the R file (due to company policies, I cannot post the entire source code and I apologize for not giving much info)
#run time/online time series models
LAST_TIME_ID <- DATA[nrow(DATA),id];
LAST_TIME_ID <- strptime(LAST_TIME_ID,format="%d-%m-%Y %H:%M");
#timestamp tag computation using frequency
FREQUENCY_VEC <- rep(TIMESTAMP_FREQUENCY*60,PREDICTION_NUMBER);
FREQUENCY_VEC <- cumsum(FREQUENCY_VEC);
TIMESTAMP_TAGS <- LAST_TIME_ID + FREQUENCY_VEC;
TIMESTAMP_TAGS <- format(strptime(TIMESTAMP_TAGS,format="%Y-%m-%d %H:%M"),format="%d-%m-%Y %H:%M");
#prepare the prediction points data per tag into table format
PREDICTION_DATA <- NULL;
startTime <- Sys.time();
for (tag_index in 1:length(MODEL[,tag_id])) {
TEMP <- data.table(id=as.character(TIMESTAMP_TAGS),tag_id = MODEL[tag_index,tag_id], prediction = as.vector(MODEL[,Forecast][[tag_index]]));
PREDICTION_DATA <- data.table(rbind(PREDICTION_DATA,TEMP));
rm(TEMP);
};
endTime <- Sys.time();
print(paste("seconds consumed (prediction points data per tag into TEMP): ",(endTime-startTime)/1000));
#OUTPUT <- dcast(PREDICTION_DATA,id~tag_id); #into output
OUTPUT <- PREDICTION_DATA;
#compute final output in json format
js_object <- toJSON(OUTPUT,asIs = TRUE);
js_object;
I can assure you the rest of code looks the same (i.e. no prints). I'm running my R code through Java (1.8) using RServe (REngine.jar) on Windows 8.
Any ideas/clues would be greatly appreciated.
The last line of your choice snippet where you just execute:
js_object;
prints the variable to the console.
Remove such type of statements where nothing assigned to a variable.
When you type the js_object file name at the end, you are calling that object and R is printing the contents to the console. All you need to do is remove that an it should stop printing it out.

Apache-Zeppelin / Spark : Why can't I access a remote DB with this code sample

I am doing my first own steps with Spark and Zeppelin and don't understand why this code sample isn't working.
First Block:
%dep
z.reset() // clean up
z.load("/data/extraJarFiles/postgresql-9.4.1208.jar") // load a jdbc driver for postgresql
Second Block
%spark
// This code loads some data from a PostGreSql DB with the help of a JDBC driver.
// The JDBC driver is stored on the Zeppelin server, the necessary Code is transfered to the Spark Workers and the workers build the connection with the DB.
//
// The connection between table and data source is "lazy". So the data will only be loaded in the case that an action need them.
// With the current script means this the DB is queried twice. ==> Q: How can I keep a RDD in Mem or on disk?
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.rdd.JdbcRDD
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import org.apache.spark.sql.hive._
import org.apache.spark.sql._
val url = "jdbc:postgresql://10.222.22.222:5432/myDatabase"
val username = "postgres"
val pw = "geheim"
Class.forName("org.postgresql.Driver").newInstance // activating the jdbc driver. The jar file was loaded inside of the %dep block
case class RowClass(Id:Integer, Col1:String , Col2:String) // create a class with possible values
val myRDD = new JdbcRDD(sc, // SparkContext sc
() => DriverManager.getConnection(url,username,pw), // scala.Function0<java.sql.Connection> getConnection
"select * from tab1 where \"Id\">=? and \"Id\" <=? ", // String sql Important: we need here two '?' for the lower/upper Bounds vlaues
0, // long lowerBound = start value
10000, // long upperBound, = end value that is still included
1, // int numPartitions = the area is spitted into x sub commands.
// e.g. 0,1000,2 => first cmd from 0 ... 499, second cmd from 500..1000
row => RowClass(row.getInt("Id"),
row.getString("Col1"),
row.getString("Col2"))
)
myRDD.toDF().registerTempTable("Tab1")
// --- improved methode (not working at the moment)----
val prop = new java.util.Properties
prop.setProperty("user",username)
prop.setProperty("password",pw)
val tab1b = sqlContext.read.jdbc(url,"tab1",prop) // <-- not working
tab1b.show
So what is the problem.
I want to connect to an external PostgreSql DB.
Block I is adding the necessary JAR file for the DB and first lines of the second block is already using the JAR and it is able get some data out of the DB.
But the first way is ugly, because you have to convert the data by your own into a table, so I want to use the easier method at the end of the script.
But I am getting the error message
java.sql.SQLException: No suitable driver found for
jdbc:postgresql://10.222.22.222:5432/myDatabase
But it is the same URL / same login / same PW from the above code.
Why is this not working?
Maybe somebody has a helpful hint for me.
---- Update: 24.3. 12:15 ---
I don't think the loading of the JAR is not working. I added an extra val db = DriverManager.getConnection(url, username, pw); for testing. (The function that fails inside of the Exception) And this works well.
Another interesting detail. If I remove the %dep block and class line, produces the first block a very similar error. Same Error Message; same function + line number that is failing, but the stack of functions is a bit different.
I have found the source code here: http://code.metager.de/source/xref/openjdk/jdk8/jdk/src/share/classes/java/sql/DriverManager.java
My problem is in line 689. So if all parameters are OK , maybe it comes from the isDriverAllowed() check ?
I ve had the same problem with dependencies in Zeppelin, and I had to add my jars to the SPARK_SUBMIT_OPTIONS in zeepelin-env.sh to have them included in all notebooks and paragraphs
SO in zeppelin-env.sh you modify SPARK_SUBMIT_OPTIONS to be:
export SPARK_SUBMIT_OPTIONS="--jars /data/extraJarFiles/postgresql-9.4.1208.jar
Then you have to restart your zeppelin instance.
In my case while executing a spark/scala code, I received the same error. I had previously set SPARK_CLASSPATH in my spark-env.sh conf file - it was pointing to a jar file. I removed/commented out the line in spark-env.sh and restarted zepplin. This got rid of the error.

JavaImp plugin not able to parse Java files

I have been using the JavaImp.vim script for auto importing Java statements in VIM
But trying out different directories in the JavaImpPaths, I am still unable to make JavaImp parse the Java files in the source to make auto imports possible
this is how my .vimrc looks like
let g:JavaImpPaths = "~/Documents/android-sdks/sources/android-21/android/content/"
let g:JavaImpClassList = "~/.vim/JavaImp/JavaImp.txt"
let g:JavaImpJarCache = "~/.vim/JavaImp/cache/"
This is what I get running JIG in new Vim window
:JIG
Do you want to create the directory ~/.vim/JavaImp/cache/?
Searching in path (package): ~/Documents/android-sdks/sources/android-21/android
/content/ ()
Sorting the classes, this may take a while ...
Assuring uniqueness...
Error detected while processing function <SNR>10_JavaImpGenerate:
line 75:
E37: No write since last change (add ! to override)
Done. Found 1 classes (0 unique)
Press ENTER or type command to continue
It might be late, but if anyone else comes along this might help them...
I got it working with the following changes to the script:
line 181 from
close
to
close!
And lines 207/208 from
let l:javaList = glob(a:cpath . "/**/*.java", 1, 1)
let l:clssList = glob(a:cpath . "/**/*.class", 1, 1)
to
let l:javaList = split(glob(a:cpath . "/**/*.java"), "\n")
let l:clssList = split(glob(a:cpath . "/**/*.class"), "\n")

Using meta learning in RWeka

I used RWeka to call Weka functions directly in R.
I tried using meta learning (bagging) but failed.
My code is Bagging(classLabel ~ ., data = train, control = Weka_control(W = J48))
However, the following error pops up:
Error in Bagging(classLabel ~ ., data = train, control = Weka_control(W = J48)) :
unused argument(s) (data = train, control = Weka_control(W = J48))
I also tried several different base learners but always met such error.
If you successfully used meta learning in RWeka before, please let me know.
Just tried another writing:
optns <- Weka_control(W = "weka.classifiers.trees.REPTree") Bagging <- make_Weka_classifier("weka/classifiers/meta/Bagging") model <- Bagging(classLabel ~ ., data=dat, control = optns)
Surprisingly the R code works now.
-Credit Leo5188

Categories

Resources