Saturday, August 11, 2012

Create table in PostgreSQL.

In this Section we are going to learn that how are tables created in PostgreSQL.

First of all you need the PostgreSQL software installed on your computer. If you don't have no problem you can download from the following link. Choose your platform and you are ready to download.

Download :  PostgreSQL

OK after you download and install the software then run it from the command prompt as mentioned in the read me manual.

A screen will appear in front of you when you run the program by filling in the appropriate login or authentication information.

Then simple write the following lines on the screen and run it.

Type the two paragraphs A) and B) on your screen and run it.

A) Item Table

     create table item
      (item_no integer primary key,
      item_name text,
      qty float);

B) Supplier table.

     create table supplier
     (supp_no integer primary key,
     supp_name text,
     address text,
     city text,
     phoneno integer);

When you run these two codes in your command prompt two tables named Item  and Supplier will be created in your database.

Now we will insert data in these two tables. now Run the Following statements on your command prompt and data will be inserted in both tables.

C) Inserting Data in Item Table.

     insert into item values(1,'cdrom',1200);
     insert into item values(2,'cd writer',1500);
     insert into item values(3,'fdd',800);
     insert into item values(4,'hdd',3200);
     insert into item values(5,'speaker',1200);
     insert into item values(6,'usb',500);
     insert into item values(7,'mouse',500);
     insert into item values(8,'monitor',1200);





D) Inserting Data in Supplier table.


     insert into supplier values(1,'singh0','ozar0','nasik0',5602077);
     insert into supplier values(2,'singh1','ozar1','nasik1',5602076);
     insert into supplier values(3,'singh2','ozar2','nasik2',5602075);
     insert into supplier values(4,'singh3','ozar3','nasik3',5602074);
     insert into supplier values(5,'singh4','ozar4','nasik4',5602073);
     insert into supplier values(6,'singh5','ozar5','nasik5',5602072);
     insert into supplier values(7,'singh6','ozar6','nasik6',5602071);
     insert into supplier values(8,'singh7','ozar7','nasik7',5602070);*/
     insert into supplier values(9,'singh8','ozar8','nasik0',2775411);





PL/pgSql



The Full Form of PL/pg Sql is  Procedural language/Postgre Sql.
It is a Structured Query language. It is Almost Similar to Sql Queries but it is more structured and more easy than the Sql Commands and functions.

Specifications of the Pl/pg Sql is as Follows:

1) Database created has no Size Limit ie it can be unlimited.
2) The table created in it can have a maximum size of  32 TB and not more than that.
3) The maximum Row Size can be maximum  upto 1.6 TB and not more than that.
4) There can be any number of rows per tables .
5) It is Highly Customizable.

Postgres Sql is available under the liberal open source license(LOSL) to download and modify,distribute and use for development. It is a powerful tool that can be used for home applications, web development, ecommerce and at places where softwares or products of high RDBMS is required.

Below is a Simple example of Postgres sql function.



 
create table Doctor
    (
        doc_no        integer        primary key    ,
        doc_name     text        not null    ,
        address        text        not null    ,
        city        text        not null   
    );

create table Hospital
    (
        hosp_no        integer        primary key    ,
        hosp_name    text        not null    ,
        hosp_city    text        not null   
    );   

create table Doc_Hosp
    (
        doc_no        integer        references Doctor    ,
        hosp_no        integer        references Hospital   
    );

insert into Doctor values(1,'Mr. Chandan','Ram krishna Nagar','Nasik');
insert into Doctor values(2,'Mr. Rahul','Gagapur road','Pune');
insert into Doctor values(3,'Mr. Amit','Ojhar','Mumbai');
insert into Doctor values(4,'Mr. Prasanna','Trimurti','Nagpur');
insert into Doctor values(5,'Mr. Atul','Colony','Kanpur');

insert into Hospital values(1,'Grand Hospital','Nasik');
insert into Hospital values(2,'Charity Hospital','Pune');
insert into Hospital values(3,'Perfect Hospital','Nagpur');
insert into Hospital values(4,'Maya Hospital','Kanpur');
insert into Hospital values(5,'Hayat Hospital','Mumbai');

insert into Doc_Hosp values(1,2);
insert into Doc_Hosp values(1,3);
insert into Doc_Hosp values(1,4);
insert into Doc_Hosp values(1,5);
insert into Doc_Hosp values(2,3);
insert into Doc_Hosp values(2,4);
insert into Doc_Hosp values(3,5);
insert into Doc_Hosp values(4,4);
insert into Doc_Hosp values(5,3);
insert into Doc_Hosp values(5,1);


a) 
create or replace function ass1()
    returns text as'

declare
    cursor1 cursor for
            select doc_no,doc_name,city
            from doctor;
   
    cursor2 cursor(city text)  for
            select hosp_no
            from hospital
            where hospital.hosp_city <> city;

    cursor3 cursor(dno integer) for
            select *
            from doc_hosp
            where doc_hosp.doc_no = dno;
       
    temp1 record;           
    temp2 record;
    temp3 record;
    flag integer;
    output text := ''\n'';

begin
   
    open cursor1;
    loop
        fetch cursor1 into temp1;
        exit when not found;   

        flag := 1;
       
        open cursor2(temp1.city);
        loop
            fetch cursor2 into temp2;   
            exit when not found;

            open cursor3(temp1.doc_no);
            loop
                fetch cursor3 into temp3;   
                exit when not found;

                if(temp2.hosp_no = temp3.hosp_no) then
                    flag := 1;
                output := output||''Match found : ''||temp2.hosp_no||''\n'';
                    exit;   
                else
                    flag := 0;
                end if;
            end loop;
            close cursor3;   -- cursor3 end

            if(flag = 0) then
                exit;
            end if;   
        end loop;
        close cursor2;  -- cursor2 end

        if(flag = 1) then
            output := output || temp1.doc_name ||''\n'';
        end if;
    end loop;
    close cursor1;    -- cursor1 end

    return output;
end;

'language plpgsql

/*
    OUTPUT 

SLIP=# select ass1();
     ass1
---------------
 
Mr. Chandan

(1 row)

*/



b)   create or replace function ass2()returns text as'

declare
    cursor1 cursor for
            select doc_no,doc_name
            from doctor;   

    cursor2 cursor(dno integer) for
            select *
            from doc_hosp
            where doc_hosp.doc_no = dno;

    temp3 hospital %rowtype;
    temp1 record;
    temp2 record;
    output text := ''\n'';

begin
    open cursor1;
    loop
        fetch cursor1 into temp1;
        exit when not found;

        output := output || temp1.doc_name || ''\n'';

        open cursor2(temp1.doc_no);
        loop
            fetch cursor2 into temp2;
            exit when not found;   

            for temp3 in select * from hospital where hospital.hosp_no = temp2.hosp_no
            loop
                 output := output ||''\t''||temp3.hosp_name||''\n'';
            end loop; -- close for temp3
        end loop;
        close cursor2; -- close cursor2
    end loop;   
    close cursor1; -- close cursor1

    return output;
end;

'language plpgsql;
/*

    OUTPUT

SLIP=# select ass2();
                                                                                                             ass2                                                                                                    
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
Mr. Chandan
        Charity Hospital
        Perfect Hospital
        Maya Hospital
        Hayat Hospital
Mr. Rahul
        Perfect Hospital
        Maya Hospital
Mr. Amit
        Hayat Hospital
Mr. Prasanna
        Maya Hospital
Mr. Atul
        Perfect Hospital
        Grand Hospital

(1 row)

*/

Wednesday, August 8, 2012

Linklist in Java

Here is simple Link List program in java.

import java.util.*;

class linklist
{
    public static void main(String args[])
    {
        LinkedList l1 = new LinkedList();
        LinkedList l2 = new LinkedList();
        LinkedList l3 = new LinkedList();
        LinkedList l4 = new LinkedList();
        int i,j;
      
        l1.add("a");
        l1.add("b");
        l1.add("c");
        l1.add("d");
        l1.add("e");
      
        l2.add("a");
        l2.add("c");
        l2.add("e");
        l2.add("g");
        l2.add("i");

        System.out.print("Intersection of link list : ");
        for(i = 0 ; i < 5 ; i++)
        {
            for(j = 0 ; j < 5 ; j++)
            {
                if(l1.get(i).equals(l2.get(j)))
                {
                    l3.add(l1.get(i));
                    break;
                }
            }
        }
        System.out.print(l3);
      
        System.out.print("\nUnion of list : ");
        for(i = 0 ; i < 5 ; i++)
        {
            l4.add(l1.get(i));
        }  
        for(i = 0 ; i < 5 ; i++)
        {
             for(j = 0 ; j < 5 ; j++)
             {
                 if(l2.get(i).equals(l1.get(j)))
                 {
                     break;
                 }
             }
             if(j == 5)
             {
                 l4.add(l2.get(i));
             }
        }
        System.out.print(l4);
    }
}

Dialog box in Java

Java Program which displays a dialog box on body load(Page Load).

import java.awt.*;
import java.awt.event.*;


public class msgDialog extends Frame
{
  msgDialog()
  {
    messageBox mb = new messageBox(this,"This is a Simple Dialog Box!!!");
    mb.setLocation(200,200);
    mb.setVisible(true);
  }
 
  public static void main(String args[])
  {
    msgDialog md = new msgDialog();
    System.out.println("Displaying Dialog Box....");
    md.setVisible(true);
  }
}

Message Box in Java

Display a Message box in Java on Button Click.

import java.awt.*;
import java.awt.event.*;

public class messageBox extends Dialog
{
  Button b1,b2;
  messageBox(Frame fm,String lab)
  {
    super(fm,"Message",true);
    setLayout(new GridLayout(2,1,0,0));

    Panel p1 = new Panel();
    Panel p2 = new Panel();

    p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,15));
    p2.setLayout(new FlowLayout(FlowLayout.CENTER,20,15));

    p1.add(new Label(lab));

    b1 = new Button("Ok");
    b1.addActionListener(new B1());
    p2.add(b1);

    b2 = new Button("Cancel");
    b2.addActionListener(new B1());
    p2.add(b2);

    add(p1);
    add(p2);

    setSize(350,125);
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent we)
      {
        System.exit(0);
      }
    });
  }

  class B1 implements ActionListener
  {
    public void actionPerformed(ActionEvent ae)
    {
      try
      {
        //Button ok = (Button)ae.getSource();
        //String s = ok.getLabel();
        if(ae.getSource() == b1 || ae.getSource() == b2)
        {
      System.out.println("Button Clicked");
      dispose();
      System.exit(0);
        }
      }
      catch(Exception e){} 
    }
  }
}

Servlet Session in Java

Here is a simple servlet program which display session information.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class sessionInfo extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    HttpSession mySession = req.getSession(true);
   
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
   
    out.println("<HTML><BODY>");
    out.println("<h3>Session Information</H3>");
    out.println("<BR>New Session    : " + mySession.isNew());
    out.println("<BR>Session ID : " + mySession.getId());
    out.println("<BR>Session Creation Time : " + mySession.getCreationTime());
    out.println("<BR>Session Last Accessed Time : " + mySession.getLastAccessedTime());

    out.println("<BR><H3>Request Information</H3>");
    out.println("<BR>Session ID from Request : " + req.getRequestedSessionId());
    out.println("<BR>Session ID via Cookie : " + req.isRequestedSessionIdFromCookie());
    out.println("<BR>Valid Session ID : " + req.isRequestedSessionIdValid());

    out.println("</BODY></HTML>");
    out.close();
  }
}

Animation in Java

Here is a Simple Animation Program in Java.

import java.awt.*;
import java.awt.event.*;

public class Animation extends Frame implements ActionListener,Runnable
{
    Button bStart,bExit;
    int i,j;
    Thread t;
    public Animation()
    {
        bStart = new Button("Start");
        bExit = new Button("Exit");
       
        setLayout(new FlowLayout());
        add(bStart);
        add(bExit);
       
        bStart.addActionListener(this);
        bExit.addActionListener(this);
    }
   
    public void run()
    {
        try
        {
            j = 0;
            for(i = 0 ; i < 100 ; i = i + 2)
            {
                paint(getGraphics());
                t.sleep(100);
            }
            i=50;
            for(j = 0 ; j < 100 ; j = j + 2)
            {
                paint(getGraphics());
                t.sleep(100);
            }
        }
        catch(Exception e){}
    }
   
    public void start1()
    {
        t = new Thread(this);
        try
        {       
            t.start();
        }
        catch(Exception e)
        {
            System.out.println("Exception Occured : " + e);
        }
    }
   
    public void paint(Graphics g)
    {
        //Color c = new Color(i);
        //setForeground(c);
        //g.setColor(Color.BLUE);
        g.clearRect(0,0,this.getHeight(),this.getWidth());
        g.drawOval(50+j,50+i,30,30);       
        return;
    }

    public void actionPerformed(ActionEvent ae)
    {
        if(ae.getSource() == bExit)
        {
            System.exit(1);
        }
        if(ae.getSource() == bStart)
        {
            System.out.println("Start Button Clicked...");
            start1();
        }
   
    }
    public static void main (String[] args)
    {   
        Animation a1 = new Animation();
        a1.setSize(400,400);
        a1.show();
    }
}

Menu Driven Program in Java

 A menu driven system which will perform following options for student data
 1) (Roll No,Name,Per)
 2) Insert, Update, Delete, Search  record
 3) Raise Exception if wrong data are entered like negative for roll no.

import java.io.*;
 import java.util.*;

 class NegativeNumberException extends Exception  { }


 class Slip5_9_13_2
 {
     public static void main(String agrs[]) throws IOException
     {
    
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       Student stud;
  &stud);
                       break;
                case 2:System.out.print("\nEnter Position where to insert record : ");
                        pos=Integer.parseInt(br.readLine());
         System.out.println("|------------------------------|");
         System.out.println("|\t [1] :Add \t\t|");
         System.out.println("|\t [2] :Insert \t\t|");
         System.out.println("|\t [3] :Update \t\t|");
         System.out.println("|\t [4] :Search \t\t|");
         System.out.println("|\t [5] :Delete \t\t|");
         System.out.println("|\t [6] :Print \t\t|");
         System.out.println("|\t [7] :Exit \t\t|");
          System.out.println("|------------------------------|");
         System.out.print("\nEnter Choice : ");
        
        
         try
          {
              ch=Integer.parseInt(br.readLine());
             
               switch(ch)
              {
                case 1:System.out.println("\nEnter Stud Details\n");
                       stud=new Student();
                       perfect=stud.read_data();   
                       if(perfect==1)
                           L.add(stud);
                       break;
                case 2:System.out.print("\nEnter Position where to insert record : ");
                        pos=Integer.parseInt(br.readLine());
                       if(pos>L.size())
                         {
                              System.out.println("\n\nPosition out of range\n\n");
                              break;
                         }   
                      
                       stud= new Student();
                       perfect=stud.read_data();
                       if(perfect==1)
                            L.add(pos,stud);
                       break;
                 case 3:System.out.print("\n Enter Roll no to update record : ");
                        no=Integer.parseInt(br.readLine());
                        found=0;
                        it=L.iterator();
                         while(it.hasNext())
                         {
                           stud=(Student)it.next();
                           if(stud.rno==no)
                              {
                                 found=1;   
                                  pos=L.indexOf(stud);
                                L.remove(pos);// remove old record from specified pos
                               
                                perfect=stud.read_data();
                               
                                if(perfect==1)
                                     L.add(pos,stud);
                            
                                break;
                               }
                         } 
                       if(found!=0)  //found==0
                           System.out.println("\nRoll_No not present so Record Not Updated ");
                                               
                       break;        
                              
                case 4:System.out.print("Enter Rollno to search record : ");
                       no=Integer.parseInt(br.readLine());
                       found=0;
                       it=L.iterator();
                      
                       while(it.hasNext())
                       {
                           stud=(Student)it.next();
                            if(stud.rno==no)
                              {
                                  found=1;
                                  pos=L.indexOf(stud);
                                  System.out.println("\n\nReord Found at "+pos+" Position\n");
                                  stud.show_data();
                                 
                                  break;
                                 
                              }
                       }
                       if(found!=1)
                             System.out.println("\nRoll_No not present so Record Not Found");
                         
                      break;
                     
                case 5:System.out.print("\n Enter Roll no to delete record : ");
                        no=Integer.parseInt(br.readLine());
                        found=0;
                        it=L.iterator();
                       
                        while(it.hasNext())
                         {
                          stud=(Student)it.next();
                              if(stud.rno==no)
                            {
                                 found=1;
                                 L.remove(stud);
                                 System.out.print("\nRecord deleted succesfully \n");
                                 break;   
                               }
                         }
                        if(found!=1)
                          System.out.println("\nRoll_No not present so Record Not Deleted\n");
                        
                       break;
            
                case 6:System.out.println("\n\n|------* Student Details *-----|");
                       System.out.println("|------------------------------|");
                      System.out.println("|ROLL NO\t NAME\t PERCENTAGE|");
                      System.out.println("|------------------------------|");

                      it=L.iterator();

                      while(it.hasNext())
                       {
                             stud=(Student)it.next();
                             stud.show_data();
                       }
                      System.out.println("|------------------------------|");
                      break;
                case 7:System.exit(0);           
               
            
              }//switch
           }
         catch(NumberFormatException n)
         {   System.out.println("Exception "+n); }
        
       }while(ch!=7);
     }//main
    
 }// class slip


 class Student
 {
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     int rno;    // Roll no
     String name; //name
     double per;//percentage
    
     int  read_data() throws IOException
     {
         try
         {
        
             System.out.print("Roll No : ");
             rno=Integer.parseInt(br.readLine());
                if(rno<0)
                   throw new NegativeNumberException();
           
             System.out.print("Name : ");
             name=br.readLine();
            
             System.out.print("Percentage : ");
             per=Double.parseDouble(br.readLine());
                 if(per<0)
                     throw new NegativeNumberException();
            
          }
         
         catch(NegativeNumberException n)
         {
          System.out.println("Exception: Number Must be Positive");
           return 0;
         } 
       return 1;    
       
      }// read_data()
     
      void show_data()
      {
          System.out.println("| "+rno+"\t | "+name+" | "+per+" |");
      }  

 }

File Watcher Program in Java

Java Program to create a class called File Watcher that can be given several file names
that may or may not exist. the class should start a thread for each file name
Each thread will periodically check for the existence of it's file.
If the file exist,the thread will write a message to the console & then end.

import java.io.*;
class SlipFileWatch
{
 public static void main(String args[]) throws IOException
  {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\n Enter Several N  files");
        try
        {
          int n =Integer.parseInt(br.readLine());
          System.out.println("\n Enter File name");
          for(int i=1;i<=n;i++)
                  new FileWatcher(br.readLine());
        }  
        catch(Exception e)
        { System.out.println("Invalid Input");}
    }
}   
   
class FileWatcher implements Runnable
{
    Thread T;
    String fname;
    FileWatcher(String fn)
    {
        fname=fn;
        T=new Thread(this,fname);
        System.out.println("\n\nNew = "+T);
        T.start();
    }
   
    public void run()
    {
        File f = new File(fname);
        if(f.exists())
          System.out.println(" "+fname+"  File Exist ");
        else 
          System.out.println(" "+fname+"  File Not Exist");
         try
          {
              Thread.sleep(1000);
          }
          catch(InterruptedException it){}
    }
}

Multiple Select Box and Combo box in Java

The java program given below does the following tasks,

 1) Button(<<) moves all items from list1 to list2.
 2) Button(<) moves single item from list1 to list2.
 3) Button(>>) moves all items from list2 to list1.
 4)Button(>) moves single item from list2 to list1.
  5)When 1 item is moved the next item should be highlighted automatically.
  6)No list box should contain duplicate entries
  7)Add & Remove button should work for their own list box & not for other

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;

public class Slip2_1 extends JFrame implements ActionListener
{
    List list1,list2;
    JButton b1,b2,b3,b4,b5,b6,b7,b8;
   
    JTextField t1;
  
    int i,j;
   // String d;
  
   

    public static void main(String args[])
       {
               Slip2_1  s = new Slip2_1();
              
       }
   
   // Container c=getContentPane();
       
    public Slip2_1()
    {
       
        super("List add/remove item ");
       
        setSize(550,450);
        setLocation(100,100);
        //setBounds(100,100,550,450);
        setVisible(true);
        setLayout(null);
       
        list1 = new List();
        list1.add("Ball");
        list1.add("Bat");
        list1.add("Stump");
        list1.add("Pad");
        list1.add("Gloves");
        list1.add("Shoes");
        list1.add("Helemet");
        list1.add("Bells");
        list1.add("Caps");
        list1.add("Medicine");
        list1.setBounds(75,100,90,200);
        add(list1);
       
        list2 = new List();
        list2.add("Computer");
        list2.add("Laptop");
        list2.add("Camera");
        list2.add("Veg");
        list2.add("Non_Veg");
        list2.add("Medicine");
        list2.setBounds(350,100,100,200);
        add(list2);
       
        b1 =new JButton("<<");
        b1.setBounds(225,100,75,25);
        add(b1);
       
        b2 =new JButton("<");
        b2.setBounds(225,150,75,25);
        add(b2);
       
        b3 =new JButton(">>");
        b3.setBounds(225,200,75,25);
        add(b3);
       
        b4 =new JButton(">");
        b4.setBounds(225,250,75,25);
        add(b4);
       
        //list1
        b5 =new JButton("Add");
        b5.setBounds(25,350,75,25);
        add(b5);
       
        b6 =new JButton("Remove");
        b6.setBounds(150,350,85,25);
        add(b6);
       
       
        //list2
        b7 =new JButton("Add");
        b7.setBounds(325,350,75,25);
        add(b7);
       
        b8 =new JButton("Remove");
        b8.setBounds(425,350,85,25);
        add(b8);
        
        
        b1.addActionListener(this) ;
        b2.addActionListener(this);
        b3.addActionListener(this) ;
        b4.addActionListener(this) ;
        b5.addActionListener(this);
        b6.addActionListener(this) ;
        b7.addActionListener(this) ;
        b8.addActionListener(this) ;
        
       
    }//slip2_1 constructor

 public void actionPerformed(ActionEvent ae)   
 {
    
    
     if(ae.getSource()==b1) // list1 << list2
     {
      // << copy all item from list1 to list2
     int cnt1 = list1.getItemCount();
     int cnt2 = list2.getItemCount();
     for(int i=0;i<cnt1;i++)
      {
       int flag=0;
        for(int j=0;j<cnt2;j++)
          if(list1.getItem(i).equalsIgnoreCase(list2.getItem(j))==true)
             {
                      flag=1;
                      break;
            }

          if(flag==0)
           list2.add(list1.getItem(i));
       }
      list1.removeAll();    
       } // b1 list1 << list2
    
    
     if(ae.getSource()==b3) // list2 >> list1
     {
      //  copy all item from list2 to list1
       
     int cnt1 = list1.getItemCount();
     int cnt2 = list2.getItemCount();
     for(int i=0;i<cnt2;i++)
      {
       int flag=0;
        for(int j=0;j<cnt1;j++)
          if(list1.getItem(j).equalsIgnoreCase(list2.getItem(i))==true)
             {
                      flag=1;
                      break;
            }

          if(flag==0)
           list1.add(list2.getItem(i));
       }
      list2.removeAll();    
       }// b3  list1 >> list2
    
  String d;

   if(ae.getSource()==b2) // list1 < list2
   {
       // add single selected item from list1 to list2
       d =list1.getSelectedItem();
       int cnt = list2.getItemCount();
       for(i=0;i<cnt;i++)
        {
           if(list2.getItem(i).equals(d)) // d is selcted item from list1
            return;
        }
       list2.add(d);
      
   }// b2 list1 < list2


 if(ae.getSource()==b4) // list1 > list2
   {
       // add single selected item from list2 to list1
       d =list2.getSelectedItem();
       int cnt = list1.getItemCount();
       for(i=0;i<cnt;i++)
        {
           if(list1.getItem(i).equals(d)) // d is selcted item from list1
            return;
        }
       list1.add(d);
      
   }// b4 list1 > list2
  
  
   if(ae.getSource()==b5)
            {
                 String m = "Enter the item";
                 String result  =JOptionPane.showInputDialog(m);
                 int cnti=0,cnt = list1.getItemCount();
                
                 if(result!=null)
                 if(result.equals("")!=true)
                   {
                     for(int i=0;i<cnt;i++)
                      {
                        if(result.equalsIgnoreCase(list1.getItem(i))==true)
                         {cnti=1; break;}
                      }
                    if(cnt==0 || cnti==0)
                    list1.add(result);
                  }
            }

         if(ae.getSource()==b6)
            {
                String m = "Enter the item";
                String result  = JOptionPane.showInputDialog(m);
                   list1.remove(result);
               }

           if(ae.getSource()==b7)
               {
            String res=JOptionPane.showInputDialog("Enter The Item");
                int cnti=0,cnt = list2.getItemCount();
           
                           
                if(res!=null)
                if(res.equals("")!=true)
                 {
                   for(int i=0;i<cnt;i++)
                    {
                      if(res.equalsIgnoreCase(list2.getItem(i))==true)
                       {cnti=1; break;}
                    }
                   if(cnt==0 || cnti==0)
                   list2.add(res);
                 }
              }

         if(ae.getSource()==b8)
             {
              String res= JOptionPane.showInputDialog("Enter the item");
                list2.remove(res);
             }

  
  

    
 }//actionperformed
   
}

HashTable In Java

Here is a Hash Table program in java.

In this program we are going to,

 1]Accept n  records of student(Name,percentage)
 2]Disply details of all students
 3]Find out highest marks

 import java.util.*;
 import java.io.*;
 class Slip1_2
 {
   public static void main(String args[]) throws IOException
   {
     
       Slip1_2 htc = new Slip1_2();
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int opt=1;
      while(opt!=4)
       {
         
           System.out.println("1:Enter Record");
           System.out.println("2:Disply Details");
           System.out.println("3:Find Highest Marks");
           System.out.println("4:Exit");
           System.out.print("Select Option : ");
      
        int r=Integer.parseInt(br.readLine());
      
        System.out.println();
        
           switch(r)
           {
               case 1:htc.get_record();      break;
               case 2:htc.disp_record();    break;
               case 3:htc.highest_record(); break;
               case 4:System.exit(0);
           }//switch
       }//while
     }//main


     Hashtable ht =new Hashtable();
     //Enumeration names;
     String nm;
    Slip1_2(){ }
    void get_record() throws IOException
     {
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       System.out.print("Enter n Records of stud : ");       int n=Integer.parseInt(br.readLine());
       Double d;
          System.out.println();
          for(int i=0;i<n;i++)
          {
               System.out.print("Enter Name : ");    nm = br.readLine();
              System.out.print("Enter Percentage : ");   d = Double.parseDouble(br.readLine());
              System.out.println();
              ht.put(nm,d);
          }
      }
    
         
   
   
     void disp_record()
     {
         Enumeration names= ht.keys();
         //Returns an enumeration of the keys in this hashtable. <-=keys()
         while(names.hasMoreElements())     //Tests if this enumeration contains more elements.
         {
             nm=(String)names.nextElement();
                             //the next element of this enumeration.
 
              System.out.print(nm+" => "+ht.get(nm));
              //Returns the value to which the specified key is mapped in this hashtable.
              System.out.println();
         }
             System.out.println();
      }
  
     void highest_record()
     {
         Collection c=ht.values();
         //Object obj=Collections.max(c);
         //System.out.println("Highest Marks: "+obj);
         System.out.println("Highest Marks: "+Collections.max(c));
     }   
   
 }

Tuesday, August 7, 2012

LRU Page replacement Algorithm

Below is a C Program Which Explains the LRU Page replacement Algorithm in a Proper and Clear Way.

#include<stdio.h>
#include<conio.h>
struct node
{
  int pno,reftime;
}frames[20];
int n;

int page_found(int pno)
{
  int fno;
  for(fno=0;fno<n;fno++)
    if(frames[fno].pno==pno)
       return fno;
    return -1;
}

int get_free_frame()
{  int fno;
  for (fno=0; fno<=n; fno++)
    if (frames[fno].pno==-1)
        return(fno);
   return(-1);
}

int get_lru_frame()
{
  int fno;
  int selfno=0;
  for (fno=1; fno<n; fno++)
    if(frames[fno].reftime<frames[selfno].reftime)
    selfno=fno;
  return selfno;
}
void main()
{
   int p_request[]={5,8,10,14,10,9,5,10,8,5,1,10,9,12,10};
   int size=15,currtime;
   int page_falts=0,i,j,fno;
   clrscr();
   printf("\nHow many frames:");  scanf("%d",&n);
   //initialize frames
   for (i=0; i<n; i++)
   { frames[i].pno=-1;
     frames[i].reftime=-1;
   }

   printf("\nPageNo     Page Frames          Page Fault");
   printf("\n-------------------------------------------");
   currtime=0;
   for(i=0;i<size;i++)
   {
     j=page_found(p_request[i]);
     if(j==-1)  //page fault occurs
     {
       j=get_free_frame();
       if (j==-1) //no free frame - do page replacement
         j=get_lru_frame();
       page_falts++;
       frames[j].pno=p_request[i];
       frames[j].reftime=currtime;
       printf("\n%4d\t ",p_request[i]);
       for (fno=0; fno<n; fno++)
         printf("%4d",frames[fno].pno);
       printf(" : YES");
     }
    else//page found
    {
       printf("\n%4d\t ",p_request[i]);
       frames[j].reftime=currtime;
       for (fno=0; fno<n; fno++)
         printf("%4d",frames[fno].pno);
       printf(" : NO");
    }
       currtime++;
   }
  printf("\n------------------------------------------");
  printf("\n Number of Page_Falts=%d",page_falts);
  getch();
}

MFU Page Replacement Algorithm

Here is a C Program Which Explain the Working of MFU Page Replacement Algorithm in C.

#include<stdio.h>
#include<conio.h>
struct node
{
  int pno,freq;
}frames[20];
int n;

int page_found(int pno)
{
  int fno;
  for(fno=0;fno<n;fno++)
    if(frames[fno].pno==pno)
       return fno;
    return -1;
}

int get_free_frame()
{  int fno;
  for (fno=0; fno<=n; fno++)
    if (frames[fno].pno==-1)
        return(fno);
   return(-1);
}

int get_mfu_frame()
{
  int fno;
  int selfno=0;
  for (fno=1; fno<n; fno++)
    if(frames[fno].freq>frames[selfno].freq)
    selfno=fno;
  return selfno;
}
void main()
{
   int p_request[]={5,8,10,14,10,9,5,10,8,5,1,10,9,12,10};
   int size=15;
   int page_falts=0,i,j,fno;
   clrscr();
   printf("\nHow many frames:");  scanf("%d",&n);
   //initialize frames
   for (i=0; i<n; i++)
   { frames[i].pno=-1;
     frames[i].freq=0;
   }

   printf("\nPageNo     Page Frames              Page Fault");
   printf("\n---------------------------------------------------");
   for(i=0;i<size;i++)
   {
     j=page_found(p_request[i]);
     if(j==-1)  //page fault occurs
     {
       j=get_free_frame();
       if (j==-1) //no free frame - do page replacement
         j=get_mfu_frame();
       page_falts++;
       frames[j].pno=p_request[i];
       frames[j].freq=1;
       printf("\n%4d\t ",p_request[i]);
       for (fno=0; fno<n; fno++)
         printf("%4d:%2d",frames[fno].pno,frames[fno].freq);
       printf(" : YES");
     }
    else //page found in frame j
    {
       printf("\n%4d\t ",p_request[i]);
       frames[j].freq++;
       for (fno=0; fno<n; fno++)
         printf("%4d:%2d",frames[fno].pno,frames[fno].freq);
       printf(" : NO");
    }
   }
  printf("\n-------------------------------------------------------");
  printf("\n Number of Page_Falts=%d",page_falts);
  getch();
}

C Program To Print Lines From File

Below Given Is a Simple Program which prints the lines of a file but with different user given instructions.

The Feature of the Program is as Follows:

The Program Prints,

1) print first 10 lines of file

2) print last  20 lines of file

3) print all lines of file


#include <stdio.h>
#include <conio.h>
#include <process.h>
void main(int argc, char *argv[])
{
    int tot_lines,cnt;
    char *ptr;
    if( argc != 3 )
    {
        printf("\nInvalid number of arguments\n");
        return;
    }
    if( *argv[1] == '+' || *argv[1] == '-')
    {
        tot_lines = count_lines(argv[2]);
        ptr = argv[1];
        ptr++;  // skip '+' or '-'
        cnt = atoi(ptr);
        if ( cnt > tot_lines)
        {
            printf("\nInvalid line count\n");
            return;
        }
    }
    if( *argv[1] == '+' ) // typeline +cnt fname
        print_top_lines(argv[2],cnt);
    else
    if( *argv[1] == '-' ) // typeline -cnt fname
        print_bottom_lines(argv[2],cnt,tot_lines);
    else if (*argv[1]=='a')
        print_all_lines(argv[2]);
     else
         printf("\nInvalid option...");
} // main

int count_lines( char *fname)
{
    int tot_lines,ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open file");
        return(-1);
    }
    tot_lines = 0;
    while (fgets(buff,80,fp)!=NULL)
       tot_lines++;
    tot_lines++;
    fclose(fp);
    return(tot_lines);
} // count lines


int print_all_lines( char *fname)
{
    int ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    printf("\n");
    while(fgets(buff,80,fp)!=NULL)
     printf("%s",buff);

    fclose(fp);
    return;
} // print all lines

int print_top_lines(char *fname, int cnt)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];

    curr_cnt = 0;

    fp = fopen(fname,"r");

    fgets(buff,80,fp);
    printf("\n");
    while( curr_cnt < cnt )
    {
        printf("%s",buff);
        fgets(buff,80,fp);
        curr_cnt++;
    }
    fclose(fp);
    return;
}
int print_bottom_lines(char *fname, int cnt, int tot_lines)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];
    curr_cnt = 0;
    printf("\n");
    fp = fopen(fname,"r");
    while( 1)
    {
        fgets(buff,80,fp);
        curr_cnt++;
        if( curr_cnt >= tot_lines - cnt )
            break;
    }
    while( fgets(buff,80,fp) != NULL)
    {
        printf("%s", buff);
    }
    fclose(fp);
    return;
}

Shell Program For Searching a String.

Below is a Simple Shell Program in C Language which Implement search command as follows

1) search first occurrence of pattern in file name

2) count no of occurrences of pattern in file name

3) search all occurrences of pattern in file name


#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <string.h>


void main( int argc, char *argv[])
{
    char pattern[20],fname[20],option;

    printf("\nSearch Starts..");
    if( argc != 4 )
    {
        printf("\nInvalid number of arguments");
        return;
    }// if
    // set param
    option = *argv[1];
    strcpy(pattern,argv[2]);
    strcpy(fname,argv[3]);

    switch(option)
    {
        case 'f' :       find_first_occ(fname,pattern);
                        break;
        case 'c' :       count_all_occ(fname,pattern);
                        break;
        case 'a' :       print_all_occ(fname,pattern);
                        break;
        default  :        printf("\nInvalid option");
                        break;
    } // switch
} // main

int find_first_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr;
    int i,m,c,lineno;

    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    lineno=0;
    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);
        lineno++;

        ptr = strstr(str,pattern);
        if( ptr != NULL )
        {
            printf("\n lineno = %d : Line = %s", lineno,str);
            printf("\n position = %d", ptr - str +1 );
            break;
        }
    } // while
    fclose(fp);
    return;
} // find first occ


int count_all_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr,*ptr1;
    int count=0;

    int i,m,c,lineno;

    fp = fopen(fname,"r");

    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);

        ptr1 = str;
        ptr = strstr(ptr1,pattern);

        while( ptr != NULL )
        {
            count++;
            ptr1= ptr+1;
            ptr = strstr(ptr1,pattern);
        }
    } // while
    fclose(fp);
    printf("\nPattern %s occurs %d times", pattern,count);
    return;
} // count all occ


int print_all_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr,*ptr1;
    int lineno=0;

    int i,m,c;

    fp = fopen(fname,"r");

    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);
        lineno++;
        if( strstr(str,pattern) != NULL )
            printf("Line:%d: %s",lineno,str);

    } // while
    fclose(fp);
    return;
} // print all occurences

LOOK Algorithm using Disk Scheduling

Below is a Simple Program in C Language Which Explains Simulation of LOOK Algorithm of Disk Scheduling

#include <alloc.h>

struct reqblock
{ int block;
   struct reqblock *next;
} *first,*curr,*prev;

int n,currpos,headmove=0;
char direction;

void get_req_blocks();
 void scan();
void main()
{
  clrscr();
   printf("\nEnter total number of blocks in the disk:");
   scanf("%d",&n);
   printf("\nEnter request block numbers string terminated by -1\n");
    get_req_blocks();
    //print req string
    curr=first;
    while(curr!=NULL)
    { printf("%d\t",curr->block);
      curr=curr->next;
     }
     printf("\nEnter direction of head movement:(F-Forwad,B-Backward):");
     flushall(); scanf("%c",&direction);
      printf("\nEnter block no. as current head position:");
      scanf("%d",&currpos);
     scan();
     printf("\nNumber of headmovements:%d",headmove);
  }

  void get_req_blocks()
  { struct reqblock *t,*pt;
    int blockno;
    first=NULL;
    scanf("%d",&blockno);
    while(blockno!=-1)
    { curr=(struct reqblock *) malloc(sizeof(struct reqblock));
      curr->block=blockno;
      curr->next=NULL;
     if (first==NULL) //req str is empty
         first=curr;
     else
         prev->next=curr;
      prev=curr;
      scanf("%d",&blockno);
    }//while
  }

 void scan()
  {  int selblock;
     printf("\nList of request served:\n");

     while(first!=NULL)
     {
       if (!look())
         direction=(direction=='F')?'B':'F';
       selblock=get_next_block();
       if (selblock!=-1)
           printf("%d\t",selblock);
        if (direction=='F')
        {  if (currpos==n-1)
             direction='B';
         else
         {  currpos++; headmove++;
          }
      }
      else
      {
         if (currpos==0)
             direction='F';
         else
         { currpos--;  headmove++;}
       }
      }//while
      headmove--;
   }

 int look()
 {
   if (direction=='F')
   {  curr=first;
      while(curr!=NULL)
      {   if (curr->block>currpos)
          return(1);
          curr=curr->next;
       }
       return(0);
     }
   else //direction='B'
   {   curr=first;
      while(curr!=NULL)
      {  if (curr->block<currpos)
          return(1);
          curr=curr->next;
       }
       return(0);
     }
 }

 get_next_block()
   {
        int selblock;
         curr=first;
          while(curr->block!=currpos)
           {  prev=curr;
              curr=curr->next;
              if (curr==NULL) return(-1);
            }
            selblock=curr->block;
            if (curr==first)
               first=first->next;
             else
               prev->next=curr->next;
             free(curr);
            return(selblock);
  }

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...