rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
newline = newline + line[:res.start(0)] + \ string.upper('=%02x' % ord(line[res.group(0)])) line = line[res.end(0):] line = newline + line
newline = newline + line[pos:res.start(0)] + \ string.upper('=%02x' % ord(res.group(0))) pos = res.end(0) line = newline + line[pos:]
def mime_encode(line, header): '''Code a single line as quoted-printable. If header is set, quote some extra characters.''' if header: reg = mime_header_char else: reg = mime_char newline = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%...
while 1: res = mime_header.search(line)
pos = 0 while 1: res = mime_header.search(line, pos)
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):...
newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):] return newline + line
newline = '%s%s%s=?%s?Q?%s?=%s' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1), res.group(3)) pos = res.end(0) return newline + line[pos:]
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):...
line = chrset_res.group(1) + \ CHARSET + chrset_res.group(3)
line = '%s%s%s' % (chrset_res.group(1), CHARSET, chrset_res.group(3))
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while...
line = chrset_res.group(1) + 'us-ascii' + chrset_res.group(3)
line = '%sus-ascii%s' % chrset_res.group(1, 3)
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while...
ServerClass = SocketServer.TCPServer):
ServerClass = BaseHTTPServer.HTTPServer):
def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = SocketServer.TCPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' ]
self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' , '/DNDEBUG']
def __init__ (self, verbose=0, dry_run=0, force=0):
except socket.sslerror, msg: break
except socket.sslerror, err: if (err[0] == socket.SSL_ERROR_WANT_READ or err[0] == socket.SSL_ERROR_WANT_WRITE or 0): continue if err[0] == socket.SSL_ERROR_ZERO_RETURN: break raise except socket.error, err: if err[0] = errno.EINTR: continue raise
def makefile(self, mode, bufsize=None): """Return a readable file-like object with data from socket.
This is called by send_reponse().
This is called by send_response().
def log_request(self, code='-', size='-'): """Log an accepted request.
self.errors.append((test, self._exc_info_to_string(err)))
self.errors.append((test, self._exc_info_to_string(err, test)))
def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ self.errors.append((test, self._exc_info_to_string(err)))
self.failures.append((test, self._exc_info_to_string(err)))
self.failures.append((test, self._exc_info_to_string(err, test)))
def addFailure(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().""" self.failures.append((test, self._exc_info_to_string(err)))
def _exc_info_to_string(self, err):
def _exc_info_to_string(self, err, test):
def _exc_info_to_string(self, err): """Converts a sys.exc_info()-style tuple of values into a string.""" return ''.join(traceback.format_exception(*err))
return ''.join(traceback.format_exception(*err))
exctype, value, tb = err while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: length = self._count_relevant_tb_levels(tb) return ''.join(traceback.format_exception(exctype, value, tb, length)) return ''.join(traceback.format_exception(exctype, value, tb)) def _is_relevant...
def _exc_info_to_string(self, err): """Converts a sys.exc_info()-style tuple of values into a string.""" return ''.join(traceback.format_exception(*err))
newtb = tb.tb_next if newtb is None: return (exctype, excvalue, tb) return (exctype, excvalue, newtb)
return (exctype, excvalue, tb)
def __exc_info(self): """Return a version of sys.exc_info() with the traceback frame minimised; usually the top level of the traceback frame is not needed. """ exctype, excvalue, tb = sys.exc_info() if sys.platform[:4] == 'java': ## tracebacks look different in Jython return (exctype, excvalue, tb) newtb = tb.tb_next i...
run_unittest(LongReprTest)
if os.name != 'mac': run_unittest(LongReprTest)
def __repr__(self): raise Exception("This should be caught by Repr.repr_instance")
def __init__(self, *args): apply(URLopener.__init__, (self,) + args)
def __init__(self, *args, **kwargs): apply(URLopener.__init__, (self,) + args, kwargs)
def __init__(self, *args): apply(URLopener.__init__, (self,) + args) self.auth_cache = {} self.tries = 0 self.maxtries = 10
revparse_prog = re.compile(r'^(\d{1,3})\.(\d{1-4})$')
revparse_prog = re.compile(r'^(\d{1,3})\.(\d{1,4})$')
def revparse(rev): global revparse_prog if not revparse_prog: revparse_prog = re.compile(r'^(\d{1,3})\.(\d{1-4})$') m = revparse_prog.match(rev) if not m: return None [major, minor] = map(string.atoi, m.group(1, 2)) return major, minor
'.ps': 'application/postscript',
'.pyo': 'application/x-python-code',
def read_mime_types(file): try: f = open(file) except IOError: return None map = {} while 1: line = f.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: map['.'+suff] ...
self.msg('IAC %d not recognized' % ord(opt))
self.msg('IAC %d not recognized' % ord(c))
def process_rawq(self): """Transfer from raw queue to cooked queue.
raise 'catch me' except:
1/0 except ZeroDivisionError:
def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise 'catch me' except: return sys.exc_traceback.tb_frame.f_back
f = open(filename, 'rb')
f = open(filename, 'rT')
def showframe(self, stackindex): (frame, lineno) = self.stack[stackindex] W.SetCursor('watch') filename = frame.f_code.co_filename if filename <> self.file: editor = self.geteditor(filename) if editor: self.w.panes.bottom.src.source.set(editor.get(), filename) else: try: f = open(filename, 'rb') data = f.read() f.close...
filename = tempfilename = tempfile.mktemp() if not self.writefile(filename):
(tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_') filename = tempfilename os.close(tfd) if not self.writefile(tempfilename):
def print_window(self, event): tempfilename = None saved = self.get_saved() if saved: filename = self.filename # shell undo is reset after every prompt, looks saved, probably isn't if not saved or filename is None: # XXX KBK 08Jun03 Wouldn't it be better to ask the user to save? filename = tempfilename = tempfile.mktem...
print `header`
def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) print `header` try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header e...
return None
return False
def begin(self): self.resetoutput() if use_subprocess: nosub = '' client = self.interp.start_subprocess() if not client: self.close() return None else: nosub = "==== No Subprocess ====" self.write("Python %s on %s\n%s\n%s\nIDLE %s %s\n" % (sys.version, sys.platform, self.COPYRIGHT, self.firewallmessage, idlever.ID...
return client
return True
def begin(self): self.resetoutput() if use_subprocess: nosub = '' client = self.interp.start_subprocess() if not client: self.close() return None else: nosub = "==== No Subprocess ====" self.write("Python %s on %s\n%s\n%s\nIDLE %s %s\n" % (sys.version, sys.platform, self.COPYRIGHT, self.firewallmessage, idlever.ID...
encoding = parts[2]
encoding = parts[2].lower()
def decode(s): """Return a decoded string according to RFC 2047, as a unicode string.""" rtn = [] parts = ecre.split(s, 1) while parts: # If there are less than 4 parts, it can't be encoded and we're done if len(parts) < 5: rtn.extend(parts) break # The first element is any non-encoded leading text rtn.append(parts[0])...
if encoding.lower() == 'q':
if encoding == 'q':
def decode(s): """Return a decoded string according to RFC 2047, as a unicode string.""" rtn = [] parts = ecre.split(s, 1) while parts: # If there are less than 4 parts, it can't be encoded and we're done if len(parts) < 5: rtn.extend(parts) break # The first element is any non-encoded leading text rtn.append(parts[0])...
elif encoding.lower() == 'b':
elif encoding == 'b':
def decode(s): """Return a decoded string according to RFC 2047, as a unicode string.""" rtn = [] parts = ecre.split(s, 1) while parts: # If there are less than 4 parts, it can't be encoded and we're done if len(parts) < 5: rtn.extend(parts) break # The first element is any non-encoded leading text rtn.append(parts[0])...
if encoding.lower() == 'q':
encoding = encoding.lower() if encoding == 'q':
def encode(s, charset='iso-8859-1', encoding='q'): """Encode a string according to RFC 2047.""" if encoding.lower() == 'q': estr = _qencode(s) elif encoding.lower() == 'b': estr = _bencode(s) else: raise ValueError, 'Illegal encoding code: ' + encoding return '=?%s?%s?%s?=' % (charset.lower(), encoding.lower(), estr) ...
elif encoding.lower() == 'b':
elif encoding == 'b':
def encode(s, charset='iso-8859-1', encoding='q'): """Encode a string according to RFC 2047.""" if encoding.lower() == 'q': estr = _qencode(s) elif encoding.lower() == 'b': estr = _bencode(s) else: raise ValueError, 'Illegal encoding code: ' + encoding return '=?%s?%s?%s?=' % (charset.lower(), encoding.lower(), estr) ...
return '=?%s?%s?%s?=' % (charset.lower(), encoding.lower(), estr)
return '=?%s?%s?%s?=' % (charset.lower(), encoding, estr)
def encode(s, charset='iso-8859-1', encoding='q'): """Encode a string according to RFC 2047.""" if encoding.lower() == 'q': estr = _qencode(s) elif encoding.lower() == 'b': estr = _bencode(s) else: raise ValueError, 'Illegal encoding code: ' + encoding return '=?%s?%s?%s?=' % (charset.lower(), encoding.lower(), estr) ...
for checkArgName in expected.keys():
s = str(e) for checkArgName in expected:
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
for checkArgName in expected.keys():
for checkArgName in expected:
def testAttributes(self): # test that exception attributes are happy try: str(u'Hello \u00E1') except Exception, e: sampleUnicodeEncodeError = e
sys.stdout = sys.__stdout__
sys.stdout = saved_stdout
def assertValid(self, str, symbol='single'): '''succeed iff str is a valid piece of code''' if is_jython: code = compile_command(str, "<input>", symbol) self.assert_(code) if symbol == "single": d,r = {},{} sys.stdout = cStringIO.StringIO() try: exec code in d exec compile(str,"<input>","single") in r finally: sys.stdo...
return code.split('.')[:2]
return tuple(code.split('.')[:2])
def _parse_localename(localename): """ Parses the locale code for localename and returns the result as tuple (language code, encoding). The localename is normalized and passed through the locale alias engine. A ValueError is raised in case the locale name cannot be parsed. The language code corresponds to RFC 1766. ...
testit('rint(0.7)', math.rint(0.7), 1) testit('rint(-0.3)', math.rint(-0.3), 0) testit('rint(2.5)', math.rint(2.5), 2) testit('rint(3.5)', math.rint(3.5), 4)
try: math.rint except AttributeError: pass else: testit('rint(0.7)', math.rint(0.7), 1) testit('rint(-0.3)', math.rint(-0.3), 0) testit('rint(2.5)', math.rint(2.5), 2) testit('rint(3.5)', math.rint(3.5), 4)
def testmodf(name, (v1, v2), (e1, e2)): if abs(v1-e1) > eps or abs(v2-e2): raise TestFailed, '%s returned %s, expected %s'%\ (name, `v1,v2`, `e1,e2`)
for tagName in DESCRIPTOR_ELEMENTS: nodes = find_all_elements(doc, tagName) for node in nodes: rewrite_descriptor(doc, node)
sections = find_all_elements(doc, "section") for section in sections: find_and_fix_descriptors(doc, section) def find_and_fix_descriptors(doc, container): children = container.childNodes for child in children: if child.nodeType == xml.dom.core.ELEMENT: tagName = child.tagName if tagName in DESCRIPTOR_ELEMENTS: rewrit...
def fixup_descriptors(doc): for tagName in DESCRIPTOR_ELEMENTS: nodes = find_all_elements(doc, tagName) for node in nodes: rewrite_descriptor(doc, node)
install = self.distribution.get_command_obj('install')
install = self.reinitialize_command('install')
def run (self):
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close()
TESTFN2 = TESTFN + "2"
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
zip = zipfile.ZipFile(f, "r", compression) readData2 = zip.read(srcname) readData1 = zip.read("another"+os.extsep+"name") zip.close()
class TestsWithSourceFile(unittest.TestCase): def setUp(self): line_gen = ("Test of zipfile line %d." % i for i in range(0, 1000)) self.data = '\n'.join(line_gen)
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
if readData1 != srccontents or readData2 != srccontents: raise TestFailed, "Written data doesn't equal read data."
fp = open(TESTFN, "wb") fp.write(self.data) fp.close()
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
try: fp = open(srcname, "wb") for i in range(0, 1000): fp.write("Test of zipfile line %d.\n" % i) fp.close()
zipfp = zipfile.ZipFile(f, "r", compression) self.assertEqual(zipfp.read(TESTFN), self.data) self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data) zipfp.close()
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
fp = open(srcname, "rb") writtenData = fp.read() fp.close()
def testStored(self): for f in (TESTFN2, TemporaryFile(), StringIO()): self.zipTest(f, zipfile.ZIP_STORED)
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
for file in (zipname, tempfile.TemporaryFile(), StringIO.StringIO()): zipTest(file, zipfile.ZIP_STORED, writtenData)
if zlib: def testDeflated(self): for f in (TESTFN2, TemporaryFile(), StringIO()): self.zipTest(f, zipfile.ZIP_DEFLATED)
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
for file in (zipname, tempfile.TemporaryFile(), StringIO.StringIO()): zipTest(file, zipfile.ZIP_DEFLATED, writtenData)
def tearDown(self): os.remove(TESTFN) os.remove(TESTFN2)
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
finally: if os.path.isfile(srcname): os.unlink(srcname) if os.path.isfile(zipname): os.unlink(zipname)
class OtherTests(unittest.TestCase): def testCloseErroneousFile(self): fp = open(TESTFN, "w") fp.write("this is not a legal zip file\n") fp.close() try: zf = zipfile.ZipFile(TESTFN) except zipfile.BadZipfile: os.unlink(TESTFN)
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
fp = open(srcname, "w") fp.write("this is not a legal zip file\n") fp.close() try: zf = zipfile.ZipFile(srcname) except zipfile.BadZipfile: os.unlink(srcname)
self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
try: zipfile.ZipFile(srcname) except IOError: pass else: raise TestFailed("expected creation of readable ZipFile without\n" " a file to raise an IOError.")
self.assertRaises(RuntimeError, zipf.testzip)
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
data = StringIO.StringIO() zipf = zipfile.ZipFile(data, mode="w") zipf.writestr("foo.txt", "O, for a Muse of Fire!") zipf.close() zipf = zipfile.ZipFile(data, mode="r") zipf.close() try: zipf.testzip() except RuntimeError: pass else: raise TestFailed("expected calling .testzip on a closed ZipFile" " to raise a Runt...
if __name__ == "__main__": test_main()
def zipTest(f, compression, srccontents): zip = zipfile.ZipFile(f, "w", compression) # Create the ZIP archive zip.write(srcname, "another"+os.extsep+"name") zip.write(srcname, srcname) zip.close() zip = zipfile.ZipFile(f, "r", compression) # Read the ZIP archive readData2 = zip.read(srcname) readData1 = zip.read("...
if forceload and path in sys.modules: if path not in sys.builtin_module_names: info = inspect.getmoduleinfo(sys.modules[path].__file__) if info[3] != imp.C_EXTENSION: cache[path] = sys.modules[path] del sys.modules[path]
def safeimport(path, forceload=0, cache={}): """Import a module; handle errors; return None if the module isn't found. If the module *is* found but an exception occurs, it's wrapped in an ErrorDuringImport exception and reraised. Unlike __import__, if a package path is specified, the module at the end of the path is ...
def __init__(self, locale_time=LocaleTime()):
def __init__(self, locale_time=None):
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" #XXX: Does 'Y' need to worry about having less or more than 4 digits? base = super(TimeRE, self) base.__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| ...
self.locale_time = locale_time
if locale_time: self.locale_time = locale_time else: self.locale_time = LocaleTime()
def __init__(self, locale_time=LocaleTime()): """Init inst with non-locale regexes and store LocaleTime object.""" #XXX: Does 'Y' need to worry about having less or more than 4 digits? base = super(TimeRE, self) base.__init__({ # The " \d" option is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| ...
install = self.find_peer ('install') inputs = install.get_inputs () outputs = install.get_outputs () assert (len (inputs) == len (outputs))
def run (self):
self.strip_base_dirs (outputs, install)
install = self.distribution.find_command_obj('install') install.root = self.bdist_dir
def run (self):
build_base = self.get_peer_option ('build', 'build_base') output_dir = os.path.join (build_base, "bdist") self.make_install_tree (output_dir, inputs, outputs)
self.announce ("installing to %s" % self.bdist_dir) install.ensure_ready() install.run()
def run (self):
print "output_dir = %s" % output_dir
print "self.bdist_dir = %s" % self.bdist_dir
def run (self):
root_dir=output_dir)
root_dir=self.bdist_dir)
def run (self):
remove_tree (output_dir, self.verbose, self.dry_run)
remove_tree (self.bdist_dir, self.verbose, self.dry_run)
def run (self):
def strip_base_dirs (self, outputs, install_cmd): base = install_cmd.install_base + os.sep platbase = install_cmd.install_platbase + os.sep b_len = len (base) pb_len = len (platbase) for i in range (len (outputs)): if outputs[i][0:b_len] == base: outputs[i] = outputs[i][b_len:] elif outputs[i][0:pb_len] == plat...
def run (self):
vrefnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kSharedLibrariesFolderType, 0) fss = macfs.FSSpec((vrefnum, dirid, fname))
vrefnum, dirid = macfs.FindFolder(MACFS.kLocalDomain, MACFS.kSharedLibrariesFolderType, 1)
def getextensiondirfile(fname): import macfs import MACFS try: vrefnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kSharedLibrariesFolderType, 0) fss = macfs.FSSpec((vrefnum, dirid, fname)) except macfs.error: return None return fss.as_pathname()
return None
try: vrefnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kSharedLibrariesFolderType, 1) except macfs.error: return None fss = macfs.FSSpec((vrefnum, dirid, fname))
def getextensiondirfile(fname): import macfs import MACFS try: vrefnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kSharedLibrariesFolderType, 0) fss = macfs.FSSpec((vrefnum, dirid, fname)) except macfs.error: return None return fss.as_pathname()
if oldcwd != newcwd:
if verbose: print "Not running as applet: Skipping check for preference file correctness." elif oldcwd != newcwd: sys.path.insert(0, os.path.join(oldcwd, ':Mac:Lib'))
def main(): verbose = 0 try: h = Res.GetResource('DLOG', SPLASH_COPYCORE) del h except Res.Error: verbose = 1 print "Not running as applet: verbose on" oldcwd = os.getcwd() os.chdir(sys.prefix) newcwd = os.getcwd() if oldcwd != newcwd: import Dlg rv = Dlg.CautionAlert(ALERT_NOTPYTHONFOLDER, None) if rv == ALERT_NOTPYTH...
imageop.mono2grey(img, x, y, 0, 255)
return imageop.mono2grey(img, x, y, 0, 255)
def mono2grey(img, x, y): imageop.mono2grey(img, x, y, 0, 255)
if hasattr(object, '__doc__') and object.__doc__: lines = string.split(string.expandtabs(object.__doc__), '\n')
try: doc = object.__doc__ except AttributeError: return None if not isinstance(doc, (str, unicode)): return None try: lines = string.split(string.expandtabs(doc), '\n') except UnicodeError: return None else:
def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" if hasattr(object, '__doc__') and object.__doc__: lines ...
<style>TT { font-family: lucida console, lucida typewriter, courier }</style> </head><body bgcolor="
<style type="text/css"><!-- TT { font-family: lucida console, lucida typewriter, courier } --></style></head><body bgcolor="
def page(self, title, contents): """Format an HTML page.""" return '''
result = result + '<p>%s\n' % self.small(doc)
result = result + '<p>%s</p>\n' % self.small(doc)
def docmodule(self, object, name=None): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) l...
if not cl.__dict__.has_key(name):
if object.im_class is not cl:
def docroutine(self, object, name=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): if cl: if not cl._...
reallink = '<a href="%s">%s</a>' % (
reallink = '<a href="
def docroutine(self, object, name=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): if cl: if not cl._...
if not cl.__dict__.has_key(name):
if object.im_class is not cl:
def docroutine(self, object, name=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): if cl: if not cl.__dict__.has_key(name): base = object.im_class basename = base.__name__ if base.__mo...
lib_dirs = self.compiler.library_dirs + ['/lib', '/usr/lib']
lib_dirs = self.compiler.library_dirs + ['/lib', '/usr/lib', '/usr/lib/lib64']
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
return not not self.cl.methods
try: return not not self.cl.methods except AttributeError: return False
def IsExpandable(self): if self.cl: return not not self.cl.methods
if (rframe is frame) and rcur:
if (rframe is not frame) and rcur:
def trace_dispatch_exception(self, frame, t): rt, rtt, rct, rfn, rframe, rcur = self.cur if (rframe is frame) and rcur: return self.trace_dispatch_return(rframe, t) return 0
return int(resp[3:].strip())
s = resp[3:].strip() try: return int(s) except OverflowError: return long(s)
def size(self, filename): '''Retrieve the size of a file.''' # Note that the RFC doesn't say anything about 'SIZE' resp = self.sendcmd('SIZE ' + filename) if resp[:3] == '213': return int(resp[3:].strip())
if m: return int(m.group(1)) return None
if not m: return None s = m.group(1) try: return int(s) except OverflowError: return long(s)
def parse150(resp): '''Parse the '150' response for a RETR request. Returns the expected transfer size or None; size is not guaranteed to be present in the 150 message. ''' if resp[:3] != '150': raise error_reply, resp global _150_re if _150_re is None: import re _150_re = re.compile("150 .* \((\d+) bytes\)", re.IGNORE...
if istart < istop: return istart + int(self.random() * (istop - istart))
def randrange(self, start, stop=None, step=1, int=int, default=None): """Choose a random item from range(start, stop[, step]).
"""Return the sum of the two operands.
"""Return the difference between the two operands.
def subtract(self, a, b): """Return the sum of the two operands.
u = madunicode(u"12345") verify(unicode(u) == u"12345")
base = u"12345" u = madunicode(base) verify(unicode(u) == base)
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__(u"".join(L)) return self._rev
currentThread()
def wait(self, timeout=None): currentThread() # for side-effect assert self._is_owned(), "wait() of un-acquire()d lock" waiter = _allocate_lock() waiter.acquire() self.__waiters.append(waiter) saved_state = self._release_save() try: # restore state no matter what (e.g., KeyboardInterrupt) if timeout is None: waiter....
currentThread()
def notify(self, n=1): currentThread() # for side-effect assert self._is_owned(), "notify() of un-acquire()d lock" __waiters = self.__waiters waiters = __waiters[:n] if not waiters: if __debug__: self._note("%s.notify(): no waiters", self) return self._note("%s.notify(): notifying %d waiter%s", self, n, n!=1 and "s" or...
"[TARGETDIR]Lib;[TARGETDIR]DLLs;[TARGETDIR]lib-tk", "REGISTRY"),
r"[TARGETDIR]Lib;[TARGETDIR]DLLs;[TARGETDIR]Lib\lib-tk", "REGISTRY"),
# File extensions, associated with the REGISTRY.def component
if isclass(object):
if hasattr(object, '__module__'):
def getmodule(object): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file...
def __init__(self, _class=Message.Message):
def __init__(self, _class=Message.Message, strict=1):
def __init__(self, _class=Message.Message): """Parser of RFC 2822 and MIME email messages.
def parse(self, fp):
self._strict = strict def parse(self, fp, headersonly=0):
def __init__(self, _class=Message.Message): """Parser of RFC 2822 and MIME email messages.
self._parsebody(root, fp)
if not headersonly: self._parsebody(root, fp)
def parse(self, fp): root = self._class() self._parseheaders(root, fp) self._parsebody(root, fp) return root
def parsestr(self, text): return self.parse(StringIO(text))
def parsestr(self, text, headersonly=0): return self.parse(StringIO(text), headersonly=headersonly)
def parsestr(self, text): return self.parse(StringIO(text))
else:
elif self._strict:
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 1: # Don't strip the line before we test for the end condition, # because whitespace-only header lines are RFC compliant ...
raise Errors.HeaderParseError( 'Not a header, not a continuation')
if self._strict: raise Errors.HeaderParseError( "Not a header, not a continuation: ``%s''"%line) elif lineno == 1 and line.startswith('--'): continue else: raise Errors.HeaderParseError( "Not a header, not a continuation: ``%s''"%line)
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 1: # Don't strip the line before we test for the end condition, # because whitespace-only header lines are RFC compliant ...
start += len(mo.group(0)) * (1 + isdigest)
start += len(mo.group(0))
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_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately...
if not mo:
if mo: terminator = mo.start() linesep = mo.group('sep') if mo.end() < len(payload): epilogue = payload[mo.end():] elif self._strict:
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_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately...
"Couldn't find terminating boundary: %s" % boundary) terminator = mo.start() linesep = mo.group('sep') if mo.end() < len(payload): epilogue = payload[mo.end():]
"Couldn't find terminating boundary: %s" % boundary) else: endre = re.compile('(?P<sep>\r\n|\r|\n){2}$') mo = endre.search(payload) if not mo: raise Errors.BoundaryError( "Couldn't find terminating boundary, and no "+ "trailing empty line") else: linesep = mo.group('sep') terminator = len(payload)
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_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately...
separator += linesep * (1 + isdigest)
separator += linesep
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_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately...
msgobj = self.parsestr(part)
if isdigest: if part[0] == linesep: msgobj = self._class() part = part[1:] else: parthdrs, part = part.split(linesep+linesep, 1) msgobj = self.parsestr(parthdrs, headersonly=1) submsgobj = self.parsestr(part) msgobj.attach(submsgobj) msgobj.set_default_type('message/rfc822') else: msgobj = self.parsestr(part)
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_type() == 'multipart/digest') # If there's a boundary, split the payload text into its constituent # parts and parse each separately...
funcid, " ".join(self._subst_format)))
funcid, self._subst_format_str))
def _bind(self, what, sequence, func, add, needcleanup=1): """Internal function.""" if type(func) is StringType: self.tk.call(what + (sequence, func)) elif func: funcid = self._register(func, self._substitute, needcleanup) cmd = ('%sif {"[%s %s]" == "break"} break\n' % (add and '+' or '', funcid, " ".join(self._subst_f...
def startElement(self, name, tagName, attrs):
def startElement(self, name, attrs):
def startElement(self, name, tagName, attrs): if not hasattr(self, "curNode"): # FIXME: hack! self.startDocument()
node = self.document.createElement(tagName) for attr in attrs.keys():
node = self.document.createElement(name) for (attr, value) in attrs.items():
def startElement(self, name, tagName, attrs): if not hasattr(self, "curNode"): # FIXME: hack! self.startDocument()
def endElement(self, name, tagName):
def endElement(self, name):
def endElement(self, name, tagName): node = self.curNode self.lastEvent[1] = [(END_ELEMENT, node), None] self.lastEvent = self.lastEvent[1] #self.events.append((END_ELEMENT, node)) self.curNode = node.parentNode
for meth in get_methods(handler):
for meth in dir(handler):
def add_handler(self, handler): added = 0 for meth in get_methods(handler): if meth[-5:] == '_open': protocol = meth[:-5] if self.handle_open.has_key(protocol): self.handle_open[protocol].append(handler) else: self.handle_open[protocol] = [handler] added = 1 continue i = meth.find('_') j = meth[i+1:].find('_') + i + 1 ...
if isinstance(fullurl, types.StringType):
if isinstance(fullurl, (types.StringType, types.UnicodeType)):
def open(self, fullurl, data=None): # accept a URL or a Request object if isinstance(fullurl, types.StringType): req = Request(fullurl, data) else: req = fullurl if data is not None: req.add_data(data) assert isinstance(req, Request) # really only care about interface
def is_callable(obj): if type(obj) in (types.BuiltinFunctionType, types.BuiltinMethodType, types.LambdaType, types.MethodType): return 1 if isinstance(obj, types.InstanceType): return hasattr(obj, '__call__') return 0 def get_methods(inst): methods = {} classes = [] classes.append(inst.__class__) while classes: kla...
def error(self, proto, *args): if proto in ['http', 'https']: # XXX http[s] protocols are special cased dict = self.handle_error['http'] # https is not different then http proto = args[2] # YUCK! meth_name = 'http_error_%d' % proto http_err = 1 orig_args = args else: dict = self.handle_error meth_name = proto + '_erro...
if isinstance(check, types.ClassType):
if inspect.isclass(check):
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP and FTP. If there is a ProxyHandler, it must be at the front of the list of handlers. (Yuck.) If any of the handlers passed as arguments are subclasses of the def...