Aug 31, 2010

More Python functions

del()
This can be used to remove lists and rev=move slices from a list.
del a[0]
del a[2:4]
del a
Tuples
t=123,567,'hello'
print t
(123, 576, 'hello')
nested tuples
u = t,(45,67)
print u
((123,567,'hello'),(45,67))
sets
This will do the arithmetic operations like union, intersection, etc.
basket=['apple','orrange', 'banana', apple' , 'orrange']
fruit=set(basket)
print fruit
set('apple','orrange','banana')
print orrange in fruit
TRUE
set_a=('abcdefg')
set_b=('efghijk')
set_a - set_b - this give the lettres which are only in "set_a"
set_a | set_b - gives the union
set_a & set_b - gives the intersection
set_a ^ set_b - letters in set_a or set_b but not both

Python functions

i = 5

def f(arg=i):
print arg

i = 8
f()

This will print 5. In this it will only assign a defaule value for one time.
def car(wheels,modle="toyota"):
print "No of wheels",wheels
print "Modle name : ",modle

car(4,modle="dimo")


More list methods
a=[2,333,333,45.4,] We will use this list for the following samples.
print a.count(333),a.count(2),a.count(99)
2 1 0
-
a.append(x)
this will add x to the end of "a" list.
-
a.extend(list)
add another list to list 'a'.
-
a.insert(index,value)
this will add a value to a given index.
-
a.remove(x)
this will remove the first x value.
-
a.pop()
this will remove & return the last value in the list
if it is like this;
a.pop(3)
it will remove the 4th value and return that value.
-
a.index(333)
this will give the index of the first 333 value in the array.
-
a.sort()
this will sort the array
-
a.reverse()
this will revers te array

List as stacks
pop() - to pop
append() - to push

Further bash

Return value of a program
Try this
#!/bin/bash
cd dada/ &> /dev/null/
echo return value : $?
cd &> /dev/null/
echo return value : $?
In ths program it will give a value as
1
0
If there is an error it will return 1 & if there is no error it will return value 0.
By this values we can make our program more user friendly.

Special things
To check if a variable is empty
-z s1
To chrck if a value is not empty
-n s1
Arithmetic relational operators
-lt - < -gt - >
-le - <= -ge - >=
-eq - ==
-ne - !=

sed
$sed 's/to_be_replace/replaced/g' /file_path
eg :
$sed /s/name/Name/g' ~/user_details.t
This will read the "user_details.t" file in my home directory and it will replace the "name" keyword to "Name" and give the output on stdout.

$sed 12,18d /user_file.t
This will show all the line except 12 to 18.

awk
$awk '/test/ {print}' ~/file.t
This will search the keyword test and print it.

$bc - a simple calculator
$bc -q [-q is to avoid the welcome screen]

Aug 30, 2010

MOre on bash

Functions
function my_function{
my_code}

Eg:
#!/bin/bash
function quit{
exit}
function hello{
echo Hello World!
}
hello
echo foo
quit

functions with parametrs
function my_function{
echo $1
echo $2
}
my_function para1 para2

In this the parametrs we are sending are assigned in the order of $1, $2, $3 ....
The $0 will give the script name that we excecute.

Options
#!/bin/bash
OPTIONS="Hello Quit"
select opt in $OPTIONS; do
if["$opt"="Quit"]; then
echo Done
exit
elif["$opt"="Hello"]; then
echo Hello World
else
clear
echo bad option
fi
done

More on python

For loop
a=['cat','window','home']
for x in a:
print x, len(x)
This will give the length of each text in the array of a.
The output will be like;
cat 3
window 6
home 4

range() -
This gives a numarical like
range(5)
[1,2,3,4,5]
but if you use as:
range(10,15)
Ti will give the output as
[10,11,12,13,14]
But it will give the output only upto 14.

break and cnntinue
for n in range(2,10)
for x in range(2,n)
if n%x ==0:
print n,'equals',n,'*',n/x
break

pass statment
It do nothinmg. We can yous it to create delay loops.
while true
pass

Default argument values
def ask_ok(prompt,retries=4,complaint='yes or no, please !'):
while true:
ok =row_input(prompt)
if ok in ('y','ye','yes'):
return true
if ok in ('n','no','nop','nope'):
return false
retries=retries-1
i fretries <0
raise IOError('refusnik user')
print complaint

Aug 27, 2010

Python

Python is an interpreted programming language. By just tuping python you can start programming.
When you type,
$python
It willl display as;
>>>
here you can type your program.
To exit from it, you can type Crlt+d or quit().

# is used to comment

Interpreter can be used as a calculator.
>>> (25+5)/5
6

The equal sign in used to assign values to a variable
>>>a=100 # assign 100 to a
>>>b=2*5 # assign 2*5 (10) to b
>>>a+b
110

complplex numbers are also supported, like
>>>complex(3,5)+complex(5,-5)
10+0j

In the interactive mode, the last printed output is asigned to the _ variable. So you can use,
>>>100+50
>>> _/3 # this work as 150/3
50
to forword last output to some other task.

Strings in python
>>>word="hello \n world"
>>>print word
hello
world

If you are deviding the string in to two parts you should use a \ like
>>>word="hello \
...world"
>>>echo word
hello world

String concatination
>>>word='A'+'Help'
>>>print word
AHelp

String repeat
>>>word='-Help-'
>>>print word*3
-HELP--HELP--HELP-

String indexing
>>> word='HELP'
>>>word[2]
'L'
Note: The string index is starting from [0].

Some special thing
>>>word='colombo'
>>>word[2]
'l'
>>>word[:2] # will give [0]and [1]
'co'
>>>word[2:] # will give [2], [3], [4]..
'lombo'
>>>word[:2]+word[2:]

Bash Programming

Write,

#!/bin/bash
echo Hello World
In a file and save it as script.sh

Then type
$chmode 777 script.sh
{To make it as an excecutable}

now type
$./sript.sh
to run the script
You will see the output as
$Hello World

It is a basic bash shell script.

There are 3 file descriptors
stdin <0 (<) stsout 1> (>)
stderr 2>
(std=standard)

By using fle descriptors we can do,

1. Redirect stdout to a file
eg:- ls -la > fileNmae.txt
This will not print the result of the "ls -la" command but will store in the file "fieName.txt"

2. Redirect stdout to a file
eg: grep da * 2> error_log.txt
This will store data if there is any error only.

3. Redirect stderr to stdout
eg: grep da * 2>&1

4. Redirect stdout to stderr
eg: grep da * 1>&2

5. redirect stdout and stderr
eg: grep &> out_error.txt

Pipe (|)
Send a output of a processer as an input to another processer.
eg: ls -la | less

Variables

#!/bin/bash
SRT='Hello World'
echo $SRT

This is a basic bash script which use variables. Variable is SRT and to get the stored data it use "$" sign infront of the variable.

We can create local variables by using "local" keyword.
local VB="hello world"
echo $VB

Basic conditions
If then else
if [expretion];
then
code for if the expretion is true
else
code for if the expretion is falls
fi
{note the fi in the last line}

eg:-
A="foo"
B="bar"
if ["$A"="$B"]; then
echo "Both are same"
else
echo "Not equal"
fi

For loop

num=10
for i in `seq 1 $num`; do
code
done

While loop
COUNT="0"
while [ $COUNT -lt 10]; do
code
let COUNT=COUNT+1
done

Until loop
COUNT="0"
until [ $COUNT -lt 10 ]; do
code
let COUNT=$COUNT+1
done

Aug 26, 2010

More on Emacs

Auto save
In emacs ther is a recovery mechanisum which is usefull if the system crashes while editing something.
When you need to recover something; it was saved in a format of "#file_name#". So you only need to open this file. But note if you save a file, this #file# will deleted by the emacs.

Mode line
--:** TUTORIAL 63% L749 (TEXT)------------------

63% :- indicates the current position of the document.
** :- indicates that you have edit the document
L749:- indicates the line number of the point
(TEXT):-_give an idea of the mode that you'r editing

Search
Emacs can search for strings. To search;
Ctrl + s
this will pormpt to input characters you need to search. While you are typing it will highlight the words.
By pressing Ctrl+s again and again you can switch between highlighted words.

Getting help
Ctrl+h ? - will list what kind of a help you need.

More on Linux commands

If you need to compress a text document you can use;
$gzip textfile.txt
This will convert the txt file to "textfile.gz".
To view a gz file you can use; $zcat

To view diffes between two files we can use;
$diff file1 file2 - in the output of this command < will view the diffes in file1 & > will view the diffes in file2

$find . -name "*.txt" -print ;
This command will find for the file name with ".txt" and print the file path. And also note the "." after the command. It meens the find is running on current directory and in all other sub-directories.

Compiling source code

First create a directory in homedirectory to store the program. Use mkdir command for it.

Then go inside the directory and type;
$./configure -prefix=$HOME/file_name
It will set the instalation path to your destination.
Now type;
$make
This will make the excecutable files
After that we should check the excecutable is working properly. To do that;
$make check
Then,
$make install - to install the program.
Now type;
$./"your_command_name"
It will run the program.
(* Note:- if you need to run the program by only typing the program name, you mustadd the path of the program to the PATH variable.
$set path=($path ~/directory/bin)
)

Variables
Variables are a kind ofpassing information from the shell to programs when there are running.
There are two types of variables,
1. Environment variables (in UPPER CASE)
2. Shell variables (in lower case)
By using $env command you can view environment variabler with their values.
USER, HOME, PATH and HOST are some environment variables.

More on Linux commands

If you need to compress a text document you can use;
$gzip textfile.txt
This will convert the txt file to "textfile.gz".
To view a gz file you can use; $zcat

To view diffes between two files we can use;
$diff file1 file2 - in the output of this command < will view the diffes in file1 & > will view the diffes in file2

$find . -name "*.txt" -print ;
This command will find for the file name with ".txt" and print the file path. And also note the "." after the command. It meens the find is running on current directory and in all other sub-directories.

Compiling source code

First create a directory in homedirectory to store the program. Use mkdir command for it.

Then go inside the directory and type;
$./configure -prefix=$HOME/file_name
It will set the instalation path to your destination.
Now type;
$make
This will make the excecutable files
After that we should check the excecutable is working properly. To do that;
$make check
Then,
$make install - to install the program.
Now type;
$./"your_command_name"
It will run the program.

More on GIT

Do some changers to the files and add them to the index.
$git add file1 file2 file3 - will do it.

Then $git diff --catched
You may see what is about to be commited by using this.

$git commit -this will commit the progect and it will record the new version.

View the history;
$git log - can get the history of changers
and
$git log -p gives the changers with diffs at each poit.

Manage branchers;
$git branch "name" - this will create a new branch with a nane.
$git branch - this will give a list of branchers.

BY using;
$git checout "name"- you can change the branch, edit, commit and switch back to the master branch.
(edit files)
$git commit -a
$git checkout master
Then make changers in master branch;
(edit files)
$git commit -a

Now you can merg them together by;
$git merg "name"
If there is no conflict you are done.If there are, it will be left in problematic files showing the conflicts.
$git branch -d "name" will ensure that the changers in the "name" branch are already in the current branch.

Aug 25, 2010

GIT virsion contrl system

It is a free and open source virsion controling system designed to handle very larg projects with speed and efficiecy.

To install it in fedora : yum install git
Then type;
$git-config usre.name "your name"
$git-config user.email "your mail address"
to interduce yourself.

The all download a project from :
http://git.wiki.kernel.org/

Extract the tar file :

$tar xzf project.tar.gz
$cd project
$git init

It will initialized the project and creats a .git file in the working directory.
Next tell git to create a snapshot of the content of each document inside the working directory.
$git add . {note the .}

$git commit
This will prompt you for a commit message.

A guide to Linux operating systems

Unix is an operating system which was first developed in 1960. It is astable, multitasking, multiuser operating system for all laptops, desktops and servers.
There are three parts of an UNIX operating system.
1. Kernel - The hub of the os. It manage time and memory. Handle file storage and communication.
2. Shell - It works as a inteface between user and the system.
3. Programs

Basic commands

ls - list the content in a directory
(type "man ls" to get more details about ls command)

cd - change the directory
cd .. - goto parent
cd or cd ~ - goto home

pwd - view the path to the current directory

mkdir - make a new file

rmddir - delete a directory if it is empty

cp - copy file
useage:"cp file1 file2" this will copy file1 as file2.

rm - remove file

cat - concatinate
useage: "cat foo.t" display the content of foo.t
("cat > bar.t" "cat >> bar" & "cat < bar.t") less - view page by page head - view first lines in a document useage: head 5 foo.t - will view fist 5 lines tail - view last lines in a document useage: tail 5 bar.t - will view last 5 lines wc : count words in a file & will give the output as "lines words charactors" grep - find keywords in a file useage: "grep 'foo bar' text.t" search for the pattern "foo bar". "command" > file - redirect the output to file
"command" < file - redirect the input from file

command1 | command2 - pipe command1s output to command2s input

man "command" - read the manual of the command

chmod - change the file mode

"command" & - command will run in background

Aug 24, 2010

Emacs basics

Emacs is a basic GNU Emacs is an extensible, customizable text editor--and more. At its core is an interpreter for Emacs Lisp, a dialect of the Lisp programming language with extensions to support text editing.

Emacs tutorial: http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html

Basic key stocks -
-----------------------------
         Ctrl + v : page down                     Alt   + v : page up
         Ctrl + l : clear screen
-----------------------------
         Ctrl + n : next line - dawn
         Ctrl + p : previous line- up
         Ctrl + f : forward - right              Alt + f : move forward by a word
         Ctrl + b : backward - left             Alt + b :  move backward by a word
----------------------------
         Ctrl + a : move to beginning       Alt + a : move to beginning of a
                         of a line                                      sentence
         Ctrl + e : move to the end           Alt + a : move to the end of a line
                          of a line

update:

Ctrl+x Ctrl+f - Find file
Ctrl+x Ctrl+s - save file
Ctrl+x s - save buffer_________________