DZone 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
  • submit to reddit

Python Snippets

  • ElementTree
  • XML
  • Python
                    ElementTree is becoming python's standard XML framework.
It also supports processing data as it coming/loading.
<code>
import cElementTree

for event, elem in cElementTree.iterparse(file):
    if elem.tag == "record":
        ... process record element ...
        elem.clear()
</code>                
  • expression
  • in
  • regular
  • Python
                    // code contains regular expression for contact number and email address in python

<code>
str='[email protected]'
match=re.search(r'\w+@\w+',str) #return [email protected]
num=555-555-555
match_num=re.search(r'^(\d{3}--\d{3}--\d{4})$',num) #return 555-555-5555
</code>                
  • formating
  • String
  • Python
  • percent
  • format
                    // description of your code here

<code>
# format % 2
%d     : '2'
%5d    : '    2'
%-5d   : '2    '
%05d   : '00002'
%.2e   : '2.00e+000'
%.2f   : '2.00'

%s     : string, applying str()
%-20s  : left-adjust
</code>                
  • mock
  • zope
  • Python
                    Given a Zope interface IFoo, the method below creates a Mock (<a href="http://www.voidspace.org.uk/python/mock">http://www.voidspace.org.uk/python/mock</a>) subclass IFooMock that properly implements IFoo.

See <a href="http://programmaticallyspeaking.com/?p=30">http://programmaticallyspeaking.com/?p=30</a> for more info.

<code>
from mock import Mock
from zope.interface import classImplements
import types

def create_interface_mock(interface_class):
    """Dynamically create a Mock sub class that implements the given Zope interface class."""

    # the init method, automatically specifying the interface methods
    def init(self, *args, **kwargs):
        Mock.__init__(self, spec=interface_class.names(),
                      *args, **kwargs)

    # we derive the sub class name from the interface name
    name = interface_class.__name__ + "Mock"

    # create the class object and provide the init method
    klass = types.TypeType(name, (Mock, ), {"__init__": init})

    # the new class should implement the interface
    classImplements(klass, interface_class)

    # make the class available to unit tests
    globals()[name] = klass
</code>                
  • XSLT
  • XML
  • windows
  • web
  • URL
  • Unix
  • time
  • Text
  • String
  • SQL
  • Sinatra
  • shell
  • series60
  • rubyonrails
  • Ruby
  • rscript
  • rexml
  • regex
  • REBOL
  • raoni
  • Rails
  • Python
  • php
  • Perl
  • OSX
  • MySQL
  • math
  • Linux
  • jsfromhell
  • JOnAS
  • javascript
  • java
  • image
  • http
  • html
  • hash
  • Google
  • find
  • file
  • date
  • Database
  • css
  • csharp
  • convert
  • C++
  • C
  • bash
  • Array
  • apache
  • ActiveRecord
                    // Month Day Year Smart Dropdowns

<code>
function mdy($mid = "month", $did = "day", $yid = "year", $mval, $dval, $yval)
	{
		if(empty($mval)) $mval = date("m");
		if(empty($dval)) $dval = date("d");
		if(empty($yval)) $yval = date("Y");
		
		$months = array(1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May", 6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October", 11 => "November", 12 => "December");
		$out = "<select name='$mid' id='$mid'>";
		foreach($months as $val => $text)
			if($val == $mval) $out .= "<option value='$val' selected>$text</option>";
			else $out .= "<option value='$val'>$text</option>";
		$out .= "</select> ";

		$out .= "<select name='$did' id='$did'>";
		for($i = 1; $i <= 31; $i++)
			if($i == $dval) $out .= "<option value='$i' selected>$i</option>";
			else $out .= "<option value='$i'>$i</option>";
		$out .= "</select> ";

		$out .= "<select name='$yid' id='$yid'>";
		for($i = date("Y"); $i <= date("Y") + 2; $i++)
			if($i == $yval) $out.= "<option value='$i' selected>$i</option>";
			else $out.= "<option value='$i'>$i</option>";
		$out .= "</select>";
		
		return $out;
	}
</code>
                
  • AST
  • Python
  • template
                    

<code>

def template(self):
    '<h1>'; self.title ; '</h1>'
    '<ul>'
    for itm in self.items:
        '<li>'; str(itm); '</li>'
    '</ul>'
</code>                
  • Python
  • WSGI
  • async
                    // согласно информации отсюда: http://bottlepy.org/docs/dev/async.html, ожидалось, что данный код будет демонстрировать асинчхронное поведение, что оказалось не правдой. UPDATE: проблема решена. Дело в том, что "Some browsers buffer a certain amount of data before they start rendering a page. You might need to yield more than a few bytes to see an effect in these browsers."

<code>
from gevent.pywsgi import WSGIServer
import gevent
from gevent import monkey; monkey.patch_all()

def hello_world(env, start_response):
    #import ipdb; ipdb.set_trace()
    if env['PATH_INFO'] == '/':
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield 'qwerty'
        gevent.sleep(5)
        yield "<b>hello world</b>"
    else:
        start_response('404 Not Found', [('Content-Type', 'text/html')])
        yield '<h1>Not Found</h1>'

print 'Serving on 8088...'
WSGIServer(('', 8088), hello_world).serve_forever()
</code>                
  • artist
  • title
  • song
  • regex
  • Python
                    Extract the artist and the title of the song from a string formatted as: ARTIST - TITLE.EXT
This code strips the extension, splits the string, trims each part and capitalize it correctly (fixed pythons string.title() bug for handling apostrophes)

<code>
#filename = "rihanna - please don't stop the music.pdf"
artist, title = [re.sub("([a-zA-Z])'([A-Z])", lambda m: m.group(1) + "'" + m.group(2).lower(), t.strip().title()) for t in filename[:filename.rfind('.')].split('-')]
</code>                
  • extension
  • filename
  • path
  • Python
  • os

Strip Extension

Snippets Manager on 06/21/11 in Python
                    Get only the filename part of a string without the need to use os.path.splitext

<code>
def get_filename(path):
	return path[:path.rfind('.')]
</code>                
  • PAGE
  • Python
  • count
  • pdf
  • regex

Count PDF Pages

Snippets Manager on 06/21/11 in Python
                    Returns the number of pages in a PDF file

<code>
import re

def count_pdf_pages(path):
	pattern = re.compile("<<.*?Page.*?>>", re.MULTILINE)
	file = open(path, 'rb')
	content = f.read()
	file .close()
	return len(pattern.findall(content))
</code>