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.

Wednesday, November 11, 2015

Node.js with MySQL

In this post, I am going to put forward the approach to save data we sent by a HTML to Node.js server into MySQL database. 

Simple HTML form:

I created a simple HTML form that accepts username and password and on click of submit, sends the data to node.js server as post parameters.

Here is my 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
<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: 30px;
    color:white;
    background-color:#5882FA;
   }
  table {
    position:relative;
    bottom:-10px;
   }
 </style>
 </head>
 <body>
  <h1 style="text-align:center;">Form to save data to MySQL</h1>
  <p style="text-align:center;font-weight:bold;">Enter the text and click submit.</p>
  <form action="http://localhost:2000/requestServer" method="post" align='center'>
   <table align="center" style="font-size:30px;">
    <tr>
     <td>User Name:</td> <td><input type="input" 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="submit"/></td></tr>
   </table>
  </form>
 </body>
</html>

Rendering:









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
var http=require("http");
var mysql = require("mysql");
var postDataObject;
//connection to mysql
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});
connection.connect();

http.createServer(function(request, response) {
 request.on("data", function(postVars) {
  var dataFromPost = "";
  if(request.url!="/favicon.ico") { 
   var dataFromPostTemp = "";
   dataFromPost+=postVars;
   var userName = dataFromPost.split("&")[0].split("=")[1];
   var password1 = dataFromPost.split("&")[1].split("=")[1];
   var date = new Date();
   var formattedDate = date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay();
   postDataObject = {username: userName, password: password1, date: formattedDate};
   connection.query("insert into users_nodejs set ?", postDataObject, 
   function(err, result) {
    if(err) throw err;
   });
  }
 });
 request.on("end", function() {
  response.writeHead(200, {"Location":"e:/js/nodejs/page1.html"});
  response.write("<p style='color:red;text-align:center;font-size:30px;'>A Node JS Server</p>");
  response.end();
 });
}).listen(2000);
console.log("le succès de démarrage du serveur");

MySQL code:

To acquire node module mysql, one has to use:



1
var mysql = require("mysql");

Once we have got mysql module, we have to pass host, username, password and database name to createConnection of mysql instance as below.


1
2
3
4
5
6
var connection = mysql.createConnection({
 host: "localhost",
 user: "root",
 password: "somePass",
 database: "mysql"
});

I have passed the above to a variable 'connection'.

I used an object and passed the data I have to insert into table of mysql, in the object, data before column is column name and data after column is the data I got from post parameters.

For example from below:


1
2
3
4
5
postDataObject = {username: userName, password: password1, date: formattedDate};
connection.query("insert into users_nodejs set ?", postDataObject, 
   function(err, result) {
    if(err) throw err;
   });

postDataObject has username:userName

here username is the column name in the table, userName is the variable into which I stored the post parameter, (refer to main Node.js program above).

And further there we have query in connection using which we will pass queries to MySQL.

General syntax of sql is 

Syntax specified for mysql module in node.js (from npmjs.com) is:

"Insert into table_name set ? ", obj

obj here is postDataObject that has columns and data.

Test from UI:











On click of submit, we have






In MySQL,







Don't hesitate to drop in any suggestions, happy learning 

Comments

blog comments powered by Disqus