rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if pathname[0] == '/':
if pathname and pathname[0] == '/':
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local conventio...
if pathname[-1] == '/':
if pathname and pathname[-1] == '/':
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local conventio...
self.capabilities = tuple(string.split(self.untagged_responses[cap][-1]))
self.capabilities = tuple(string.split(string.upper(self.untagged_responses[cap][-1])))
def __init__(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_respo...
XXX When wrapping around and failing to find anything, the portion of the text after the selection is searched twice :-(
def search_text(self, text, prog=None, ok=0): """Search a text widget for the pattern.
i, j = m.span()
def search_backward(self, text, prog, line, col, wrap, ok=0): chars = text.get("%d.0" % line, "%d.0" % (line+1)) while 1: m = search_reverse(prog, chars[:-1], col) if m: i, j = m.span() if ok or m.start() < col: return line, m line = line - 1 ok = 1 if line <= 0: if not wrap: break wrap = 0 pos = text.index("end-1c") l...
'sys_prefix': sysconfig.PREFIX, 'sys_exec_prefix': sysconfig.EXEC_PREFIX,
'sys_prefix': prefix, 'prefix': prefix, 'sys_exec_prefix': exec_prefix, 'exec_prefix': exec_prefix,
def finalize_options (self):
server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)]
client_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', client_version)]
def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-agent', server_version)] # manage the individual handlers self.handlers = [] self.handle_open = {} self.handle_error = {} self.process_response = {} self.process_request = {}
('build_platlib', 'build_dir'), ('install_platlib', 'install_dir'))
('build_lib', 'build_dir'), ('install_lib', 'install_dir'))
def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir'))
elif os.name == 'windows': if verbose: print string.join (cmd, ' ') if not dry_run: os.spawnv (os.P_WAIT, cmd[0], cmd[1:])
elif os.name in ( 'nt', 'windows' ): _spawn_nt (cmd, search_path, verbose, dry_run)
def spawn (cmd, search_path=1, verbose=0, dry_run=0): """Run another program, specified as a command list 'cmd', in a new process. 'cmd' is just the argument list for the new process, ie. cmd[0] is the program to run and cmd[1:] are the rest of its arguments. There is no way to run a program with a name different fr...
pass
__dynamic__ = 0
def dynamics(): if verbose: print "Testing __dynamic__..." verify(object.__dynamic__ == 0) verify(list.__dynamic__ == 0) class S1: __metaclass__ = type verify(S1.__dynamic__ == 0) class S(object): pass verify(S.__dynamic__ == 0) class D(object): __dynamic__ = 1 verify(D.__dynamic__ == 1) class E(D, S): pass verify(E.__...
pass
__dynamic__ = 0
def rich_comparisons(): if verbose: print "Testing rich comparisons..." class Z(complex): pass z = Z(1) verify(z == 1+0j) verify(1+0j == z) class ZZ(complex): def __eq__(self, other): try: return abs(self - other) <= 1e-6 except: return NotImplemented zz = ZZ(1.0000003) verify(zz == 1+0j) verify(1+0j == zz) class clas...
class C(complex): pass
class C(complex): __dynamic__ = 0
def coercions(): if verbose: print "Testing coercions..." class I(int): pass coerce(I(0), 0) coerce(0, I(0)) class L(long): pass coerce(L(0), 0) coerce(L(0), 0L) coerce(0, L(0)) coerce(0L, L(0)) class F(float): pass coerce(F(0), 0) coerce(F(0), 0L) coerce(F(0), 0.) coerce(0, F(0)) coerce(0L, F(0)) coerce(0., F(0)) clas...
fin = open(self.tmpin, 'wb')
fin = open(self.tmpin, 'w')
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
fin = open(self.tmpin, 'rb')
fin = open(self.tmpin, 'r')
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
uu.encode(self.tmpin, self.tmpout, mode=0644)
uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644)
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close()
f = open(self.tmpin, 'wb')
f = open(self.tmpin, 'w')
def test_decode(self): try: f = open(self.tmpin, 'wb') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close()
f = open(self.tmpin, 'rb')
f = open(self.tmpin, 'r')
def test_decode(self): try: f = open(self.tmpin, 'wb') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close()
f = open(self.tmpin, 'rb')
f = open(self.tmpin, 'r')
def test_decodetwice(self): # Verify that decode() will refuse to overwrite an existing file try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout))
cdll.load('libGL.so', mode=RTLD_GLOBAL) cdll.load('libGLU.so')
if os.path.exists('/usr/lib/libGL.so'): cdll.load('libGL.so', mode=RTLD_GLOBAL) if os.path.exists('/usr/lib/libGLU.so'): cdll.load('libGLU.so')
def test_GL(self): cdll.load('libGL.so', mode=RTLD_GLOBAL) cdll.load('libGLU.so')
if not edit: if cmd: sys.argv = ["-c"] + args else: sys.argv = args or [""]
def main(): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(sys.argv[1:], "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-e': edit = 1 if o == '-...
root = Tk()
root = Tk(className="Idle")
def main(): cmd = None edit = 0 debug = 0 startup = 0 try: opts, args = getopt.getopt(sys.argv[1:], "c:deist:") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) for o, a in opts: if o == '-c': cmd = a if o == '-d': debug = 1 if o == '-e': edit = 1 if o == '-...
self._ent_handler.resolveEntity(publicId, systemId)
return self._ent_handler.resolveEntity(publicId, systemId)
def resolveEntity(self, publicId, systemId): self._ent_handler.resolveEntity(publicId, systemId)
fp.write("\t\taetools.enumsubst(_arguments, %s, _Enum_%s)\n" %
if ename <> '****': fp.write("\t\taetools.enumsubst(_arguments, %s, _Enum_%s)\n" %
fp.write("\tdef %s(self, "%funcname)
designed so that you can specifiy a list of potential
designed so that you can specify a list of potential
def read(self, filenames):
self.create_exe(arcname, fullname)
self.create_exe(arcname, fullname, self.bitmap)
def run (self): if (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform")
title = self.distribution.get_fullname()
title = self.title or self.distribution.get_fullname()
def get_inidata (self): # Return data describing the installation.
def create_exe (self, arcname, fullname):
def create_exe (self, arcname, fullname, bitmap=None):
def create_exe (self, arcname, fullname): import struct
header = struct.pack("<ii", 0x12345679, len(cfgdata))
header = struct.pack("<iii", 0x1234567A, len(cfgdata), bitmaplen, )
def create_exe (self, arcname, fullname): import struct
AAAA8AAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1v ZGUuDQ0KJAAAAAAAAABwj7aMNO7Y3zTu2N807tjfT/LU3zXu2N+38tbfNu7Y39zx3N827tjfVvHL 3zzu2N807tnfae7Y3zTu2N857tjf3PHS3znu2N+M6N7fNe7Y31JpY2g07tjfAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAUEUAAEwBAwAu6+E5AAAAAAAAAADgAA8BCwEGAABAAAAAEAAAAJAAAPDUAAAA oAAAAOAAAAAA...
AAAA4AAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1v ZGUuDQ0KJAAAAAAAAABwr7eMNM7Z3zTO2d80ztnfT9LV3zXO2d+30tffNs7Z39zR3d82ztnfVtHK 3zzO2d80ztjfVM7Z3zTO2d85ztnf3NHT3znO2d+MyN/fNc7Z31JpY2g0ztnfAAAAAAAAAABQRQAA TAEDAG/hkDoAAAAAAAAAAOAADwELAQYAAEAAAAAQAAAAkAAAwNUAAACgAAAA4AAAAABAAAAQAAAA AgAABAAAAAAA...
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
bGwgUmlnaHRzIFJlc2VydmVkLiAkCgBVUFghDAkCCl/uS+s25ddS0bYAAO40AAAAsAAAJgEAkP+/ /f9TVVaLdCQUhfZXdHaLfAi9EHBAAIA+AHRoalxWbP/29v8V/GANi/BZHll0V4AmAFcRmP833//Y g/v/dR5qD5SFwHUROUQkHHQLV9na//9VagX/VCQog8QM9sMQdR1otwAAJJD/T9itg10cACHGBlxG dZNqAVhfXu/u/v9dW8NVi+yD7AxTVleLPXguM/a7OsA5dQjt7d39dQfHRQgBDFZogE0RVlZTBfsz 9v8M/9eD+P+J...
bGwgUmlnaHRzIFJlc2VydmVkLiAkCgBVUFghDAkCCqpen60jTE6a87YAALo1AAAAsAAAJgcAZP/b //9TVVaLdCQUhfZXdH2LbCQci3wMgD4AdHBqXFb/5vZv/xUIYUAAi/BZHVl0X4AmAFcReGD9v/n+ 2IP7/3Unag98hcB1E4XtdA9XaBBw/d/+vw1qBf/Vg8QM6wdXagEJWVn2wxB1HGi3ABOyna0ALYAp Dcb3/3/7BlxGdYssWF9eXVvDVYvsg+wMU1ZXiz2ILe/uf3cz9rs5wDl1CHUHx0UIAQxWaIBMsf9v bxFWVlMFDP/X...
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
eGl0AABFbmRQYWludAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
eGl0AABHZXREQwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
def get_exe_bytes (self): import base64 return base64.decodestring(EXEDATA)
self.__frame.grid(row=3, column=0, ipadx=5)
self.__frame.grid(row=3, column=0, ipadx=5, sticky='NSEW')
def __init__(self, switchboard, master=None): self.__sb = switchboard self.__frame = Frame(master, relief=RAISED, borderwidth=1) self.__frame.grid(row=3, column=0, ipadx=5) # create the chip that will display the currently selected color # exactly self.__sframe = Frame(self.__frame) self.__sframe.grid(row=0, column=0) ...
elif os.sep == ':': sitedirs = [os.path.join(prefix, "lib", "site-packages")]
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dir...
sitedirs = [prefix]
sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dir...
pass
if self.include_dirs is None: self.include_dirs = self.distribution.include_dirs or [] elif type(self.include_dirs) is StringType: self.include_dirs = string.split(self.include_dirs, os.pathsep) if self.libraries is None: self.libraries = [] elif type(self.libraries) is StringType: self.libraries = [self.libraries] i...
def finalize_options (self): pass
y.__dict__.update(state)
if hasattr(y, '__setstate__'): y.__setstate__(state) else: y.__dict__.update(state)
def _reconstruct(x, info, deep, memo=None): if isinstance(info, str): return x assert isinstance(info, tuple) if memo is None: memo = {} n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args, memo) y = callable(*args) if state: if deep: state...
except socket.err, exc:
except socket.error, exc:
def test_timeout(): test_support.requires('network') if test_support.verbose: print "test_timeout ..." # A service which issues a welcome banner (without need to write # anything). # XXX ("gmail.org", 995) has been unreliable so far, from time to time # XXX non-responsive for hours on end (& across all buildbot slave...
f = open('/dev/null', 'wb')
if sys.platform[:3]=="win": f = open('nul', 'wb') else: f = open('/dev/null', 'wb')
def main(): VERBOSE = 0 opts, args = getopt.getopt(sys.argv[1:], 'vq') for k, v in opts: if k == '-v': VERBOSE = 1 visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1 if k == '-q': f = open('/dev/null', 'wb') sys.stdout = f if not args: print "no files to compile" else: for filename in args: if VERBOSE: print f...
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
def page(self, title, contents): """Format an HTML page.""" return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return '''
<p><table width="100%%" cellspacing=0 cellpadding=2 border=0>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
def section(self, title, fgcol, bgcol, contents, width=10, prelude='', marginalia=None, gap='&nbsp;&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '<tt>' + '&nbsp;' * width + '</tt>' result = '''
return '<table width="100%%"><tr>%s</tr></table>' % result
return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
def multicolumn(self, list, format, cols=4): """Format a list of items into a multi-column list.""" result = '' rows = (len(list)+cols-1)/cols for col in range(cols): result = result + '<td width="%d%%" valign=top>' % (100/cols) for i in range(rows*col, rows*col+rows): if i < len(list): result = result + format(list[i]...
decl = '<em>lambda</em>'
title = '<strong>%s</strong> <em>lambda</em> ' % name
def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): imclass ...
decl_re = re.compile(r"coding[=:]\s*([-\w.]+)")
import sys, os, re
def walk_python_files(self, paths, *args, **kwargs): for path in paths: if os.path.isfile(path): yield path.endswith(".py") elif os.path.isdir(path): for root, dirs, files in os.walk(path): for filename in files: if filename.endswith(".py"): yield os.path.join(root, filename)
def get_declaration(line): match = decl_re.search(line) if match: return match.group(1) return ''
binary_re = re.compile('[\x00-\x08\x0E-\x1F\x7F]')
def get_declaration(line): match = decl_re.search(line) if match: return match.group(1) return ''
def has_correct_encoding(text, codec):
debug = False def print_debug(msg): if debug: print msg def _open(fullpath):
def has_correct_encoding(text, codec): try: unicode(text, codec) except UnicodeDecodeError: return False else: return True
unicode(text, codec) except UnicodeDecodeError:
size = os.stat(fullpath).st_size except OSError, err: print_debug("%s: permission denied: %s" % (fullpath, err)) return None if size > 1024*1024: print_debug("%s: the file is too big: %d bytes" % (fullpath, size)) return None try: return open(fullpath, 'rU') except IOError, err: print_debug("%s: access denied: %s" % ...
def has_correct_encoding(text, codec): try: unicode(text, codec) except UnicodeDecodeError: return False else: return True
else:
line = infile.readline() infile.close() if binary_re.search(line): print_debug("%s: appears to be binary" % fullpath) return False if fullpath.endswith(".py") or fullpath.endswith(".pyw"): return True elif "python" in line:
def has_correct_encoding(text, codec): try: unicode(text, codec) except UnicodeDecodeError: return False else: return True
def needs_declaration(fullpath):
return False def can_be_compiled(fullpath): infile = _open(fullpath) if infile is None: return False code = infile.read() infile.close()
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() ret...
infile = open(fullpath, 'rU') except IOError: return None
compile(code, fullpath, "exec") except Exception, err: print_debug("%s: cannot compile: %s" % (fullpath, err)) return False
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() ret...
line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): infile.close() return False rest = infile.read() infile.close() if has_correct_encoding(line1+line2+rest, "ascii"): return False
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() ret...
usage = """Usage: %s [-cd] paths... -c: recognize Python source files trying to compile them -d: debug output""" % sys.argv[0]
def walk_python_files(paths, is_python=looks_like_python, exclude_dirs=None): """\ Recursively yield all Python source files below the given paths.
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() ret...
try: opts, args = getopt.getopt(sys.argv[1:], 'cd') except getopt.error, msg: print >>sys.stderr, msg print >>sys.stderr, usage sys.exit(1) is_python = pysource.looks_like_python debug = False for o, a in opts: if o == '-c': is_python = pysource.can_be_compiled elif o == '-d': debug = True if not args: print >>sys.s...
paths: a list of files and/or directories to be checked. is_python: a function that takes a file name and checks whether it is a Python source file exclude_dirs: a list of directory base names that should be excluded in the search """ if exclude_dirs is None: exclude_dirs=[] for path in paths: print_debug("testing: %s...
def needs_declaration(fullpath): try: infile = open(fullpath, 'rU') except IOError: # Oops, the file was removed - ignore it return None line1 = infile.readline() line2 = infile.readline() if get_declaration(line1) or get_declaration(line2): # the file does have an encoding declaration, so trust it infile.close() ret...
library_dirs=None):
library_dirs=None, build_info=None):
def link_shared_lib (self, objects, output_libname, libraries=None, library_dirs=None): """Link a bunch of stuff together to create a shared library file. Has the same effect as 'link_static_lib()' except that the filename inferred from 'output_libname' will most likely be different, and the type of file generated wil...
library_dirs=None):
library_dirs=None, build_info=None):
def link_shared_object (self, objects, output_filename, libraries=None, library_dirs=None): """Link a bunch of stuff together to create a shared object file. Much like 'link_shared_lib()', except the output filename is explicitly supplied as 'output_filename'.""" pass
def object_filenames (source_filenames):
def object_filenames (self, source_filenames):
def object_filenames (source_filenames): """Return the list of object filenames corresponding to each specified source filename.""" pass
def shared_object_filename (source_filename):
def shared_object_filename (self, source_filename):
def shared_object_filename (source_filename): """Return the shared object filename corresponding to a specified source filename.""" pass
def library_filename (libname):
def library_filename (self, libname):
def library_filename (libname): """Return the static library filename corresponding to the specified library name.""" pass
def shared_library_filename (libname):
def shared_library_filename (self, libname):
def shared_library_filename (libname): """Return the shared library filename corresponding to the specified library name.""" pass
class ListTestCase(unittest.TestCase):
class BaseTestCase(unittest.TestCase):
def __index__(self): return self.ind
self.seq = [0,10,20,30,40,50]
def setUp(self): self.seq = [0,10,20,30,40,50] self.o = oldstyle() self.n = newstyle() self.o2 = oldstyle() self.n2 = newstyle()
def test_basic(self): self.o.ind = -2 self.n.ind = 2 assert(self.seq[self.n] == 20) assert(self.seq[self.o] == 40) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2) def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' myfunc = lambda x, obj: obj.seq[x] self.failUnlessRaises(TypeError, op...
def setUp(self): self.seq = [0,10,20,30,40,50] self.o = oldstyle() self.n = newstyle() self.o2 = oldstyle() self.n2 = newstyle()
class UnicodeTestCase(unittest.TestCase): def setUp(self): self.seq = u"this is a test" self.o = oldstyle() self.n = newstyle() self.o2 = oldstyle() self.n2 = newstyle()
def test_wrappers(self): n = self.n n.ind = 5 assert n.__index__() == 5 assert 6 .__index__() == 6 assert -7L.__index__() == -7 assert self.seq.__getitem__(n) == self.seq[5] assert self.seq.__mul__(n) == self.seq * 5 assert self.seq.__rmul__(n) == self.seq * 5 def test_infinite_recusion(self): class Trap1(int): def __...
def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 assert(self.seq[self.o:self.o2] == self.seq[1:3]) assert(self.seq[self.n:self.n2] == self.seq[2:4])
def test_basic(self):
class ListTestCase(BaseTestCase): seq = [0,10,20,30,40,50] def test_setdelitem(self):
def test_basic(self): self.o.ind = -2 self.n.ind = 2 assert(self.seq[self.n] == self.seq[2]) assert(self.seq[self.o] == self.seq[-2]) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2)
assert(self.seq[self.n] == self.seq[2]) assert(self.seq[self.o] == self.seq[-2]) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2)
lst = list('ab!cdefghi!j') del lst[self.o] del lst[self.n] lst[self.o] = 'X' lst[self.n] = 'Y' assert lst == list('abYdefghXj')
def test_basic(self): self.o.ind = -2 self.n.ind = 2 assert(self.seq[self.n] == self.seq[2]) assert(self.seq[self.o] == self.seq[-2]) assert(operator.index(self.o) == -2) assert(operator.index(self.n) == 2)
def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' myfunc = lambda x, obj: obj.seq[x] self.failUnlessRaises(TypeError, operator.index, self.o) self.failUnlessRaises(TypeError, operator.index, self.n) self.failUnlessRaises(TypeError, myfunc, self.o, self) self.failUnlessRaises(TypeError, myfunc, self.n, self)
lst = [5, 6, 7, 8, 9, 10, 11] lst.__setitem__(self.n, "here") assert lst == [5, 6, "here", 8, 9, 10, 11] lst.__delitem__(self.n) assert lst == [5, 6, 8, 9, 10, 11]
def test_error(self): self.o.ind = 'dumb' self.n.ind = 'bad' myfunc = lambda x, obj: obj.seq[x] self.failUnlessRaises(TypeError, operator.index, self.o) self.failUnlessRaises(TypeError, operator.index, self.n) self.failUnlessRaises(TypeError, myfunc, self.o, self) self.failUnlessRaises(TypeError, myfunc, self.n, self)
def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 assert(self.seq[self.o:self.o2] == self.seq[1:3]) assert(self.seq[self.n:self.n2] == self.seq[2:4])
def test_inplace_repeat(self): self.o.ind = 2 self.n.ind = 3 lst = [6, 4] lst *= self.o assert lst == [6, 4, 6, 4] lst *= self.n assert lst == [6, 4, 6, 4] * 3 lst = [5, 6, 7, 8, 9, 11] l2 = lst.__imul__(self.n) assert l2 is lst assert lst == [5, 6, 7, 8, 9, 11] * 3 class TupleTestCase(BaseTestCase): seq = (0,10,20,...
def test_slice(self): self.o.ind = 1 self.o2.ind = 3 self.n.ind = 2 self.n2.ind = 4 assert(self.seq[self.o:self.o2] == self.seq[1:3]) assert(self.seq[self.n:self.n2] == self.seq[2:4])
UnicodeTestCase
UnicodeTestCase, XRangeTestCase,
def test_main(): test_support.run_unittest( ListTestCase, TupleTestCase, StringTestCase, UnicodeTestCase )
self.write('<OBJECT type="text/sitemap">\n') self.tab('\t<param name="Local" value="%s/%s">\n' % (self.path, href))
self.hrefstack.append(href)
def anchor_bgn(self, href, name, type): if self.proc: self.saved_clear() self.write('<OBJECT type="text/sitemap">\n') self.tab('\t<param name="Local" value="%s/%s">\n' % (self.path, href))
self.tab('\t<param name="Name" value="%s">\n' % self.saved_get()) self.tab('\t</OBJECT>\n')
title = cgi.escape(self.saved_get(), True) path = self.path + '/' + self.hrefstack.pop() if len(self.hrefstack) == 0: self.tab(object_sitemap % (title, path))
def anchor_end(self): if self.proc: self.tab('\t<param name="Name" value="%s">\n' % self.saved_get()) self.tab('\t</OBJECT>\n')
output.write(object_sitemap % (book.directory + "/" + book.firstpage, book.title))
path = book.directory + "/" + book.firstpage output.write('<LI>') output.write(object_sitemap % (book.title, path))
def do_content(library, version, output): output.write(contents_header % version) for book in library: print '\t', book.title, '-', book.firstpage output.write(object_sitemap % (book.directory + "/" + book.firstpage, book.title)) if book.contentpage: content(book.directory, book.contentpage, output) output.write(conten...
Retrieves a list of addresses from a header, where each address is a tuple as returned by getaddr(). """ try: data = self[name] except KeyError: return [] a = AddrlistClass(data)
Retrieves a list of addresses from a header, where each address is a tuple as returned by getaddr(). Scans all named headers, so it works properly with multiple To: or Cc: headers for example. """ raw = [] for h in self.getallmatchingheaders(name): if h[0] in ' \t': raw.append(h) else: if raw: raw.append(', ') i = st...
def getaddrlist(self, name): """Get a list of addresses from a header. Retrieves a list of addresses from a header, where each address is a tuple as returned by getaddr(). """ # New, by Ben Escoto try: data = self[name] except KeyError: return [] a = AddrlistClass(data) return a.getaddrlist()
self.CR = '\r'
self.CR = '\r\n'
def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r' self.atomends = self.specials + self.LWS + self.CR self.field = field self.commentlist = []
if node.nodeType==Node.ELEMENT_NODE and self.documentElement: raise TypeError, "Two document elements disallowed" else: self.documentElement=node
if node.nodeType==Node.ELEMENT_NODE: if self.documentElement: raise TypeError, "Two document elements disallowed" else: self.documentElement=node
def appendChild( self, node ): if node.nodeType==Node.ELEMENT_NODE and self.documentElement: raise TypeError, "Two document elements disallowed" else: self.documentElement=node Node.appendChild( self, node ) return node
import poll if map is None: map = socket_map if timeout is not None: timeout = int(timeout*1000) if map: l = [] for fd, obj in map.items(): flags = 0 if obj.readable(): flags = poll.POLLIN if obj.writable(): flags = flags | poll.POLLOUT if flags: l.append((fd, flags)) r = poll.poll(l, timeout) for fd, flags in r: obj ...
def poll2(timeout=0.0, map=None): import poll if map is None: map = socket_map if timeout is not None: # timeout is in milliseconds timeout = int(timeout*1000) if map: l = [] for fd, obj in map.items(): flags = 0 if obj.readable(): flags = poll.POLLIN if obj.writable(): flags = flags | poll.POLLOUT if flags: l.append((...
if use_poll: if hasattr(select, 'poll'): poll_fun = poll3 else: poll_fun = poll2
if use_poll and hasattr(select, 'poll'): poll_fun = poll2
def loop(timeout=30.0, use_poll=0, map=None): if map is None: map = socket_map if use_poll: if hasattr(select, 'poll'): poll_fun = poll3 else: poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
def loop(timeout=30.0, use_poll=False, map=None):
def loop(timeout=30.0, use_poll=False, map=None, count=1e309):
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
while map:
while map and count >= 0:
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
return self.open(newurl, data)
if data is None: return self.open(newurl) else: return self.open(newurl, data)
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): # XXX The server can force infinite recursion here! if headers.has_key('location'): newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return void = fp.read() fp.close() # In case the server sent a relative URL,...
return getattr(self,name)(url, realm) def retry_http_basic_auth(self, url, realm, data):
if data is None: return getattr(self,name)(url, realm) else: return getattr(self,name)(url, realm, data) def retry_http_basic_auth(self, url, realm, data=None):
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): if headers.has_key('www-authenticate'): stuff = headers['www-authenticate'] import re match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) if match: scheme, realm = match.groups() if string.lower(scheme) == 'basic': name = 'retry_' + sel...
return self.open(newurl, data)
if data is None: return self.open(newurl) else: return self.open(newurl, data)
def retry_http_basic_auth(self, url, realm, data): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = 'http://' + host + selector return self.open(newurl,...
def retry_https_basic_auth(self, url, realm):
def retry_https_basic_auth(self, url, realm, data=None):
def retry_https_basic_auth(self, url, realm): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = '//' + host + selector return self.open_https(newurl)
self.shared_library_filename (output_libname),
self.library_filename (output_libname, lib_type='shared'),
def link_shared_lib (self, objects, output_libname, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
shared = os.path.join (dir, self.shared_library_filename (lib)) static = os.path.join (dir, self.library_filename (lib))
shared = os.path.join ( dir, self.library_filename (lib, lib_type='shared')) static = os.path.join ( dir, self.library_filename (lib, lib_type='static'))
def find_library_file (self, dirs, lib):
codecs.StreamWriter.__init__(self,strict,errors)
codecs.StreamWriter.__init__(self,stream,errors)
def __init__(self,stream,errors='strict',mapping=None):
_userprog = re.compile('^([^@]*)@(.*)$')
_userprog = re.compile('^(.*)@(.*)$')
def splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" global _userprog if _userprog is None: import re _userprog = re.compile('^([^@]*)@(.*)$') match = _userprog.match(host) if match: return map(unquote, match.group(1, 2)) return None, host
/* Routines to convert any CF type to/from the corresponding CFxxxObj */ PyObject *CFObj_New(CFTypeRef itself) { if (itself == NULL) { PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL"); return NULL; } if (CFGetTypeID(itself) == CFArrayGetTypeID()) return CFArrayRefObj_New((CFArrayRef)itself); if (CFGetTypeID(itse...
#ifdef USE_TOOLBOX_OBJECT_GLUE
self._out.write(' %s="%s"' % (name, escape(value)))
self._out.write(' %s=%s' % (name, quoteattr(value)))
def startElement(self, name, attrs): self._out.write('<' + name) for (name, value) in attrs.items(): self._out.write(' %s="%s"' % (name, escape(value))) self._out.write('>')
self._out.write(' %s="%s"' % (name, escape(value)))
self._out.write(' %s=%s' % (name, quoteattr(value)))
def startElementNS(self, name, qname, attrs): if name[0] is None: # if the name was not namespace-scoped, use the unqualified part name = name[1] else: # else try to restore the original prefix from the namespace name = self._current_context[name[0]] + ":" + name[1] self._out.write('<' + name)
from time import sleep
def demo2(): # exercises some new and improved features speed('fast') width(3) # draw a segmented half-circle setheading(towards(0,0)) x,y = position() r = (x**2+y**2)**.5/2.0 right(90) pendown = True for i in range(18): if pendown: up() pendown = False else: down() pendown = True circle(r,10) sleep(2) reset() left(9...
if localename is not None:
if localename:
def getdefaultlocale(envvars=('LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG')): """ Tries to determine the default locale settings and returns them as tuple (language code, encoding). According to POSIX, a program which has not called setlocale(LC_ALL, "") runs using the portable 'C' locale. Calling setlocale(LC_ALL, "") l...
self._prepareInstall(pkg, force, recursive)
self._prepareInstall(pkg, False, recursive)
def _prepareInstall(self, package, force=0, recursive=1): """Internal routine, recursive engine for prepareInstall. Test whether the package is installed and (if not installed or if force==1) prepend it to the temporary todo list and call ourselves recursively on all prerequisites.""" if not force: status, message = ...
if dir[-1] == '\n': dir = dir[:-1]
dir = dir.rstrip()
def addpackage(sitedir, name): global _dirs_in_sys_path if _dirs_in_sys_path is None: _init_pathinfo() reset = 1 else: reset = 0 fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exe...
str = self.__rmjunk.sub('', str)
for pattern, replacement in REPLACEMENTS: str = pattern.sub(replacement, str)
def __init__(self, link, str, seqno): self.links = [link] self.seqno = seqno # remove <#\d+#> left in by moving the data out of LaTeX2HTML str = self.__rmjunk.sub('', str) # build up the text self.text = split_entry_text(str) self.key = split_entry_key(str)
try: msg = str(self.msg) except UnicodeError: msg = self.msg
msg = self.msg if type(msg) not in (types.UnicodeType, types.StringType): try: msg = str(self.msg) except UnicodeError: msg = self.msg
def getMessage(self): """ Return the message for this LogRecord.
"""test whether PATH corresponds to a CGI script. Return a tuple (dir, rest) if PATH requires running a
"""Test whether self.path corresponds to a CGI script. Return a tuple (dir, rest) if self.path requires running a
def is_cgi(self): """test whether PATH corresponds to a CGI script.
if not executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return nobody = nobody_uid()
ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return env = {} env['SERVER_...
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = string.rfind(rest, '?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = string.find(rest, '/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.tran...
self.wfile.flush() pid = os.fork() if pid != 0: pid, sts = os.waitpid(pid, 0)
decoded_query = string.replace(query, '+', ' ') if self.have_fork: args = [script] if '=' not in decoded_query: args.append(decoded_query) nobody = nobody_uid() self.wfile.flush() pid = os.fork() if pid != 0: pid, sts = os.waitpid(pid, 0) if sts: self.log_error("CGI script exit status % return try: try: os.setuid(n...
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = string.rfind(rest, '?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = string.find(rest, '/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.tran...
self.log_error("CGI script exit status x%x" % sts) return try: env = {} env['SERVER_SOFTWARE'] = self.version_string() env['SERVER_NAME'] = self.server.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PROTOCOL'] = self.protocol_version env['SERVER_PORT'] = str(self.server.server_port) env['REQUEST_METHOD...
self.log_error("CGI script exit status %
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = string.rfind(rest, '?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = string.find(rest, '/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.tran...
env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length accept = [] for line in self.headers.getallmatchingheaders('accept'): if line[:1] in string.whitespace: accept.append(string.strip(line)) else: accept = accept + string.split(line[7:...
self.log_error("CGI script exited OK") else: os.environ.update(env) save_argv = sys.argv save_stdin = sys.stdin save_stdout = sys.stdout save_stderr = sys.stderr
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = string.rfind(rest, '?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = string.find(rest, '/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.tran...