Wednesday, March 30, 2011

Install Python from Source

localhost:~$ su −
Password: [enter your root password]
localhost:~# wget http://www.python.org/ftp/python/2.3/Python−2.3.tgz
Resolving www.python.org... done.
Connecting to www.python.org[194.109.137.226]:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 8,436,880 [application/x−tar]
...
localhost:~# tar xfz Python−2.3.tgz
localhost:~# cd Python−2.3
localhost:~/Python−2.3# ./configure
checking MACHDEP... linux2
checking EXTRAPLATDIR...
checking for −−without−gcc... no
...
localhost:~/Python−2.3# make
gcc −pthread −c −fno−strict−aliasing −DNDEBUG −g −O3 −Wall −Wstrict−prototypes
−I. −I./Include −DPy_BUILD_CORE −o Modules/python.o Modules/python.c
gcc −pthread −c −fno−strict−aliasing −DNDEBUG −g −O3 −Wall −Wstrict−prototypes
−I. −I./Include −DPy_BUILD_CORE −o Parser/acceler.o Parser/acceler.c
gcc −pthread −c −fno−strict−aliasing −DNDEBUG −g −O3 −Wall −Wstrict−prototypes
−I. −I./Include −DPy_BUILD_CORE −o Parser/grammar1.o Parser/grammar1.c
...
localhost:~/Python−2.3# make install
/usr/bin/install −c python /usr/local/bin/python2.3
...
localhost:~/Python−2.3# exit
logout
localhost:~$ which python
/usr/local/bin/python
localhost:~$ python
Python 2.3.1 (#2, Sep 24 2003, 11:39:14)
[GCC 3.3.2 20030908 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [press Ctrl+D to get back to the command prompt]
localhost:~$

Sunday, March 27, 2011

Design pattern with Swing Actions

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToolBar;

public class ActionSample extends JFrame {
 
 private Action sampleAction;
 private Action exitAction;
 
 public ActionSample(){
  super("Using Actions");
  
  sampleAction = new AbstractAction(){
   public void actionPerformed(ActionEvent event){
    JOptionPane.showMessageDialog(ActionSample.this, "The sampleAction was invoked!");
    
    exitAction.setEnabled(true);
   }
  };
  
  sampleAction.putValue(Action.NAME, "Sample Action");
  
  sampleAction.putValue(Action.SHORT_DESCRIPTION, "A Sample Action");
  
  sampleAction.putValue(Action.MNEMONIC_KEY, new Integer('s'));
  
  exitAction = new AbstractAction(){
   public void actionPerformed(ActionEvent event){
    JOptionPane.showMessageDialog(ActionSample.this, "The exitAction was invoked");
    
    System.exit(0);
   }
  };
 
  exitAction.putValue(Action.NAME, "Exit");
  
  exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit Application");
  
  exitAction.putValue(Action.MNEMONIC_KEY, new Integer('x'));
  
  exitAction.setEnabled(false);
  
  JMenu fileMenu = new JMenu("File");
  
  fileMenu.add(sampleAction);
  fileMenu.add(exitAction);
  fileMenu.setMnemonic('F');
  
  JMenuBar menuBar = new JMenuBar();
  menuBar.add(fileMenu);
  setJMenuBar(menuBar);
  
  JToolBar toolBar = new JToolBar();
  
  toolBar.add(sampleAction);
  toolBar.add(exitAction);
  
  JButton sampleButton = new JButton();
  sampleButton.setAction(sampleAction);
  
  JButton exitButton = new JButton(exitAction);
  
  JPanel buttonPanel = new JPanel();
  
  buttonPanel.add(sampleButton);
  buttonPanel.add(exitButton);
  
  Container container = getContentPane();
  container.add(toolBar, BorderLayout.NORTH);
  container.add(buttonPanel, BorderLayout.CENTER);  
 }
 
 public static void main(String args[]){
  ActionSample sample  = new ActionSample();
  sample.setDefaultCloseOperation(EXIT_ON_CLOSE);
  sample.pack();
  sample.setVisible(true);
 }

}

Tuesday, March 22, 2011

Control mouse using the Robot Class

For these examples you will need to make sure you import the java.awt.Robot & java.awt.event.InputEvent classes.

Move the mouse cursor position on screen:


import java.awt.Robot;
 
public class MouseClass {
 
 public static void main(String[] args) throws Exception {
 
            Robot robot = new Robot();
 
            // SET THE MOUSE X Y POSITION
            robot.mouseMove(300, 550);
 
 }
}
--------------------------------------------------

Click the left mouse button:


import java.awt.Robot;
import java.awt.event.InputEvent;
 
public class MouseClass {
 
 public static void main(String[] args) throws Exception {
 
            Robot robot = new Robot();
 
            // LEFT CLICK
            robot.mousePress(InputEvent.BUTTON1_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_MASK);
 
 }
}

--------------------------------------------------------------------------------

Click the right mouse button:

import java.awt.Robot;
import java.awt.event.InputEvent;
 
public class MouseClass {
 
 public static void main(String[] args) throws Exception {
 
            Robot robot = new Robot();
 
            // RIGHT CLICK
            robot.mousePress(InputEvent.BUTTON3_MASK);
            robot.mouseRelease(InputEvent.BUTTON3_MASK);
 
 }
}

--------------------------------------------------------------------

Click & scroll the mouse wheel:

import java.awt.Robot;
import java.awt.event.InputEvent;
 
public class MouseClass {
 
 public static void main(String[] args) throws Exception {
 
            Robot robot = new Robot();
 
            // MIDDLE WHEEL CLICK
            robot.mousePress(InputEvent.BUTTON3_DOWN_MASK);
            robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
 
            // SCROLL THE MOUSE WHEEL
            robot.mouseWheel(-100);
 
 }
}

Log in to MySQL in Terminal

>>> mysql -u root -h localhost -p

ztron@ztron-desktop ~ $ mysql -u root -h localhost -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 42
Server version: 5.1.49-1ubuntu8.1 (Ubuntu)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

Monday, March 21, 2011

Reading and Displaying Text Files

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

@SuppressWarnings("serial")
public class isuru extends Frame implements ActionListener{
 String directory;
 TextArea textarea;
 
 public isuru(){
  this(null, null);
 }
 
 public isuru(String filename){
  this(null, filename);
 }
 
 public isuru(String directory, String filename){
  super();
  
  addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    dispose();
   }
  });
  
  textarea = new TextArea("", 24, 80);
  textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
  textarea.setEditable(false);
  this.add("Center", textarea);
  
  Panel p = new Panel();
  p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
  this.add(p, "South");
  
  Font font = new Font("SansSerif", Font.BOLD, 14);
  Button openfile = new Button("Open File");
  Button close = new Button("Close");
  openfile.addActionListener(this);
  openfile.setActionCommand("open");
  openfile.setFont(font);
  
  close.addActionListener(this);
  close.setActionCommand("close");
  close.setFont(font);
  p.add(openfile);
  p.add(close);
  
  this.pack();
  
  if(directory == null){
   File f;
   if((filename != null) && (f = new File(filename)).isAbsolute()){
    directory = f.getParent();
    filename = f.getName();
   }else{
    directory = System.getProperty("user.dir");
   }
   
   this.directory = directory;
   setFile(directory, filename);
  }
 }
 
 public void setFile(String directory, String filename){
  if((filename == null) || filename.length() == 0)
   return;
  File f;
  FileReader in = null;
  try{
   f = new File(directory, filename);
   in = new FileReader(f);
   char[] buffer = new char[4096];
   int len;
   textarea.setText("");
   while((len = in.read(buffer)) != -1){
    String s = new String(buffer,0,len);
    textarea.append(s);
   }
   this.setTitle("FileViewer: "+filename);
   textarea.setCaretPosition(0);
  }catch(IOException e){
   textarea.setText(e.getClass().getName()+ ": " + e.getMessage( ));
   this.setTitle("FileViewer: "+filename+ ": I/O Exception");
  }finally{
   try{
    if(in != null)
     in.close();
   }catch(IOException e){
   
   }
  }
 }
 
 public void actionPerformed(ActionEvent e){
  String cmd = e.getActionCommand();
  if(cmd.equals("open")){
   FileDialog f = new FileDialog(this, "Open File");
   f.setDirectory(directory);
   
   f.show();
   
   directory = f.getDirectory();
   setFile(directory, f.getFile());
   f.dispose();
  }
  else if(cmd.equals("close"))
   this.dispose();
 }
 
 public static void main(String args[]){
  Frame f = new isuru((args.length == 1)?args[0]:null);
  f.addWindowListener(new WindowAdapter(){
    public void windowClosed(WindowEvent e){
     System.exit(0);
    }
  });
  
  f.show();
 }

}

Sunday, March 20, 2011

File Copy by Java

import java.io.*;

public class isuru{

 public static void main(String args[]){
  if(args.length != 2){
   System.err.println("Usage: java File Copy");
  }else{
   try{
   copy(args[0], args[1]);
   }catch(IOException e){
    System.err.println(e.getMessage());
   }
  }
 }
 
 public static void copy(String from_name, String to_name) throws IOException {
 
  File from_file = new File(from_name);
  File to_file = new File(to_name);
  
  if(!from_file.exists())
   abort("No such source file: "+from_name);
  if(!from_file.isFile())
   abort("Can't copy directory: "+ from_name);
  if(!from_file.canRead())
   abort("Source file is unreadable"+from_name);
  
  //to_name
  if(!to_file.exists()){
   if(!to_file.canWrite()){
    abort("destination file is unwriteable: "+to_name);
   System.out.println("Overwrite existing file "+ to_file.getName()+"?(Y/N): ");
   System.out.flush();
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   String response = in.readLine();
   if(!response.equals("Y") && !response.equals("y"))
    abort("existing file was not overwritten! ");
   
   }
  }else{
   String parent = to_file.getParent();
   if(parent == null)
    parent = System.getProperty("user.dir");
   File dir = new File(parent);
   if(!dir.exists())
    abort("destination directory doesn't exist: "+parent);
   if(dir.isFile())
    abort("destination is not a directory: "+parent);
   if(!dir.canWrite())
    abort("destination directory is unwritable "+parent);
  }
  
  FileInputStream from = null;
  FileOutputStream to = null;
  
  try{
   from = new FileInputStream(from_file);
   to = new FileOutputStream(to_file);
   byte[] buffer = new byte[4096];
   int bytes_read;
    while((bytes_read = from.read(buffer)) != -1)
    to.write(buffer,0, bytes_read);
  }finally{
   if(from != null) try {from.close();} catch(IOException e){;}
   if(to != null) try { to.close(); } catch(IOException e ){ ; }
  
  }
 
 }
 private static void abort(String msg) throws IOException {
  throw new IOException("FileCopy: "+msg);
 }

}

Delete File by Java

import java.io.*;

class isuru{
 public static void main(String args[]){
  if(args.length != 1){
   System.err.println("Usage: java Delete");
   System.exit(0);
  }try{
   delete(args[0]);
   System.out.println("Deleted successfully!");
  }catch(IllegalArgumentException e){
   System.err.println(e.getMessage());
  }
 }
 
 public static void delete(String fileName){
  File f = new File(fileName);
  if(!f.exists()) fail("Delete: no such file or Directory:"+fileName);
  if(!f.canWrite()) fail("Delete: write protected:"+fileName);
  
  if(f.isDirectory()){
   String[] files = f.list();
   if(files.length > 0){
    fail("Delete: directory not empty: "+fileName);
   }
  }
  
  boolean success = f.delete();
  
  if(!success) fail("Delete: deletion failed! ");
 }
 
 protected static void fail(String msg) throws IllegalArgumentException{
  throw new IllegalArgumentException(msg);
 }
}

Wednesday, March 2, 2011

Unix Basic Command

A

at : execute commands at a specified time/date.
awk: a scripting language, especially useful for manipulating text and automation.

B
bash : invokes the Bourne Again Shell (standard on most boxes).
batch: execute comands when load permits.
bc : interactive C-like calcultor (integers only).

C
cal : displays a calender, also lets you choose month/year using parameters.
calender : invoke a reminder service.
cancel : cancel request to calender.
cat : concatenate files (displays a file without scrolling ability. Simply dumps
it to the standard output. Can be useful when chaining multiple
applications to do complicated jobs, so one application can use another's
output as input).

cd : change the current working directory.
chgrp : change group ownership of a file.
chmod : change access patterns (permissions) to files.
chown : change user ownership of files.
clear : clear the screen.
cmp : compare two files.
cp : copy files.
cpio : archive and extract files.
cron : clock deamon (executes "batch" and "at" commands).
crontab : schedules commands at regular intervals.
crypt : encrypt , decrypt files using altered DES, standard to Unix passwords
(restricted distribution).
csh : invoke the C shell.
csplit : split file into several other files.
cu : call up another unix terminal.
cut : cut selected fields from each line of file.

D
date : displays the time and date (can also change it if you're root).
dd : convert and copy a file.
df : reports space (free, total etc') on all mounted file systems.
diff : copare two files.
diff3 : compare 3 or more files.
dircmp : compare two directories.
du : report disk usage.

E
echo : echo argument to standart output.
ed : line oriented editor.
egrep : extended version of grep (searches for extended regular expressions).
expr : evaluate boolean and arithmetic expression.

F
fgrep : same as grep, only it interprets patterns as a list of fixed strings.
false : return nonzero (false) exit status.
file : report type of file.
find : find matching files and run specified programs on them (optional).
finger : report user information (operates remotely only if a finger server is running
on the remote host).
ftp : (file transfer protocol) a client for FTP servers.

G
grep : search files for regular expression matches.

H
haltsys : gracefully shutdown sytem (can only be run by root. halt in Linux).
head : display first 10 lines of a file.

J
join : display the combination (lines with command field) of two fields.

K
kill : send a signal to terminate a process.
ksh : invoke the korn shell.

L
line : read a specific line out of a file (shell script usage).
ln : create a link to a file/directory.
logname : gets your login name.
lpr : sends a request to printer.
lprint : prints on local printer.
lpstat : reports printer status.
lpq : same as above.
ls : lists the contents of directory.

M
mail : send and recieve mail.
man : displays manual pages.
mesg : grant or deny permissions to recieve messages from other users using the
write command.
mkdir : create a new directory .
mknod : build a special file.
more : display file one page at a time.
mount : mount a storage device.
mv : move or rename a file.

N
news : display news item from NNTP servers.
nice : change priorities of processes.
nohup : run a command after logout (ignores hangup signals).
nroff : format files for printing.
nslookup : retrieve information from DNS servers.

O
od : displays a file in 8-based octals.

P
passwd : create or change login password.
paste : merge lines of files.
pr : format and print file.
ps : reports status of active processes.
pstat : report system status.
pwcheck : check /etc/passwd (default) file.
pwd : display current working directory.

R
rm : remove (erase) files or directories (unrecoverable).
rmdir : remove an empty directory.
rsh : invoke Restricted Bourne Shell.

S
sed : the stream editor.
set : assign value to variable.
setenv : assign value to enviroment variable.
sh : invoke Bourne shell.
sleep : suspend execution of a command for a given period.
sort : sort and merge files.
spell : find spelling errors.
split : split file to smaller files.
stty : set options for a terminal.
su : spawns a subshell with a different username, requires other user's
password,unless you're root.
sum : compute checksums and number of blocks for files.

T
tabs : set tabs on a terminal.
tail : display last 10 lines of file.
tar : a simple compression tool that merges multiple files into a single one,
originally made to make backing up materials on backup tapes easier.
tee : create a tee in a pipe.
telnet : access remote systems using the telnet protocol.
test : test various expressions and files.
time : display elapsed time (execution, process, and system times) for a
command.
touch : change time/date stamps of files.
tr : substitutes sets of charecters.
translate : translates files to different format.
troff : format files to phototypester.
true : return zero (true) exit status.
tset : set terminal mode.
tty : report a name of a terminal.

U
umask : set file-creation mode (permissions) mask.
umount : unmount a device.
uname : display the name of the current system.
uniq : report any duplicate line in a file.
units : convert numbers from one unit to another.
unzip : extract files from zip archieve.
uptime : report system activety.
uucp : copy files between two unix systems (oldie but still beautiful).
uulog : report uucp status.
uuname : list uucp sites known to this site.
uudecode : decode to binary after "uuencode" transmission.
uencode : encode binary file for email transmission.
uustat : report status of uucp or cancel a job.
uupick : receive public files sent bu uuto.
uuto : send files to another public Unix system.
uux : execute command to remote Unix system.

V
vi : a screen oriented (visual) editor (cool ,but Vim is better).

W
wall : sends message to all users (root only).
wait : await completion of background process.
wc : count lines, words, bytes etc' in one or more files.
who : report active users.
whois : search for user information.
write : send a message for another user (see mesg).
whoami : which user you are logged in as at the moment. If you, for example,
switch to a different user, logname will show the original username you
logged in as, and whoami will show the current user.


Z
zip : archieve file or files in zip format.