2015년 7월 2일 목요일

join every 2 lines in a file

http://www.theunixschool.com/2012/03/join-every-2-lines-in-file.html


훌륭하다 훌륭해.
$ paste - - -d, < file
$ paste -s -d",\n" file
$ sed 'N;s/\n/,/' file
$ perl -pne 'if($.%2){s/\n/,/;}' file
$ xargs -L 2 < file | awk '$1=$1' OFS=,
$ awk 'NR%2{printf "%s,",$0;next}{print;}' file

2015년 6월 30일 화요일

다른 리소스를 필요로 하는 프로그램

 어떤 프로그램은 다른 리소스를 필요로 한다. 예를 들어 face detector는 model file이 필요하다(물론 그렇지 않은 detector도 있다). 얼굴에 대한 정보를 가지고 있는 model file이 있어야 target image에서 얼굴을 잡아낼 수 있다. OpenCV가 제공하는 face detector의 경우 xml파일이 이에 해당한다.
 팀 내에서 프로젝트를 하는데 이 model파일을 찾아내서 사용하는 프로그램을 넘겨받았다. 환경변수를 다 뒤져서 그 경로마다 해당 파일이 있는지 확인하고 있으면 사용한다. 이런 짓은 이식성에 도움을 주기는 커녕 사용하는 사람들을 혼란에 빠트릴 뿐이다. 프로그램이 현재 실행되는 디렉토리에서 찾아보든지 아니면 실행시 argument로 file을 명시적으로 지정하게 해야 한다. 그 외에는 에러를 주고 멈추면 되는 것이다.
 쓸데없는 노력으로 자신의 자부심나무에만 열심히 물을 주고 주변 모든 사람들을 괴롭게 만드는 사람들이 어디에나 있다.


 Some program needs other resources to run. For example, OpenCV's face detector needs an xml file which includes model data about face. It finds faces using this model.
 If one writes a program like this, there is no need to make the program find everywhere possible to find that xml file. Just find 'current' directory or get an argument that specifies the xml path. If it can not find an xml file, just stop to run with a generous error. My co-worker writes a program that finds everywhere possible using environment variables. If it runs well that way, it is more harmful more than not running. If the program stops or runs problematic way with the xml file problem, a user would not know where is errornous.

2015년 5월 21일 목요일

grep: count total number of occurrences

원출처는 http://unix.stackexchange.com/questions/6979/grep-count-total-number-of-occurrences


파일안에 특정 스트링이 총 몇번 나오는지 세려고 -c옵션을 쓰면, 해당 스트링을 포함하는 라인수만 나온다. 예를 들어 라인은 하나인데(\n이 딱 하나 들어있는데) 스트링은 수천만자에 달하는 긴 스트링에 대해 grep -c string 하면 1만 나온다는 뜻.

-o 옵션과 wc 명령을 섞어 쓴다.
grep -o string filename | wc -l

-o
--only-matching
Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line. 

2015년 4월 14일 화요일

‘도은이 아빠’네

확실하지는 않지만 아마
‘도은이 아빠’라고 불리는 분의 블로그인것 같다.
http://doeun.blogspot.kr
요즘도 조판에 열심이신가보다.
한국에서 \(\LaTeX\)을 접하는 사람이라면 누구나 한번쯤 접해보았을 그 이름.

 작정하고 파고들 기회도 없었지만, 계속 다루다보면 어느정도 감이 생길법도 한데 아직도 어떤 원리나 구조로 \(\TeX\)이 동작하는지, 한글을 가능하게 한 노고는 어디에서 비롯된 것인지 대강도 이해하지 못한다. 아마 앞으로도 그럴 것 같다. 그래서 한번 만나뵌적도 없지만 존경하게 되는 것 같다. 교수님이시라는 얘기도 있던데. 검색해봐도 KTUG의 무수한 질문과 답변글 뿐, 흔한 뉴스기사 한토막 안나온다.

2015년 3월 25일 수요일

tiff로 스캔받은것 pdf로 변환

처음부터 pdf로 받으면 되는데 사정상 이리 됨.


150메가정도 되는 multi page tiff file을 pdf로 변환하려고 하는데 적당한 툴을 못찾겠다.
웹에서 무료변환해주는 사이트나 툴이 몇개 있는데 두세개 해보니 모두 메모리 부족.
(총 104페이지로 분량이 많은건 아닌데 full color가 들어있어서 중간에 메모리가 많이 필요한것 같았다. 하나씩 분리한 뒤 보니 가장 큰 페이지가 22M정도.)
acrobat XI pro 로 한번에 import 한 뒤 변환하려 했는데 이것도 에러남.




tiff를 하나씩 split한 다음 다시 pdf로 합하는 방법을 쓰기로 했다.
tiff splitter만 성공했다. 다른것들은 모두 메모리 부족. imagemagick도 받아서 convert를 썼는데 역시 메모리 부족이었다.


이렇게 해서 다 나누고 나니 페이지가 돌아가 있어서 바로 돌리고,
 for i in {3..104}; do  convert page\ \($i\).tif -rotate 270 p$i.tif ; done

이제 acrobat XI에서 모두 import하면 pdf를 얻는다.

pdf에서 한쪽이 다음과 같은 모양이어서,


split.py를 이용해 pdf의 각 페이지를 자른다.
(이게 출처가 기억이 안남..)

(split.py 코드)
import copy
import math
import pyPdf

def split_pages(src, dst):
src_f = file(src, 'r+b')
dst_f = file(dst, 'w+b')

input = pyPdf.PdfFileReader(src_f)
output = pyPdf.PdfFileWriter()

for i in range(input.getNumPages()):
p = input.getPage(i)
q = copy.copy(p)
q.mediaBox = copy.copy(p.mediaBox)

x1, x2 = p.mediaBox.lowerLeft
x3, x4 = p.mediaBox.upperRight

x1, x2 = math.floor(x1), math.floor(x2)
x3, x4 = math.floor(x3), math.floor(x4)
x5, x6 = math.floor(x3/2), math.floor(x4/2)

if x3 > x4:
# horizontal
p.mediaBox.upperRight = (x5, x4)
p.mediaBox.lowerLeft = (x1, x2)

q.mediaBox.upperRight = (x3, x4)
q.mediaBox.lowerLeft = (x5, x2)
else:
# vertical
p.mediaBox.upperRight = (x3, x4)
p.mediaBox.lowerLeft = (x1, x6)

q.mediaBox.upperRight = (x3, x6)
q.mediaBox.lowerLeft = (x1, x2)

output.addPage(p)
output.addPage(q)

output.write(dst_f)
src_f.close()
dst_f.close()


그럼 끝.


2014년 5월 30일 금요일

install VTK at OSX 10.9.3

The goal is setup python environment of VTK.
Main idea was came from the document http://www.it.uu.se/edu/course/homepage/vetvis/ht10/vtk/instructions_vtk_OSX.pdf

ccmake must be installed already. But tk/tcl is not (at least as for me).


  1. Download source code.
    • Use Google to find the URL
    • Move the downloaded folder to target path where you want to install VTK. After compile, you cannot move the folder. If you move that, python would not find the VTK module.
  2. ccmake
    • If your VTK folder is /Users/me/VTK
      > mkdir build
      > cd build
      > ccmake ..
    • An old-fashioned screen appears. Then, hit 'c' until you can see 'g' option.
      Maybe after two hit of 'c', you would see 'g' option.
    • Hit 'g'.
  3. make
    • After ccmake screen disappears,
      > make
    • This takes about 30 minutes for me.
  4. export some environment variables and run
    • > export PYTHONPATH=$PYTHONPATH:/Users/me/VTK/build/bin:/Users/me/VTK/build/Wrapping/Python:/Users/me/VTK/build/lib
    • run python and test some examples.
    • If python complains about import vtk, export some more environment variables.
      eg. LD_LIBRARY_PATH , DYDL_FALLBACK_LIBRARY_PATH
      (for more information, refer the pdf mentioned above.)
  5. A test program

    import vtk

    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # create cube
    cube = vtk.vtkCubeSource()

    # mapper
    cubeMapper = vtk.vtkPolyDataMapper()
    #cubeMapper.SetInput(cube.GetOutput())
    if vtk.VTK_MAJOR_VERSION <= 5:
        cubeMapper.SetInput(cube.GetOutput())
    else:
        cubeMapper.SetInputConnection(cube.GetOutputPort())  

    # actor
    cubeActor = vtk.vtkActor()
    cubeActor.SetMapper(cubeMapper)

    # assign actor to the renderer
    ren.AddActor(cubeActor)

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()

    You can find many more examples by googling.

2014년 3월 18일 화요일

R integer factorization code

# simple but ineffective.

factor =function (x) {
  limit = ceiling(sqrt(x))
  g = x/(1:limit)
  k = x/g[g%%1==0]
  c(k, rev(x/k))
}