2014년 8월 3일 일요일

ipython autoreload

Class 나 file 을 import 한 뒤에 수정한 뒤 다시 import 를 해도 수정된 결과가 적용이 안되는 경우 ipython 에서는 쉽게 해결할 수 있다.
다음과 같이 autoreload 라는 ipython magic 을 사용하면 된다.


In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from foo import some_function

In [4]: some_function()
Out[4]: 42

In [5]: # open foo.py in an editor and change some_function to return 43

In [6]: some_function()
Out[6]: 43

2014년 7월 24일 목요일

Making a tuple by iteration 여러개의 tuple을 하나의 tuple로 만들기

예를 들어 a=(1,2) 과 b=3 을 c=(1,2,3) 으로 바꾸고 싶다면 어떻게 할까?

+ operator for tuple 을 사용하면 된다. 단, tuple+tuple 의 형태가 되어야한다. 따라서
b 대신, (b,) 으로 tuple로 바꾸어서 더해준다.

예를 들어
a=(1,2)
b=3
c=a+(b,) ==> gives (1,2,3)


한편, 이렇게 만든 tuple을 function의 argument로 사용하기 위해서는
tuple unpack 을 해주어야한다.

예를 들어, argument 가 3개인 함수에 tuple을 사용하려면,

tuple=(1,2,3)
func(tuple) ==> gives ERROR
func(*tuple)==> equivalent to func(tuple[0],tuple[1],tuple[2])





2014년 7월 23일 수요일

VMWARE 에서 마우스 위치가 일치하지 않는 문제

어느 순간부터 VMWARE PLAYER 의 host 와 guest 사이에
마우스 포인터가 일치하지 않는 문제가 생겼다.

guest에 click을 했을때 mouse 의 시작 위치가 host 에서 클릭한 위치와 다르게 되어서
매번 다시 클릭을 해야하는 것이다.

이것은 아래와 같은 내용을 vmx file에 추가하는 것으로 해결되었다.

mouse.vusb.enable = "TRUE"
mouse.vusb.useBasicMouse = "FALSE"
usb.generic.allowHID = "TRUE"



2014년 7월 22일 화요일

black screen after login screen 로긴 화면 다음에 검은 화면이 나오는 문제

display problem after update/upgrade ubuntu

우분투를 사용하면서 무심코 업데이트를 시켰는데,
리부팅후 로그인 후 갑자기 화면이 검게 변하면서 아무런 반응을 보이지 않는 현상이 생겼다.
인터넷을 찾아보니 다음과 같은 방법으로 해결할 수 있었다. 하지만, 여전히 문제가 완전히 해결된 것인지는 확실하지 않다.

증상: 로그인 화면까지는 정상적으로 나타난다. 하지만, 로그인을 하고 나면 black screen으로 변한다.
2014/12/11: Nvidia driver 를 update 한 뒤 비슷한 문제가 다시 생겼다.

해결책: 확실하지는 않지만, 일단 다음과 같은 방법으로 로그인후 정상적인 화면이 나타나도록 되었다.

(1) 로그인 화면에서 CTRL+ALT+F1 을 누른다. 그러면 terminal과 비슷한 text 화면이 나타난다. (Emergency text/command terminal)
(2) 로그인 후, 다음 명령으로 xserver-xorg를 제거한다.

    sudo apt-get remove --purge xserver-xorg

2014/12/11: Nvidia driver 를 제거했다. 
    sudo apt-get remove --purge nvidia-*

(3) CTRL+ALT+DEL 을 눌러 리부팅한다.
(4) 리부팅 후 다시 CTRL+ALT+F1으로 prompt 상태로 바꾸어 로그인한다. (원래 설명에서는 UBUNTU logo 와 그 밑의 다섯개 점이 움직이는 동안에 해야만 하고, 로그인 스크린이 나오기 전에 해야만 한다고 하는데, 나의 경우에는 상관이 없었다.
(5) 로그인후 다음 명령으로 xserver-xorg를 다시 install 한다.

sudo apt-get install xserver-xorg

(6) xorg 설정을 다시 한다.

sudo dpkg-reconfigure xserver-xorg

(7) 리부팅 후 로그인하면, 문제가 해결되었다. (원래 설명에서는 startx 를 사용하여 GUI 로 바꾸라고 되어 있는데, 상관 없는 듯 하다.)


2014년 7월 9일 수요일

Python: 길이를 모르는 리스트에 format 사용하기.


python format string을 길이를 정하지 않은 일반적인 리스트에 적용해야 할 경우 다음과 같은 방법을 사용한다.

Using string format for unknown length of argument, tuple, list

예를 들어 함수에 임의의 argument를 받은 다음, argument를 정해진 format에 따라 출력하고 싶다고
하자.

먼저, 함수에 arbitrary number of argument를 사용하려면 * 를 사용한다.
>>> def StartDance(*args):
        return "%d, %d, %d, %d!" % tuple(args)

>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
하지만, 위의 경우 argument의 갯수가 4개의 경우만 format이 정해져 있기 때문에 다른 수의 argument를 넣으면 (예를 들어 (1,2) 나 (1,2,3,4,5) ) Error 가 발생한다.  
이럴 때, string multiplication 과 join 을 이용할 수 있다.
>>> def StartDance(*args):
        return (", ".join(["%d"] * len(args))+"!") % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
>>> StartDance(5, 6, 7, 8, 9, 10)
'5, 6, 7, 8, 9, 10!'
>>> StartDance(1)
'1!'

여기서, 
(1) ["%d"]*5 는 ['%d', '%d', '%d', '%d', '%d'] 과 같다.
(2) ", ".join(['%d', '%d', '%d', '%d', '%d'] ) 는  '%d, %d, %d, %d, %d' 와 같다.
S.join(iterable) -> string                                                                                                                            
Return a string which is the concatenation of the strings in the                                                                
iterable.  The separator between elements is S.                                                                                      
(3) +"!" 는 string의 마지막에 ! 를 붙여준다.
(4) tuple(args)는 주어진 args를 tuple (1,2,3,4) 로 바꾸어 준다.


아래 방법은 일일이 ['1,','2,','3,'..] 으로 list를 먼저 만든 다음에 하나의 string으로 만드는 것이고
print ' '.join(['%-2s' % (i,) for i in lst])
아래는 fotmat을 먼저 '%s %s %s ...'  식으로 만들어서 print 하는 것이다.
print ('%-2s ' * len(l))[:-1] % tuple(lst)
일반적으로 string multiplication을 이용하는 것이 효율적이다.


2014년 7월 6일 일요일

Linux 에서 Path 지정하기 (Original page http://www.cyberciti.biz/faq/unix-linux-adding-path/)

UNIX / Linux: Set your PATH Variable Using set or export Command


Finding out your current path

 
echo "$PATH"
 
OR
 
printf "%s\n" "$PATH"
 
How do I modify my path?
Bash, Sh, Ksh shell syntax to modify $PATH
If you are using bash, sh, or ksh, at the shell prompt, type:
## please note 'PATH' is CASE sensitivity and must be in UPPERCASE ##
export PATH=$PATH:/path/to/dir1
export PATH=$PATH:/path/to/dir1:/path/to/dir2
 
OR
## please note 'PATH' is CASE sensitivity and must be in UPPERCASE ##
PATH=$PATH:/path/to/dir1; export PATH
 
Tcsh or csh shell syntax to modify $PATH
If you are using tcsh or csh, shell enter:
 ## please note 'path' is case sensitivity and must be in lowercase ##
set path = ($path /path/to/dir1)
set path = ($path /path/to/dir1 /path/to/dir2)
 
OR
## please note 'PATH' is CASE sensitivity and must be in UPPERCASE ##
setenv PATH $PATH:/path/to/dir1
setenv PATH $PATH:/path/to/dir1:/path/to/dir2
 
To make these changes permanent, add the commands described above to the end of your~/.profile file for sh and ksh shell, or ~/.bash_profile file for bash shell:
## BASH SHELL ##
echo 'export PATH=$PATH:/usr/local/bin'  >> ~/.bash_profile
 
KSH/sh shell user try:
## KSH / SH SHELL ##
echo 'export PATH=$PATH:/usr/local/bin'  >> ~/.profile
 
In this final example add /usr/local/bin/ and /scripts/admin/ to your path under csh / tcsh shell, enter:
 
set path = ($path /usr/local/bin /scripts/admin)
 
OR
 
setenv PATH $PATH:/usr/local/bin:/scripts/admin
 
To make these changes permanent, add the commands described above to the end of your~/.cshrc file:
 
echo 'set path = ($path /usr/local/bin /scripts/admin)'  >> ~/.cshrc
 
OR
 
echo 'setenv PATH $PATH:/usr/local/bin:/scripts/admin'  >> ~/.cshrc
 
To verify new path settings, enter:
$ echo $PATH

2014년 6월 12일 목요일

Linux Library 사용하기

Linux 에서 사용하는 library는 크게 두가지로 나뉜다.


  • Static library
  • Shared library(or Dynamical library)


Ubuntu software center 에서 library 를 찾아보면 static 인 경우도 있고 shared 인 경우도 있다. 초보자의 입장에서는 별로 상관이 없고, 사용법만 알 면 될 것 같은데,
문제는 경우에 따라 다운 받은 library를 사용하는 데 compiler 가 library를 못찾는 경우가 있다.

저장되는 library는 3가지 중에 하나의 이름을 가진다.

  • linker 가 사용하는 이름: 'lib' 로 시작하고 '.a' 나 '.so' 로 끝나는 이름. '.a' 는 static library 인 경우이고 '.so'는 shared object library인 경우이다. (예: libpthread.so) 이것은 Dynamic library 라고 불린다. 
  • Fully qualified name or soname: linker 가 사용하는 이름과 같지만, 마지막에 버전 넘버가 붙는다. (예: libpthread.so.1) 
  • Real name : 버전 넘버 뒤에 마이너 버전 넘버가 붙는 경우.(예: libpthread.so.1.1 )


library를 다운 받으면 보통 다음 3개 directory 중 하나에 저장된다고 한다.

  • /lib   : 처음 linux start up 에서 사용되거나 root file system이 사용하는 library들이 위치한다.
  • /usr/lib : 대부분의 user 가 사용하거나 system 이 internally 사용하는 library들이 위치한다. 
  • /usr/local/lib : standard libary가 아닌 대부분의 library가 위치한다.

이러한 표준 directory에 저장된 경우 특별한 위치 지정이 없어도 library를 컴파일러가 알아서 찾지만, 그 이외의 특별한 위치에 저장되면 그 위치를 알려 주어야만 library를 사용할 수 있다.  

보통 지정해 주어야하는 directory는 linker 가 사용하는 이름인 *.a 나 *.so 가 있는 곳이다.

gcc -L/usr/lib -llapack -lmathlib

gcc 에서 -L 은 디렉토리 위치를 추가하기 위한 것이고, -l 은 library를 불러오기 위한 것이다.
여기서 -l 뒤에 library의 이름을 붙이는데 library 이름 중 lib 는 뺀다. (예를 들어 원래 library 이름이 liblapack.a 일 때 lapack 만 사용한다.)