Thursday, October 27, 2011

[Level 1] Get partition uuid on Ubuntu.

# blkid
/dev/sda1: UUID="05580ede-bec4-44ae-b1a5-8e8c7b2e7c58" TYPE="ext4" 
/dev/sda2: UUID="3df58602-322b-437a-b65c-de21293f6840" TYPE="swap" 
/dev/sda5: UUID="5417e3d4-4b7d-4a79-a58a-a53cbeab6112" TYPE="ext4"
Wish this helps.
regards,
Stanley Huang

[Level 1] Backup directories by cpio.

#!/bin/bash
source=$1
target=$2
(cd $source; find . -print | cpio -ocv) | (cd $target; cpio -icuvd)
# cd $source; find . -print | cpio -ocv > /tmp/tmp.cpio
# cd $target; cpio -icuvd < /tmp/tmp.cpio
Wish this helps.
regards,
Stanley Huang

Monday, October 17, 2011

[Level 2] Rock-Paper-Scissors

#!/bin/env python
import random
RPS = { 'Rock' : 1, 'Paper' : 2, 'Scissors' : 3 } 

if __name__ == '__main__':
    comRPS = random.choice(RPS.keys())
    com = RPS[comRPS]
    youRPS = raw_input('Rock/Paper/Scissors: ')
    you = RPS[youRPS]
    print 'Com: %s' % comRPS
    print 'You: %s' % youRPS
    if com % len(RPS.keys()) + 1 == you:
        print 'You wins!'
    elif you % len(RPS.keys()) + 1 == com:
        print 'Com win!'
    else:
        print 'Break even!'
Wish this helps.
regards,
Stanley Huang

[Level 2] map, reduce and filter methods in Python

#!/bin/env python
a = [1,2,3,4,5,6,7,8,9]
b = [1,2,3,4]
c = [5,6,7,8]
 
print filter(lambda x: x>5, a)
print map(lambda x,y: x+y, b, c)
print map(lambda x,y: bool(x) and bool(y), a, b)
print map(lambda x,y: bool(x) or bool(y), b, a)
print reduce(lambda x,y: x+y, a)
$ /tmp/t.py 
[6, 7, 8, 9]
[6, 8, 10, 12]
[True, True, True, True, False, False, False, False, False]
[True, True, True, True, True, True, True, True, True]
45
Wish this helps. regards, Stanley Huang

Sunday, October 16, 2011

[Level 2] The sample of functools.partial() in Python.

#!/bin/env python
import functools
try:
print int('10')    ## equiv: print int('10', base=10)
print int('10', 2) ## equiv: print int('10', base=2)
int2 = functools.partial(int, 2) ## no default bonding parameter.
print int2('10')   ## fail, must assign the value of base
int2 = functools.partial(int, base=2) ## set default base to 2
print int2('10')   ## equiv: print int2('10', base=2)
print int2('10', 10) ## fail, TypeError: keyword parameter 'base' was given by position and by name
print int2('10', base=10)
Wish this helps.
regards,
Stanley Huang

Friday, October 14, 2011

[Level 2] How to implement Enum in Python

#!/bin/env python
class CreateRemove:
    Create = 1
    Remove = 2

class AllowDeny:
    Allow = 1
    Deny = 2

print CreateRemove.Create
print AllowDeny.Deny
Wish this helps.
regards,
Stanley Huang

[Level 1] Restrict user login in ssh.

You can use AllowUsers/AllowGroups/DenyUsers/DenyGroups in sshd_config to limit user login.
e.g.
# cat /etc/ssh/sshd_config
AllowUsers user1
AllowGroups group1
DenyUsers user2
DenyGroups group2
Wish this helps.
regards,
Stanley Huang

Tuesday, October 11, 2011

[Level 2] How to execute super() in Python

If you want to use parent method in Python,
you could use 'super()' method.
But it only support new style class,
therefore, you need to inherit 'object' class when you create your own class.
e.g.
#!/bin/env python
import os, sys 
 
def new_style():
    class NewSystemTools(object):
        def __init__(self):
            pass
        
        def runCmd(self, sCmd):
            return os.popen(sCmd).read()
     
    class MyNewSystemTools(NewSystemTools):
        def __init__(self):
            pass
        
        def runCmd(self, sCmd):
            return super(MyNewSystemTools, self).runCmd(sCmd)

    print '-- new style --' 
    mnst = MyNewSystemTools()
    print mnst.runCmd('ls /')
 
def old_style(): 
    class SystemTools:
        def __init__(self):
            pass
    
        def runCmd(self, sCmd):
            return os.popen(sCmd).read()
    
    class MySystemTools(SystemTools):
        def __init__(self):
            pass
    
        def runCmd(self, sCmd):
            return super(MySystemTools, self).runCmd(sCmd)
    
    print '-- old style --'
    mst = MySystemTools()
    print mst.runCmd('ls /')
 
new_style()
old_style()


# /tmp/t.py 
-- new style --
bin
boot
cdrom
data
dev
etc
filedb
...
-- old style --
Traceback (most recent call last):
  File "/tmp/t.py", line 17, in 
    print mst.runCmd('ls /')
  File "/tmp/t.py", line 14, in runCmd
    return super(MySystemTools, self).runCmd(sCmd)
TypeError: super() argument 1 must be type, not classobj
Wish this helps. regards, Stanley Huang

Saturday, October 8, 2011

[ Level 2] How to dump object to file in Python

#!/bin/env python    
import os, sys 

import marshal
a = [1,2,3]
fd = open('/tmp/t.log', 'wb')
marshal.dump(a, fd) 
fd.close()

fd = open('/tmp/t.log', 'rb')
b = marshal.load(fd)
for i in b:
    print i
fd.close()
Wish this helps.
regards,
Stanley Huang

[Level 2] Vim autocomplete for python.

If you want to use vim to writing python script.
You could download vim autocomplete for python from here
And then, you could put pythoncomplete.vim in ~/.vim/autoload/
When you writing python, you could use ctrl+p to autocomplete python syntax.

Wish this helps.
regards,
Stanley Huang

[Level 1] Useful vim environment settings.

My current vim settings are below.
You could get more sample in here.

set nu
set ic
:au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
set nosmartindent
set tabstop=4
set shiftwidth=4
set expandtab
set hlsearch
syntax on

" filetype indent plugin on
set background=dark
set modeline

" filetype indent on
" au FileType python setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4
" au FileType python setlocal ts=8 et sw=4 sts=4
set nobackup
set noswapfile
set showmode
set ruler
map j gj
map k gk<

" auto trim tailing spaces
autocmd BufWritePre *.py :%s/\s\+$//e

" folding
set foldenable 
set foldmethod=syntax 
set foldcolumn=0 
nnoremap @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')

" auto command
autocmd BufRead *.py nmap  :w !python %
autocmd FileType java map  :!javac "%:p" && java -cp "%:p:h" "%:t:r"
autocmd FileType c map  :!gcc --o "%:p:r.out "%:p" && "%:p:r.out"
autocmd FileType php noremap  :w!:!/usr/bin/php %
autocmd BufRead *.py nmap  :w !sh %

Wish this helps. regards, Stanley Huang

Wednesday, October 5, 2011

[Level 1] Encoding in Python script.

If there are some wording not for ascii, you should add # -*- coding: (encoding) -*-
to prevent compile error.
example error message:
File "./testEncoding.py", line 21
SyntaxError: Non-ASCII character '\xe6' in file ./testForLoop_2.6.py on line 21, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
e.g.
#!/usr/bin/python2.6
# -*- coding: utf8 -*-

### chinese testing
slang="有嘴說別人無嘴說自己"
sword="嘴"

## error with encoding
#for i in slang:
#  print i

# use python shell to display encoding
# ex.
# >>> "有嘴說別人無嘴說自己"
# '\xe6\x9c\x89\xe5\x98\xb4\xe8\xaa\xaa\xe5\x88\xa5\xe4\xba\xba\xef\xbc\x8c\xe7\x84\xa1\xe5\x98\xb4\xe8\xaa\xaa\xe8\x87\xaa\xe5\xb7\xb1\xe3\x80\x82'
# >>> "嘴"
# '\xe5\x98\xb4'

l=len(sword)
h=0
k=0
count=0
for item in slang:
  k=0
  f=1
  while k<l:
    if slang[h+k]==sword[k]:
      k+=1
      continue
    else:
      f=0
      break
  if f==1:
    count+=1
  h+=1
  if h>=(len(slang)-l):
    break
print count
$ ./testEncoding.py 
2
$
Wish this helps.
regards,
Stanley Huang

Tuesday, October 4, 2011

[Level 1] Install telnetd in Ubuntu 10.04

Install telnetd in Ubuntu 10.04:
# sudo su
# apt-get install openbsd-inetd
# echo "telnet stream tcp nowait root /usr/sbin/tcpd /usr/sbin/in.telnetd" >> /etc/inetd.conf
# /etc/init.d/openbsd-inetd restart
Wish this helps.
regards,
Stanley Huang