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 22 total  RSS 

Simple Resize PIL Image with python

// description of your code here

def resize(im,percent):
    """ retaille suivant un pourcentage 'percent' """
    w,h = im.size
    return im.resize(((percent*w)/100,(percent*h)/100))

def resize2(im,pixels):
    """ retaille le coté le plus long en 'pixels' 
        (pour tenir dans une frame de pixels x pixels)
    """
    (wx,wy) = im.size
    rx=1.0*wx/pixels
    ry=1.0*wy/pixels
    if rx>ry:
        rr=rx
    else:
        rr=ry

    return im.resize((int(wx/rr), int(wy/rr)))

Decode html entities

use like this :

print decode_htmlentities("l'eau")

from htmlentitydefs import name2codepoint as n2cp
import re

def substitute_entity(match):
    ent = match.group(2)
    if match.group(1) == "#":
        return unichr(int(ent))
    else:
        cp = n2cp.get(ent)

        if cp:
            return unichr(cp)
        else:
            return match.group()

def decode_htmlentities(string):
    entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")
    return entity_re.subn(substitute_entity, string)[0]

python : send a mail (text), with attachments

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

def sendMail(to, subject, text, files=[],server="localhost"):
    assert type(to)==list
    assert type(files)==list
    fro = "Expediteur <expediteur@mail.com>"

    msg = MIMEMultipart()
    msg['From'] = fro
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(fro, to, msg.as_string() )
    smtp.close()


sendMail(
        ["destination@dest.kio"],
        "hello","cheers",
        ["photo.jpg","memo.sxw"]
    )

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 :
from BeautifulSoup import BeautifulSoup
import urllib

class Keyword: # top tags
    def __init__(self,tag,nb):
        self.tag=tag
        self.nb=int(nb)
    def __repr__(self):
        return "<Keyword '%s' : %d>" % (self.tag,self.nb)

class Snippet:
    def __init__(self,title,code,tags):
        self.title=title
        self.code=code
        self.tags = tags
    def __repr__(self):
        return "<Snippet '%s' : tags %s>" % (self.title,str(self.tags))

class Snippets:
    urlForTags = "http://www.bigbold.com/snippets/tags"
    
    def __init__(self,l=[]):
        url = self.__getUrlForTags(l)
        
        #load the url
        fu = urllib.urlopen(url)
        content = fu.read()
        fu.close()

        self.tags = l
        self.keywords,self.snippets = self.__extractContent(content)

    def __repr__(self):
        return "<Snippets for tags:%s>" % (str(self.tags))

    def __getUrlForTags(self, l ):
        assert type(l)==list
        l = [Snippets.urlForTags] + l
        return "/".join(l)
    
    def __extractContent(self,content):
        
        soup = BeautifulSoup( content ) 
            
        # get the keywords
        tagTable=soup('div', {'id' : "sidebar"})[0].table
        keywords=[]
        for i in tagTable("tr"):
            td = i("td")
            
            # add this keyword
            try:
                # extract from the empty selection page "/tags"
                keywords.append( Keyword(td[1].span.a.string , td[0].string) )
            except TypeError:
                # extract from a selected selection page "/tag/something"
                keywords.append( Keyword(td[2].span.a.string , td[1].string) )
        
        # get the snippets
        postList=soup('div', {'class' : "post"})
        snippets=[]
        for i in postList:
            divs = i("div")
            
            # get title and tags
            title =  divs[0].h3.a.string # title
            tags = [j.string for j in divs[1]("a")][:-1] #don't get the user ;-)

            # get code of the snippet
            list = [j for j in divs[0]][1:]# zap the first (h3)
            code=""
            for i in list: 
                try:
                    if i.name == "pre":
                        try:
                            code+=i.string
                        except TypeError:
                            pass
                except AttributeError:
                    # transform "out-pre-text" in comment
                    out = str(i).strip()
                    if out:
                        code+="#| "+out+"\n" 
            
            # add this snippet
            snippets.append( Snippet(title,code,tags) )
            
        return keywords,snippets


and an example (all returned "strings" are in utf-8):
from snippets import Snippets

s = Snippets(["python","xml"])
print s
print s.keywords # the "top tags" column
for i in s.snippets:
    print i
print s.snippets[6].title # the title of the 6th
print s.snippets[6].code  # the code of the 6th

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)
from cherrypy import cpg

class HelloWorld:

    @cpg.expose
    def index(self):
        return "Hello world!"

cpg.root = HelloWorld()
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

if hasattr(myObject,myMethod):
    try:
        retValue = getattr(myObject,myMethod)(*(),**(myArgs))
    except TypeError:
        # arguments mismatch
else:
    # 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys

if __name__ == "__main__":
    _path = os.path.split(sys.argv[0])[0]
    if _path: os.chdir(_path)

python : redirect exceptions hook

import sys, traceback, string

def myExceptHook(type, value, tb):
   sys.__excepthook__(type, value, tb)
   lines = traceback.format_exception(type, value, tb)
   print string.join(lines)

sys.excepthook = myExceptHook

python : send a mail (text)

import smtplib
from email.MIMEText import MIMEText

def sendTextMail(to,sujet,text,server="localhost"):
    fro = "Expediteur <expediteur@mail.com>"
    mail = MIMEText(text)
    mail['From'] = fro
    mail['Subject'] =sujet
    mail['To'] = to
    smtp = smtplib.SMTP(server)
    smtp.sendmail(fro, [to], mail.as_string())
    smtp.close()
    
sendTextMail("toto@titi.com","hello","cheers")

play with set (new python 2.4 module)

a = set("ABC")
b = set("CDE")

print "A:",a
print "B:",b
print "Intersection:\t",a & b
print "Union:\t\t",a | b
print "Diff a-b:\t\t",a - b
print "Diff b-a:\t\t",b - a
print "Exclusive:\t\t",a ^ b
« Newer Snippets
Older Snippets »
Showing 1-10 of 22 total  RSS