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

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

Python - Query BabelFish

//Example di POST HTTP

   1  
   2  #!/usr/bin/python
   3  
   4  import urllib
   5  
   6  def translate(lang='it_en', text='ciao'):
   7  	
   8  	'''Converte delle frasi da una lingua sorgente ad una lingua destinazione'''
   9  
  10  	url = urllib.URLopener()
  11  	
  12  	query = urllib.urlencode({'doit':'done', 'intl':'1', 'lp':lang, 'tt':'urltext', 'urltext':text})
  13  	
  14  	responde = url.open('http://babelfish.altavista.com/tr', query).read()
  15  
  16  	start = responde.find('<div style=padding:10px;>') + 25
  17  	stop = responde.find('</div>', start)
  18  
  19  	print responde[start:stop]

Python - Copy List

// Copiare una Lista

   1  
   2  a = [1, 2, 3]
   3  b = a[:]

Python - eggs

1)

import __hello__

2)

from __future__ import braces

Get mobile cpu speed

   1  
   2  import miso
   3  print miso.get_hal_attr(11)  # 104000 for my 6600

Get LAST_INSERT_ID from Symbian DBMS

   1  
   2  # table schema
   3  # CREATE TABLE person (id COUNTER, name VARCHAR)
   4  
   5  db = e32db.Dbms()
   6  db.begin()  # begin transaction (lock other inserts)
   7  db.execute(u"INSERT INTO person(name) VALUES 'korakot' ") # insert a new row
   8  
   9  dbv = e32db.Db_view()
  10  dbv.prepare(db, u"SELECT id FROM person ORDER BY id DESC")
  11  dbv.first_line()
  12  dbv.get_line()
  13  last_id = dbv.col(1)  # get it!
  14  
  15  db.commit()  # commit the transaction

Keep light on using thread

Copy-paste version
   1  
   2  import e32, miso, thread
   3  running = 1
   4  def lighton():
   5    while running:
   6      miso.reset_inactivity_time()
   7      e32.ao_sleep(5)
   8  
   9  thread.start_new_thread(lighton, ())
  10  # end by set running = 0


2 functions (lighton, lightoff) version.
   1  
   2  import e32
   3  import miso
   4  import thread
   5  
   6  flag = 1
   7  def _lighton():
   8      while flag:
   9          miso.reset_inactivity_time()
  10          e32.ao_sleep(5)
  11  
  12  def lighton():
  13      thread.start_new_thread(_lighton, ())
  14  
  15  def lightoff():
  16      global flag
  17      flag = 0

PyS60 - Gallery Thumbnail Ver. 2

// Versione riveduta e corretta di Gallery Thumbnail postata da korakot ^_^

   1  
   2  import appuifw
   3  import e32
   4  import graphics
   5  import key_codes
   6  import os
   7  
   8  class FlickrS60Error(Exception): pass
   9  
  10  class FlickrS60Thumb:
  11  
  12  	def __init__(self, path):
  13  
  14  		self.path = unicode(path)
  15  		self.listFile = []
  16  		self.ldivx = 0
  17  		self.ldivy = 0
  18  		self.lock = e32.Ao_lock()
  19  		self.canvas = None
  20  		self.img = graphics.Image.new((176, 144))
  21  		self.img_tmp = graphics.Image.new((42, 36))
  22  		self.x, self.y = 0, 0
  23  		self.p = 0
  24  		self.pages = 0
  25  		self.currpages = 0
  26  		self.mpath = 0
  27  
  28  	def OnRun(self):
  29  
  30  		appuifw.app.exit_key_handler = self.lock.signal
  31  	
  32  		self._createList()
  33  		
  34  		self.canvas = appuifw.Canvas(redraw_callback=self.OnUpdate)
  35  		appuifw.app.body = self.canvas
  36  
  37  		self.canvas.bind(key_codes.EKeyRightArrow, lambda: self.move(1, 0))
  38  		self.canvas.bind(key_codes.EKeyLeftArrow, lambda: self.move(-1, 0))
  39  		self.canvas.bind(key_codes.EKeyUpArrow, lambda: self.move(0, -1))
  40  		self.canvas.bind(key_codes.EKeyDownArrow, lambda: self.move(0, 1))
  41  		self.canvas.bind(key_codes.EKeySelect, self.IMG)
  42  
  43  		self._drawIMG()
  44  		
  45  		self.lock.wait()
  46  
  47  	def OnUpdate(self, rect):
  48  
  49  		self.canvas.blit(self.img)
  50  		self.canvas.rectangle([(self.p+(42*self.x), 36*self.y), (self.p+(42*self.x)+42, (36*self.y)+36)], width=2, outline=0x123456)
  51  
  52  	def move(self, x, y):
  53  
  54  		self.x = (self.x+x)%4
  55  		self.y = (self.y+y)
  56  
  57  		if x == 1: self.p = (self.p+2)%8
  58  		if x == -1: self.p = (self.p-2)%8
  59  
  60  		if self.y == 4:
  61  			if self.currpages < self.pages-1:
  62  				self.y = 0
  63  				self.currpages += 1
  64  				self._drawIMG(start=self.currpages)
  65  			else:
  66  				self.y = 3
  67  			
  68  		if self.y == -1:
  69  			if self.currpages > 0:
  70  				self.y = 3
  71  				self.currpages -= 1
  72  				self._drawIMG(start=self.currpages)
  73  			else:
  74  				self.y = 0
  75  	
  76  		self.mpath = (4*self.y + self.x)+(16*self.currpages)
  77  		
  78  		self.OnUpdate(None)
  79  	
  80  	def IMG(self):
  81  
  82  		try:
  83  			m = self.listFile[self.mpath].replace('_PalbTN\\', '')
  84  			appuifw.Content_handler().open(m)
  85  		except:
  86  			pass
  87  		
  88  	def _drawIMG(self, start=0):
  89  
  90  		self.img.clear(0xffffff)
  91  		z = 0
  92  		
  93  		for id in range(start*16, (start+1)*16):
  94  			j, i = divmod(id-(start*16), 4)
  95  			try:
  96  				self.img_tmp.load(self.listFile[id])
  97  				self.img.blit(self.img_tmp, target=(z+(42*i)+(z+1), 36*j))
  98  				z = (z+1)%4
  99  			except:
 100  				break
 101  
 102  		self.OnUpdate(None)
 103  
 104  	def _createList(self):
 105  
 106  		try:
 107  			for id in os.listdir(self.path):
 108  				self.listFile.append(self.path + id)
 109  
 110  			self.ldivx, self.ldivy = divmod(len(self.listFile), 16)
 111  
 112  			self.pages = self.ldivx
 113  			if self.ldivy <> 0: self.pages += 1
 114  		except:
 115  			raise FlickrS60Error('Errore nella creazione della lista.')
 116  
 117  if __name__ == '__main__':
 118  
 119  	FlickrS60Thumb('E:\\Images\\_PalbTN\\').OnRun()
 120  

Gallery thumbnails

   1  
   2  from appuifw import *
   3  from graphics import Image
   4  from key_codes import *
   5  #from status import *
   6  #from e32db import format_time
   7  import os, e32
   8  
   9  dir = u'C:\\Nokia\\Images\\_PAlbTN\\'
  10  os.chdir(dir)
  11  fs = os.listdir('')
  12  mtime = os.path.getmtime
  13  # newest first
  14  fs.sort(lambda a,b: cmp(mtime(b), mtime(a)))
  15  
  16  app.body = canvas = Canvas()
  17  # show just 16 images
  18  for k in range(min(16, len(fs))):
  19      j, i = divmod(k, 4)
  20      im = Image.open(dir + fs[k])
  21      canvas.blit(im, target=(2+44*i, 2+34*j))
  22  canvas.rectangle([(0,0), (43,33)], 0xff, width=2)  # selected
  23  
  24  x, y, k = 0, 0, 0
  25  def move(dx, dy):
  26      global x, y, k
  27      canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xffffff, width=2)  
  28      k = 4*y + x + 4*dy + dx
  29      y, x = divmod(k, 4)
  30      canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xff, width=2)
  31      if 0 <= k < len(fs):
  32          app.title = u''+fs[k]
  33          #status_on(format_time(mtime(fs[k])))
  34  
  35  # move cursor and open image
  36  canvas.bind(EKeyUpArrow,   lambda: move(0,-1))
  37  canvas.bind(EKeyDownArrow, lambda: move(0,1))
  38  canvas.bind(EKeyLeftArrow, lambda: move(-1,0))
  39  canvas.bind(EKeyRightArrow,lambda: move(1,0))
  40  canvas.bind(EKeySelect,    lambda: Content_handler().open(dir[:-8]+fs[k]))
  41  
  42  # standard code for non-loop app
  43  lock = e32.Ao_lock()
  44  app.exit_key_handler = lock.signal
  45  lock.wait()

ORM for pys60

I have asked for this a few months.
Here's my own first version for an ORM.
It's adapted from SQLAlchemy and SQLObject.
(and whatever library I have searched)

You need to create a database manually first.
My previous snippets (shell, SQL) may help.
   1  
   2  from __future__ import generators
   3  import e32db, re
   4  db = e32db.Dbms()
   5  dbv = e32db.Db_view()
   6  db.open(u'C:\\test.db')
   7  
   8  # Some helping classes (need more in next version)
   9  class String:
  10      pass
  11  
  12  class Integer:
  13      pass
  14  
  15  class Float:
  16      pass
  17  
  18  class column:
  19      def __init__(self, coltype):
  20          self.coltype = coltype

Here's the mother of all your classes that map to database tables.
   1  
   2  class Mapper(object):
   3      def __init__(self, id=None, **kw):
   4          if id is None:
   5              self.id = self._insert(**kw)
   6          else:
   7              self.id = id
   8      def _insert(self, **kw):
   9          names = ','.join(kw.keys())
  10          values = ','.join([self.quote(k,v) for k,v in kw.items()])
  11          tablename = self.__class__.__name__
  12          q = u"INSERT INTO %s(%s) VALUES (%s)" % (tablename, names, values)
  13          db.execute(q)
  14          # get last insert ID
  15          dbv.prepare(db, u'SELECT id FROM '+tablename+' ORDER BY id DESC')
  16          dbv.first_line()
  17          dbv.get_line()
  18          return dbv.col(1)
  19      def __getattr__(self, name):
  20          if name in self.mapping.__dict__:
  21              q = 'SELECT '+name+' FROM '+self.__class__.__name__
  22              q += ' WHERE id='+str(self.id)
  23              dbv.prepare(db, unicode(q))
  24              dbv.first_line()
  25              dbv.get_line()
  26              return dbv.col(1)
  27          else:
  28              return self.__dict__[name]
  29      def __repr__(self):
  30          return '<%s id=%d>' % (self.__class__.__name__, self.id)
  31      def quote(self, name, value):
  32          if self.mapping.__dict__[name].coltype == String:
  33              return "'%s'" % value.replace("'", "''")  # encode single quote
  34          else:
  35              return str(value)
  36      def __setattr__(self, name, value):
  37          if name in self.mapping.__dict__:
  38              q = 'UPDATE '+self.__class__.__name__+' SET '+name+'='
  39              q += self.quote(name, value) + " WHERE id=" + str(self.id)
  40              db.execute(unicode(q))
  41          else:
  42              self.__dict__[name] = value
  43      def set(self, **kw):
  44          q = "UPDATE "+self.__class__.__name__+" SET "
  45          for k, v in kw.items():
  46              q += k+'='+self.quote(k,v)+','
  47          q = q[:-1]+" WHERE id=%s" % self.id
  48          db.execute(unicode(q))
  49      def delete(self):
  50          q = 'DELETE FROM '+self.__class__.__name__+" WHERE id=" + str(self.id)
  51          db.execute(unicode(q))
  52          self.id = None
  53      def dict(self):
  54          names = [k for k in self.mapping.__dict__.keys() if not k.startswith('__')]
  55          q = 'SELECT '+','.join(names)+' FROM '+self.__class__.__name__
  56          q += ' WHERE id=' + str(self.id)
  57          dbv.prepare(db, unicode(q))
  58          dbv.first_line()
  59          dbv.get_line()
  60          dct = {'id': self.id}
  61          for i in range(dbv.col_count()):
  62              dct[names[i]] = dbv.col(i+1)
  63          return dct
  64      def select(cls, where=None, orderby=None):
  65          q = 'SELECT id FROM '+cls.__name__
  66          if where:
  67              q += ' WHERE '+where
  68          if orderby:
  69              q += ' ORDER BY '+orderby
  70          dbv = e32db.Db_view()  # need its own cursor
  71          dbv.prepare(db, unicode(q))
  72          dbv.first_line()
  73          for i in range(dbv.count_line()):
  74              dbv.get_line()
  75              yield cls(dbv.col(1))
  76              dbv.next_line()
  77      select = classmethod(select)

Here's how you create your class.
   1  
   2  class Person(Mapper):
   3      class mapping:
   4          # doesn't need id = column(Integer)
   5          name = column(String)
   6          age = column(Integer)

Getting phone model

I put Korakot snippet (Looking up phone model using firmware code) into an useful module.

You need miso module.
All info can be found at this site

   1  
   2  #
   3  # Firmware.py  infos found at http://homepage.mac.com/alvinmok/nokia/firmware.html
   4  #
   5  
   6  '''
   7  firmware.prefix_name 
   8  firmware.suffix_name 
   9  firmware.phone_model
  10  firmware.phone_cpu_speed
  11  '''
  12  import sysinfo
  13  import miso
  14  
  15  ECPUSpeed = 0x0B
  16  
  17  mapping_firmware_model={
  18    'RM-51': '3230',
  19    'RM-38': '3250',
  20    'NHM-10': '3600',
  21    'NHM-10X': '3620',
  22    'NHL-8': '3650',
  23    'NHL-8X': '3660',
  24    'RM-25': '6260',
  25    'RM-29': '6260b',
  26    'NHL-10': '6600',
  27    'NHL-12': '6620',
  28    'NHL-12X': '6620',
  29    'RM-1': '6630',
  30    'RH-67': '6670',
  31    'RH-68': '6670b',
  32    'RM-36': '6680',
  33    'RM-57': '6681',
  34    'RM-58': '6682',
  35    'RH-51': '7610',
  36    'RH-52': '7610b',
  37    'NHL-2NA': '7650',
  38    'RM-49': 'E60-1',
  39    'RM-89': 'E61-1',
  40    'RM-10': 'E70-1',
  41    'RM-24': 'E70-?',
  42    'NEM-4': 'N-Gage',
  43    'RH-29': 'N-Gage QD (asia/europe)',
  44    'RH-47': 'N-Gage QD (americas)',
  45    'RM-84': 'N70-1',
  46    'RM-99': 'N70-5',
  47    'RM-67': 'N71-1',
  48    'RM-112': 'N71-5',
  49    'RM-91': 'N80-3',
  50    'RM-92': 'N80-1',
  51    'RM-42': 'N90-1',
  52    'RM-43': 'N91-1',
  53    'RM-158': 'N91-5' }
  54  
  55  mapping_prefix_description ={
  56   'N':'Mobile Phone',
  57   'R':'Computing Device',
  58   'T':'Terminal'}
  59  
  60  mapping_suffix_description ={
  61      'B': 'GSM 900/1900',
  62      'C': 'DAMPS 800',
  63      'D': 'CDMA/AMPS 800',
  64      'E': 'GSM 900/1800',
  65      'F': 'NMT-450',
  66      'K': 'GSM 1800',
  67      'L': 'GSM 900/1800/1900 or GSM 850/1800/1900',
  68      'M': 'EGSM 900/1800 (may include WCDMA)',
  69      'N': 'IEEE 802.11b',
  70      'P': 'CDMA 800',
  71      'W': 'AMPS/TDMA 800/1900',
  72      'X': 'ETACS/TACS'}
  73  
  74  sw = sysinfo.sw_version()
  75  sw_list = sw.split(' ')
  76  
  77  firmware_version = sw_list[1]
  78  firmware_date = sw_list[2]
  79  firmware_code=sw_list[3]
  80  
  81  temp = firmware_code.split('-')
  82  firmware_prefix = temp[0][0]
  83  firmware_suffix = temp[0][-1]
  84  
  85  prefix_name = mapping_prefix_description[firmware_prefix]
  86  suffix_name = mapping_suffix_description[firmware_suffix]
  87  phone_model = mapping_firmware_model[firmware_code] 
  88  phone_cpu_speed = miso.get_hal_attr(ECPUSpeed) # CPU speed in Hz


usage:
   1  
   2  >>>import firmware
   3  >>>firmware.phone_model
   4  >>>'6600'
   5  >>>firmware.phone_cpu_speed
   6  >>>104000

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