Hidden tips 001

Tuesday, November 22, 2011

hidden tips

1, install ruby-1.9.3 on Mac OSX Lion via rvm

 rvm install 1.9.3 --with-gcc=clang

2, package name with underscore in buildout, should be replace underscore to DASH, for example pyramid_jinja2 in buildout.

 [versions]
 pyramid-jinja2 = 1.2

3, install proxychains on Mac OSX Lion via homebrew
download my Proxychains Formula, and run brew install proxychains

4, setting pyramid_debugtoolbar.
If the request’s REMOTE_ADDR is not 127.0.0.1, u should add config debugtoolbar.hosts in your .ini file, for example:

debugtoolbar.hosts = 127.0.0.1 192.168.0.116

Upgrade postgresql-8.4 to postgresql-9.1

Tuesday, November 22, 2011

install postgresql 9.1 on ubuntu via apt-get

1, back up your databases

 ~ pg_dumpall > outputfile

2, add postgresql apt repository

~ sudo add-apt-repository ppa:pitti/postgresql

3, remove postgresql-8.4

~ sudo apt-get remove postgresql-8.4

4, update apt source index

~ sudo apt-get update

5, install postgresql-9.1

~ sudo apt-get install postgresql-9.1

6, create new user for postgres

~ sudo -u postgres sh
[sudo] password for eric: 
$ createuser -P eric
Enter password for new role: 
Enter it again: 
Shall the new role be a superuser? (y/n) y
$ exit

7, restore your data from backup

~ psql -d postgres -f outputfile

Done!~

Mac OS X 下无密钥方式连接基于L2TP协议的VPN

Monday, November 7, 2011

需要连接一个L2TP协议的vpn, 填好信息竟然报错“IPSec 共享密钥”丢失。请验证您的设置并尝试重新连接。 但是这个vpn不需要IPSec 共享密钥啊, google了一把发现需要打补丁来绕过它。

/etc/ppp目录下新建一个文件options, 写入下面的内容

plugin L2TP.ppp
l2tpnoipsec

就可以无需密钥连接了,最后别忘了把高级设置里面"通过VPN连接发送所有流量"钩上。

In Pyramid-based website production environments, should generate a 404 NotFound Error instead of Server Error `URLDecodeError`.

Sunday, October 30, 2011

a unknown url
http://lxneng.com/sms/ests%C3%CD%E1%EF2.asp always request my
Pyramid-based website server, it will be raise a URLDecodeError.

Traceback:

Traceback (most recent call last):
File "/root/env/lib/python2.6/site-packages/repoze.tm2-1.0b2-py2.6.egg/repoze/tm/__init__.py", line 24, in __call__
    result = self.application(environ, save_status_and_headers)
File "/var/www/lxneng/src/lxneng/__init__.py", line 27, in __call__
    return self.application(environ, start_response)
File "/root/env/lib/python2.6/site-packages/pyramid/router.py", line 176, in __call__
    response = self.handle_request(request)
File "/root/env/lib/python2.6/site-packages/pyramid/tweens.py", line 17, in excview_tween
    response = handler(request)
File "/root/env/lib/python2.6/site-packages/pyramid/router.py", line 116, in handle_request
    tdict = traverser(request)
File "/root/env/lib/python2.6/site-packages/pyramid/traversal.py", line 610, in __call__
    vpath_tuple = traversal_path(vpath)
File "/root/env/lib/python2.6/site-packages/repoze/lru/__init__.py", line 96, in lru_cached
    val = f(*arg)
File "/root/env/lib/python2.6/site-packages/pyramid/traversal.py", line 486, in traversal_path
    raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason)
URLDecodeError: 'utf8' codec can't decode bytes in position 4-5: invalid data

so this should generate a 404 instead of a 500 internal server error.

@view_config(context='pyramid.exceptions.URLDecodeError', renderer='404.html')
@view_config(context='pyramid.exceptions.NotFound', renderer='404.html')
def error_view(context, request):
    return {}

Pyramid project paster command line tools script template

Wednesday, October 26, 2011

1, new a commands script file commands.py

from paste.script.command import Command
import os.path
from pyramid.threadlocal import manager as threadlocal_manager
from paste.deploy import loadapp


class PyramidCommand(Command):

    group_name = "lxneng"
    min_args = 1
    max_args = 1
    parser = Command.standard_parser()

    def setupPyramid(self):
        app = loadapp('config:%s' % self.args[0], relative_to=os.path.abspath('.'))
        registry = app.registry
        try:
            threadlocal_manager.push({'registry':registry})
        finally:
            threadlocal_manager.pop()


class DemoCommand(PyramidCommand):
    summary = "demo script"
    usage = "paster --plugin=lxneng demo_script development.ini"
    parser = PyramidCommand.standard_parser()

    def command(self):
        from lxneng.models.post import Tag
        tag = Tag.find_by_name('Python')
        print tag.name

2, add command to setup.py

entry_points="""\
  [paste.app_factory]
  main = lxneng:main

  [paste.paster_command]
  demo_script = lxneng.commands:DemoCommand
  """,

3, build

python setup.py develop

4, run

paster --plugin=lxneng demo_script development.ini

note:
lxneng is my project name

Objective-C 扩展名

Tuesday, October 25, 2011

  • .h 头文件, 头文件包含类, 类型, 函数和常数的声明.
  • .m 源代码文件, 这是典型的源代码文件扩展名, 可以包含Objective-C和C代码.
  • .mm 源代码文件, 带有这种扩展名的源代码文件, 除了可以包含Objective-C和C代码以外还可以包含C++代码. 仅在你的Objective-C代码中确实需要使用C++类或者特性的时候才使用这种扩展名.

Setup ipython to work in a virtualenv

Monday, August 29, 2011

add this script to \~/.ipython/ipython_virtualenv.py

#Call this inside ~/.ipython/ipy_user_conf.py main()

import sys
import subprocess
from os import environ

if 'VIRTUAL_ENV' in environ:
    #This is kludgy but it works; grab the right sys.path from the virtualenv python install:
    path = subprocess.Popen(['python', '-c','import sys;print(repr(sys.path))'],
                            stdout=subprocess.PIPE).communicate()[0]
    sys.path = eval(path)
    del path

del sys, subprocess, environ

from https://gist.github.com/817737

using gettext convert .mo to .po, and .po to .mo

Monday, August 29, 2011

install gettext

on Mac OSX via Homebrew

brew install gettext

on Ubuntu via apt-get

apt-get install gettext

mo to po ###

msgunfmt xxx.mo -o xxx.po

po to mo

msgfmt xxx.po -o xxx.mo

Manage (Add, Edit, & Delete) cookies in jQuery

Monday, June 27, 2011

原文
http://www.akchauhan.com/manage-add-edit-delete-cookies-in-jquery/
Setting and deleting cookies with jQuery is really easy (especially in
comparison to regular JavaScript) but this feature is not included in
the jQuery core. For this we need a plug-in. This post shows how to set
and get the value of cookies with jQuery.

First download the jQuery cookie plugin for here:
http://plugins.jquery.com/project/Cookie

Set a cookie

Setting a cookie with jQuery is as simple as this, here
we are creating a cookie called “example” with a value “demo”:

$.cookie("example", "demo");

This is a session cookie and will be destroy when user close his/her
browser. To make the same cookie for suppose 7 days. We can do it like
this:

$.cookie("example", "demo", { expires: 7 });

The above example will create the cookie at the root level. If you
wanted to make it apply only to e.g. “/admin” and make it for 7 days you
can do it like this:

$.cookie("example", "demo", { path: '/admin', expires: 7 });

Get the cookie’s value

Getting the cookie’s value is also very easy
in jQuery. The following would alert the value of “example” cookie:

alert( $.cookie("example") );

Delete the cookie

And finally, to delete a cookie set its value to
null.
Note:Setting it to e.g. an empty string doesn’t remove it;
it just clears the value.

$.cookie("example", null);

设计者的品味

Sunday, June 12, 2011

  • 好设计是简单的设计
  • 好设计是永远不过时的设计
  • 好设计是解决主要问题的设计
  • 好设计是启发性的设计
  • 好设计通常是有点趣味性的设计
  • 好设计是艰苦的设计
  • 好设计是看似很容易的设计
  • 好设计是对称的设计
  • 好设计是模仿大自然的设计
  • 好设计是一种再设计
  • 好设计是能够复制的设计
  • 好设计常常是奇特的设计
  • 好设计是成批出现的
  • 好设计常常是大胆的设计

——摘自《黑客与画家》第九章-设计者的品味

UUID in SQLAlchemy

Friday, June 10, 2011

Add a Custom Types

types:

# model/uuid.py
from __future__ import absolute_import
import uuid
from sqlalchemy.types import TypeDecorator, CHAR
from sqlalchemy.dialects.postgresql import UUID


class GUID(TypeDecorator):
    """Platform-independent GUID type.

    Uses Postgresql's UUID type, otherwise uses
    CHAR(32), storing as stringified hex values.

    """
    impl = CHAR

    def load_dialect_impl(self, dialect):
        if dialect.name == 'postgresql':
            return dialect.type_descriptor(UUID())
        else:
            return dialect.type_descriptor(CHAR(32))

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        elif dialect.name == 'postgresql':
            return str(value)
        else:
            if not isinstance(value, uuid.UUID):
                return "%.32x" % uuid.UUID(value)
            else:
                # hexstring
                return "%.32x" % value

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            return uuid.UUID(value)

example

mode:

# model/user.py
from you.app.model.uuid import GUID
from you.app.model import meta

class User(meta.BaseObject):

    __tablename__ = "user"

    uuid = schema.Column(GUID(), default=uuid.uuid4, nullable=False, unique=True)

meta:

# model/meta.py
from sqlalchemy import schema
from sqlalchemy.ext.declarative import declarative_base

__all__ = ["Session", "metadata", "BaseObject" ]

Session = None

metadata = schema.MetaData()
BaseObject = declarative_base(metadata=metadata)

reference: Backend-agnostic GUID
Type

ajax get server side time string, pyramid example

Friday, June 10, 2011

ajax get server side time string, pyramid example

#route
config.add_route("servertime", "/servertime")

#server side
@view_config(route_name="servertime", renderer='string')
def serverTime(request):
    return datetime.now()

#client
var timeStr = $.ajax({url: "/servertime", async: false}).responseText;

UUID primary keys in Rails 3

Friday, June 10, 2011

Gemfile

# Gemfile
…
gem 'uuidtools'
…

migrations
# 1. :id => false
# 2. :uuid
#

class CreateSites < ActiveRecord::Migration
  def self.up
    create_table(:sites, :id => false) do |t|
      t.string :uuid, :limit => 36, :primary => true
      t.timestamps
    end
  end

  def self.down
    drop_table :sites
  end
end

model

# app/models/site.rb
class Site < ActiveRecord::Base
  include Extensions::UUID
end

extensions

# app/models/extensions/uuid.rb
#
module Extensions
  module UUID
    extend ActiveSupport::Concern

    included do
      set_primary_key 'uuid'
      before_create :generate_uuid

      def generate_uuid
        self.id = UUIDTools::UUID.random_create.to_s
      end
    end
  end
end

SQLAlchemy's not in

Friday, June 10, 2011

from sqlalchemy import not_ 
session.query(Region).filter(not_(Region.id.in_( (1,2,3) )))

div>img 底部对齐

Friday, June 10, 2011

外层div的位置设置成绝对的, img 设置成块级元素,位置设置成相对的,bottom设置成0

html code

<div class="bodyShape">
    <div class="barbara">
        <img src="${tools.static_url('media/images/figure-analysis-barbara-82x135.png')}" />
    </div>
</div>

css code

.bodyShape{height:150px; width:200px;border-right: 2px solid #ccc;}
.bodyShape .barbara{position:relative;height:100%;}
.bodyShape .barbara img{bottom:0;display:block;position:absolute;}

Shorthand for the jQuery ready event

Saturday, June 4, 2011

The explicit and verbose way:

$(document).ready(function (){
    // do something here ...
});

The shorthand:

$(function (){
    // do something here ...
});

让Nginx支持mp4格式的视频播放,搭建一个mp4流媒体服务器

Saturday, April 16, 2011

在vps上下载了一些mp4格式的视频,点击是直接下载,不能直接在线播放,
所以google了一下有个nginx_mod_h264_streaming的模块。

下载

wget http://h264.code-shop.com/download/nginx_mod_h264_streaming-2.2.7.tar.gz
tar -zxvf nginx_mod_h264_streaming-2.2.7.tar.gz

编译安装

./configure --sbin-path=/usr/local/sbin --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre=/usr/local/src/pcre-8.10 --add-module=/usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.2/ext/nginx/ --add-module=/usr/local/src/nginx_mod_h264_streaming-2.2.7

make
make install

出错了

....
In file included from /usr/local/src/nginx_mod_h264_streaming-2.2.7/src/ngx_http_h264_streaming_module.c:2:
/usr/local/src/nginx_mod_h264_streaming-2.2.7/src/ngx_http_streaming_module.c: In function ‘ngx_streaming_handler’
:
/usr/local/src/nginx_mod_h264_streaming-2.2.7/src/ngx_http_streaming_module.c:158: error: ‘ngx_http_request_t’ has
 no member named ‘zero_in_uri’
make[1]: *** [objs/addon/src/ngx_http_h264_streaming_module.o] Error 1
make[1]: Leaving directory `/usr/local/src/nginx-0.8.54'
make: *** [build] Error 2

解决错误:

因为在新版本的nginx中废弃了zero_in_uri这个flag,稍微修改一下nginx_mod_h264_streaming的源代码

vim /usr/local/src/nginx_mod_h264_streaming-2.2.7/src/ngx_http_streaming_module.c

把158到161行注释掉

157   /* TODO: Win32 */
158   //if (r->zero_in_uri)
159   //{
160   //  return NGX_DECLINED;
161   //}

然后再make就正常了,make install 完成安装
配置nginx使之支持mp4
在nginx配置文件中加入

location ~ \.mp4$ {
                mp4;
        }

重启nginx

/etc/init.d/nginx restart

效果来了

image

reference

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top