为了做一个显示歌词的小玩意,学习了一把x window,我希望歌词窗口能背景透明但文字清晰显示。理论基础就是 composite window manager(比如compiz)支持窗口使用 alpha channel。那么应用程序只要整好rgba的图像交给x服务器即可。
发现使用 gtk+cairo+pango 大大简化了工作。
代码:http://code.google.com/p/huangyilib/source/browse/trunk/py_transparent_window.py

2008年11月12日星期三
linux下的半透明窗口
2008年11月11日星期二
关于设计模式
又看到关于设计模式的文章,突然联想到vim的作者说过一句大概是这样的话:学习vim的方法就是使用它,然后在使用过程中注意发现那些经常重复的行为,然后简化之。 写程序的模式又何尝不是如此呢?只不过程序的事情更复杂罢了,那些重复的模式往往需要灵感来发现,简化的方法也总是不那么明显,甚至需要思维方式的彻底改变。
2008年11月8日星期六
2008年10月28日星期二
2007年12月18日星期二
工作后
转眼来到腾讯有5个月了,博客也就长个5个月的草了。 china-pub 又给我送了几本书来,自然也就又有一百多块离开了我的身边。 拿到书的时候心情自然是不用说,不过想起床上躺着上个月的科幻世界没看完时,却也着实让人发愁。 有时间的时候没钱,有钱的时候没时间,人生啊!!! 还有可爱的python也是许久没有贡献新东西了,真是惭愧,唉~~~
2007年9月26日星期三
爆强的翻译
第一次见到翻译得这么好的编程之道了:http://livecn.huasing.org/tao_of_programming.htm Prince Wang's programmer was coding software. His fingers danced upon the keyboard. The program compiled without an error message, and the program ran like a gentle wind. Excellent!" the Prince exclaimed, "Your technique is faultless!" "Technique?" said the programmer, turning from his terminal, "What I follow is the Tao -- beyond all technique. When I first began to program I would see before me the whole program in one mass. After three years I no longer saw this mass. Instead, I used subroutines. But now I see nothing. My whole being exists in a formless void. My senses are idle. My spirit, free to work without a plan, follows its own instinct. In short, my program writes itself. True, sometimes there are difficult problems. I see them coming, I slow down, I watch silently. Then I change a single line of code and the difficulties vanish like puffs of idle smoke. I then compile the program. I sit still and let the joy of the work fill my being. I close my eyes for a moment and then log off." Price Wang said, "Would that all of my programmers were as wise!" 程序员为公子王写软件,指飞键舞,不差丝毫,行之如风。 公子王曰:『嘻,善哉!技盖至此乎?』 程序员释键对曰:『臣之所好者道也,进乎技矣。始臣之编程之时,所见无非程序者;三年之后,未尝见程序也,见其子程序也;方今之时,臣以神遇而不以目视,官知止而神欲行,因其固然,程序自写之。诚然,尝至于难者,吾见其难为,怵然为戒,视为止,行为迟,改其一字,謋然已解,如烟随风。使之编译,释键而坐,为之踌躇满志,闭目而log off之。』 公子王曰:『吾之程序员皆如此,则其善焉!』
2007年6月26日星期二
实现一个 django 的 url dispatcher
心血来潮,实现了一个 django 的 url dispatcher,比想象中简单多了。 http://djangodispatcher.googlecode.com/svn/trunk/mapper.py http://djangodispatcher.googlecode.com/svn/trunk/test.py 实际实现功能的代码才2、30行,功能基本完整,包括分层次的url配置,和发生异常时帮助调试用的一些信息。 PS:发现最近爱上了 Test Driven.
2007年6月22日星期五
如何在醉酒的情况下编写正确的程序
答案很简单:Test Driven。 哈哈,这个(http://code.google.com/p/pylifegame/)就是好例子! 醉了,不多说了,自己看去,我要睡觉去了,嗯 ...
2007年6月20日星期三
Faint! 和我同名的编辑器
原来 pickle 这么有意思
Pickle: An interesting stack language 原来 pickle 本身就是就是一个微型的基于栈的语言,呵呵,有点意思。 研究一下 pickle.py 和 pickletools.py ,可以看到更细节的东西。
翻译了这篇文章
Python 3000 进度报告 也可以从 guido 的中文 blog 看到:http://blog.csdn.net/gvanrossum/archive/2007/06/20/1658829.aspx
标签: python3000
2007年6月19日星期二
Python 3000 Status Update (Long!)
Python 3000 Status Update (Long!) by Guido van Rossum """ Summary Here's a long-awaited update on where the Python 3000 project stands. We're looking at a modest two months of schedule slip, and many exciting new features. I'll be presenting this in person several times over the next two months. """
标签: python3000
2007年6月8日星期五
2007年6月3日星期日
SQLAlchemy Examples
看 SQLAlchemy 自带的 zblog 的例子,可以看到 SQLAlchemy 一些非常有用的特性。
文章相关评论数统计
比如显示文章列表的同时我们希望获得相关文章的评论数,如果是用 django 那就只能放弃 ORM 的好处自己去执行 sql 语句了,否则就只会导致 n+1 条 SQL 语句的执行。 在 SQLAlchemy 中你可以把任意的 select 语句映射到一个 class ,这样就可以用一条 SQL 语句搞定,还能获得 ORM 的好处,下面是原封不动拷过来的代码(只调整了下格式):
# Post mapper, these are posts within a blog.
# since we want the count of comments for each post,
# create a select that will get the posts
# and count the comments in one query.
posts_with_ccount = select(
[c for c in tables.posts.c if c.key != 'body'] + [
func.count(tables.comments.c.comment_id).label('comment_count')
],
from_obj = [
outerjoin(tables.posts, tables.comments)
],
group_by=[
c for c in tables.posts.c if c.key != 'body'
]
) .alias('postswcount')
# then create a Post mapper on that query.
# we have the body as "deferred" so that it loads only when needed,
# the user as a Lazy load, since the lazy load will run only once per user and
# its usually only one user's posts is needed per page,
# the owning blog is a lazy load since its also probably loaded into the identity map
# already, and topics is an eager load since that query has to be done per post in any
# case.
mapper(Post, posts_with_ccount, properties={
'id':posts_with_ccount.c.post_id,
'body':deferred(tables.posts.c.body),
'user':relation(user.User, lazy=True,
backref=backref('posts', cascade="all, delete-orphan")),
'blog':relation(Blog, lazy=True,
backref=backref('posts', cascade="all, delete-orphan")),
'topics':relation(TopicAssociation, lazy=False, private=True,
association=Topic, backref='post')
}, order_by=[desc(posts_with_ccount.c.datetime)])
树形评论
映射如下:
# comment mapper. This mapper is handling a hierarchical relationship on itself,
# and contains
# a lazy reference both to its parent comment and its list of child comments.
mapper(Comment, tables.comments, properties={
'id':tables.comments.c.comment_id,
'post':relation(Post, lazy=True,
backref=backref('comments', cascade="all, delete-orphan")),
'user':relation(user.User, lazy=False,
backref=backref('comments', cascade="all, delete-orphan")),
'parent':relation(Comment,
primaryjoin=tables.comments.c.parent_comment_id==tables.comments.c.comment_id,
foreignkey=tables.comments.c.comment_id, lazy=True, uselist=False),
'replies':relation(Comment,
primaryjoin=tables.comments.c.parent_comment_id==tables.comments.c.comment_id,
lazy=True, uselist=True, cascade="all"),
})
很多时候我们需要一次性获取对应一个文章的所有评论,可以用一条 select 先把数据取出,然后手动建立树形结构:
# we define one special find-by for the comments of a post, which is going to make its own
# "noload" mapper and organize the comments into their correct hierarchy in one pass. hierarchical
# data normally needs to be loaded by separate queries for each set of children, unless you
# use a proprietary extension like CONNECT BY.
def find_by_post(post):
"""returns a hierarchical collection of comments based on a given criterion.
uses a mapper that does not lazy load replies or parents, and instead
organizes comments into a hierarchical tree when the result is produced.
"""
q = session().query(Comment).options(noload('replies'), noload('parent'))
comments = q.select_by(post_id=post.id)
result = []
d = {}
for c in comments:
d[c.id] = c
if c.parent_comment_id is None:
result.append(c)
c.parent=None
else:
parent = d[c.parent_comment_id]
parent.replies.append(c)
c.parent = parent
return result
Comment.find_by_post = staticmethod(find_by_post)
标签: sqlalchemy
2007年5月30日星期三
multitask and Hive
multitask multitask allows Python programs to use generators (aka coroutines) to perform cooperative multitasking and asynchronous I/O. Applications written using multitask consist of a set of cooperating tasks that yield to a shared task manager whenever they perform a (potentially) blocking operation, such as I/O on a socket or getting data from a queue. The task manager temporarily suspends the task (allowing other tasks to run in the meantime) and then restarts it when the blocking operation is complete. Such an approach is suitable for applications that would otherwise have to use select() and/or multiple threads to achieve concurrency. Producer/Consumer with multitask library Hive This is a basic concurrency module that uses only dependencies available in the Python 2.5 standard library. It allows the creation of a jobfile for uses to queue work that any number of worker processes with access to the jobfile can pull from the queue and run. 看到这两个库很快就联想到曾经写过的那段代码,python2.5 增强的 yield 表达式所蕴涵的 continuation 的能力似乎终于有人拿它来发挥点实际作用了。
标签: continuation, python, stackless
Polymorphic Associations in Rails
Polymorphic Associations with SQLAlchemy SQLAlchemy 老大展示怎么用 sqlalchemy 实现 rails 的 Polymorphic Associations 顺便看了下 Rails 所谓Polymorphic Associations 的介绍,才发现其实就是我很早就介绍过的 django 的 content-type app 所干的事情,app 就是插件的意思。
标签: django, rails, sqlalchemy
2007年5月26日星期六
Python and vim: Two great tastes that go great together
Python and vim: Two great tastes that go great together 用 python 扩展 vim ,想法倒是不新,不过第一次看到 tutotial 。 记得 tocer 说过要用 python 写个 vim 库的,不知道有没有进展哈,呵呵。
Evolution of a Python programmer
http://dis.4chan.org/read/prog/1180084983/ 哈哈,有点意思,再加一个: Python 2.5 programmer:
def fact(x):
return x * fact(x - 1) if x > 1 else 1
print fact(6)
2007年5月22日星期二
多重继承真是好哇
写 model 的时候发现有些东西在重复,第一反应就是写个基类,把这些重复的东西拿出来,然而 Model 类之间继承却不是那么方便的,应该会影响到 ORM 的行为。 怎么办呢?幸好 python 有多重继承。 下面就是项目中做这些重复事情的类:
class ModelMixin(object):
def save(self):
if not self.id: # creation time
if hasattr(self, 'pubdate'):
self.pubdate = datetime.now()
if hasattr(self, 'pubtime'):
self.pubtime = datetime.now()
if hasattr(self, 'updatedate'):
self.updatedate = datetime.now()
if hasattr(self, 'updatetime'):
self.updatetime = datetime.now()
if hasattr(self, 'number'): # 今天第几次发布
self.number = self.__class__.objects.filter(pubdate=datetime.now()).count()+1
if hasattr(self, 'before_save'):
self.before_save()
super(ModelMixin, self).save()
if hasattr(self, 'after_save'):
self.after_save()
注意:django 将废弃 auto_add 和 auto_now 这些东西,认为太 magic ,建议在 save 中处理,所以上面这个类就更有用了。
怎么用呢?
class Product(ModelMixin, models.Model):
pubdate = models.DateField(u'...', editable=False)
number = models.IntegerField(u'...', editable=False)
...
这样 pubdate 和 number 自然就有了相应的含义了。另外 ModelMixin 还定义了 before_save 和 after_save 的钩子,具体 model 可以在这两个方法里放点代码,比如:
def before_save(self):
self.totalprice = self.count * self.product.unitprice
...
def after_save(self):
if self._create:
p = OutProduct(postuser=self.postuser,count=1,
pubdate=self.pubdate,mainproduct=self)
p.save()
这些都是项目中直接拷出来的代码,具体意思你就慢慢猜吧,呵呵。
多重继承的实现其实是个还算复杂的过程,复杂的多重继承也会产生一些奇特的行为,不过基本上只要遵守一些良好的习惯(比如常用 super ,虽然写起来有些繁琐),了解一些多重继承的基本原理,基本上不会遇到什么奇怪的问题了。
关于 python 多重继承的实现,请看:The Python 2.3 Mehod Resolution Order
Profile
- 黄毅
- 深圳, 广州, China
- I Love Python !
Recent Posts
Recent Comments
Tags
- 设计模式 (1)
- ajax (3)
- allegra (1)
- cherrypy (1)
- compiler (1)
- continuation (2)
- descriptor (1)
- django (17)
- dotnet (1)
- framework (2)
- functional (1)
- genshi (1)
- gtk (1)
- haskell (1)
- inkscape (1)
- IronPython (2)
- javascript (1)
- libevent (1)
- mako (1)
- metaclass (4)
- mochikit (1)
- network (1)
- newforms (1)
- orm (1)
- others (18)
- paste (1)
- PEAK (1)
- pickle (1)
- ply (1)
- pocoo (1)
- pypy (3)
- python (38)
- python3000 (3)
- rails (2)
- REST (3)
- sqlalchemy (3)
- stackless (3)
- turbogears (1)
- tutorial (1)
- vim (1)
- web (11)
- wsgi (1)



