'Programming'에 해당되는 글 17건

  1. 2010.06.07 linux install tip
  2. 2010.03.05 Network programming with the Twisted framework, Part 1
  3. 2009.10.17 BeautifullSoup을 사용한 html 파서
  4. 2009.09.15 8 point 알고리즘
  5. 2009.08.18 FLEX 관련
  6. 2009.05.31 tar & gz & bz2 사용법
  7. 2009.05.29 mysql index
  8. 2009.05.02 AutoAlbum


   ./configure --help
   ./configure --help | grep client
   ./configure --without-server
   ./configure --prefix=/daum/program/mysql
   ./make; make install
   ./python setup.py install

   아파치
   ./configure --prefix=/daum/program/apache
   make; make install

   mysql
   ./configure --prefix=/daum/program/mysql --without-server
   make; make install

   vi .bash_profile
   export LD_LIBRARY_PATH=/usr/local/apache2/lib:/daum/program/mysql/lib/mysql
   ./source .bash_profile

   zope
   su
   python setup.py install

   setuptools
   su
   python setup.py install

   MySQL-python
   su
   site.cfg mysql-config = /usr/local/bin/mysql_config => /daum/program/mysql/bin/mysql_config
   python setup.py install
   
   twisted
   su
   python setup.py install
 

  • mysql++ 설치: http://sourceforge.net/projects/mysqlcppapi/files/
  • ffmpeg + opencv 설치
  • opencv 2.0 install
  • 시도 1

       uname -a
    
       Linux spb-cv-web03 2.6.9-55.ELsmp #1 SMP Fri Apr 20 17:03:35 EDT 2007 i686 athlon i386 GNU/Linux
    
       Red Hat EL 4 - i386 (우리 회사는 현재 이렇게 설치하고 있음.)
    
       소스 컴파일 하지 말고 그냥 받자...
       http://dag.wieers.com/rpm/packages/ffmpeg/
    
       ffmpeg-libpostproc-0.4.9-0.9.20070530.el4.rf.i386.rpm Fri 11 Jan 2008 37 kB Red Hat EL 4 - i386
    
       wget으로 다운 받음.
       rpm -Uvh --nodeps ffmpeg-libpostproc-0.4.9-0.9.20070530.el4.rf.i386.rpm
    
       http://www.rpmfind.net/linux/rpm2html/search.php?query=libgsm.so.1
       http://www.rpmfind.net/linux/rpm2html/search.php?query=libmp3lame
    
       history | grep cmake
       cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/daum/program/opencv -D BUILD_PYTHON_SUPPORT=ON ..
       
     

  • gcc 설치

    ./configure --prefix=/daum/program/gcc4.4.2 --enable-shared --enable-languages=c --enable-thread=posix --disable-nls --without-headers --with-newlib
    
    Libraries have been installed in:
       /daum/program/gmp-4.3.1/lib
    
    Libraries have been installed in:
       /daum/program/mpfr-2.4.1/lib
    
    =======================================================================================
    
    cd /usr/src
    tar zxf gcc-4.3.0.tar.gz
    tar zxf mpfr-2.3.1.tar.gz
    tar zxf gmp-4.2.2.tar.gz
    cd gcc-4.3.0
    ln -s ../mpfr-2.3.1 ./mpfr
    ln -s ../gmp-4.2.2 ./gmp
    cd ..
    
    # the following as per cross compiler article
    mkdir build-gcc
    cd build-gcc
    export PATH=$PATH:$PREFIX/bin
    ../gcc-4.3.0/configure --target=$TARGET --prefix=$PREFIX --disable-nls --enable-languages=c,c++ --without-headers --with-newlib
    make all-gcc
    make install-gcc
    
    ../gcc-4.4.2/configure --prefix=/daum/program/gcc4.4.2 --enable-shared --enable-languages=c,c++ --enable-thread=posix --disable-nls --without-headers --with-newlib
    
    
     
  • rpm 사용법


       RPM은 레드햇 계열의 리눅스에서 패키지(프로그램?)를 설치하고 삭제하는 등의 작업을 하는 프로그램이다. 여기서는 알짜리눅스 5.2 바이블 책에 나온 RPM 사용법을 실질 사용 예를 위주로 정리한다.
    
      * 가장 많이 사용하는 - 설치하기 옵션!
       : rpm -Uvh 패키지파일이름 : 업그레이드(기존의 것을 삭제하고 설치)하며 그 과정을 자세히 보여준다.
      * 가장 많이 사용하는 - 삭제하기 옵션!
       : rpm -e 패키지이름 : 설치된 패키지의 삭제. 버전번호등을 제외하고 패키지의 이름만 적어준다.
      * 일반 패키지 설치
       : rpm -i 패키지파일이름 : 설치한다. (기존의 것 삭제 안함)
      * 업그레이드
       : rpm -U 패키지파일이름 : 업그레이드한다. 업그레이드 과정을 자세히 보여주지 않는다.
      * 설치 거부할 경우 강제 설치하기
       : rpm -Uvh 패키지파일이름 --force : 동일하거나 더 높은 버전의 패키지가 이미 설치되어 있는 경우라도 강제로 기존의 것을 삭제하고 설치한다.
      * 의존성을 무시하고 설치하기
       : rpm -Uvh 패키지파일이름 --nodeps : 의존관계에 있는 다른 패키지가 설치되어 있지 않다해도 강제 설치한다.
      * 의존성과 버전을 무시하고 강제설치하기
       : rpm -Uvh 패키지파일이름 --nodeps --force : 걸림없이 무조건 설치!
      * 의존성 무시하고 삭제하기
       : rpm -e 패키지이름 --nodeps : 이 패키지를 필요로 하는 다른 패키지가 있더라도 무시하고 패키지를 삭제한다.
      * 테스트만 해보기
       : rpm [설치/삭제 등의 옵션들] --test : 실제로 작업을 하지 않고 작업 결과에 대한 테스트만 해볼 때 사용한다.
      * 설치된 모든 패키지 보기
       : rpm -qa : 모든 패키지 리스트 출력
       : rpm -qa | wc -l : 총 설치된 패키지 개수 출력
      * 설치된 패키지의 정보 보기
       : rpm -qi 패키지이름
      * 특정 패키지가 포함하고 있는 파일 목록은?
       : rpm -ql 패키지이름
      * 패키지 파일이 포함하고 있는 파일 목록은?
       : rpm -qlp 패키지파일이름
      * 이 파일은 어느 패키지에 포함된 걸까?
       : rpm -qf 파일이름
      * 패키지 파일에서 패키지 정보 출력
       : rpm -qip 패키지파일이름
      * 패키지 검사하기
       : rpm -V 패키지이름 : 설치된 패키지 검사하기. 설치 후 어떤 파일이 어떻게 바꼈는지 알 수 있다.
      * 의존성에 문제있는 패키지는?
       : rpm -Va --nofiles : 설치된 모든 패키지를 검사하여 의존성에 문제가 있는 것을 찾아낸다. 
     

  • Install ffmpeg on CentOS/RHEL i386 via rpm


    • crontab -e, 

    • doxegen 사용법

          doxygen --help
          doxygen -g ImageDuplicate.doxy
          vi ImageDuplicate.doxy
            PROJECT_NAME           = Duplicated Image Dictionary
            PROJECT_NUMBER         = 1.0
            OUTPUT_DIRECTORY       = /hanmail/service/DuplDic/
            OUTPUT_LANGUAGE        = Korean
            STRIP_FROM_INC_PATH    = /hanmail/service/DuplDic/
            GENERATE_TREEVIEW      = YES
            INPUT                  = DuplSig.cpp DuplUtil.cpp DuplUtil.h
            SOURCE_BROWSER         = YES
            GENERATE_LATEX         = NO
      
          doxygen ImageDuplicate.doxy
       

    • 한글 깨지는 문제

         echo $LANG
         export LANG=euckr.ko_KR
      
         기존 
          # vi /etc/sysconfig/i18n 
          LANG="ko_KR.UTF-8" 
          SYSFONT="lat0-sun16" 
      
       => 수정 
         LANG="ko_KR.eucKR" 
         SUPPORTED="ko_KR.UTF-8:ko_KR:ko" 
         SYSFONT="lat0-sun16" 
      
       

    • DB서버

         mysql 서버: spb-cv-web06 (121.254.251.82) 
         id: color 
         passwd: search 
      
         SQLyog MySQL GUI - Community Edition 
         SQLyong Installers - Windows download
         http://www.webyog.com/en/downloads.php 
      
       

    • rebuilding

         cd /daum/service/index_controller/schedule/IMG_s7_vol
         touch rebuilding.source.0
         알아서 rebuilding이 일어남
       

    • 아파치

         아파치 시작
         $ /daum/program/apache/bin/apachectl start
         아파치 재시작
         apache setting
         $ cd /daum/program/apache/conf
         $ vi httpd.conf
         $ su
         # restart apache
         /daum/program/apache/bin/apachectl restart
         # exit
         실행 권한 설정
         /daum/program/conf/httpd.conf
       

    • glob 사용법

         import glob
         l = glob.glob('*.sh')
         for i in l:
            p = i + '.thumb.jpg'
            print p
       

    • 한꺼번에 kill

          ps -ef | grep ShotCut | grep -v grep | awk '{print $2}' | xargs kill -9
       

    • svn 설치
    • svn 사용법 

       *로그인
       http://source.daumcorp.com/jsr/login.do
      
       *svn에 처음으로 올리기
       svn import . http://source.daumcorp.com/private/Clone_dinaa1/trunk
      
       *svn에서 데이타 full로 받기(check out)
       svn co http://source.daumcorp.com/private/Clone_dinaa1/trunk Clone
      
       *싱크 맞추기
       svn up
      
       *svn에 바뀐 데이타 보내기
       svn ci
      
       *커밋할 때 커맨드라인상에서 주석추가시 (check in)
       svn ci -m "bin/CloneServer.py 주석 변경"
      
       *svn에 올라가 있는 데이터 삭제시
       svn rm http://source.daumcorp.com/private/Clone_dinaa1/trunk/data
      
       *svn에 데이타 추가
       svn add checkColor
       svn add checkSpam
      
       * 현재버전 알아내기
         svn ci 하면 밑에 버전 번호가 나온다. 
         받은 소스의 버젼은   svn status --show-updates
         예)  77
       
       * 이전버전 받기
         svn co -r 77 url_address
       

    • FTP IP 추가


         su 로그인
         cd /etc
         vi hosts.allow
         vpn ip 추가
       

    • 동영상 cp 조정

      [http]CP 데이타 확인

         cd VD3/conf
         vi VD3-schema.conf
         vi VD2_qp_expansion.conf (total, tab 2줄 추가)
         cd VD3/pexpect
         ./CopyFile.py ;./QPRestart.py (배포)
       

    • 동적 링크 추가


         su 로그인
         cd /etc
         vi ld.so.conf한 후 path 추가
         cd /sbin/ldconfig -f /etc/ld.so.conf
       

    • tar Tip


         [압축]
            # tar -cvf 압축파일명.tar 압축파일
             # gzip -f 압축파일명.tar
      
            # tar -cvfz filename.tgz --exclude=file2 --exclude=dir2
            # tar -cvjf bak.tbz2 --exclude==dir2 *
         [풀기]
            # gunzip 파일명.tar.gz
            # tar -xvf 파일명.tar
       

    • 우리 서버에 FTP로 데이타 전송하기 위한 Tip 

      $fpt "자신이 실행한 ftp 서버 IP"
      ftp> help
      ftp> lcd TestImage (옮기고자 하는 폴더로 이동)
      ftp> prompt
      ftp> bin
      ftp> mget *.jpg (현 위치에 파일 받기)
      ftp> mput *.jpg (현 위치에 있는 파일 보내기)
      ftp> bye
       

    • 권한 변경

         chown hanadmin.hanmail daum
         chown hanadmin.hanmail -R *
       

    • awk 사용법 Tip

         awk -F, '{print $2}' file > url.txt
       





    Posted by 한효정

    Summary:  Twisted is an increasingly popular pure-Python framework for programming network services and applications. While there are a large number of loosely coupled modular components within Twisted, a central concept to the framework is the idea of non-blocking asynchronous servers. In this article, David introduces you to this style of programming -- a novel one for developers accustomed to threading or forking servers, but one capable of great efficiency under heavy loads.

    Sorting through the Twisted framework is reminiscent of the old story about blind men and elephants. Twisted has many capabilities, and it takes a bit of a paradigm switch to get a good sense of why they are all there. In fact, as I write this first installment, I am probably only halfway toward getting my mind fully around Twisted. We can work through it together.

    One of the strengths of recent versions of Python is that they come with "batteries included" -- that is, the standard distribution includes modules to do just about everything you want to accomplish in most programming tasks. For the most part, when you want a third-party Python module or package, it is to accomplish some specialized and unusual task. Twisted is one of few exceptions to the pattern described; developed by Twisted Matrix Laboratories, it is a well-designed and general-purpose collection of modules for performing all manner of network programming tasks, in ways not easily facilitated by Python's standard library.

    It is not quite true that Python's standard library lacks support for asynchronous, non-blocking network applications. The module asyncore provides basic support for switching among I/O channels within a single thread. But Twisted takes the style to a higher level and provides a huge collection of pre-built and reusable protocols, interfaces, and components.

    A first server

    The documentation that accompanies Twisted is quite extensive, but hard to get a handle on. Let's start with a simple server, and build on that. In a recent developerWorks tip (see Resources for a link), I demonstrated an XML-based "Weblog server" that presents to a client a stream of records about the latest hits to a Web server. The XML aspect is not important here, but the use of SocketServer and its ThreadingTCPServer class is useful as a baseline. This pre-Twisted server consists of:


    Listing 1. SocketServer-weblog.py
    from SocketServer import BaseRequestHandler, ThreadingTCPServer
    from time import sleep
    import sys, socket
    from webloglib import log_fields, hit_tag

    class WebLogHandler(BaseRequestHandler):
    def handle(self):
    print "Connected from", self.client_address
    self.request.sendall('<hits>')
    try:
    while True:
    for hit in LOG.readlines():
    self.request.sendall(hit_tag % log_fields(hit))
    sleep(5)
    except socket.error:
    self.request.close()
    print "Disconnected from", self.client_address

    if __name__=='__main__':
    global LOG
    LOG = open('access-log')
    LOG.seek(0, 2) # Start at end of current access log
    srv = ThreadingTCPServer(('',8888), WebLogHandler)
    srv.serve_forever()

    Other than that overhead of its per-client thread creation, a notable feature of the SocketServer-based server is its use of a blocking call to time.sleep() within its handler. For Twisted's non-blocking select() loop, such a block is not permissible.

    A first non-blocking approach pushes any artificial delays onto the client, and lets the client specifically request each new batch of Weblog records (and also sends a message to indicate their absence, rather than send nothing). This Twisted server looks like:


    Listing 2. twisted-weblog-1.py
    from twisted.internet import reactor
    from twisted.internet.protocol import Protocol, Factory
    from webloglib import hit_tag, log_fields

    class WebLog(Protocol):
    def connectionMade(self):
    print "Connected from", self.transport.client
    self.transport.write('<hits>')
    def dataReceived(self, data):
    newhits = LOG.readlines()
    if not newhits:
    self.transport.write('<none/>')
    for hit in newhits:
    self.transport.write(hit_tag % log_fields(hit))
    def connectionLost(self, reason):
    print "Disconnected from", self.transport.client

    factory = Factory()
    factory.protocol = WebLog

    if __name__=='__main__':
    global LOG
    LOG = open('access-log')
    LOG.seek(0, 2) # Start at end of current access log
    reactor.listenTCP(8888, factory)
    reactor.run()

    Readers should refer to my prior tip for details on the client application. But the following change should be noted. The main client loop adds two lines:


    Listing 3. Enhanced (blocking) client loop
    while 1:
    xml_data = sock.recv(8192)
    parser.feed(xml_data)
    sleep(5) # Delay before requesting new records
    sock.send('NEW?') # Send signal to indicate readiness


    The parts of a Twisted server

    A Twisted server consists of several modular elements. At a bytestream level, a server implements a protocol, often by inheriting from twisted.internet.protocol.Protocol or from some previously specialized child of it. For example, provided subclasses (in twisted.protocols) include dns, ftp, gnutella, http, nntp, shoutcast, and many others. Basically, a protocol should know how to handle making and losing connections, and receiving and sending data within a connection. These responsibilities are not much different than in a SocketServer-based server, except in being slightly more modular in defining methods for each element.

    The next level of a Twisted server is a factory. In our twisted-weblog-1.py example, the factory really does nothing besides store a protocol. In a more sophisticated server, however, a factory is a good place to perform initialization and finalization related to a protocol server. And probably of greatest interest, a factory can be persisted within applications (we will see those soon).

    Neither a protocol nor a factory knows anything about the network the server runs on. Instead, a reactor is a class that actually listens on a network (utilizing a factory instance for its protocol). Basically, a reactor is just a loop that listens on a given port and network interface (which one is chosen by calling a method like .listenTCP(), .listenSSL(), or .listenUDP()). The thing to understand is that the basic reactor in Twisted, SelectReactor, runs in a single thread; each connection is checked for new data, and the data is delivered to the relevant protocol object. An upshot is that a protocol object is really not allowed to block, or even just take too long to complete (protocols must be programmed appropriately).


    An enhanced server

    Let's try to enhance the Twisted Weblog server so that it follows the pattern of SocketServer-weblog.py in feeding new records to clients without the need for repeated requests from those clients. The problem here is inserting a time.sleep() call into a method of WebLog(Protocol) causes it to block, and so is not allowed. While we are at it, notice that the prior servers probably do the wrong thing in that they feed each new batch of records only to one client. Presumably, if you want to allow multiple clients to monitor a Weblog, you want them all to receive ongoing updates.

    The way you delay actions in Twisted without blocking is to add callbacks to a reactor, using the .callLater() method. A callback added this way is added to the queue of events to service, but it will not actually be processed until after a specified delay. Putting both changes together, an enhanced Weblog server looks like:


    Listing 4. twisted-weblog-1.py
    from twisted.internet import reactor
    from twisted.internet.protocol import Protocol, Factory
    from webloglib import hit_tag, log_fields
    import time

    class WebLog(Protocol):
    def connectionMade(self):
    print "Connected from", self.transport.client
    self.transport.write('<hits>')
    self.ts = time.time()
    self.newHits()
    def newHits(self):
    for hit in self.factory.records:
    if self.ts <= hit[0]:
    self.transport.write(hit_tag % log_fields(hit[1]))
    self.ts = time.time()
    reactor.callLater(5, self.newHits)
    def connectionLost(self, reason):
    print "Disconnected from", self.transport.client

    class WebLogFactory(Factory):
    protocol = WebLog
    def __init__(self, fname):
    self.fname = fname
    self.records = []
    def startFactory(self):
    self.fp = open(self.fname)
    self.fp.seek(0, 2) # Start at end of current access log
    self.updateRecords()
    def updateRecords(self):
    ts = time.time()
    for rec in self.fp.readlines():
    self.records.append((ts, rec))
    self.records = self.records[-100:] # Only keep last 100 hits
    reactor.callLater(1, self.updateRecords)
    def stopFactory(self):
    self.fp.close()

    if __name__=='__main__':
    reactor.listenTCP(8888, WebLogFactory('access-log'))
    reactor.run()

    In this case, we define a custom factory and move some of the initialization from the _main_ block to the factory. Notice also that the clients for this server need not (and should not) sleep or send new requests -- in fact, I use the exact client application I discussed in the XML tip (see Resources).

    The factory and the protocol use the same technique in their custom methods .updatedRecords() and .newHits(), respectively. That is, if a method wants to run periodically, its last line can schedule it to run again at a specified delay. On its face, this pattern looks a lot like recursion -- but it is not (moreover, the repeat scheduling need not occur on the last line; it just makes sense there). The method .newHits(), for example, simply lets the controlling reactor loop know that it wants to be called in another 5 seconds, but the method itself terminates. There is no requirement that a method schedule only itself -- it can schedule whatever it wants to occur, and functions quite apart from factory or protocol methods can be added to a reactor loop, if you wish.


    Persistence and scheduling

    Besides reactor.callLater() scheduling, Twisted contains a general class twisted.internet.defer.Deferred. In essence, deferreds are a generalization of scheduled callbacks, but allow techniques such as chaining dependent callbacks and handling error conditions in these chains. The idea behind a Deferred object is that when you call a method, rather than wait for its results (which may take a while to arrive), the method can immediately return a Deferred object that the reactor/scheduler can call again later, when results are expected to be available.

    I have not really played with Deferred objects yet, but it feels like getting them right will be slightly tricky. If you need to wait on a blocking action -- say, the results from a remote database query -- it is not clear exactly how long you will need to wait for results to be available. Deferred objects do have a timeout mechanism, but I will have to come back to that in a later installment. Interested readers should at least know that the Twisted Matrix developers have attempted to provide a standard API for wrapping blocking actions. Of course, the worst case is to fall back to using threads for blocking actions that really cannot be converted into asynchronous callbacks.

    Another important element to Twisted servers is their easy support for persistence. A reactor is a loop that monitors and responds to I/O events. An application is much like an enhanced reactor that is able to pickle its state for later re-starting. Moreover, applications can be statefully saved into ".tap" files, and can be managed and daemonized using the tool twistd. Here's a simple example that illustrates the usage (modelled on the Twisted documentation's OneTimeKey example). This server delivers distinct Fibonacci numbers to all interested clients, without repeating numbers between them -- even if the server is stopped and started:


    Listing 5. fib_server.py
    from twisted.internet.app import Application
    from twisted.internet.protocol import Protocol, Factory

    class Fibonacci(Protocol):
    "Serve a sequence of Fibonacci numbers to all requesters"
    def dataReceived(self, data):
    self.factory.new = self.factory.a + self.factory.b
    self.transport.write('%d' % self.factory.new)
    self.factory.a = self.factory.b
    self.factory.b = self.factory.new

    def main():
    import fib_server # Use script as namespace
    f = Factory()
    f.protocol = fib_server.Fibonacci
    f.a, f.b = 1, 1
    application = Application("Fibonacci")
    application.listenTCP(8888, f)
    application.save()

    if '__main__' == __name__:
    main()

    You can see that mostly all we have changed is replacing reactor with application throughout. While the class Application also has a .run() method, we use its .save() method to create a Fibonacci.tap file. Running this server is done as:


    Listing 6. Running fib_server.py
    % python fib_server.py
    % twistd -f Fibonacci.tap
    ...let server run, then shut it down...
    % kill `cat twistd.pid`
    ...re-start server where it left off...
    % twistd -f Fibonacci-shutdown.tap
    ...serve numbers where we left off...

    The client that connects to this server should use a time.sleep() in its loop if it only wants a new number intermittently rather than as fast as possible. Obviously, a more useful server can provide a more interesting stateful datastream.

    [출처]
    [1] http://www.ibm.com/developerworks/linux/library/l-twist1.html

    'Programming > Python' 카테고리의 다른 글

    BeautifullSoup을 사용한 html 파서  (0) 2009.10.17
    Posted by 한효정

    import glob
    import os
    import os.path
    import sys
    import urllib
    from BeautifulSoup import BeautifulSoup
    import pickle
    import sgmllib
    from pprint import pprint
    import re
    import MySQLdb

     def InsertMovieData():
            db = MySQLdb.connect(host="121.254.251.82", user="color", passwd="", db="DuplicatedDB", charset='utf8')
            cursor = db.cursor()

            #file_source = open('photo_unique_keys.htm','r')
            #fsoup = BeautifulSoup(file_source)
            for i in range( 2000, 62000, 1000 ):
                    httpurl = 'http://192.168.33.192:3001/photo_unique_keys?index=' + str(i)
                    html_source = urllib.urlopen(httpurl).read()
                    soup = BeautifulSoup(html_source)

                    for tag in soup.findAll('img', width="300"):
                            ntag = str(tag).replace('<img width="300" src="', '').replace('" />', '')
                            #query = "Update MovieData Set ImagePath='" + str(ntag) + "'"
                            query = "Insert Into MovieData(ImagePath) Values('" + str(ntag) + "')"
                            #print query
                            cursor.execute(query)
                            print ntag

            #file_source.closed

            db.close()

     def InsertNewsData(httpurl,group):
            db = MySQLdb.connect(host="121.254.251.82", user="color", passwd="", db="DuplicatedDB", charset='utf8')
            cursor = db.cursor()

            html_source = urllib.urlopen(httpurl).read()
            soup = BeautifulSoup(html_source)

            for tag in soup.findAll('img', width="200"):
                    ntag = str(tag).replace('<img src="', '').replace('" width="200" />', '')
                    #print ntag
                    query = "Insert Into NewsData(ImagePath, newsgroup) Values('" + str(ntag) + "', " + str(group) + ")"
                    #print query
                    cursor.execute(query)

            db.close()


    if __name__ == '__main__':
            #InsertMovieData()
            InsertNewsData(sys.argv[1], sys.argv[2])

    'Programming > Python' 카테고리의 다른 글

    Network programming with the Twisted framework, Part 1  (0) 2010.03.05
    Posted by 한효정

    3 x 3 matrix인 Fundamenta matrix F는 8개의 corresponding point가 주어질 경우, unique하게 결정될 수 있다.
    <!-- MATH ${\tt m}=[x \, y \, 1]^\top,{\tt m'}=[x' y' 1]^\top$ -->
    <!-- MATH ${\bf f}=[F_{11} F_{12} F_{13} F_{21} F_{22} F_{23} F_{31} F_{32} F_{33} ]^\top$ -->
    라고 하자.
    <!-- MATH \begin{equation} {\bf A} {\bf f}= 0 \end{equation} -->
    위 식을 이용하여, 두 점과 f는 아래와 같이 나타낼 수 있다.
    <!-- MATH \begin{equation} \left[ \begin{array}{ccccccccc} x x' & y x' & x' & x y' & y y' & y' & x & y & 1 \end{array} \right] {\bf f} = 0 \end{equation} -->
    위 식을 사용하여 아래의 식을 생성한다.(마지막 항인 1은 생략이 가능하다.)
    사용자 삽입 이미지
    이 때, A는 8개의 corresponding point  pair를 이용하여 만든 matrix이다.
    위 식에 의해, f는 A를 Singular Value Decomposition(SVD)를 통해서 계산될 수 있다.
    A matrix는 SVD에 의해서 USVT로 decompose되고, f는 V matrix의 last column이 된다.

    출처 : http://www.cs.unc.edu/~marc/tutorial/node54.html

    아래는 위의 내용을 OpenCV로 작성해본 코드이다.
    F33은 1이므로, 위 식의 A matrix에서 마지막 column은 제거하였다.

    CvMat* A = cvCreateMat(8, 8, CV_32FC1);
    CvMat* S = cvCreateMat(8, 1, CV_32FC1);
    CvMat* U = cvCreateMat(8, 8, CV_32FC1);
    CvMat* V = cvCreateMat(8, 8, CV_32FC1);

    // assign A matrix
    float* pA = A->data.fl;

    // point assign code here
    // pA[i * 8 + j] = x;

    cvSVD(A, S, U, V);

    // f is a vector containing the elements of fundamenta matrix F
    // float* pV = V->data.fl;
    // pV[i * 8 + 7] ...


    cvReleaseMat(&U);
    cvReleaseMat(&S);
    cvReleaseMat(&V);
    cvReleaseMat(&A);

    'Programming > Computer Vision' 카테고리의 다른 글

    AutoAlbum  (0) 2009.05.02
    Computer Vision at MSR Cambridge  (0) 2009.05.02
    Posted by 한효정

    2009. 8. 18. 11:30 Programming

    FLEX 관련


    사진 객체 편집 툴로 무엇이 좋을까 고민하다 flex로 하기로 .

    FlashDevelop을 이용한 플래시 개발 환경
    http://chumbal.tistory.com/20

    Flex2/AS3 개발환경 구축하기
    http://mygony.com/archives/1098

    'Programming' 카테고리의 다른 글

    mysql index  (0) 2009.05.29
    Posted by 한효정

    압축
    $ tar cvfz XXX.tar.gz XXX

    풀기
    $ tar xvfz XXX.tar.gz
    $ tar xfj XXX.tar.bz2

    --== tar 사용하기

    [root@h200 backup]# tar cvfz back.tar *
    -- tar [옵션] [tar로 생성될 파일명] [압축할 파일명] 이렇게 사용한다.

    [root@h200 backup]# tar cvf back1.tar group passwd
    -- 파일을 선택하여 묶을 경우 한칸띄우고 파일명을 나열한다.

    [root@h200 backup]# tar rvf back1.tar group1
    -- 이미 묶여진 tar파일에 추가로 묶을경우 r을 사용하면 된다.

    [root@h200 backup]# tar tvf back1.tar
    -rw-r--r-- root/root 674 2005-05-27 19:40:38 group
    -rw-r--r-- root/root 1622 2005-05-27 19:40:06 passwd
    -rw-r--r-- root/root 674 2005-05-27 19:40:58 group1
    -- tar로 묶은 파일의 내용을 보고자 할경우 t를 사용하면 된다.

    [root@h200 backup]# tar f back1.tar --delete group1
    -- tar로 묶은 파일에서 하나를 삭제할 경우 f를 사용 [tar명] --delete [삭제할 파일명]
    [root@h200 backup]# tar tvf back1.tar -- 다시 확인시 파일이 빠져 있다.
    -rw-r--r-- root/root 674 2005-05-27 19:40:38 group
    -rw-r--r-- root/root 1622 2005-05-27 19:40:06 passwd

    [root@h200 backup]# tar xvf back.tar
    -- tar파일을 풀때는 x를 사용한다.


    --== gzip 사용하기

    [root@h200 backup]# gzip [gz로 생성될 파일명] -- gz으로 압축
    [root@h200 backup]# gunzip [gz 파일명].gz -- gz 압축풀기


    --== bzip2 사용하기

    [root@h200 backup]# bzip2 -v [bz2로 생성될 파일명] -- bz2으로 압축 '-v'옵션은 압축결과를 보여준다.
    [root@h200 backup]# bunzip2 [bz2 파일명].bz2 -- bz2 압축풀기
    [root@h200 backup]# tar xfj [bz2 파일명].bz2 -- tar와 bz2를 한번에 같이 풀기

    --== tar와 gz 한번에 풀기
    [root@h200 backup]# tar cvfz test1.tar.gz * ; tar xvfz test1.tar.gz -C /opt/aaa
    -- 현재폴더안의 파일 모두를 tar로 묶고 gz로 압축하여 그 파일을 /opt/aaa폴더안에 tar와 gz를 푼다. 여기서 -C옵션은 지정한 폴더로 풀어라는 명령이다.


    --== 텍스트기반 인터넷을 사용하기 위한 패키지 설치
    [root@h200 rpms]# rpm -Uvh lynx-2.8.5-11.i386.rpm --nodeps
    -- 마운트후 lynx-2.8.5-11.i386.rpm 패키지를 찾아서 위처럼 설치한다.

    'Programming > Install&Tip' 카테고리의 다른 글

    우분투에 opencv 2.2 설치하기  (0) 2011.10.08
    sqlyog 무료버전  (0) 2011.09.05
    [펌] 티스토리에 소스 코드 올리기 - Google SyntaxHighlihter  (0) 2010.06.09
    linux install tip  (0) 2010.06.07
    Posted by 한효정

    2009. 5. 29. 10:28 Programming

    mysql index


    1. 만들기
    CREATE INDEX <인덱스명> ON <테이블명> ( 칼럼명1, 칼럼명2, ... );

    create unique index index_name  using btree  on table_name ( name(10)  ) ;
    create index index_name  on  table_name ( id(10), name(30) );

    2. 테이블 생성시 만들기
    create table index_sample (
    product_code char(10) not null,
    product_name char(20) not null,
    product_detail char(100) not null,
    index (product_code)   <---- product_code에만 인덱스 걸기
    );

    3. 테이블 생성시 2개 만들기
    create table index_sample (
    product_code char(10) not null,
    product_name char(20) not null,
    product_detail char(100) not null,
    index (product_code, product_name)  <---- product_code, product_name 두개에 인덱스 걸기
    );                                                             and 조건으로 검색시에만 인덱스 활용

    4. 인덱스 보기
    show index from index_sample;

    5. 인덱스 제거
    drop index index_name on table_name

    'Programming' 카테고리의 다른 글

    FLEX 관련  (0) 2009.08.18
    Posted by 한효정

    AutoAlbum




    A system for automatically summarizing your digital photographs to make them easier to find.

     

    Quick Links

    About AutoAlbum & PhotoTOC

    It is getting increasingly popular for consumers to buy a digital camera and take thousands of photos of daily life. Most consumers simply dump these photos into one directory, analogous to dumping developed prints into a shoebox. A typical user generates thousands of photos a year. Finding a photo in this shoebox directory is difficult. AutoAlbum and PhotoTOC are browsing user interfaces that help solve this problem. AutoAlbum was the original UI, while PhotoTOC is a new, updated UI. PhotoTOC consists of two panes. Thumbnails of all images in the shoebox directory is shown on the right pane, as a big contact sheet. PhotoTOC automatically clusters these images. One representative photograph from every cluster is shown on the left pane. When the user clicks on a representative photograph, the right pane scrolls to show that same photograph in the center of the window. The user can then find his/her photograph with minimal scrolling on the right-hand pane. Both AutoAlbum and PhotoTOC use two forms of metadata to help cluster the photos: the creation time of the photo and the order that the photos were taken. Under some circumstances, the creation time of the photo is preserved after download from the camera to the PC. In those cases, PhotoTOC can cluster on the creation time and ignore the content. In other cases, the creation time is destroyed (e.g., by downloading with a serial cable, or camera running out of batteries). However, the order of the photographs is still often preserved, via either download time or file name. In this second case, PhotoTOC uses the content of the photos to cluster, but creates clusters that obey the photographic order. In the demo, the combination of these two clustering techniques are used: first, time-based clustering uses the creation date of the file to form albums. If the creation date of the file is not the creation date of the photo, time-based clustering will produce very large clusters. So, any very large cluster will get broken down by content-based clustering that obeys the order of the photographs.

    'Programming > Computer Vision' 카테고리의 다른 글

    8 point 알고리즘  (0) 2009.09.15
    Computer Vision at MSR Cambridge  (0) 2009.05.02
    Posted by 한효정
    이전버튼 1 2 3 이전버튼

    블로그 이미지
    착하게 살자.
    한효정

    카테고리

    공지사항

    Yesterday
    Today
    Total

    달력

     « |  » 2024.12
    1 2 3 4 5 6 7
    8 9 10 11 12 13 14
    15 16 17 18 19 20 21
    22 23 24 25 26 27 28
    29 30 31

    최근에 올라온 글

    최근에 달린 댓글

    글 보관함