Monday, 27 February 2017

Write an application to parse input text file concurrently and compare the result of concurrent parsing with serial parsing ( Use concurrent YACC parser)


CODE(assign.l):

%{
#include<stdio.h>
#include "y.tab.h"

#define YYSTYPE int    //to avoid global var coz multiple instances
%}
%option reentrant bison-bridge

%%
[0-9]+ {
          *yylval=atoi(yytext);    //to refer to address of yylval
          return NUMBER;
       }
[\t] ;
[\n] return 0;
. return yytext[0];
%%
int yywrap(yyscan_t yyscanner)  //parser object in bracket
{
return 1;
}


CODE(assign.y):


 %{
    #include<stdio.h>
    #include<stdlib.h>
    #include<omp.h>
   
    #define YYSTYPE int

    int numofthreads,expsperthread;
    char inputfilename[30];
%}
%token NUMBER

%left '+' '-'
%left '*' '/' '%'
%left '(' ')'

%pure-parser
%lex-param {void * scanner}
%parse-param {void * scanner}

%%

ArithmeticExpression: E{
         
         //printf("\nResult=%d\n",$$);
     
         return $$;
        }
E:E'+'E {$$=$1+$3;}
 |E'-'E {$$=$1-$3;}
 |E'*'E {$$=$1*$3;}
 |E'/'E {$$=$1/$3;}
 |E'%'E {$$=$1%$3;}
 |'('E')' {$$=$2;}
 | NUMBER {$$=$1;}
;

%%

void func()
{
void * scanner;
    yylex_init(&scanner);        /*parser object created ie scanner initialized and destroyed*/

FILE *fp;
fp=fopen(inputfilename,"r");

int i,j;

int tid;
int res;
 
tid=omp_get_thread_num();

char *s=malloc(100);
size_t n=100;

for(i=0;i<(expsperthread*tid);i++)        //to skip some lines
  {
    getline(&s,&n,fp);
  }

yyset_in(fp,scanner);

for(j=0;j<expsperthread;j++)
  {
    res=yyparse(scanner);            //invoking parser  which invokes lexer

    printf("%dth Expression=%d is given by Thread %d\n",(expsperthread*tid+j+1),res,tid);
  }

    yylex_destroy(scanner);

fclose(fp);
}

void main()
{
printf("Enter Input Text File Name\n");
scanf("%s",inputfilename);
printf("Enter Number of threads to be created\n");
scanf("%d",&numofthreads);
printf("Enter Number of Arithmetic Expressions to be evaluated by each thread\n");
scanf("%d",&expsperthread);

#pragma omp parallel num_threads(numofthreads)
  {
    func();
  }
}

int yyerror()
{
   printf("\nArithmetic expression is Invalid\n\n");
}

CODE(file.txt):

2+3
3+4
4+5
5+6
1*2
2*3
3*4
4*5
5*6
2-1
3-2
4-3
5-4
6-5
7+5
5*7
34+790
120+210
12*23
1+2

OUTPUT:

[pl3@pl3]$ lex test.l
[pl3@pl3]$ yacc -d test.y
[pl3@pl3]$ ls
a.out  lex.yy.c  file.txt  assign.l  assign.l~  assign.y  assign.y~  y.tab.c  y.tab.h
[pl3@pl3]$ gcc -fopenmp lex.yy.c y.tab.c
[pl3@pl3]$ ./a.out
Enter Input Text File Name
test1.txt
Enter Number of threads to be created
5
Enter Number of Arithmetic Expressions to be evaluated by each thread
3
7th Expression=12 is given by Thread 2
13th Expression=1 is given by Thread 4
14th Expression=1 is given by Thread 4
15th Expression=12 is given by Thread 4
4th Expression=11 is given by Thread 1
8th Expression=20 is given by Thread 2
1th Expression=5 is given by Thread 0
9th Expression=30 is given by Thread 2
10th Expression=1 is given by Thread 3
2th Expression=7 is given by Thread 0
3th Expression=9 is given by Thread 0
5th Expression=2 is given by Thread 1
11th Expression=1 is given by Thread 3
6th Expression=6 is given by Thread 1
12th Expression=1 is given by Thread 3
[cnlab@localhost 3]$ ./a.out
Enter Input Text File Name
test1.txt
Enter Number of threads to be created
3
Enter Number of Arithmetic Expressions to be evaluated by each thread
3
7th Expression=12 is given by Thread 2
8th Expression=20 is given by Thread 2
1th Expression=5 is given by Thread 0
9th Expression=30 is given by Thread 2
4th Expression=11 is given by Thread 1
5th Expression=2 is given by Thread 1
6th Expression=6 is given by Thread 1
2th Expression=7 is given by Thread 0
3th Expression=9 is given by Thread 0

Saturday, 25 February 2017

Implement an calculator (64 bit Binary Multiplication) application using concurrent lisp

The following lisp program shows implementation of a calculator:

CODE(calculator.lisp):

(write-line "Welcome to a Calculator Program using Concurrent Lisp")     

(defvar num1)     
(defvar num2)
(defvar result)

(defun square(x)
(write-line "SQUARE of first number is:")
(setf result (* x x))
(format t "~D" result ))

(defun cube(x)
(write-line "CUBE of second number is:")
(setf result (* x x x))
(format t "~D" result ))

(defun sine(x)
(write-line "SINE of first number is:")
(setf result (sin x))
(format t "~D" result ))

(defun tangent(x)
(write-line "TANGENT of first number is:")
(setf result (tan x))
(format t "~D" result ))

(defun cosine(x)
(write-line "COSINE of first number is:")
(setf result (cos x))
(format t "~D" result ))

(defun exponential(x)
(write-line "EXPONENTIAL FUNCTION of first number is:")
(setf result (exp x))
(format t "~D" result ))

(defun exponential1(x y)
(write-line "EXPONENTIAL FORM of BASE AND POWER is:")
(setf result (expt x y))
(format t "~D" result ))

(defun logarithm(x)
(write-line "LOGARITHM of first number to base 2 is:")
(setf result (log x 2))
(format t "~D" result ))

(defun logarithm1(x)
(write-line "LOGARITHM of first number to base 10 is:")
(setf result (log x 10))
(format t "~D" result ))

(write-line "Enter two numbers:") 
(setf num1(read)) 
(setf num2(read))
 

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(+ num1 num2))
    (print "ADDITION in binary:")
    (format t "~b" result )
    (print "ADDITION in decimal:")
    (format t "~D" result ))))

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(- num1 num2))
    (print "SUBTRACTION in binary:")
    (format t "~b" result )
    (print "SUBTRACTION in decimal:")
    (format t "~D" result ))))

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(* num1 num2))
    (print "MULTIPLICATION in binary:")
    (format t "~b" result )
    (print "MULTIPLICATION in decimal:")
    (format t "~D" result ))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(/ num1 num2))
    (print "DIVISION in binary:")
    (format t "~b" result )
    (print "DIVISION in decimal:")
    (format t "~D" result ))))

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(mod num1 num2))
    (print "MODULUS in binary:")
    (format t "~b" result )
    (print "MODULUS in decimal:")
    (format t "~D" result ))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (square num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (cube num2))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (sine num1))))

(sb-thread:make-thread(lambda()(progn (sleep 0)
    (tangent num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (cosine num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (exponential num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (exponential1 num1 num2))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (logarithm num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (logarithm1 num1))))
   
(print (sb-thread:list-all-threads))
(sleep 30 )      

(exit)




OUTPUT:

pl3@pl3:~$ sbcl
This is SBCL 1.3.1.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.

SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses.  See the CREDITS and COPYING files in the
distribution for more information.
* (load "calculator.lisp")   
Welcome to a Calculator Program using Concurrent Lisp
Enter two numbers:
5
3

"ADDITION in binary:" 1000
"ADDITION in decimal:" 8
"SUBTRACTION in binary:" 10
"SUBTRACTION in decimal:" 2
"MULTIPLICATION in binary:" 1111
"MULTIPLICATION in decimal:" 15
"DIVISION in binary:" 101/11
"DIVISION in decimal:" 5/3
"MODULUS in binary:" 10
"MODULUS in decimal:" 2
SQUARE of first number is:25
CUBE of second number is:27
SINE of first number is:-0.9589243
TANGENT of first number is:-3.380515
COSINE of first number is:0.2836622
EXPONENTIAL FUNCTION of first number is:148.41316
EXPONENTIAL FORM of BASE AND POWER is:125
LOGARITHM of first number to base 2 is:2.321928
LOGARITHM of first number to base 10 is:0.69897

(#<SB-THREAD:THREAD FINISHED values: NIL {1003F13763}>
#<SB-THREAD:THREAD "main thread" RUNNING {100399C4D3}>)

Thursday, 23 February 2017

Write an application to and demonstrate the change in BeagleBoard( ARM Cortex A8) /CPU frequency or square wave of programmable frequency.



Following is the code to demonstrate change in  Beagle Bone Board CPU Frequency:

#Code (assignment.py):

import os


print "Current CPU Information"
os.system("cpufreq-info")

print "\n"

#300MHz
print "Changing current frequency to: 300MHz"
os.system("cpufreq-set -f 300Mhz")
os.system("python fact.py")

print "\n"

#600MHz
print "Changing current frequency to: 600MHz"
os.system("cpufreq-set -f 600Mhz")
#os.system("cpufreq-info")
os.system("python fact.py")

print "\n"

#800MHz
print "Changing current frequency to: 800MHz"
os.system("cpufreq-set -f 800Mhz")
os.system("python fact.py")

print "\n"

#1000MHz
print "Changing current frequency to: 1000MHz"
os.system("cpufreq-set -f 1000Mhz")
os.system("python fact.py")

print "\n"

os.system("cpufreq-set -f 300Mhz")   #Restoring back original frequency



#fact.py:

import sys,time
def Factorial():
    n = 100
    fact=1
    for i in range(1,n+1):
       fact=fact*i

start_time=time.time()
Factorial()
print "Time taken in fact.py: %s seconds" % (time.time()-start_time)

#Output:

root@beaglebone:~# python assignment.py
cpufrequtils 008: cpufreq-info (C) Dominik Brodowski 2004-2009
Report errors and bugs to cpufreq@vger.kernel.org, please.
analyzing CPU 0:
  driver: generic_cpu0
  CPUs which run at the same hardware frequency: 0
  CPUs which need to have their frequency coordinated by software: 0
  maximum transition latency: 300 us.
  hardware limits: 300 MHz - 1000 MHz
  available frequency steps: 300 MHz, 600 MHz, 800 MHz, 1000 MHz
  available cpufreq governors: conservative, ondemand, userspace, powersave, performance
  current policy: frequency should be within 300 MHz and 1000 MHz.
                  The governor "userspace" may decide which speed to use
                  within this range.
  current CPU frequency is 300 MHz (asserted by call to hardware).
  cpufreq stats: 300 MHz:68.71%, 600 MHz:3.54%, 800 MHz:25.30%, 1000 MHz:2.45%  (33)

Current frequency: 300MHz
Time taken in fact.py: 0.000475883483887 seconds


Current frequency: 600MHz
Time taken in fact.py: 0.000253200531006 seconds


Current frequency: 800MHz
Time taken in fact.py: 0.000197887420654 seconds


Current frequency: 1000MHz
Time taken in fact.py: 0.000165939331055 seconds

Implement a Multi-threading application for echo server using socket programming in JAVA


The folllowing code implements a multi-threading application for echo server in java:

EchoServer.java:

import java.io.*;
import java.net.*;

public class EchoServer implements Runnable
{
    public Socket client;
 
    public EchoServer(Socket sock)
    {
      this.client = sock;
    }
   
    public EchoServer(int portnum)
    {
        try
        {
            server = new ServerSocket(portnum);    //create new socket
        }
        catch (Exception err)
        {
            System.out.println(err);
        }
    }   

    public void serve()
    {
        try
        {
            while (true)    //wait for client connection
            {               
                Socket client = server.accept();    //accept client connection               
                System.out.println("Connection accepted at :" + client);
                new Thread(new EchoServer(client)).start();   
            }
        }
        catch (Exception err)
        {
            System.err.println(err);
        }
    }
   
    public void run()
    {
        try
        {
           long threadId = Thread.currentThread().getId();                   
           BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));
           PrintWriter w = new PrintWriter(client.getOutputStream(), true);
           w.println("Welcome to the Java EchoServer.  Type 'bye' to close.");                   
           String line;
           do
           {
              line = r.readLine();
              if ( line != null )
              {
                  System.out.println("Received from Client "+ threadId +":"+line);
                  w.println("Echo in client: "+line);
              }
           }
           while ( !line.trim().equals("bye") );
           client.close();   
        }
        catch (Exception err)
        {
            System.err.println(err);
        }       
   
    }

    public static void main(String[] args)
    {
       
        EchoServer s = new EchoServer(9999);
        s.serve();       
    }

    private ServerSocket server;
}


EchoClient.java:

import java.io.*;
import java.net.*;

public class EchoClient
{
    public static void main(String[] args)
    {
        try
        {
            Socket s = new Socket("127.0.0.1", 9999);
            BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter w = new PrintWriter(s.getOutputStream(), true);
            BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
            String line;
            do
            {
                line = r.readLine();
                if ( line != null )
                    System.out.println(line);
                line = con.readLine();
                w.println(line);
            }
            while ( !line.trim().equals("bye") );
        }
        catch (Exception err)
        {
            System.err.println(err);
        }
    }
}


Output: 


Saturday, 4 February 2017

Python - Article 2 : Installation

Installing Python is really quick and easy. So let's follow a few simple steps to setup our own Python Environment...😊

                         
                        Installing Python in Linux:

-Python comes preinstalled in most of the linux flavours.
-To check if python is installed or not open the terminal and type:
                              $python --version
-If python is installed the version will be shown in ouput as follows:
                              Python 2.7.12
-The latest version of python available is 3.6.0
-To update/install latest version in the terminal type the command:
                              $sudo apt-get install python <version>
where <version> represents the required version number.



                        Installing Python in Windows:
-The installer for Windows can be downloaded from the following link:
                 https://www.python.org/downloads/windows/
-Keeping in mind the architecture of the machine(64 bit or so) required installer must be downloaded
-Then go to the downloaded installer and double click on it and run it.
-Python version 3 also automatically sets the path variable for python. But if you are using Python version 2 then in windows command prompt type the command:
                   path %path%;C:\Python
-This can also be done by GUI as follows:
               My Computer>>Properties>>Advanced System    Settings>>Environment Variables>>New>>Name(Enter anything like python or pythonexe)>>Value(Path to Python e.g.C:\Python\)>>Select: 'Add python.exe to path'>>Finish/Save



                         Installing Python in Mac OS:
-The installer for Mac OS can be downloaded from the following link:
                 https://www.python.org/downloads/mac-osx/
-Keeping in mind the architecture of the machine(64 bit or so) required installer must be downloaded
-Then go to the downloaded installer and double click on it and run it.
-For Mac OS the installer itself takes care to setup the path variable.



                         How to run Python...
-To use interactive Python just type 'python' in the terminal as:
     python@python:~$ python
     Python 2.7.12 (default, Nov 19 2016, 06:48:10)
     [GCC 5.4.0 20160609] on linux2
     Type "help", "copyright", "credits" or "license" for more information.
     >>>

-To run a python script type the command in the terminal:
                               $python <script_name.py>

Thursday, 2 February 2017

Python - Article 1 : Introduction




 Now the question arises why should I learn python?





The answer to this is very interesting. Do you want to reduce your workload and enjoy your machine doing your work???Also do you want to be more creative at work???


The answer to the above questions is surely a 'YES'😎😎. So this 'YES' requires one to learn python, write high level compact codes, explore the language and use it for various amazing applications like :

1) Customizing you business software according to your needs to speed work.
2) write scripts for getting digital data from your sensor using microprocessor to analyse it. Example: get data from your proximity sensor to know someone is entering your room. OR get data from weight sensor to know that your milk in refrigerator is over etc.
3)write scripts to automatically play your favourite music playlist when you turn on your computer.
4)you can even ask your computer to do some boring repetitive task efficiently by writing a few lines in python.

So in order to explore Python and apply it in various creative ways let's learn Python through a series of brief articles....

Before knowing about installation of Python lets just see a brief introduction of Python Programming Language

-Python is a high level, object oriented interpreted scripting language.
-It is easy to understand and great to begin programming with.
-Python has a huge standard library and has support for various api's, this makes it a good choice in many applications,customizations,tools etc.