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

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]

Simulate a (mysql)LIMIT on "MS SQLserver"

return lines from 7995 to 8000 (5 lines)

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

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"]
    )

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)
# visual options of the gui
tabbar.hide.one=0
toolbar.visible=1
tabbar.visible=1
statusbar.visible=1
line.margin.visible=1
line.margin.width=4
buffers=20
buffers.zorder.switching=1

# editing options
braces.check=1
braces.sloppy=1
are.you.sure=1
load.on.activate=1
are.you.sure.on.reload=1
reload.preserves.undo=1

# source-respect options
strip.trailing.spaces=1
tabsize=4
indent.size=4
use.tabs=0
indent.auto=1
indent.opening=1
indent.closing=1
tab.indents=1
backspace.unindents=1
eol.mode=LF
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 :
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

use qemu on ubuntu linux

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

then create a virtual filesystem (to simulate a hdd) (1000000 = 10go), under your home directory
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
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)
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
« Newer Snippets
Older Snippets »
Showing 1-10 of 27 total  RSS