Wednesday, February 26, 2014

Linux AWK Command

Many useful awk programs are short, just a line or two. Here is a collection of useful, short programs to get you started. Some of these programs contain constructs that haven't been covered yet. The description of the program will give you a good idea of what is going on, but please read the rest of the book to become an awk expert!
Most of the examples use a data file named `data'. This is just a placeholder; if you were to use these programs yourself, you would substitute your own file names for `data'.
awk '{ if (length($0) > max) max = length($0) }

END { print max }' data
This program prints the length of the longest input line.

awk 'length($0) > 80' data
This program prints every line that is longer than 80 characters. The sole rule has a relational expression as its pattern, and has no action (so the default action, printing the record, is used). 


expand data | awk '{ if (x < length()) x = length() }

END { print "maximum line length is " x }'
This program prints the length of the longest line in `data'. The input is processed by the expand program to change tabs into spaces, so the widths compared are actually the right-margin columns. 


awk 'NF > 0' data
This program prints every line that has at least one field. This is an easy way to delete blank lines from a file (or rather, to create a new file similar to the old file but from which the blank lines have been deleted). 


awk 'BEGIN { for (i = 1; i <= 7; i++)

print int(101 * rand()) }'
This program prints seven random numbers from zero to 100, inclusive.


ls -lg files | awk '{ x += $5 } ; END { print "total bytes: " x }'
This program prints the total number of bytes used by files


ls -lg files | awk '{ x += $5 }

END { print "total K-bytes: " (x + 1023)/1024 }'
This program prints the total number of kilobytes used by files


awk -F: '{ print $1 }' /etc/passwd | sort
This program prints a sorted list of the login names of all users. 


awk 'END { print NR }' data
This program counts lines in a file. 


awk 'NR % 2' data
This program prints the even numbered lines in the data file. If you were to use the expression `NR % 2 == 1' instead, it would print the odd number lines.

Tuesday, February 25, 2014

JAVA JDBC Connection

 import java.sql.*;
import java.io.*;

class dataDB
{
DataInputStream in =new DataInputStream(System.in);
Connection con;
void  connect()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:she","scott","tiger");
System.out.println("Connected");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void insert()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
System.out.println("How many records to insert?");
int n=Integer.parseInt(in.readLine());
for(int i=1;i<=n;i++)
{
System.out.println("Enter studid:");
int si=Integer.parseInt(in.readLine());
System.out.println("Enter stud name:");
String na=in.readLine();
System.out.println("Enter marks:");
int ma=Integer.parseInt(in.readLine());
String query="insert into studs values("+si+",'"+na+"',"+ma+")";
int rows=stmt.executeUpdate(query);
System.out.println("Rows Inserted");
con.commit();
}
}
catch(Exception e1)
{
System.out.println(e1+"Exception insertion");
}
}
void create()
{
Statement stmt;
try
{
stmt=con.createStatement();
String query="create table studs(studid number(3),name varchar2(20),marks number

(5))";
int rows=stmt.executeUpdate(query);
System.out.println("Table Created");
}
catch(SQLException e1)
{
//System.out.println(e1.getMessage());
System.out.println("Table already exists");
}
}

void update()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
System.out.println("Enter studid to update:");
int sid=Integer.parseInt(in.readLine());
System.out.println("Enter new marks:");
int ma=Integer.parseInt(in.readLine());
String query="update studs set marks="+ma+"where studid="+sid;
int rows=stmt.executeUpdate(query);
System.out.println(rows+"Rows Updated");
con.commit();
}
catch(Exception e1)
{
System.out.println(e1.getMessage());
}
}

void delete()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
System.out.println("Enter studid:");
int si=Integer.parseInt(in.readLine());
String query="delete from studs where studid="+si;
int rows=stmt.executeUpdate(query);
System.out.println(rows+"Rows Deleted");
con.commit();
}
catch(Exception e1)
{
System.out.println(e1+"Exception Deletion");
}
}

void disp()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from studs");
System.out.println("Student Details");
System.out.println("Studid      Name    Marks");
while(rs.next())
{
System.out.print(rs.getInt(1)+"           ");
System.out.print(rs.getString(2)+"           ");
System.out.print(rs.getString(3)+"         \n ");
}
}
catch(Exception e1)
{
System.out.println(e1+"Exception insertion");
}
}

public static void main(String ar[])throws IOException
{
DataInputStream in =new DataInputStream(System.in);
dataDB d=new dataDB();
int c;
System.out.println("VARIOUS OPERATION ON DATABASE");
d.connect();
do
{
System.out.println("1.create");
System.out.println("2.insert");
System.out.println("3.delete");
System.out.println("4.modify");
System.out.println("5.display");
System.out.println(" enter ur choice:");
int ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
d.create();
break;
case 2:
d.insert();
break;
case 3:
d.delete();
break;
case 4:
d.update();
break;
case 5:
d.disp();
break;
}
System.out.println("Enter 1->Continue");
c=Integer.parseInt(in.readLine());
}while(c==1);
}
}

Java Animation (Mouse Events)

import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;



             /*<applet code="DigitalClock" width=800 height=800>
             </applet>*/

public class DigitalClock extends Applet
    implements Runnable,MouseMotionListener ,MouseListener
{

    Font theFont;
    Date theDate;
    Thread runner;
    int x1;
    int y1;
    int x2;
    int y2;
    int cx1;
    int cy1;
    int cx2;
    int cy2;

    public DigitalClock()
    {
        theFont = new Font("TimesRoman", 1, 24);
    }

    public void init()
    {
        x1 = 100;
        y1 = 100;
        x2 = 150;
        y2 = 100;
 this.addMouseMotionListener(this);
this.addMouseListener(this);

    }

public void mouseMoved(MouseEvent event){

      setBackground(Color.red);

}

public void mouseDragged(MouseEvent event){

      setBackground(Color.cyan);

}
public void mouseClicked(MouseEvent e){

if (e.getButton() == MouseEvent.BUTTON1)
{
   runner.stop();
      runner = null;     
}
if (e.getButton() == MouseEvent.BUTTON3)
{

           runner = new Thread(this);
            runner.start();
}

 
      setBackground(Color.blue);

}

public void mouseEntered(MouseEvent e){

      setBackground(Color.cyan);

}

public void mouseExited(MouseEvent e){

      setBackground(Color.green);

}

public void mousePressed(MouseEvent e){

      setBackground(Color.magenta);

}

public void mouseReleased(MouseEvent e){

      setBackground(Color.yellow);

}
    public void start()
    {
        if(runner == null)
        {
            runner = new Thread(this);
            runner.start();
        }
    }

    public void stop()
    {
        if(runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        do
        {
            theDate = new Date();
            x1 = x1 + 100;
            x2 = x2 + 100;
            if(x2 > 1000)
            {
                x2 = 150;
                x1 = 100;
            }
            repaint();
            try
            {
                Thread.sleep(200L);
            }
            catch(InterruptedException interruptedexception) { }
        } while(true);
    }

    public void paint(Graphics g)
    {
        g.drawLine(x1, y1, x2, y2);
        g.drawOval(x1, y1, x2, y2);
        g.setFont(theFont);
        g.drawString(theDate.toString(), 10, 50);
    }
}

Wednesday, February 12, 2014

Java Programming Applet Animation

import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Date;


             /*<applet code="DigitalClock" width=800 height=800>
             </applet>*/

public class DigitalClock extends Applet
    implements Runnable
{

    Font theFont;
    Date theDate;
    Thread runner;
    int x1;
    int y1;
    int x2;
    int y2;
    int cx1;
    int cy1;
    int cx2;
    int cy2;

    public DigitalClock()
    {
        theFont = new Font("TimesRoman", 1, 24);
    }

    public void init()
    {
        x1 = 100;
        y1 = 100;
        x2 = 150;
        y2 = 100;

    }

    public void start()
    {
        if(runner == null)
        {
            runner = new Thread(this);
            runner.start();
        }
    }

    public void stop()
    {
        if(runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        do
        {
            theDate = new Date();
            x1 = x1 + 100;
            x2 = x2 + 100;
            if(x2 > 1000)
            {
                x2 = 150;
                x1 = 100;
            }
            repaint();
            try
            {
                Thread.sleep(200L);
            }
            catch(InterruptedException interruptedexception) { }
        } while(true);
    }

    public void paint(Graphics g)
    {
        g.drawLine(x1, y1, x2, y2);
        g.drawOval(x1, y1, x2, y2);
        g.setFont(theFont);
        g.drawString(theDate.toString(), 10, 50);
    }
}

Sunday, February 2, 2014

Linux Grep Command

Create a file of yellow pages with details of cutomer name , address , phone number,date . Perform
the following command for the above file.
1. 1. display the line that having phone number with extension “x” and end with 4 digits” ex:
(x1234)
2. extract the date using the format of ddmmyear.
3. Display the line the customer name do not end with “s”
4. To print two lines after the pattern searched regarding to the customer address.
5. Display the customer name which starts with “y”
6. Display the count of the customers situated in madurai.
7. Display the line that having customer name “vinai” not using grep / egrep command by
8. Print the matching line along with the line number.
9. Print the line donot have the city as chennai.
10. Dipslay the line with zero byte with any pattern searching.
ignoring case.
Answer:
1. egrep “x.{4}$” filename
2. egrep “[az]{3}[][09]{1,2}” filename
3. grep e '[^s]$' filename
4. grep A 2 “pattern” filename
5. grep “^y” filename
6. grep c “madurai” filename
7. look f “vinai” filename
8. grep n “pattern” filename
9. grep v “pattern” filename
10. grep z “patern” filename


Create a student details of various department with Fields (studentname, regno, marks,
Percentage). Perform the following commands based on the above file.
1. Print all the student name containing a vowel (a, e, i, o, or u) followed by a single character
followed by the same vowel again. Thus, it will find “eve” or “adam” but not “vera”.
2. Print the line that’s having upper case letters of student name.
3. Print 2 lines before the matching pattern
4. Display only the student name start with “a” and end with “i”
5. Display the student details having mark of 100
6. Display computer science student name alone.
7. Extract 2011 batch student Regno for all the departments.
8. Print the student detail who doesn’t having the 80% .
9. Display the count of student s having name “Jeya”
10. Display the student details name starts with “L” or “T” (no case sensitive).
egrep "[11]{2}[az]{4}[09]{2}" stu
saran |11pite02|100
Answer:
1. egrep "^[aeiou]{1}[az]{1}[aeiou]{1}” file1
2. egrep '[[:upper:]]' filenmae
3. grep B 2 “patterrn” filename
4. grep “^a . * i$” filenmae
5. grep 100 fnanme
6. egrep "pite" stu|cut d"|" f1
7. cut d"|" f2 stu|egrep ^11
8. grep – v 80
9. grep –c “pattern” fname
10. egrep ‘^[LT].*’ fname
Create two files as given below
Water pollution -
• Water pollution is one of the most serious environmental problems.
• It occurs when water is contaminated by such substances as human and animal wastes, toxic
   industrial chemicals, agricultural residues, oil and heat.
• Most of our water bodies— rivers, lakes, seas, oceans, estuaries and underground water sources
     (i.e., tubwells, bore wells) are gradually becoming polluted.
• In the course "Covered so far, you have seen how deforestation, urbanization, intensive
agriculture and industrialization have caused pollution of water bodies.
•Air Pollution
• Air pollution is a common problem in our country.
• Air pollution comes from dangerous chemical substances which spread in the air, for example,
carbon monoxide, CFC, carbon dioxide, hydro carbon, sulfur dioxide, etc.
• Those substances are produced by human activities such as the using of vehicles which produce
smokes causing the air pollution and factory activities such as producing the tires and fake animal
skin which use fuels and machine that trigger the air pollution.
• However, most people are lack of attention to this problem. Even, they do not care that air
pollution can be very dangerous for the human health and our environment.
1. print the filename itself which is having the pattern people.
2. Print the matching lines from both the files for the pattern “pollution”
3. Print the matching lines along with line number from both the files for the pattern “human”
(ignorecase).
4. Print the 1 line above and below the matching pattern “animal” from both files.
5. Print the common pattern from file1 and file2.
6. Display line for that pattern starts with “C” and ends with “y” for “Air pollution file”
7. Search for the pattern “country” in file1 and file2 and suppress the error message.
8. Search for the full line content in the file1
9. Print the line which do not have the word “is” in file1
10. Print line which is start with the word “Air” (ignore case)
Answer:
1.grep –l people f1 f2
2. grep –h “pollution” f1 f2
3. grep –n i “human” f1 f2
4. grep –C 1 “animal” f1 f2
5. grep –f f1 f2
6. egrep ‘^C.*y$’ f2
7. grep –s “country” f2
8. grep –X “sdfafds” f1
9. grep –v “is” f1
10. look -f “Air” f2