Saturday, 23 December 2017

Using Ant build.xml for dependency management

Steps:
  1. Right click on the project in project explorer in Eclipse --> new 'Ant Files'. This will generate a template file (.xml and a .properties file). 
  2. Create a Ivy.xml file by right clicking on the project --> new 'Ivy File'.
  3. Now you have 3 files in your project structure. the contents of these files are as follows:
axix_bujava.xml

<?xml version="1.0"?>

<project xmlns:ivy="antlib:org.apache.ivy.ant" default="retrieve-dependencies" basedir=".">

 <echo message="pulling in property files"/>
 <property file="axis_bujava.properties"/>
 
 <echo message="calling the web services generation ant task: axis_bujava"/>
 
 <target name="retrieve-dependencies" description="Retrieve dependencies with Apache IVY">
     <ivy:retrieve type="jar" />
 </target>
 
</project>

ivy.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="com.test"
        module="Test"
        status="integration">
 </info>
 <dependencies>
    <dependency org="commons-validator" name="commons-validator" rev="1.3.1"/>
    
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
  <dependency org="commons-logging" name="commons-logging" rev="1.2"/>
    
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
  <dependency org="org.springframework" name="spring-context" rev="5.0.2.RELEASE"/>
    
 </dependencies>
</ivy-module>


axis_bujava.properties
###############################################################################
# Copyright (c) 2008, 2014 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#     IBM Corporation - initial API and implementation
###############################################################################
!-- ScenarioType REQUIRED. Differentiates from "client" scenario.
ScenarioType=service

!-- InitialSelection REQUIRED.  Workspace relative URI to the input WSDL or Java
InitialSelection=/dynamicWebProjectName/src/packagename/myService.java

!--Utility property values - use these to list valid values for the following properties:
!-- Service.RuntimeId, Service.ServerId 
ListRuntimes=true
ListServers=true
!-- Verbose will list informational messages as well as errors if set to true
Verbose=true

!--  Service.RuntimeId - ID of web service runtime 
Service.RuntimeId=org.eclipse.jst.ws.axis.creation.axisWebServiceRT
!-- Service.ServerId -  ID of target server 
Service.ServerId=org.eclipse.jst.server.tomcat.80
!-- Service.TypeId - Java Bean is default for both Top Down and Bottom Up
!-- Service.TypeId=Java Bean

!-- ServiceProjectName - !--type:String - name of Service project - this property can be used to give the service project a different name than the project containing the initial selection.  type: String    
!--ServiceProjectName=serviceProjectName
!-- ServiceEarProjectName - !--type:String - name of Service EAR project - this property can be used to give the service EAR project a different name than the EAR project already associated with the service project.  type: String
!--ServiceEarProjectName=serviceEarProjectName

!-- Mappings
!-- Top down or bottom up scenario. Workspace relative URI to property file containing mappings.
!-- Top Down: Mappings are used to override the default package names of the generated Java template classes.
!-- The content of the properties file must be of the format namespace=package  
!-- Bottom Up: Mappings are used to override the default namespace names in the generated WSDL.
!-- The content of the properties file must be of the format package = namespace 
!--Mappings=/testProj/mappings/mappings.txt

!-- JavaOutput
!-- Top down - String: the workspace relative URI for a Java source folder for the generated Java code - must be existing workspace source folder
!--JavaOutput=/projectName/JavaSource

!-- Methods
!-- Bottom up - space delimited string of method signatures (i.e. method1(parmType1) method2(parmType2)) to be exposed in output WSDL.  If no list is provided, all methods are exposed.
!-- Methods=

!-- Style
!-- Bottom up - String: one of: RPC, DOCUMENT, WRAPPED
!--Style=DOCUMENT

!-- Use
!-- Bottom up - String: one of: LITERAL, ENCODED 
!--Use=LITERAL

!--OverwriteFilesEnabled - set to true to overwrite files that already exist. type:boolean 
!-- note for non-interactive mode it is recommended that this be set to true
!--OverwriteFilesEnabled=true

!--CreateFoldersEnabled - set to true create folders necessary during file generation type:boolean
!-- note for non-interactive mode it is recommended that this be set to true
!--CreateFoldersEnabled=true

!--CheckoutFilesEnabled - set to true to check out files with no warning to the user type:boolean
!-- note for non-interactive mode it is recommended that this be set to true
!--CheckoutFilesEnabled=true


Now right-click on axix_bujava.xml --> Run As --> Ant Build

First Eclipse project using Apache Ivy

For installation of IvDE plugin in eclipse refer to this post.

In this post I'll discuss getting started with first project using Ivy.

Steps:
  • Create a new project in eclipse. (In the usual way)
  • Right click on the project in project explorer and then click on new --> other and search for 'ivy file'. Create a new Ivy file. You will get a template file.
Modify the contents of this file so that it looks like this:

<?xml version="1.0" encoding="ISO-8859-1"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="com.test"
        module="Test"
        status="integration">
 </info>
 <dependencies>
    <dependency org="commons-validator" name="commons-validator" rev="1.3.1"/>
 </dependencies>
</ivy-module>


  • This says that we have one dependency on "commons-validator". Search your dependencies on the maven repo and add it to your ivy file.
  • Once you have added all the dependencies, right click on the ivy.xml file and click add Ivy Library. This will add all the dependencies to your project transitively.
  • Create a Test class in com.test package in your project which has following contents:

package com.test;

import org.apache.commons.validator.GenericValidator;

public class Test {

 public static void main(String[] args) {
  if (GenericValidator.isEmail("lavishkothari004@gmail.com")) {
   System.out.println("the entered Email is valid.");
  } else {
   System.out.println("the entered email is not valid");
  }
 }

}


Run the project using Ctrl+F11.

What is Ivy? Installing Ivy on Eclipse

What is Ivy?
Apache Ivy is a dependency manager. Or to put it elaborately, Ivy is a dependency manager (basically an Ant extension) to manage external libraries in an agile manner during development.

Benefits of using Ivy:
  • Suppose you want to use some external Java library during development and you end up adding all the resources as external JARs. (In eclipse you can manually add external JARs to your project by right-clicking on the project in project explorer --> build path --> configure build path... --> go to libraries Tab and click on 'Add External JARs'). Note that before adding these external JARs you need to go to the painstaking task of downloading them.
    • And in the case when you decide to use some other version of existing external library, you again need to go and download and manually add the JARs. This is no doubt, a clumsy and error-prone task.
  • Suppose the JARs that you download have transitive dependencies, you will have to go and manually add all the libraries which are missing and repeat this process forever until all the dependencies are resolved transitively. Apache Ivy helps us in resolving transitive dependencies with no pain.
  • Suppose you want to add your project on GitHub and someone else clones the project for reference, he/she will not get all the external libraries that your project is dependent on and will end up adding all the dependencies. This is horrible. Ivy lets you specify the dependencies and downloads it for you automatically at a click. :)
 And this list goes on. See this for more details.

But I think these points are enough to make you feel trying your hands on Ivy.

Installing Ivy plugin on eclipse
This is very simple. Go to Help --> Install new Software --> click on Add button
Name: IvyDE
Click OK.

IvDE will install after this and you will be prompted to restart eclipse.

Tuesday, 20 June 2017

Hash Functions and Encoding and Decoding of Integer in Crypto++

/*
	This program shows encoding of an integer into a byte array
	and again decoding the byte array into integer.

	This encoding and decoding is basically used when we need to give a byte array to SHA256 or SHA512
*/

#include <iostream>
using std::cout;
using std::endl;
using std::cin;

#include <cryptopp/integer.h>
using CryptoPP::Integer;

#include <cryptopp/sha.h>
using CryptoPP::SHA512;


Integer hashOfInteger(const Integer &a) // {0,1}* -> Zp*
{
	cout<<"Finding hash of "<<a<<endl;
	// using SHA512 here
	int byteCount=a.BitCount()/8;
	if(a.BitCount()%8!=0)
		byteCount++;
	byte byteArray[byteCount];	
	byte digest[SHA512::DIGESTSIZE];
	a.Encode(byteArray,byteCount);
	
	// now byte array contains bytes corresponding to the Integer a

	SHA512().CalculateDigest(digest,byteArray,byteCount);

	Integer result;
	result.Decode(digest,SHA512::DIGESTSIZE);
	return result;
}

int main()
{

	int n;
	cin>>n;
	cout<<"result  = "<<hashOfInteger(Integer::Power2(n))<<endl;
	return 0;
}

Scalar Multiplication in Elliptic curve in Crypto++

#include<bits/stdc++.h>
using std::cout;
using std::endl;

#include <cryptopp/ecp.h>
#include <cryptopp/asn.h>
#include <cryptopp/integer.h>
using CryptoPP::Integer;

#include <cryptopp/eccrypto.h>
using CryptoPP::ECP;    // Prime field
using CryptoPP::ECPPoint;
using CryptoPP::DL_GroupParameters_EC;

#include <cryptopp/asn.h>
#include <cryptopp/oids.h>
namespace ASN1 = CryptoPP::ASN1;

int main()
{
	DL_GroupParameters_EC<ECP> groupParameter = ASN1::secp160r1();

	
	cout << "Modulus: "<< groupParameter.GetCurve().GetField().GetModulus() << endl;
	cout << "Cofactor: "<< groupParameter.GetCofactor() << endl;
		    
	cout << "Coefficients" << endl;
	cout << "  A: "<< groupParameter.GetCurve().GetA() << endl;
	cout << "  B: "<< groupParameter.GetCurve().GetB() << endl;
	
	ECP curve=groupParameter.GetCurve();
	
	Integer y = groupParameter.GetSubgroupGenerator().x;
	Integer x = groupParameter.GetSubgroupGenerator().y;
	
	ECPPoint P=ECPPoint(x,y);
	cout<<"P = "<<P.x<<" , "<<P.y<<endl;

	ECPPoint R = curve.ScalarMultiply(P,Integer(2));

	cout<<"R = "<<R.x<<" , "<<R.y<<endl;

	return 0;
}



Basic Elliptic Curve Parameters in Crypto++

#include<bits/stdc++.h>
using std::cout;
using std::endl;

#include <cryptopp/ecp.h>
#include <cryptopp/asn.h>
#include <cryptopp/integer.h>
using CryptoPP::Integer;

#include <cryptopp/eccrypto.h>
using CryptoPP::ECP;    // Prime field
using CryptoPP::ECPPoint;
using CryptoPP::DL_GroupParameters_EC;

#include <cryptopp/asn.h>
#include <cryptopp/oids.h>
namespace ASN1 = CryptoPP::ASN1;

int main()
{
	DL_GroupParameters_EC<ECP> groupParameter = ASN1::secp160r1();

	
	cout << "Modulus: "<< groupParameter.GetCurve().GetField().GetModulus() << endl;
	cout << "Cofactor: "<< groupParameter.GetCofactor() << endl;
		    
	cout << "Coefficients" << endl;
	cout << "  A: "<< groupParameter.GetCurve().GetA() << endl;
	cout << "  B: "<< groupParameter.GetCurve().GetB() << endl;
	
	ECP curve=groupParameter.GetCurve();
	
	Integer y = groupParameter.GetSubgroupGenerator().x;
	Integer x = groupParameter.GetSubgroupGenerator().y;
	
	ECPPoint P=ECPPoint(x,y);
	cout<<"P = "<<P.x<<" , "<<P.y<<endl;

        return 0;
}



Random number Generation in Crypto++

#include<iostream>
using std::cout;
using std::endl;

#include<cryptopp/integer.h>
using CryptoPP::Integer;

#include<cryptopp/osrng.h>
using CryptoPP::AutoSeededRandomPool;

int main()
{
	// Illustration of generating a random number using AutoSeededRandomPool
	AutoSeededRandomPool rng;
	cout<<Integer(rng,Integer(400),Integer(500))<<endl;
	return 0;
}


Basics about Integer class in Crypto++

// refer this documentation - https://www.cryptopp.com/docs/ref/class_integer.html
// http://www.cryptopp.com/docs/ref561/class_integer.html
#include<iostream>
#include<cryptopp/integer.h>
using CryptoPP::Integer;
using std::cout;
using std::endl;

int main()
{
	// example showing calculation of 2^x for really big x
	cout<<"2**30000 = "<<Integer::Power2(30000)<<endl; // Power2 is a static member function of class. 
	

	// addition, subtraction, multiplication, division of two big numbers
	Integer i1=Integer::Power2(100); 
	Integer i2=Integer::Power2(50);

	cout<<"2**100 + 2**50 = "<<i1+i2<<endl;
	cout<<"2**100 - 2**50 = "<<i1-i2<<endl;
	cout<<"2**100 * 2**50 = "<<i1*i2<<endl;
	cout<<"2**100 / 2**50 = "<<i1/i2<<endl;
	
	// example showing use of modular operator
	Integer i3=Integer::Power2(1024);
	Integer i4(501);

	cout<<"2**1024 % 501 = "<<i3%i4<<endl;

	// example showing calculation of modular inverse
	Integer i5(3628800);
	Integer i6(2431);
	cout<<"modular inverse of 3628800 wrt 2431 = "<<i5.InverseMod(i6)<<endl;
	
	// example showing GCD of two numbers
	cout<<"GCD("<<i5<<","<<i6<<") = "<<Integer::Gcd(i5,i6)<<endl;

	Integer a,b,c;
	a=Integer(10241024);
	b=Integer(10241024);
	c=Integer(1000000007);

	// modular Multiplication 
	cout<<a_times_b_mod_c(a,b,c)<<endl;
	// modular Exponentiation
	cout<<a_exp_b_mod_c(a,b,c)<<endl;


	return 0;
}


Integer XOR in Crypto++

#include<iostream>
#include<algorithm>
using std::cout;
using std::cin;
using std::endl;

#include<cryptopp/integer.h>
using CryptoPP::Integer;


Integer XOR(Integer &a,Integer &b)
{
	Integer result=0;
	if(a>b)
	{
		for(int i=a.BitCount()-1;i>=b.BitCount();i--)
			result=result*2 + a.GetBit(i);
		for(int i=b.BitCount()-1;i>=0;i--)
			result=result*2 + (a.GetBit(i) ^ b.GetBit(i));
	}
	else
	{
		for(int i=b.BitCount()-1;i>=a.BitCount();i--)
			result=result*2 + b.GetBit(i);
		for(int i=a.BitCount()-1;i>=0;i--)
			result=result*2 + (a.GetBit(i) ^ b.GetBit(i));
	}

	return result;
}
void printBits(Integer &a)
{	
	for(int i=a.BitCount()-1;i>=0;i--)
		cout<<a.GetBit(i);
	cout<<endl;
}
int main()
{
	int x,y;
	cin>>x>>y;
	Integer a(Integer::Power2(x));
	Integer b(Integer::Power2(y));

	cout<<XOR(a,b)<<endl;
	return 0;
}



Printing the same character n number of times in Vim

Many times you need to type the same character many times and for that you need to long press that character and this wastes time. Well, there is a smarter way to do this in Vim.

Suppose you need to type _(underscore) 50 times.

So to do this, go in command mode by pressing Esc key and type the following:
50i_<Esc>

The moment you press <Esc>, the one undersocre that appears on the screen will be repeated 50 times, and now you can see 50 underscores on the screen one after the other.

Running python code from Vim and replacing the code with output

It is possible to write python code in vim and then execute the code. The output of the code will be placed in place of the python code. Let me illustrate you an example so that it becomes more clear.

Example:
Suppose that you have a string "Lavish" and you want to put each character of this string into a new line. We can write python code to do this.

for i in "Lavish":
    print i

Now select the above two lines by going in visal mode and then execute the following commmand:
:'<,'>!python

This will replace the python code with following lines:
L
a
v
i
s
h

Now, you may not see the real difference when the string is small, but as the string goes bigger, the power of vim becomes more visible.

Similarly, as an another example, say you want to print the following thing in a text file

1 Lavish
2 Lavish
3 Lavish
4 Lavish
5 Lavish

I'm sure, you must have figured it out that the python code for this will be:

for i in range(1,6):
    print str(i)+" Lavish"

and then follow the same thing again as described above. Similarly to the above mentioned examples, there is a lot of cool stuff that you can try out and make yourself more productive and efficient.

I hope this was interesting and you learned something from this. :)

Automatic Indentation of Code in Vim

Indentation is very important as it increases the readability of the codea and is considered to be a good programming practice. But a lot of times you may have to get some code that is not indented, and it is really irritating to mannualy indent each line. Vim provides a very eays way to indent your code just with unbelievably few keystrokies.

gg=G

is will indent your code from beginning of the file till the end of the file. Note that here gg means go to the starting of the file and = means to indent and G is for the end of the file. Puting it together we can read it as "indent the code from first line till the last line."

Similarly, to order to indent the current line, just place your cursor anywhere in that line and press
==
This will indent the current line.

Moving to the matching paranthesis in Vim

A lot of times while programming, we need to move to the matching paranthesis/braces. Place your cursor under one of the paranthesis in normal mode and press % the cursor will move to the corresponding matching paranthesis, bracket or brace what so ever it is. This is an efficient way of moving around functions in programming languages.

Saving and Quiting in Vim (shortcut Method)

Normal way to save and quit a file in vim is using :wq in vim. This is used by most of the user, but this involves three different keystrokes. But there is another way to do this saving and quiting. Just press ZZ in the normal mode and the file will be written and then vim will exit. I personally think that this is more efficient because it involves only one keystroke and it does all the things. Hope you also find this way of saving and quiting easier.

Thursday, 27 April 2017

Pattern making - Spirograph - Javascript - using array of rods

In the previous post we saw how to create two rods and make them rotate relative to each other, with each rod having different speed and different length. In this post we will extend the previous code so as to make more than two rods rotate relative to the previous rod, and we will also trace the trajectory of end point of the last rod as done in previous post.

The following is the code:

HTML Code

<html>
 <title>Rakshit</title>
 <script type="text/javascript" src="a.js"></script>
 <body>
  <canvas id="mycanvas" width="500" height="500"></canvas>
  <canvas id="desingcanvas" width="500" height="500"></canvas>
  <button id="stopButton">Stop</button>
  <button id="resumeButton">Resume</button>
  <button id="restartButton">Restart</button>

 </body>

</html>

Javascript Code
/*
    Taking array of rods.
*/

var width=0;
var height=0;
var interval;

var rods=[];
var drawing=false; // a global variable that keeps track of whether we are drawing or not.

window.onload = function(){
    var cns = document.getElementById("mycanvas");

    width = cns.width;
    height = cns.height;
    var designContext =  document.getElementById("desingcanvas").getContext("2d");
    var context = cns.getContext("2d");
    rod1=Rod.create(250,250,100,0,10.0,"#0000FF");
    rod2=Rod.create(rod1.endx,rod1.endy,70,Math.PI,60.0,"#FF0000");
    rod3=Rod.create(rod2.endx,rod2.endy,50,Math.PI,30.0,"#00FF00");
    rod4=Rod.create(rod3.endx,rod3.endy,20,Math.PI,10.0,"#0F00F0");

    rods.push(rod1);
    rods.push(rod2);
    rods.push(rod3);
    rods.push(rod4);

    interval = setInterval(function(){draw(context,designContext);},1);

    var stopButton = document.getElementById("stopButton");
    stopButton.addEventListener("click",stopButtonClicked,false);
    var resumeButton = document.getElementById("resumeButton");
    resumeButton.addEventListener("click",resumeButtonClicked,false);
    var restartButton = document.getElementById("restartButton");
    restartButton.addEventListener("click",restartButtonClicked,false);

};

function stopButtonClicked()
{
    if(drawing)
    {
        clearInterval(interval);
        drawing=false;
    }
}
function resumeButtonClicked()
{
    if(drawing===false)
    {
        var context = document.getElementById("mycanvas").getContext("2d");
        var designContext =  document.getElementById("desingcanvas").getContext("2d");
        interval = setInterval(function(){draw(context,designContext);},1);
    }
}
function restartButtonClicked()
{
    if(drawing===true)
        clearInterval(interval);
    var canvas1 = document.getElementById("mycanvas");
    var canvas2 = document.getElementById("desingcanvas");
    var context = canvas1.getContext("2d");
    var designContext =  canvas2.getContext("2d");

    context.clearRect(0,0,canvas1.width,canvas1.height);
    designContext.clearRect(0,0,canvas2.width,canvas2.height);

    interval = setInterval(function(){draw(context,designContext);},1);
}

var Rod={
    startx:0,
    starty:0,
    endx:0,
    endy:0,
    length:0,
    angle:0,
    speed:100,
    color:"#000000",
    create:function(startx,starty,length,angle,speed,color)
    {
        var obj=Object.create(this);
        obj.startx=startx;
        obj.starty=starty;
        obj.length=length;
        obj.angle=angle;
        obj.speed=speed/500.0;

        obj.color=color;

        obj.endx=startx+length*Math.cos(angle);
        obj.endy=starty+length*Math.sin(angle);
        return obj;
    },

    update:function(startx,starty)
    {
        this.startx=startx;
        this.starty=starty;
        this.angle+=this.speed;
        if(this.angle>2*Math.PI)
            this.angle=0;
        this.endx=this.startx+this.length*Math.cos(this.angle);
        this.endy=this.starty+this.length*Math.sin(this.angle);
    },

    drawRod:function(context)
    {
        context.strokeStyle = this.color;
        context.lineWidth = 2;
        context.beginPath();
        context.moveTo(this.startx,this.starty);
        context.lineTo(this.endx,this.endy);
        context.stroke();
        context.closePath();
    }

};


function draw(context,designContext)
{
    var n=rods.length; // n is the number of rods.
    drawing=true;
    designContext.strokeStyle="#FF0000";
    designContext.lineWidth=0.25;
    designContext.beginPath();
    designContext.moveTo(rods[n-1].endx,rods[n-1].endy);

    context.clearRect(0,0,width,height);

    for(var i=0;i<n;i++)
    {
        if(i===0)
        {
            rods[i].drawRod(context);
            rods[i].update(rods[i].startx,rods[i].starty);
        }
        else {
            rods[i].drawRod(context);
            rods[i].update(rods[i-1].endx,rods[i-1].endy);
        }
    }

    designContext.lineTo(rods[n-1].endx,rods[n-1].endy);
    designContext.stroke();
    designContext.closePath();
}


The following animation is the illustration of the above mentioned code. You can try changing the length and speed of each rod and generate some really amazing patterns. You can also try adding more rods, or removing some of the rods so as to get something interesting.



Please feel free to comment if have any problem, or if you find any other thing that is interesting in this context. Also feel free to point any mistakes in the code.

Pattern Making - Spirograph - JavaScript

This post contains an illustration of making a spirograph using HTML5 and Javascript. Note that down there, we have three small buttons for you to play with the animation. The concept used here is that I have two rods/arms attached back to back and I'm plotting the trajectory of end-point of the last rod. See the below animation to get a clear idea.



Note that the code mentioned above is not easily extendable but the coming posts in this series will show how you can create an array of rods, and loop over all the rods to track the path traced by the end point of the last rod.
You can always right click and go to view page source to view the code behind construction of the above spirograph, but for the sake of simplicity and cutting off all the dirty code, here is the clean code used to make the above spirograph.
HTML Code
<html>
<title>Rakshit</title>
<script type="text/javascript" src="a.js"></script>
<body>
    <canvas id="mycanvas" width="500" height="500"></canvas>
    <canvas id="desingcanvas" width="500" height="500"></canvas>
    <button id="stopButton">Stop</button>
    <button id="resumeButton">Resume</button>
    <button id="restartButton">Restart</button>

</body>

</html>


Javascript Code
/*
    This program adds two rotating rods, representing robotic arm

    This is a simple program that just adds 2 rods
    and gives the trajectory of the end point of the second rod
*/
var width=0;
var height=0;
var interval;
var rod1,rod2;
var drawing=false; // a global variable that keeps track of whether we are drawing or not.
window.onload = function(){
    var cns = document.getElementById("mycanvas");

    width = cns.width;
    height = cns.height;
    var context = cns.getContext("2d");
    var designContext =  document.getElementById("desingcanvas").getContext("2d");
    rod1=Rod.create(250,250,80,0,10.0,"#0000FF");
    rod2=Rod.create(rod1.endx,rod1.endy,130,Math.PI,80.0,"#FF0000");

    interval = setInterval(function(){draw(context,designContext);},1);

    var stopButton = document.getElementById("stopButton");
    stopButton.addEventListener("click",stopButtonClicked,false);
    var resumeButton = document.getElementById("resumeButton");
    resumeButton.addEventListener("click",resumeButtonClicked,false);
    var restartButton = document.getElementById("restartButton");
    restartButton.addEventListener("click",restartButtonClicked,false);

};

function stopButtonClicked()
{
    if(drawing)
    {
        clearInterval(interval);
        drawing=false;
    }
}
function resumeButtonClicked()
{
    if(drawing===false)
    {
        var context = document.getElementById("mycanvas").getContext("2d");
        var designContext =  document.getElementById("desingcanvas").getContext("2d");
        interval = setInterval(function(){draw(context,designContext,rod1,rod2);},1);
    }
}
function restartButtonClicked()
{
    if(drawing===true)
        clearInterval(interval);
    var canvas1 = document.getElementById("mycanvas");
    var canvas2 = document.getElementById("desingcanvas");
    var context = canvas1.getContext("2d");
    var designContext =  canvas2.getContext("2d");

    context.clearRect(0,0,canvas1.width,canvas1.height);
    designContext.clearRect(0,0,canvas2.width,canvas2.height);

    interval = setInterval(function(){draw(context,designContext,rod1,rod2);},1);
}

var Rod={
    startx:0,
    starty:0,
    endx:0,
    endy:0,
    length:0,
    angle:0,
    speed:100,
    color:"#000000",
    create:function(startx,starty,length,angle,speed,color)
    {
        var obj=Object.create(this);
        obj.startx=startx;
        obj.starty=starty;
        obj.length=length;
        obj.angle=angle;
        obj.speed=speed/500.0;

        obj.color=color;

        obj.endx=startx+length*Math.cos(angle);
        obj.endy=starty+length*Math.sin(angle);
        return obj;
    },

    update:function(startx,starty)
    {
        this.startx=startx;
        this.starty=starty;
        this.angle+=this.speed;
        if(this.angle>2*Math.PI)
            this.angle=0;
        this.endx=this.startx+this.length*Math.cos(this.angle);
        this.endy=this.starty+this.length*Math.sin(this.angle);
    },

    drawRod:function(context)
    {
        context.strokeStyle = this.color;
        context.lineWidth = 2;
        context.beginPath();
        context.moveTo(this.startx,this.starty);
        context.lineTo(this.endx,this.endy);
        context.stroke();
        context.closePath();
    }

};


function draw(context,designContext)
{
    drawing=true;
    designContext.strokeStyle="#FF0000";
    designContext.lineWidth=0.25;
    designContext.beginPath();
    designContext.moveTo(rod2.endx,rod2.endy);

    context.clearRect(0,0,width,height);

    rod1.drawRod(context);
    rod1.update(rod1.startx,rod1.starty);
    rod2.drawRod(context);
    rod2.update(rod1.endx,rod1.endy);

    designContext.lineTo(rod2.endx,rod2.endy);
    designContext.stroke();
    designContext.closePath();
}

Please bear with me as I am new to javascript and comment if you have any new idea or find anything wrong in this post.