Wednesday, February 24, 2010

Gương người xưa: Thực hành nhân đức và để lại tiếng thơm

Trương Phương Bình, sống ở Nam Kinh dưới thời Bắc Tống, là người khoan dung nhân hậu và trọng lễ nghĩa. Ông luôn giữ vững tiết tháo cao thượng và rất tin tưởng vào Thần Phật. Là người có phong cách cao nhã và độ lượng, ông luôn được nhiều người kính trọng.

Vào mùa thu năm 1054 sau Công nguyên, tức năm Chí Hòa thứ nhất đời vua Tống Nhân Tông, có một tin đồn ở vùng Tứ Xuyên truyền đến rằng quân địch đang sắp sửa xâm phạm biên giới. Quân sĩ đóng nơi biên cương tỉnh Tứ Xuyên nửa đêm được tin vô cùng kinh hãi, trăm họ đều tháo chạy, đạo tặc nổi lên khắp nơi, trật tự xã hội trở nên đại loạn.

Khi tin tức truyền đến kinh thành ở Khai Phong, cả triều đình từ trên xuống dưới đều chấn động kinh hãi. Tống Nhân Tông phải tìm người chủ soái để phái đi dẹp loạn, bèn nói với triều thần: “Đừng gây nên họa loạn, cũng đừng khiến nó trở thành sự biến. Dẫu rằng tin đồn trong dân chúng có tới tấp đi nữa, nhưng chủ ý của Trẫm đã định, họa xâm lăng chưa chắc là sẽ đến, chỉ sợ sự biến nổi lên từ nội bộ mà thôi. Sự việc này cần giải quyết theo cả hai cách là ‘nhu văn’ và ‘võ công’. Trẫm cần một hoặc hai vị đại thần đi xử lý chuyện này một cách khéo léo. Ai có khả năng làm nổi sự việc này, Trẫm sẽ phái người đó đi chiêu an quân dân của Trẫm”. Mọi người trong triều đều tiến cử Trương Phương Bình. Tống Nhân Tông đồng ý và phái Trương Công đi. More

From: Dai Phat Thanh Hy Vong (

Petitioners Beware: Detainment, Detainment, Then ‘Reeducation Through Labor’

By Rona Rui
[] Epoch Times Staff
Created: Feb 23, 2010 Last Updated: Feb 23, 2010

This billboard reads 'Persistent and Noisy Petitioners: First time—detention, second time—detention, third time—Reeducation Through Labor,' set up by 'The Chinese Communist Party Tianxin Township Committee, Tianxin Township People's Government.' (Photo by anonymous citizen)
A billboard with a foreboding message erected beside a road in Jiahe County, China’s Hunan Province, is indicative of the ruling regime’s tighter control of dissent, according to commentators: “To All Persistent and Noisy Petitioners: First time—Detention; Second time—Detention; Third time—Reeducation Through Labor.”

According to an eyewitness, this sign is located in Tianxin Township in Jiahe County to the right of a highway. Standing in a fork in the road, the sign stood at 7-8 square meters and was inscribed with “The Chinese Communist Party (CCP) Tianxin Township Committee, Tianxin Township People's Government.” Photos of forced labor detainees, large handcuffs, and policemen with austere expressions made it a startling sight, according to an observer. More

Tuesday, February 23, 2010

Jack in the Box offering free sandwich -- today only

At your local Jack in the Box you can buy a large soda and received a FREE grilled sandwich. The offer, available today only, is an introduction to the two new items at Jack in the Box.

The sandwiches, the turkey bacon cheddar and deli trio sandwiches, are grilled and are said to be made with fresh ingredients. Since the yummy items won't cost you a dime (and sound great for lunch or dinner) there is nothing wrong with stopping by and giving in to an inexpensive meal.

There are a few places in the country this offer is not valid (almost everywhere though.) Check your local Jack in the Box or if you want to save some time, got to the Jack in the Box website to see if your area is a freebie location.

Monday, February 22, 2010

Twisted's DeferredQueue

import itertools
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet import task


def startProducing(q):
"""Put an incrementing number in the queue every 1/FREQUENCY
counter = itertools.count()
def produce():

def startConsuming(q):
"""Consume an object from the queue and print it.
def consumer(o):
print o

q = defer.DeferredQueue()

Saturday, February 20, 2010

China’s Crises in Tibet and Xinjiang Beijing believes investment is the way out


While those in charge of propaganda work to intoxicate the country with the image of a “harmonious society” at the behest of party leader Hu Jintao, frequent uprisings in China’s western ethnic provinces of Tibet and Xinjiang have, to the embarrassment of officials, laid bare the lie.

In fact, the intensifying social conflicts in the west have pushed China’s teetering stability to the limit.

Official Chinese media reported that a Tibetan protest on March 14, 2008 resulted in 13 deaths and an economic loss of 200 million yuan (US$29 million). Over the following nine months, numerous other protests broke out in Tibet and surrounding areas. ...more ...

Friday, February 19, 2010

create Defered function from non-asynchronous blocking code

def largeFibonnaciNumber():
Represent a long running blocking function by calculating
the TARGETth Fibonnaci number
TARGET = 10000

first = 0
second = 1

for i in xrange(TARGET - 1):
new = first + second
first = second
second = new

return second

from twisted.internet import threads, reactor

def fibonacciCallback(result):
Callback which manages the largeFibonnaciNumber result by
printing it out
print "largeFibonnaciNumber result =", result
# make sure the reactor stops after the callback chain finishes,
# just so that this example terminates

def run():
Run a series of operations, deferring the largeFibonnaciNumber
operation to a thread and performing some other operations after
adding the callback
# get our Deferred which will be called with the largeFibonnaciNumber result
d = threads.deferToThread(largeFibonnaciNumber)
# add our callback to print it out
print "1st line after the addition of the callback"
print "2nd line after the addition of the callback"

if __name__ == '__main__':

python DOM example
xml.dom.minidom — Lightweight DOM implementation

Deferred Reference

This document is a guide to the behaviour of the twisted.internet.defer.Deferred object, and to various ways you can use them when they are returned by functions.

This document assumes that you are familiar with the basic principle that the Twisted framework is structured around: asynchronous, callback-based programming, where instead of having blocking code in your program or using threads to run blocking code, you have functions that return immediately and then begin a callback chain when data is available.

After reading this document, the reader should expect to be able to deal with most simple APIs in Twisted and Twisted-using code that return Deferreds.

* what sorts of things you can do when you get a Deferred from a function call; and
* how you can write your code to robustly handle errors in Deferred code

Deferreds are beautiful! (A Tutorial)


Deferreds are quite possibly the single most confusing topic that a newcomer to Twisted has to deal with. I am going to forgo the normal talk about what deferreds are, what they aren't, and why they're used in Twisted. Instead, I'm going show you the logic behind what they do.

A deferred allows you to encapsulate the logic that you'd normally use to make a series of function calls after receiving a result into a single object. In the examples that follow, I'll first show you what's going to go on behind the scenes in the deferred chain, then show you the deferred API calls that set up that chain. All of these examples are runnable code, so feel free to play around with them.

Linux System Administration and Configuration

Generating Deferreds

twistmatrix python doc

Deferred objects are signals that a function you have called does not yet have the data you want available. When a function returns a Deferred object, your calling function attaches callbacks to it to handle the data when available.

This document addresses the other half of the question: writing functions that return Deferreds, that is, constructing Deferred objects, arranging for them to be returned immediately without blocking until data is available, and firing their callbacks when the data is available.

This document assumes that you are familiar with the asynchronous model used by Twisted, and with using deferreds returned by functions .

Using the Twisted Web Client

This document describes how to use the HTTP client included in Twisted Web. After reading it, you should be able to make HTTP requests using Twisted Web. You will be able to specify the request method, headers, and body and you will be able to retrieve the response code, headers, and body.

Limiting Parallelism

Concurrency can be a great way to speed things up, but what happens when you have too much concurrency? Overloading a system or a network can be detrimental to performance. Often there is a peak in performance at a particular level of concurrency. Executing a particular number of tasks in parallel will be easier than ever with Twisted 2.5 and Python 2.5:

from twisted.internet import defer, task

def parallel(iterable, count, callable, *args, **named):
coop = task.Cooperator()
work = (callable(elem, *args, **named) for elem in iterable)
return defer.DeferredList([coop.coiterate(work) for i in xrange(count)])

Here's an example of using this to save the contents of a bunch of URLs which are listed one per line in a text file, downloading at most fifty at a time:

from twisted.python import log
from twisted.internet import reactor
from twisted.web import client

def download((url, fileName)):
return client.downloadPage(url, file(fileName, 'wb'))

urls = [(url, str(n)) for (n, url) in enumerate(file('urls.txt'))]
finished = parallel(urls, 50, download)
finished.addCallback(lambda ign: reactor.stop())


python twisted Throttling with Cooperator

Example 8: Throttling with Cooperator

from twisted.internet import reactor
from twisted.web.client import getPage
from twisted.internet import defer, task

maxRun = 2

urls = [

def pageCallback(result):
print len(result)
return result

def doWork():
for url in urls:
d = getPage(url)
yield d

def finish(ign):

def test():
deferreds = []
coop = task.Cooperator()
work = doWork()
for i in xrange(maxRun):
d = coop.coiterate(work)
dl = defer.DeferredList(deferreds)


This is the last example for this post, and it's is probably the most arcane :-) This example is taken from JP's blog post from a couple years ago. Our observation in the previous example about the way that the deferreds were created in the for loop and how they were run is now our counter example. What if we want to limit when the deferreds are created? What if we're using deferred semaphore to create 1000 deferreds (but only running them 50 at a time), but running out of file descriptors? Cooperator to the rescue.

This one is going to require a little more explanation :-) Let's see if we can move through the justifications for the strangeness clearly:

1. We need the deferreds to be yielded so that the callback is not created until it's actually needed (as opposed to the situation in the deferred semaphore example where all the deferreds were created at once).
2. We need to call doWork before the for loop so that the generator is created outside the loop. thus making our way through the URLs (calling it inside the loop would give us all four URLs every iteration).
3. We removed the result-processing callback on the deferred list because coop.coiterate swallows our results; if we need to process, we have to do it with pageCallback.
4. We still use a deferred list as the means to determine when all the batches have finished.

This example could have been written much more concisely: the doWork function could have been left in test as a generator expression and test's for loop could have been a list comprehension. However, the point is to show very clearly what is going on.

I hope these examples were informative and provide some practical insight on working with deferreds in your Twisted projects :-)

twisted task and schedule handler

from twisted.internet import task, reactor
import time
def timer():
print time.ctime()
loop = task.LoopingCall(timer)
loop.start(1, now=True)

python urllib2 handle cookies

To handle python cookies in urllib2, it's already provide with new urllib2.

Here is a example to deal with cookies return from http server.
opener = urllib2.build_opener(HTTPCookieProcessor(),HTTPBasicAuthHandler(),HTTPDefaultErrorHandler( ))
opener.addheaders = [('User-agent', 'Mozilla/5.0'),("Content-type", "text/xml; charset=\"UTF-8\"")]

We have register the opener into urllib2, afterward; we can use without worry about handling cookies return.

python conversion unicode to ascii

unicodeStr = something
ascii = unicodeStr.encode('ascii','ignore')

Usage Python twisted

For new page usage:
from twisted.internet import reactor
from twisted.internet.defer import DeferredList

data = "some data for http body"

def responseData(result, factory)
print "Content Length=", len(result)
print "Cookies =", factory.cookies

def failurePage(error)
print 'msg=', error.getErrorMessage()
print 'err=', error

def finished(ign):

d1, factory = getNewPage(url, postdata=data)

dl = DeferredList([d1])
dl.addCallback(responseData, factory)

Đức Đạt Lai Lạt Ma viếng thăm Hoa Kỳ

Đức Đạt Lai Lạt Ma viếng thăm Hoa Kỳ
Đăng ngày: 19-02-2010 lúc 5:26 PM Font size:

Đức Đạt Lai Lạt Ma đã đến Washington hôm thứ Tư, trước một cuộc họp với Tổng thống Hoa Kỳ Barack Obama.

Chế độ cộng sản Trung Quốc đã thúc giục chính quyền của tổng thống Obama hủy bỏ cuộc họp. Họ coi Đức Đạt Lai Lạt Ma như một phần tử ly khai.

Lưu tâm tới sự nhạy cảm của chế độ Trung Quốc, ông Obama đã trì hoãn cuộc họp với Đức Đạt Lai Lạt Ma cho đến sau khi ông gặp những người lãnh đạo Trung Quốc trước trong chuyến công du Châu Á tháng 11 năm ngoái.

Như một cử chỉ nhượng bộ nữa trước Trung Quốc, ông Obama sẽ không tiếp Đức Đạt Lai Lạt Ma tại Phòng Bầu dục của Nhà trắng. Thay vào đó, ông sẽ đón tiếp Ngài ở Phòng Bản đồ, nơi thường được dùng cho các cuộc gặp gỡ mang tính xã hội.

Tin tức Tân Đường Nhân, ngày 18 tháng 02 năm 2010.

Tags : Tin nổi bật
Chuyên mục: Tin thế giới

twisted framework

Modified getPage () to return a factory and deferred, so that we when extract the return cookies.

from twisted.web import client
def getNewPage(url, contextFactory=None, *args, **kwargs):
Download a web page as a string and return clientfactory.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.

See HTTPClientFactory to see what extra args can be passed.
factory = client._makeGetterFactory(url,client.HTTPClientFactory, contextFactory=contextFactory, *args, **kwargs)
return factory.deferred, factory