Saturday, September 4, 2010

HTML5 : The canvas element

The canvas element is actually a rectangle of space, ie a two dimensional grid. With this canvas element we can render graphs, game graphics and other visual images and use javascript. It has no content and border of its own.

The mark up for creating a canvas,

canvas id = "a" width = "200" height = "200" /canvas

Define a variable and assign the canvas element by id.

var a_canvas = document.getElementById("a");

After finding the canvas element in the DOM invoke its getcontext method, the context is where all the actions on canvas take place. Pass a string 2d to the function. Now we got the context.

var a_context = a_canvas.getContext("2d");

Now we got the canvas and its drawing context, where all the drawing methods are defined like fillStyle, fillRect,fillStroke etc. Now draw a rectangle in the canvas.

a_context.fillRect(0,0,200,200);

The parameters indicate starting x,y coordinates and width and height.

HTML5 : Introduction

It is not a totally new version of HTML 4 . It support the features of HTML 4 and is a collection of individual features like canvas, video, geolocation etc. We can interacts with javascript through DOM (Document Object Model). It does not have any special notation to handle features like video. The API defines this. Upgrading to HTML5 need only change the doctype.

!DOCTYPE html

It defines new semantics like article, section, footer etc.

Local Storage :

HTML5 provides local storage. It stores information on the mechine, this allows the sites to retrieve it later.

Friday, September 3, 2010

Programming in UNIX Environment : Using the shell

A greater than sign '>' followed by a name makes a file of that name. the -n option of echo command is for omiting the newline. the '-l' option for the 'who' command shows the details of users. The shell is a command like all unix commands. It is represented by 'sh'.

$ > file //creates a file named file.
$ echo -n you are lucky
$ echo /* //prints the all the folders in root (not recursively)
$ echo \* //prints a '*' character
$ who -l

Programming in python : Classes

Create a class as follows,

>>> class abc():
... a = 1
... b = 2
...
create x as an instance of the class abc,

>>> x = abc()
>>> x
<__main__.abc instance at 0xb7fab3ac>
>>> x.b
2
Create another class with a function definition,

>>> class abc():
... a = 3
... b = 4
... def fun():
... print 'hello'
...
>>> x = abc()
>>> x.a
3
>>> x.b
4
>>> x.fun()
Traceback (most recent call last):
File "", line 1, in
TypeError: fun() takes no arguments (1 given)

We cannot call the function in class abc, as an attribute of x. x has no such an attribute. But the address of x is already given by the interpreter as a parameter to that function. Usually we give an extra parameter 'self', have no special meaning.

>>> class abc():
... a = 1
... b = 2
... def fun(self):
... p = 5
... q = 6
... print 'hello'
...
>>> x = abc()
>>> x.a
>>> 1
>>> x.p
>>> x.fun()
The above statement causes an error. Because x has no attribute p. 'x.fun()' cannot print hello, so little changes are needed to our code and is shown below.

>>> class abc():
... x = 1
... y = 2
... def fun(self):
... self.p = 3
... self.q = 4
... print 'Hello'
...
>>> m = abc()
>>> m.p
Traceback (most recent call last):
File "", line 1, in
AttributeError: abc instance has no attribute 'p'

Here the interpreter says that the abc instance has no attribute 'p'.'p' is an attribute of the function 'fun'. So create an instance of abc and pass the address of m to 'self'.

>>> m = abc()
>>> m .fun()
Hello

Thursday, September 2, 2010

Programming in UNIX Environment : Commands - sort, tail, cmp, diff

The command 'sort' is for sorting the line of the text. 'tail' prints the last ten lines of the file. 'cmp' for showing the difference between the files. It shows only the first difference. But 'diff' shows all the difference between two files.

sort filename1 file2
sort -r // reverse normal order.
sort -n // numeric order.
sort -f // fold upper and lower case together.
sort -b // Ignore the leading blanks.

tail filename // prints last 10 lines.
tail -3 filename // print last 3 lines.

cmp filename1 filename2 // prints only the 1st difference.

diff filen1 filen2 // prints all differences.

pwd - For printing current working directory.
cp - For copying a file.

cp /home/abhi/Pclass/num.c num.c

ed /home/abhi/Pclass/num.c

Programming in UNIX Environment : Commands - mv, rm, wc, grep

The 'mv' command is using for renaming. And 'rm' command for removing files. 'wc' for counting lines,words,characters. The 'grep' command is for searching a word. '-v' for searching all words except the indicating word in a line.

mv filename newname

rm filename1 filename2

wc filename1 filename2 // count lines,words,characters.
wc -l //only counts the new lines.
wc -w //print the word count.
wc -m //print the character counts.
wc -c //printf the byte counts.

grep int filename // for searching the word int.
grep -v int filename // all except int.

Programming in UNIX Environment : Commands - kill, ps, nohup, nice

The ampersand at the end of the command says that run this command and also take another from the terminal without stopping the first. It prints the process id. For stopping a process we use 'kill' command followed by process id. 'ps' command prints what that user running. Using 'nohup', the command will run even if the user logged out. 'nice' is for using another system to run our job.

$wc a* >wc.out &

$kill 6578

$ps

$ps -ag // all process that are currently running.

$nohup command & // No hangup for this command even if user logged out.

$nice expensive-command & // if your command take a lot of processor resources.

The 'at' command followed by time is to run our job at whatever time we want.

$ at 2340
There is a file '.profile' in the user's login directory, this file contains commands which the user want to run when the user logged in. A user can set things in it.

a=/long/directory/name

$cd $a

We can put 'a' as given above in our profile. So we can refer that directory by the value of shell variable.

Unix file system : Devices

/dev/rp00 and /dev/rp01 are named after the DEC RP06 disc drive attached to the system. We cannot make a link to a file in another subsystem. One reason is that the inode numbers are not unique in different file systems.
$ df
$ tty
$ mesg n
$ mesg y

The 'df' command tells the available space in the mounted file subsystem. The 'tty' command tells which terminal we are using. So we can send files and informations to that terminal and it appears in the corresponding terminal. 'mesg n' turn off the messages. /dev/tty is a synonym for our terminal.

If we want to run a program and its output files are not importent we can redirect it to '/dev/null' causes its output to be thrown away.

Wednesday, September 1, 2010

Unix file system : The directory hierarchy

When the system starts the file /boot is read, it then reads /unix (it is the program for the UNIX kernal itself).

The following shows some directories which reside in root and its contents.

/bin : basic programs like who,ed reside.

/etc/rc : This is a file of shell commands which is executed after the system is bootstrapped.

/etc/group : lists the members of each group.

/lib : Contains the parts of the C compiler.

/tmp : Contains temporary (short-lived) files that are created in the execution of programs.

Unix file system : Inodes

The administrative infomation is stored in the inode. It contains information such as how long it is, where the contents of the file are stored on disc etc.
System's internal name for a file is its i-number.

$ ls -lut
$ ls -lct
$ ls -i
$ ls -ict

'rm' command is for removing a file. 'mv' command is for moving and renaming the files.

$ rm filename1 filename2
$ mv filename1 filename2



The -ut lists the file in order of usage time. -ct lists the files in the order of inode change time. The '-i' option is for listing the i-numbers of the directories contents. '-ict' lists inode number in order of the modifications in the inode (most recently first).

Unix file system : Permissions

The file /etc/passwd is the password file. It contains all the login information about each user. We can discover each users id and group id by looking name in /etc/passwd.

$grep name /etc/passwd

The fields in the password file looks like 'login-id:encrypted password:uid:group-id:miscellany:login-directory:shell'. The -l option of ls command prints the permissions.

$ls -l

We can find a string like '-rw-r--r--' . The first - means that it is an ordinary file. If it is a directory there prints a 'd'. The next three field is the permissions of the owner followed by the next three field is the permissions of the group and the next is the others permissions. We cannot edit the passwd file . But the super user can do it.


The 'chmod' command changes the permissions of a file. 'permissions' may occupy octal numbers. The '+' sign is for 'ON' permission modes and to OFF the '-' sign is using. The '-w' option is for turn off the write permisssion for all incliding the owner. '+x' allows every one to execute the following command.

$ chmod permissions filename
$ chmod -w filename
$ chmod +x command
$ chmod -w .
$ chmod 775 filename //Restores the permission.

The '-w .' means removing the write permission of all files in that directory.

Sunday, August 29, 2010

Programming in Python : Dictionaries

Dictionaries are another data type in python. It can be think as a unordered collection of keys associated with values. The keys can be numbers, strings, or tuples. An empty dictionary is denoted by '{ }'. We can view all keys by simply calling keys(). The dict() constructor is using to build a dictionary.

>>> dic = {'one':1,'two':2,'three':3,'four':4,'five':5}

>>> dic
{'four': 4, 'three': 3, 'five': 5, 'two': 2, 'one': 1}

>>> dic['six'] = 6

>>> dic
{'six': 6, 'three': 3, 'two': 2, 'four': 4, 'five': 5, 'one': 1}

>>> del dic['five']

>>> dic
{'six': 6, 'three': 3, 'two': 2, 'four': 4, 'one': 1}

>>> dic['seven'] = 7

>>> dic
{'seven': 7, 'six': 6, 'three': 3, 'two': 2, 'four': 4, 'one': 1}

>>> dic.key()

Traceback (most recent call last):
File "", line 1, in
AttributeError: 'dict' object has no attribute 'key'

>>> dic.keys()
['seven', 'six', 'three', 'two', 'four', 'one']

>>> dic['seven']
7
>>> dic['one']
1

>>> 'one' in dic
True

>>> 'three' in dic
True

>>> 'kjkk' in dic
False

>>> del dic['one']

>>> dic
{'seven': 7, 'six': 6, 'three': 3, 'two': 2, 'four': 4}

>>> dic.keys()
['seven', 'six', 'three', 'two', 'four']

>>> dic.values()
[7, 6, 3, 2, 4]

>>> a=[('aass',23),('iiii',56),('dftj',38)]

>>> a
[('aass', 23), ('iiii', 56), ('dftj', 38)]

>>> dict(a)
{'aass': 23, 'iiii': 56, 'dftj': 38}

>>> b = dict(a)

>>> b
{'aass': 23, 'iiii': 56, 'dftj': 38}

>>> dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)
{'jkhjkhk': 3434, 'jhjkhk': 433, 'iuijmkm': 344343}

>>> c = dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)

>>> c
{'jkhjkhk': 3434, 'jhjkhk': 433, 'iuijmkm': 344343}

Programming in Python : Sets

Set is a data type in python. It is an unordered set of elements without duplicates. We can test an element is a member of the set. Set operations can operate on unique letters as given below.

>>> list1 = ['apple','mango','pineapple','mango','apple','orange']

>>> fruit = set(list1)

>>> fruit
set(['orange','mango','apple','pineapple'])

>>> 'mango' in fruit
True

>>> 'grape' in fruit
False

>>> a = ('abhilash')

>>> a
'abhilash'

>>> b = ('abhijith')

>>> b
'abhijith'

>>> set(a)
set(['a', 'b', 'i', 'h', 'l', 's'])

>>> set(b)
set(['a', 'b', 'i', 'h', 'j', 't'])

>>> c = set(a)

>>> d = set(b)

>>> c
set(['a', 'b', 'i', 'h', 'l', 's'])

>>> d
set(['a', 'b', 'i', 'h', 'j', 't'])

>>> c-d
set(['s', 'l'])

>>> d-c
set(['j', 't'])

>>> c |d
set(['a', 'b', 'i', 'h', 'j', 'l', 's', 't'])

>>> c & d
set(['a', 'i', 'b', 'h'])

>>> c ^ d
set(['s', 't', 'j', 'l'])

Programming in python: Tuples and sequences

Tuples consists of elements that are enclosed in parenthesis. The empty tuples is represented by '()'. The single element tuple is ending with a comma.

>>> t = ('one','two','three')

>>> t
('one','two','three')

>>> e = ()

>>> e
()

>>> len(e)
0

>>> single = ('one',)

>>> single
('one',)

>>> len(single)
1

The statement t = 1223,5676,'one','two' is an example of tuple packing. The elements are packed together in a tuple. The sequence unpacking is also possible. ex: a,b,c,d = t

>>> t = 1223,5676,'one','two'

>>> t
(1223,5676,'one','two')

>>> a,b,c,d = t

>>> a
1223

>>> d
'two'

Programming in Python : Lists

The list data type in python allows more operations compared to the other data types. The items in the lists are enclosed by brackets '[]'. It may contain numbers, srtings, tuples or lists (nesting of lists).

>>> list1 = [1,2,3,'how','are','you']

>>> list1
[1, 2, 3, 'how', 'are', 'you']

>>> list1[3]
'how'

>>> list1[3:]
['how', 'are', 'you']

>>> list1[:2]
[1, 2]

>>> list1[:2] = 'and'

>>> list1
['a', 'n', 'd', 3, 'how', 'are', 'you']

>>> list1[:2] = ['and']

>>> list1
['and', 3, 'how', 'are', 'you']

>>> list1 = [12,34,56,'s','y']

>>> list1
[12, 34, 56, 's', 'y']

>>> list2 = [22,'22']

We can add members of one list to the members of another list.
>>> list1[3:3] = list2

>>> list1
[12, 34, 56, 22, '22', 's', 'y']

>>> list3 = [33,list2,'33']

The following list is nested.
>>> list3
[33, [22, '22'], '33']

>>> list3[1][1]
'22'

>>> list3[1][0]
22


The del statement :

It is used to remove an element from a list when the index of that element is given. It can be used to clear the entire list or remove the variable.

Programming in Python : Strings

Strings are also manupulated by python. Strings are represented within single quotes or double quotes. We can assign a string to a variable, and printed by using 'print'. Strings can be surrounded by triple quotes """. If there is \n the end of line, is echoed in the output.

>>> "Hello"+"world"
'Helloworld'

>>> a='how are you?'

>>> print a
how are you?

The slice notation :

The slice notation is used to return the elements of a list or characters of a string as specified by the indices.

>>> string1 = 'hello world'

>>> string1
'hello world'

>>> string1[0:1]
'h'

>>> string1[0:4]
'hell'

>>> string1[2:4]
'll'

>>> string1[:4]
'hell'

>>> string1[3:]
'lo world'

>>> string1[:0] = 'Hai'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment

>>> string1[:0] + 'Hai'
'Hai'

>>> string1
'hello world'

>>> string1[:] + 'Hai'
'hello worldHai'

>>> 'Hai' + string1[:]
'Haihello world'

The negative indices are using to indicate from the right to the begining of the string.

>>> string1[-1]
'd'

>>> string1[-4:-1]
'orl'

>>> string1[-4:-2]
'or'

>>> string1[-4:0]
''

>>> string1[-1:-4]
''

>>> string1[-11:-1]
'hello worl'

Programming in Python : Arithmetic operations in python

Python is a functional programming language. Arithmetic operations are simply done as shown below in python interactive mode.

>>> 3+5
8

>>> (10+40)/10
5
A value can be assigned to sevaral variables simultaneously. Complex numbers are also supported. Imaginary numbers are written with a suffix j or J. In a complex number z, z.real and z.imag returns real and imaginary parts respectively. In interactive mode the last printed character is assigned to a variable'_'.

>>> x = y = z = 0

>>> -1j * 1j
(1+0j)

>>> a=678

>>> a*23
15594

>>> print _
15594

>>> _/22
708

Tuesday, August 24, 2010

Programming in Unix Environment : Using the shell

Command line structure :

A command usually ends with a newline but a semicolon ';' is also a command terminator. Parentheses can be used to group commands. Data flowing through a pipe can be trapped and placed in a file by using 'tee' command. tee copies its input to the file and its output. Another command terminator is '&' ampersand, which tells the shell not to wait for the command to complete, and we can enter another command to execute. The 'sleep' command waits the specified number of seconds before exiting. Here shows an example in which the the command after ampersand is 'who' it executes first and date executes after five seconds.

$ (date ; who) | wc
$ (who ; date) | tee file | wc
$ long-running-command &
$ sleep 5
$ (sleep 5 ; date) & who

Metacharacters :

The way to specify the metacharacters without its meaning - within single quotes.

$ echo '**'

Friday, August 13, 2010

UNIX file system : An Overview

A file is nothing more than a collection of data. Here describes a set of commands.

The command 'od' prints a visible representation of a file. The '-c' option is for interpreting bytes as characters. '-b' for printing the bytes as octal numbers.

$od -c file_name
$od -b file_name

The 'file' command guesses the type of the file. 'od' command with no option dumps the file in 16 bit words.

$od file_name
$file file_name



The command 'du' (disc usage) is to display the disc usage that consumed by the files in that directory. The -a option is for displaying all including the files in a directory. To search a specific file, the output is piped through grep.

$du
$du -a
$du -a | grep file_name

A directory consists of 16 byte chunks, the last 14 bytes of which hold the file name padded with ascii NULs. The first two of which tell the system where the administrative information resides.

The 'find' command finds the file specified.

$find file_name

Programming in C: Remember these points on constants.

A 'long' constant is written like 1234567697L or 567874338l. Big integer type constant is also taken as long. 'unsigned' constants written with a terminal u or U. 'unsigned' long type constants written with the terminal ul or UL. Floating point constants contain decimal point or an exponent (1e-1) or both. They are declared as 'double' type. The value of an integer can be specified as octal or hexadecimal. A leading zero on an integer constant means octal and a leading 0x or 0X means hexadecimal.

decimal : 31 octal : 031 hex : 0x1F

Character constants :

It is an integer. eg.'x'. A constant expression is an expression that involves only constants. They are used in any place where a constant occurs. A string constant or a string literal is a sequence of zero or more characters surrounded by double quotes.

In switch each case is labeled by integer valued constants or constant expressions. In the while and do loops 'continue' means that the test part is executed immediately. In for loop the control passes to the increment step. The continue statement applies only to loops not to 'switch'.

Programming in C : Remember these points on operators.

The cast operator has same high degree of precedence as other unary operators. The increment and decrement operators can only be applied to variables. An expression like '(exp) ++' is illegal. Bitwise shift operators can be used with constants or variables.

Var >> n

Here 'Var' is shifted n positions to the right. 'n' must be a positive value. Bitwise operators are using only on integral operands.

Tuesday, August 10, 2010

Programming in C: Remember these points on Datatypes.

'int' is 32 or 16 bit long and it depend upon machines. 'short' is often 16 bit long. 'signed' and 'unsigned' may be applied to char. But is plain chars are signed or unsigned ? It is machine dependent. If 'x' is float and 'i' is int, x = i and i = x both cause conversions.

Specify type correctly:

Please take a nice look to these points,
In C when we write an expression we must ensure that we specified the types correctly.
In an expression even if the left hand side is declared as floating point and the right hand side contain integer arithmetic & constant division, these constant division results the number truncated to integer. So we must represent these constants, as floating point number.
Consider the following expression

(float) a = (b - 18) * 7 / 9 ;

false result will goes to ' a '
we must write as,

(float) a = (b - 18) * 7 .0 / 9.0 ;

or

(float) a = (float) (b - 18) * 7 / 9 ;
Now,
when talking about the range of int , float it depends on the machines,
16 - bit int that is 2^16 = 65536 , dividing by 2 , 65536 / 2 it equals 32768
that is range - 32768 to 32767 for signed integers.


Consider the following expression,

(n > 0) ? f : n ;

If 'f' is float and 'n' is int the expression has type 'float' according to the conversion rule, not by the result of the condition.

Programming in C: Remember these points on Variables.

Don't begin variable names with underscore, since library routines often use such names. Upper and lower case letters are distinct. Atleast first 31 characters of an internal name are significant. External names may be used by assemblers and loaders over which the language has no control. The definition of C gurantees that any character in the machine's standard printing character set will never be negative.

Programming in C: A Small note on Functions.

printf, getchar(),putchar() all are C functions. No fuction can be split between files. 'main' function returns a value ,zero if normal termination or nonzero erroneous termination. The function prototype agree with the definition and uses of the function. If the actual arguments are more than the formal arguments, the extra arguments are discarded. And if the actual arguments are smaller than the formal arguments extra formal arguments are initialized to some garbage values. Automatic variables do not retain their values from one call to the next and must be set upon each entry. Any expression may follow a return statement. To assure a high degree of portability between programs a function should generally be coded without involving any I/O operations.Function returns int as default.To assure a high degree of portability between programs, a function should generally be coded without involving any I/O operations.

If a function fails to return a value its value is certain to be garbage. We can also compile three source files using 'cc' command which contain the program functions.

$ gcc main.c fun1.c fun2.c

Consider the statement, x = function1() + function2();

Here the order in which the calculation, function1() may be evaluated first or function2() may. C cannot specify such an order.

Programming in UNIX Environment : Commands - echo, rm, whoami

Take a look to the following UNIX commands.
who am i -This command shows your user name,teletype,date and time.

whoami - Shows only user name.

In UNIX systems,

parent directory is denoted by '..'
current directory is denoted by '.'

rmdir - for remove a directory. It removes only empty directories.

About shell :

When we type the commands it goes to the shell.It is an ordinary program.

cat c* //prints all file that begins with c.

when * occurs shell takes it and it means any string of characters. Note the * is not the property of the cat command.

The echo command lists what we type.

echo word

echo ch* //lists all begin wth ch.

echo * //lists all.

rm * - removes all.

rm *.text - removes all with .text.

pr r[1234]* // prints all that begin wth r and followed by 1,2,3 or 4.

rm te[a-z] //removes all files starting with te and followed by a lower case.


You cannot make up new files using pattern matching.

ls \? or ls '?' loses its meaning.

echo * // prints all.

We can redirect the output by using '>'. Take input from a file by using '<' followed by filename.When the file does not exist it will be created. For redirecting output to a file without losing the data of yhe file we uses '>>'.

ls > filelist

pr -3
cat file1.c file2.c > file3

cat file4.c >> file3.c

grep num.c

Thursday, August 5, 2010

Programming in UNIX environment : Commands - ed, cat, ls, pr,

In UNIX environment we use a lot of commands. Some commands are explaining here.
For editing a file we use ed command.
$ed file1
no such file or...
a
Enter the text
.
w file1
q
$

When we type the command 'ed' and the filename, if the file does not exist, it shows a message. Type 'a' for appending. After adding types a '.' character in the next line to indicate writing is over.Then write it into the file by typing 'w' and the file name.And 'q' to quit.
The command 'cat' shows the content of the file.
$cat sachin
$cat sachin num
'pr' instead shows the content by pages and the file name.In 'pr -m filename' the 'm' indicates the columns.
pr sachin
pr sachin num
$pr -3 sachin num
$pr -m // a set of files in parallel columns.

The 'ls' command lists all the files. The ls * lists all including the files in the directories.

ls DIRname
$ls *
$ls -t // list by time.
$ls -l //list by details.
$ls -lt //list by details by recent first.
$ls -u // infn abt when files were used.
$ls -ult // most recent.

Monday, August 2, 2010

Programming in C : A small note on arrays

The subscript of an array can be ' an expression ' which yields integers. Note that any reference to the array outside the declared limit would not necessarily cause an error.

If array size declared as 10 , then we declare first element to zero , as

int array [10] = {10} ;

then all elements are declared as zero automatically.

Here is an example of wrong declaration to an array.

char alpha [3] = {a,b,c} .

If you want to store alphabets into an array store its integer values ,

char alpha [3] = { 'a' , 'b' , 'c' }
and print them as characters.

Friday, July 30, 2010

Programming in C : The value of the Expression

In C the value of the expression like (n == 0) , (x != n+1) , getchar() != EOF is zero or one.

Value of EOF is -1. This value may vary according to the machine.
And the value of character constants like '\n' has an integer value as 'A' has the value 65.