rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.assertEqual(list(a), range(2, n))
self.assertEqual(list(a), range(100, n))
def irange(n): for i in xrange(n): yield i
try: class A(tee): pass except TypeError: pass else: self.fail("tee constructor should not be subclassable") a, b = tee(xrange(10)) self.assertRaises(TypeError, type(a)) self.assert_(a is iter(a))
self.assertRaises(TypeError, tee, [1,2], 3, 'x') a, b = tee('abc') c = type(a)('def') self.assertEqual(list(c), list('def')) a, b, c = tee(xrange(2000), 3) for i in xrange(100): self.assertEqual(a.next(), i) self.assertEqual(list(b), range(2000)) self.assertEqual([c.next(), c.next()], range(2)) self.assertEqual(lis...
def irange(n): for i in xrange(n): yield i
def test_tee(self): a = [] p, q = t = tee([a]*2) a += [a, p, q, t] p.next() del a, p, q, t
def test_starmap(self): a = [] self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
... return izip(a, islice(b, 1, None))
... try: ... b.next() ... except StopIteration: ... pass ... return izip(a, b)
>>> def pairwise(iterable):
start += stop
start += step
def frange(start, stop, step): while start <= stop: yield start start += stop
self.status = status = int(status)
try: self.status = status = int(status) if status < 100 or status > 999: raise BadStatusLine(line) except ValueError: raise BadStatusLine(line)
def begin(self): if self.msg is not None: # we've already started reading the response return
self.includepath = [':', INCLUDEDIR]
self.includepath = [os.curdir, INCLUDEDIR]
def initpaths(self): self.includepath = [':', INCLUDEDIR]
if MacOS:
if MacOS and CREATOR:
def initosspecifics(self): if MacOS: self.filetype = 'TEXT' self.filecreator = CREATOR else: self.filetype = self.filecreator = None
save_warnings_filters = warnings.filters[:] globals = func.func_globals if '__warningregistry__' in globals: del globals['__warningregistry__'] warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) warnings.filterwarnings("error", r""".*format requires.*""", DeprecationWarning)
def deprecated_err(func, *args): # The `warnings` module doesn't have an advertised way to restore # its filter list. Cheat. save_warnings_filters = warnings.filters[:] # Grrr, we need this function to warn every time. Without removing # the warningregistry, running test_tarfile then test_struct would fail # on 64-bi...
try: func(*args) except (struct.error, TypeError): pass except DeprecationWarning: if not PY_STRUCT_OVERFLOW_MASKING: raise TestFailed, "%s%s expected to raise struct.error" % ( func.__name__, args) else: raise TestFailed, "%s%s did not raise error" % (
func(*args) except (struct.error, TypeError): pass except DeprecationWarning: if not PY_STRUCT_OVERFLOW_MASKING: raise TestFailed, "%s%s expected to raise struct.error" % (
def deprecated_err(func, *args): # The `warnings` module doesn't have an advertised way to restore # its filter list. Cheat. save_warnings_filters = warnings.filters[:] # Grrr, we need this function to warn every time. Without removing # the warningregistry, running test_tarfile then test_struct would fail # on 64-bi...
finally: warnings.filters[:] = save_warnings_filters[:]
else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args) deprecated_err = with_warning_restore(deprecated_err)
def deprecated_err(func, *args): # The `warnings` module doesn't have an advertised way to restore # its filter list. Cheat. save_warnings_filters = warnings.filters[:] # Grrr, we need this function to warn every time. Without removing # the warningregistry, running test_tarfile then test_struct would fail # on 64-bi...
mime_header = regex.compile('\\([ \t(]\\)\\([-a-zA-Z0-9_+]*[\240-\377][-a-zA-Z0-9_+\240-\377]*\\)\\([ \t)]\\|$\\)')
mime_header = regex.compile('\\([ \t(]\\|^\\)\\([-a-zA-Z0-9_+]*[\240-\377][-a-zA-Z0-9_+\240-\377]*\\)\\([ \t)]\\|$\\)')
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('=%...
QSIZE = 16 TIME = 5
format = SV.RGB8_FRAMES qsize = 2
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:')
rate = 2 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:')
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
QSIZE = string.atoi(arg)
qsize = string.atoi(arg)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
[nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt == '-t': TIME = string.atoi(arg)
rate = string.atoi(arg) if rate < 2: sys.stderr.write('-r rate must be >= 2\n') sys.exit(2)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
v.BindGLWindow(win, SV.IN_REPLACE)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
v.SetCaptureFormat(SV.RGB_FRAMES) v.SetCaptureMode(SV.BLOCKING_CAPTURE) v.SetQueueSize(QSIZE) v.InitCapture() if v.GetQueueSize() != QSIZE: QSIZE = v.GetQueueSize() print 'Warning: QSIZE reduced to', QSIZE
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
recorded = 0
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
if recorded: gl.ringbell() continue gl.prefsize(x, y) gl.winconstraints() record(v, filename, audiofilename) recorded = 1 print 'Wait until "Done writing" is printed!'
info = format, x, y, qsize, rate record(v, info, filename, audiofilename)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
if not recorded: x, y = gl.getsize() print x, 'x', y v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE)
x, y = gl.getsize() print x, 'x', y v.SetSize(x, y) v.BindGLWindow(win, SV.IN_REPLACE)
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
if not recorded: posix._exit(0) v.EndCapture()
def main(): QSIZE = 16 TIME = 5 audio = 0 num, den = 1, 1 opts, args = getopt.getopt(sys.argv[1:], 'aq:r:t:') for opt, arg in opts: if opt == '-a': audio = 1 elif opt == '-q': QSIZE = string.atoi(arg) elif opt == '-r': [nstr, dstr] = string.splitfields(arg, '/') num, den = string.atoi(nstr), string.atoi(dstr) elif opt...
def record(v, filename, audiofilename):
def record(v, info, filename, audiofilename):
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' ...
x, y = gl.getsize()
format, x, y, qsize, rate = info fps = 59.64 tpf = 1000.0 / fps
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' ...
buffer = [] thread.start_new_thread(saveframes, (vout, buffer))
MAXSIZE = 20 import Queue queue = Queue.Queue().init(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() thread.start_new_thread(saveframes, (vout, queue, done))
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' ...
initaudio(audiofilename, buffer)
audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone)
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' ...
v.StartCapture()
lastid = 0
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' ...
if v.GetCaptured() > 2: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y) cd.UnlockCaptureData() buffer.append(data, t) else: time.millisleep(10) v.StopCapture() while v.GetCaptured() > 0: t = time.millitimer() - t0 cd, st = v.GetCaptureData() data = cd.interleave(x, y)
try: cd, id = v.GetCaptureData() except RuntimeError: time.millisleep(10) continue id = id + 2*rate lastid = id data = cd.InterleaveFields(1)
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' ...
buffer.append(data, t) buffer.append(None)
queue.put(data, int(id*tpf)) t1 = time.millitimer() gl.wintitle('(busy) ' + filename) print lastid, 'fields in', t1-t0, 'msec', print '--', 0.1 * int(lastid * 10000.0 / (t1-t0)), 'fields/sec' if audiofilename: audiostop.append(None) audiodone.acquire_lock() v.EndContinuousCapture() queue.put(None) done.acquire_lock()
def record(v, filename, audiofilename): import thread x, y = gl.getsize() vout = VFile.VoutFile().init(filename) vout.format = 'rgb8' vout.width = x vout.height = y vout.writeheader() buffer = [] thread.start_new_thread(saveframes, (vout, buffer)) if audiofilename: initaudio(audiofilename, buffer) gl.wintitle('(rec) ' ...
def saveframes(vout, buffer):
def saveframes(vout, queue, done):
def saveframes(vout, buffer): while 1: if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n') vout.close()
if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n')
x = queue.get() if not x: break data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing video\n')
def saveframes(vout, buffer): while 1: if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n') vout.close()
AQSIZE = 8000 def initaudio(filename, buffer):
AQSIZE = 8000 def initaudio(filename, stop, done):
def saveframes(vout, buffer): while 1: if not buffer: time.millisleep(10) else: x = buffer[0] if not x: break del buffer[0] data, t = x vout.writeframe(t, data, None) del data sys.stderr.write('Done writing\n') vout.close()
thread.start_new_thread(audiorecord, (afile, aport, buffer))
thread.start_new_thread(audiorecord, (afile, aport, stop, done))
def initaudio(filename, buffer): import thread, aiff afile = aiff.Aiff().init(filename, 'w') afile.nchannels = AL.MONO afile.sampwidth = AL.SAMPLE_8 params = [AL.INPUT_RATE, 0] al.getparams(AL.DEFAULT_DEVICE, params) print 'audio sampling rate =', params[1] afile.samprate = params[1] c = al.newconfig() c.setchannels(AL...
def audiorecord(afile, aport, buffer): while buffer[-1:] <> [None]:
def audiorecord(afile, aport, stop, done): while not stop:
def audiorecord(afile, aport, buffer): while buffer[-1:] <> [None]: data = aport.readsamps(AQSIZE/2)
self.flags = []
self.flags = 0
def __init__(self):
def setflag(self, flag): if flag in self.flags: self.flags.append(flag)
def setflag(self, flag):
self.flags = []
def __init__(self, pattern, data=None):
lo = lo + i * av[0] hi = hi + j * av[1]
lo = lo + long(i) * av[0] hi = hi + long(j) * av[1]
def getwidth(self):
def set(self, flag): if not flag in self.flags: self.flags.append(flag) def reset(self, flag): if flag in self.flags: self.flags.remove(flag)
def set(self, flag):
self.string = list(string)
self.index = 0 self.string = string
def __init__(self, string):
if not self.string:
if self.index >= len(self.string):
def __next(self):
char = self.string[0]
char = self.string[self.index]
def __next(self):
c = self.string[1]
c = self.string[self.index + 1]
def __next(self):
try: if c == "x": for i in xrange(2, sys.maxint): c = self.string[i] if str(c) not in HEXDIGITS: break char = char + c elif str(c) in DIGITS: for i in xrange(2, sys.maxint): c = self.string[i] if str(c) not in DIGITS: break char = char + c except IndexError: pass del self.string[0:len(char)]
self.index = self.index + len(char)
def __next(self):
def _fixescape(escape, character_class=0): if character_class: code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code = ESCAPES.get(escape)
def _group(escape, state): try: group = int(escape[1:]) if group and group < state.groups: return group except ValueError: pass return None def _class_escape(source, escape): code = ESCAPES.get(escape)
def _fixescape(escape, character_class=0): # convert escape to (type, value) if character_class: # inside a character class, we'll look in the character # escapes dictionary first code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code ...
if not character_class: try: group = int(escape[1:]) return GROUP, group except ValueError: pass
code = CATEGORIES.get(escape) if code: return code
def _fixescape(escape, character_class=0): # convert escape to (type, value) if character_class: # inside a character class, we'll look in the character # escapes dictionary first code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code ...
return LITERAL, chr(int(escape[-2:], 16) & 0xff) elif str(escape[1:2]) in DIGITS: return LITERAL, chr(int(escape[1:], 8) & 0xff) elif len(escape) == 2:
return LITERAL, chr(int(escape[-4:], 16) & 0xff) elif str(escape[1:2]) in OCTDIGITS: while source.next in OCTDIGITS: escape = escape + source.get() escape = escape[1:] return LITERAL, chr(int(escape[-6:], 8) & 0xff) if len(escape) == 2:
def _fixescape(escape, character_class=0): # convert escape to (type, value) if character_class: # inside a character class, we'll look in the character # escapes dictionary first code = ESCAPES.get(escape) if code: return code code = CATEGORIES.get(escape) else: code = CATEGORIES.get(escape) if code: return code code ...
def _branch(subpattern, items):
def _escape(source, escape, state): code = CATEGORIES.get(escape) if code: return code code = ESCAPES.get(escape) if code: return code try: if escape[1:2] == "x": while source.next in HEXDIGITS: escape = escape + source.get() escape = escape[2:] return LITERAL, chr(int(escape[-4:], 16) & 0xff) elif str(escape[1:2]) i...
def _branch(subpattern, items): # form a branch operator from a set of items (FIXME: move this # optimization to the compiler module!) # check if all items share a common prefix while 1: prefix = None for item in items: if not item: break if prefix is None: prefix = item[0] elif item[0] != prefix: break else: # all s...
return
return subpattern
def _branch(subpattern, items): # form a branch operator from a set of items (FIXME: move this # optimization to the compiler module!) # check if all items share a common prefix while 1: prefix = None for item in items: if not item: break if prefix is None: prefix = item[0] elif item[0] != prefix: break else: # all s...
def _parse(source, pattern, flags=()):
return subpattern def _parse(source, state, flags=0):
def _branch(subpattern, items): # form a branch operator from a set of items (FIXME: move this # optimization to the compiler module!) # check if all items share a common prefix while 1: prefix = None for item in items: if not item: break if prefix is None: prefix = item[0] elif item[0] != prefix: break else: # all s...
subpattern = SubPattern(pattern) this = None
subpattern = SubPattern(state)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
code1 = _fixescape(this, 1)
code1 = _class_escape(source, this)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
code2 = _fixescape(this, 1)
code2 = _class_escape(source, this)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
min, max = 0, sys.maxint
min, max = 0, MAXREPEAT
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
min, max = 1, sys.maxint
min, max = 1, MAXREPEAT
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
index = len(subpattern)-1 while subpattern[index][0] is MARK: index = index - 1 item = subpattern[index:index+1]
item = subpattern[-1:]
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
subpattern[index] = (MIN_REPEAT, (min, max, item))
subpattern[-1] = (MIN_REPEAT, (min, max, item))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
subpattern[index] = (MAX_REPEAT, (min, max, item))
subpattern[-1] = (MAX_REPEAT, (min, max, item))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
if char is None or char == ">":
if char is None: raise SyntaxError, "unterminated name" if char == ">":
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
elif source.match_set("iI"): pattern.setflag("i") elif source.match_set("lL"): pattern.setflag("l") elif source.match_set("mM"): pattern.setflag("m") elif source.match_set("sS"): pattern.setflag("s") elif source.match_set("xX"): pattern.setflag("x")
elif source.match(" while 1: char = source.get() if char is None or char == ")": break else: while FLAGS.has_key(source.next): state.flags = state.flags | FLAGS[source.get()]
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
group = pattern.getgroup(name) if group: subpattern.append((MARK, (group-1)*2))
group = state.getgroup(name)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
p = _parse(source, pattern, flags)
p = _parse(source, state, flags)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
_branch(subpattern, b) else: subpattern.append((SUBPATTERN, (group, p)))
p = _branch(state, b) subpattern.append((SUBPATTERN, (group, p)))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
if group: subpattern.append((MARK, (group-1)*2+1))
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
code =_fixescape(this)
code = _escape(source, this, state)
def _parse(source, pattern, flags=()): # parse regular expression pattern into an operator list. subpattern = SubPattern(pattern) this = None while 1: if str(source.next) in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if this and this[0] not in SPECIAL_CHARS: ...
def parse(source, flags=()): s = Tokenizer(source) g = Pattern()
def parse(pattern, flags=0): source = Tokenizer(pattern) state = State()
def parse(source, flags=()): s = Tokenizer(source) g = Pattern() b = [] while 1: p = _parse(s, g, flags) tail = s.get() if tail == "|": b.append(p) elif tail == ")": raise SyntaxError, "unbalanced parenthesis" elif tail is None: if b: b.append(p) p = SubPattern(g) _branch(p, b) break else: raise SyntaxError, "bogus cha...
p = _parse(s, g, flags) tail = s.get()
p = _parse(source, state, flags) tail = source.get()
def parse(source, flags=()): s = Tokenizer(source) g = Pattern() b = [] while 1: p = _parse(s, g, flags) tail = s.get() if tail == "|": b.append(p) elif tail == ")": raise SyntaxError, "unbalanced parenthesis" elif tail is None: if b: b.append(p) p = SubPattern(g) _branch(p, b) break else: raise SyntaxError, "bogus cha...
p = SubPattern(g) _branch(p, b)
p = _branch(state, b)
def parse(source, flags=()): s = Tokenizer(source) g = Pattern() b = [] while 1: p = _parse(s, g, flags) tail = s.get() if tail == "|": b.append(p) elif tail == ")": raise SyntaxError, "unbalanced parenthesis" elif tail is None: if b: b.append(p) p = SubPattern(g) _branch(p, b) break else: raise SyntaxError, "bogus cha...
for dir in sys.path:
path = sys.path try: path = [os.path.dirname(__file__)] + path except NameError: pass for dir in path:
def get_qualified_path(name): """ return a more qualified path to name""" import sys import os for dir in sys.path: fullname = os.path.join(dir, name) if os.path.exists(fullname): return fullname return name
self._lookup()
assert self._toc is not None self._file.seek(0, 2) cur_len = self._file.tell() if cur_len != self._file_length: raise ExternalClashError('Size of mailbox file changed ' '(expected %i, found %i)' % (self._file_length, cur_len))
def flush(self): """Write any pending changes to disk.""" if not self._pending: return self._lookup() new_file = _create_temporary(self._path) try: new_toc = {} self._pre_mailbox_hook(new_file) for key in sorted(self._toc.keys()): start, stop = self._toc[key] self._file.seek(start) self._pre_message_hook(new_file) new_...
self._file.seek(0, 2) self._file_length = self._file.tell()
def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 label_lists = [] while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == '\037\014' + os.linesep: if len(stops) < len(starts): stops.append(...
exec("""def __%(method)s__(self, *args):
exec """def __%(method)s__(self, *args):
exec("""def __%(method)s__(self, *args): print "__%(method)s__:", args
"""%locals(), AllTests.__dict__);
"""%locals() in AllTests.__dict__
exec("""def __%(method)s__(self, *args): print "__%(method)s__:", args
f.seek(0)
def test_truncate(self): eq = self.assertEqual f = self.MODULE.StringIO() f.write(self._lines) f.seek(10) f.truncate() eq(f.getvalue(), 'abcdefghij') f.seek(0) f.truncate(5) eq(f.getvalue(), 'abcde') f.close() self.assertRaises(ValueError, f.write, 'frobnitz')
def testMultiply(self);
def testMultiply(self):
def testMultiply(self); self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40)
contain tuples of (testcase, exceptioninfo), where exceptioninfo is a tuple of values as returned by sys.exc_info().
contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred
def testMultiply(self); self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40)
"Called when an error has occurred" self.errors.append((test, err))
self.errors.append((test, self._exc_info_to_string(err)))
def addError(self, test, err): "Called when an error has occurred" self.errors.append((test, err))
"Called when a failure has occurred" self.failures.append((test, err))
self.failures.append((test, self._exc_info_to_string(err)))
def addFailure(self, test, err): "Called when a failure has occurred" self.failures.append((test, err))
for line in apply(traceback.format_exception, err): for l in string.split(line,"\n")[:-1]: self.stream.writeln("%s" % l)
self.stream.writeln("%s" % err)
def printErrorList(self, flavour, errors): for test, err in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) self.stream.writeln(self.separator2) for line in apply(traceback.format_exception, err): for l in string.split(line,"\n")[:-1]: self.stream.writeln...
spec_file.append('Source0: %{name}-%{version}.tar.bz2')
spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2')
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.repl...
spec_file.append('Source0: %{name}-%{version}.tar.gz')
spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.repl...
('prep', 'prep_script', "%setup"),
('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.repl...
origin_req_host = cookielib.request_host(self)
origin_req_host = request_host(self)
def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {}...
if inspect.isclass(check):
if 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 any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() de...
if inspect.isclass(h):
if isclass(h):
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 any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() de...
thingie = pickle.load(open(self.infile, 'r')) if isinstance(thingie, dict): self.update(self.__class__(thingie)) elif isinstance(thingie, tuple) and len(thingie) == 2: counts, calledfuncs = thingie self.update(self.__class__(counts, calledfuncs)) except (IOError, EOFError), err:
counts, calledfuncs = pickle.load(open(self.infile, 'r')) self.update(self.__class__(counts, calledfuncs)) except (IOError, EOFError, ValueError), err:
def __init__(self, counts=None, calledfuncs=None, infile=None, outfile=None): self.counts = counts if self.counts is None: self.counts = {} self.counter = self.counts.copy() # map (filename, lineno) to count self.calledfuncs = calledfuncs if self.calledfuncs is None: self.calledfuncs = {} self.calledfuncs = self.called...
bool,
def update(self): self.w.browser.update()
items = map(None, range(len(seq)), seq) items = map(lambda (k, v), type = type, simp = SIMPLE_TYPES, indent = indent: (k, v, not type(v) in simp, indent), items) return items
return [(i, v, not isinstance(v, SIMPLE_TYPES), indent) for i, v in enumerate(seq)]
def unpack_sequence(seq, indent = 0): items = map(None, range(len(seq)), seq) items = map(lambda (k, v), type = type, simp = SIMPLE_TYPES, indent = indent: (k, v, not type(v) in simp, indent), items) return items
def buildappbundle(executable, output=None, copyfunc=None, creator=None, plist=None, nib=None, resources=None): if not output: output = os.path.split(executable)[1] + '.app' if not copyfunc: copyfunc = shutil.copy2 if not creator: creator='????' if not resources: resources = [] if nib: resources = resources + [nib] ...
def buildappbundle(executable, output=None, copyfunc=None, creator=None, plist=None, nib=None, resources=None): if not output: output = os.path.split(executable)[1] + '.app' if not copyfunc: copyfunc = shutil.copy2 if not creator: creator='????' if not resources: resources = [] if nib: resources = resources + [nib] # #...
print "buildappbundle creates an application bundle" print "Usage:" print " buildappbundle [options] executable" print "Options:" print " --output o Output file; default executable with .app appended, short -o" print " --link Symlink the executable (default: copy), short -l" print " --plist file Plist fi...
print __doc__
def usage(): print "buildappbundle creates an application bundle" print "Usage:" print " buildappbundle [options] executable" print "Options:" print " --output o Output file; default executable with .app appended, short -o" print " --link Symlink the executable (default: copy), short -l" print " --plist f...
output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help")
output = None symlink = 0 creator = "????" plist = None nib = None resources = [] verbosity = 0 SHORTOPTS = "o:ln:r:p:c:v?h" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help", "verbose")
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for...
copyfunc = os.symlink
symlink = 1
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for...
elif opt in ('-?', '--help'):
elif opt in ('-v', '--verbose'): verbosity += 1 elif opt in ('-?', '-h', '--help'):
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for...
buildappbundle(args[0], output=output, copyfunc=copyfunc, creator=creator, plist=plist, resources=resources)
if output is not None: builddir, bundlename = os.path.split(output) else: builddir = os.curdir bundlename = None if plist is not None: plist = Plist.fromFile(plist) builder = AppBuilder(name=bundlename, executable=executable, builddir=builddir, creator=creator, plist=plist, resources=resources, symlink=symlink, verbos...
def main(): output=None copyfunc=None creator=None plist=None nib=None resources=[] SHORTOPTS = "o:ln:r:p:c:?" LONGOPTS=("output=", "link", "nib=", "resource=", "plist=", "creator=", "help") try: options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) except getopt.error: usage() if len(args) != 1: usage() for...
fullname = os.path.join(dirname, basename)
def updatecache(filename): """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list.""" if cache.has_key(filename): del cache[filename] if not filename or filename[0] + filename[-1] == '<>': return [] fullname = filename try: stat = ...
stat = os.stat(fullname) break except os.error:
fullname = os.path.join(dirname, basename) except (TypeError, AttributeError):
def updatecache(filename): """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list.""" if cache.has_key(filename): del cache[filename] if not filename or filename[0] + filename[-1] == '<>': return [] fullname = filename try: stat = ...
interp_path = os.path.join(sys.exec_prefix, "bin", "python")
interp_path = os.path.join(sys.exec_prefix, "Resources", "Python.app", "Contents", "MacOS", "Python") if not os.path.exists(interp_path): interp_path = os.path.join(sys.exec_prefix, "bin", "python")
def _run_with_cl_interpreter(self): import Terminal interp_path = os.path.join(sys.exec_prefix, "bin", "python") file_path = self.path if not os.path.exists(interp_path): # This "can happen" if we are running IDE under MacPython-OS9. raise W.AlertError, "Can't find command-line Python" cmd = '"%s" "%s" ; exit' % (inter...
t.do_script(with_command=cmd)
t.do_script(cmd)
def _run_with_cl_interpreter(self): import Terminal interp_path = os.path.join(sys.exec_prefix, "bin", "python") file_path = self.path if not os.path.exists(interp_path): # This "can happen" if we are running IDE under MacPython-OS9. raise W.AlertError, "Can't find command-line Python" cmd = '"%s" "%s" ; exit' % (inter...
if time.strftime(directive, time_tuple).find('00'):
if '00' in time.strftime(directive, time_tuple):
def __calc_date_time(self): # Set self.date_time, self.date, & self.time by using # time.strftime().
list.append('%s: %s\n' % (str(stype), str(value))) return list
list.append('%s: %s\n' % (str(stype), _some_str(value))) return list def _some_str(value): try: return str(value) except: return '<unprintable %s object>' % type(value).__name__
def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError...