Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, December 5, 2013

Insertion Sort in Different Flavors

NOTE: Blog moved to Wordpress. Click here for latest posts and more cool stuffs.


Been revving up algorithms for my job hunt. Thought, I should share some. Here's Insertion Sort, in Ruby, Java and C.
It has a Worst and Average Case Scenario Complexity of Theta(n^2) (or Theta n-squared). It is efficient for smaller data sets while larger data sets would require a lot of time for sorting.
Oh! I've also been dabbling in the art of Ruby Programming.
I find the language a lot more neat and simpler than my previously known languages - C and Java. The best thing is that with multiple syntax possibility, I can quickly code in free flow without the need to frequently check and recheck whetehr I'm sticking to the syntax rules to express my thoughts.
This is one of the features of ruby to have multiple syntax rules for the same task, incorporated from C, Python, Small-Talk, Java and more. This makes it easy to learn and apply.
Without further delay, here's the algorithm;

INSERTION SORT (PSEUDO-CODE)

A = [1,5,3,7,6,2,8,9,10,4]
print "Initial Array Order " + A
for j = 1 to A.length
{
i = j-1
key = A[j]
while i>=0 && A[i]>key
{
A[i+1] = A[i]
i = i-1
}
A[i+1] = key
}
print "Sorted Array Order "+ A
OUTPUT>> [1,2,3,4,5,6,7,8,9,10]
Note: The above algorithm assumes a Zero indexing for the Array. For One indexed Arrays, alter the for loop to -
"for j = 2 to A.length"
and alter the while loop to -
"while i>0 && A[i]>key"
Now, Insertion Sort in Ruby;

INSERTION SORT (RUBY)

A = [1,5,3,7,6,2,8,9,10,4]
p "Initial Array Order"
p A
for j in 1...A.length
i = j-1;
key = A[j];
while i>=0 && A[i]>key
A[i+1] = A[i];
i = i-1;
end
A[i+1] = key;
end
p "Sorted Array Order"
p A

Here's the screen shot of the running Ruby program:

ruby Insertion Sort

InsertionSort (Java)

public class InsertionSorting
{
public static void main( String[] args )
{
int A[] = { 10, 9, 5, 7, 3, 1 };
System.out.printf("\nInitial Array:\n");
for( int k=0;  k<A.length;  k++)
{
System.out.printf( "%d, ", A[k]);
}
for( int j=1;  j<A.length;  j++)
{
int i = j-1;
int key = A[j];
while((i>=0)&&(A[i]>key))
{
A[i+1] = A[i];
i=i-1;
}
A[i+1] = key;
}
System.out.println("\nFinal Array:");
for( int k=0;  k<A.length;  k++)
{
System.out.printf("%d, ",A[k]);
}
}
}

Here's the screen shot of the running Java program:

InsertionSort Java Capture
Java program run in Netbeans IDE.

INSERTION SORT (C)

//Insertion Sort
void main()
{
int A[6] = { 10, 5, 7, 3, 4, 1 };
printf("\nInitial Array\n");
for ( int l=0;  l<6;  l++)
{
printf("%d\n", A[l]);
}
int j =0;
for( j=1;  j<6;  j++)
{
int i = j-1;
int key = A[j];
while((i>=0)&&(A[i]>key))
{
A[i+1] = A[i];
i=i-1;
}
A[i+1] = key;
}
printf("\nFinal Array\n");
for (int k=0; k<6; k++)
{
printf("%d\n", A[k]);
}
getch();
}

Here's the screen shot of the running C program:

tcc Insertion Sort
[C Program compiled with TCC.]
Hey! It's a nice idea to code the same stuff in C, Java and Ruby. Next time onward I'll try to post programs in all three languages. Not entire applications, though, it gets tedious when the program runs long.
Next hopefully should be Data Structures Stack and Queue, or Merge Sort. Lets see. Till then, adios!
PS: Attached Ruby, Java and C files. [LINK]

Friday, September 20, 2013

A simple way to send your mails in Java; Java Mail API

I had played around with Java Mail API last year for a competition (while I was in college) where my team was assigned to build a system which would send bulk mail customized by the sender to a list of recipents as per their age and gender. I built the core messaging system in fifteen minutes or so, thanks to Java Mail!

Though Java Mail is said to be more complicated and low-level than any (most) other Java APIs around. I found sending a simple email pretty easy.

The entire source code (which is comfortably small) can be divided into specific part;

1) Properties of E-Mail Service:

Here, I've setup the properties initializing them in the Properties object - java.util.Properties, provided by the Utility Class - java.util.

        Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
                   "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

2) Starting the Session by logging in using the Authenticator from JavaMail.

          Session session = Session.getDefaultInstanc (props,new  javax.mail.Authenticator()
            {protected PasswordAuthentication getPasswordAuthentication()
             {
                 return new PasswordAuthentication(target_email,password);
             }
            }
        );

Here, you'll need to enter your EMail service provider Username (with the postfix @yourhost.com) and the password. I used a Class attribute to keep the password, sender email ID and the recipents email address.

    public static String password = "mypassword";
    public static String sender_email = "iam.legend.n@gmail.com";
    public static String recipent_email = "md.naseem.ashraf@gmail.com";

A better way of fashioning this code is by setting up these attributes as private and keeping an Arraylist of recipent's email address which would be fetched, altered and mainteained separately.

3) Sending the MIME Message (the actual E-Mail message):


try {
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(sender_email));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(reciever_email));

        message.setSubject("EMail Subject!!");

        message.setText("Congratulations!!" +
                        "\nYour EMail has been successfuly recieved by this EMail client.");

        Transport.send(message);
        System.out.println("Message Sent!!");       
        }

        catch (MessagingException e)
        {
                throw new RuntimeException(e);               
        }

This block of code is self-explanatory. Some specific options I'd like to talk about, required to customize our E-Mails are:

1. message.addHeader(String ....)

Useful to add headers to E-Mails which are used by E-Mail Clients to sort, classify and identify emails. This is pretty useful now a days with GMail's new layout where E-Mails are classified as Standard, Social (Group, Mailing Lists etc) and Promotions (Advertisements) under respective tabs.

Though I'm finding it annoying in the new layout to open multiple emails simultaneously in separate tabs. Thus, I stick to basic HTML layout which has the plus point of being super fast.

2. Message.RecipientType.XX - You can set, TO (To a single prime recipient), CC (Carbon Copies) and BCC (Blind Carbon Copies) in the Recipient Type.

Example:

message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(reciever_email));

message.setRecipients(Message.RecipientType.CC,InternetAddress.parse(another_email));

3. message.setFrom(X) - You can also set the sender email address specifically in the mail even though it will be identified by the EMail client.

Example:

message.setFrom(new InternetAddress(sender_email));

Note that the string sender_email usage with InternetAddress.

CONGRATULATIONS!!


You've setup your Java program to send E-Mails. Some of the ways you can put added functionalities would be by creating a good String creation method which would arrange the message text and then add to "message.setText(...)" method.

I'll be soon studying about recieving and processing E-mail with JavaMail. Will blog about it later.

ADDENDUM:

Source code is added here -
https://docs.google.com/file/d/0B4e1TZA7mwrNV01rTDBrQVluc3M/edit?usp=sharing

Saturday, August 17, 2013

NexusGrapher2: An exploration deeper into the JUNGle

I've recently got a lot of free time on my hands and thus decided to upgrade my previous tool; NexusGrapher [Note: Previous work with JUNG is linked here] by utilizing the large set of features provided by JUNG2.0 (Java Universal Graph/Network Framework) and adding some more features to it's data handling capabilities. Earlier it only used to draw Graphs of data stored as CSVs (Comma Separated Values) in text files.

Features of NexusGrapher2

  • "Graph Themes" to use predefined graph visualization attributes for different color, shape and sizes of vertices.
  • "Data type Discriminant" feature which let's user's customize different vertex shapes for numbers, strings etc for graph elements.
  • "Multiple Layout" facility from which user can choose a certain layout to display his graph in.
  • A "Query Engine" which will process data from text files, CSVs etc and return a Graph visualization of the query. [wip = work in progress]
  • The Query Engine will also be usable to make graphs directly with small instructions/commands. [wip]
  • Graph Image and Data saving facility as well as ability to read saved Graph data to rebuild graphs. (I know using GraphML will ease the task exponentially but it deals with bulky XML formats).[wip]
  • "Graph Comparator"; A feature to facilitate comparison of two graphs and also a facility to plot graphs with changing data-sets/attributes in order to be overlapped and observed for differences. Another useful additional feature would be to merge different Graphs and alter graphs (elements, vertices, relations, vertex attributes etc.).[wip]
 Here are the screen-shots.of some themes I have coded into the source code. If you wish to contribute to this project do send me an e-mail regarding it.

Screen Shots:

"Happy" Theme


 "Gotham Theme"


"Tech_Noir"  Theme



Reference:

Monday, July 15, 2013

Javadoc: The Bible of Your Java Source Code

Today I'll be sermonizing on Java, my dear readers. I have observed since I began learning Java in my third semester of Computer Science Engineering undergraduate course that comments are a vital part of a program or rather the source code. But, never were we taught about good commenting standards and commenting conventions. Also, our exposure to the Javadocs was minimal. Our only interaction with the Javadoc was when the IDE (Netbeans or Eclipse or any other) would produce a small popup window with a summary about the keyword over which our mouse pointer was hovering.

It fills me with sadness that such vital skills of reading, navigating, understanding and producing Javadocs was never taught or even appreciated. Like some unspoken truth, we all kept mum and so did our teachers, that we’ll eventually learn it “on the job” or “later in life”. I seriously doubt about the many Indian, so called, software professionals knowledge on how to comment code correctly and generate usable Javadocs or read other programmer’s Javadocs. Any Java programmer worth his salt must have this essential skill of playing around with the Javadocs.

There are various commenting styles in the art of programming each style has a certain aim in mind. Some of the commenting styles can be roughly categorized as:
  • Explanatory/Verbose Commenting – Used by experts, teachers and trainers to explain in detail what each line of the code does. It is generally regarded as “How?” themed commenting. It is also used when a complicated piece of algorithm is implemented which cannot be understood without certain explanatory aid. This style is generally picked up by students from their teachers, but, is not good for day to day professional use. Most of what any programmer will code in life will be simple and easy to understand without any comments. The best code is self-explanatory without necessitating a single line of code.
  • Reasoning/Terse Commenting – Used by professionals in day to day coding, it involves adding comments only when a certain part of the code is not self-explanatory and departs from the ordinary trend of coding. For example the forking of a certain thread to handle background tasks etc. It is generally regarded as “Why?” themed commenting. In other words it is a minimalist approach to commenting. You comment only when it is most required.
  • Documentation CommentingUsed to generate documents or guide other programmers using your source-code either as an API or a Legacy code. It may detail hardware and software dependencies, performance issues, code vulnerability (Yeah, you’ll find in some legacy codes useless warning comments such as, “//DON’T TOUCH THIS CODE! EVERYTHING WILL BREAK. TALK TO BOB BEFORE EDITING THIS CLASS”, where Bob is someone who has left the company 15 years ago. Good luck with that, mate.) This commenting style is best seen in Open Source APIs, where you can seek help from Open Source communities which may take a longer time to resolve your issues and even third party licenced APIs, though they provide a paid support service to resolve your issues in the least time possible.
Note: No adherence to a single style is requisite. Often, a mix of all styles will be required to deliver a useable and malleable source-code.

Javadocs, ahoy!!

 

Javadoc is a documentation generator from Oracle Corporation for generating API documentation in HTML format from Java source code. (Yes. This line is ripped off from Wikipedia. Now, please, don’t label me as a plagiarist.)

Javadoc handles only a specific format of commenting within the Java source codes. It can be either generated by using the pre-bundled javadoc tool with the JDK or invoking it via any Java compatible IDE (I’ll be sticking with Eclipse in this blog. Go to hell, Netbeans! *Just joking! I know how many of you still depend on it and I can empathize with you.*).

I’ve attached the source-code of a simple java program (which I did not care to test run even once. Don’t bother compiling and running it. Our focus should be on commenting for Javadoc.) with screen shots of generating and using the related Javadocs of this project. [The screen-shots are available here only, as my paid internet data usage quota has expired and I am currently blogging at the speed of 3~4 Kbps. I promise to update the bundled project with screen shots after I get my internet connection recharged which is looking doubtful considering I have already paid for the recharge and the confirmation SMS or transaction SMS has not yet been received since today morning 8 AM or so.]

Now, let’s see. Step 1:

Select the Element you want to comment on. Like in the above screen grab, I’ve selected method Circle from class FigureStore.

 

Step 2:

Select the Generate Element Comment option from the drop down menu of Source button from the main menu.



Step 3:

Eclipse auto-generates the comments depending on the selected element. As here the selected method Circle has two parameters, the Radius as X and the Diameter as Y.


Step 4:

Now, edit the element comment as required. Try adding details as briefly as possible.

Step 5:

After you’ve added all the element comments you need to generate the Javadoc. For generating the Javadoc for your project, select it in the package explorer and the choose Generate Javadoc from the Project option in the main menu.

Step 6:


Now, you’ll see a dialog as shown in the above image. Make sure your project is selected as well as all of its components. The Javadoc tool is selected via the Configure button. The Javadoc tool is present in the “bin” directory of the JDK. Also, set the path of your doclet to a new “doc” directory of your project.


Step 7:

You can add a specific document title to your doclet and you may add any referenced/dependent jars and packages which mainly comprise of the JDK libraries. Then select Finish. (Yes, I don’t go any further with that alluring “Next” button.)



Step 8:

Now, sit back and relax for a few moments while the Javadoc is being generated. The time take for Javadoc generation is dependent on the number of Elemental Comments, program size, structure etc. Your Console should show something like this:

 


Alternate Method:


Here’s an alternate method to generate Javadocs. Right click on your project in the Package Explorer. Select “Export” from the drop down menu and a dialog will appear as shown below.

Select Javadoc from the Java directory and Bam! It’s done (It’ll take you to the Javadoc Generaton Dialog). 

What to expect from Javadocs?

You’ll see a new directory under your Project in your Package Explorer called “doc”. Exanded it’ll look like this;

The “index” html file is the start or main page of your Javadoc. Double click on it to open it inside Eclipse. A sample Javadoc is shown below;

 



Also, now you’ll be able to invoke small popup help windows for your project/package which can be used in other projects as well if the Javadoc is imported in there Project directories.
 

IMPORTANT END NOTE:
A good habit is to keep on making Element Comments while programming in order to keep the burden of commenting low. Once the size of the source code gets out of hand commenting becomes difficult and you’ll not be able to leverage the Javadoc prompts for other parts of your source-code.

Also, one must always try to keep deprecated (i.e discontinued) methods in future iterations and newer versions of the program/package in order to maintain backward compatibility.”

Sample Documents and Source Codes::

My Experiments with JUNG 2.0 (Java Universal Network/Graph Framework)

My first minor project was a major disaster. But, in hindsight I can salvage out some simple nifty tools from the graveyard of codes on my laptop. I had to settle for a simple "Simpletron: A Simulated Microprocessor in Java." (I've blogged about it earlier here.) All it took was firing one of our three team members and the remaining duo pair-programmed into the night.....or at least for a few hours until he too quit and went away to see a movie. We ended up showing this little nifty tool and anther tool which Chitransh had designed to go together with this one. I then finally completed and perfected Simpletron on my own.

Nexus Grapher was a tool to be added to a data-mining project which we failed to complete due to broken team dynamics and interaction, as well as, pressing deadlines. I coded this small tool from Open Source, JUNG 2.0 API. That's "Java Universal Network/Graph Framework" Version 2.0.

This project had a lot of potential and planned features that were never realized. Nexus - as we named it, was supposed to be a suite of various data mining tools which can be used on a directory full of web-pages (preferably from Wikipedia & news-sites) and text files etc documents.

Initially we planned to adopt Stanford NLP Parser to perform NER tagging (Named Entity Recognition - This link is a Wikipedia page). This would produce a Penn-treebank structure which would be parsed by a method of my nexus-grapher to generate a visible, click able, interactive graph of inter-relating facts and texts from across the webpages and texts saved in the directory.

Selecting a node with the label of a named entity would invoke another method that I wrote with my team-mate Harshdeep Sokhey which will open a window displaying a consolidated text file with (that label) related texts collected from all over the mined directory. (Like a dynamically generated Wikipedia page).

But, this consolidation and compaction method was in it's nascent state without much intelligent features of context aware auto-data updates (on comparison with recent file save) and even basic features like text-redundancy. All it could do was get paragraphs and lines, consisting of the keywords, from all over the directory and order them by file creation date.

The connecting edges of the graph was also meant to be click able to pull up a consolidated file with paragraphs of texts where both these named entities would appear simultaneously. Another feature we failed to implement. I tried switching to Apache Lucene but due to approaching dead-line I didn't have enough time to learn Lucene.

Currently, the nexus-grapher reads from a CSV of preselected named entities to generate the graph.

If you want to know more of my plans for "Nexus: An interactive data-mining & visualization suite." send me an email. If you're able to implement such a suite, very well, do inform me.

Directions/Code Walk through::
--------------------------------

This small tool is built with open source JUNG 2.0. My knowledge and expertise with it is... limited. If you encounter any troubles and have questions relating the graph and its subsequent visualization, please contact them. Here's a tutorial of JUNG 2.0, as a PDF, which I found handy and it should be enough for the Java noob to get his feet wet.


Before I get into the details of my Java project, let's first go over the basics of my C.S.V formatting and rules for, what I call, "nexusft"; nexus-format-textfile.

The first token of the C.S.V is the available roots that can be searched and all other succeeding tokens are it's children.

Now, onto Java! The project package is split into three classes:

1) naseemgraphexp2.java
2) ReadFile.java
3) search.java

"naseemgraphexp2.java" is the core class with a Main  method to run a simple graph visualization. The code is self-explanatory with comments.

A name (search-token) is sought from the user when the program runs and calls the readnexus() method. The searched nexusft file address is passed as a parameter for the class ReadFile.

This ReadFile returns the arraylist of lines of texts in the nexusft file which is tokenized and searched against the entered keywords. Only the first token of the C.S.V (if matched) is considered the root and all others are considered children. Else the method returns an error message.

The constructor method "naseemgraphexp2()" is where my iterative loop adds the tokens as vertices and their names as labels. Only the searched central/root node of the graph is connected to its relatives.

The rest of the code in the Main method is self-explanatory and JUNG specific, to build a graph and visualize it. The geniuses behind JUNG kept very clean and clear examples for me to hack with my shoddy programming skills. I've left behind some original code of JUNG examples, which has been commented, I know it's bad practice (I read in one of them, Pragmatic Programmer/Publishers book), but, it is there for all those who are new to JUNG 2.0, to see and realize the available features I did not use.

"ReadFile.java" is a straight forward file reading program to read and add each line of text into a String[] array which is returned to the calling method in naseemgraphexp2.java.

Finally, in "search.java" is the small program to tokenize each string that we previously stored in our String[] array to be matched with our search token. If a match is found, then a true Boolean is returned to  nexusgraphexp2.java's method "readnexus()" which then proceeds to tokenize this string to create nodes for the graph.

I hope, you find it useful despite this poor hacking. If you polish it and go onto implementing better features do e-mail me and credit me for this shoddy hack.

Your,
Md.Naseem Ashraf
iam.legend.n@gmail.com

Source Available at:


https://docs.google.com/file/d/0B4e1TZA7mwrNVTYyTk9fOGVuT1E/edit?usp=sharing

Screen Shot:

 

 

 

Creative Commons License

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 United States License.