Monday 7 April 2014

Check for prime number in Objective-C

#import <Foundation/Foundation.h>

int isPrime(int n)
{
int i;
if(n==1||n==2)
return 0;
for(i=3;i<=n/2;i++)
if(n%i==0)
return 0;
return 1;
}

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   int i;
   for(i=1;i<=100;i++)
   {
   if(isPrime(i)==1)
    NSLog (@"%d is Prime number,",i);
   else
    NSLog (@"%d is not Prime number,",i);
   }
 [pool drain];
   return 0;
}

How to print Fibonacci series in Objective-C

#import <Foundation/Foundation.h>

int fibonacci(int n)
{
if(n<=2)
return(1);
return fibonacci(n-1) + fibonacci(n-2);
}

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   int i;
   for(i=1;i<=8;i++)
   {
   int fib=fibonacci(i);
   NSLog (@"%d,",fib);
   }
 [pool drain];
   return 0;
}

Find Factorial of a number recursively in Objective-C

#import <Foundation/Foundation.h>

float factorial(int n)
{
if(n<=1)
return(1);
return n*factorial(n-1);
}

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   long fact=factorial(8);
   NSLog (@"Factorial of 8 is %ld",fact);
 [pool drain];
   return 0;
}

Sunday 6 April 2014

How to format Date using SimpleDateFormat in JSP

<%@ page import="java.io.*,java.util.*" %>
<%@ page import="javax.servlet.*,java.text.*" %>
<html>
<head>
<title>Current Date & Time</title>
</head>
<body>
<center>
<h1>Display Current Date & Time</h1>
</center>
<%
   Date currDt = new Date( );
   SimpleDateFormat sdf =  new SimpleDateFormat ("dd/MM/yyyy hh:mm:ss");
   out.print( "<h1 align=\"center\">" + sdf.format(currDt) + "</h1>");
%>
</body>
</html>

How to open last edited file in Linux

Suppose you have edited last three following files using vi
user1@localhost$ vi file1.txt
user1@localhost$ vi file2.txt
user1@localhost$ vi file3.txt

Now to open the last edited file command is

user1@localhost$ vi ls -t | head -1

Here ls -t sort the file in order of last modified file and head -1 picks up the first file.

So here the output of the command executed above will be file1.txt file will be opened in vi for editing.

How to connect to Oracle 11g using PYTHON

import cx_Oracle
con = cx_Oracle.connect('username/password@[ipaddress or hostname]/SID')
# for example con = cx_Oracle.connect('scott/tiger@127.0.0.1/orcl')
               
ver = con.version.split(".")
print ver
             
con.close()

Manipulating string variable in Python

#!/usr/local/bin/python2.7
   
#Concatenate string
a="This "
b="Python "
c="program "
d="is "
e="about "
f="variable "
resultstr=a+b+c+d+e+f
print(resultstr)

#Repeat string n number of times
str="I will not stop.." * 4
print("\n" + str)
#This is the output : I will not stop..I will not stop..I will not stop..I will not stop..

#Concatenation of Number and string

n=4
m=4.5

s="We can repeat string " + repr(n) + " times but not " + repr(m) + " times"

Different methods used in array in PYTHON

#!/usr/local/bin/python2.7
# pleases follow the indention as it is most important in python. python don't use begin/end, if/end if or loop/
#end loop so python identify statement by indention.

from array import *
my_array = array('i', [1,2,3,4,5,6,7,8,9])

#inserting in nth position .insert(position,value)
my_array.insert(0,12)

#appending value to to the last position
my_array.append(10)

#extending python array using extend method

my_extnd_array = array('i', [7,8,9,10])
my_array.extend(my_extnd_array) # extend(array object)

#add item from list into array using fromlist
lst = [13,14,15]
my_array.fromlist(lst)

#check the number of occurance of an element in array
print('\n9 occured %d times'%my_array.count(9))

#convert any array element to list using tolist() method
c=my_array.tolist()

#remove element from the list from any position
my_array.remove(4) # remove element from 4th position

#reverse elements in a python array using reverse method
my_array.reverse()

#remove element from the last position using pop method
my_array.pop()

#Search any element by index using index method
print('\nElement in 6th position is %d'%my_array.index(6))

#print array list
for i in my_array:
  print(i)

How to check prime number in using Python.

#!/usr/local/bin/python2.7
# pleases follow the indention as it is most important in python. python don't use begin/end, if/end if or loop/
#end loop so python identify statement by indention.

def PrimeNumber(n):
  if n==1 or n==2:
    return 0
  for i in range(3,n/2+1):
    if n%i == 0:
      return 0
  return 1

n = input ('Enter the number to check prime: ')
if PrimeNumber(n)==1:
  print('\n%d is Prime Number'%n)
else:
  print('\n%d is not Prime Number'%n)

How to find factorial of a number using Python in both iteration and recursive method

#!/usr/local/bin/python2.7
# pleases follow the indention as it is most important in python. python don't use begin/end, if/end if or loop/
#end loop so python identify statement by indention.

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

    return fact


def FactorialRecursive(n):
  if n <=1:
    return 1
  return n*FactorialRecursive(n-1)

n = input ('Enter the number to find factorial: ')
print('\nFactorial of a number %d is %d'%(n,Factorial(n)))

print('Factorial (recursive) of a number %d is %d'%(n,FactorialRecursive(n)))

Saturday 5 April 2014

How to read a file from script using PERL

#!/usr/bin/perl
use strict;
use warnings;

use Path::Class;
use autodie; # die if error in reading file

my $dir = dir("/tmp"); # /tmp

my $file = $dir->file("sample_file.txt");

# Read in the whole contents of the file 
 
my $stuff = $file->slurp();

# openr() returns an IO::File object to read from 
 
my $file_handle = $file->openr();

# Read one line at a time
 
 while( my $line = $file_handle->getline() ) {
print $line;
}

How to write to a file using PERL script

#!/usr/bin/perl
use strict;
use warnings;

use Path::Class;
use autodie; # die if writing a file fails

my $dir = dir("/tmp"); # /tmp

my $file = $dir->file("file.txt"); # /tmp/file.txt

# Get a File Handle (IO::File object) you can write to
my $file_handle = $file->openw();

my @arr = ('This', 'is', 'my', 'first',"Perl","Program");

foreach my $line ( @arr ) {
    # Add the line to the file
    $file_handle->print($line . "\n");

Using JDBC thin client to connect to Oracle - A sample JSP.

<!--This is a program written in HTML JSP embedded. This program use JDBC thin client to connect to Oracle 11g. Page gives user to select from 2 checkbox options and uses post method  two create criteria for SQL query. A single file is used for both post and get method, two separate form is used for post and get method.-->

<html>
<head>
  <title>Employee</title>
</head>
<body>
  <h1>Employee Details</h1>
  <h3>Choose Grade(s):</h3>
  <form method="get">
    <input type="checkbox" name="grade" value="Worker">Worker
    <input type="checkbox" name="grade" value="Staff">Staff
    <input type="submit" value="Query">
  </form>

  <%@ page import = "java.sql.*" %>
  <%
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@[ipaddress or hostname]:portnumber:sid","username","password";
    Statement stmt = conn.createStatement();
    String sql="select emp_code,emp_name,date_of_birth,emp_sex from employee_master";
    String[] grade = request.getParameterValues("grade");
if (grade != null)
    {
    if(grade.length>0)
        {
        sql+=" where emp_grade in (";
        int i;
        for (i = 0; i < grade.length; ++i)
        {
        sql+="'" + grade[i].charAt(0) + "'";
        if(i<grade.length-1)
        sql+=",";
        }
        sql+=")";
        sql+=" and status='A' order by emp_name";
        %>
        <hr>
        <form method="get" action="dbconn.jsp">
        <tr> <%
            try
            { %>
              <table border=1 cellpadding=5><tr><td> Emp Code</td><td>Emp Name</td><td>DOB</td><td>Sex</td><td><%=sql%></td></tr>
            <%  ResultSet rs = stmt.executeQuery(sql);
              while (rs.next()) {
          %>
                  <tr>
                    <td><%= rs.getString("emp_code") %></td>
                    <td><%= rs.getString("emp_name") %></td>
                    <td>$<%= rs.getString("date_of_birth") %></td>
                    <td><%= rs.getString("emp_sex") %></td>
                  </tr>
          <%
              }
          %>
                </table></form>
              <a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>
          <%
              rs.close();
            }
            catch(SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
      stmt.close();
      conn.close();
  %>
</body>
</html>

Python programing basic examples

#!/usr/local/bin/python2.7

# printing a string
print "Hello, World!"

#defining and invoking function
def hello (what):
 text = "Hello, " + what + "!"
 print text

hello("Dave")

#---------------------------------------------
# functions returning multiple values.
str = "foo"; lst = ["abra", 2038, "cadabra"]
for char in str:
  print char

def squareandcube (x):
 return x*x, x*x*x

a, b = squareandcube(3)
print a
print b

#---------------------------------------------
# functions used as an iterable object creating its own object runtime.
def cubeseries ():
 for i in range(5):
   yield (i*i*i)

for j in cubeseries():
 print j

How to echo HTML request parameters

<html>
<head>
  <title>HTML Request Parameters</title>
</head>
<body>
  <h2>Choose an Actor:</h2>
  <form method="get">
    <input type="checkbox" name="actor" value="Shahrukh Khan">Shahrukh Khan
    <input type="checkbox" name="actor" value="Amir Khan">Amir Khan
    <input type="checkbox" name="actor" value="Salman Khan">Salman Khan
    <input type="submit" value="Query">
  </form>

  <%
  String[] actors = request.getParameterValues("actor");
  if (actors != null) {
  %>
    <h3>You have selected actor(s):</h3>
    <ul>
  <%
      for (int cnt = 0; cnt < actors.length; cnt++) {
  %>  
        <li><%= actors[cnt] %></li>
  <%
      }
  %>
    </ul>
    <a href="<%= request.getRequestURI() %>">Go Home</a>
  <%
  }
  %>
</body>
</html>

A simple JSP script

<html>
<body>
<% if(1>2) {%>
<h2>You are hell pathetic </h2>
<%} else {%>
<h2>I think you are sensible </h2>
<%}%>
</body>
</html>

How to Shutdown from Terminal in Red Hat Linux 6.0

Suppose you are logged in as a normal user say:

user1@localhost ~]$

Now you need to switch to root user using switch user command
The command is

su -

Shell prompt you to enter rot user password like this

user1@localhost ~]$ su -
password:

Type your password and press enter.

Now you are switched to root user.

root@localhost ~]$ 

Type this command

 root@localhost ~]$  init 0

Thats all done.

Friday 4 April 2014

How to read a file using Java Applet

import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import javax.swing.JScrollPane;
import javax.swing.JApplet;
public class readFileApplet extends Applet {
    String fileToRead="OracleCon.java";
    StringBuffer strBuff;
    TextArea txtArea;
    Graphics g;
    public void init()
    {
        txtArea = new TextArea(100,100);
        txtArea.setEditable(true);
        JScrollPane sp=new JScrollPane(txtArea);
        add(txtArea,"center");
        String prHtml = this.getParameter("fileToRead");
        if(prHtml!=null) fileToRead = new String(prHtml);
        readFile();
        add(sp);
    }
    public void readFile()
    {
        String line;
        URL url=null;
        try
        {
            url = new URL(getCodeBase(),fileToRead);
        }
        catch(MalformedURLException e){}
        try
        {
            InputStream in = url.openStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(in));
            strBuff = new StringBuffer();
            while((line=bf.readLine())!=null)
            strBuff.append(line + "\n");
            txtArea.append("File Name : " + fileToRead + "\n");
            txtArea.append(strBuff.toString());
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Understandng Arrays in Java

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.text.SimpleDateFormat;
public class array1
{
public static void main(String[] args)
{
Integer array[]={6,32,9,1,-4,76,-23,5,8,2,-4,-11};
Arrays.sort(array);
printArray("Sorted Array : ",array);
int index=Arrays.binarySearch(array,-6);
System.out.print("\nFound 2 @ " + index);
}
public static void printArray(String message,Integer array[])
{
System.out.print("\n" + message + ": [Length : " + array.length + "]  ");
for(int i=0;i<array.length;i++)
System.out.print(array[i] + ",");
printMaxMin(array);
printTime();
}
public static void printMaxMin(Integer[] arr)
{
//System.out.print("\nMaximum in the array : " + (int)Collections.max(Arrays.asList(array)) +
//                 "\nMinimum in the array : " + (int)Collections.min(Arrays.asList(array)));
      int min = (int) Collections.min(Arrays.asList(arr));
      int max = (int) Collections.max(Arrays.asList(arr));
      System.out.print("\nMin number: " + min);
      System.out.print("\nMax number: " + max);
}
public static void printTime()
{
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.print("\nCurrent Time is : " + sdf.format(date));
}
}

How to create a Form using Java applet

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.Applet.*;
import java.lang.*;
public class loginForm extends Frame implements ActionListener
{
Label lblUname
;
Label lblPass;
Label lblblnk;
TextField usrTxt;
TextField pwdTxt;
Button btn;
public loginForm()
{
lblUname = new Label("user name");
lblPass  = new Label("password");
lblblnk  = new Label(" ");
usrTxt = new TextField();
pwdTxt = new TextField();
btn = new Button("button");
add(lblUname);
add(lblPass);
add(usrTxt);
add(pwdTxt);
add(btn);
add(lblblnk);
lblUname.setBounds(0,10,100,40);
lblPass.setBounds(0,50,100,90);
usrTxt.setBounds(110,10,210,40);
pwdTxt.setBounds(110,50,210,90);
btn.setBounds(150,110,210,130);
lblblnk.setBounds(0,130,200,150);
btn.addActionListener(this);
pwdTxt.setEchoChar('*');
addWindowListener(new mwa());
}
public void actionPerformed(ActionEvent e)
{
lblblnk.setText("Welcome " + usrTxt.getText());
}
public static void main(String[] args)
{
loginForm l = new loginForm();
l.setSize(new Dimension(600,600));
l.setTitle("Login");
l.setVisible(true);
}
}
class mwa extends WindowAdapter
{
public mwa() {}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

How to calculate factorial of a number using recursive methods in Java


import java.io.*;
class factorial
{
public static long getfactorial(int n)
{
if(n<=0)
return 1;
return n * getfactorial(n-1);
}
public static void main(String[] args) throws IOException
{
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter number : ");
int n=Integer.parseInt(rd.readLine());
System.out.print("\nFactorial of " + n + " = " + getfactorial(n));
}
}

How to print the nth number of a Fibonacci series by recursive method

//How to print the nth number of a Fibonacci series by recursive method

//                                                            fibo(5)         
//                               fibo(4)                      +                    f ibo(3)
//           fibo(3)             +         f ibo(2)      +        fibo(2)        +     fibo(1)
//fibo(2)   +   fibo(1)     +              1           +             1            +        1
//   1         +       1          +              1           +             1            +        1         =  5

import java.io.*;
class factorial
{
public static long getfactorial(int n)
{
if(n<=0)
return 1;
return n * getfactorial(n-1);
}
public static void main(String[] args) throws IOException
{
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter number : ");
int n=Integer.parseInt(rd.readLine());
System.out.print("\nFactorial of " + n + " = " + getfactorial(n));
}
}

How to connect to Oracle using JDBC thin client

// Hello this is a java program to connect to oracle database connection string and sql query  is //customize you have to set your own value.
//after you compile this code run in the command line with following sysntax
// you can ignore lpad and rpad function it is only given to print data in well tabed format
// java -cp "path\jdbcjarfilename" classfilename
//  i am giving the ojdbc5.jar link here : ojdbc5.jar

import java.sql.*;
import java.io.*;
class OracleCon
{

public static void main(String[] args)
{
ConnectToDB();
}
public static void ConnectToDB()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("\nOracle JDBC driver not found");
e.printStackTrace();
return;
}
System.out.print("\nOracle JDBC Driver Registered");
Connection connection=null;
Statement stmt=null;
try
{
connection = DriverManager.getConnection("jdbc:oracle:thin:@192.168.171.166:1521:orcl","payroll",
             "payroll");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select emp_code,emp_name,date_of_birth from employee_master");
File file = new File("/sub/aaa.csv");
if(!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.print("\n" + lpad("Emp Code",10) + "|" + lpad("Emp Name",50) + "|" + lpad("Date of Birth",20));
while(rs.next())
{
System.out.print("\n" + lpad(rs.getString("emp_code"),10) + "|" + lpad(rs.getString("emp_name"),50) + "|" + lpad(rs.getString("date_of_birth"),20));
bw.write("\n" + lpad(rs.getString("emp_code"),10) + "|" + lpad(rs.getString("emp_name"),50) + "|" + lpad(rs.getString("date_of_birth"),20));
}bw.close();
rs.close();
connection.close();
}
catch(SQLException e)
{
System.out.print("\nConnection Failed! Check output console");
e.printStackTrace();
return;
}
catch(IOException e)
{
e.printStackTrace();
return;
}
if(connection!=null)
System.out.print("\nSuccess");
else
{
System.out.print("\nFailed");
return;
}
}
public static String lpad(String s,int l)
{
String gap="";
for(int i=s.length();i<=l;i++)
gap+=" ";
return gap + s;
}

public static String rpad(String s,int l)
{
String gap="";
for(int i=s.length();i<=l;i++)
gap+=" ";
return s + gap;
}
}