Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Monday, June 8, 2009

Common vi editor command list

Common vi editor command list

From:http://www.freeos.com/guides/lsst/misc.htm#commonvi

For this Purpose
Use this vi Command Syntax

To insert new text
esc + i ( You have to press 'escape' key then 'i')

To save file
esc + : + w (Press 'escape' key  then 'colon' and finally 'w')

To save file with file name (save as)
esc + : + w  "filename"

To quit the vi editor
esc + : + q

To quit without saving
esc + : + q!

To save and quit vi editor
esc + : + wq

To search for specified word in forward direction
esc + /word (Press 'escape' key, type /word-to-find, for e.g. to find word 'shri', type as
/shri)

To continue with search 
n

To search for specified word in backward direction
esc + ?word (Press 'escape' key, type word-to-find)

To copy the line where cursor is located
esc + yy

To paste the text just deleted or copied at the cursor
esc + p

To delete entire line where cursor is located
esc + dd

To delete word from cursor position
esc + dw

To Find all occurrence of given word and Replace then globally without confirmation 
esc + :$s/word-to-find/word-to-replace/g

For. e.g. :$s/mumbai/pune/g
Here word "mumbai" is replace with "pune"

To Find all occurrence of given word and Replace then globally with confirmation
esc + :$s/word-to-find/word-to-replace/cg

To run shell command like ls, cp or date etc within vi
esc + :!shell-command
For e.g. :!pwd

Sunday, May 31, 2009

Python 4


getopt.getopt(args, options[, long_options])

Parses command line options and parameter list. args is the argument list to
be parsed, without the leading reference to the running program. Typically, this
means sys.argv[1:]. options is the string of option letters that the
script wants to recognize, with options that require an argument followed by a
colon
(':'; i.e., the same format that Unix getopt uses).

Saturday, May 30, 2009

Python 3

1. Parentheses are optional

2. End of line is end of statement

3. End of indentation is end of block
Inside a block all the indentation should be the same.

4. Multi-statements per line, separate them using semicolon ';'
 
5. One statement span across multiple lines, by putting the statements into a bracketed pair - parentheses "()", square brackets "[]", or dictionary braces "{}".

6. raw_input() for console input

7. print to file: print >> filename, a, b, c

8. Statements execute one after another, until you say otherwise

9. Block and statement boundaries are detected automatically

10. Compound statements=header,":" indented statements

11. Blank lines, spaces, and comments are usually ignored

12. Docstrings are ignored, but saved and displayed by tools

13. A=Y if X else z

14. while
      while <test1>:
               <statements1>
      else:
               <statements2>


15. pass, continue, break, else

16. for
      for <target> in <object>:
               <statements1>
      else:
               <statements2>


17. the else statement in while and loop will be executed only when the loop is terminated because of the testing condition is broken, i.e. else statement won't be executed when the loop is stopped by a break in the <statements1>.

18. File scanners:
read file character by character
      for char in open('test.txt').read():
              print char

read file line by line
     for line in open('test.txt').realines():
             print line

or
     for line in open('test.txt').xreadlines():
              print line

readlines() load the file once, xreadlines() load the file when demanded.
We can also
     for line in open('test.txt')
             print line


19. range()

20. Parallel Traversals: zip and map
Using zip to construct dictionaries.

21. Don't forget the colons

22. Start in column 1

23. Blank lines matter at the interactive prompt

24. Indent consistently.

25. Don't code C in python

26. Use simple for loops instead of while or range

27. Beware of mutables in assignments

28. Don't expect results from functions that change objects in-place

29. Always use parentheses to call a function

30. Don't use extensions or paths in imports and reloads

31. def Statements for function definition
    def <name>(arg1, arg2,..., argN):
           <statements>
           return <value>

32. Python Scope Basics
    a. The enclosing module is a global scope;
    b. The global scope spans a single file only;
    c. Each call to a function creates a new local scope;
    d. Assigned names are local unless declared global;
    e. All other names are enclosing locals, globals, or built-ins.

33. Immutable arguments are passed by value
      Mutable arguments are passed by pointer

34. lambda Expressions
    lambda arg1, arg2,... , argN : expression using args


Python 2

1. Dictionary
Mapping operations:
    d['quantity']+=1
Create a dictionary:
    d={}
    d['name']='bob'
    d['job']='dev'
    d['age']=40

Nesting:
    d={'name':{'first':'Bob','last':'Smith'},'job':['dev','mgr'],'age':40.5}
    res['name']['first'] is the 'Bob'

We can not sort the dictionaries directly, but we can sort the keys.
    ks=d.keys()
    ks.sort()
    for key in  ks: print key, '=>', D[key]

Another way is:
    for key in sorted(D): print key, '=>', D[key]

2. Iteration
    squares=[x**2 for x in [1,2,3]] #result is [1,4,9]

3. Performance
using time and timeit modules and the profile module to find more information about the code.

4. Check missing keys
We can add new keys to dictionaries, but fetching nonexistent keys are still a mistake.
    d.has_key('f')
    if not d.has_key('f'): print 'missing'

5. Tuples
    t=(1,2,3)
tuples are similar to list, but they are immutable, they cannot be changed in place.

6. Files - core type of python
    f=open('data.txt','w')
    f.write('Hello\n')
    f.close()
read mode is the default one.
    f=open('data.txt')
    bytes=f.read()  #read entire file into a string, here bytes is 'Hello\n', noticing the control characters
   
7. Set
    X=set('spam')  #result set(['s','p','a','m'])
    Y=set(['h','a','m'])
    X&Y  #intersection
    X|Y    #union
    X-Y    #difference

8. Decimal

9. check the type
    if type(L)==type([]): print 'list'
    if type(L)==list: print 'list'
    if isinstance(L,list): print 'list'

10. string format of numeric data
    num=1/3.0
    "%e" % num     #result '3.3333e-001'
    "%2.2f"  %  num    #result '0.33'


Friday, May 29, 2009

Python I

1. Unix Shell Scripts
     #! /usr/bin/env python
     ...script goes here...

2. Pause the script
    raw_input()

3. Python built in types
    Numbers      1234, 3.14, 999L, 3+4j, Decimal
    Strings          'spam', "guido's"
    Lists              [1,[2,'three'],4]
    Dictionaries   {'food':'spam', 'taste':'yum'}
    Tuples            (1,'spam',r,'U')
    Files               myfile=open('eggs','r')
    Other types    Sets, types,None,Booleans


4. math module contains more advanced numeric functions
    import math
    math.pi
    math.sqrt(85)

5. random module performs random number generation and random selections
    import random
    random.random()
    random.choice([1,2,3,4])

6. String in python
     len(S) #length
     S[0]    #the first character of string S
     S[-1]   #the last item of string S
     S[1:3]  #substring of S, includes S[1] and S[2], without S[3]
     S[0:]
     S[:3]
     S[:-1]
     S[:]
     s1+s2   # concatenation
     s*8       # repetition

   Notice: string objects in python are immutable, we can never change the content of the string, only can we create new strings.
    s[0]='z'  will cause error
    s='z'+s[1:] is the correct way
    s.find('pa')  # find substring
    s.replace('pa','XYZ') #replace

    These functions don't change the original string.
    s.split(',')
    s.upper()
    s.isalpha() #content tests: isalpha, isdigit, etc
    s.rstrip() #remove whitespace on the right side


7. use dir(object) function to see what methods it has.
 
8. to ask about what each function does, use help(object.function)

9. show the value of character, ord('\n')

10. re module for regular expression
    import re
    match=re.match('/(.*)/(.*)/(.*)','/usr/home/jack')
    match.groups() #output is ('usr','home','jack')

11. List is mutable, i.e. changed in place unlike string.
     l[0]='123'
     l.append('NI')
     l.pop(2)
     l.sort()
     l.reverse()

12. arbitrary nesting is supported
     M=[[1,2],[3,4]]
     M[1]    # result is [3,4]
     M[0][1]   # result is 2

13. List comprehension - accessing columns
     c=[row[1] for row in M]  # result is [2,4]

Tuesday, May 19, 2009

Write floats to binary file

1. Randomly create a series of float numbers, then write it in a binary file:

#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
    srand(time(NULL));
    ofstream fout("test",ios::binary);
    ofstream fres("res.txt");
    float data;
   
    cout<<sizeof(data)<<endl;
    for(int i=0;i<100;++i)
    {
        for(int j=0;j<21;++j)
        {
            data=rand()*10.0/(RAND_MAX+1.0);
            fres<<data<<endl;
            fout.write((char*)(&data),sizeof(data));
        }
    }
   
    fout.close();
    return 0;
}

2. Decode the binary file:

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    ifstream fin("test",ios::binary);
    ofstream fout("de.txt");
    char buffer[5];
    float *data;
   
    cout<<sizeof(data)<<endl;
   
    while(!fin.eof())
    {
        fin.read(buffer,4);
        buffer[4]='\0';
        data=(float*)buffer;
        fout<<*data<<endl;
    }
   
    return 0;
   
}
Google+