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
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
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)
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<title>XHTML Template</title>
</head>
<body>
</body>
</html>
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")
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
because translate and maketrans don't love utf-8 ;-(
import string
french=u"15 résultats trouvés".encode("utf_16")
sfrom = u"à âäéèêëïîôöûùüç".encode("utf_16")
sto = u"aaaeeeeiioouuuc".encode("utf_16")
print french.translate( string.maketrans(sfrom,sto) )
free adaptation of http://slugathon.python-hosting.com/changeset/205
import gtk
import Image
def image2pixbuf(im):
file1 = StringIO.StringIO()
im.save(file1, "ppm")
contents = file1.getvalue()
file1.close()
loader = gtk.gdk.PixbufLoader("pnm")
loader.write(contents, len(contents))
pixbuf = loader.get_pixbuf()
loader.close()
return pixbuf
responding "hello" at http://localhost:8080
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200, 'OK')
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write( "hello" )
@staticmethod
def serve_forever(port):
HTTPServer(('', port), MyServer).serve_forever()
if __name__ == "__main__":
MyServer.serve_forever(8080)
import sqlite
con = sqlite.connect('mydatabase.db')
cur = con.cursor()
#~ cur.execute('CREATE TABLE foo (o_id INTEGER PRIMARY KEY, fruit VARCHAR(20), veges VARCHAR(30))')
#~ con.commit()
cur.execute('INSERT INTO foo (o_id, fruit, veges) VALUES(NULL, "apple", "broccoli")')
con.commit()
print cur.lastrowid
cur.execute('SELECT * FROM foo')
print cur.fetchall()
def mulby2(a):
"""
>>> mulby2(5)
10
"""
return 2*a
import doctest
doctest.testmod()
Singleton with same states
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
a=Borg()
a.toto = 12
b=Borg()
print b.toto
print id(a),id(b) # different ! but states are sames
real Singleton instance
class Singleton(object):
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
a=Singleton()
a.toto = 12
b=Singleton()
print b.toto
print id(a),id(b) # the same !!
CSPyInterpreter* it = CSPyInterpreter::NewInterpreterL();
CleanupStack::PushL(it);
PyEval_RestoreThread(PYTHON_TLS->thread_state);
PyRun_SimpleString("open(r'c:\\foo.txt', 'w').write('hello')\n");
PyEval_SaveThread();
CleanupStack::PopAndDestroy(it);
From <a href=http://discussion.forum.nokia.com/forum/showthread.php?t=55828>Nokia Forum</a>
works well on IE/firefox ... (need to be adapted)
function getDomFromFile(file) {
// Load XML
if (typeof ActiveXObject != 'undefined') {// IE
var xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.load(XML);
}
else { // others
var myXMLHTTPRequest = new XMLHttpRequest();
myXMLHTTPRequest.open("GET", XML, false);
myXMLHTTPRequest.send(null);
var xml = myXMLHTTPRequest.responseXML;
}
return xml;
}
function getDomFromXml(xml) {
if (typeof ActiveXObject != 'undefined') {
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(xml);
}
else {
parser = new DOMParser();
dom = parser.parseFromString(xml, "text/xml");
}
return dom;
}
function xslt(xmlDoc,xslDoc) {
var transform;
if (typeof ActiveXObject != 'undefined') {
transform = xmlDoc.transformNode(xslDoc);
}
else {
var xsl = new XSLTProcessor();
xsl.importStylesheet(xslDoc);
var fragment=xsl.transformToFragment(xmlDoc, document);
if( fragment.childNodes.length>0 )
transform = fragment.childNodes[0].innerHTML;
else
alert("error");
}
return transform;
}
myObject is an instance of a class
myMethod is the name of the method (string)
String [] argNames = new String[ 1 ]; String [] argValues = new String[ 1 ]; argNames[0]="param"; argNames[1]="value"; Type t = myObject.GetType(); t.InvokeMember ( myMethod, BindingFlags.InvokeMethod, null, site, argValues, null, null, argNames);





