rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
>>> set_unittest_reportflags(ELLIPSIS)
>>> doctest.set_unittest_reportflags(ELLIPSIS)
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doc...
>>> set_unittest_reportflags(old) == (REPORT_NDIFF |
>>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doc...
print >> sys.stderr, """\ WARNING: an attempt to connect to %r timed out, in test_timeout. That may be legitimate, but is not the outcome we hoped for. If this message is seen often, test_timeout should be changed to use a more reliable address.""" % (ADDR,)
error_msg('timed out')
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...
print "Connection refused when connecting to", ADDR
error_msg('was refused')
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...
co_name = frame.f_code.co_name
def user_line(self, frame):
try: func = frame.f_locals[co_name] if getattr(func, "DebuggerStepThrough", 0): print "XXXX DEBUGGER STEPPING THROUGH"
exclude = ('rpc.py', 'threading.py', '<string>') for rpcfile in exclude: if co_filename.count(rpcfile):
def user_line(self, frame):
except: pass if co_filename in (r'.\rpc.py', 'rpc.py','<string>'): self.set_step() return if co_filename.endswith('threading.py'): self.set_step() return
def user_line(self, frame):
apply(self.cb, self.cb_arg)
apply(self.cb, (self.cb_arg,))
def poll(self): if not self.async: raise error, 'Can only call poll() in async mode' if not self.busy_cmd: return if self.testready(): if self.cb: apply(self.cb, self.cb_arg)
return s[:colon-1], s[colon:]
path, file = s[:colon-1], s[colon:] if path and not ':' in path: path = path + ':' return path, file
def split(s): if ':' not in s: return '', s colon = 0 for i in range(len(s)): if s[i] == ':': colon = i+1 return s[:colon-1], s[colon:]
return From(fromname, [('*', None)])
return From(fromname, [('*', None)], lineno=nodelist[0][2])
def import_from(self, nodelist): # import_from: 'from' dotted_name 'import' ('*' | # '(' import_as_names ')' | import_as_names) assert nodelist[0][1] == 'from' assert nodelist[1][0] == symbol.dotted_name assert nodelist[2][1] == 'import' fromname = self.com_dotted_name(nodelist[1]) if nodelist[3][0] == token.STAR: #...
d[types.CodeType] = _deepcopy_atomic
try: d[types.CodeType] = _deepcopy_atomic except AttributeError: pass
def _deepcopy_atomic(x, memo): return x
return Falso
return False
def ignored(self, file): if os.path.isdir(file): return True for pat in self.IgnoreList: if fnmatch.fnmatch(file, pat): return True return Falso
TESTFN = '@test'
import os if os.name !='riscos': TESTFN = '@test' else: TESTFN = 'test' del os
def fcmp(x, y): # fuzzy comparison function if type(x) == type(0.0) or type(y) == type(0.0): try: x, y = coerce(x, y) fuzz = (abs(x) + abs(y)) * FUZZ if abs(x-y) <= fuzz: return 0 except: pass elif type(x) == type(y) and type(x) in (type(()), type([])): for i in range(min(len(x), len(y))): outcome = fcmp(x[i], y[i]) if...
if exppart: expo = eval(exppart[1:])
if exppart: expo = int(exppart[1:])
def extract(s): res = decoder.match(s) if res is None: raise NotANumber, s sign, intpart, fraction, exppart = res.group(1,2,3,4) if sign == '+': sign = '' if fraction: fraction = fraction[1:] if exppart: expo = eval(exppart[1:]) else: expo = 0 return sign, intpart, fraction, expo
extra_postargs.extend(extra_postargs)
pp_args.extend(extra_postargs)
def preprocess (self, source, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None):
if self.force or (output_file and newer(source, output_file)):
if self.force or output_file is None or newer(source, output_file)):
def preprocess (self, source, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None):
class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.mbcs_decode(input,self.errors)[0]
class IncrementalDecoder(codecs.BufferedIncrementalDecoder): def _buffer_decode(self, input, errors, final): return codecs.mbcs_decode(input,self.errors,final)
def encode(self, input, final=False): return codecs.mbcs_encode(input,self.errors)[0]
if os.sep != '/': paths = string.split (pathname, '/') return apply (os.path.join, paths) else: return pathname
paths = string.split(pathname, '/') return apply(os.path.join, paths)
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...
tmp = [] def callit(func=func, args=args, self=self, tmp=tmp):
def callit():
def after(self, ms, func=None, *args): """Call function once after given time.
self.deletecommand(tmp[0])
self.deletecommand(name)
def callit(func=func, args=args, self=self, tmp=tmp): try: func(*args) finally: try: self.deletecommand(tmp[0]) except TclError: pass
tmp.append(name)
def callit(func=func, args=args, self=self, tmp=tmp): try: func(*args) finally: try: self.deletecommand(tmp[0]) except TclError: pass
self.rfile = self.connection.makefile('rb', 0) self.wfile = self.connection.makefile('wb', 0)
self.rfile = self.connection.makefile('rb', self.rbufsize) self.wfile = self.connection.makefile('wb', self.wbufsize)
def setup(self): self.connection = self.request self.rfile = self.connection.makefile('rb', 0) self.wfile = self.connection.makefile('wb', 0)
ValueError if 'pathname' is absolute (starts with '/') or contains local directory separators (unless the local separator is '/', of course).
ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash.
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...
occurrence of '$' followed by a name, or a name enclosed in braces, is considered a variable. Every variable is substituted by the value found in the 'local_vars' dictionary, or in 'os.environ' if it's not in 'local_vars'. 'os.environ' is first checked/ augmented to guarantee that it contains certain values: see '_ch...
occurrence of '$' followed by a name is considered a variable, and variable is substituted by the value found in the 'local_vars' dictionary, or in 'os.environ' if it's not in 'local_vars'. 'os.environ' is first checked/augmented to guarantee that it contains certain values: see 'check_environ()'. Raise ValueError for...
def subst_vars (str, local_vars): """Perform shell/Perl-style variable substitution on 'string'. Every occurrence of '$' followed by a name, or a name enclosed in braces, is considered a variable. Every variable is substituted by the value found in the 'local_vars' dictionary, or in 'os.environ' if it's not in 'local...
return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, str)
try: return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, str) except KeyError, var: raise ValueError, "invalid variable '$%s'" % var
def _subst (match, local_vars=local_vars): var_name = match.group(1) if local_vars.has_key(var_name): return str(local_vars[var_name]) else: return os.environ[var_name]
Single = group("^'", "[^\]'") Double = group('^"', '[^\]"') Single3 = group("^'''", "[^\]'''") Double3 = group('^"""', '[^\]"""')
Single = group("[^'\]", "[\].") + "*'" Double = group('[^"\]', '[\].') + '*"' Single3 = group("[^'\]","[\].","'[^'\]","'[\].","''[^'\]","''[\].") + "*'''" Double3 = group('[^"\]','[\].','"[^"\]','"[\].','""[^"\]','""[\].') + '*"""'
def group(*choices): return '\(' + string.join(choices, '\|') + '\)'
String = group("'" + group('[\].', "[^\n'\]") + "*'", '"' + group('[\].', '[^\n"\]') + '*"')
String = group("'" + group("[^\n'\]", "[\].") + "*'", '"' + group('[^\n"\]', '[\].') + '*"')
def group(*choices): return '\(' + string.join(choices, '\|') + '\)'
contstr = ''
contstr, needcont = '', 0
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
if not line: raise TokenError, "EOF within multi-line string" if endprog.search(line) >= 0:
if not line: raise TokenError, ("EOF in multi-line string", strstart) if endprog.match(line) >= 0:
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
tokeneater(DEDENT, line[:pos], (lnum, 0), (lnum, pos), line)
tokeneater(DEDENT, '', (lnum, pos), (lnum, pos), line)
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
if not line: raise TokenError, "EOF within multi-line statement"
if not line: raise TokenError, ("EOF in multi-line statement", (lnum, 0))
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
spos, epos = (lnum, start), (lnum, end)
spos, epos, pos = (lnum, start), (lnum, end), end
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
pos = end
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
elif initial in numchars:
elif initial in numchars \ or (initial == '.' and token != '.'):
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
if endprog.search(line, pos) >= 0:
if endprog.match(line, pos) >= 0:
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
endprog, contstr = endprogs[initial], line[start:]
endprog = endprogs[initial] contstr, needcont = line[start:], 1
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
tokeneater(ERRORTOKEN, line[pos], spos, (lnum, pos+1), line)
tokeneater(ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos+1), line)
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
tokenize(open(sys.argv[-1]).readline)
if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) else: tokenize(syss.tdin.readline)
def tokenize(readline, tokeneater=printtoken): lnum = parenlev = continued = 0 namechars, numchars = string.letters + '_', string.digits contstr = '' indents = [0] while 1: # loop over lines in stream line = readline() lnum = lnum + 1 pos, max = 0, len(line) if contstr: ...
self.assert_(len(items) == 0, "iterator did not touch all items")
self.assert_(len(items) == 0, "iteritems() did not touch all items")
def check_iters(self, dict): # item iterator: items = dict.items() for item in dict.iteritems(): items.remove(item) self.assert_(len(items) == 0, "iterator did not touch all items")
self.assert_(len(keys) == 0, "iterator did not touch all keys")
self.assert_(len(keys) == 0, "__iter__() did not touch all keys") keys = dict.keys() for k in dict.iterkeys(): keys.remove(k) self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
def check_iters(self, dict): # item iterator: items = dict.items() for item in dict.iteritems(): items.remove(item) self.assert_(len(items) == 0, "iterator did not touch all items")
self.assert_(len(values) == 0, "iterator did not touch all values")
self.assert_(len(values) == 0, "itervalues() did not touch all values")
def check_iters(self, dict): # item iterator: items = dict.items() for item in dict.iteritems(): items.remove(item) self.assert_(len(items) == 0, "iterator did not touch all items")
srcfinfo = srcfss.GetFInfo() Res.FSpCreateResFile(dstfss, srcfinfo.Creator, srcfinfo.Type, -1)
if os.path.isdir(src): cr, tp = 'MACS', 'fdrp' else: cr, tp = srcfss.GetCreatorType() Res.FSpCreateResFile(dstfss, cr, tp, -1)
def mkalias(src, dst, relative=None): """Create a finder alias""" srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) if relative: relativefss = macfs.FSSpec(relative) # ik mag er geen None in stoppen :-( alias = srcfss.NewAlias(relativefss) else: alias = srcfss.NewAlias() srcfinfo = srcfss.GetFInfo() Res.FSpCreateR...
print_lines is the default callback.'''
print_line() is the default callback.'''
def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_lines is the default callback.''' if not callback: callback = print_line re...
except:
except (ValueError, OverflowError):
def mimify(infile, outfile): """Convert 8bit parts of a MIME mail message to quoted-printable.""" if type(infile) == type(''): ifile = open(infile) if type(outfile) == type('') and infile == outfile: import os d, f = os.path.split(infile) os.rename(infile, os.path.join(d, ',' + f)) else: ifile = infile if type(outfile)...
name = alogger.name namelen = len(name)
def _fixupChildren(self, ph, alogger): """ Ensure that children of the placeholder ph are connected to the specified logger. """ #for c in ph.loggers: for c in ph.loggerMap.keys(): if string.find(c.parent.name, alogger.name) <> 0: alogger.parent = c.parent c.parent = alogger
if string.find(c.parent.name, alogger.name) <> 0:
if c.parent.name[:namelen] != name:
def _fixupChildren(self, ph, alogger): """ Ensure that children of the placeholder ph are connected to the specified logger. """ #for c in ph.loggers: for c in ph.loggerMap.keys(): if string.find(c.parent.name, alogger.name) <> 0: alogger.parent = c.parent c.parent = alogger
return self.version or "???"
return self.version or "0.0.0"
def get_version(self): return self.version or "???"
if "badsyntax" in basename:
if "badsyntax" in basename or "bad_coding" in basename:
def testCompileLibrary(self): # A simple but large test. Compile all the code in the # standard library and its test suite. This doesn't verify # that any of the code is correct, merely the compiler is able # to generate some kind of code for it.
class ResFunction(ResMixIn, OSErrFunctionGenerator): pass class ResMethod(ResMixIn, OSErrMethodGenerator): pass
class ResFunction(ResMixIn, OSErrWeakLinkFunctionGenerator): pass class ResMethod(ResMixIn, OSErrWeakLinkMethodGenerator): pass
def checkit(self): if self.returntype.__class__ != OSErrType: OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX
def test_wide(self):
def test_width(self):
def test_wide(self): self.assertEqual(u''.width(), 0) self.assertEqual(u'abcd'.width(), 4) self.assertEqual(u'\u0187\u01c9'.width(), 2) self.assertEqual(u'\u2460\u2329'.width(), 3) self.assertEqual(u'\u2329\u2460'.width(), 3) self.assertEqual(u'\ud55c\uae00'.width(), 4) self.assertEqual(u'\ud55c\u2606\uae00'.width(), 5...
information. The application must not attempt to read from the array outside of the specified range."""
information."""
def ignorableWhitespace(self, whitespace): """Receive notification of ignorable whitespace in element content.
raise ValueError, "Mode " + mode + " not supported"
raise IOError, "Mode " + mode + " not supported"
def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None): if fileobj is None: fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') if filename is None: if hasattr(fileobj, 'name'): filename = fileobj.name else: filename = '' if mode is None: if hasattr(fileobj, 'mode'): mode = fileobj....
replacement = convert_entityref(name)
replacement = self.convert_entityref(name)
def handle_entityref(self, name): """Handle entity references, no need to override.""" replacement = convert_entityref(name) if replacement is None: self.unknown_entityref(name) else: self.handle_data(convert_entityref(name))
self.handle_data(convert_entityref(name))
self.handle_data(self.convert_entityref(name))
def handle_entityref(self, name): """Handle entity references, no need to override.""" replacement = convert_entityref(name) if replacement is None: self.unknown_entityref(name) else: self.handle_data(convert_entityref(name))
def getlongresp(self):
def getlongresp(self,fileHandle=None):
def getlongresp(self): """Internal: get a response plus following text from the server. Raise various errors if the response indicates an error.""" resp = self.getresp() if resp[:3] not in LONGRESP: raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if line == '.': break if line[:2] == '..': line = lin...
resp = self.getresp() if resp[:3] not in LONGRESP: raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if line == '.': break if line[:2] == '..': line = line[1:] list.append(line)
openedFile = None try: if isinstance(fileHandle, types.StringType): openedFile = fileHandle = open(fileHandle, "w") resp = self.getresp() if resp[:3] not in LONGRESP: raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if line == '.': break if line[:2] == '..': line = line[1:] if fileHandle: fileHandl...
def getlongresp(self): """Internal: get a response plus following text from the server. Raise various errors if the response indicates an error.""" resp = self.getresp() if resp[:3] not in LONGRESP: raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if line == '.': break if line[:2] == '..': line = lin...
def longcmd(self, line):
def longcmd(self, line, fileHandle=None):
def longcmd(self, line): """Internal: send a command and get the response plus following text.""" self.putcmd(line) return self.getlongresp()
return self.getlongresp()
return self.getlongresp(fileHandle)
def longcmd(self, line): """Internal: send a command and get the response plus following text.""" self.putcmd(line) return self.getlongresp()
def artcmd(self, line):
def artcmd(self, line, fileHandle=None):
def artcmd(self, line): """Internal: process a HEAD, BODY or ARTICLE command.""" resp, list = self.longcmd(line) resp, nr, id = self.statparse(resp) return resp, nr, id, list
resp, list = self.longcmd(line)
resp, list = self.longcmd(line,fileHandle)
def artcmd(self, line): """Internal: process a HEAD, BODY or ARTICLE command.""" resp, list = self.longcmd(line) resp, nr, id = self.statparse(resp) return resp, nr, id, list
def body(self, id):
def body(self, id, fileHandle=None):
def body(self, id): """Process a BODY command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body"""
- list: the lines of the article's body""" return self.artcmd('BODY ' + id)
- list: the lines of the article's body or an empty list if fileHandle was used""" return self.artcmd('BODY ' + id, fileHandle)
def body(self, id): """Process a BODY command. Argument: - id: article number or message id Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body"""
dotted_req_host = "."+req_host
req_host = "."+req_host
def domain_return_ok(self, domain, request): # Liberal check of. This is here as an optimization to avoid # having to load lots of MSIE cookie files unless necessary. req_host, erhn = eff_request_host(request) if not req_host.startswith("."): dotted_req_host = "."+req_host if not erhn.startswith("."): dotted_erhn = "....
dotted_erhn = "."+erhn if not (dotted_req_host.endswith(domain) or dotted_erhn.endswith(domain)):
erhn = "."+erhn if not (req_host.endswith(domain) or erhn.endswith(domain)):
def domain_return_ok(self, domain, request): # Liberal check of. This is here as an optimization to avoid # having to load lots of MSIE cookie files unless necessary. req_host, erhn = eff_request_host(request) if not req_host.startswith("."): dotted_req_host = "."+req_host if not erhn.startswith("."): dotted_erhn = "....
raise DistutilsClasserror, \
raise DistutilsClassError, \
def parse_command_line (self, args): """Parse the setup script's command line: set any Distribution attributes tied to command-line options, create all command objects, and set their options from the command-line. 'args' must be a list of command-line arguments, most likely 'sys.argv[1:]' (see the 'setup()' function)....
print 'setcmapinfo:', stuff
def setcmapinfo(self): stuff = 0, 0, 0, 0, 0 if self.format in ('rgb8', 'grey'): stuff = 8, 0, 0, 0, 0 if self.format == 'grey4': stuff = 4, 0, 0, 0, 0 if self.format == 'grey2': stuff = 2, 0, 0, 0, 0 if self.format == 'mono': stuff = 1, 0, 0, 0, 0 print 'setcmapinfo:', stuff self.c0bits, self.c1bits, self.c2bits, \ se...
self.send_error(501, "Unsupported method (%s)" % `mname`)
self.send_error(501, "Unsupported method (%s)" % `command`)
def handle(self): """Handle a single HTTP request.
j = string.index(rawdata, '>', i) except string.index_error: return -1 attrs = [] tagfind = regex.compile('[a-zA-Z][a-zA-Z0-9]*') attrfind = regex.compile( '[ \t\n]+\([a-zA-Z_][a-zA-Z_0-9]*\)' + '\([ \t\n]*=[ \t\n]*' + '\(\'[^\']*\'\|"[^"]*"\|[-a-zA-Z0-9./:+*%?!()_ k = tagfind.match(rawdata, i+1) if k < 0: raise Runti...
method = getattr(self, 'end_' + tag)
def parse_starttag(self, i): rawdata = self.rawdata try: j = string.index(rawdata, '>', i) except string.index_error: return -1 # Now parse the data between i+1 and j into a tag and attrs attrs = [] tagfind = regex.compile('[a-zA-Z][a-zA-Z0-9]*') attrfind = regex.compile( '[ \t\n]+\([a-zA-Z_][a-zA-Z_0-9]*\)' + '\([ \t\...
try: method = getattr(self, 'do_' + tag) except AttributeError: self.unknown_starttag(tag, attrs) return j-i method(attrs) return j-i self.stack.append(tag) method(attrs) return j-i def parse_endtag(self, data): if data[:2] <> '</' or data[-1:] <> '>': raise RuntimeError, 'unexpected call to parse_endtag' tag = strin...
self.unknown_endtag(tag) return found = len(self.stack) for i in range(found): if self.stack[i] == tag: found = i while len(self.stack) > found: tag = self.stack[-1] try: method = getattr(self, 'end_' + tag) except AttributeError: method = None if method: self.handle_endtag(tag, method) else: self.unknown_endtag(tag) d...
def parse_starttag(self, i): rawdata = self.rawdata try: j = string.index(rawdata, '>', i) except string.index_error: return -1 # Now parse the data between i+1 and j into a tag and attrs attrs = [] tagfind = regex.compile('[a-zA-Z][a-zA-Z0-9]*') attrfind = regex.compile( '[ \t\n]+\([a-zA-Z_][a-zA-Z_0-9]*\)' + '\([ \t\...
f = open(file, 'r') x = TestSGML() while 1: line = f.readline() if not line: x.close() break x.feed(line)
if file == '-': f = sys.stdin else: try: f = open(file, 'r') except IOError, msg: print file, ":", msg sys.exit(1) data = f.read() if f is not sys.stdin: f.close() x = klass() for c in data: x.feed(c) x.close()
def test(): file = 'test.html' f = open(file, 'r') x = TestSGML() while 1: line = f.readline() if not line: x.close() break x.feed(line)
def remove_option(section, option):
def remove_option(self, section, option):
def remove_option(section, option): """Remove an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) existed = sectdict.has_key(key) if existed: del sectdict[key] return existed
def remove_section(section):
def remove_section(self, section):
def remove_section(section): """Remove a file section.""" if self.__sections.has_key(section): del self.__sections[section] return 1 else: return 0
def __init__(self, text):
def __init__(self, text, fileclass=StringIO.StringIO):
def __init__(self, text): self.text = text
return StringIO.StringIO(self.text)
return self.fileclass(self.text) class NoEOFStringIO(StringIO.StringIO): """Like StringIO, but raises AssertionError on EOF. This is used below to test that httplib doesn't try to read more from the underlying file than it should. """ def read(self, n=-1): data = StringIO.StringIO.read(self, n) if data == '': raise A...
def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text)
import sys
def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise httplib.UnimplementedFileMode() return StringIO.StringIO(self.text)
>>> msg = '''
>>> msg = '''\\
def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]): """This command performs an entire mail transaction.
want = int((have - 1) // self.indentwidth) * self.indentwidth
want = ((have - 1) // self.indentwidth) * self.indentwidth
def smart_backspace_event(self, event): text = self.text first, last = self.editwin.get_selection_indices() if first and last: text.delete(first, last) text.mark_set("insert", first) return "break" # Delete whitespace left, until hitting a real char or closest # preceding virtual tab stop. chars = text.get("insert line...
file = open(filename)
try: file = open(filename) except IOError: return None
def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (0, None)) if lastupdate < mtime: info = inspect.getmoduleinfo(filename) file = open(filename) if info and 'b' in info[2]: # binary modules have to be import...
(fd, filename) = tempfile.mkstemp() file = os.fdopen(fd, 'w')
filename = tempfile.mktemp() file = open(filename, 'w')
def tempfilepager(text, cmd): """Page through text by invoking a program on a temporary file.""" import tempfile (fd, filename) = tempfile.mkstemp() file = os.fdopen(fd, 'w') file.write(text) file.close() try: os.system(cmd + ' ' + filename) finally: os.unlink(filename)
def __init__(self, screenName=None, baseName=None, className='Tk'):
def __init__(self, screenName=None, baseName=None, className='Tix'):
def __init__(self, screenName=None, baseName=None, className='Tk'): Tkinter.Tk.__init__(self, screenName, baseName, className) tixlib = os.environ.get('TIX_LIBRARY') if tixlib is not None: self.tk.eval('global auto_path; lappend auto_path {%s}' % tixlib) self.tk.eval('global tcl_pkgPath; lappend tcl_pkgPath {%s}' % tix...
class TixWidget(Widget):
class TixWidget(Tkinter.Widget):
def slaves(self): return map(self._nametowidget, self.tk.splitlist( self.tk.call( 'tixForm', 'slaves', self._w)))
"""ComboBox - an Entry field with a dropdown menu
"""ComboBox - an Entry field with a dropdown menu. The user can select a choice by either typing in the entry subwdget or selecting from the listbox subwidget.
def invoke(self, name): if self.subwidget_list.has_key(name): self.tk.call(self._w, 'invoke', name)
slistbox ScrolledListBox tick Button } cross Button } present if created with the fancy option"""
slistbox ScrolledListBox tick Button cross Button : present if created with the fancy option"""
def invoke(self, name): if self.subwidget_list.has_key(name): self.tk.call(self._w, 'invoke', name)
"""Control - An entry field with value change arrows.
"""Control - An entry field with value change arrows. The user can adjust the value by pressing the two arrow buttons or by entering the value directly into the entry. The new value will be checked against the user-defined upper and lower limits.
def pick(self, index): self.tk.call(self._w, 'pick', index)
"""DirList - Directory Listing.
"""DirList - displays a list view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory.
def update(self): self.tk.call(self._w, 'update')
"""DirList - Directory Listing in a hierarchical view.
"""DirTree - Directory Listing in a hierarchical view. Displays a tree view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory.
def chdir(self, dir): self.tk.call(self._w, 'chdir', dir)
It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again.
def popdown(self): self.tk.call(self._w, 'popdown')
"""FileEntry - Entry field with button that invokes a FileSelectDialog
"""FileEntry - Entry field with button that invokes a FileSelectDialog. The user can type in the filename manually. Alternatively, the user can press the button widget that sits next to the entry, which will bring up a file selection dialog.
def popdown(self): self.tk.call(self._w, 'popdown')
"""HList - Hierarchy display.
"""HList - Hierarchy display widget can be used to display any data that have a hierarchical structure, for example, file system directory trees. The list entries are indented and connected by branch lines according to their places in the hierachy.
def file_dialog(self): # XXX return python object pass
"""LabelEntry - Entry field with label.
"""LabelEntry - Entry field with label. Packages an entry widget and a label into one mega widget. It can beused be used to simplify the creation of ``entry-form'' type of interface.
def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixInputOnly', None, cnf, kw)
"""LabelFrame - Labelled Frame container.
"""LabelFrame - Labelled Frame container. Packages a frame widget and a label into one mega widget. To create widgets inside a LabelFrame widget, one creates the new widgets relative to the frame subwidget and manage them inside the frame subwidget.
def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixLabelEntry', ['labelside','options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry')
<pages> g/p widgets added dynamically"""
<pages> page widgets added dynamically with the add method"""
def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixLabelFrame', ['labelside','options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['frame'] = _dummyFrame(self, 'frame')
"""OptionMenu - Option menu widget.
"""OptionMenu - creates a menu button of options.
def raised(self): return self.tk.call(self._w, 'raised')
"""PanedWindow - Multi-pane container widget. Panes are resizable.
"""PanedWindow - Multi-pane container widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.The user changes the sizes of the panes by dragging the resize handle between two panes.
def enable(self, name): self.tk.call(self._w, 'enable', name)
<panes> g/p widgets added dynamically"""
<panes> g/p widgets added dynamically with the add method."""
def enable(self, name): self.tk.call(self._w, 'enable', name)
"""PopupMenu widget.
"""PopupMenu widget can be used as a replacement of the tk_popup command. The advantage of the Tix PopupMenu widget is it requires less application code to manipulate.
def panes(self): names = self.tk.call(self._w, 'panes') ret = [] for x in names: ret.append(self.subwidget(x)) return ret
"""TList - Hierarchy display.
"""TList - Hierarchy display widget which can be used to display data in a tabular format. The list entries of a TList widget are similar to the entries in the Tk listbox widget. The main differences are (1) the TList widget can display the list entries in a two dimensional format and (2) you can use graphical images a...
def invoke(self, name): if self.subwidget_list.has_key(name): self.tk.call(self._w, 'invoke', name)
class _dummyTList(TList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyComboBox(ComboBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physicall...
class _dummyScrolledHList(ScrolledHList, TixSubWidget):
def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically)
if self.libraries is None: self.libraries = [] if self.library_dirs is None: self.library_dirs = [] if self.rpath is None: self.rpath = [] if os.name == 'nt': self.library_dirs.append (os.path.join(sys.exec_prefix, 'libs')) if self.debug: self.build_temp = os.path.join (self.build_temp, "Debug") else: self.build_te...
def finalize_options (self): from distutils import sysconfig
if self.libraries is None: self.libraries = [] if self.library_dirs is None: self.library_dirs = [] if self.rpath is None: self.rpath = []
def run (self):