Sunday, August 18, 2013

Sorting Multi-Column Datasets in R

Sorting Multi-Column Datasets in R


August 18, 2013

In this entry, we present the most straightforward way to sort multi-column datasets

Suppose that we have a vector in three dimensional space. This vector can be defined as

<- c(3,1,2)

in R. The built-in function sort sorts a given vector in ascending order by default. An ordered version of vector a is calculated as shown below:

sorted_<- sort(a)

The result is

[1] 1 2 3

For reverse ordering, the value of decreasing parameter must be set to TRUE.

> sort(a,decreasing=TRUE) 
[1] 3 2 1

Another related function order returns indices of sorted elements.

> a <- c(3,1,2) 
> order (a) 
[1] 2 3 1

In the example above, it is shown that if the vector a is ordered in ascending order, second element of a will be placed at index 1. It is easy to show that, result of the function order can be used to sort data.

> a <- c(3,1,2) 
> o <- order (a) 
> a[o] 
[1] 1 2 3

Suppose that we need to sort a matrix by a desired row. The solution is easy. Get the indices of sorted desired column and use the same method as in example given above.

> x <- round(runif(5, 0, 100)) 
> y <- round(runif(5, 0, 100)) 
> z <- round(runif(5, 0, 100)) 
> data <- cbind(x,y,z) 
> data 
      x  y  z 
[1,] 48 35 75 
[2,] 40 21 43 
[3,] 58 69  1 
[4,] 49 38  2 
[5,] 43 66 46

Now, get the indices of sorted z:

> o <- order(z) 
> data[o,] 
      x  y  z 
[1,] 58 69  1 
[2,] 49 38  2 
[3,] 40 21 43 
[4,] 43 66 46 
[5,] 48 35 75

Finally, we sorted the dataset data by the column vector z.

Saturday, August 17, 2013

A User Document For RCaller

A new research paper as a RCaller documentation is freely available at http://www.sciencedomain.org/abstract.php?iid=550&id=6&aid=4838#.U5YSoPmSy1Y




RCaller: A library for calling R from Java

by M.Hakan Satman

August 17, 2013

Contents


Abstract

RCaller is an open-source, compact, and easy-to-use library for calling R from Java. It offers not only an elegant solution for the task but its simplicity is key for non-programmers or programmers who are not familier with the internal structure of R. Since R is not only a statistical software but an enormous collection of statistical functions, accessing its functions and packages is of tremendous value. In this short paper, we give a brief introduction on the most widely-used methods to call R from Java and highlight some properties of RCaller with short examples. User feedback has shown that RCaller is an important tool in many cases where performance is not a central concern.

1 Introduction


R [R Development Core Team(2011)] is an open source and freely distributed statistics software package for which hundreds of external packages are available. The core functionality of R is written mostly in C and wrapped by R functions which simplify parameter passing. Since R manages the exhaustive dynamic library loading tasks in a clever way, calling an external compiled function is easy as calling an R function in R. However, integration with JVM (Java Virtual Machine) languages is painful.
The R package rJava [Urbanek(2011a)] provides a useful mechanism for instantiating Java objects, accessing class elements and passing R objects to Java methods in R. This library is convenient for the R packages that rely on external functionality written in Java rather than C, C++ or Fortran.
The library JRI, which is now a part of the package rJava, uses JNI (Java Native Interface) to call R from Java [Urbanek(2009)]. Although JNI is the most common way of accessing native libraries in Java, JRI requires that several system and environment variables are correctly set before any run, which can be difficult for inexperienced users, especially those who are not computer scientists.
The package Rserve [Urbanek(2011b)] uses TCP sockets and acts as a TCP server. A client establishes a connection to Rserve, sends R commands, and receives the results. This way of calling R from the other platforms is more general because the handshaking and the protocol initializing is fully platform independent.
Renjin (http://code.google.com/p/renjin) is an other interesting project that addresses the problem. It solves the problem of calling R from Java by re-implementing the R interpreter in Java! With this definition, the project includes the tasks of writing the interpreter and implementing the internals. Renjin is intended to be 100% compatible with the original. However, it is under development and needs help. After all, an online demo is available which is updated simultaneously when the source code is updated.
Finally, RCaller [RCaller Development Team(2011)] is an LGPL’d library which is very easy to use. It does not do much but wraps the operations well. It requires no configuration beyond installing an R package (Runiversal) and locating the Rscript binary distributed with R. Altough it is known to be relatively inefficient compared to other options, its latest release features significant performance improvements.

2 Calling R Functions


Calling R code from other languages is not trivial. R includes a huge collection of math and statistics libraries with nearly 700 internal functions and hundreds of external packages. No comparable library exists in Java. Although libraries such as the Apache Commons Math [Commons Math Developers(2010)] do provide many classes for those calculations, its scope is quite limited compared to R. For example, it is not easy to find such a library that calculates quantiles and probabilities of non-central distributions. [Harner et al.(2009)Harner, Luo, and Tan] affirms that using R’s functionality from Java prevents the user from writing duplicative codes in statistics softwares.
RCaller is an other open source library for performing R operations from within Java applications in a wrapped way. RCaller prepares R code using the user input. The user input is generally a Java array, a plain Java object or the R code itself. It then creates an external R process by running the Rscript executable. It passes the generated R code and receives the output as XML documents. While the process is alive, the output of the standard input and the standard error streams are handled by an event-driven mechanism. The returned XML document is then parsed and the returned R objects are extracted to Java arrays.
The short example given below creates two double vectors, passes them to R, and returns the residuals calculated from a linear regression estimation.
RCaller caller = new RCaller();
RCode code = new RCode();
double[] xvector = new double[]{1,3,5,3,2,4};
double[] yvector = new double[]{6,7,5,6,5,6};

caller.setRscriptExecutable("/usr/bin/Rscript");

code.addDoubleArray("X", xvector);
code.addDoubleArray("Y", yvector);
code.addRCode("ols <- lm ( Y ~ X )");

caller.setRCode(code);

caller.runAndReturnResult("ols");

double[] residuals =
   caller.getParser().
     getAsDoubleArray("residuals");  

The lm function returns an R list with a class of lm whose elements are accessible with the $ operator. The method runAndReturnResult() takes the name of an R list which contains the desired results. Finally, the method getAsDoubleArray() returns a double vector with values filled from the vector residuals of the list ols.
RCaller uses the R package Runiversal [Satman(2010)] to convert R lists to XML documents within the R process. This package includes the method makexml() which takes an R list as input and returns a string of XML document. Although some R functions return the results in other types and classes of data, those results can be returned to the JVM indirectly. Suppose that obj is an S4 object with members member1 and member2. These members are accessible with the @ operator like obj@member1 and obj@member2. These elements can be returned to Java by constructing a new list like result\A1-list(m1=obj@member1, m2=obj@member2).

3 Handling Plots


Although the graphics drivers and the internals are implemented in C, most of the graphics functions and packages are written in the R language and this makes the R unique with its graphics library. RCaller handles a plot with the function startPlot() and receives a java.io.File reference to the generated plot. The function getPlot() returns an instance of the javax.swing.ImageIcon class which contains the generated image in a fully isolated way. A Java example is shown below:
RCaller caller = new RCaller();
RCode code = new RCode();
File plotFile = null;
ImageIcon plotImage = null;

caller.
setRscriptExecutable("/usr/bin/Rscript");

code.R_require("lattice");

try{
 plotFile = code.startPlot();
 code.addRCode("
      xyplot(rnorm(100)~1:100, type=’l’)
      ");
}catch (IOException err){
 System.out.println("Can not create plot");
}

caller.setRCode(code);
caller.runOnly();

plotImage = code.getPlot(plotFile);
code.showPlot(plotFile);

The method runOnly() is quite different from the method RunAndReturnResult(). Because the user only wants a plot to be generated, there is nothing returned by R in the example above. Note that more than one plots can be generated in a single run.
Handling R plots with a java.io.File reference is also convenient in web projects. Generated content can be easly sent to clients using output streams opened from the file reference. However, RCaller uses the temp directory and does not delete the generated files automatically. This may be a cause of a too many files OS level error which can not be caught by a Java program. However, cleaning the generated output using a scheduled task solves this problem.

4 Live Connection


Each time the method runAndReturnResult() is called, an Rscript instance is created to perform the operations. This is the main source of the inefficiency of RCaller. A better approach in the cases that R commands are repeatedly called is to use the method runAndReturnResultOnline(). This method creates an R instance and keeps it running in the background. This approach avoids the time required to create an external process, initialize the interpreter, and load packages in subsequent calls.
The example given below returns the determinants of a given matrix and its inverse in sequence, that is, it uses a single external instance to perform more than one operation.
double[][] matrix =
    new double[][]{{5,4,5},{6,1,0},{9,-1,2}};
caller.setRExecutable("/usr/bin/R");
caller.setRCode(code);

code.clear();
code.addDoubleMatrix("x", matrix);
code.addRCode("result<-list(d=det(x))");
caller.runAndReturnResultOnline("result");

System.out.println(
"Determinant is " +
  caller.getParser().
   getAsDoubleArray("d")[0]
   );

code.addRCode("result<-list(t=det(solve(x)))");
caller.runAndReturnResultOnline("result");

System.out.println(
"Determinant of inverse is " +
  caller.getParser().
   getAsDoubleArray("t")[0]
   );

This use of RCaller is fast and convenient for repeated commands. Since R is not thread-safe, its functions can not be called by more than one threads. Therefore, each single thread must create its own R process to perform calculations simultaneously in Java.

5 Monitoring the Output


RCaller receives the desired content as XML documents. The content is a list of the variables of interest which are manually created by the user or returned automatically by a function. Apart from the generated content, R produces some output to the standard output (stdout) and the standard error (stderr) devices. RCaller offers two options to handle these outputs. The first one is to save them in a text file. The other is to redirect all of the content to the standard output device. The example given below shows a conditional redirection of the outputs generated by R.
if(console){
 caller.redirectROutputToConsole();
}else{
 caller.redirectROutputToFile(
     "output.txt" /* filename */,
     true  /* append? */);
}

6 Conclusion


In addition to being a statistical software, R is an extendable library with its internal functions and external packages. Since the R interpreter was written mostly in C, linking to custom C/C++ programs is relatively simple. Unfortunately, calling R functions from Java is not straightforward. The prominent methods use JNI and TCP sockets to solve this problem. In addition, renjin offers a different perspective to this issue. It is a re-implementation of R in Java which is intended to be 100% compatible with the original. However, it is under development and needs help. Finally, RCaller is an alternative way of calling R from Java. It is packaged in a single jar and it does not require setup beyond the one-time installation of the R package Runiversal. It supports loading external packages, calling functions, handling plots and debugging the output generated by R. It is not the most efficient method compared to the alternatives, but users report that performance improvements in the latest revision and its simplicity of use make it an important tool in many applications.

References


[Commons Math Developers(2010)]   Commons Math Developers. Apache Commons Math, Release 2.1. Available from http://commons.apache.org/math/download_math.cgi, Apr. 2010. URL http://commons.apache.org/math.
[Harner et al.(2009)Harner, Luo, and Tan]   E. Harner, D. Luo, and J. Tan. JavaStat: A Java/R-based statistical computing environment. Computational Statistics, 24(2):295–302, May 2009.
[R Development Core Team(2011)]   R Development Core Team. R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria, 2011. URL http://www.R-project.org/. ISBN 3-900051-07-0.
[RCaller Development Team(2011)]   RCaller Development Team. RCaller: A library for calling R from Java, 2011. URL http://code.google.com/p/rcaller.
[Satman(2010)]   M. H. Satman. Runiversal: A Package for converting R objects to Java variables and XML., 2010. URL http://CRAN.R-project.org/package=Runiversal. R package version 1.0.1.
[Urbanek(2009)]   S. Urbanek. How to talk to strangers: ways to leverage connectivity between R, Java and Objective C. Computational Statistics, 24(2):303–311, May 2009.
[Urbanek(2011a)]   S. Urbanek. rJava: Low-level R to Java interface, 2011a. URL http://CRAN.R-project.org/package=rJava. R package version 0.9-2.
[Urbanek(2011b)]   S. Urbanek. Rserve: Binary R server, 2011b. URL http://CRAN.R-project.org/package=Rserve. R package version 0.6-5.





A new research paper as a RCaller documentation is freely available at http://www.sciencedomain.org/abstract.php?iid=550&id=6&aid=4838#.U5YSoPmSy1Y






























Sunday, July 7, 2013

How To Connect MySQL Database Using Java

Hello

In this article, I'll show you how to connect MySQL database using java. For this, you should configure the settings about MySQL connector in the JAVA IDE first. So all things what we need are;


  • IDE (NetBeans or EClipse is so good!)
  • MySQL Connector

  • MySQL Connector is a jar file which is so small size. You can download MySQL Connector here and check this line up:
    JDBC Driver for MySQL (Connector/J)
    After downloading, you have to introduce IDE and Connector. I use NetBeans. Because of I will show you how to introduce on the NetBeans already. Actually It doesn't matter which program has used. For that reason This process is the same for EClipse.

    Screen views given above show us the process about introducing. You click OK and it's finish. Your MySQL driver and JAVA IDE know each other from on now. Let's create a db class on there.
    void vt() {
            Connection conn = null;
            String hostName = "jdbc:mysql://localhost:3306/";
            String dbName = "DatabaseName";
            String driver = "com.mysql.jdbc.Driver";
            String userName = "root";
            String password = "*****";
            try {
                conn = DriverManager.getConnection(
                    hostName+dbName,userName,password);
                System.out.println("Connected to the database");
                Statement st = conn.createStatement();
                ResultSet result = st.executeQuery("SELECT * FROM  test");
                while (result.next()) {
                   int id = result.getInt("id");
                   String name = result.getString("name");
                   System.out.println(id + "\t" + name);
            }
                conn.close();
            } catch (Exception e) {
                System.out.println("No Connection!");
            }
    }
    

    In the try..catch debugging part, if there is no connection, You are going to see "No Connection!" alert on the screen. If not, You'll get names of the test table from your database. This code given above is not so good, but useful. If you want to code better, you can use OOP for example. Create a class of database connection, and use it each time connection.
    See you next article!

    Friday, July 5, 2013

    CURL Requests With PHP

    Hello,
    Most developers prefer to use HTTP Request / Response service in their projects. In this situation, you have to send data as POST method to the opponent.

    Imagine that you are a web master of your own e-commerce web site. Members of the site use coupon during check out. In these conditions, you may connect to other systems, for example the store which is in another sector, and have to validate if the coupon is correct or something like that. Here is the magnificent specimen of pure one of the best example in the world for this article :)

    If you want, let's code CURL for now!

    For this, I set a service up for posting data: service.php
    if(isset($_POST['field'])) {
        print "Field is: ".$_POST['field'];
    }
    else {
        print "Field is blank!";    
    }
    
    Like you've just seen above, the service is waiting for field post variable on it. If you send a field data, the screen is going to be like,

    Field is your field value
    
    But else,

    Field is blank!
    
    I suppose to send a field value to the service: myfile.php

    //display error
    ini_set('display_errors', 1);
     
    //curl
    $ch = curl_init("http://localhost/CURL/service.php");
     
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'field=phpservisi.com');
     
    curl_exec($ch);
    curl_close($ch);
    
    If I run the myfile.php page, just going to see on on the screen like,

    Field is phpservisi.com
    
    For this example, I used a page which was http protocol. But sometimes I need use to https. In these conditions,have to add this line on it,

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    There are so many settings and options in CURL. If you want to check it out, you can visit PHP official page, here

    See you next articles!

    Thursday, July 4, 2013

    How To Generate EXCEL Files With PHP

    Hello,
    Today, I will share a very useful application with you guys, generating excel files with using PHP. As you know, we need reports as excel, pdf, word etc. in our web sites. For that reason, generating all of'em is important thing for us. Some of us use basic HTML files with using PHP & a data base. But this is not enough. Thus, I use generating excel.
    So, Let's code :)
    $filename = "myExcelFile_".date('Y-m-d-h-i').".xls"; 
    
    header("Content-Disposition: attachment; 
            filename=\"$filename\""); 
    
    header("Content-Type: application/vnd.ms-excel"); 
    
    header('Content-Type: application/x-msexcel; 
            charset=UTF-8; format=attachment;');
    
    echo "\tMy EXCEL DATA\r\n"; 
    
    exit;
    

    I set my file name up as myExcelFile_ plus current time and some header configuration. Then finally I print. That's it.
    If you run, you'll see this view:

    This article was short but so useful. You can develop better, of course.
    See you next article.

    Sunday, April 21, 2013

    R Package: mcga

    Machine coded genetic algorithm (MCGA) is a fast tool for real-valued optimization problems. It uses the byte representation of variables rather than real-values. It performs the classical crossover operations (uniform) on these byte representations. Mutation operator is also similar to classical mutation operator, which is to say, it changes a randomly selected byte value of a chromosome by +1 or -1 with probability 1/2. In MCGAs there is no need for encoding-decoding process and the classical operators are directly applicable on real-values. It is fast and can handle a wide range of a search space with high precision. Using a 256-unary alphabet is the main disadvantage of this algorithm but a moderate size population is convenient for many problems. Package also includes multi_mcga function for multi objective optimization problems. This function sorts the chromosomes using their ranks calculated from the non-dominated sorting algorithm.

    Package Url:

    http://cran.r-project.org/web/packages/mcga/index.html

    R Installation:

      install.packages ("mcga")
    

    For help and example type

      ?mcga
    
    
    in R console.


    Tuesday, October 16, 2012

    Encryption Functions in PHP: crypt() and md5()

    Hi! In this article, I am going to share encryption functions on PHP programming language with you. Well, there are several functions about this subject, but here the point is crypt and md5.


    md5 function is a text encryption. Here the text or string may be probably as password. md5 function makes the text a value which is 32-digit. Sure this value is probably going to be more complex than older text value.
    print md5("phpservisi.com");
    
    md5 function's output
    The example given above shows us phpservisi.com string value's output with md5 function.

    crypt function is the same mission with md5. Namely this is encryption function too. Here the variety is complexity of output. Because of it is some of us use this one, like me :) 

    One more feature is the output of crypt function's about making one-way string hashing. crypt function will return a hashed string using alternative algorithms that may be available on the system.

    Now, I'm coding about this:


    echo crypt("phpservisi.com"); 
    echo "\n".crypt("phpservisi.com"); 
    echo "\n".crypt("phpservisi.com"); 
    echo "\n".crypt("phpservisi.com"); 
    echo "\n".crypt("phpservisi.com"); 
    echo "\n".crypt("phpservisi.com"); 
    echo "\n".crypt("phpservisi.com"); 
    echo "\n".crypt("phpservisi.com");
    

    crypt function's output
    As you've seen on the top is crypt function's output. I did the same thing 8 times, and crypt function has just given us different results about those.

    If you want to learn more information about this subject, you can visit the PHP Manual web page: md5cryptsha1_filecrc32sha1hash

    Friday, August 17, 2012

    A nice video on RCaller 2.0


    A nice video on RCaller is in Youtube now. The original link is in Quantlabs.net. Thanks for the uploader.

    Wednesday, August 8, 2012

    libjvm.so: cannot open shared object file: No such file or directory


    In my Ubuntu Linux, I was trying to call Java from C++ using JNI. Compiling progress was succeed but at runtime I saw an error on concole:

    libjvm.so: cannot open shared object file: No such file or directory

    Finding the right solution took five seconds but it was quite easy. I modified the LD_LIBRARY_PATH environment variable using export command in the Linux shell:

    export LD_LIBRARY_PATH=/usr/lib/jvm/default-java/jre/lib/i386:/usr/lib/jvm/default-java/jre/lib/i386/client

    The location of JDK is always changed because of updates but Ubuntu stores the links of current JVM in default-java directory. It is /usr/lib/jvm/default-java in my Linux. Two directories must be added to LD_LIBRARY_PATH. The first one is jre/lib/i386 and the second one is jre/lib/i386/client or jre/lib/i386/server in default-java directory. Use of export solves my problem.

    Good luck!


    Monday, August 6, 2012

    Online Interpreters and Compilers in codepad.org

    Today, I stumbled upon a web page which has got an online interpreter/compiler interface for many languages including C, C++, D, Haskell, Lua, OCaml, Php, Perl, Python, Ruby, Scheme and Tcl.

    Just write your code, select the corresponding language and hit the submit button.
    You will be forwarded to an other page in which the output of your code is shown.

    Click here to goto codepad.org. Have Fun!

    Thursday, August 2, 2012

    Fuzuli Android Application and Online Interpreter

    We have just released the online interpreter and the Android application of Fuzuli, our programming language and interpreter.

    You can simply run your Fuzuli programs using the site Fuzuli Online Interpreter. You will see a small hello world program. Since it only writes the "Hello world" string on the screen, it is not really relevant but makes sense. Every single programming language has its own Hello world! Type your program after deleting classical hello world program then click the RUN button. If your program is correct, you will see the output of your program at the bottom of the code. The other option for using our online interpreter is to download and install the Android application. You can download and install Fuzuli Online Interpreter for Android here. The file you will have found is ready to download and install. Do not forget to uninstall older versions if you have already installed one.

    Have fun with Fuzuli!

    Tuesday, July 31, 2012

    Garbage Collection Mechanism of Fuzuli Interpreter

    Fuzuli, our programming language and interpreter, has a garbage collection utility since its early stages. Garbage collection is an old term in computer science.

    A chunk of memory is allocated for each software program by operating systems. Programs also allocate memory at runtime. Those programs are responsable to free the memory they allocated. Operations for allocating and freeing memory areas are performed using single commands such like malloc, free, new and delete in C and C++.

    But allocating and freeing the chunks of memory is not that easy. When a reference to a dynamically created object is broken, the object remains suspended in the memory. Look at code below:


    (let a (list 5 6 10 "Text"))
    (let a NULL)
    

    In the code above, a list of 5, 6, 10 and Text is created and referenced by the variable 'a'. Then, a is set to NULL. After all, what happened to list and its objects? The answer is easy. They suspended in the memory and waiting to be cleaned.

    Ok, what about the code given below?


    (let b 11)
    (let a (list 5 6 10 b))
    (let a NULL)
    


    In the code above, a is linked to a list which contains 5,6,10 and b. b is an other variable which has a value of 11. After setting the value of 'a' to NULL, there is some garbage but this is a little bit different. Cleaning the object referenced by 'a' also means cleaning the object referenced by b. But we don't 'b' to be cleaned, it should stay alive. Reference Counting now comes into account. Counting references given to an object gives more information about the aliveness status of an object. In this example, the integer object has only one references in (let b 11).

    When the code (let a (list 5 6 10 b)) runs; references of objects 5, 6, 10 and b increased by 1. The old reference count of b was 1, so b has a reference counting of 2. When (let a NULL) runs; reference counts of all objects contained by 'a' are decreased by 1. After all, the object which have reference count of 0 are deleted from the memory. The object 'b' is still alive!. Fuzuli uses this mechanism.

    Garbage collecting in Fuzuli is automatic by default. Calling


    (gc false)
    


    simply disables the automatic garbage collector. Calling

    (gc true)
    


    enables the garbage collector. Whenever the garbage collector is enabled or disabled, it can be called manually. Simply calling (gc) triggers the garbage collector:

    (let total (gc))
    (print "Number of gargabe collected: " total "\n")
    


    In the example below, a list of 1,2,...,1000000 created and referenced by a variable 'a'. Then a is set to NULL and generated garbage is collected manually.

    (gc off)
    (let limit 1000000)
    (print "Creating array of 0..." limit "\n")
    (let a (: 0 limit))
    (print "Array created with length " (length a) "\n")
    (dump)
    (let a NULL)
    (print "Gargabe Collecting manually:\n")
    (gc)
    (dump)
    


    The output is

    Creating array of 0...1000000
    Array created with length 1000001
    Environment Deep: 0
    # Sub Environments: 0
    # Tokens 1000054
    Gargabe Collecting manually:
    Environment Deep: 0
    # Sub Environments: 0
    # Tokens 67


     In the example above, there are 1000054 garbage objects before manual garbage collection. After garbage collecting, there are 67 objects which includes the source code itself. It was a nice experiment to implement a garbage collector in Fuzuli. Hope you have fun with it!

    Sunday, July 29, 2012

    How to Change Main/Start Screen on Android?

    Hello! As you known, there is nothing to say about developing  and progressive Android all around the world. In this situation, we can find any idea to make application. Actually, this is not so easy :) Namely what I am trying to say is that Android provides us to create applications and be a developer in mobile world.

    I am sure that most of us have played a game via our mobile phones. Things I said above were for any application actually. Because, games, software about educations, politics, health education, voluntariness, etc applications  allow Android skills.

    If you want to create an application to be used by everyone (this is very assertive :) ), you have to be different than other apps. This difference should be about design, software or your idea. 

    In this article, I'll show you some codes about tiny difference, "starting page" on your Android application.

    I want to tell you about my mind. Users download your app and install it on the phone. The next step will be starting your application. This step is so important. Because, people who use the app decide how good the app is. For that reason, how to start the app should be very important for us. In this context, I can start to code about this.

    I've got two classes: Main.java and startingPage.java

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.startingPagexml);
            
            Thread MyScreen = new Thread() {
             public void run() {
              try {
               sleep(5000);
         
               startActivity(new Intent(getApplicationContext(),startingPage.class));
              } catch (InterruptedException e) {
               e.printStackTrace();
              }
              finally {
               finish();
              }
             }
            };
            MyScreen.start();
        }
    


    The code given above is the first page will be opened on the app. Thread "MyScreen" helps to go another page. When the app opened, wait 5 second and go to the startingPage.class. startingPage.class includes startingPagexml.xml Android Xml file. This file calls the page after 5 seconds.


    public class acilis2 extends Activity {
    
     public void onCreate(Bundle savedInstanceState) {
      Toast.makeText(this, "Welcome to My Application", Toast.LENGTH_LONG).show();
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
     }
    


    Toast.makeText(this, "Welcome to My Application", Toast.LENGTH_LONG).show();
    


    This code introduces how to give user message after 5 second. If you want to see and learn more information about Toast notification, you can visit android developer official guide in here.


    See you next article!

    Thursday, July 19, 2012

    Multithreading in Fuzuli Programming Language

    Since our last commit, Fuzuli supports multithreading. This is the latest milestone that Fuzuli reached in revision tree of 0.1.x.

    Fuzuli's multithreading capability stands on the well known boost threading library which will be a built-in package in next C++ standard.

    Creating and running a thread in Fuzuli is easy. Define a function and create a thread for this function then call the thread_join method. The join method will wait until the function finishes its job. More than one threads can run at the same time in a time-sharing manner. Multithreading functions are stored thread.nfl, which is now a standard in Fuzuli API.

    Lets give an example:


    (require "/usr/lib/fuzuli/nfl/thread.nfl")
    
    (function f (params)
     (block
      (print "F started\n")
      (foreach i in (: 1 10)
       (print "f\n")
       (thread_yield)
       (thread_sleep 100)
      )
      (return 0)
     )
    )
    
    (function g (params)
     (block
      (print "G started\n")
      (foreach i in (: 1 10)
       (print "g\n")
       (thread_yield)
       (thread_sleep 100)
      )
      (return 0)
     )
    )
    
    (function h (params)
     (block
      (print "H started\n")
      (foreach i in (: 1 10)
       (print "h\n")
       (thread_yield)
       (thread_sleep 100)
      )
      (return 0)
     )
    )
    
    (let t0 (thread "f"))
    (let t1 (thread "h"))
    (let t2 (thread "g"))
    
    (thread_join t0)
    
    
    
    In the example given above, we have three function f(), g() and h(). Those functions print messages "F started", "G started" and "H started" at the top of their bodies. A foreach loop then count from 1 to 10 and wait 100 milliseconds after each step. The output is shown below:

    F started
    H started
    G started
    g
    h
    f
    g
    h
    f
    g
    h
    f
    g
    h
    f
    g
    h
    f
    f
    g
    h
    f
    h
    g
    g
    f
    h
    g
    h
    f
    f
    g
    h

    Functions in this example run simultaneously. thread_join was called on t0, so whenever the function f() finishes its job, program ends. thread_yield is called for giving a chance to run to another threads. thread_sleep waits for given milliseconds if needed.That's all.


    Sunday, June 17, 2012

    Getting Contents of a DIV With PHP's DOM

    Hi! Almost all of us use XML in our web sites. We can get contents with parsing XML files. But sometimes, we need another ways. The reason of this is that we want to get only one dom's content. For example an img element's content or it's value of id


    Well, I will introduce how to get contents of element in this article. That's why I'll show you the sample given belown.


    For my example, I got two files here:
    1. GetContent.php
    2. test.html
    GetContent.php
    <?php
    $content="test.html";
    $source=new DOMdocument();
    $source->loadHTMLFile($content);
    $path=new DOMXpath($source);
    $dom=$path->query("*/div[@id='test']");
    if (!$dom==0) {
       foreach ($dom as $dom) {
          print "<br>The Type of the element is: ". $dom->nodeName. "<br><b><pre><code>";
          $getContent = $dom->childNodes;
          foreach ($getContent as $attr) {
             print $attr->nodeValue. "</code></pre></b>";
          }
       }
    }
    ?>
    
    So, If you analyze the sample given above, you can see the point easily. The point is the content of div element which is id=test. The reason of existing test.html page is to get div's content.

    test.html
    <div id="test">This is my content</div>
    

    What we have just seen up there, should be like on this demo page.

    The Type of the element is: div
    This is my content
    

    The result is the text above. We'll see you guys next article!

    Saturday, June 16, 2012

    List Operations in Fuzuli Programming Language

    Fuzuli, our new programming language and interpreter has several internal functions for list operations. Arrays are prominent objects of programming languages. Although many other programming languages use brackets for setting and getting values of array, this operator is not defined in Fuzuli. Lists are similar to Lisp's lists but they are different. As we said before, Fuzuli is neither a Lisp nor an Algol family, but it is something like a combination of them.
    Any one dimensional Fuzuli list can be created using the list keyword. This keyword corresponds to internal ListExpression and can take infinite number of parameters to hold. An example for use of list keyword is given below:

    (let a (list 12 3 4 5 "Hello" 5 4 2 10 2.13))

    In the code above, a is list of elements 12, 3, 4, 5, "Hello", 5, 4, 2, 10, and 2.13, respectively. As we can see, the list a can hold elements from any type.

    The keyword nth corresponds to the function nth for accessing elements using their indices. An example for use of nth is given below:

    (let element (nth a 4))

    The variable element now holds the value "Hello" because it has the indices of 4. Note that the index of first elements is zero. 4th element of list a can be changes as

    (set a 4 "Fuzuli")

    and variable a contains these elements:

    12 3 4 5 "Fuzuli" 5 4 2 10 2.13


    Lists can be constructed automatically in an increasing manner from an integer a to integer b. The code shown below is for creating a list from 1 to 1000:

    (let biglist (: 1 1000))

     Ok! We borrowed this command from R because it is very nice and easy! Let's get the length of this list:

    (let mylen (length biglist))

    and mylen carries the value of 1000, the number of elements contained by biglist. One may need to append or prepend elements to lists. For those, we have append and prepend keywords for appending and prepending.

    # Creating a list
    (let mylist (list 1 2 3 4 5 6))

    # Appending 7 to the end of mylist
    (append mylist 7)

    # Put a zero at the beginning
    (prepend mylist 0)

    # Print out the list
    (print mylist)

    The output is

    [0, 1, 2, 3, 4, 5, 6, 7]

    Well! How about removing elements? Lets remove the "4" from this list:

    # Removing 4
    (remove mylist 4)

    The output is

    [0, 1, 2, 3, 5, 6, 7]

    There is also a find keyword for determining location of a given element in a list. Look at the code:

    (let mylist (list "Jan" "Jun" "Aug" "Sep"))
    (let index (find mylist "Jun"))
    (print index)


    The output is 1 because "Jun" has the index of 1 in array mylist.

    There are extra functions in utils.nfl package for list operations. Those functions are not built-in but shipped within Fuzuli. Current utils.nfl package contains shuffle, sorta and sortb functions for mixing, ascending sorting and descending sorting of elements of a given list.

    Another important point of Fuzuli lists is multi-dimensionality. We mentioned that Fuzuli lists can contain any type of objects. These object can exactly be an other list! And those list can take lists as their elements and so on... Let's create a 2x2 matrix of elements.

    (let matrix
        (list
            (list 1 2)
            (list 3 4)
        )
    )

    (print matrix)

    The output is


    [[1, 2], [3, 4]]

    The matrix given below has a dimension of 3x5:

    (let matrix
        (list
            (list 1 2 3 4 5)
            (list 6 7 8 9 10)
            (list 11 12 13 14 15)
        )
    )

    (print matrix)

    The output is

    [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

    Accessing elements of multi-dimensional lists is easy! Follow the code:

    (let matrix
        (list
            (list 1 2 3 4 5)
            (list 6 7 8 9 10)
            (list 11 12 13 14 15)
        )
    )

    (print (nth (nth matrix 0) 0) "\n")
    (print (nth (nth matrix 1) 3) "\n")
    (print (nth (nth matrix 2) 3) "\n")
    (print (nth (nth matrix 2) 4) "\n")


    The output is

    1
    9
    14
    15


    becase matrix[0][0] is 1, matrix[1][3] is 9, matrix[2][3] is 14 and matrix[2][4] is 15 in C or Java notation.

    Have fun with Fuzuli lists!







    Sorting data with Fuzuli

    In this article, I want to show how to sort data vectors using Bubble sort and Quick sort. Bubble sort is known to be one of the most in-efficient sorting algorithms. Quick sort has lower order of magnitude and it is known to be the most efficient one. There are tons of articles about these algorithms around the Internet and I don't want to give a detailed description and comparison of them.


    Let me show how to write them in Fuzuli.



    Bubble Sort in Fuzuli:


    (def mylist LIST)
    (let mylist (list 5 6 4 2 3 9 1 10 5))
    
    (print "Original List:\n")
    (print mylist "\n")
    
    (for (let i 0) (< i (length mylist)) (inc i)
        (for (let j (clone i)) (< j (length mylist)) (inc j)
            (if (> (nth mylist i) (nth mylist j))
                (block
                (let temp (nth mylist i))
                (set mylist i (nth mylist j))
                (set mylist j temp)
                )
            )
        )
    )
    
    (print "After sorting:\n")
    (print mylist "\n")
    


    The output is :

    Original List:
    [5, 6, 4, 2, 3, 9, 1, 10, 5]

    After sorting:
    [1, 2, 3, 4, 5, 5, 6, 9, 10] 

     The code is similar to one written in both Lisp, C or Java! Hope the taste of code is good for you. Next one is the Quick sort:

    Quick Sort in Fuzuli:


    (def mylist LIST)
    (let mylist (list 5 6 4 2 3 9 1 10 5))
    
    (print "Original List:\n")
    (print mylist "\n")
    
    
    
    (function partition (params arr left right)
     (block
      (def i INTEGER) (def j INTEGER)(def tmp INTEGER)
      (def pivot INTEGER)
      (let i (clone left)) (let j (clone right))
      
      (let pivot (nth arr (/ (+ left right) 2)))
      
    
      (while (<= i  j)
       (block
                 (while (< (nth arr i) pivot)(inc i))
                    (while (> (nth arr j) pivot) (-- j)) 
           (if (<= i  j) 
         (block
                (let tmp  (nth arr i)) 
                   (set arr i (nth arr j))
                   (set arr j  tmp)
                   (++ i)
                   (-- j)
            )
        )
       )
      )
      (return i)
     )
    )
    
    
    (function quicksort (params arr left right) 
     (block
      (def index INTEGER)
      (let index (partition arr left right))
      (if (< left  (- index 1))
         (block
                 (quicksort arr left  (- index 1))
       )
      )
    
           (if (< index right)
       (block
                 (quicksort arr  index  right)
       )
      )
     )
    )
    
    (quicksort mylist 0 (- (length mylist) 1))
    (print "After sorting:\n")
    (print mylist "\n")
    


    The output is :

    Original List:
    [5, 6, 4, 2, 3, 9, 1, 10, 5]

    After sorting:
    [1, 2, 3, 4, 5, 5, 6, 9, 10]

    which is the same for bubble sort but the latter is faster.

    Hope you like the code. See you next!