rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
import string
def __init__(self, dirname): import string self.dirname = dirname
import string
def _test(): import time import sys import string import os args = sys.argv[1:] if not args: for key in 'MAILDIR', 'MAIL', 'LOGNAME', 'USER': if os.environ.has_key(key): mbox = os.environ[key] break else: print "$MAIL, $LOGNAME nor $USER set -- who are you?" return else: mbox = args[0] if mbox[:1] == '+': mbox = os.environ['HOME'] + '/Mail/' + mbox[1:] elif not '/' in mbox: mbox = '/usr/mail/' + mbox if os.path.isdir(mbox): if os.path.isdir(os.path.join(mbox, 'cur')): mb = Maildir(mbox) else: mb = MHMailbox(mbox) else: fp = open(mbox, 'r') mb = UnixMailbox(fp) msgs = [] while 1: msg = mb.next() if msg is None: break msgs.append(msg) if len(args) <= 1: msg.fp = None if len(args) > 1: num = string.atoi(args[1]) print 'Message %d body:'%num msg = msgs[num-1] msg.rewindbody() sys.stdout.write(msg.fp.read()) else: print 'Mailbox',mbox,'has',len(msgs),'messages:' for msg in msgs: f = msg.getheader('from') or "" s = msg.getheader('subject') or "" d = msg.getheader('date') or "" print '-%20.20s %20.20s %-30.30s'%(f, d[5:], s)
num = string.atoi(args[1])
num = int(args[1])
def _test(): import time import sys import string import os args = sys.argv[1:] if not args: for key in 'MAILDIR', 'MAIL', 'LOGNAME', 'USER': if os.environ.has_key(key): mbox = os.environ[key] break else: print "$MAIL, $LOGNAME nor $USER set -- who are you?" return else: mbox = args[0] if mbox[:1] == '+': mbox = os.environ['HOME'] + '/Mail/' + mbox[1:] elif not '/' in mbox: mbox = '/usr/mail/' + mbox if os.path.isdir(mbox): if os.path.isdir(os.path.join(mbox, 'cur')): mb = Maildir(mbox) else: mb = MHMailbox(mbox) else: fp = open(mbox, 'r') mb = UnixMailbox(fp) msgs = [] while 1: msg = mb.next() if msg is None: break msgs.append(msg) if len(args) <= 1: msg.fp = None if len(args) > 1: num = string.atoi(args[1]) print 'Message %d body:'%num msg = msgs[num-1] msg.rewindbody() sys.stdout.write(msg.fp.read()) else: print 'Mailbox',mbox,'has',len(msgs),'messages:' for msg in msgs: f = msg.getheader('from') or "" s = msg.getheader('subject') or "" d = msg.getheader('date') or "" print '-%20.20s %20.20s %-30.30s'%(f, d[5:], s)
self.literal = message
self.literal = MapCRLF.sub(CRLF, message)
def append(self, mailbox, flags, date_time, message): """Append message to named mailbox.
test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':CRLF}
test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'}
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ if isinstance(date_time, (int, float)): tt = time.localtime(date_time) elif isinstance(date_time, (tuple, time.struct_time)): tt = date_time elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'): return date_time # Assume in correct format else: raise ValueError("date_time not of a known type") dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+03d%02d" % divmod(zone/60, 60) + '"'
class IEEEOperationsTestCase(unittest.TestCase): if float.__getformat__("double").startswith("IEEE"): def test_double_infinity(self): big = 4.8e159 pro = big*big self.assertEquals(repr(pro), 'inf') sqr = big**2 self.assertEquals(repr(sqr), 'inf')
def test_float_specials_do_unpack(self): for fmt, data in [('>f', BE_FLOAT_INF), ('>f', BE_FLOAT_NAN), ('<f', LE_FLOAT_INF), ('<f', LE_FLOAT_NAN)]: struct.unpack(fmt, data)
IEEEFormatTestCase, IEEEOperationsTestCase, )
IEEEFormatTestCase)
def test_main(): test_support.run_unittest( FormatFunctionsTestCase, UnknownFormatTestCase, IEEEFormatTestCase, IEEEOperationsTestCase, )
index = terminator.find (self.ac_in_buffer)
index = ac_in_buffer.find (self.terminator)
def handle_read (self):
capability_name = _capability_names[ch]
capability_name = _capability_names.get(ch) if capability_name is None: return 0
def has_key(ch): if type(ch) == type( '' ): ch = ord(ch) # Figure out the correct capability name for the keycode. capability_name = _capability_names[ch] #Check the current terminal description for that capability; #if present, return true, else return false. if _curses.tigetstr( capability_name ): return 1 else: return 0
if lastcs is not None: if nextcs is None or nextcs == 'us-ascii':
if lastcs not in (None, 'us-ascii'): if nextcs in (None, 'us-ascii'):
def __unicode__(self): """Helper for the built-in unicode function.""" uchunks = [] lastcs = None for s, charset in self._chunks: # We must preserve spaces between encoded and non-encoded word # boundaries, which means for us we need to add a space when we go # from a charset to None/us-ascii, or from None/us-ascii to a # charset. Only do this for the second and subsequent chunks. nextcs = charset if uchunks: if lastcs is not None: if nextcs is None or nextcs == 'us-ascii': uchunks.append(USPACE) nextcs = None elif nextcs is not None and nextcs <> 'us-ascii': uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks)
elif nextcs is not None and nextcs <> 'us-ascii':
elif nextcs not in (None, 'us-ascii'):
def __unicode__(self): """Helper for the built-in unicode function.""" uchunks = [] lastcs = None for s, charset in self._chunks: # We must preserve spaces between encoded and non-encoded word # boundaries, which means for us we need to add a space when we go # from a charset to None/us-ascii, or from None/us-ascii to a # charset. Only do this for the second and subsequent chunks. nextcs = charset if uchunks: if lastcs is not None: if nextcs is None or nextcs == 'us-ascii': uchunks.append(USPACE) nextcs = None elif nextcs is not None and nextcs <> 'us-ascii': uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks)
readermode=None):
readermode=None, usenetrc=True):
def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None): """Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting.
if not user:
if usenetrc and not user:
def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None): """Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting.
all, scheme, rfc, selfdot, name = match.groups()
all, scheme, rfc, pep, selfdot, name = match.groups()
def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'(self\.)?(\w+))\b') while 1: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start]))
url = 'http://www.rfc-editor.org/rfc/rfc%s.txt' % rfc
url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'(self\.)?(\w+))\b') while 1: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start]))
if cache.has_key(path) and cache[path] != info: module = reload(module)
if cache.get(path) == info: continue module = reload(module)
def freshimport(name, cache={}): """Import a module, reloading it if the source file has changed.""" topmodule = __import__(name) module = None for component in split(name, '.'): if module == None: module = topmodule path = split(name, '.')[0] else: module = getattr(module, component) path = path + '.' + component if hasattr(module, '__file__'): file = module.__file__ if os.path.exists(file): info = (file, os.path.getmtime(file), os.path.getsize(file)) if cache.has_key(path) and cache[path] != info: module = reload(module) file = module.__file__ if os.path.exists(file): info = (file, os.path.getmtime(file), os.path.getsize(file)) cache[path] = info return module
return '''To get help on a Python object, call help(object).
return '''Welcome to Python %s! To get help on a Python object, call help(object).
def __repr__(self): return '''To get help on a Python object, call help(object).
help(module) or call help('modulename').'''
help(module) or call help('modulename').''' % sys.version[:3]
def __repr__(self): return '''To get help on a Python object, call help(object).
(typ, [data]) = <instance>.create(mailbox, who, what)
(typ, [data]) = <instance>.setacl(mailbox, who, what)
def setacl(self, mailbox, who, what): """Set a mailbox acl.
simple_err(struct.pack, "Q", -1)
any_err(struct.pack, "Q", -1)
def simple_err(func, *args): try: apply(func, args) except struct.error: pass else: raise TestFailed, "%s%s did not raise struct.error" % ( func.__name__, args)
chars = list(value) chars.reverse() return "".join(chars) if has_native_qQ:
else: return string_reverse(value) def test_native_qQ():
def bigendian_to_native(value): if isbigendian: return value chars = list(value) chars.reverse() return "".join(chars)
print "before _get_package_data():" print "vendor =", self.vendor print "packager =", self.packager print "doc_files =", self.doc_files print "changelog =", self.changelog
if DEBUG: print "before _get_package_data():" print "vendor =", self.vendor print "packager =", self.packager print "doc_files =", self.doc_files print "changelog =", self.changelog
def run (self):
if line == '\037\014\n':
if line == '\037\014\n' or line == '\037':
def _search_end(self): while 1: pos = self.fp.tell() line = self.fp.readline() if not line: return if line == '\037\014\n': self.fp.seek(pos) return
args = ('wm', 'colormapwindows', self._w) + _flatten(wlist)
if len(wlist) > 1: wlist = (wlist,) args = ('wm', 'colormapwindows', self._w) + wlist
def wm_colormapwindows(self, *wlist): args = ('wm', 'colormapwindows', self._w) + _flatten(wlist) return map(self._nametowidget, self.tk.call(args))
env['CONTENT_TYPE'] = self.headers.type
if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader
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.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return if not executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return nobody = nobody_uid() self.send_response(200, "Script output follows") self.wfile.flush() # Always flush before forking pid = os.fork() if pid != 0: # Parent pid, sts = os.waitpid(pid, 0) if sts: self.log_error("CGI script exit status x%x" % sts) return # Child try: # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html # XXX Much of the following could be prepared ahead of time! 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.command uqrest = urllib.unquote(rest) env['PATH_INFO'] = uqrest env['PATH_TRANSLATED'] = self.translate_path(uqrest) env['SCRIPT_NAME'] = scriptname if query: env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] # AUTH_TYPE # REMOTE_USER # REMOTE_IDENT env['CONTENT_TYPE'] = self.headers.type 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:]) env['HTTP_ACCEPT'] = string.joinfields(accept, ',') ua = self.headers.getheader('user-agent') if ua: env['HTTP_USER_AGENT'] = ua # XXX Other HTTP_* headers decoded_query = string.replace(query, '+', ' ') try: os.setuid(nobody) except os.error: pass os.dup2(self.rfile.fileno(), 0) os.dup2(self.wfile.fileno(), 1) print scriptfile, script, decoded_query os.execve(scriptfile, [script, decoded_query], env) except: self.server.handle_error(self.request, self.client_address) os._exit(127)
if self.debuglevel > 0: print 'connect:', (host, port)
if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
def connect(self, host='localhost', port = 0): """Connect to a host on a given port.
if self.debuglevel > 0: print 'connect fail:', (host, port)
if self.debuglevel > 0: print>>stderr, 'connect fail:', (host, port)
def connect(self, host='localhost', port = 0): """Connect to a host on a given port.
if self.debuglevel > 0: print "connect:", msg
if self.debuglevel > 0: print>>stderr, "connect:", msg
def connect(self, host='localhost', port = 0): """Connect to a host on a given port.
if self.debuglevel > 0: print 'send:', repr(str)
if self.debuglevel > 0: print>>stderr, 'send:', repr(str)
def send(self, str): """Send `str' to the server.""" if self.debuglevel > 0: print 'send:', repr(str) if self.sock: try: self.sock.sendall(str) except socket.error: self.close() raise SMTPServerDisconnected('Server not connected') else: raise SMTPServerDisconnected('please run connect() first')
if self.debuglevel > 0: print 'reply:', repr(line)
if self.debuglevel > 0: print>>stderr, 'reply:', repr(line)
def getreply(self): """Get a reply from the server.
print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
def getreply(self): """Get a reply from the server.
if self.debuglevel >0 : print "data:", (code,repl)
if self.debuglevel >0 : print>>stderr, "data:", (code,repl)
def data(self,msg): """SMTP 'DATA' command -- sends message data to server.
if self.debuglevel >0 : print "data:", (code,msg)
if self.debuglevel >0 : print>>stderr, "data:", (code,msg)
def data(self,msg): """SMTP 'DATA' command -- sends message data to server.
... def f():
... def _f():
... def f():
>>> d = {"_f": m1.f, "g": m1.g, "h": m1.H, ... "f2": m2.f, "g2": m2.g, "h2": m2.H}
... def bar(self):
>>> t.rundict(d, "rundict_test", m1)
>>> t.rundict(m1.__dict__, "rundict_test", m1)
... def bar(self):
>>> t.rundict(d, "rundict_test_pvt", m1)
>>> t.rundict(m1.__dict__, "rundict_test_pvt", m1)
... def bar(self):
>>> t.rundict(d, "rundict_test_pvt")
>>> t.rundict(m1.__dict__, "rundict_test_pvt")
... def bar(self):
f, t = tester.rundict(m.__dict__, name)
f, t = tester.rundict(m.__dict__, name, m)
def testmod(m, name=None, globs=None, verbose=None, isprivate=None, report=1): """m, name=None, globs=None, verbose=None, isprivate=None, report=1 Test examples in docstrings in functions and classes reachable from module m, starting with m.__doc__. Private names are skipped. Also test examples reachable from dict m.__test__ if it exists and is not None. m.__dict__ maps names to functions, classes and strings; function and class docstrings are tested even if the name is private; strings are tested directly, as if they were docstrings. Return (#failures, #tests). See doctest.__doc__ for an overview. Optional keyword arg "name" gives the name of the module; by default use m.__name__. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use m.__dict__. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "isprivate" specifies a function used to determine whether a name is private. The default function is doctest.is_private; see its docs for details. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if not _ismodule(m): raise TypeError("testmod: module required; " + `m`) if name is None: name = m.__name__ tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate) failures, tries = tester.rundoc(m, name) f, t = tester.rundict(m.__dict__, name) failures = failures + f tries = tries + t if hasattr(m, "__test__"): testdict = m.__test__ if testdict: if not hasattr(testdict, "items"): raise TypeError("testmod: module.__test__ must support " ".items(); " + `testdict`) f, t = tester.run__test__(testdict, name + ".__test__") failures = failures + f tries = tries + t if report: tester.summarize() if master is None: master = tester else: master.merge(tester) return failures, tries
[("MyInBuffer", 'inDataPtr', "InMode")])
[("MyInBuffer", 'inDataPtr', "InMode")]), ([("Boolean", 'ioWasInRgn', "OutMode")], [("Boolean", 'ioWasInRgn', "InOutMode")]),
def makerepairinstructions(self): return [ ([("UInt32", 'inSize', "InMode"), ("void_ptr", 'inDataPtr', "InMode")], [("MyInBuffer", 'inDataPtr', "InMode")]) ]
print ("bdist.run: format=%s, command=%s, rest=%s" % (self.formats[i], cmd_name, commands[i+1:]))
def run (self):
os.fsync(f.fileno())
if hasattr(os, 'fsync'): os.fsync(f.fileno())
def _sync_flush(f): """Ensure changes to file f are physically on disk.""" f.flush() os.fsync(f.fileno())
self.dict[headerseen] = string.strip(line[len(headerseen)+2:])
self.dict[headerseen] = string.strip(line[len(headerseen)+1:])
def readheaders(self): """Read header lines. Read header lines up to the entirely blank line that terminates them. The (normally blank) line that ends the headers is skipped, but not included in the returned list. If a non-header line ends the headers, (which is an error), an attempt is made to backspace over it; it is never included in the returned list. The variable self.status is set to the empty string if all went well, otherwise it is an error message. The variable self.headers is a completely uninterpreted list of lines contained in the header (so printing them will reproduce the header exactly as it appears in the file). """ self.dict = {} self.unixfrom = '' self.headers = list = [] self.status = '' headerseen = "" firstline = 1 startofline = unread = tell = None if hasattr(self.fp, 'unread'): unread = self.fp.unread elif self.seekable: tell = self.fp.tell while 1: if tell: startofline = tell() line = self.fp.readline() if not line: self.status = 'EOF in headers' break # Skip unix From name time lines if firstline and line[:5] == 'From ': self.unixfrom = self.unixfrom + line continue firstline = 0 if headerseen and line[0] in ' \t': # It's a continuation line. list.append(line) x = (self.dict[headerseen] + "\n " + string.strip(line)) self.dict[headerseen] = string.strip(x) continue elif self.iscomment(line): # It's a comment. Ignore it. continue elif self.islast(line): # Note! No pushback here! The delimiter line gets eaten. break headerseen = self.isheader(line) if headerseen: # It's a legal header line, save it. list.append(line) self.dict[headerseen] = string.strip(line[len(headerseen)+2:]) continue else: # It's not a header line; throw it back and stop here. if not self.dict: self.status = 'No headers' else: self.status = 'Non-header line where header expected' # Try to undo the read. if unread: unread(line) elif tell: self.fp.seek(startofline) else: self.status = self.status + '; bad seek' break
"""Signals the start of an element.
def endElement(self, name): """Signals the end of an element in non-namespace mode. The name parameter contains the name of the element type, just as with the startElement event.""" def startElementNS(self, name, qname, attrs): """Signals the start of an element in namespace mode.
def startElement(self, name, attrs): """Signals the start of an element.
def endElement(self, name ): """Signals the end of an element.
def endElementNS(self, name, qname): """Signals the end of an element in namespace mode.
def endElement(self, name ): """Signals the end of an element.
as with the startElement event."""
as with the startElementNS event."""
def endElement(self, name ): """Signals the end of an element.
{'code': code, 'message': message, 'explain': explain})
{'code': code, 'message': _quote_html(message), 'explain': explain})
def send_error(self, code, message=None): """Send and log an error reply.
child.id = None
child.my_id = None
def my_ringer(child): child.id = None stdwin.fleep()
WindowSched.enter(child.my_number*1000, 0, my_ringer, child)
WindowSched.enter(child.my_number*1000, 0, my_ringer, (child,))
def my_hook(child): # schedule for the bell to ring in N seconds; cancel previous if child.my_id: WindowSched.cancel(child.my_id) child.my_id = \ WindowSched.enter(child.my_number*1000, 0, my_ringer, child)
self._parseheaders(root, fp)
firstbodyline = self._parseheaders(root, fp)
def parse(self, fp, headersonly=False): """Create a message structure from the data in a file.
self._parsebody(root, fp)
self._parsebody(root, fp, firstbodyline)
def parse(self, fp, headersonly=False): """Create a message structure from the data in a file.
raise Errors.HeaderParseError( "Not a header, not a continuation: ``%s''"%line)
firstbodyline = line break
def _parseheaders(self, container, fp): # Parse the headers, returning a list of header/value pairs. None as # the header means the Unix-From header. lastheader = '' lastvalue = [] lineno = 0 while True: # Don't strip the line before we test for the end condition, # because whitespace-only header lines are RFC compliant # continuation lines. line = fp.readline() if not line: break line = line.splitlines()[0] if not line: break # Ignore the trailing newline lineno += 1 # Check for initial Unix From_ line if line.startswith('From '): if lineno == 1: container.set_unixfrom(line) continue elif self._strict: raise Errors.HeaderParseError( 'Unix-from in headers after first rfc822 header') else: # ignore the wierdly placed From_ line # XXX: maybe set unixfrom anyway? or only if not already? continue # Header continuation line if line[0] in ' \t': if not lastheader: raise Errors.HeaderParseError( 'Continuation line seen before first header') lastvalue.append(line) continue # Normal, non-continuation header. BAW: this should check to make # sure it's a legal header, e.g. doesn't contain spaces. Also, we # should expose the header matching algorithm in the API, and # allow for a non-strict parsing mode (that ignores the line # instead of raising the exception). i = line.find(':') if i < 0: if self._strict: raise Errors.HeaderParseError( "Not a header, not a continuation: ``%s''"%line) elif lineno == 1 and line.startswith('--'): # allow through duplicate boundary tags. continue else: raise Errors.HeaderParseError( "Not a header, not a continuation: ``%s''"%line) if lastheader: container[lastheader] = NL.join(lastvalue) lastheader = line[:i] lastvalue = [line[i+1:].lstrip()] # Make sure we retain the last header if lastheader: container[lastheader] = NL.join(lastvalue)
def _parsebody(self, container, fp):
return firstbodyline def _parsebody(self, container, fp, firstbodyline=None):
def _parseheaders(self, container, fp): # Parse the headers, returning a list of header/value pairs. None as # the header means the Unix-From header. lastheader = '' lastvalue = [] lineno = 0 while True: # Don't strip the line before we test for the end condition, # because whitespace-only header lines are RFC compliant # continuation lines. line = fp.readline() if not line: break line = line.splitlines()[0] if not line: break # Ignore the trailing newline lineno += 1 # Check for initial Unix From_ line if line.startswith('From '): if lineno == 1: container.set_unixfrom(line) continue elif self._strict: raise Errors.HeaderParseError( 'Unix-from in headers after first rfc822 header') else: # ignore the wierdly placed From_ line # XXX: maybe set unixfrom anyway? or only if not already? continue # Header continuation line if line[0] in ' \t': if not lastheader: raise Errors.HeaderParseError( 'Continuation line seen before first header') lastvalue.append(line) continue # Normal, non-continuation header. BAW: this should check to make # sure it's a legal header, e.g. doesn't contain spaces. Also, we # should expose the header matching algorithm in the API, and # allow for a non-strict parsing mode (that ignores the line # instead of raising the exception). i = line.find(':') if i < 0: if self._strict: raise Errors.HeaderParseError( "Not a header, not a continuation: ``%s''"%line) elif lineno == 1 and line.startswith('--'): # allow through duplicate boundary tags. continue else: raise Errors.HeaderParseError( "Not a header, not a continuation: ``%s''"%line) if lastheader: container[lastheader] = NL.join(lastvalue) lastheader = line[:i] lastvalue = [line[i+1:].lstrip()] # Make sure we retain the last header if lastheader: container[lastheader] = NL.join(lastvalue)
container.set_payload(fp.read())
text = fp.read() if firstbodyline is not None: text = firstbodyline + '\n' + text container.set_payload(text)
def _parsebody(self, container, fp): # Parse the body, but first split the payload on the content-type # boundary if present. boundary = container.get_boundary() isdigest = (container.get_content_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately. Otherwise, just parse the rest of # the body as a single message. Note: any exceptions raised in the # recursive parse need to have their line numbers coerced. if boundary: preamble = epilogue = None # Split into subparts. The first boundary we're looking for won't # always have a leading newline since we're at the start of the # body text, and there's not always a preamble before the first # boundary. separator = '--' + boundary payload = fp.read() # We use an RE here because boundaries can have trailing # whitespace. mo = re.search( r'(?P<sep>' + re.escape(separator) + r')(?P<ws>[ \t]*)', payload) if not mo: if self._strict: raise Errors.BoundaryError( "Couldn't find starting boundary: %s" % boundary) container.set_payload(payload) return start = mo.start() if start > 0: # there's some pre-MIME boundary preamble preamble = payload[0:start] # Find out what kind of line endings we're using start += len(mo.group('sep')) + len(mo.group('ws')) mo = nlcre.search(payload, start) if mo: start += len(mo.group(0)) # We create a compiled regexp first because we need to be able to # specify the start position, and the module function doesn't # support this signature. :( cre = re.compile('(?P<sep>\r\n|\r|\n)' + re.escape(separator) + '--') mo = cre.search(payload, start) if mo: terminator = mo.start() linesep = mo.group('sep') if mo.end() < len(payload): # There's some post-MIME boundary epilogue epilogue = payload[mo.end():] elif self._strict: raise Errors.BoundaryError( "Couldn't find terminating boundary: %s" % boundary) else: # Handle the case of no trailing boundary. Check that it ends # in a blank line. Some cases (spamspamspam) don't even have # that! mo = re.search('(?P<sep>\r\n|\r|\n){2}$', payload) if not mo: mo = re.search('(?P<sep>\r\n|\r|\n)$', payload) if not mo: raise Errors.BoundaryError( 'No terminating boundary and no trailing empty line') linesep = mo.group('sep') terminator = len(payload) # We split the textual payload on the boundary separator, which # includes the trailing newline. If the container is a # multipart/digest then the subparts are by default message/rfc822 # instead of text/plain. In that case, they'll have a optional # block of MIME headers, then an empty line followed by the # message headers. parts = re.split( linesep + re.escape(separator) + r'[ \t]*' + linesep, payload[start:terminator]) for part in parts: if isdigest: if part.startswith(linesep): # There's no header block so create an empty message # object as the container, and lop off the newline so # we can parse the sub-subobject msgobj = self._class() part = part[len(linesep):] else: parthdrs, part = part.split(linesep+linesep, 1) # msgobj in this case is the "message/rfc822" container msgobj = self.parsestr(parthdrs, headersonly=1) # while submsgobj is the message itself msgobj.set_default_type('message/rfc822') maintype = msgobj.get_content_maintype() if maintype in ('message', 'multipart'): submsgobj = self.parsestr(part) msgobj.attach(submsgobj) else: msgobj.set_payload(part) else: msgobj = self.parsestr(part) container.preamble = preamble container.epilogue = epilogue container.attach(msgobj) elif container.get_main_type() == 'multipart': # Very bad. A message is a multipart with no boundary! raise Errors.BoundaryError( 'multipart message with no defined boundary') elif container.get_type() == 'message/delivery-status': # This special kind of type contains blocks of headers separated # by a blank line. We'll represent each header block as a # separate Message object blocks = [] while True: blockmsg = self._class() self._parseheaders(blockmsg, fp) if not len(blockmsg): # No more header blocks left break blocks.append(blockmsg) container.set_payload(blocks) elif container.get_main_type() == 'message': # Create a container for the payload, but watch out for there not # being any headers left try: msg = self.parse(fp) except Errors.HeaderParseError: msg = self._class() self._parsebody(msg, fp) container.attach(msg) else: container.set_payload(fp.read())
def __init__(self, root, flist, stack=None): self.top = top = ListedToplevel(root) top.protocol("WM_DELETE_WINDOW", self.close) top.bind("<Key-Escape>", self.close) top.wm_title("Stack viewer") top.wm_iconname("Stack") self.helplabel = Label(top, text="Click once to view variables; twice for source", borderwidth=2, relief="groove") self.helplabel.pack(fill="x") self.sv = StackViewer(top, flist, self) if stack is None: stack = get_stack() self.sv.load_stack(stack)
def __init__(self, flist=None): self.flist = flist self.stack = get_stack() self.text = get_exception()
def __init__(self, root, flist, stack=None): self.top = top = ListedToplevel(root) top.protocol("WM_DELETE_WINDOW", self.close) top.bind("<Key-Escape>", self.close) top.wm_title("Stack viewer") top.wm_iconname("Stack") # Create help label self.helplabel = Label(top, text="Click once to view variables; twice for source", borderwidth=2, relief="groove") self.helplabel.pack(fill="x") # self.sv = StackViewer(top, flist, self) if stack is None: stack = get_stack() self.sv.load_stack(stack)
def close(self, event=None): self.top.destroy()
def GetText(self): return self.text
def close(self, event=None): self.top.destroy()
localsframe = None localsviewer = None localsdict = None globalsframe = None globalsviewer = None globalsdict = None curframe = None
def GetSubList(self): sublist = [] for info in self.stack: item = FrameTreeItem(info, self.flist) sublist.append(item) return sublist
def close(self, event=None): self.top.destroy()
def show_frame(self, (frame, lineno)): if frame is self.curframe: return self.curframe = None if frame.f_globals is not self.globalsdict: self.show_globals(frame) self.show_locals(frame) self.curframe = frame
class FrameTreeItem(TreeItem):
def show_frame(self, (frame, lineno)): if frame is self.curframe: return self.curframe = None if frame.f_globals is not self.globalsdict: self.show_globals(frame) self.show_locals(frame) self.curframe = frame
def show_globals(self, frame): title = "Global Variables" if frame.f_globals.has_key("__name__"): try: name = str(frame.f_globals["__name__"]) + "" except: name = "" if name: title = title + " in module " + name self.globalsdict = None if self.globalsviewer: self.globalsviewer.close() self.globalsviewer = None if not self.globalsframe: self.globalsframe = Frame(self.top) self.globalsdict = frame.f_globals self.globalsviewer = NamespaceViewer( self.globalsframe, title, self.globalsdict) self.globalsframe.pack(fill="both", side="bottom")
def __init__(self, info, flist): self.info = info self.flist = flist
def show_globals(self, frame): title = "Global Variables" if frame.f_globals.has_key("__name__"): try: name = str(frame.f_globals["__name__"]) + "" except: name = "" if name: title = title + " in module " + name self.globalsdict = None if self.globalsviewer: self.globalsviewer.close() self.globalsviewer = None if not self.globalsframe: self.globalsframe = Frame(self.top) self.globalsdict = frame.f_globals self.globalsviewer = NamespaceViewer( self.globalsframe, title, self.globalsdict) self.globalsframe.pack(fill="both", side="bottom")
def show_locals(self, frame): self.localsdict = None if self.localsviewer: self.localsviewer.close() self.localsviewer = None if frame.f_locals is not frame.f_globals: title = "Local Variables" code = frame.f_code funcname = code.co_name if funcname not in ("?", "", None): title = title + " in " + funcname if not self.localsframe: self.localsframe = Frame(self.top) self.localsdict = frame.f_locals self.localsviewer = NamespaceViewer( self.localsframe, title, self.localsdict) self.localsframe.pack(fill="both", side="top") else: if self.localsframe: self.localsframe.forget() class StackViewer(ScrolledList): def __init__(self, master, flist, browser): ScrolledList.__init__(self, master, width=80) self.flist = flist self.browser = browser self.stack = [] def load_stack(self, stack, index=None): self.stack = stack self.clear() for i in range(len(stack)): frame, lineno = stack[i] try: modname = frame.f_globals["__name__"] except: modname = "?" code = frame.f_code filename = code.co_filename funcname = code.co_name sourceline = linecache.getline(filename, lineno) sourceline = string.strip(sourceline) if funcname in ("?", "", None): item = "%s, line %d: %s" % (modname, lineno, sourceline) else: item = "%s.%s(), line %d: %s" % (modname, funcname, lineno, sourceline) if i == index: item = "> " + item self.append(item) if index is not None: self.select(index) def popup_event(self, event): if self.stack: return ScrolledList.popup_event(self, event) def fill_menu(self): menu = self.menu menu.add_command(label="Go to source line", command=self.goto_source_line) menu.add_command(label="Show stack frame", command=self.show_stack_frame) def on_select(self, index): if 0 <= index < len(self.stack): self.browser.show_frame(self.stack[index]) def on_double(self, index): self.show_source(index) def goto_source_line(self): index = self.listbox.index("active") self.show_source(index) def show_stack_frame(self): index = self.listbox.index("active") if 0 <= index < len(self.stack): self.browser.show_frame(self.stack[index]) def show_source(self, index): if not (0 <= index < len(self.stack)): return frame, lineno = self.stack[index]
def GetText(self): frame, lineno = self.info try: modname = frame.f_globals["__name__"] except: modname = "?"
def show_locals(self, frame): self.localsdict = None if self.localsviewer: self.localsviewer.close() self.localsviewer = None if frame.f_locals is not frame.f_globals: title = "Local Variables" code = frame.f_code funcname = code.co_name if funcname not in ("?", "", None): title = title + " in " + funcname if not self.localsframe: self.localsframe = Frame(self.top) self.localsdict = frame.f_locals self.localsviewer = NamespaceViewer( self.localsframe, title, self.localsdict) self.localsframe.pack(fill="both", side="top") else: if self.localsframe: self.localsframe.forget()
if os.path.isfile(filename):
funcname = code.co_name sourceline = linecache.getline(filename, lineno) sourceline = string.strip(sourceline) if funcname in ("?", "", None): item = "%s, line %d: %s" % (modname, lineno, sourceline) else: item = "%s.%s(...), line %d: %s" % (modname, funcname, lineno, sourceline) return item def GetSubList(self): frame, lineno = self.info sublist = [] if frame.f_globals is not frame.f_locals: item = VariablesTreeItem("<locals>", frame.f_locals, self.flist) sublist.append(item) item = VariablesTreeItem("<globals>", frame.f_globals, self.flist) sublist.append(item) return sublist def OnDoubleClick(self): if self.flist: frame, lineno = self.info filename = frame.f_code.co_filename
def show_source(self, index): if not (0 <= index < len(self.stack)): return frame, lineno = self.stack[index] code = frame.f_code filename = code.co_filename if os.path.isfile(filename): edit = self.flist.open(filename) if edit: edit.gotoline(lineno)
if edit: edit.gotoline(lineno)
edit.gotoline(lineno)
def show_source(self, index): if not (0 <= index < len(self.stack)): return frame, lineno = self.stack[index] code = frame.f_code filename = code.co_filename if os.path.isfile(filename): edit = self.flist.open(filename) if edit: edit.gotoline(lineno)
def getexception(type=None, value=None):
def get_exception(type=None, value=None):
def get_stack(t=None, f=None): if t is None: t = sys.last_traceback stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next return stack
class NamespaceViewer: def __init__(self, master, title, dict=None): width = 0 height = 40 if dict: height = 20*len(dict) self.master = master self.title = title self.repr = Repr() self.repr.maxstring = 60 self.repr.maxother = 60 self.frame = frame = Frame(master) self.frame.pack(expand=1, fill="both") self.label = Label(frame, text=title, borderwidth=2, relief="groove") self.label.pack(fill="x") self.vbar = vbar = Scrollbar(frame, name="vbar") vbar.pack(side="right", fill="y") self.canvas = canvas = Canvas(frame, height=min(300, max(40, height)), scrollregion=(0, 0, width, height)) canvas.pack(side="left", fill="both", expand=1) vbar["command"] = canvas.yview canvas["yscrollcommand"] = vbar.set self.subframe = subframe = Frame(canvas) self.sfid = canvas.create_window(0, 0, window=subframe, anchor="nw") self.load_dict(dict) dict = -1 def load_dict(self, dict, force=0): if dict is self.dict and not force: return subframe = self.subframe frame = self.frame for c in subframe.children.values(): c.destroy() self.dict = None if not dict: l = Label(subframe, text="None") l.grid(row=0, column=0) else: names = dict.keys() names.sort() row = 0 for name in names: value = dict[name] svalue = self.repr.repr(value) l = Label(subframe, text=name) l.grid(row=row, column=0, sticky="nw") l = Entry(subframe, width=0, borderwidth=0) l.insert(0, svalue) l.grid(row=row, column=1, sticky="nw") row = row+1 self.dict = dict subframe.update_idletasks() width = subframe.winfo_reqwidth() height = subframe.winfo_reqheight() canvas = self.canvas self.canvas["scrollregion"] = (0, 0, width, height) if height > 300: canvas["height"] = 300 frame.pack(expand=1) else: canvas["height"] = height frame.pack(expand=0) def close(self): self.frame.destroy()
if __name__ == "__main__": root = Tk() root.withdraw() StackBrowser(root)
def getexception(type=None, value=None): if type is None: type = sys.last_type value = sys.last_value if hasattr(type, "__name__"): type = type.__name__ s = str(type) if value is not None: s = s + ": " + str(value) return s
Aassumes that the line does *not* end with \r\n.
Assumes that the line does *not* end with \\r\\n.
def _output(self, s): """Add a line of output to the current request buffer. Aassumes that the line does *not* end with \r\n. """ self._buffer.append(s)
Appends an extra \r\n to the buffer.
Appends an extra \\r\\n to the buffer.
def _send_output(self): """Send the currently buffered request and clear the buffer.
self.compiler = new_compiler (verbose=self.verbose,
self.compiler = new_compiler (compiler=self.compiler, verbose=self.verbose,
def run (self):
while 1:
while formlength > 0:
def initfp(self, file): self._file = file self._version = 0 self._decomp = None self._markers = [] self._soundpos = 0 form = self._file.read(4) if form != 'FORM': raise Error, 'file does not start with FORM id' formlength = _read_long(self._file) if formlength <= 0: raise Error, 'invalid FORM chunk data size' formdata = self._file.read(4) formlength = formlength - 4 if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk().init(self._file) except EOFError: raise Error, 'COMM chunk and/or SSND chunk missing' formlength = formlength - 8 - chunk.chunksize if chunk.chunksize & 1: formlength = formlength - 1 if chunk.chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunk.chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 if formlength <= 0: if not self._comm_chunk_read: raise Error, 'COMM chunk missing' break elif chunk.chunkname == 'FVER': self._version = _read_long(chunk) elif chunk.chunkname == 'MARK': self._readmark(chunk) elif chunk.chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if self._aifc and self._decomp: params = [CL.ORIGINAL_FORMAT, 0, \ CL.BITS_PER_COMPONENT, 0, \ CL.FRAME_RATE, self._framerate] if self._nchannels == AL.MONO: params[1] = CL.MONO else: params[1] = CL.STEREO_INTERLEAVED if self._sampwidth == AL.SAMPLE_8: params[3] = 8 elif self._sampwidth == AL.SAMPLE_16: params[3] = 16 else: params[3] = 24 self._decomp.SetParams(params) return self
try: chunk = Chunk().init(self._file) except EOFError: raise Error, 'COMM chunk and/or SSND chunk missing'
chunk = Chunk().init(self._file)
def initfp(self, file): self._file = file self._version = 0 self._decomp = None self._markers = [] self._soundpos = 0 form = self._file.read(4) if form != 'FORM': raise Error, 'file does not start with FORM id' formlength = _read_long(self._file) if formlength <= 0: raise Error, 'invalid FORM chunk data size' formdata = self._file.read(4) formlength = formlength - 4 if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk().init(self._file) except EOFError: raise Error, 'COMM chunk and/or SSND chunk missing' formlength = formlength - 8 - chunk.chunksize if chunk.chunksize & 1: formlength = formlength - 1 if chunk.chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunk.chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 if formlength <= 0: if not self._comm_chunk_read: raise Error, 'COMM chunk missing' break elif chunk.chunkname == 'FVER': self._version = _read_long(chunk) elif chunk.chunkname == 'MARK': self._readmark(chunk) elif chunk.chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if self._aifc and self._decomp: params = [CL.ORIGINAL_FORMAT, 0, \ CL.BITS_PER_COMPONENT, 0, \ CL.FRAME_RATE, self._framerate] if self._nchannels == AL.MONO: params[1] = CL.MONO else: params[1] = CL.STEREO_INTERLEAVED if self._sampwidth == AL.SAMPLE_8: params[3] = 8 elif self._sampwidth == AL.SAMPLE_16: params[3] = 16 else: params[3] = 24 self._decomp.SetParams(params) return self
if formlength <= 0: if not self._comm_chunk_read: raise Error, 'COMM chunk missing' break
def initfp(self, file): self._file = file self._version = 0 self._decomp = None self._markers = [] self._soundpos = 0 form = self._file.read(4) if form != 'FORM': raise Error, 'file does not start with FORM id' formlength = _read_long(self._file) if formlength <= 0: raise Error, 'invalid FORM chunk data size' formdata = self._file.read(4) formlength = formlength - 4 if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk().init(self._file) except EOFError: raise Error, 'COMM chunk and/or SSND chunk missing' formlength = formlength - 8 - chunk.chunksize if chunk.chunksize & 1: formlength = formlength - 1 if chunk.chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunk.chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 if formlength <= 0: if not self._comm_chunk_read: raise Error, 'COMM chunk missing' break elif chunk.chunkname == 'FVER': self._version = _read_long(chunk) elif chunk.chunkname == 'MARK': self._readmark(chunk) elif chunk.chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if self._aifc and self._decomp: params = [CL.ORIGINAL_FORMAT, 0, \ CL.BITS_PER_COMPONENT, 0, \ CL.FRAME_RATE, self._framerate] if self._nchannels == AL.MONO: params[1] = CL.MONO else: params[1] = CL.STEREO_INTERLEAVED if self._sampwidth == AL.SAMPLE_8: params[3] = 8 elif self._sampwidth == AL.SAMPLE_16: params[3] = 16 else: params[3] = 24 self._decomp.SetParams(params) return self
def setmark(self, (id, pos, name)):
def setmark(self, id, pos, name):
def setmark(self, (id, pos, name)): if id <= 0: raise Error, 'marker ID must be > 0' if pos < 0: raise Error, 'marker position must be >= 0' if type(name) != type(''): raise Error, 'marker name must be a string' for i in range(len(self._markers)): if id == self._markers[i][0]: self._markers[i] = id, pos, name return self._markers.append((id, pos, name))
self._nframes == self._nframeswritten:
self._nframes == self._nframeswritten and \ self._marklength == 0:
def _patchheader(self): curpos = self._file.tell() if self._datawritten & 1: datalength = self._datawritten + 1 self._file.write(chr(0)) else: datalength = self._datawritten if datalength == self._datalength and \ self._nframes == self._nframeswritten: self._file.seek(curpos, 0) return self._file.seek(self._form_length_pos, 0) dummy = self._write_form_length(datalength) self._file.seek(self._nframes_pos, 0) _write_long(self._file, self._nframeswritten) self._file.seek(self._ssnd_length_pos, 0) _write_long(self._file, datalength + 8) self._file.seek(curpos, 0) self._nframes = self._nframeswritten self._datalength = datalength
_write_short(len(self._file, markers))
_write_short(self._file, len(self._markers))
def _writemarkers(self): if len(self._markers) == 0: return self._file.write('MARK') length = 2 for marker in self._markers: id, pos, name = marker length = length + len(name) + 1 + 6 if len(name) & 1 == 0: length = length + 1 _write_long(self._file, length) self._marklength = length + 8 _write_short(len(self._file, markers)) for marker in self._markers: id, pos, name = marker _write_short(self._file, id) _write_long(self._file, pos) _write_string(self._file, name)
context = context.copy()
context = copy.deepcopy(context) context.clear_flags()
def setcontext(context): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() threading.currentThread().__decimal_context__ = context
context = context.copy()
context = copy.deepcopy(context) context.clear_flags()
def setcontext(context, _local=local): """Set this thread's context to context.""" if context in (DefaultContext, BasicContext, ExtendedContext): context = context.copy() _local.__decimal_context__ = context
if self._int[prec-1] %2 == 0:
if self._int[prec-1] & 1 == 0:
def _round_half_even(self, prec, expdiff, context): """Round 5 to even, rest to nearest."""
if tmp._exp % 2 == 1:
if tmp._exp & 1:
def sqrt(self, context=None): """Return the square root of self.
if tmp.adjusted() % 2 == 0:
if tmp.adjusted() & 1 == 0:
def sqrt(self, context=None): """Return the square root of self.
return self._int[-1+self._exp] % 2 == 0
return self._int[-1+self._exp] & 1 == 0
def _iseven(self): """Returns 1 if self is even. Assumes self is an integer.""" if self._exp > 0: return 1 return self._int[-1+self._exp] % 2 == 0
zinfo.flag_bits = 0x08
zinfo.flag_bits = 0x00
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" st = os.stat(filename) mtime = time.localtime(st[8]) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: zinfo = ZipInfo(filename, date_time) else: zinfo = ZipInfo(arcname, date_time) zinfo.external_attr = st[0] << 16 # Unix attributes if compress_type is None: zinfo.compress_type = self.compression else: zinfo.compress_type = compress_type self._writecheck(zinfo) fp = open(filename, "rb") zinfo.flag_bits = 0x08 zinfo.header_offset = self.fp.tell() # Start of header bytes self.fp.write(zinfo.FileHeader()) zinfo.file_offset = self.fp.tell() # Start of file bytes CRC = 0 compress_size = 0 file_size = 0 if zinfo.compress_type == ZIP_DEFLATED: cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) else: cmpr = None while 1: buf = fp.read(1024 * 8) if not buf: break file_size = file_size + len(buf) CRC = binascii.crc32(buf, CRC) if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) fp.close() if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) self.fp.write(buf) zinfo.compress_size = compress_size else: zinfo.compress_size = file_size zinfo.CRC = CRC zinfo.file_size = file_size # Write CRC and file sizes after the file data self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo
CRC = 0 compress_size = 0 file_size = 0
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" st = os.stat(filename) mtime = time.localtime(st[8]) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: zinfo = ZipInfo(filename, date_time) else: zinfo = ZipInfo(arcname, date_time) zinfo.external_attr = st[0] << 16 # Unix attributes if compress_type is None: zinfo.compress_type = self.compression else: zinfo.compress_type = compress_type self._writecheck(zinfo) fp = open(filename, "rb") zinfo.flag_bits = 0x08 zinfo.header_offset = self.fp.tell() # Start of header bytes self.fp.write(zinfo.FileHeader()) zinfo.file_offset = self.fp.tell() # Start of file bytes CRC = 0 compress_size = 0 file_size = 0 if zinfo.compress_type == ZIP_DEFLATED: cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) else: cmpr = None while 1: buf = fp.read(1024 * 8) if not buf: break file_size = file_size + len(buf) CRC = binascii.crc32(buf, CRC) if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) fp.close() if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) self.fp.write(buf) zinfo.compress_size = compress_size else: zinfo.compress_size = file_size zinfo.CRC = CRC zinfo.file_size = file_size # Write CRC and file sizes after the file data self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo
position = self.fp.tell() self.fp.seek(zinfo.header_offset + 14, 0)
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" st = os.stat(filename) mtime = time.localtime(st[8]) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: zinfo = ZipInfo(filename, date_time) else: zinfo = ZipInfo(arcname, date_time) zinfo.external_attr = st[0] << 16 # Unix attributes if compress_type is None: zinfo.compress_type = self.compression else: zinfo.compress_type = compress_type self._writecheck(zinfo) fp = open(filename, "rb") zinfo.flag_bits = 0x08 zinfo.header_offset = self.fp.tell() # Start of header bytes self.fp.write(zinfo.FileHeader()) zinfo.file_offset = self.fp.tell() # Start of file bytes CRC = 0 compress_size = 0 file_size = 0 if zinfo.compress_type == ZIP_DEFLATED: cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) else: cmpr = None while 1: buf = fp.read(1024 * 8) if not buf: break file_size = file_size + len(buf) CRC = binascii.crc32(buf, CRC) if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) fp.close() if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) self.fp.write(buf) zinfo.compress_size = compress_size else: zinfo.compress_size = file_size zinfo.CRC = CRC zinfo.file_size = file_size # Write CRC and file sizes after the file data self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo
'euc-jp': 'japanese.euc-jp', 'iso-2022-jp': 'japanese.iso-2022-jp', 'shift_jis': 'japanese.shift_jis', 'euc-kr': 'korean.euc-kr', 'ks_c_5601-1987': 'korean.cp949', 'iso-2022-kr': 'korean.iso-2022-kr', 'johab': 'korean.johab', 'gb2132': 'eucgb2312_cn',
'gb2312': 'eucgb2312_cn',
def _isunicode(s): return isinstance(s, UnicodeType)
'utf-8': 'utf-8',
def _isunicode(s): return isinstance(s, UnicodeType)
self.input_codec)
self.output_charset)
def __init__(self, input_charset=DEFAULT_CHARSET): # RFC 2046, $4.1.2 says charsets are not case sensitive input_charset = input_charset.lower() # Set the input charset after filtering through the aliases self.input_charset = ALIASES.get(input_charset, input_charset) # We can try to guess which encoding and conversion to use by the # charset_map dictionary. Try that first, but let the user override # it. henc, benc, conv = CHARSETS.get(self.input_charset, (SHORTEST, BASE64, None)) # Set the attributes, allowing the arguments to override the default. self.header_encoding = henc self.body_encoding = benc self.output_charset = ALIASES.get(conv, conv) # Now set the codecs. If one isn't defined for input_charset, # guess and try a Unicode codec with the same name as input_codec. self.input_codec = CODEC_MAP.get(self.input_charset, self.input_charset) self.output_codec = CODEC_MAP.get(self.output_charset, self.input_codec)
e.set_lk_detect(db.DB_LOCK_DEFAULT)
def _openDBEnv(cachesize): e = db.DBEnv() if cachesize is not None: if cachesize >= 20480: e.set_cachesize(0, cachesize) else: raise error, "cachesize must be >= 20480" e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK | db.DB_INIT_MPOOL) e.set_lk_detect(db.DB_LOCK_DEFAULT) return e
import sys
def test_main(verbose=None): import sys from test import test_sets test_classes = ( TestSet, TestSetSubclass, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, TestExceptionPropagation, TestBasicOpsEmpty, TestBasicOpsSingleton, TestBasicOpsTuple, TestBasicOpsTriple, TestBinaryOps, TestUpdateOps, TestMutate, TestSubsetEqualEmpty, TestSubsetEqualNonEmpty, TestSubsetEmptyNonEmpty, TestSubsetPartial, TestSubsetNonOverlap, TestOnlySetsNumeric, TestOnlySetsDict, TestOnlySetsOperator, TestOnlySetsTuple, TestOnlySetsString, TestOnlySetsGenerator, TestCopyingEmpty, TestCopyingSingleton, TestCopyingTriple, TestCopyingTuple, TestCopyingNested, TestIdentities, TestVariousIteratorArgs, ) test_support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts
if ((template_exists and template_newer) or self.force_manifest or self.manifest_only):
if ((template_exists and (template_newer or setup_newer)) or self.force_manifest or self.manifest_only):
def get_file_list (self): """Figure out the list of files to include in the source distribution, and put it in 'self.files'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """ template_exists = os.path.isfile (self.template) if template_exists: template_newer = newer (self.template, self.manifest)
print>>sys.__stderr__, "** __file__: ", __file__
def view_readme(self, event=None): print>>sys.__stderr__, "** __file__: ", __file__ fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'README.txt') textView.TextViewer(self.top,'IDLEfork - README',fn)
if kind[0] == 'f' and not re.search('\$IN\b', cmd):
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.append: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.append: bad kind ' + `kind` if kind == SOURCE: raise ValueError, \ 'Template.append: SOURCE can only be prepended' if self.steps and self.steps[-1][1] == SINK: raise ValueError, \ 'Template.append: already ends with SINK' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.append: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
if kind[1] == 'f' and not re.search('\$OUT\b', cmd):
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.append: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.append: bad kind ' + `kind` if kind == SOURCE: raise ValueError, \ 'Template.append: SOURCE can only be prepended' if self.steps and self.steps[-1][1] == SINK: raise ValueError, \ 'Template.append: already ends with SINK' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.append: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
if kind[0] == 'f' and not re.search('\$IN\b', cmd):
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.prepend: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.prepend: bad kind ' + `kind` if kind == SINK: raise ValueError, \ 'Template.prepend: SINK can only be appended' if self.steps and self.steps[0][1] == SOURCE: raise ValueError, \ 'Template.prepend: already begins with SOURCE' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.prepend: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
if kind[1] == 'f' and not re.search('\$OUT\b', cmd):
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.prepend: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.prepend: bad kind ' + `kind` if kind == SINK: raise ValueError, \ 'Template.prepend: SINK can only be appended' if self.steps and self.steps[0][1] == SOURCE: raise ValueError, \ 'Template.prepend: already begins with SOURCE' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.prepend: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
version_number = float(version.split('/', 1)[1]) except ValueError:
base_version_number = version.split('/', 1)[1] version_number = base_version_number.split(".") if len(version_number) != 2: raise ValueError version_number = int(version_number[0]), int(version_number[1]) except (ValueError, IndexError):
def parse_request(self): """Parse a request (internal).
if version_number >= 1.1 and self.protocol_version >= "HTTP/1.1":
if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
def parse_request(self): """Parse a request (internal).
if version_number >= 2.0:
if version_number >= (2, 0):
def parse_request(self): """Parse a request (internal).
"Invalid HTTP Version (%f)" % version_number)
"Invalid HTTP Version (%s)" % base_version_number)
def parse_request(self): """Parse a request (internal).
else:
elif (i + 1) < n:
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
elif rawdata[i] == '&':
elif rawdata[i:i+2] == "&
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
if end and rest != "&" and match.group() == rest:
if end and match.group() == rest:
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]