Monday, September 5, 2016

Bubble Sort Analysis

In this post I wanted to put down the information I have gathered from the analysis of Bubble sort.

Java program used:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Random;
import java.util.Scanner;

public class Class1 {

 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  int n=scanner.nextInt();
  int[] arr=new int[n];
  Random random = new Random();
  for (int i=0;i<n;i++) arr[i]=random.nextInt(n);
  scanner.close();
  long startTime = System.nanoTime();
  for (int i=0;i<arr.length;i++) {
   boolean flag=false;
   for (int j=0;j<arr.length-i-1;j++){
    if (arr[j]>arr[j+1]){
     int temp=arr[j];
     arr[j]=arr[j+1];
     arr[j+1]=temp;
     flag=true;
    }
   }
   if (!flag) break;
  }
  System.out.println("time taken: "+(double)((System.nanoTime()-startTime))/1000000000);
 }

}

In the above program, I have only considered the start time as the one just before the sorting started and the end time likewise.

Data:


Record count
Time taken in seconds
199
0.001364608
699
0.010424671
999
0.013886809
3999
0.03367852
6999
0.094484978
9999
0.20464032
39999
2.708212326
49999
4.271805616
99999
17.222403548
399999
299.15396555

Graph:






















The following graph plotted takes the function O(n^2).

Bubble sort has the worst case and average case complexity of O(n^2).

Source: Bubble Sort Wiki

Please do comment on any discrepancy in my analysis.

Sunday, March 13, 2016

JQuery with XSLT

I have been trying some XML transformation with XSLT and as I saw the XML can be transformed into HTML, I thought why not include JQuery into the transformation that I am doing.

I took a sample XML, in XSL I included the HTML and javascript along with JQuery that I wanted.

XML to be transformed:

1
2
3
4
5
6
7
8
<?xml version="1.0"?>
 <root>
  <node_1>
   <element_1>Data of element 1</element_1>
   <element_2>Data of element 2</element_2>
   <element_3>Data of element 3</element_3>
  </node_1>
 </root>

XSL used to transform the above XML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
 <xsl:template match="/">
 
  <html>
   <head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
     $(document).ready(
     $(function() {
      $("#root").accordion();
     }));
    </script>
   </head>
   <body style="background-color:red;">
   <h1 style="text-align:center;color:white;">JQuery accordion</h1>
    <div id="root">
     <xsl:for-each select="/root/node_1/*">
     <xsl:variable name="counter" select="position()" />
      <h6><xsl:value-of select="concat('Step No.',$counter)"/></h6>
      <div>
       <p><xsl:value-of select="."/></p>
       <textarea rows="4" cols="100"></textarea>
      </div>
     </xsl:for-each>
    </div>
    
   </body>
  </html>
 </xsl:template>
</xsl:stylesheet>

In the above XSL transformation, I included the JQuery CDNs and javascript code to make the accordion available and I used a counter variable to dynamically name the accordion steps.

In the XSL I am accessing and looping through node_1's child elements and using the data of the elements in each steps of the accordion.

For transformation I used a java code based on the javax.xml.transform package and it's classes.

Java code used to transform and generate HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.java;

import java.io.File;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XSLTest {

 public XSLTest() {

 }

 public static void main(String[] args) {
  TransformerFactory factory = TransformerFactory.newInstance();
  StreamSource xslStream = new StreamSource(new File(
    "demoXslFile1.xsl"));
  Transformer transformer;
  try {
   transformer = factory.newTransformer(xslStream);
   StreamSource in = new StreamSource(new File(
     "demoFile1.xml"));
   StreamResult out = new StreamResult(new File(
     "htmlFile1.html"));
   transformer.transform(in, out);
  } catch (TransformerConfigurationException e) {
   e.printStackTrace();
  } catch (TransformerException e) {
   e.printStackTrace();
  }
 }
}

I used transformer class to transform the XML input to HTML output using XSL transformation file.

The transform method of Transformer class takes StreamSource and StreamResult type variables as parameters.

StreamSource variable holds the xml source file.

StreamResult variable holds the final html file where the html has to be put into.

Another StreamSource instance variable holds xsl file.

The TransformerFactory class' instance variable holds reference to a fresh object. The variable then can be used to call newTransformer method which takes xsl file's StreamSource variable as method paramter.

The Transformer class' instance variable references the above.

XML transformed into HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script><script>
   $(document).ready(
    $(function() {
     $("#root").accordion();
   }));
  </script>
 </head>
 <body style="background-color:red;">
  <h1 style="text-align:center;color:white;">JQuery accordion</h1>
  <div id="root">
   <h6>Step No.1</h6>
   <div>
    <p>Data of element 1</p>
    <textarea rows="4" cols="100"></textarea>
   </div>
   <h6>Step No.2</h6>
   <div>
    <p>Data of element 2</p>
    <textarea rows="4" cols="100"></textarea>
   </div>
   <h6>Step No.3</h6>
   <div>
    <p>Data of element 3</p>
    <textarea rows="4" cols="100"></textarea>
   </div>
  </div>
 </body>
</html>

HTML rendering:



Applications of XSLT are just awesome, ability to transform the XML data into a structured format is just amazing.

Sunday, January 31, 2016

Sending text email from Java using Apache Commons Email

In this post, I wanted to show how to send an email using Apache Commons Email.

In this post I wanted to cover:
  • The program written in Java to send emails.
  • Challenges that I faced when sending emails.

Things one requires:

  • Eclipse.
  • Java.
  • Apache Commons Email library.
  • Two Gmail accounts (One acts as from address and one as to address) or One Gmail account (From and to address).

Apache Commons Email library can be downloaded from here: Apache Commons Email.

Configuration necessary in Eclipse before writing java program using Apache Commons Email library.

Create a Java project.
Right click on the project and choose properties.
In the properties choose Java Build Path and in Libraries tab click the button Add External Jars button on the right side.

Choose the jar that was downloaded from Apache website and add it.

Click OK and create a new Java class.

My Java class with Apache Commons Email code is as below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.java;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class ApacheMailSample {

 public static void main(String[] args) {
  Email email = new SimpleEmail();
  email.setHostName("smtp.gmail.com");
  email.setSmtpPort(465);
  email.setAuthenticator(new DefaultAuthenticator("<sender>@gmail.com", "<sendersPass>"));
  email.setSSLOnConnect(true);
  email.setStartTLSEnabled(true);
  email.setStartTLSRequired(true);
  try {
   email.setFrom("<sender>@gmail.com");
   email.setSubject("Test email from java program");
   email.addTo("<recipient>@gmail.com");
   email.send();
  } catch (EmailException e) {
   e.printStackTrace();
  }
 }

}

In the above code, I have created an object of class SimpleEmail.

I have set host to smtp.gmail.com, smtp port to 465.

To the DefaultAuthenticator's constructor I have passed Username (from address) and Password.

According to Google, the following has to be configured to send an email.


SMTP HOST: smtp.gmail.com

SMTPPORT: 587 (465 for SSL) 
USE SSL: Optional
SMTP Auth: Login



I have used port 465 in my java program and set SSL to true using method setSSLOnConnect.

I have set TLSEnabled to true using the methods setStartTLSEnabled and setStartTLSRequired.

Using methods setFrom, setSubject, addTo one can add from address, set subject of the email, set to address respectively.

One will have to send email using method send.

Challenges that I have faced:

  • Initially I was getting AuthenticationFailedException, on my google search I found out that we have to enable access to less secure apps on from email address at this link: Less Secure Apps Setting. I had to click turn on to let my java program access the email.
  • I have initially used smtp.googlemail.com and I was getting a message, couldn't connect to smtp host with response -1. After I changed the smtp host to smtp.gmail.com I was able to send emails.
  • Without having methods setStartTLSEnabled and setStartTLSRequired, I was getting the exception AuthenticationFailedException.


After I resolved the above errors, I was able to send email successfully from one email address to another (Gmail).

Sunday, November 29, 2015

Using JQuery to play a GIF on hovering the mouse over.

I used JQuery to implement the hover functionality.

The objective is to play a GIF image when the mouse is on the image and image should go static when the mouse is out of image area.

Once the mouse is out of the image area, the image goes static.

HTML + JQuery code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<html>
 <head>
  <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
 </head>
 <body>
  <img src="image_1_static.jpg" id="id1"/>
  <script>
   $(document).ready(function() {
    $("#id1").hover(
     function() {
      $(this).attr("src", "image_1.gif")
     }, function() {
      $(this).attr("src", "image_1_static.jpg")
     }
    );
   });
  </script>
 </body>
</html>


For achieving the above, I took a GIF (image_1.gif), opened the GIF in mspaint and saved it as jpeg/jpg image (image_1_static.jpg), now I have a static image and a GIF.

I took src for the img as the static image (image_1_static.jpg) and in the hover, I have written two functions one that accepts gif (image_1.gif) when mouse hovers over the img area and one that accepts jpeg/jpg (image_1_static.jpg) when mouse is out of img area.

This functionality can be very useful for creating menu icons in a website. When user places mouse over, icon plays.

Suggestions are well appreciated and happy learning.

Friday, November 27, 2015

Stack implementation in Python 3.5

Stack is a data structure that follows the LIFO model last in first out, the data that is inserted last will come out first.

Program for implementation of stack in Python:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
stack = []

stackLength = input("Specify the limit of the stack: ")


class Stack:
    def push(self, value):
        if len(stack) != int(stackLength):
            stack.append(value)
            return
        else:
            print("Stack is full !")
            return

    def pop(self):
        if len(stack)!= 0:
            stack.remove(stack[len(stack)-1])
            return
        else:
            print("Stack is empty")
            return

    def length(self):
        return len(stack)

stackClassInst = Stack()
stackClassInst.push(100)
stackClassInst.push(200)
stackClassInst.push(300)
stackClassInst.push(400)
stackClassInst.push(500)
stackClassInst.push(600)
stackClassInst.push(700)
stackClassInst.push(800)
stackClassInst.push(900)
stackClassInst.push(1000)
stackClassInst.push(1100)

print(stack)

lengthofstack = stackClassInst.length();

print(lengthofstack,": is the length of the stack")

stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();
stackClassInst.pop();

print(stack)

Firstly I took an empty array and I requested the input of stack's length using input.

Once I have input, once push method is called, I compared the length of stack array with the actual length from input.

If the length of the stack reaches the limit, stack is full message is printed.

Otherwise push continues and inserts data into the stack.

In pop, one can remove the elements from stack until it reaches the end of stack, once the end is reached, stack is empty message is printed.

The length method is used to calculate the length of the stack at any given time.

I enclosed push, pop and length methods into a class.

Output:


Specify the limit of the stack: 10
Stack is full !
[100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
10 : is the length of the stack
Stack is empty
[]

Process finished with exit code 0

Feel free to suggest on the post, happy learning.



Tuesday, November 17, 2015

Registration and login application using Express.js

In this post I am going to show how to create a simple registration and login form using Express.js, a web application framework of Node.js.

I used MySQL to store the data.

BCrypt module of Node.js to encrypt passwords.

Body-Parser module of Node.js to handle post parameters of Http requests.

Below is my Node.js code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// bcrypt
var bcrypt = require("bcrypt");

// body-parser
var bodyParser = require("body-parser");
var urlEncodedParser = bodyParser.urlencoded({extended: false});

// express
var express = require("express");
var app = express();

//mysql
var mysql = require("mysql");
// connect strings for mysql
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});

// connecting ......
connection.connect();

// requesting express to get data as text
app.use(bodyParser.text());

// using express for post method
app.post("/somePage", urlEncodedParser, function(request, response) {
 if(request.url!="/favicon.ico") {
  if(request.body.regOrLogin=="Register") {
   bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(request.body.pwd, salt, function(err, hash) {
     var body = request.body;
     var date = new Date();
     var currentDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
     var postVars = {username: body.username, password: hash, dob: body.dob, reg_date: currentDate};
     // insertion into MySQL
     connection.query("INSERT INTO REG_NODEJS set ?", postVars, function(err, result) {
      if(err) throw err;
     });
    });
   });
   console.log("user registered");
   response.sendFile( "/js/nodejs/folder1/regSuccess.html");
  } else if (request.body.regOrLogin=="Login") {
   var  body = request.body;
   console.log(body.username+": username");
   connection.query("SELECT * FROM REG_NODEJS WHERE username='"+body.username+"'", function(err, res, fields){
    if(err) { 
     response.sendFile( "/js/nodejs/folder1/unauthorised.html");
    } else {
     bcrypt.compare(body.pwd, res[0].password, function(err, res) {
      if(res) {
       console.log("authorised user");
       response.sendFile( "/js/nodejs/folder1/authorised.html");
      } else {
       console.log("not an authorised user");
       response.sendFile( "/js/nodejs/folder1/unauthorised.html");
      }
     });
    }
   });
  }
 }
});

app.listen(3000);

My HTML documents:

HTML for registration:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body { 
 font-family: 'Josefin Slab';
 font-size: 35px;
 color:white;
 background-color: #007a99;
}
table {
 font-size:30px;
 position:relative;
 bottom:-10px;
}
</style>
</head>
<body>
<center>
<h1>Register</h1>
<p>Enter your username and password</p>
<table>
<form action="http://localhost:3000/somePage" method="post">
<tr>
<td>Username</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>Date of birth:</td>
<td>
<input type="date" name="dob"/></td>
</td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit"value="Register" name="regOrLogin"/></td>
</tr>
</form>
</table>
</center>
</body>
</html>

Rendering:













Objective here is basically to let a user enter data in this form and once the user clicks Register, the data will be saved into MySQL database and a success HTML page along with Login form is shown.

Registration success and Login form HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body {
 font-family: "Josefin Slab";
 font-size: 35px;
 color: #cc9900;
 background-color: #00ff99;
}
.class1 {
 width:200px;
 height:30px; 
 border-radius: 60px;
 background-color: #ff3300;
 color: white;
 font-size:20px;
}
table {
 font-weight: bold;
 font-size: 25px;
}
p{
 font-weight: bold;
}
</style>
</head>
<body>
<center>
<h1>Registration Successful</h1>
<p>Login below</p>
<table>
<form action="http://localhost:3000/somePage" method="post">
<tr>
<td>Username: </td>
<td><input type="username" name="username"/></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" name="regOrLogin" class="class1"/>
</tr>
</form>
</table>
</center>
</body>
</html>

Rendering:












Once user enters data and clicks submit in registration form, one will be navigated to the registration success form, as shown above.

User can login with the credentials entered at the time of registration.

Upon entering correct credentials, the user will be navigated to the page which shows the user is an authorized one.

Login success HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body {
 font-family: "Josefin Slab";
 font-size: 45px;
 font-weight: bold;
 color: white;
 background-color: #9966ff;
}
h1 {
 position:relative;
 bottom:-50px;
}
</style>
</head>
<body>

</body>
<center>
<h1>voila un utilisateur autoris&#232;</h1>
</center>
</html>

Rendering:






If the user enters wrong password, user will be navigated to login failure HTML.

Login failure HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab">
<style>
body {
 font-family: "Josefin Slab";
 font-size: 45px;
 font-weight: bold;
 color: white;
 background-color: #ff0000;
}
h1 {
 position:relative;
 bottom:-50px;
}
</style>
</head>
<body>

</body>
<center>
<h1>pas un utilisateur autoris&#232;</h1>
</center>
</html>

Rendering:







The user gets the above message page when the login credentials are wrong.

Process:

User enters data into registration HTML as below and clicks Register button.













The request in the form goes to Node.js server and Node.js is written in Express here. It takes the post request and inserts the data into MySQL.

My Node.js code in Express that facilitates Registration and data insertion in MySQL:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
if(request.body.regOrLogin=="Register") {
   bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(request.body.pwd, salt, function(err, hash) {
     var body = request.body;
     var date = new Date();
     var currentDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
     var postVars = {username: body.username, password: hash, dob: body.dob, reg_date: currentDate};
     // insertion into MySQL
     connection.query("INSERT INTO REG_NODEJS set ?", postVars, function(err, result) {
      if(err) throw err;
     });
    });
   });
   console.log("user registered");
   response.sendFile( "/js/nodejs/folder1/regSuccess.html");
  }

In the above code I have used body-parser module to get username, password and date of birth from post request of registration HTML.

I used mysql module to insert data into MySQL database.

Before inserting password directly I used bcrypt module to hash the password and passed the hash to the database for password security.

Once user clicks register below happens:










The redirection is handled by Express of course, I used the below code to redirect from registration page to login page.


response.sendFile( "/js/nodejs/folder1/regSuccess.html");


This is where my regSuccess html is present.

Upon receiving the reSuccess page, the user can enter the credentials entered in the registration as below and click Login.











Once the user clicks enter he will be navigated to either success or failure forms based on the credentials entered.

I used the mysql module again to validate the parameters entered by the user.

I used bcrypt module once again in login part to convert the password entered by user in login with the hash in the MySQL database.

Record in MySQL database:








Below is the code containing selecting the password from MySQL and Bcrypt password comparision.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
else if (request.body.regOrLogin=="Login") {
   var  body = request.body;
   console.log(body.username+": username");
   connection.query("SELECT * FROM REG_NODEJS WHERE username='"+body.username+"'", function(err, res, fields){
    if(err) { 
     response.sendFile( "/js/nodejs/folder1/unauthorised.html");
    } else {
     bcrypt.compare(body.pwd, res[0].password, function(err, res) {
      if(res) {
       console.log("authorised user");
       response.sendFile( "/js/nodejs/folder1/authorised.html");
      } else {
       console.log("not an authorised user");
       response.sendFile( "/js/nodejs/folder1/unauthorised.html");
      }
     });
    }
   });
  }

The above example is just a simple way of showing how one can use various modules of Node.js.

One can download the code from GitHub.

Suggestions are well appreciated and Happy learning.

Comments

blog comments powered by Disqus