Posts

Showing posts with the label Level 2

[ Level 2 ] Test Singleton Implementation in Python.

Days ago, just search how to use implement "Singleton" design pattern. ( http://stackoverflow.com/questions/6760685/crea(ing-a-singleton-in-python ) And today, I just need to implement for it. In my case, I need to create mutliple loggers and I also want to use "Singleton" to reduce system resource usage. Therefore, I create a Singleton meta class and also use a parameter called "singleton_id" to define the instance category. Source Code: #!/bin/env python class Singleton(object): _singleton_key = 'singleton_id' _instance = {} def __new__(class_, *args, **kwargs): if class_._singleton_key not in kwargs.keys(): kwargs[class_._singleton_key] = '' if class_._singleton_key in kwargs and kwargs[class_._singleton_key] not in class_._instance.keys(): class_._instance[kwargs[class_._singleton_key]] = object.__new__(class_) return class_._instance[kwargs[class_._singleton_key]] class my...

[Level 2] pstree implementation with Python.

Because I couldn't find pstree command in our company's product. Therefore, I just search from internet and found someone implement pstree layout with Python. (http://stackoverflow.com/questions/16395207/create-a-process-tree-like-pstree-command-with-python-in-linux) And I just modify it and create a pstree.py system utility. #!/bin/env python ''' ## Implement pstree in Python ## data structure of tree, cmd_list tree = { 0: [1], 1: [2, 3], 2: [5, 6, 7, 8], ... } cmd_list = { 0: '/sbin/init', 1: '[kthreadd]', ... } ''' import os import sys import re tree = {} cmd_list = {} def printTree(parent, tree, cmd_list, indent=''): print '%s:%s' % (parent, cmd_list[parent]) if parent not in tree: return for child in tree[parent][:-1]: sys.stdout.write(indent + '|-') printTree(child, tree, cmd_list, indent + '| ') child = tree[parent][-1] sys.stdout.write(indent + '`-') ...

[ Level 2 ] Create an egg for Python in Ubuntu.

How to create an egg file for Python. First of all, you must have setuptools module. $ sudo apt-get -y install python-setuptools Now, you could try to create an empty egg now. $ mkdir /tmp/demo $ cd /tmp/demo $ cat &ht; ./setup.py <<EOF #!/bin/env python #-*- coding:utf-8 -*- from setuptools import setup setup() EOF $ python setup.py bdist_egg ## bdist_egg is the option for creating egg. $ ls -ALb build dist setup.py UNKNOWN.egg-info You could find, we have three more directories after you execute setup.py build -> dist -> final egg file UNKNOW.egg-info -> egg info Now, we could give setuptools more information about egg. cat > ./setup.py <<EOF #!/bin/env python #-*- coding:utf-8 -*- from setuptools import setup, find_packages setup( name = "my_first_egg", version="0.0.1", packages = find_packages(), zip_safe = False, description = "my first egg.", long_descriptio...

[ Level 2 ] Fix duplicate vg/lv name.

1. scan vgs: $ vgscan 2. get vg information: $ vgdisplay --- Volume group --- VG Name vg00 ... VG UUID FUoK9F-9mgs-jO4M-vub1-Y7zs-6wpQ-uM2S11 --- Volume group --- VG Name vg00 ... VG UUID FUoK9F-9mgs-jO4M-vub1-Y7zs-6wpQ-uM2S12 3. export vg $ vgexport 4. rename vg name $ vgrename FUoK9F-9mgs-jO4M-vub1-Y7zs-6wpQ-uM2S12 vg01 5. import vg $ vgimport vg01 6. get vg information: $ vgdisplay --- Volume group --- VG Name vg00 ... VG UUID FUoK9F-9mgs-jO4M-vub1-Y7zs-6wpQ-uM2S11 --- Volume group --- VG Name vg01 ... VG UUID FUoK9F-9mgs-jO4M-vub1-Y7zs-6wpQ-uM2S12 7. get lv information $ lvscan ACTIVE '/dev/vg00/lv00' [13.99 GiB] inherit inactive '/dev/vg01/lv00' [13.99 GiB] inherit 8. active vg01 $ vgchange --ignorelockingfailure --noudevsync --sysinit -ay vg01 >/dev/null 2>&1 && 9. rename lv name(optio...

[ Level 2 ] Get last argument in bash.

You could use the following methods to get the last argument that you pass to script. #!/bin/bash getLastArg1() { for last do true done echo $last } getLastArg2() { echo $@ | awk '{print($NF)}' } getLastArg3() { eval echo `echo \\$${#@}` } getLastArg1 $@ getLastArg2 $@ getLastArg3 $@ $ ./test.sh a b c c c c $ Wish this helps. regards, Stanley Huang

[ Level 2 ] Tips of unittest for Python.

There are tips for Python: 1. Use mock for replace method. ex. myMock=mox.Mox() myMock.StubOutWithMock(myModule, 'replaceMethod') myModule.replaceMethod(input).AndReturn('Hello World!') myMock.ReplayAll() expected = 'Hello World!' self.assertEqual(module.replaceMethod(input), expected) myMock.VerifyAll() #verify if all mocks be executed. myMock.UnsetStubs() #release all mocks 2. Use -m to test one method only. ex. $ python -m unittest myApp.TestClass.testMethod Wish this helps. regards, Stanley Huang

[ Level 2 ] Coverage in Python.

$ sudo pip install coverage $ coverage run myApp.py arg1 arg2... $ coverage report -m $ coverage html $ coverage help (run) ## or coverage run --help Commands of coverage: run – Run a Python program and collect execution data. report – Report coverage results. html – Produce annotated HTML listings with coverage results. xml – Produce an XML report with coverage results. annotate – Annotate source files with coverage results. erase – Erase previously collected coverage data. combine – Combine together a number of data files. debug – Get diagnostic information. Ref: http://nedbatchelder.com/code/coverage/ http://nedbatchelder.com/code/coverage/cmd.html#cmd Wish this helps. regards, Stanley Huang

[ Level 2 ] Ubuntu package install script.

I wrote an easy script for install Ubuntu packages. #!/bin/bash # # This script is for install popular packages # #$: check package, if exists, skip the following prefix #^ #@: apt-get install packages #!: unix command #^@: apt-get install packages, depends on previous #$ #^!: unix command, depends on previous #$ # showUsage() { cat <<EOF Usage: $0 $0 [package name] Ex. $0 $0 rdesktop EOF } isPackageNotInstall() { dpkg -l $1 >/dev/null 2>&1 if [ $? -eq 0 ] then echo "Package '$1' exists, skip it!" return 1 else return 0 fi } getContent() { declare -i begin declare -i end declare -i size begin=$1 end=$2 size=$end-$begin+1 tail -n +$begin $0 | head -$size } getPackageName() { echo $1 | cut -d' ' -f2- | cut -d'#' -f1 } getCommand() { echo "$line" | cut -d' ' -f2- | cut -d'#' -f1 } die() { echo $1 exit 1 } aptGetInstall() { echo -n "Start instal...

[ Level 2 ] Recovery disk partition utility in for Ubuntu.

There is a tool for Ubuntu could help you to recover disk partition, called "testdisk'. $ sudo apt-get -y install testdisk $ sudo testdisk and choose: Create -> [select disk] -> Intel -> Analyse -> Quick Search -> Write And done~ Wish this helps. regards, Stanley Huang

[ Level 2 ] Enable USB 3.0 in Ubuntu 12.04

After I upgrade 12.04, the USB 3.0 port seems not work. Then I google the solution: add "blacklist uas" in the file /etc/modprobe.d/blacklist.conf Wish this helps. regards, Stanley Huang

[Level 2] Allow remote display in Ubuntu 12.04/10.04

If you want to allow remote display in Ubuntu 12.04, you have do the following steps: 1. remove "-nolisten tcp" from /etc/X11/xinit/xserverrc #[before] $ cat /etc/X11/xinit/xserverrc exec /usr/bin/X -nolisten tcp "$@" #[after] $ cat /etc/X11/xinit/xserverrc exec /usr/bin/X "$@" 2. add "xserver-allow-tcp=true" into /etc/lightdm/lightdm.conf #[before] [SeatDefaults] user-session=ubuntu greeter-session=unity-greeter #[after] [SeatDefaults] user-session=ubuntu greeter-session=unity-greeter xserver-allow-tcp=true 3. restart X 4. allow remote x connection local> xhost + 5. ssh remote server and set DISPLAY local> ssh remote_server remote> export DISPLAY=local_ip:0.0 remote> xclock in 10.04, you have to change above step 2 as the following: 2-10.04: add "DisallowTCP=false" in "security" section. #[before] $ cat /etc/gdm/custom.conf [daemon] TimedLoginEnable=false AutomaticLoginEnable=true TimedLogin=stanley Aut...

[ Level 2 ] Allow VirtualBox guest OS to create symbolic link file in host shared folder.

Allow VirtualBox guest OS to create symbolic link file in host shared folder: $ VBoxManage setextradata "VM Name" VBoxInternal2/SharedFoldersEnableSymlinksCreate[absolution path for shared folder] 1 $ VBoxManage setextradata "VM Name" VBoxInternal2/SharedFoldersEnableSymlinksCreate/[shared name] 1 Ex. $ VBoxManage setextradata "MyVM" VBoxInternal2/SharedFoldersEnableSymlinksCreate/home/stanley/shared_folder 1 $ VBoxManage setextradata "MyVM" VBoxInternal2/SharedFoldersEnableSymlinksCreate/shared_name 1 And you could verify it by command: VBoxManage getextradata "MyVM" enumerate After setup, you have to shutdown VM (not restart) and boot up it again. Wish this helps. regards, Stanley Huang

[ Level 2 ] Python with vim

Python with vim: http://wiki.python.org/moin/Vim Wish this helps. regards, Stanley Huang

[ Level 2 ] Connect pool for ssh.

If you want to use the concept "connection pool" for ssh, you could try the following sample. #!/bin/bash # # You might need to modify sshd_config with the following attributes: # # MaxStartup 200 # MaxSessions 200 # [ "$1" == "-d" ] && set -vx && shift control_master="$1" && [ "$control_master" != "false" ] && control_master=true username="$2" && [ -z $username ] && username=stanley remote_host="$3" && [ -z $remote_host ] && remote_host=127.0.0.1 cmd1="$4"&& [ -z $cmd1 ] && cmd1=ls control_master_option="" client_cmd="/tmp/a.sh" buildControlMaster() { if $control_master then ssh -N -o "ControlMaster auto" -o "ControlPath ~/.ssh/master-$username@$remote_host" $username@$remote_host & fi } createClientCmd() { mkdir -p /tmp/add rm /tmp/add/* $client_cmd if $c...

[ Level 2 ] How to edit/display mulit-files in one terminal.

You could use serval ways to do that. 1. :tabe => tab edit. You use tabn/tabN/tabn[#] to change tab 2. :vs => virtical split. Back to command mode (press ESC key) then you use ctrl-w to change window 3. :sp => horizontal split. Back to command mode (press ESC key) then you use ctrl-w to change window To get more help, use commands: :help :tabe :help :vs :help :sp Wish this helps. regards, Stanley Huang

[Level 2] Implement with syntax in Python.

#!/bin/env python class myOpen(object): def __init__(self, filename, readwrite): self.__filename = filename self.__readwrite = readwrite self.__fd = None def __enter__(self): self.__fd = open(self.__filename, self.__readwrite) return self.__fd def __exit__(self, *args): self.__fd.close() with myOpen('/tmp/my.txt', 'r') as f: print f.readlines() with myOpen('/tmp/hello.txt', 'w') as f: f.write('hello world!\n') $ ./test.py ['-rwxr--r-- 1 stanley stanley 846 2012-12-26 13:07 ./c.py\n', '-rwxr--r-- 1 stanley stanley 486 2013-01-08 17:54 ./test.py\n'] $ cat ./my.txt -rwxr--r-- 1 stanley stanley 846 2012-12-26 13:07 ./c.py -rwxr--r-- 1 stanley stanley 486 2013-01-08 17:54 ./test.py $ cat ./hello.txt hello world! Wish this helps. regards, Stanley Huang

[Level 2] Python abstract method testing

#!/bin/env python import os, sys from abc import * # ================================================= class ToolCmd(object): __metaclass__ = ABCMeta def __init__(self): pass @abstractmethod def doLocalAction(self): pass class DoAction(ToolCmd): def __init__(self): pass def doLocalAction(self): print 'doLocalAction()' # ================================================= class Test1(DoAction, ToolCmd): def __init__(self): pass class Test2(ToolCmd): def __init__(self): pass #class Test3(ToolCmd, DoAction): # def __init__(self): # pass # ================================================= t1 = Test1() t1.doLocalAction() t2 = Test2() t2.doLocalAction() #t3 = Test3() #t3.doLocalAction() # ================================================= Test Run: (Run-time error) $ ./c.py doLocalAction() Traceback (most recent call last): File "./c.py", line 42, in t2 =...

[Level 2] Scan wifi channel in Ubuntu.

#!/bin/bash iwlist wlan0 scanning | grep Channel: | grep -v grep | cut -d: -f2 | sort Wish this helps. regards, Stanley Huang

[ Level 2 ] Color for man page.

I forget where to get this information, just try it. export PAGER="`which less` -s" export BROWSER="$PAGER" export LESS_TERMCAP_mb=$'\E[38;5;167m' export LESS_TERMCAP_md=$'\E[38;5;39m' export LESS_TERMCAP_me=$'\E[38;5;231m' export LESS_TERMCAP_se=$'\E[38;5;231m' export LESS_TERMCAP_so=$'\E[38;5;167m' export LESS_TERMCAP_ue=$'\E[38;5;231m' export LESS_TERMCAP_us=$'\E[38;5;167m' Wish this helps. regards, Stanley Huang

[Level 2] How to get root permission to write file.

If you want to get root permission when you launch vim with normal user. You could try the following command in vim. 1. to write to file. 2. reload the file. :w !sudo tee [file_name] :e! Wish this helps. regards, Stanley Huang