rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if USE_FROZEN: FROZEN_ARCHIVE = "FrozenModules.marshal" SITE_PY += """\ import imp, marshal f = open(sys.path[0] + "/%s", "rb") imp.set_frozenmodules(marshal.load(f)) f.close() """ % FROZEN_ARCHIVE
if USE_ZIPIMPORT: ZIP_ARCHIVE = "Modules.zip" SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE def getPycData(fullname, code, ispkg): if ispkg: fullname += ".__init__" path = fullname.replace(".", os.sep) + PYC_EXT return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
def report(self): # XXX something decent pass
import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path) sys.modules["%(name)s"] = mod
def __load(): import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path) __load() del __load
def report(self): # XXX something decent pass
if USE_FROZEN: frozenmodules = []
if USE_ZIPIMPORT: import zipfile relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE) abspath = pathjoin(self.bundlepath, relpath) zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
def addPythonModules(self): self.message("Adding Python modules", 1)
if ispkg: self.message("Adding Python package %s" % name, 2) else: self.message("Adding Python module %s" % name, 2) frozenmodules.append((name, marshal.dumps(code), ispkg)) frozenmodules = tuple(frozenmodules) relpath = pathjoin("Contents", "Resources", FROZEN_ARCHIVE) abspath = pathjoin(self.bundlepath, relpath) f = open(abspath, "wb") marshal.dump(frozenmodules, f) f.close()
self.message("Adding Python module %s" % name, 2) path, pyc = getPycData(name, code, ispkg) zf.writestr(path, pyc) zf.close()
def addPythonModules(self): self.message("Adding Python modules", 1)
if USE_FROZEN:
if USE_ZIPIMPORT:
def findDependencies(self): self.message("Finding module dependencies", 1) import modulefinder mf = modulefinder.ModuleFinder(excludes=self.excludeModules) # manually add our own site.py site = mf.add_module("site") site.__code__ = SITE_CO mf.scan_code(SITE_CO, site)
if not USE_FROZEN or name != "site":
if not USE_ZIPIMPORT or name != "site":
def findDependencies(self): self.message("Finding module dependencies", 1) import modulefinder mf = modulefinder.ModuleFinder(excludes=self.excludeModules) # manually add our own site.py site = mf.add_module("site") site.__code__ = SITE_CO mf.scan_code(SITE_CO, site)
f.write("\0" * 8)
f.write(MAGIC) f.write("\0" * 4)
def writePyc(code, path): f = open(path, "wb") f.write("\0" * 8) # don't bother about a time stamp marshal.dump(code, f) f.seek(0, 0) f.write(MAGIC) f.close()
f.seek(0, 0) f.write(MAGIC)
def writePyc(code, path): f = open(path, "wb") f.write("\0" * 8) # don't bother about a time stamp marshal.dump(code, f) f.seek(0, 0) f.write(MAGIC) f.close()
print "link_shared_object():" print " output_filename =", output_filename print " mkpath'ing:", os.path.dirname (output_filename)
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None):
else: if __debug__: self.fail("AssertionError not raised by assert 0")
def testAssert(self): # assert_stmt: 'assert' test [',' test] assert 1 assert 1, 1 assert lambda x:x assert 1, lambda x:x+1 try: assert 0, "msg" except AssertionError, e: self.assertEquals(e.args[0], "msg") # we can not expect an assertion error to be raised # if the tests are run in an optimized python #else: # self.fail("AssertionError not raised by assert 0")
self.badmodules[fqname][parent.__name__] = None
if parent: self.badmodules[fqname][parent.__name__] = None
def import_module(self, partname, fqname, parent): self.msgin(3, "import_module", partname, fqname, parent) try: m = self.modules[fqname] except KeyError: pass else: self.msgout(3, "import_module ->", m) return m if self.badmodules.has_key(fqname): self.msgout(3, "import_module -> None") self.badmodules[fqname][parent.__name__] = None return None try: fp, pathname, stuff = self.find_module(partname, parent and parent.__path__) except ImportError: self.msgout(3, "import_module ->", None) return None try: m = self.load_module(fqname, fp, pathname, stuff) finally: if fp: fp.close() if parent: setattr(parent, partname, m) self.msgout(3, "import_module ->", m) return m
self.d.DragWindow(where, screenbounds)
self.w.DragWindow(where, screenbounds)
def _update(self, value): maxval = self.maxval if maxval == 0: # XXXX Quick fix. Should probably display an unknown duration value = 0 maxval = 1 if maxval > 32767: value = int(value/(maxval/32767.0)) maxval = 32767 progbar = self.d.GetDialogItemAsControl(3) progbar.SetControlMaximum(maxval) progbar.SetControlValue(value) # Test for cancel button ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 ) if ready : what,msg,when,where,mod = ev part = Win.FindWindow(where)[0] if Dlg.IsDialogEvent(ev): ds = Dlg.DialogSelect(ev) if ds[0] and ds[1] == self.d and ds[-1] == 1: self.w.HideWindow() self.w = None self.d = None raise KeyboardInterrupt, ev else: if part == 4: # inDrag self.d.DragWindow(where, screenbounds) else: MacOS.HandleEvent(ev)
write32(self.fileobj, int(time.time()))
write32u(self.fileobj, long(time.time()))
def _write_gzip_header(self): self.fileobj.write('\037\213') # magic header self.fileobj.write('\010') # compression method fname = self.filename[:-3] flags = 0 if fname: flags = FNAME self.fileobj.write(chr(flags)) write32(self.fileobj, int(time.time())) self.fileobj.write('\002') self.fileobj.write('\377') if fname: self.fileobj.write(fname + '\000')
if crc32 != self.crc:
if crc32%0x100000000L != self.crc%0x100000000L:
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = read32(self.fileobj) if crc32 != self.crc: raise ValueError, "CRC check failed" elif isize != self.size: raise ValueError, "Incorrect length of data produced"
def do_event(self, (dev, val)):
def do_event(self, dev, val):
def do_event(self, (dev, val)): if dev == DEVICE.REDRAW: if self.vin: self.vin.redraw(val) if self.vout: self.vout.redraw(val)
def cb_in_new(self, args):
def cb_in_new(self, *args):
def cb_in_new(self, args): self.msg('') hd, tl = os.path.split(self.ifile) filename = fl.file_selector('Input video file', hd, '', tl) if not filename: return self.open_input(filename)
def cb_in_close(self, args):
def cb_in_close(self, *args):
def cb_in_close(self, args): self.msg('') self.close_input()
def cb_in_skip(self, args):
def cb_in_skip(self, *args):
def cb_in_skip(self, args): if not self.icheck(): return if not self.vin.get(): self.err('End of input file') self.ishow()
def cb_in_back(self, args):
def cb_in_back(self, *args):
def cb_in_back(self, args): if not self.icheck(): return if not self.vin.backup(): self.err('Input buffer exhausted') self.ishow()
def cb_in_rewind(self, args):
def cb_in_rewind(self, *args):
def cb_in_rewind(self, args): if not self.icheck(): return self.vin.rewind() self.ishow()
def cb_copy(self, args):
def cb_copy(self, *args):
def cb_copy(self, args): if not self.iocheck(): return data = self.vin.get() if not data: self.err('End of input file') self.ishow() return if self.vout.getinfo() <> self.vin.getinfo(): print 'Copying info...' self.vout.setinfo(self.vin.getinfo()) self.vout.put(data) self.oshow() self.ishow()
def cb_uncopy(self, args):
def cb_uncopy(self, *args):
def cb_uncopy(self, args): if not self.iocheck(): return if not self.vout.backup(): self.err('Output buffer exhausted') return self.oshow() if not self.vin.backup(): self.err('Input buffer exhausted') return self.ishow()
def cb_out_new(self, args):
def cb_out_new(self, *args):
def cb_out_new(self, args): self.msg('') hd, tl = os.path.split(self.ofile) filename = fl.file_selector('Output video file', hd, '', tl) if not filename: return self.open_output(filename)
def cb_out_close(self, args):
def cb_out_close(self, *args):
def cb_out_close(self, args): self.msg('') self.close_output()
def cb_out_skip(self, arg):
def cb_out_skip(self, *args):
def cb_out_skip(self, arg): if not self.ocheck(): return if not self.vout.forward(): self.err('Output buffer exhausted') self.oshow()
def cb_out_back(self, args):
def cb_out_back(self, *args):
def cb_out_back(self, args): if not self.ocheck(): return if not self.vout.backup(): self.err('Output buffer exhausted') self.oshow()
def cb_out_rewind(self, args):
def cb_out_rewind(self, *args):
def cb_out_rewind(self, args): if not self.ocheck(): return self.vout.rewind() self.oshow()
def cb_quit(self, args):
def cb_quit(self, *args):
def cb_quit(self, args): self.close_input() self.close_output() sys.exit(0)
self.para.words.append(self.nextfont, text, \ self.d.textwidth(text), space, space, \ self.ascent, self.descent)
self.para.words.append((self.nextfont, text, self.d.textwidth(text), space, space, self.ascent, self.descent))
def addword(self, text, space): if self.nospace and not text: return self.nospace = 0 self.blanklines = 0 if not self.para: self.para = self.newpara() self.para.indent_left = self.leftindent self.para.just = self.just self.nextfont = self.font space = int(space * self.space) self.para.words.append(self.nextfont, text, \ self.d.textwidth(text), space, space, \ self.ascent, self.descent) self.nextfont = None
self.window.show( \
self.window.show(
def showanchor(self, id): for i in range(len(self.paralist)): p = self.paralist[i] if p.hasanchor(id): long1 = i, 0 long2 = i, len(p.extract()) hit = long1, long2 self.setselection(hit) self.window.show( \ (p.left, p.top), (p.right, p.bottom)) break
it = iter(self._fp)
eq(iter(self._fp), self._fp)
def test_iterator(self): eq = self.assertEqual unless = self.failUnless it = iter(self._fp) # Does this object support the iteration protocol? unless(hasattr(it, '__iter__')) unless(hasattr(it, 'next')) i = 0 for line in self._fp: eq(line, self._line + '\n') i += 1 eq(i, 5)
unless(hasattr(it, '__iter__')) unless(hasattr(it, 'next'))
unless(hasattr(self._fp, '__iter__')) unless(hasattr(self._fp, 'next'))
def test_iterator(self): eq = self.assertEqual unless = self.failUnless it = iter(self._fp) # Does this object support the iteration protocol? unless(hasattr(it, '__iter__')) unless(hasattr(it, 'next')) i = 0 for line in self._fp: eq(line, self._line + '\n') i += 1 eq(i, 5)
'member', 'sectcode', 'verb'):
'member', 'sectcode', 'verb', 'cfunction', 'cdata', 'ctype', ):
def startchange(): global hist, out hist.chaptertype = "chapter" hist.inenv = [] hist.nodenames = [] hist.cindex = [] hist.inargs = 0 hist.enumeratenesting, hist.itemizenesting = 0, 0 out.doublenodes = [] out.doublecindeces = []
command = '' cat_class = '' if idxsi and idxsi[-1] in ('method', 'protocol', 'attribute'): command = 'defmethod' cat_class = string.join(idxsi[:-1]) elif len(idxsi) == 2 and idxsi[1] == 'function': command = 'deffn' cat_class = string.join(idxsi) elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: command = 'deffn' cat_class = 'function of ' + string.join(idxsi[1:]) elif len(idxsi) > 3 and idxsi[:2] == ['in', 'modules']: command = 'deffn' cat_class = 'function of ' + string.join(idxsi[1:]) if not command: raise error, 'don\'t know what to do with indexsubitem ' + `idxsi`
command = 'deffn' if hist.this_module: cat_class = 'function of ' + hist.this_module else: cat_class = 'built-in function'
def do_funcdesc(length, buf, pp, i, index=1): startpoint = i-1 ch = pp[startpoint] wh = ch.where length, newi = getnextarg(length, buf, pp, i) funcname = chunk(GROUP, wh, pp[i:newi]) del pp[i:newi] length = length - (newi-i) save = hist.inargs hist.inargs = 1 length, newi = getnextarg(length, buf, pp, i) hist.inargs = save del save the_args = [chunk(PLAIN, wh, '()'[0])] + pp[i:newi] + \ [chunk(PLAIN, wh, '()'[1])] del pp[i:newi] length = length - (newi-i) idxsi = hist.indexsubitem # words command = '' cat_class = '' if idxsi and idxsi[-1] in ('method', 'protocol', 'attribute'): command = 'defmethod' cat_class = string.join(idxsi[:-1]) elif len(idxsi) == 2 and idxsi[1] == 'function': command = 'deffn' cat_class = string.join(idxsi) elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: command = 'deffn' cat_class = 'function of ' + string.join(idxsi[1:]) elif len(idxsi) > 3 and idxsi[:2] == ['in', 'modules']: command = 'deffn' cat_class = 'function of ' + string.join(idxsi[1:]) if not command: raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` ch.chtype = chunk_type[CSLINE] ch.data = command cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] cslinearg.append(chunk(PLAIN, wh, ' ')) cslinearg.append(funcname) cslinearg.append(chunk(PLAIN, wh, ' ')) l = len(cslinearg) cslinearg[l:l] = the_args pp.insert(i, chunk(GROUP, wh, cslinearg)) i, length = i+1, length+1 hist.command = command return length, i
if len(idxsi) == 2 and idxsi[1] == 'exception': command = 'defvr' cat_class = string.join(idxsi) elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: command = 'defcv' cat_class = 'exception' class_class = string.join(idxsi[1:]) elif len(idxsi) == 4 and idxsi[:3] == ['exception', 'in', 'module']: command = 'defcv' cat_class = 'exception' class_class = string.join(idxsi[2:]) elif idxsi == ['built-in', 'exception', 'base', 'class']:
if idxsi == ['built-in', 'exception', 'base', 'class']:
def do_excdesc(length, buf, pp, i): startpoint = i-1 ch = pp[startpoint] wh = ch.where length, newi = getnextarg(length, buf, pp, i) excname = chunk(GROUP, wh, pp[i:newi]) del pp[i:newi] length = length - (newi-i) idxsi = hist.indexsubitem # words command = '' cat_class = '' class_class = '' if len(idxsi) == 2 and idxsi[1] == 'exception': command = 'defvr' cat_class = string.join(idxsi) elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: command = 'defcv' cat_class = 'exception' class_class = string.join(idxsi[1:]) elif len(idxsi) == 4 and idxsi[:3] == ['exception', 'in', 'module']: command = 'defcv' cat_class = 'exception' class_class = string.join(idxsi[2:]) elif idxsi == ['built-in', 'exception', 'base', 'class']: command = 'defvr' cat_class = 'exception base class' else: raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` ch.chtype = chunk_type[CSLINE] ch.data = command cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] cslinearg.append(chunk(PLAIN, wh, ' ')) if class_class: cslinearg.append(chunk(GROUP, wh, [chunk(PLAIN, wh, class_class)])) cslinearg.append(chunk(PLAIN, wh, ' ')) cslinearg.append(excname) pp.insert(i, chunk(GROUP, wh, cslinearg)) i, length = i+1, length+1 hist.command = command return length, i
raise error, 'don\'t know what to do with indexsubitem ' + `idxsi`
command = 'defcv' cat_class = 'exception'
def do_excdesc(length, buf, pp, i): startpoint = i-1 ch = pp[startpoint] wh = ch.where length, newi = getnextarg(length, buf, pp, i) excname = chunk(GROUP, wh, pp[i:newi]) del pp[i:newi] length = length - (newi-i) idxsi = hist.indexsubitem # words command = '' cat_class = '' class_class = '' if len(idxsi) == 2 and idxsi[1] == 'exception': command = 'defvr' cat_class = string.join(idxsi) elif len(idxsi) == 3 and idxsi[:2] == ['in', 'module']: command = 'defcv' cat_class = 'exception' class_class = string.join(idxsi[1:]) elif len(idxsi) == 4 and idxsi[:3] == ['exception', 'in', 'module']: command = 'defcv' cat_class = 'exception' class_class = string.join(idxsi[2:]) elif idxsi == ['built-in', 'exception', 'base', 'class']: command = 'defvr' cat_class = 'exception base class' else: raise error, 'don\'t know what to do with indexsubitem ' + `idxsi` ch.chtype = chunk_type[CSLINE] ch.data = command cslinearg = [chunk(GROUP, wh, [chunk(PLAIN, wh, cat_class)])] cslinearg.append(chunk(PLAIN, wh, ' ')) if class_class: cslinearg.append(chunk(GROUP, wh, [chunk(PLAIN, wh, class_class)])) cslinearg.append(chunk(PLAIN, wh, ' ')) cslinearg.append(excname) pp.insert(i, chunk(GROUP, wh, cslinearg)) i, length = i+1, length+1 hist.command = command return length, i
'funcdescni', 'datadescni'):
'funcdescni', 'datadescni', 'methoddesc', 'memberdesc', 'methoddescni', 'memberdescni', ):
def changeit(buf, pp): global onlylatexspecial, hist, out i, length = 0, len(pp) while 1: # sanity check: length should always equal len(pp) if len(pp) != length: print i, pp[i] raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` if i >= length: break ch = pp[i] i = i + 1 if type(ch) is StringType: #normally, only chunks are present in pp, # but in some cases, some extra info # has been inserted, e.g., the \end{...} clauses raise 'FATAL', 'got string, probably too many ' + `end` if ch.chtype == chunk_type[GROUP]: # check for {\em ...} constructs data = ch.data if data and \ data[0].chtype == chunk_type[CSNAME] and \ fontchanges.has_key(s(buf, data[0].data)): k = s(buf, data[0].data) del data[0] pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) length, i = length+1, i+1 elif data: if len(data) \ and data[0].chtype == chunk_type[GROUP] \ and len(data[0].data) \ and data[0].data[0].chtype == chunk_type[CSNAME] \ and s(buf, data[0].data[0].data) == 'e': data[0] = data[0].data[0] print "invoking \\e magic group transform..." else:
stuff = pp[i].data if len(stuff) != 1: raise error, "parameter to \\setindexsubitem{} too long" if pp[i].chtype != chunk_type[GROUP]: raise error, "bad chunk type following \\setindexsubitem" \ "\nexpected GROUP, got " + str(ch.chtype) text = s(buf, stuff[0].data) if text[:1] != '(' or text[-1:] != ')': raise error, \ 'expected indexsubitem enclosed in parenteses' hist.indexsubitem = string.split(text[1:-1]) del stuff, text del pp[i-1:i+1] i = i - 1 length = length - 2
length, i = yank_indexsubitem(pp, length, i, buf, ch, 'setindexsubitem') elif s_buf_data == 'withsubitem': oldsubitem = hist.indexsubitem try: length, i = yank_indexsubitem(pp, length, i, buf, ch, 'withsubitem') stuff = pp[i].data del pp[i] length = length - 1 changeit(buf, stuff) stuff = None finally: hist.indexsubitem = oldsubitem elif s_buf_data in ('textrm', 'pytype'): stuff = pp[i].data pp[i-1:i+1] = stuff length = length - 2 + len(stuff) stuff = None i = i - 1
def changeit(buf, pp): global onlylatexspecial, hist, out i, length = 0, len(pp) while 1: # sanity check: length should always equal len(pp) if len(pp) != length: print i, pp[i] raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` if i >= length: break ch = pp[i] i = i + 1 if type(ch) is StringType: #normally, only chunks are present in pp, # but in some cases, some extra info # has been inserted, e.g., the \end{...} clauses raise 'FATAL', 'got string, probably too many ' + `end` if ch.chtype == chunk_type[GROUP]: # check for {\em ...} constructs data = ch.data if data and \ data[0].chtype == chunk_type[CSNAME] and \ fontchanges.has_key(s(buf, data[0].data)): k = s(buf, data[0].data) del data[0] pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) length, i = length+1, i+1 elif data: if len(data) \ and data[0].chtype == chunk_type[GROUP] \ and len(data[0].data) \ and data[0].data[0].chtype == chunk_type[CSNAME] \ and s(buf, data[0].data[0].data) == 'e': data[0] = data[0].data[0] print "invoking \\e magic group transform..." else:
cat_class = '('+string.join(idxsi)+')'
cat_class = '(%s)' % string.join(idxsi)
def changeit(buf, pp): global onlylatexspecial, hist, out i, length = 0, len(pp) while 1: # sanity check: length should always equal len(pp) if len(pp) != length: print i, pp[i] raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` if i >= length: break ch = pp[i] i = i + 1 if type(ch) is StringType: #normally, only chunks are present in pp, # but in some cases, some extra info # has been inserted, e.g., the \end{...} clauses raise 'FATAL', 'got string, probably too many ' + `end` if ch.chtype == chunk_type[GROUP]: # check for {\em ...} constructs data = ch.data if data and \ data[0].chtype == chunk_type[CSNAME] and \ fontchanges.has_key(s(buf, data[0].data)): k = s(buf, data[0].data) del data[0] pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) length, i = length+1, i+1 elif data: if len(data) \ and data[0].chtype == chunk_type[GROUP] \ and len(data[0].data) \ and data[0].data[0].chtype == chunk_type[CSNAME] \ and s(buf, data[0].data[0].data) == 'e': data[0] = data[0].data[0] print "invoking \\e magic group transform..." else:
ch.chtype = chunk_type[CSLINE] ch.data = 'pindex' length, newi = getnextarg(length, buf, pp, i) ingroupch = pp[i:newi] del pp[i:newi] length = length - (newi-i) ingroupch.append(chunk(PLAIN, ch.where, ' ')) ingroupch.append(chunk(CSNAME, ch.where, 'r')) ingroupch.append(chunk(GROUP, ch.where, [ chunk(PLAIN, ch.where, '(built-in)')])) pp.insert(i, chunk(GROUP, ch.where, ingroupch)) length, i = length+1, i+1 elif s_buf_data == 'refmodindex': ch.chtype = chunk_type[CSLINE] ch.data = 'pindex' length, newi = getnextarg(length, buf, pp, i) ingroupch = pp[i:newi] del pp[i:newi] length = length - (newi-i) pp.insert(i, chunk(GROUP, ch.where, ingroupch)) length, i = length+1, i+1
length, i = add_module_index( pp, length, i, buf, ch, '(built-in)', (s_buf_data[:3] == 'ref')) elif s_buf_data in ('modindex', 'refmodindex'): length, i = add_module_index( pp, length, i, buf, ch, '', (s_buf_data[:3] == 'ref'))
def changeit(buf, pp): global onlylatexspecial, hist, out i, length = 0, len(pp) while 1: # sanity check: length should always equal len(pp) if len(pp) != length: print i, pp[i] raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` if i >= length: break ch = pp[i] i = i + 1 if type(ch) is StringType: #normally, only chunks are present in pp, # but in some cases, some extra info # has been inserted, e.g., the \end{...} clauses raise 'FATAL', 'got string, probably too many ' + `end` if ch.chtype == chunk_type[GROUP]: # check for {\em ...} constructs data = ch.data if data and \ data[0].chtype == chunk_type[CSNAME] and \ fontchanges.has_key(s(buf, data[0].data)): k = s(buf, data[0].data) del data[0] pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) length, i = length+1, i+1 elif data: if len(data) \ and data[0].chtype == chunk_type[GROUP] \ and len(data[0].data) \ and data[0].data[0].chtype == chunk_type[CSNAME] \ and s(buf, data[0].data[0].data) == 'e': data[0] = data[0].data[0] print "invoking \\e magic group transform..." else:
ch.chtype = chunk_type[CSLINE] ch.data = 'pindex' length, newi = getnextarg(length, buf, pp, i) ingroupch = pp[i:newi] del pp[i:newi] length = length - (newi-i) ingroupch.append(chunk(PLAIN, ch.where, ' ')) ingroupch.append(chunk(CSNAME, ch.where, 'r')) ingroupch.append(chunk(GROUP, ch.where, [ chunk(PLAIN, ch.where, '(standard)')])) pp.insert(i, chunk(GROUP, ch.where, ingroupch)) length, i = length+1, i+1 elif s_buf_data in ('stmodindex', 'refstmodindex'): ch.chtype = chunk_type[CSLINE] ch.data = 'pindex' length, newi = getnextarg(length, buf, pp, i) ingroupch = pp[i:newi] del pp[i:newi] length = length - (newi-i) ingroupch.append(chunk(PLAIN, ch.where, ' ')) ingroupch.append(chunk(CSNAME, ch.where, 'r')) ingroupch.append(chunk(GROUP, ch.where, [ chunk(PLAIN, ch.where, '(standard)')])) pp.insert(i, chunk(GROUP, ch.where, ingroupch)) length, i = length+1, i+1
length, i = add_module_index( pp, length, i, buf, ch, '(standard)', (s_buf_data[:3] == 'ref')) elif s_buf_data in ('exmodindex', 'refexmodindex'): length, i = add_module_index( pp, length, i, buf, ch, '(extension)', (s_buf_data[:3] == 'ref'))
def changeit(buf, pp): global onlylatexspecial, hist, out i, length = 0, len(pp) while 1: # sanity check: length should always equal len(pp) if len(pp) != length: print i, pp[i] raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` if i >= length: break ch = pp[i] i = i + 1 if type(ch) is StringType: #normally, only chunks are present in pp, # but in some cases, some extra info # has been inserted, e.g., the \end{...} clauses raise 'FATAL', 'got string, probably too many ' + `end` if ch.chtype == chunk_type[GROUP]: # check for {\em ...} constructs data = ch.data if data and \ data[0].chtype == chunk_type[CSNAME] and \ fontchanges.has_key(s(buf, data[0].data)): k = s(buf, data[0].data) del data[0] pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) length, i = length+1, i+1 elif data: if len(data) \ and data[0].chtype == chunk_type[GROUP] \ and len(data[0].data) \ and data[0].data[0].chtype == chunk_type[CSNAME] \ and s(buf, data[0].data[0].data) == 'e': data[0] = data[0].data[0] print "invoking \\e magic group transform..." else:
while pp[i+1].chtype == chunk_type[COMMENT]: i = i + 1
def changeit(buf, pp): global onlylatexspecial, hist, out i, length = 0, len(pp) while 1: # sanity check: length should always equal len(pp) if len(pp) != length: print i, pp[i] raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` if i >= length: break ch = pp[i] i = i + 1 if type(ch) is StringType: #normally, only chunks are present in pp, # but in some cases, some extra info # has been inserted, e.g., the \end{...} clauses raise 'FATAL', 'got string, probably too many ' + `end` if ch.chtype == chunk_type[GROUP]: # check for {\em ...} constructs data = ch.data if data and \ data[0].chtype == chunk_type[CSNAME] and \ fontchanges.has_key(s(buf, data[0].data)): k = s(buf, data[0].data) del data[0] pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) length, i = length+1, i+1 elif data: if len(data) \ and data[0].chtype == chunk_type[GROUP] \ and len(data[0].data) \ and data[0].data[0].chtype == chunk_type[CSNAME] \ and s(buf, data[0].data[0].data) == 'e': data[0] = data[0].data[0] print "invoking \\e magic group transform..." else:
oparen = chunk(PLAIN, ch.where, " (") data.insert(0, oparen)
data.insert(0, chunk(PLAIN, ch.where, " ("))
def changeit(buf, pp): global onlylatexspecial, hist, out i, length = 0, len(pp) while 1: # sanity check: length should always equal len(pp) if len(pp) != length: print i, pp[i] raise 'FATAL', 'inconsistent length. thought ' + `length` + ', but should really be ' + `len(pp)` if i >= length: break ch = pp[i] i = i + 1 if type(ch) is StringType: #normally, only chunks are present in pp, # but in some cases, some extra info # has been inserted, e.g., the \end{...} clauses raise 'FATAL', 'got string, probably too many ' + `end` if ch.chtype == chunk_type[GROUP]: # check for {\em ...} constructs data = ch.data if data and \ data[0].chtype == chunk_type[CSNAME] and \ fontchanges.has_key(s(buf, data[0].data)): k = s(buf, data[0].data) del data[0] pp.insert(i-1, chunk(CSNAME, ch.where, fontchanges[k])) length, i = length+1, i+1 elif data: if len(data) \ and data[0].chtype == chunk_type[GROUP] \ and len(data[0].data) \ and data[0].data[0].chtype == chunk_type[CSNAME] \ and s(buf, data[0].data[0].data) == 'e': data[0] = data[0].data[0] print "invoking \\e magic group transform..." else:
print 'WARNING: found newline in csline arg'
def dumpit(buf, wm, pp): global out i, length = 0, len(pp) addspace = 0 while 1: if len(pp) != length: raise 'FATAL', 'inconsistent length' if i == length: break ch = pp[i] i = i + 1 dospace = addspace addspace = 0 if ch.chtype == chunk_type[CSNAME]: s_buf_data = s(buf, ch.data)
if hasattr(sys, "gettotalrefcount"):
if hasattr(set, "test_c_api"):
def test_weakref(self): s = self.thetype('gallahad') p = proxy(s) self.assertEqual(str(p), str(s)) s = None self.assertRaises(ReferenceError, str, p)
_tryorder = os.environ["BROWSER"].split(":")
_tryorder = os.environ["BROWSER"].split(os.pathsep)
def open_new(self, url): self.open(url)
day = int(mo.group(day)) year = int(mo.group(year)) hour = int(mo.group(hour)) min = int(mo.group(min)) sec = int(mo.group(sec)) zoneh = int(mo.group(zoneh)) zonem = int(mo.group(zonem))
day = int(mo.group('day')) year = int(mo.group('year')) hour = int(mo.group('hour')) min = int(mo.group('min')) sec = int(mo.group('sec')) zoneh = int(mo.group('zoneh')) zonem = int(mo.group('zonem'))
def Internaldate2tuple(resp): """Convert IMAP4 INTERNALDATE to UT. Returns Python time module tuple. """ mo = InternalDate.match(resp) if not mo: return None mon = Mon2num[mo.group('mon')] zonen = mo.group('zonen') day = int(mo.group(day)) year = int(mo.group(year)) hour = int(mo.group(hour)) min = int(mo.group(min)) sec = int(mo.group(sec)) zoneh = int(mo.group(zoneh)) zonem = int(mo.group(zonem)) # INTERNALDATE timezone must be subtracted to get UT zone = (zoneh*60 + zonem)*60 if zonen == '-': zone = -zone tt = (year, mon, day, hour, min, sec, -1, -1, -1) utc = time.mktime(tt) # Following is necessary because the time module has no 'mkgmtime'. # 'mktime' assumes arg in local timezone, so adds timezone/altzone. lt = time.localtime(utc) if time.daylight and lt[-1]: zone = zone + time.altzone else: zone = zone + time.timezone return time.localtime(utc - zone)
if __debug__: print "colorizing already scheduled"
if DEBUG: print "colorizing already scheduled"
def notify_range(self, index1, index2=None): self.tag_add("TODO", index1, index2) if self.after_id: if __debug__: print "colorizing already scheduled" return if self.colorizing: self.stop_colorizing = 1 if __debug__: print "stop colorizing" if self.allow_colorizing: if __debug__: print "schedule colorizing" self.after_id = self.after(1, self.recolorize)
if __debug__: print "stop colorizing"
if DEBUG: print "stop colorizing"
def notify_range(self, index1, index2=None): self.tag_add("TODO", index1, index2) if self.after_id: if __debug__: print "colorizing already scheduled" return if self.colorizing: self.stop_colorizing = 1 if __debug__: print "stop colorizing" if self.allow_colorizing: if __debug__: print "schedule colorizing" self.after_id = self.after(1, self.recolorize)
if __debug__: print "schedule colorizing"
if DEBUG: print "schedule colorizing"
def notify_range(self, index1, index2=None): self.tag_add("TODO", index1, index2) if self.after_id: if __debug__: print "colorizing already scheduled" return if self.colorizing: self.stop_colorizing = 1 if __debug__: print "stop colorizing" if self.allow_colorizing: if __debug__: print "schedule colorizing" self.after_id = self.after(1, self.recolorize)
if __debug__: print "cancel scheduled recolorizer"
if DEBUG: print "cancel scheduled recolorizer"
def close(self, close_when_done=None): if self.after_id: after_id = self.after_id self.after_id = None if __debug__: print "cancel scheduled recolorizer" self.after_cancel(after_id) self.allow_colorizing = 0 self.stop_colorizing = 1 if close_when_done: if not self.colorizing: close_when_done.destroy() else: self.close_when_done = close_when_done
if __debug__: print "cancel scheduled recolorizer"
if DEBUG: print "cancel scheduled recolorizer"
def toggle_colorize_event(self, event): if self.after_id: after_id = self.after_id self.after_id = None if __debug__: print "cancel scheduled recolorizer" self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: if __debug__: print "stop colorizing" self.stop_colorizing = 1 self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if __debug__: print "auto colorizing turned", self.allow_colorizing and "on" or "off" return "break"
if __debug__: print "stop colorizing"
if DEBUG: print "stop colorizing"
def toggle_colorize_event(self, event): if self.after_id: after_id = self.after_id self.after_id = None if __debug__: print "cancel scheduled recolorizer" self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: if __debug__: print "stop colorizing" self.stop_colorizing = 1 self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if __debug__: print "auto colorizing turned", self.allow_colorizing and "on" or "off" return "break"
if __debug__:
if DEBUG:
def toggle_colorize_event(self, event): if self.after_id: after_id = self.after_id self.after_id = None if __debug__: print "cancel scheduled recolorizer" self.after_cancel(after_id) if self.allow_colorizing and self.colorizing: if __debug__: print "stop colorizing" self.stop_colorizing = 1 self.allow_colorizing = not self.allow_colorizing if self.allow_colorizing and not self.colorizing: self.after_id = self.after(1, self.recolorize) if __debug__: print "auto colorizing turned", self.allow_colorizing and "on" or "off" return "break"
if __debug__: print "no delegate"
if DEBUG: print "no delegate"
def recolorize(self): self.after_id = None if not self.delegate: if __debug__: print "no delegate" return if not self.allow_colorizing: if __debug__: print "auto colorizing is off" return if self.colorizing: if __debug__: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if __debug__: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if __debug__: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if __debug__: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy()
if __debug__: print "auto colorizing is off"
if DEBUG: print "auto colorizing is off"
def recolorize(self): self.after_id = None if not self.delegate: if __debug__: print "no delegate" return if not self.allow_colorizing: if __debug__: print "auto colorizing is off" return if self.colorizing: if __debug__: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if __debug__: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if __debug__: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if __debug__: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy()
if __debug__: print "already colorizing"
if DEBUG: print "already colorizing"
def recolorize(self): self.after_id = None if not self.delegate: if __debug__: print "no delegate" return if not self.allow_colorizing: if __debug__: print "auto colorizing is off" return if self.colorizing: if __debug__: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if __debug__: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if __debug__: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if __debug__: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy()
if __debug__: print "colorizing..."
if DEBUG: print "colorizing..."
def recolorize(self): self.after_id = None if not self.delegate: if __debug__: print "no delegate" return if not self.allow_colorizing: if __debug__: print "auto colorizing is off" return if self.colorizing: if __debug__: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if __debug__: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if __debug__: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if __debug__: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy()
if __debug__: print "%.3f seconds" % (t1-t0)
if DEBUG: print "%.3f seconds" % (t1-t0)
def recolorize(self): self.after_id = None if not self.delegate: if __debug__: print "no delegate" return if not self.allow_colorizing: if __debug__: print "auto colorizing is off" return if self.colorizing: if __debug__: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if __debug__: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if __debug__: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if __debug__: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy()
if __debug__: print "reschedule colorizing"
if DEBUG: print "reschedule colorizing"
def recolorize(self): self.after_id = None if not self.delegate: if __debug__: print "no delegate" return if not self.allow_colorizing: if __debug__: print "auto colorizing is off" return if self.colorizing: if __debug__: print "already colorizing" return try: self.stop_colorizing = 0 self.colorizing = 1 if __debug__: print "colorizing..." t0 = time.clock() self.recolorize_main() t1 = time.clock() if __debug__: print "%.3f seconds" % (t1-t0) finally: self.colorizing = 0 if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): if __debug__: print "reschedule colorizing" self.after_id = self.after(1, self.recolorize) if self.close_when_done: top = self.close_when_done self.close_when_done = None top.destroy()
if __debug__: print "colorizing stopped"
if DEBUG: print "colorizing stopped"
def recolorize_main(self): next = "1.0" while 1: item = self.tag_nextrange("TODO", next) if not item: break head, tail = item self.tag_remove("SYNC", head, tail) item = self.tag_prevrange("SYNC", head) if item: head = item[1] else: head = "1.0"
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None):
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None, quiet=0):
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if rx: mo = rx.search(fullname) if mo: continue if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: ok = py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: # XXX py_compile catches SyntaxErrors if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 else: if ok == 0: success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): if not compile_dir(fullname, maxlevels - 1, dfile, force, rx): success = 0 return success
print 'Listing', dir, '...'
if not quiet: print 'Listing', dir, '...'
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if rx: mo = rx.search(fullname) if mo: continue if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: ok = py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: # XXX py_compile catches SyntaxErrors if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 else: if ok == 0: success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): if not compile_dir(fullname, maxlevels - 1, dfile, force, rx): success = 0 return success
print 'Compiling', fullname, '...'
if not quiet: print 'Compiling', fullname, '...'
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if rx: mo = rx.search(fullname) if mo: continue if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: ok = py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: # XXX py_compile catches SyntaxErrors if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 else: if ok == 0: success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): if not compile_dir(fullname, maxlevels - 1, dfile, force, rx): success = 0 return success
if not compile_dir(fullname, maxlevels - 1, dfile, force, rx):
if not compile_dir(fullname, maxlevels - 1, dfile, force, rx, quiet):
def compile_dir(dir, maxlevels=10, ddir=None, force=0, rx=None): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default 10) ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date """ print 'Listing', dir, '...' try: names = os.listdir(dir) except os.error: print "Can't list", dir names = [] names.sort() success = 1 for name in names: fullname = os.path.join(dir, name) if ddir: dfile = os.path.join(ddir, name) else: dfile = None if rx: mo = rx.search(fullname) if mo: continue if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': cfile = fullname + (__debug__ and 'c' or 'o') ftime = os.stat(fullname)[stat.ST_MTIME] try: ctime = os.stat(cfile)[stat.ST_MTIME] except os.error: ctime = 0 if (ctime > ftime) and not force: continue print 'Compiling', fullname, '...' try: ok = py_compile.compile(fullname, None, dfile) except KeyboardInterrupt: raise KeyboardInterrupt except: # XXX py_compile catches SyntaxErrors if type(sys.exc_type) == type(''): exc_type_name = sys.exc_type else: exc_type_name = sys.exc_type.__name__ print 'Sorry:', exc_type_name + ':', print sys.exc_value success = 0 else: if ok == 0: success = 0 elif maxlevels > 0 and \ name != os.curdir and name != os.pardir and \ os.path.isdir(fullname) and \ not os.path.islink(fullname): if not compile_dir(fullname, maxlevels - 1, dfile, force, rx): success = 0 return success
def compile_path(skip_curdir=1, maxlevels=0, force=0):
def compile_path(skip_curdir=1, maxlevels=0, force=0, quiet=0):
def compile_path(skip_curdir=1, maxlevels=0, force=0): """Byte-compile all module on sys.path. Arguments (all optional): skip_curdir: if true, skip current directory (default true) maxlevels: max recursion level (default 0) force: as for compile_dir() (default 0) """ success = 1 for dir in sys.path: if (not dir or dir == os.curdir) and skip_curdir: print 'Skipping current directory' else: success = success and compile_dir(dir, maxlevels, None, force) return success
success = success and compile_dir(dir, maxlevels, None, force)
success = success and compile_dir(dir, maxlevels, None, force, quiet=quiet)
def compile_path(skip_curdir=1, maxlevels=0, force=0): """Byte-compile all module on sys.path. Arguments (all optional): skip_curdir: if true, skip current directory (default true) maxlevels: max recursion level (default 0) force: as for compile_dir() (default 0) """ success = 1 for dir in sys.path: if (not dir or dir == os.curdir) and skip_curdir: print 'Skipping current directory' else: success = success and compile_dir(dir, maxlevels, None, force) return success
opts, args = getopt.getopt(sys.argv[1:], 'lfd:x:')
opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:')
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:x:') except getopt.error, msg: print msg print "usage: python compileall.py [-l] [-f] [-d destdir] " \ "[-s regexp] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print " if no directory arguments, -l sys.path is assumed" print "-x regexp: skip files matching the regular expression regexp" print " the regexp is search for in the full path of the file" sys.exit(2) maxlevels = 10 ddir = None force = 0 rx = None for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if o == '-x': import re rx = re.compile(a) if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: if not compile_dir(dir, maxlevels, ddir, force, rx): success = 0 else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
print "usage: python compileall.py [-l] [-f] [-d destdir] " \
print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:x:') except getopt.error, msg: print msg print "usage: python compileall.py [-l] [-f] [-d destdir] " \ "[-s regexp] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print " if no directory arguments, -l sys.path is assumed" print "-x regexp: skip files matching the regular expression regexp" print " the regexp is search for in the full path of the file" sys.exit(2) maxlevels = 10 ddir = None force = 0 rx = None for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if o == '-x': import re rx = re.compile(a) if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: if not compile_dir(dir, maxlevels, ddir, force, rx): success = 0 else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
if not compile_dir(dir, maxlevels, ddir, force, rx):
if not compile_dir(dir, maxlevels, ddir, force, rx, quiet):
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:x:') except getopt.error, msg: print msg print "usage: python compileall.py [-l] [-f] [-d destdir] " \ "[-s regexp] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print " if no directory arguments, -l sys.path is assumed" print "-x regexp: skip files matching the regular expression regexp" print " the regexp is search for in the full path of the file" sys.exit(2) maxlevels = 10 ddir = None force = 0 rx = None for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if o == '-x': import re rx = re.compile(a) if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args: for dir in args: if not compile_dir(dir, maxlevels, ddir, force, rx): success = 0 else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]" success = 0 return success
self.warn ("file %s (for module %s) not found" % module_file, module)
self.warn ("file %s (for module %s) not found" % (module_file, module))
def check_module (self, module, module_file): if not os.path.isfile (module_file): self.warn ("file %s (for module %s) not found" % module_file, module) return 0 else: return 1
verify(str(c1).find('C instance at ') >= 0)
verify(str(c1).find('C object at ') >= 0)
def __getitem__(self, i): if 0 <= i < 10: return i raise IndexError
verify(str(d1).find('D instance at ') >= 0)
verify(str(d1).find('D object at ') >= 0)
def __getitem__(self, i): if 0 <= i < 10: return i raise IndexError
if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') add_dir_to_list(self.compiler.library_dirs, sysconfig.get_config_var("LIBDIR")) add_dir_to_list(self.compiler.include_dirs, sysconfig.get_config_var("INCLUDEDIR"))
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
_StringType = type('')
_StringTypes = (str, unicode)
def rfind(s, *args): """rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return s.rfind(*args)
if type(x) == type(''): s = x else: s = `x` n = len(s) if n >= width: return s
if not isinstance(x, _StringTypes): x = str(x) n = len(x) if n >= width: return x
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if type(x) == type(''): s = x else: s = `x` n = len(s) if n >= width: return s sign = '' if s[0] in ('-', '+'): sign, s = s[0], s[1:] return sign + '0'*(width-n) + s
if s[0] in ('-', '+'): sign, s = s[0], s[1:] return sign + '0'*(width-n) + s
if x[0] in '-+': sign, x = x[0], x[1:] return sign + '0'*(width-n) + x
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if type(x) == type(''): s = x else: s = `x` n = len(s) if n >= width: return s sign = '' if s[0] in ('-', '+'): sign, s = s[0], s[1:] return sign + '0'*(width-n) + s
accept = accept + string.split(line[7:])
accept = accept + string.split(line[7:], ',')
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 if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length accept = [] for line in self.headers.getallmatchingheaders('accept'): if line[:1] in string.whitespace: accept.append(string.strip(line)) else: accept = accept + string.split(line[7:]) 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)
print socket.error
try: raise socket.error except socket.error: print "socket.error"
def missing_ok(str): try: getattr(socket, str) except AttributeError: pass
width=80,
width=79,
def __init__ (self, indent_increment=2, max_help_position=24, width=80, short_first=1): HelpFormatter.__init__( self, indent_increment, max_help_position, width, short_first)
width=80,
width=79,
def __init__ (self, indent_increment=0, max_help_position=24, width=80, short_first=0): HelpFormatter.__init__ ( self, indent_increment, max_help_position, width, short_first)
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: self.socket.connect(address) except socket.error: self.socket.close() self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.socket.connect(address)
self._connect_unixsocket(address)
def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER): """ Initialize a handler.
self.socket.send(msg)
try: self.socket.send(msg) except socket.error: self._connect_unixsocket(self.address) self.socket.send(msg)
def emit(self, record): """ Emit a record.
if sys.platform in ('win', 'mac'):
if sys.platform[:3] in ('win', 'mac'):
def test(): import sys if sys.platform in ('win', 'mac'): if verbose: print "Can't test select easily" return cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' p = os.popen(cmd, 'r') for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: if verbose: print 'timeout =', tout rfd, wfd, xfd = select.select([p], [], [], tout)
print "Can't test select easily"
print "Can't test select easily on", sys.platform
def test(): import sys if sys.platform in ('win', 'mac'): if verbose: print "Can't test select easily" return cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' p = os.popen(cmd, 'r') for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: if verbose: print 'timeout =', tout rfd, wfd, xfd = select.select([p], [], [], tout)
current_lang = locale.getlocale(locale.LC_TIME)[0] if current_lang: self.__lang = current_lang else: current_lang = locale.getdefaultlocale()[0] if current_lang: self.__lang = current_lang else: self.__lang = ''
self.__lang = _getlang()
def __calc_lang(self): # Set self.__lang by using locale.getlocale() or # locale.getdefaultlocale(). If both turn up empty, set the attribute # to ''. This is to stop calls to this method and to make sure # strptime() can produce an re object correctly. current_lang = locale.getlocale(locale.LC_TIME)[0] if current_lang: self.__lang = current_lang else: current_lang = locale.getdefaultlocale()[0] if current_lang: self.__lang = current_lang else: self.__lang = ''
for whitespace in whitespace_string: format = format.replace(whitespace, r'\s*')
whitespace_replacement = re_compile('\s+') format = whitespace_replacement.sub('\s*', format)
def pattern(self, format): """Return re pattern for the format string.""" processed_format = '' for whitespace in whitespace_string: format = format.replace(whitespace, r'\s*') while format.find('%') != -1: directive_index = format.index('%')+1 processed_format = "%s%s%s" % (processed_format, format[:directive_index-1], self[format[directive_index]]) format = format[directive_index+1:] return "%s%s" % (processed_format, format)
format = "(?
def compile(self, format): """Return a compiled re object for the format string.""" format = "(?#%s)%s" % (self.locale_time.lang,format) return re_compile(self.pattern(format), IGNORECASE)
locale_time = LocaleTime() compiled_re = TimeRE(locale_time).compile(format) found = compiled_re.match(data_string)
global _locale_cache global _regex_cache locale_time = _locale_cache.locale_time if locale_time.lang != _getlang(): _locale_cache = TimeRE() _regex_cache.clear() format_regex = _regex_cache.get(format) if not format_regex: if len(_regex_cache) > 5: _regex_cache.clear() format_regex = _locale_cache.compile(format) _regex_cache[format] = format_regex found = format_regex.match(data_string)
def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input data and the format string.""" locale_time = LocaleTime() compiled_re = TimeRE(locale_time).compile(format) found = compiled_re.match(data_string) if not found: raise ValueError("time data did not match format") year = 1900 month = day = 1 hour = minute = second = 0 tz = -1 # Defaulted to -1 so as to signal using functions to calc values weekday = julian = -1 found_dict = found.groupdict() for group_key in found_dict.iterkeys(): if group_key == 'y': year = int(found_dict['y']) # Open Group specification for strptime() states that a %y #value in the range of [00, 68] is in the century 2000, while #[69,99] is in the century 1900 if year <= 68: year += 2000 else: year += 1900 elif group_key == 'Y': year = int(found_dict['Y']) elif group_key == 'm': month = int(found_dict['m']) elif group_key == 'B': month = _insensitiveindex(locale_time.f_month, found_dict['B']) elif group_key == 'b': month = _insensitiveindex(locale_time.a_month, found_dict['b']) elif group_key == 'd': day = int(found_dict['d']) elif group_key is 'H': hour = int(found_dict['H']) elif group_key == 'I': hour = int(found_dict['I']) ampm = found_dict.get('p', '').lower() # If there was no AM/PM indicator, we'll treat this like AM if ampm in ('', locale_time.am_pm[0].lower()): # We're in AM so the hour is correct unless we're # looking at 12 midnight. # 12 midnight == 12 AM == hour 0 if hour == 12: hour = 0 elif ampm == locale_time.am_pm[1].lower(): # We're in PM so we need to add 12 to the hour unless # we're looking at 12 noon. # 12 noon == 12 PM == hour 12 if hour != 12: hour += 12 elif group_key == 'M': minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) elif group_key == 'A': weekday = _insensitiveindex(locale_time.f_weekday, found_dict['A']) elif group_key == 'a': weekday = _insensitiveindex(locale_time.a_weekday, found_dict['a']) elif group_key == 'w': weekday = int(found_dict['w']) if weekday == 0: weekday = 6 else: weekday -= 1 elif group_key == 'j': julian = int(found_dict['j']) elif group_key == 'Z': found_zone = found_dict['Z'].lower() if locale_time.timezone[0] == locale_time.timezone[1]: pass #Deals with bad locale setup where timezone info is # the same; first found on FreeBSD 4.4. elif locale_time.timezone[0].lower() == found_zone: tz = 0 elif locale_time.timezone[1].lower() == found_zone: tz = 1 elif locale_time.timezone[2].lower() == found_zone: tz = -1 #XXX <bc>: If calculating fxns are never exposed to the general #populous then just inline calculations. Also might be able to use #``datetime`` and the methods it provides. if julian == -1: julian = julianday(year, month, day) else: # Assuming that if they bothered to include Julian day it will #be accurate year, month, day = gregorian(julian, year) if weekday == -1: weekday = dayofweek(year, month, day) return time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz))
_wordchars_re = re.compile(r'[^\\\'\"\ ]*')
_wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
def grok_environment_error (exc, prefix="error: "): """Generate a useful error message from an EnvironmentError (IOError or OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and does what it can to deal with exception objects that don't have a filename (which happens when the error is due to a two-file operation, such as 'rename()' or 'link()'. Returns the error message as a string prefixed with 'prefix'. """ # check for Python 1.5.2-style {IO,OS}Error exception objects if hasattr (exc, 'filename') and hasattr (exc, 'strerror'): if exc.filename: error = prefix + "%s: %s" % (exc.filename, exc.strerror) else: # two-argument functions in posix module don't # include the filename in the exception object! error = prefix + "%s" % exc.strerror else: error = prefix + str(exc[-1]) return error
if s[end] == ' ':
if s[end] in string.whitespace:
def split_quoted (s): """Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The backslash is stripped from any two-character escape sequence, leaving only the escaped character. The quote characters are stripped from any quoted string. Returns a list of words. """ # This is a nice algorithm for splitting up a single string, since it # doesn't require character-by-character examination. It was a little # bit of a brain-bender to get it working right, though... s = string.strip(s) words = [] pos = 0 while s: m = _wordchars_re.match(s, pos) end = m.end() if end == len(s): words.append(s[:end]) break if s[end] == ' ': # unescaped, unquoted space: now words.append(s[:end]) # we definitely have a word delimiter s = string.lstrip(s[end:]) pos = 0 elif s[end] == '\\': # preserve whatever is being escaped; # will become part of the current word s = s[:end] + s[end+1:] pos = end+1 else: if s[end] == "'": # slurp singly-quoted string m = _squote_re.match(s, end) elif s[end] == '"': # slurp doubly-quoted string m = _dquote_re.match(s, end) else: raise RuntimeError, \ "this can't happen (bad char '%c')" % s[end] if m is None: raise ValueError, \ "bad string (mismatched %s quotes?)" % s[end] (beg, end) = m.span() s = s[:beg] + s[beg+1:end-1] + s[end:] pos = m.end() - 2 if pos >= len(s): words.append(s) break return words
self.file.write('\n' + '\n'*blankline)
self.file.write('\n'*blankline)
def send_paragraph(self, blankline): self.file.write('\n' + '\n'*blankline) self.col = 0 self.atbreak = 0
A2 = "%s:%s" % (req.has_data() and 'POST' or 'GET',
A2 = "%s:%s" % (req.get_method(),
def get_authorization(self, req, chal): try: realm = chal['realm'] nonce = chal['nonce'] qop = chal.get('qop') algorithm = chal.get('algorithm', 'MD5') # mod_digest doesn't send an opaque, even though it isn't # supposed to be optional opaque = chal.get('opaque', None) except KeyError: return None
os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IXGRP)
os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IWGRP) os.chown(p, -1, gid)
def buildPython(): print "Building a universal python" buildDir = os.path.join(WORKDIR, '_bld', 'python') rootDir = os.path.join(WORKDIR, '_root') if os.path.exists(buildDir): shutil.rmtree(buildDir) if os.path.exists(rootDir): shutil.rmtree(rootDir) os.mkdir(buildDir) os.mkdir(rootDir) os.mkdir(os.path.join(rootDir, 'empty-dir')) curdir = os.getcwd() os.chdir(buildDir) # Not sure if this is still needed, the original build script # claims that parts of the install assume python.exe exists. os.symlink('python', os.path.join(buildDir, 'python.exe')) # Extract the version from the configure file, needed to calculate # several paths. version = getVersion() print "Running configure..." runCommand("%s -C --enable-framework --enable-universalsdk=%s LDFLAGS='-g -L%s/libraries/usr/local/lib' OPT='-g -O3 -I%s/libraries/usr/local/include' 2>&1"%( shellQuote(os.path.join(SRCDIR, 'configure')), shellQuote(SDKPATH), shellQuote(WORKDIR)[1:-1], shellQuote(WORKDIR)[1:-1])) print "Running make" runCommand("make") print "Runing make frameworkinstall" runCommand("make frameworkinstall DESTDIR=%s"%( shellQuote(rootDir))) print "Runing make frameworkinstallextras" runCommand("make frameworkinstallextras DESTDIR=%s"%( shellQuote(rootDir))) print "Copy required shared libraries" if os.path.exists(os.path.join(WORKDIR, 'libraries', 'Library')): runCommand("mv %s/* %s"%( shellQuote(os.path.join( WORKDIR, 'libraries', 'Library', 'Frameworks', 'Python.framework', 'Versions', getVersion(), 'lib')), shellQuote(os.path.join(WORKDIR, '_root', 'Library', 'Frameworks', 'Python.framework', 'Versions', getVersion(), 'lib')))) print "Fix file modes" frmDir = os.path.join(rootDir, 'Library', 'Frameworks', 'Python.framework') for dirpath, dirnames, filenames in os.walk(frmDir): for dn in dirnames: os.chmod(os.path.join(dirpath, dn), 0775) for fn in filenames: if os.path.islink(fn): continue # "chmod g+w $fn" p = os.path.join(dirpath, fn) st = os.stat(p) os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IXGRP) # We added some directories to the search path during the configure # phase. Remove those because those directories won't be there on # the end-users system. path =os.path.join(rootDir, 'Library', 'Frameworks', 'Python.framework', 'Versions', version, 'lib', 'python%s'%(version,), 'config', 'Makefile') fp = open(path, 'r') data = fp.read() fp.close() data = data.replace('-L%s/libraries/usr/local/lib'%(WORKDIR,), '') data = data.replace('-I%s/libraries/usr/local/include'%(WORKDIR,), '') fp = open(path, 'w') fp.write(data) fp.close() # Add symlinks in /usr/local/bin, using relative links usr_local_bin = os.path.join(rootDir, 'usr', 'local', 'bin') to_framework = os.path.join('..', '..', '..', 'Library', 'Frameworks', 'Python.framework', 'Versions', version, 'bin') if os.path.exists(usr_local_bin): shutil.rmtree(usr_local_bin) os.makedirs(usr_local_bin) for fn in os.listdir( os.path.join(frmDir, 'Versions', version, 'bin')): os.symlink(os.path.join(to_framework, fn), os.path.join(usr_local_bin, fn)) os.chdir(curdir)
decoded[-1] = (decoded[-1][0] + dec, None)
decoded[-1] = (decoded[-1][0] + SPACE + unenc, None)
def decode_header(header): """Decode a message header value without converting charset. Returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. An email.Errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception). """ # If no encoding, just return the header header = str(header) if not ecre.search(header): return [(header, None)] decoded = [] dec = '' for line in header.splitlines(): # This line might not have an encoding in it if not ecre.search(line): decoded.append((line, None)) continue parts = ecre.split(line) while parts: unenc = parts.pop(0).strip() if unenc: # Should we continue a long line? if decoded and decoded[-1][1] is None: decoded[-1] = (decoded[-1][0] + dec, None) else: decoded.append((unenc, None)) if parts: charset, encoding = [s.lower() for s in parts[0:2]] encoded = parts[2] dec = None if encoding == 'q': dec = email.quopriMIME.header_decode(encoded) elif encoding == 'b': try: dec = email.base64MIME.decode(encoded) except binascii.Error: # Turn this into a higher level exception. BAW: Right # now we throw the lower level exception away but # when/if we get exception chaining, we'll preserve it. raise HeaderParseError if dec is None: dec = encoded if decoded and decoded[-1][1] == charset: decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1]) else: decoded.append((dec, charset)) del parts[0:3] return decoded
else: raise TestFailed, '1 and 1 is false instead of false'
else: raise TestFailed, '1 and 1 is false instead of true'
def f(): pass
if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args)
try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) except AttributeError: pass
def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) return self.docother(*args)
Returns a list describing the signiture of the method. In the
Returns a list describing the signature of the method. In the
def system_methodSignature(self, method_name): """system.methodSignature('add') => [double, int, int]
n = 100
n = 200
def test_tee(self): n = 100 def irange(n): for i in xrange(n): yield i
self.assertEqual(a.next(), 0) self.assertEqual(a.next(), 1)
for i in xrange(100): self.assertEqual(a.next(), i)
def irange(n): for i in xrange(n): yield i