Archive for Tag "python"

Python urlencode for unicode string

// python urlencode usually throws error when encoding unicode string, here's the tricks

import types,urllib
def unicode_urlencode(value):
    if type(value) is types.UnicodeType:
        return urllib.quote(value.encode("utf-8"))
    else:
        return urllib.quote(value)

It Must Have Been Love -- In Python

// print the lyric of "it must have been love", by roxette, in python

print "\n".join(["It must have been %s,but %s" % i for i in map(lambda x:(('love',"It's over now"),('good','I lost it somehow'))[x%2],range(3))])

Mandelbrot

// description of your code here

print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)

Python Factorial One Liner

// factorial, one liner

map(lambda n:(lambda f:f(f,n))(lambda f,n:{True:lambda:1,False:lambda:n*f(f,n-1)}[n<=1]()),range(0,20))

Offline Access Facebook Apps (infinite session) in Appengine Webapp

// demonstrate how to get infinite session from facebook apps

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import urllib
import facebook

FACEBOOK_API_KEY='..'
FACEBOOK_SECRET_KEY='..'

class FacebookPage(webapp.RequestHandler):
  def get(self):
    fb = Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY, 
      callback_path=self.request.path)
    auth_token = self.request.get('auth_token')
    #got auth_token, get temporary session
    if auth_token:
      try:
        fb.auth_token = auth_token
        fb.auth.getSession()
      except:
        self.redirect(fb.get_login_url(next=self.request.url, canvas=False))
    else:
      #not authenticated yet, redirect to facebook login URL
      return self.redirect(fb.get_login_url(next=self.request.url, canvas=False))
    
    #now we have a live session
    #we can get her basic info
    user_info = self.facebook.users.getInfo([self.facebook.uid], ['name', 'pic_square'])[0]

    #check for offline access permission
    permission_link = None
    if not self.facebook.users.hasAppPermission('offline_access'):
      params = {
        'api_key':FACEBOOK_API_KEY,
        'ext_perm':'offline_access,status_update,read_stream',
        'next':self.request.url,
        'cancel':self.request.url,
      }
      permission_link = "http://www.facebook.com/connect/prompt_permissions.php?%s" % urllib.urlencode(params)
    else:
      #got permission, save her session for future use
      if fb.session_key_expires == 0:
        user = User(uid=fb.uid, session_key=fb.session_key)
        user.put()
    
    self.response.out.write(template.render(
      'facebook_page.html', {
        'permission_link':permission_link, 
        'user_info':user_info})

Python RC4 Cipher

// RC4 implementation in python

def rc4crypt(data, key):
    x = 0
    box = range(256)
    for i in range(256):
        x = (x + box[i] + ord(key[i % len(key)])) % 256
        box[i], box[x] = box[x], box[i]
    x,y = 0, 0
    out = []
    for char in data:
        x = (x + 1) % 256
        y = (y + box[x]) % 256
        box[x], box[y] = box[y], box[x]
        out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
    return ''.join(out)

Python convert datetime to unix timestamp

// convert a datetime object into unix timestamp

import calendar
import datetime
now = datetime.datetime.now()
timestamp = calendar.timegm(now)
print now, timestamp

Python Valentine Code

// description of your code here

print "\n".join([" ".join(["valentine"[0:n] for n in t]).center(9) for t in [(3,3),(9,)] + map(lambda n: (n,), range(9,0,-2))])

Adding key_name when saving appengine djangoforms

// You cannot set key_name for models in appengine's djangoforms
// Now you can!

form = TagForm(request.POST or None, instance=tag)
errors = form.errors
if not errors:
  try:
    tag = form.save(commit=False)
  except ValueError, err:
    errors['__all__'] = unicode(err)
  if not errors:
    key_name = 'tag:%s' % tag.name
    saved_tag = Tag(key_name=key_name, **dict([(prop, getattr(tag, prop)) for prop in Tag.properties()]))
    saved_tag.save()

Simple Tag Clouds

// simple tagclouds

import math
for t in tags:
  print t.name, t.count, int(math.ceil(5 * math.log(t.count, math.e)))

Django Filter Terbilang

// Django filter to say indonesian number

from django import template

register = template.Library()

def terbilang(value):
	value = int(value)
	bunyi = ""
	satuan = ("", "satu", "dua", "tiga", "empat", "lima", "enam","tujuh","delapan","sembilan","sepuluh", "sebelas")
	if value >= 0 and value < 12:
		bunyi = ' ' + satuan[value]
	if value >= 12 and value < 20:
		bunyi = terbilang(value%10) + ' belas'
	if value >= 20 and value < 100:
		bunyi = terbilang(value/10) + ' puluh' + terbilang(value%10)
	if value >= 100 and value < 200:
		bunyi = ' seratus' + terbilang(value - 100)
	if value >= 200 and value < 1000:
		bunyi = terbilang(value/100) + ' ratus' + terbilang(value%100)
	if value >= 1000 and value < 2000:
		bunyi = ' seribu' + terbilang(value - 1000)
	if value >= 2000 and value < 1000000:
		bunyi = terbilang(value / 1000) + ' ribu' + terbilang(value % 1000)
	if value >= 1000000 and value < 1000000000:
		bunyi = terbilang(value/1000000) + ' juta' + terbilang(value % 1000000)
	return bunyi

register.filter('terbilang', terbilang)

Terbilang (biasanya Rupiah)

Fungsi terbilang untuk membuat kwitansi atau Invoice.

def terbilang(n):
	bunyi = ""
	satuan = ("", "satu", "dua", "tiga", "empat", "lima", "enam","tujuh","delapan","sembilan","sepuluh", "sebelas")
	if n >= 0 and n < 12:
		bunyi = ' ' + satuan[n]
	if n >= 12 and n < 20:
		bunyi = terbilang(n%10) + ' belas'
	if n >= 20 and n < 100:
		bunyi = terbilang(n/10) + ' puluh' + terbilang(n%10)
	if n >= 100 and n < 200:
		bunyi = ' seratus' + terbilang(n - 100)
	if n >= 200 and n < 1000:
		bunyi = terbilang(n/100) + ' ratus' + terbilang(n%100)
	if n >= 1000 and n < 2000:
		bunyi = ' seribu' + terbilang(n - 1000)
	if n >= 2000 and n < 1000000:
		bunyi = terbilang(n / 1000) + ' ribu' + terbilang(n % 1000)
	if n >= 1000000 and n < 1000000000:
		bunyi = terbilang(n/1000000) + ' juta' + terbilang(n % 1000000)
	return bunyi
	
if __name__ == '__main__':
	for a in (1,4,9,11,19,32,20,99,100,999, 999999, 1000000, 2535000):
		print str(a), ' => ', terbilang(a)

	

Unique Fields on Google Appengine djangoforms.ModelForm

// this is how i check for dupes

def isUnique(form, field, data):
    """Validates that a value is unique for a field.
    """
    if not isinstance(form, djangoforms.ModelForm):
        raise TypeError, u'The instance passed to isUnique is not a subclass of djangoforms.ModelForm'

    model = form._meta.model
    matching_obj = model.gql("WHERE " + field + " = :1", data).get()
    if not matching_obj:
        return data

    if form.instance and form.instance.key() == matching_obj.key():
        return data
    
    raise forms.ValidationError(u'%(optname)s with this %(fieldname)s already exists.' % {'optname':model.kind(), 'fieldname':field})

//how to use this

class TagForm(djangoforms.ModelForm):
    def clean_name(self):
        if 'name' in self.clean_data:
            value = self.clean_data['name'].strip()
            if value:
                return isUnique(self, 'name', value)
        raise forms.ValidationError('Name is required')
    class Meta:
        model = models.Tag

antigravity

// module antigravity

import webbrowser
webbrowser.open("http://xkcd.com/353/")

Django Cache Decorator

// simple decorator for caching result

from django.core.cache import cache

def cached(cache_key):
    """Cache decorator
    """
    def doCache(func):
        def _get_cached(*args, **kwargs):
            result = cache.get(cache_key)
            if result is None:
                result = func(*args, **kwargs)
                cache.set(cache_key, result)

            return result
        return _get_cached
    return doCache

def delete_cached(cache_key):
    """Delete cache decorator
    """
    def doDeleteCache(func):
        def _delete_cached(*args, **kwargs):
            result = func(*args, **kwargs)
            cache.delete(cache_key)
            return result
        return _delete_cached
    return doDeleteCache

// you can use this decorator into your models.
// for example

from google.appengine.ext import db
class Tag(db.Model):
    """The snippet tags
    """
    name = db.StringProperty()
    description = db.TextProperty()
    entrycount = db.IntegerProperty(default=0)
    
    @staticmethod
    @cached('tags')
    def getall():
        return [tag for tag in Tag.all()]

    @delete_cached('tags')
    def save(self):
        """Will save the current tag and invalidate the cache automatically"""
        self.put()
  
    @delete_cached('tags')
    def remove(self):
        self.delete()

Pidgin/Gaim Status Logger Python

"""
Plugin that log buddies status on Pidgin/Gaim
"""

#!/usr/bin/env python

import logging
import dbus
import gobject
from dbus.mainloop.glib import DBusGMainLoop

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s\t%(message)s",
                    filename='/var/log/pidgin_status.log',
                    filemode='a')

dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")

status_hash = {}

def update_status_hash(username, status):
    global status_hash
    if status_hash.has_key[username] and status_hash[username] == status:
        return False
    status_hash[username] = status
    return True

def buddy_status_changed(buddy, old_status, status):
    alias = purple.PurpleBuddyGetAlias(buddy)
    name = purple.PurpleBuddyGetName(buddy)
    status_id = purple.PurpleStatusGetId(status)
    status_text = purple.PurpleStatusGetAttrString(status, "message")
    if status_text and update_status_hash(alias, status_text):
        s = "%s\t%s" % (alias, status_text)
        logging.info(s)

def show_all_status():
    for account in purple.PurpleAccountsGetAllActive():
        for buddy in purple.PurpleFindBuddies(account, ""):
            alias = purple.PurpleBuddyGetAlias(buddy)
            name = purple.PurpleBuddyGetName(buddy)
            presence = purple.PurpleBuddyGetPresence(buddy)
            status = purple.PurplePresenceGetActiveStatus(presence)
            status_id = purple.PurpleStatusGetId(status)
            status_text = purple.PurpleStatusGetAttrString(status, "message")
            if status_text and update_status_hash(alias, status_text):
                s = "%s - %s" % (alias, status_text)
                logging.info(s)

bus.add_signal_receiver(buddy_status_changed, 
    dbus_interface="im.pidgin.purple.PurpleInterface", 
    signal_name="BuddyStatusChanged")

gobject.MainLoop().run()

Fulltext Search on appengine models

// fulltext search support on appengine models

from google.appengine.ext import search

class Tag(search.SearchableModel):
    """The snippet tags
    """
    name = db.StringProperty()
    description = db.TextProperty()

// then, use it like this

for tag in Tag.all().search("sometag").order('name').fetch(10):
  print tag.name

python convert text to html entities

from htmlentitydefs import codepoint2name

def htmlentities(u):
    result = []
    for c in u:
        if ord(c) < 128:
            result.append(c)
        else:
            result.append('&%s;' % codepoint2name[ord(c)])
    return ''.join(result)

Open browser in python

import webbrowser, sys, os
def openurl(self, url):
  try:
    webbrowser.open(url)
  except ImportError: # pre-webbrowser.py compatibility
    if sys.platform == 'win32':
      os.system('start "%s"' % url)
    elif sys.platform == 'mac':
      try: import ic
      except ImportError: pass
      else: ic.launchurl(url)
    else:
      rc = os.system('netscape -remote "openURL(%s)" &' % url)
      if rc: os.system('netscape "%s" &' % url)

check if python running compiled or source in py2exe

def isfrozen():
    import imp
    return (hasattr(sys, "frozen") or # new py2exe
            hasattr(sys, "importers") or # old py2exe
            imp.is_frozen("__main__")) # tools/freeze