Sep 30, 2010

Exceptions and a simple program

Exception handling in clojure

Clojure supports java based exceptions. There are two types of exceptions in clojure. One is clojure exceptions and the other is user defined exceptions. If you type as;
user=>(/ 1 0)
This is devide 1 by 0. So this will give an exception.
So, this is the way to catch the exceptions.
user=>(try (/ 1 0 ) (catch Exception e (prn "Cach the exception" ))(finally (prn "In finally...")))

Now it will handle the exception. But if you use a wrong type of exception it will not catch that and in the end of the try statment it will give the error.

Writing a simple clojure program.
Now we will try to write a clojure program to add remove and change things.

(alias 'set 'clojure.set)
This wiil make an alias to clojure.set. Now we can use "set" word when ever we need to write clojure.set/smoething.

(defstruct employee :name :id :role)
This will create a structore named employee.
(def employee-records (ref #{}))
The "ref" is to allow mutation of a storage with transactions.

(defn- update-role [n r recs]
(let [rec (set/select #(= (:name %) n) recs)
others (set/select #(not (= (:name %) n)) recs)]
(set/union (map #(set [(assoc % :role r)]) rec) others)))
In this set of codes, "defn-" defineds a private function. As previously sed here we use set/select behalf of clojure.set/select.

(defn- delete-by-name [n recs]
(set/select #(not (= (:name %) n)) recs))
Both of these functions update and delete will do the operation and create a
new set of data, becouse these sequences are immutable.
Now you can see some public functions which will not cantaining a "-" sign when definding it.

(defn update-employee-role [n r]
"update the role for employee named n to the new role r"
(dosync
(ref-set employee-records (update-role n r @employee-records))))

(defn delete-employee-by-name [n]
"delete employee with name n"
(dosync
(ref-set employee-records
(delete-by-name n @employee-records))))

(defn add-employee [e]
"add new employee e to employee-records"
(dosync (commute employee-records conj e)))
Now the code is completed. Save this as test.clj and in the clojure prompt you
can import that coding by,

(load-file "test.clj")
Then you can do add delete and change employee details. Here is some
coding to add some data initially. Then after that you can view what you enered.(add-employee (struct employee "Jack" 0 :Engineer))
(add-employee (struct employee "Jill" 1 :Finance))
(add-employee (struct-map employee :name "Hill" :id 2 :role :Stand))
@employee-records

Clojure program Exception handling in clojure

Sep 29, 2010

More about monad haskell

Monad Whitespace

We can recognise one or more spaces by importing monads librerys. We can try by
this coding.
readExpr input = case parse (spaces >> symbol) "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"

Return values
We can convert return valuer of some inputs. To do this we need to defined a data type which can store any data type. So for do that;

data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool

This defineds a set of data types that the LispVal can hold.
Atom is a letter or a symbol which can be a charactor number or a symbol.

Generic monad
We can write our own monad thing by this way.

Sep 28, 2010

More on monad haskell

Monad transformers
Monads transformers are also in a formata of monads. So we must make MaybeT m an instance of the Monad class.
instance Monad m => Monad (MaybeT m) where
return = MaybeT . return . Just

This will get the monads return and send it ot the monadts constructore. This thing can be wriiten as,
x >>=f= MaybeT $ do maybe_value <- runMaybeT x case maybe_value of Nothing -> return Nothing
Just value -> runMaybeT $ f value

List transformer
newtype ListT m a = ListT { runListT :: m [a] }

We can transform list also and to do that we need to crerate a datatype with a constructoore which takes an argument.

LiftM
This is a library which can transfer the non-monadic functions to monadic ones. The function is like this.
liftM :: Monad m => (a1 -> r) -> m a1 -> m r

Converting non-monadic:- myFn $ NonMonadic
Converting monadic :- myFn `liftM` monadic

Pasing monad
This is more powerful parser with monads like Maybe, list and sate. This will use parcer librery functions also. So first of all we must import relevent librery functions to our program.
import System
import Text.ParserCombinators.Parsec hiding (spaces)
Now we are going to use a parser librery function call oneOf
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~"

This will keep track of each charactor. Then we must make some arrangements to handle the errors too.
readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"

Now we can write the program.
main :: IO ()
main = do args <- getArgs
putStrLn (readExpr (args !! 0))

Now you can run this by doing
ghc -package parsec -o filename.hs

Clojure Basics

Run clojure.jar by,
java -jar clojure.jar
and it will prompt,
user=>
Clojure got three main numerical types. Integr, Float and Ratio.
To do 1 + 2 it is; (+ 1 2)
If you need to defind a function you can defid as,
The function you need to defind is a = 2 + 3
So you can write it as,
user=> (def a(+ 2 3))
Then it will give an output as
#'user/a
and prompt user=>
If you type "a" in that you will get the output of 2+3 as 5.

Number formats
user=> 10 decimal 10
010 octal 8
0xff hex 255
1.0e-2 double 0.01
1.0e2 double 100.0

And also clojure supports a radix based entry format, in a form of (radix)r(number)
(note : 1(Integer/toString 10)
"10"
user =>(Integer/toBinaryString 10)
"1010"

String to Integer
user=>(Integer/parseInt "B" 16)
11
user=>(Integer/parseInt "10" 16) ; 16r10
16
user=>(Integer/parseInt "101" 8) ; 8r101
65
User =>(Integer/parseInt "10101" 2)

Data Structures
Creating a stucture;
(defstruct employee :name :id)
Using the structures
(struct employee "Mr. X" 10)
We can make functions from these things and get values from them like;
(def e1(struct employee "Nimal" 324))
And if you type e1 it will give an output like
{:name "Nimal", :id 324}
Also you can get only a value you need by typing like;
(e1 :name)
This will print the name of e1.

We can use accessor function to get easy access of feilds. It is like this.
(def emp-name(accessor employee :name))
Now if you want to get the employee name of e1 you cann type as;
(emp-name e1)

Add or remove new fields to structures
We can only remove fields which are added by assoc, can't delete the fields which are defined by defstruct.
Adding
(def e1-new (assoc e1 :function "engineer"))
e1-new
It will give the output as;
{:name "Nimal", :id 324, :function "engineer"}
Removing
(def e1-rm (dissoc e1-new :function))
e1-rm

Sep 27, 2010

Starting clojure with Labrepl

Labrepl is an environment for exploring the Clojure language. It is a web base application.

Before downloading labrepl you must check if you got github, java and leiningen.
Then make a directory and download the labrepl repository into that directory. So for do that;


git clone git://github.com/relevance/labrepl.git

Change the directory into that and type;

lein deps to install all the dependent libraries. This will take some time.

Then run;
script/repl
This will launch the labrel.

Now you can goth http://localhost:8080 for the labs.

And press Ctrl+D to exit.

Haskell class declarations

Haskell class is not like classes in Java or c++.
Haskell got many numeric types, which are Int, Integer and Float. You can compare two numbers of the same type for equality but in not different types. Also you can compare two values of type Bool for equality, but you cannot add them together. A class is a template for types, and it gives the operations that the types must do.

class Eq a where
(==), (/=) :: a -> a -> Bool
It defines the == and /= functions.

Simple type decleration

plus :: Int -> Int -> Int
plus x y = x + y

This plus function will get 2 Int numbers, do the calculation and then it will return an Int too.

Monad
This is a very useful concept in haskell.
It,
Do an action from the type of which returns by the function.
Do an action which simply produce a value.
Do a chain "actions" together, while allowing the result of an action to be used for the second action

Maybe

farther :: Person -> maybe Person

This function will return data with type Person or if there is no value it will return nothing.

Note;
let x = foo in bar can writtern as (\x -> bar) foo
x<-foo; bar can writtern as foo>>=(\x -> bar)

Do notation
do putStr "Hello"
putStr " "
putStr "world!"
putStr "\n"

This will print in a sequence.

Then and do notations.

do action
other_action
yet_another_action

This is written by only using do naotation. but this can be wriiten by using bothe do and then notations like this;

action >>
do other_action
yet_another_action

msum

msum :: MonadPlus m => [m a] -> m a
msum = foldr mplus mzero

Sep 24, 2010

Sorting a list in haskell

We can write a hascell coding for sort a list in assending or desending order.

quickSort []=[]
quickSort [x]=[x]
quickSort (x : xs) = (quickSort less) ++ (x : equal) ++ (quickSort more)
where less = filter (< x) xs equal = filter (== x) xs more = filter (> x) xs


write this in a hakell file and load it into the intepreter. Now type;
quickSort ["i", "have", "a", "thing", "for", "linux"]
It will give the output like this.
["a","for","have","i","linux","thing"]

But if you type as;
quickSort ["I", "have", "a", "thing", "for", "Linux"]
you will get the output as;
["I","Linux","a","for","have","thing"]
this. Sorting is done by looking at the ASCII values and capital letters got less value than the others. So to avoid that thing we must ignore the case of the characters.

Modules
Module is a group of related functions in a singe package. We can use functions for our codings without implementing them. The only thing we must do is import the correct module and call the correct function. There are many ways of importing modules.

import Data -- import everything from Data module
import Data.List -- import everything exported from Data.List
import Data.Char (toLower, toUpper) -- import only the functions toLower and toUpper from Data.Char

Indentation
Haskell is depend on indentation. So you must think about the indentation when you are writing a haskell coding. Basic things are like this.
let x = a
y = b

do foo
bar

where x = a
y = b

case x of
p -> foo
p' -> baz

myFunction firstArgument secondArgument =
do foo
bar

or
myFunction firstArg secondArg = do foo
bar

Foo and bar must inline
If else statment --

if foo
then do first thing
second thing
third thing
else do something else

Setting the clojure-lein mode in emacs

First you should get the emacs configuration file. It is in your home directory as .emacs or .emacs.d/init.el (you should use ls -la to view the hidden files)

In that file you must insert this.

(let ((buffer (url-retrieve-synchronously
"http://tromey.com/elpa/package-install.el")))
(save-excursion
(set-buffer buffer)
(goto-char (point-min))
(re-search-forward "^$" nil 'move)
(eval-region (point) (point-max))
(kill-buffer (current-buffer))))

This will download come congigeration packages into the .emacs or .emacs.d directory and update the init.el file. Then you should remove the above code part (only that thing) from the init.el file.
Then open an emacs window and type

M-x package-list-packages
Then type r to update the list. And then select package (clojer-mode) from i and install it by x.

Then type;
M-x describe-variable and in the prompt type;
inferior-lisp-program

In that you should customize the variable to;
lein repl
then save it.
Now open a .clj file from emacs.

MySQL access form a Haskell script

This script will connect to a mysql database via haskell script.
Firs of all you must need to download some modules which used to communicate with the database. For that you may you can use
hackage.haskell.org/package/
This link.

You should download and install,
HDBC module and
HDBC-mysql module.

If you encount some problen while you are installing those modules, you should check the dependenci packages as well. You should install those thing also inorder to run those packages without errors. Dependence details are in the package webpage.

Then you can create a test database to test the script. So for that do these thing in MySQL.

>CREATE DATABASE animal
>CREATE TABLE `animal` (`name` char(40) DEFAULT NULL,`category` char(40) DEFAULT NULL)
>INSERT INTO `animal` VALUES ('snake','reptile'), ('crockadile','amphibian')

Now you should create the database.

import Database.HDBC
import Database.HDBC.MySQL

run_quary = do
conn <- connectMySQL defaultMySQLConnectInfo { mysqlHost = "localhost", mysqlDatabase = "animal", mysqlUser = "username",mysqlPassword = "", mysqlUnixSocket="/var/lib/mysql/mysql.sock"}
quickQuery' conn "INSERT INTO animal VALUES ('tuna','fish'),('racoon','mammal')" []


In this script you must change the user name, password and the mysqlUnixSocket path. The user name and its passwd should be able to access the animal database. You can get the mysql.sock path from the file /etc/my.cnf

Clojure

Clojure is a dynamic programing language which use the java virtual machine. It directly compile the source code into java bytecode.
Doing projects with leingingen
Leiningen is a simple building tool for clojure. It will make "Build" files for your clojure project.

You can install leniingin by this script. Alsoit will install clojure for you.

http://github.com/technomancy/leiningen/raw/stable/bin/lein

First download the lein file from this. Then,
chmod +x lein
./lein self-install

It will install all the nessesary things.

Now we can create the project. I will create a simple project to display "Hello World". So for do that;

mkdir helloworld
mkdir helloworld/src
touch helloworld/src/helloworld.clj

Then you should edit the helloworld.clj file like this.

(ns helloworld
(:gen-class))

(defn -main [& args]
(println "Hello world"))

Then you must create a file call project.clj in the helloworld directory. That file should contain,

(defproject helloworld "0.1"
:dependencies [[org.clojure/clojure
"1.1.0-master-SNAPSHOT"]
[org.clojure/clojure-contrib
"1.0-SNAPSHOT"]]
:main helloworld)

Now you had complete the source files and project details files. It is time to compile the project.
To compile the project you must type,

$ lein compile
This will compile the project and create lib file which contains all jar files of the project. But we can create a single .jar file for the project. To make it,

$ lein uberjar

This will create two jar files, you can distribute your project with the standalone.jar file.
to run the jar file you must type,

java -jar .jar

Sep 23, 2010

selenium with python

Selenium is a good testing tool which can be controled by many programing languages. So here is some sample coding in python.

from selenium import selenium
import unittest

class TestGoogle(unittest.TestCase):
def setUp(self):
self.selenium = selenium("localhost", \
4444, "*firefox", "http://www.google.com/webhp")
self.selenium.start()

def test_google(self):
sel = self.selenium
sel.open("http://www.google.com/webhp")
sel.type("q", "hello world")
sel.click("btnG")
sel.wait_for_page_to_load(5000)
self.assertEqual("hello world - Google Search", sel.get_title())

def tearDown(self):
self.selenium.stop()

if __name__ == "__main__":
unittest.main()

This will test the google.com website.

Sep 21, 2010

Installing Selenium

Selenium is a good web application testing tool which is a free and open source software. It can run in many browsers, inmany operating systems and can controled by many programing languages and testing frameworks.
You can get more datails as well as the software from visiting the official website http://seleniumhq.org

First of all download the selenium ide from the website.

Then extrat the zip file.

Now you can see some jar file as well as some library files.

So first run the selenium server. For that you may need java. If you do not have java, you must install JDK first.
java -jar selenium-server.jar

Wait for about 1 min. It will give the configurations of your system.

Then you should deside which language you are using to control the selenium. I will use python but you can do it in come other language.(see the website)

Now you should change the directory to python library file. There you can see selenium lib files for python.
Then try to run a default test. To do that;

python test_default_server.py

So now you can write your script in this folder and run it.

Sep 20, 2010

Database connect via python

fgTo connect to a database we must first install a special module to communicate with the database.If the database is MYSQL you must install MySQLdb module.

To do that you must type;

yum install MySQL-python

After the instalation you shoyld be able to; >>>import MySQLdb

If this thing won't give any error you can continue.

First we must import modules which we need to runour script. So;

import sys
import MySQLdb

Then we must connect to the databace and to do that;

try:
conn=MySQLdb.connect(host="",user="",passwd="",db="")

except MySQLdb.Error,e:
print "Can not connect to the database"
sys.exit(1)

Now we are connected to the database. Now we need to send querys to our database.

Try:
cursor=conn.cursor()
cursor.execute(""" your query """)
cursor.close()
except MySQLdb.Error,e:
priint "Some error...!!!"
sys.exit(1)

You had done all the things for now. So you shoul close the connection which you open.

conn.commit()
conn.close()
sys.exit()

Haskell - filter

Filter
If a list meet a certain condition it will
create another list according to that. Try this,
retainEven :: [Int]->[Int]
retainEven []=[]
retainEven (n:ns)=
if (mod n 2 == 0)
then n:(retainEven ns)
else retainEven ns

If you run this program like

retainEven [12,13,14,15,16]
You will get the output as;
[12,14,16]

If then else statment with strings

msg :: Int -> String
msg n =
if n< 10 then "Less than 10" else "Equal or greater than 10" Let and where addStr :: Float -> String -> Float
addStr xstr = x + read str
sumStr :: [String] -> Float
SumStr = foldl addstr 0.0

But You can write this by using let keyword easilly.
sumStr=
let addStr x str = x + read str
in foldl addStr 0.0

or else you can write it by using where keyword like this.
aumStr = foldl addStr 0.0
where addStr x str = x + read str

Sep 17, 2010

Haskell folds

Folds - a flod apply a function to a list, accumilate items and give a single output.
There are 4 main fold functions;
foldr - this will fold up a list from the last element to the first element and apply a given function for each element.

fac n = foldr (*) 2 [1..n]

if you run this code and type as;
fac 3
it will give the output as
12
What will happen in this is,
3*2 + 2*2 + 1*2 = 12

foldl - this will go from the first element to the last element.
foldl1 and foldr1 -
these things will work as the way the foldl and foldr work. But this will give an error message when it is an empty array.

scan
This do the both things done by map and fold. It will accumilate values like fold but the output will be given as a list as in map for each intermediate value.

scanl (+) 0 [1,2,3]
this will give the output as
[0,1,3,6]

Data types

data SpecialDay = Birthday Int Int Int
| Wedding String Int Int Int
SpecialDay is a data which can be ether a birthday or a wedding. So,

mySpeDay :: SpecialDay
mySpeDay = Birthday 1988 09 16

Installing PostgreSQL database.

PostgreSQL is a very powerfull open source database. You can download the binary package or the source code by visitiing the website.
http://www.postgresql.org

I will describe how to install this by using the source code.

First of all you must download the source code from the website. It may like;
postgresql-.tar.bz2
Decompress the tar file.
Then change the directory into the decompressed diredtory.
Now you can see source files of the software.

Now type;
./configure
Then after that;
gmake
Then you should become a super user to comtinue the instalation.
For that type;
su
then if it ask for the password. Give the password and type,
gmake install

This will copy all files which needed to the software. But the instalation is not over. This database need an user called postgres. So to add this user to your system you must type;
useradd postgres
Then do these instructions
mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data
su - postgres
The last instruction will change the user root to postgres.

Also you should type some instructions to make the configuration files. For that;
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data

/usr/local/pgsql/bin/postgres -D /user/local/pgsql/data >logfile 2>&1 &

So now you had compleated the instalation part.
Then you must create a database. For that,

/usr/local/pgsql/bin/createdb

To use that database;
/usr/local/pgsql/bin/pqsl

Sep 16, 2010

Installing a proxy server

Proxy is used to control network trafic and access controling. It will increase the network speed by caching the websites which freequently access by the users. It can also restrict ip addresses as well as protocls.

squid-cache is a proxy server which we can freely download and use.

You can download this by visiting the website http://squid-cache.org .

Download a stable vertion of squid.
There may by some distribution which are still on testing.

If you download a tar file decompress it.
Then change the directory to the squid director.

Now you can read the INSTALL file. It will say to run configuratoion file.
like
./configure --prefix=/usr/local/

This instalation will be placed in /user/local/ directory.
then type;
make all
Now you must switch to super user mode.
For that;
su -
After that;
make install

Now the instalation will run.
After the instalation you must customised the squid.conf file. It will be located in;
/usr/local/squid/etc/squid.conf

In that folder you may see some examples and those things will help you to do your task.

Then run the squid by typping
/usr/local/squid/sbin/squid

In that time if some permition error occure you may goto the directory,
/usr/llocal/squuid/
Then add a user and a group call squid by typing

useradd squid
groupadd squid

then type
chown squid -R var
chgrp qsuid -R var

And also change line of the squid.conf which like
#cache_effective_user nobody to
cache_effective_user squid

Then try to restart the squid.

More about list

Dot Dot notation
You can get a sequence of integer numbers like;
[1..10] it will give the result as [1,2,3,4,5,6,7,8,9,10]
And also if you type it as
[1,3..10] it will be like
[1,3,5,7,9]
And also on the other way around too.
[5..0]
[5,4,3,2,1,0]

Never ending list
This is like a never ending loop;

loop n=n: loop(n+1)
runLoop = loop 1

If the user type;
runLoop
The haskell will give a never ending loop.

Head and tali
If you type;
let list = [1,2,3,4,5,6]
head list
it will give the output as
1
tail list
it will give the output as
[2,3,4,5,6]

This will devide a list to two parts like (x:sx)

Sep 15, 2010

More about Haskell

Functions with if-then-else
myfunction f=
if x<0 then -1 else if x=0 0 else 1 Case statment In haskell we can write case statment also. casefunction c= case c of 0 -> 0
10 -> 1
100 -> 2
_ -> -1

We can write this as;
casefunction c =
case c of {0->0;10->1;100->2;_->-1}

This also gives the same answer.
But the order of these statments are very important. Because if you insert the default statement (_-> ) in the beggining you will get that as the result for every thing.

Outputs

hello = do
putStrLn "Hello World"

Load this one and type hello you will see;
Hello world

Inputs

input = do
putStrLn "What is your name ?"
name <- getLine putStrLn (" Welcome "++ name ++" ...!!! ") This will give user to input some thing. Then it will print it. You can use if else statments with inputs and outputs as; num x = if x==10 then do putStrLn "Num is equal to 10" else if x>10 then
do putStrLn "Num is greater than 10"
else
do putStrLn "Num is less than 10"

IF you load this thing and type as;
num 12
It will give the out put as
Num is greater than 10

Read Inputs

main =
do putStrLn "What is your name"
name <- getLine
if (read name) =="guest" then
do putStrLn ("Welcome "++ name ++" ..!! ")
else
do putStrLn "Opss ...!!!"

In this it will ask to user to input some thing.
Then it will read the input and chech the condition.

Sep 14, 2010

Haskell if else statement

You can write a if else statment like this.

function_name x =
if x<0 -1 else 1 if you write this as; function_name 5 it will give the output as; 0 And also you can write if then else statment also. function_name y = if y<0 -1 else if y>0
1
else
0

Haskell if else statement

You can write a if else statment like this.

function_name x =
if x<0 -1 else 1 if you write this as; function_name 5 it will give the output as; 0 And also you can write if then else statment also. function_name y = if y<0 -1 else if y>0
1
else
0

Sep 8, 2010

Haskell programming language

Haskell is an advance purely functional language. This language is not like java or c.

Install haskell compiler in fedora
$yum install ghc

After the installation you can type
$ghci
to run haskell in interactive prompt.

Writing your own functions
You can write Haskell source code and load it into the interpreter. To do that you should;
1. Write a Haskell code in the working directiry including 'import Data.Maybe'at the top of your code if that code need modules.
2. Sav the code with the extention of .hs.
3. Run ghci command and at the prompt type ":l .sh " (l= L in lowercase)

Writing a basic function
In c ---->
int foo(int bar){
return bar*10-4
}
In Haskell -------->
foo :: Int->Int
foo bar = bar * 10 +4

This means that foo is a integer and it returns a integer value.

Lists
let list=[2,3,4,5,7]
This is a list defined in Haskell. You can add values to the front of the list by doing
23:14:list
This will add 23 and 14 to the list and its output will like this.
[23,14,2,3,4,5,7]

Note:- If you need to get the file type of a variable and function you can type ':t'like this;
:t list
list - zipping and unzipping
This will take two lists zips them and returns a tupples.
zip [1,2,3]["aaa","bbb","ccc"]
the output will be like this,
[(1,"aaa"),(2,"bbb"),(3,"ccc")]

List - tali
This will alter the first item in the list. If you type as;
let list2=[1,2,3]
tail list2
This will give the output as;
[2,3]
In Haskell it is not updating the values, it only computes and give the output.

List - !!
Try this:
list2 !! 0
list2 !! 1
This will give the output as
1
2
!! is the sign of index operator in Haskell.

Sep 7, 2010

Python librarys

OS library - This will provide many number of functons which will interact with the operating system.
>>>import os # import the os library.
>>>dir(os) # can get a list of all module
# functions in the os module
>>>help(os) # will give the man page of os # module

Some important things from os module.

os.chdir('path') - change the current directory
os.chmod('path', 0777) - change the mode
os.chown('path',user_id,group_id) - change owner
fd=os.open('path', flag, 0755) open or create file
this will return a file descripter.
os.close(fd) - close the opend file according to the file descripter.
os.execl('file', *args) - excecute a file
os.fork() - make a chiled process
os.fstat(fd) - get stat of the file descripter
os.mkdir('path', 0644) - create a directiory
os.pipe(read,write) - pipe
os.read(fd,buffersize)
os.remove('path') - remove file
os.rename(old , new) - rename files

shutil module - THis will do the file management tasks.

import shutil
shutil.copyfile('source','destination')
shutil.move('source','destination') - recursivly move file or directory to another location
shutil.copytree(src,dst,symlinks=False) - recursivly copy a directory
shutil.rmtree(path, ignore_errors=False,onerror=None) -
shutil.recursivly remove files in a direstory

glob - provide wildcard search
import glob
glob.glob(*.py)

sys.argv - give the command line arguments
sys.exit - directly exit from a script

re module - this provide reguler expresion for python
math module - this provide mathematical functioons defined by the C standards.
random module - this provide randome selection

Sep 6, 2010

Python classes

This is a basic python class.

class MyClass:
i=12345
def f(self)
return 'Hello world'

Now you can use this as like this.
MyClass.i &
MyClass.f()
These are now valid atributes and functions.

As well as this you can create an instance and ues the class llike this

x=MyClass
x.i &
x.f()
Are also now a valid atribute and a method.

Writing an __init__() to a class
MyClass:
__init__(self,read,imag)
self.r=real
self.i=imag

x=MyClass(25,90)
print x.r x.i

There are no private classes in python

Sep 2, 2010

Python error and exceptions

while True:
try:
x=int(raw_input(Please enter a number))
break
except ValueError
print Please enter an integer value

This will handle the error if the user inputs an non-integer value.
In a program first the try clause runs. The exception clause runs only if try clause mane an exception.
If an exception occurs two things can be happend. first thing the exception will mach the exception clause and will excecute the code belongs to that thing. The other thing is an exception is not matching our names in the exception clause.

Try except and else
"else" part is a optional.But;

for arg in sys.argv[1:]:
try:
f=open(arg,'r')
except IOError:
print 'Can not open the file',arg
else:
print agr,'has'len(f.lreadlines()), 'lines'
f.close()

In a case like this, it is very useful. If the try clause excecute normaly it will go to the else part and excecute that code. This will not create any exceptions

Finally clause
If an exception occures or not, this clause will excecute.
try:
code
except:
code
finally:
code

In python it supports to create your own exceptions also.

Python classes

This is the way to write a simple class;

class MyClass:
i=234
def f(self):
return 'Hello World'
Now MyClass.i and MyClass.f are valid attributes.

Create an instance of an class.
x=MyClass()
And now we can use it as;
x.f
x.i

Git - get some ones project and edit it.

We can download a git project edit that thing. To do that we must;
$git clone remort_URL Our_destinatioon_folder
Eg:
bob$git clone git://git.videolan.org/vlc.git ~/vlc_clone

This will save a clone of vlc in the directory called vlc_clone.

Now you can edit that clone and commit.
If some other person is also involving on editing this clone he/she can get the Bob's edited git by using;

alise$git pull /home/bob/vlc_clone master

This will merges the changes of Bob's Master branch with Alise's current branch.

alise$git fetch /home/bob/vlc_clone master
alise$git log -p HEAD..FETCH_HEAD
This is more safer than just pulling if alise has not committed her editings.
By typing;
alise$gitk HEAD..FETCH_HEAD
Alise can see what are the changes Bob had done for the original clone.

alise$git remort add bob /home/bob/vlc_clone
By this Alice can add bob's clone without merging with her own branch.

alise$git fetch bob
In this it will simply create an extra branch without merging them with any of Alise's branchers.
In that case we must use:
alise$git log -p master..bob/master
in order to see the changers which Bob had make. Then if Alise need to merg them she can use;
$git pull . remortes/bob/master

Sep 1, 2010

Sed & awk

sed
We can use sed to search for some string patterns. By using sed we can easily modify a string.

Search and replace
The basic command is like this:
sed 's/day/night/' output_fie
This code will search for the keyword 'day'in the input_file and replace it by night then save the changed file in output_file.

sed 's/\(day\).*/\1' output_file
This will search for the day keyword in the input file and it will delete other characters behind the keyword, then it save the data in output_file.

AWK
We can use awk for report writing and filtering. Mainly it is a good table creator.

A bacsic structure of a awk command
BEGIN { print "START" }
{ print }
END { print "STOP" }

Try this out;
#!/bin/csh -f
awk '
BEGIN {print "FILE\tOWNER" } \
{ print $8 "\t" $3 }\
END { print "--DONE--"}\ '

This will give the output as
FILE OWNER

Note :
In awk "$2" is not a variable. It always reffer to a column number.
There are three types of awk.awk, nawk and gawk.

If you want to use a variable use it as,
variable=something
and in the code;
$'$variable'

Python modules

We can create a module file and can use it in some other files. TO do that we must create the module file in the same directory and in our coding we must import it. If the module file is "module_file.py".
>>>import module_file
Then we can get the variables and methods by;
>>>module_file.variable #or
>>>module_file.method

We can view the thing in a module by doing
>>>import module
>>>def(module)
This will give all related details about the module.

Inputs and outputs
We can pass parameters when we are executing the python script.
$python script.py argument1 argument2

in the script we can use these arguments by using
if __name__="__main__":
import sys
function(sys.arg[1], sys.arg[2])

Open file
we can use this to open a externel file.
f=open('file_name','mode')
mode can be,
w - write
r - read
r+ - read and write
a - append

f.read(size) - will give the size
f.read - will read the file
f.readline - will read a line
f.write(string) - will write string to file
f.close() - will close the file

Format an output
for x in range(1,11)
print repr(x).rjust(2), repr(x*x).rjust(3),
repr(x*x*x).rjust(4)

this will give the output like this
1 1 1
2 4 8
3 9 27
4 16 64 ....