Git tips

  • Create a new branch and checkout it
  • git checkout -b new_branch_name [based_on_another_branch]
    
  • Track branch
  • When pulling/pushing a ‘tracking branch’, git will automatically pull/push from remote repository so there’s no need to specify the upstream

    git branch --track new_branch origin_branch (e.g. origin/master)
    git checkout new_branch
    git pull
    # do some editing
    git push
    
  • Squash merge
  • Will merge all commits on another branch into one commit on current branch. Squash merge is mostly used when commits on another branch are mess

    git merge --squash another_branch
    
  • diff
  • Show you the changes in your working tree that haven’t been staged or committed yet

    git diff
    

    Show staged changes

    git diff --cached
    

    Show all changes

    git diff HEAD
    
    发表在 未分类 | 标签为 | 留下评论

    Asynchronous Pattern In Tornado

    This article aim to explain how can we schedule a job in another thread when developing tornado web server.

    Why we need asynchronous

    Tornado will deal all web requests in a single thread — the main io loop,

    so it’s wise to dispatch a blocking job to another thread other than the main thread,

    otherwise it will make your web server occur an out of service error.

    Key points

    • Use tornado.web.asynchronous to wrap your request-handler’s “get”
    • Push the (job_func,job_func_param,result_callback) to another thread’s queue
    • Do the job in that thread
    • When the job is done, add a callback to the main thread
    • Finish the requst in the callback

    Pseudo Code

    ?View Code PYTHON
    import functools
    from threading import Thread
    import Queue
    import tornado.ioloop
     
    class WorkerThread :
        def __init__(self):
            super(WorkerThread, self).__init__()
            self.req_queue = Queue.Queue()
            self.ioloop = tornado.ioloop.IOLoop.instance()
     
        def AddReq(self, req_func, req_msg, result_callback):
            '''
            we will call req_func with req_msg
            and then call callback with return value of req_func as a parameter
            callback will be called in the main thread, means ioloop
            '''
     
            self.req_queue.put((req_func,req_msg,result_callback))
     
        def run(self):
            while(True):
                req_func,req_msg,result_cb = self.req_queue.get()
                result = req_func(req_msg)
                self.ioloop.add_callback(
                    functools.partial(result_cb,
                                      resp = result
                    )
                )
     
    import tornado.web
    class HomeHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        def get(self):        
            req = YourRequest()        
            worker = WorkerThread()
            worker.AddReq(self.do_req,req,self.on_finished)
     
        def do_req(self,req):
            resp = DoSomeThingWith(req)
            return resp
     
        def on_finished(self,resp):
            self.render("home.html",message = str(resp.some_message))
    发表在 未分类 | 标签为 , , | 留下评论

    我的E家 zte h618, PPPOE IPTV 无线路由配置

    一直是用自己的无线路由器再接电信送的zte h168b, 来达到iptv,无线路由,PPPOE的功能.

    今天突然发现zte h168b 上写着有无线功能. 原来自己浪费了一年的电……, 于是可以让自己的路由器休息了, 让zte我的E家送的路由器搞定一切.

    超级用户

    用户为 telecomadmin
    密码为 nE7jA%5m

    IPTV与宽带上网的模型

    两者不相关, 相当于两个路由器, 宽带上网是宽带上网, IPTV是IPTV, 只是二者使用了同一出口.

    IPTV会桥接到宽带的出口上.

    与vmware的桥接模型是一样的, 虚拟机会以桥接的方式使用主机的网卡与外部通信, 而ip是独立的, 在外部看来虚拟机就是一台真实的有网卡有ip的机器.

    因此与普通常用的路由器不同, 该路由器可以以桥接的方式建立多个对外的连接通道.

    PPPOE设置

    新增一个 WAN 连接 (我把原来的宽带设置都删除了, 然后全新建的.)

    注意 选择, PPPoE路由桥混合模式, 注意不要绑定 LAN2, 我家的IPTV插在LAN2上. 其它的可以全绑上.

    IPTV设置

    再新增一个 WAN 连接

    无线设置

    进入 WLAN 配置, 启用之. 配置项与其它路由器的大同小异.

    UPNP

    ……

    发表在 未分类 | 标签为 | 留下评论

    Tips For C++er to use Python

    Is something empty?

    it is recommended to use

    ?View Code PYTHON
    if items:
      do some thing

    other than

    ?View Code PYTHON
    if len(items) != 0: 
      do some thing
    if items != None: 
      do some thing

    Don’t forget ‘:’ at the end

    Python uses ‘:’ to indicate a block of code. Although I think it is not necessarily need, but it is.

    ?View Code PYTHON
    if some_condition:
      do something
    while some_condition:
      do something

    use ‘pass’ if nothing to do

    ?View Code PYTHON
    if some_condition:
      pass
    else:
      do something

    NULL/true/false

    Use ‘None/True/False’ instead.

    logic

    ‘&& || !’ -> ‘and, or, not’

    ?View Code PYTHON
    if not some_condition:
      pass
    if some_condition and another_condtion:
      pass

    Indention

    Indention in python is essential and compulsive. Code-block is defined by indention like {} in C++

    ?View Code PYTHON
    if some_condition:
      do something
      do another thing # OK, indention is consist with the previous statement
    else:
      do something else
        do another thing # Fails because indention is illegal

    Be careful to use tab and space. It is wisely to config your editor to display white-chars.

    for_each

    ?View Code PYTHON
    for item in item_list:
      print item

    enumerate items in a container

    ?View Code PYTHON
    for (index, item) in enumerate(items): 
      print index, item
     
    for (key,value) in mydict.items():
      print key,value

    string

    ‘this is a string’
    “this is also a string”
    ”’this is a
    multi-line string”’

    join string

    ?View Code PYTHON
    colors = ['red', 'blue', 'green', 'yellow'] 
    result = '|'.join(colors)
    print result #It will print 'red|blue|green|yellow'

    Swap

    ?View Code PYTHON
    a,b = b,a

    list,set,tuple,dict

    list -> array/vector: ['this','is','a','list']
    set -> std::set
    tuple -> const list: (‘this’,'is’,'a’,'list’)
    dict -> hash map: {“key1″:”value1″, “key2″:”value2″}

    list to set: aNewSet = set(mylist), with duplicated item automatically removed
    set to list: aNewList = list(myset)
    list to tuple: aNewTuple = tuple(mylist)
    tuple to list: aNewList = list(mytuple)

    List comprehension

    result = [x for x in xrange(10) if I % 2 == 0]
    print result #will be 2 4 6 8

    True?1:2

    a = 1 if some_condition else 2

    Reference or Value

    every object is a reference to memory. python will collect an object if there is nobody refer to it.

    you can use copy to clone a object

    ?View Code PYTHON
    import copy
    #simple copy, like in C++, do simple copy only if there is no pointer member
    aNewList = copy.copy(theOldList)
    #like in C++, you should do deep copy if there any pointer member
    aNewList = copy.deepcopy(theOldList)
    发表在 未分类 | 标签为 | 一条评论

    Outline Of Defensive programming

    Summary

      Defensive at compile time
      Use Static Analysis Tools
      Assertion
      Use Run-time Analysis Tools
      Alpha Version

    Failing fast

      Don’t Work around problems
      Fail immediately and visibly
      Prefer compile err to run-time err
      Dead Programs Tell No Lies

    Warning as error

      Turn on all warnings (-Wall)
      Turn on variable argument s check (-Wformat)
      Treat warning as error (-Werror)
      Use -isystem to ignore warnings
      check out for more useful flags of GCC

    Refine define

    • Static cast, So FLY(pDuck); will fail
    • #define FLY(pBird) static_cast<CBird*>(pBird)->Eat()
    • Do while(0)
    • limit the scope of variables in define

    Pclint

      Variable have not been initialized
      new [] / delete mismatch
      Access out-of-bounds

    Pclint walker

      Enhanced Error description (Chinese)
      Only Essential Errors, without errors that compiler can check.
      Automatically and recursively check all project files
      Easily Integrated to tools (e.g. Jenkins)

    Key points of Assertion

      Data invariants that ensure data integrity
      Pre- and postconditions that ensure function correctness
      No Side effect
      Enable In Alpha and Debug Version
      Redirect output on Linux, or log to file

    Practices of Assertion

      MFC assert_valid
      Default of switch
      Null pointer
      Index of array
      u32 defer u8 memory in our Sybase SDK

    Valgrind

      Runtime Analysis Tool More Precise
      new [] / delete Mismatch
      Access out-of-bounds
      Uninitialized Memory

    Alpha Version

      Enable Core and Symbol
      -fstack-protector-all(>gcc4.1)
      Enable Assert, and Crash ASAP
      Enable Optimize Same As Release Version
      Enable Runtime Analysis Tool(eg. TCMalloc heapcheck)

    Reference

      Code complete : C hapter 8 defensive programming
      Code craft : Chapter 1 on the defensive
    发表在 未分类 | 标签为 , , , | 一条评论