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

manatlan http://manatlan.online.fr

« Newer Snippets
Older Snippets »
Showing 1-10 of 28 total  RSS 

Simple Resize PIL Image with python

// description of your code here

   1  
   2  def resize(im,percent):
   3      """ retaille suivant un pourcentage 'percent' """
   4      w,h = im.size
   5      return im.resize(((percent*w)/100,(percent*h)/100))
   6  
   7  def resize2(im,pixels):
   8      """ retaille le coté le plus long en 'pixels' 
   9          (pour tenir dans une frame de pixels x pixels)
  10      """
  11      (wx,wy) = im.size
  12      rx=1.0*wx/pixels
  13      ry=1.0*wy/pixels
  14      if rx>ry:
  15          rr=rx
  16      else:
  17          rr=ry
  18  
  19      return im.resize((int(wx/rr), int(wy/rr)))
  20  

Decode html entities

use like this :

print decode_htmlentities("l'eau")

   1  
   2  from htmlentitydefs import name2codepoint as n2cp
   3  import re
   4  
   5  def substitute_entity(match):
   6      ent = match.group(2)
   7      if match.group(1) == "#":
   8          return unichr(int(ent))
   9      else:
  10          cp = n2cp.get(ent)
  11  
  12          if cp:
  13              return unichr(cp)
  14          else:
  15              return match.group()
  16  
  17  def decode_htmlentities(string):
  18      entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")
  19      return entity_re.subn(substitute_entity, string)[0]

Simulate a (mysql)LIMIT on "MS SQLserver"

return lines from 7995 to 8000 (5 lines)

   1  
   2  select * from (
   3  select top 5 * from 
   4  (select top 8000 * from TABLE order by 1 asc) as tbl1 order by 1 desc 
   5  ) as tbl2 order by 1 asc

python : send a mail (text), with attachments

   1  
   2  import smtplib
   3  from email.MIMEMultipart import MIMEMultipart
   4  from email.MIMEBase import MIMEBase
   5  from email.MIMEText import MIMEText
   6  from email.Utils import COMMASPACE, formatdate
   7  from email import Encoders
   8  import os
   9  
  10  def sendMail(to, subject, text, files=[],server="localhost"):
  11      assert type(to)==list
  12      assert type(files)==list
  13      fro = "Expediteur <expediteur@mail.com>"
  14  
  15      msg = MIMEMultipart()
  16      msg['From'] = fro
  17      msg['To'] = COMMASPACE.join(to)
  18      msg['Date'] = formatdate(localtime=True)
  19      msg['Subject'] = subject
  20  
  21      msg.attach( MIMEText(text) )
  22  
  23      for file in files:
  24          part = MIMEBase('application', "octet-stream")
  25          part.set_payload( open(file,"rb").read() )
  26          Encoders.encode_base64(part)
  27          part.add_header('Content-Disposition', 'attachment; filename="%s"'
  28                         % os.path.basename(file))
  29          msg.attach(part)
  30  
  31      smtp = smtplib.SMTP(server)
  32      smtp.sendmail(fro, to, msg.as_string() )
  33      smtp.close()
  34  
  35  
  36  sendMail(
  37          ["destination@dest.kio"],
  38          "hello","cheers",
  39          ["photo.jpg","memo.sxw"]
  40      )
  41  

SciTE, my "good default options"

They should be default options of SciTE (good for python too)
just put them in your scite user properties (menu > options > open user properties)
   1  
   2  # visual options of the gui
   3  tabbar.hide.one=0
   4  toolbar.visible=1
   5  tabbar.visible=1
   6  statusbar.visible=1
   7  line.margin.visible=1
   8  line.margin.width=4
   9  buffers=20
  10  buffers.zorder.switching=1
  11  
  12  # editing options
  13  braces.check=1
  14  braces.sloppy=1
  15  are.you.sure=1
  16  load.on.activate=1
  17  are.you.sure.on.reload=1
  18  reload.preserves.undo=1
  19  
  20  # source-respect options
  21  strip.trailing.spaces=1
  22  tabsize=4
  23  indent.size=4
  24  use.tabs=0
  25  indent.auto=1
  26  indent.opening=1
  27  indent.closing=1
  28  tab.indents=1
  29  backspace.unindents=1
  30  eol.mode=LF
  31  eol.auto=1

A simple python class to browse snippets website (with beautifoulsoup)

if you got some path/enhancements, you can mail me at my pseudo at gmail.com, i'll update it.
(you should install the marvellous beautifulsoup module, http://www.crummy.com/software/BeautifulSoup/documentation.html)

the snippets.py file :
   1  
   2  from BeautifulSoup import BeautifulSoup
   3  import urllib
   4  
   5  class Keyword: # top tags
   6      def __init__(self,tag,nb):
   7          self.tag=tag
   8          self.nb=int(nb)
   9      def __repr__(self):
  10          return "<Keyword '%s' : %d>" % (self.tag,self.nb)
  11  
  12  class Snippet:
  13      def __init__(self,title,code,tags):
  14          self.title=title
  15          self.code=code
  16          self.tags = tags
  17      def __repr__(self):
  18          return "<Snippet '%s' : tags %s>" % (self.title,str(self.tags))
  19  
  20  class Snippets:
  21      urlForTags = "http://www.bigbold.com/snippets/tags"
  22      
  23      def __init__(self,l=[]):
  24          url = self.__getUrlForTags(l)
  25          
  26          #load the url
  27          fu = urllib.urlopen(url)
  28          content = fu.read()
  29          fu.close()
  30  
  31          self.tags = l
  32          self.keywords,self.snippets = self.__extractContent(content)
  33  
  34      def __repr__(self):
  35          return "<Snippets for tags:%s>" % (str(self.tags))
  36  
  37      def __getUrlForTags(self, l ):
  38          assert type(l)==list
  39          l = [Snippets.urlForTags] + l
  40          return "/".join(l)
  41      
  42      def __extractContent(self,content):
  43          
  44          soup = BeautifulSoup( content ) 
  45              
  46          # get the keywords
  47          tagTable=soup('div', {'id' : "sidebar"})[0].table
  48          keywords=[]
  49          for i in tagTable("tr"):
  50              td = i("td")
  51              
  52              # add this keyword
  53              try:
  54                  # extract from the empty selection page "/tags"
  55                  keywords.append( Keyword(td[1].span.a.string , td[0].string) )
  56              except TypeError:
  57                  # extract from a selected selection page "/tag/something"
  58                  keywords.append( Keyword(td[2].span.a.string , td[1].string) )
  59          
  60          # get the snippets
  61          postList=soup('div', {'class' : "post"})
  62          snippets=[]
  63          for i in postList:
  64              divs = i("div")
  65              
  66              # get title and tags
  67              title =  divs[0].h3.a.string # title
  68              tags = [j.string for j in divs[1]("a")][:-1] #don't get the user ;-)
  69  
  70              # get code of the snippet
  71              list = [j for j in divs[0]][1:]# zap the first (h3)
  72              code=""
  73              for i in list: 
  74                  try:
  75                      if i.name == "pre":
  76                          try:
  77                              code+=i.string
  78                          except TypeError:
  79                              pass
  80                  except AttributeError:
  81                      # transform "out-pre-text" in comment
  82                      out = str(i).strip()
  83                      if out:
  84                          code+="#| "+out+"\n" 
  85              
  86              # add this snippet
  87              snippets.append( Snippet(title,code,tags) )
  88              
  89          return keywords,snippets


and an example (all returned "strings" are in utf-8):
   1  
   2  from snippets import Snippets
   3  
   4  s = Snippets(["python","xml"])
   5  print s
   6  print s.keywords # the "top tags" column
   7  for i in s.snippets:
   8      print i
   9  print s.snippets[6].title # the title of the 6th
  10  print s.snippets[6].code  # the code of the 6th

use qemu on ubuntu linux

you must install qemu first ... run this :
   1  
   2  sudo apt-get install qemu

then create a virtual filesystem (to simulate a hdd) (1000000 = 10go), under your home directory
   1  
   2  dd of=hd.img bs=1024 seek=1000000 count=0

put a bootable cd (or an "iso-file") in your cd drive (win2k, xp, linux live-cd, ...), and run
   1  
   2  qemu -hda /home/[your_name]/hd.img -cdrom /dev/hdd -boot d -m 512 -user-net

option -hda = the virtual disk to use (~/hd.img)
option -m = memory to use (512 mo).
option -cdrom = cd-drive (/dev/hdd for me) (or an iso file)
option -boot = which drive to boot (d as the cdrom)
option -user-net : net user mode (see http://fabrice.bellard.free.fr/qemu/qemu-doc.html#SEC21)

and it's run like a charm ...impressive

python : simplest http server with cherrypy

taken from http://www.cherrypy.org/wiki/CherryPyTutorial
in the browser, return a "Hello world!" at http://localhost:8080(/index)
   1  
   2  from cherrypy import cpg
   3  
   4  class HelloWorld:
   5  
   6      @cpg.expose
   7      def index(self):
   8          return "Hello world!"
   9  
  10  cpg.root = HelloWorld()
  11  cpg.server.start()

python : call an unknow method with named params

myObject is an instance of a class
myMethod is the name of the method (string)
myArgs is a dict for named arguments

   1  
   2  if hasattr(myObject,myMethod):
   3      try:
   4          retValue = getattr(myObject,myMethod)(*(),**(myArgs))
   5      except TypeError:
   6          # arguments mismatch
   7  else:
   8      # there is no "myMethod" method in myObject

python : ensure script is executed in its folder path

could be a good start for a new script
   1  
   2  #!/usr/bin/env python
   3  # -*- coding: utf-8 -*-
   4  import os,sys
   5  
   6  if __name__ == "__main__":
   7      _path = os.path.split(sys.argv[0])[0]
   8      if _path: os.chdir(_path)
« Newer Snippets
Older Snippets »
Showing 1-10 of 28 total  RSS