Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 11-20 of 200 total

The zen of python

An easter egg in python.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 

A dynamic form of the class statement.

These 2 methods are equivalent.
# method 1
class X(object):
    a = 1

# method 2
X = type('X', (object,), dict(a=1))

Python % formating

# format % 2
%d     : '2'
%5d    : '    2'
%-5d   : '2    '
%05d   : '00002'
%.2e   : '2.00e+000'
%.2f   : '2.00'

%s     : string, applying str()
%-20s  : left-adjust

Python sorting

list.sort() work in place (doesn't return anything)
If you want a version that return result, use sorted() function.
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()    # become [1, 2, 3, 4, 5]
>>> a.sort(cmp) # same as above

>>> a = "This is a test string from Andrew".split()
>>> a.sort(key=str.lower) # using key is simpler
# ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

>>> import operator 
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# itemgetter allows easy Schwartzian transform

3 equivalent ways
- key=operator.itemgetter(1)
- key=lambda x: x[1]
- cmp=lambda a,b: cmp(a[1], b[1])

Learn more at Sorting Howto.

Getting HTML from Windows clipboard

Get the code for class HtmlClipboard() by Phillip Piper here.

Usage
>>> cb = HtmlClipboard()
>>> cb.GetAvailableFormats()
[49161, 49562, 49339, 49560, 49561, 13, 1, 49334, 49335, 49333, 49344, 49478, 49171, 16, 7]
>>> cb.HasHtmlFormat()
True
>>> cb.GetFromClipboard()
>>> cb.htmlClipboardVersion
'0.9'
>>> cb.GetFragment()
'<p>Writing to the clipboard is <strong>easy</strong> with this code.</p>'
>>> cb.GetSource()
'http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474121'
>>> 

You can also put a html fragment to the clipboard as well.
See more detials in the recipe.

Another simple datetime+struct_time class

I had shown how datetime can be used in python 2.2
in a previous snippet. Still, it's sometimes too big.

Here's a minimal implementation. It works like both
datetime and stuct_time (as returned by localtime() and gmtime()).
import time

class datetime(object):
    def __init__(self, *argv):
        self.t = time.struct_time(argv+(0,)*(9-len(argv)))    # append to length 9 
    def __getattr__(self, name):
        try:
            i = ['year', 'month', 'day', 'hour', 'minute', 'second', 'weekday'].index(name)
            return self.t[i]
        except:
            return getattr(self.t, name)
    def __len__(self): return len(self.t)
    def __getitem__(self, key): return self.t[key]
    def __repr__(self): return repr(self.t)
    def now(self=None):
        return datetime(*time.localtime())
    now = staticmethod(now)
    def strftime(self, fmt="%Y-%m-%d %H:%M:%S"):
        return time.strftime(fmt, self.t)

Here's its usage
# here it works like datetime.datetime()
>>> t = datetime.now()
>>> t.year, t.month, t.day
(2006, 3, 13)
>>> t.hour, t.minute, t.second
(23, 3, 28)

# but also works like localtime()
>>> t
(2006, 3, 13, 23, 3, 28, 0, 72, -1)
>>> t.tm_year, t[0]
(2006, 2006)
>>> mktime(t)
1142265808.0

# good default for strftime (= ctime)
>>> t.strftime()
'2006-03-13 23:03:28'

Get LAST_INSERT_ID from Symbian DBMS

# table schema
# CREATE TABLE person (id COUNTER, name VARCHAR)

db = e32db.Dbms()
db.begin()  # begin transaction (lock other inserts)
db.execute(u"INSERT INTO person(name) VALUES 'korakot' ") # insert a new row

dbv = e32db.Db_view()
dbv.prepare(db, u"SELECT id FROM person ORDER BY id DESC")
dbv.first_line()
dbv.get_line()
last_id = dbv.col(1)  # get it!

db.commit()  # commit the transaction

Keep light on using thread

Copy-paste version
import e32, miso, thread
running = 1
def lighton():
  while running:
    miso.reset_inactivity_time()
    e32.ao_sleep(5)

thread.start_new_thread(lighton, ())
# end by set running = 0


2 functions (lighton, lightoff) version.
import e32
import miso
import thread

flag = 1
def _lighton():
    while flag:
        miso.reset_inactivity_time()
        e32.ao_sleep(5)

def lighton():
    thread.start_new_thread(_lighton, ())

def lightoff():
    global flag
    flag = 0

Simple thread in python

Taken from this article.

import time
import thread

def myfunc(string,sleeptime):
    while 1:
        print string
        time.sleep(sleeptime)

thread.start_new_thread(myfunc,("Thread No:1",2))
# Then do other things.

Create a primary key with autoincrement in Symbian DBMS

CREATE TABLE person (id COUNTER, name VARCHAR)
CREATE UNIQUE INDEX id_index ON person(id)

COUNTER is UNSIGNED INTEGER with Autoincrement.
You still need a UNIQUE INDEX as well.
« Newer Snippets
Older Snippets »
Showing 11-20 of 200 total