rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
_monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] _daynames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] | _monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] | def dump_address_pair(pair): """Dump a (name, address) pair in a canonicalized form.""" if pair[0]: return '"' + pair[0] + '" <' + pair[1] + '>' else: return pair[1] |
if data[0][-1] == ',' or data[0] in _daynames: | if data[0][-1] in (',', '.') or string.lower(data[0]) in _daynames: | def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = string.split(data) if data[0][-1] == ',' or data[0] in _daynames: # There's a dayname here. Skip it del data[0] if len(data) == 3: # RFC 850 date, deprecated stuff = string.split(data[0], '-') if len(stuff) ==... |
dd, mm, yy, tm, tz = mm, dd, tm, yy, tz | dd, mm = mm, string.lower(dd) | def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = string.split(data) if data[0][-1] == ',' or data[0] in _daynames: # There's a dayname here. Skip it del data[0] if len(data) == 3: # RFC 850 date, deprecated stuff = string.split(data[0], '-') if len(stuff) ==... |
lexer.wordchars = lexer.wordchars + '.' | lexer.wordchars = lexer.wordchars + '.-@' | def __init__(self, file=None): if not file: file = os.path.join(os.environ['HOME'], ".netrc") try: fp = open(file) except: return None self.hosts = {} self.macros = {} lexer = shlex.shlex(fp) lexer.wordchars = lexer.wordchars + '.' while 1: # Look for a machine, default, or macdef top-level keyword toplevel = tt = lexe... |
if prog.match(line) == len(line): | if prog.match(line) >= 0: | def pickline(file, key, casefold = 1): try: f = open(file, 'r') except IOError: return None pat = key + ':' if casefold: prog = regex.compile(pat, regex.casefold) else: prog = regex.compile(pat) while 1: line = f.readline() if not line: break if prog.match(line) == len(line): text = line[len(key)+1:] while 1: line = f.... |
websucker.Sucker.savefilename(self, url)) | websucker.Sucker.savefilename(self.sucker, url)) | def go(self, event=None): if not self.msgq: self.msgq = Queue.Queue(0) self.check_msgq() if not self.sucker: self.sucker = SuckerThread(self.msgq) if self.sucker.stopit: return self.url_entry.selection_range(0, END) url = self.url_entry.get() url = url.strip() if not url: self.top.bell() self.message("[Error: No URL en... |
builtin = r"([^\\.]\b|^)" + any("BUILTIN", builtinlist) + r"\b" | builtin = r"([^.'\"\\]\b|^)" + any("BUILTIN", builtinlist) + r"\b" | def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] builtin = r"([^\\.]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) sqstring = r"(\b[rR])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = r'(\... |
return kw + "|" + builtin + "|" + comment + "|" + string + "|" + any("SYNC", [r"\n"]) | return kw + "|" + builtin + "|" + comment + "|" + string +\ "|" + any("SYNC", [r"\n"]) | def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] builtin = r"([^\\.]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) sqstring = r"(\b[rR])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = r'(\... |
allow_colorizing = 1 colorizing = 0 | allow_colorizing = True colorizing = False | def delete(self, index1, index2=None): index1 = self.index(index1) self.delegate.delete(index1, index2) self.notify_range(index1) |
self.stop_colorizing = 1 | self.stop_colorizing = True | 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.af... |
self.allow_colorizing = 0 self.stop_colorizing = 1 | self.allow_colorizing = False self.stop_colorizing = True | 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... |
self.stop_colorizing = 1 | self.stop_colorizing = True | 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.all... |
print "auto colorizing turned", self.allow_colorizing and "on" or "off" | print "auto colorizing turned",\ self.allow_colorizing and "on" or "off" | 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.all... |
self.stop_colorizing = 0 self.colorizing = 1 | self.stop_colorizing = False self.colorizing = True | 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 "colorizin... |
self.colorizing = 0 | self.colorizing = False | 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 "colorizin... |
while 1: | while True: | 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" |
ok = 0 | ok = False | 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 readfp(self): | def readfp(self, fp): | def readfp(self): """Read a single mime.types-format file.""" map = self.types_map while 1: line = f.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: map['.' + suff]... |
line = f.readline() | line = fp.readline() | def readfp(self): """Read a single mime.types-format file.""" map = self.types_map while 1: line = f.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: map['.' + suff]... |
print >>sys.stderr, "l1=%r, l2=%r, ignore=%r" % (l1, l2, ignore) | print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore) | def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' try: for p1, p2 in (l1, l2), (l2, l1): for item in p1: ok = (item in p2) or (item in ignore) if not ok: self.fail("%r missing" % item) except: print >>sys.stderr, "l1=%r, l2=%r, ignore=%r" % (l1, l2, ignore) raise |
if type(getattr(py_item, m)) == MethodType: | if ismethod(getattr(py_item, m), m): | def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' |
self.assertListEq(foundMethods, actualMethods, ignore) self.assertEquals(py_item.__module__, value.module) | try: self.assertListEq(foundMethods, actualMethods, ignore) self.assertEquals(py_item.__module__, value.module) | def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' |
self.assertEquals(py_item.__name__, value.name, ignore) | self.assertEquals(py_item.__name__, value.name, ignore) except: print >>sys.stderr, "class=%s" % py_item raise | def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' |
self.checkModule('doctest', ignore=['_isclass', '_isfunction', '_ismodule', '_classify_class_attrs']) self.checkModule('rfc822', ignore=["get"]) | self.checkModule('doctest') self.checkModule('rfc822') | def test_easy(self): self.checkModule('pyclbr') self.checkModule('doctest', ignore=['_isclass', '_isfunction', '_ismodule', '_classify_class_attrs']) self.checkModule('rfc822', ignore=["get"]) self.checkModule('difflib') |
cm('cgi', ignore=('f', 'g', 'log')) cm('mhlib', ignore=('do', 'bisect')) cm('urllib', ignore=('getproxies_environment', 'getproxies_registry', 'open_https')) cm('pickle', ignore=('g',)) cm('aifc', ignore=('openfp',)) cm('Cookie', ignore=('__str__', 'Cookie')) cm('sre_parse', ignore=('literal', 'makedict', 'dump' ... | cm('cgi', ignore=('log',)) cm('mhlib') cm('urllib', ignore=('getproxies_registry', 'open_https')) cm('pickle', ignore=('g',)) cm('aifc', ignore=('openfp',)) cm('Cookie') cm('sre_parse', ignore=('dump',)) cm('pdb') cm('pydoc') | def test_others(self): cm = self.checkModule |
cm('test.test_pyclbr', ignore=('defined_in',)) | cm('test.test_pyclbr') | def test_others(self): cm = self.checkModule |
return st[stat.ST_MTIME] | return st[stat.ST_ATIME] | def getatime(filename): """Return the last access time of a file, reported by os.stat().""" st = os.stat(filename) return st[stat.ST_MTIME] |
if verbose: print "starting pause() loop..." | print "starting pause() loop..." | def force_test_exit(): # Sigh, both imports seem necessary to avoid errors. import os fork_pid = os.fork() if fork_pid: # In parent. return fork_pid # In child. import os, time try: # Wait 5 seconds longer than the expected alarm to give enough # time for the normal sequence of events to occur. This is # just a stop-... |
def __hasattr__(self, attr): "Delegate attribute access to the interpreter object" return hasattr(self.tk, attr) def __delattr__(self, attr): "Delegate attribute access to the interpreter object" return delattr(self.tk, attr) | def __hasattr__(self, attr): "Delegate attribute access to the interpreter object" return hasattr(self.tk, attr) | |
pass | if size > self.extrasize: size = self.extrasize | def read(self, size=None): if self.extrasize <= 0 and self.fileobj is None: return '' |
self.extrasize = len(self.extrabuf) | self.extrasize = len(buf) + self.extrasize | def _unread(self, buf): self.extrabuf = buf + self.extrabuf self.extrasize = len(self.extrabuf) |
return string.split(buf, '\n') | lines = string.split(buf, '\n') for i in range(len(lines)-1): lines[i] = lines[i] + '\n' if lines and not lines[-1]: del lines[-1] return lines | def readlines(self): buf = self.read() return string.split(buf, '\n') |
fragment = url[i+1:] | def urlparse(url, scheme = '', allow_fragments = 1): key = url, scheme, allow_fragments cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() find = string.find netloc = path = params = query = fragment = '' i = find(url, ':') if i > 0... | |
query = url[i+1:] | def urlparse(url, scheme = '', allow_fragments = 1): key = url, scheme, allow_fragments cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() find = string.find netloc = path = params = query = fragment = '' i = find(url, ':') if i > 0... | |
params = url[i+1:] | def urlparse(url, scheme = '', allow_fragments = 1): key = url, scheme, allow_fragments cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() find = string.find netloc = path = params = query = fragment = '' i = find(url, ':') if i > 0... | |
SyntaxError: 'yield' outside function (<doctest test.test_generators.__test__.coroutine[10]>, line 1) | SyntaxError: 'yield' outside function (<doctest test.test_generators.__test__.coroutine[21]>, line 1) | >>> def f(): list(i for i in [(yield 26)]) |
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[11]>, line 1) | SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[22]>, line 1) | >>> def f(): return lambda x=(yield): 1 |
SyntaxError: assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[12]>, line 1) | SyntaxError: assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[23]>, line 1) >>> def f(): (yield bar) = y Traceback (most recent call last): ... SyntaxError: can't assign to yield expression (<doctest test.test_generators.__test__.coroutine[24]>, line 1) >>> def f(): (yield... | >>> def f(): x = yield = y |
(msg is None or mod.match(module)) and | (mod is None or mod.match(module)) and | def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} if isinstance(message, Warning): text = str(message) category = message.__c... |
if self.disp.format == 'mono': nline = (len(data)*8)/self.vw elif self.disp.format == 'grey2': nline = (len(data)*4)/self.vw elif self.disp.format == 'grey4': nline = (len(data)*2)/self.vw else: nline = len(data)/self.vw if nline*self.vw <> len(data): print 'Incorrect-sized video fragment ignored' return | nline = len(data)/self.linewidth() if nline*self.linewidth() <> len(data): print 'Incorrect-sized video fragment ignored' return | def putnextpacket(self, pos, data): if self.disp.format == 'mono': # Unfortunately size-check is difficult for # packed video nline = (len(data)*8)/self.vw elif self.disp.format == 'grey2': nline = (len(data)*4)/self.vw elif self.disp.format == 'grey4': nline = (len(data)*2)/self.vw else: nline = len(data)/self.vw if n... |
rd, wr, ex = select([self.socket.fileno()], | rd, wr, ex = select.select([self.socket.fileno()], | def serve_until_stopped(self): abort = 0 while not abort: rd, wr, ex = select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort |
sys.stdout.write("About to start TCP server...\n") | def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #... | |
banner("logrecv output", "begin") sys.stdout.write(sockOut.getvalue()) sockOut.close() banner("logrecv output", "end") | def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #... | |
sys.stdout.flush() | def test_main(): rootLogger = logging.getLogger("") rootLogger.setLevel(logging.DEBUG) hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter(logging.BASIC_FORMAT) hdlr.setFormatter(fmt) rootLogger.addHandler(hdlr) #Set up a handler such that all events are sent via a socket to the log #receiver (logrecv). #... | |
__import__(ext.name) | imp.load_dynamic(ext.name, ext_filename) | def build_extension(self, ext): |
oparg = ord(code[i]) + ord(code[i+1])*256 | oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 | def disassemble(co, lasti=-1): """Disassemble a code object.""" code = co.co_code labels = findlabels(code) n = len(code) i = 0 while i < n: c = code[i] op = ord(c) if op == SET_LINENO and i > 0: print # Extra blank line if i == lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print ... |
self.simpleElement("real", str(value)) | self.simpleElement("real", repr(value)) | def writeValue(self, value): if isinstance(value, (str, unicode)): self.simpleElement("string", value) elif isinstance(value, bool): # must switch for bool before int, as bool is a # subclass of int... if value: self.simpleElement("true") else: self.simpleElement("false") elif isinstance(value, int): self.simpleElement... |
import base64 | def fromBase64(cls, data): import base64 return cls(base64.decodestring(data)) | |
import base64 | def asBase64(self): import base64 return base64.encodestring(self.data) | |
"""Primitive date wrapper, uses time floats internally, is agnostic about time zones. | """Primitive date wrapper, uses UTC datetime instances internally. | def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self.data)) |
if isinstance(date, str): from xml.utils.iso8601 import parse date = parse(date) | if isinstance(date, datetime.datetime): pass elif isinstance(date, (float, int)): date = datetime.datetime.fromtimestamp(date) elif isinstance(date, basestring): order = ('year', 'month', 'day', 'hour', 'minute', 'second') gd = _dateParser.match(date).groupdict() lst = [] for key in order: val = gd[key] if val is None:... | def __init__(self, date): if isinstance(date, str): from xml.utils.iso8601 import parse date = parse(date) self.date = date |
from xml.utils.iso8601 import tostring return tostring(self.date) | d = self.date return '%04d-%02d-%02dT%02d:%02d:%02dZ' % ( d.year, d.month, d.day, d.second, d.minute, d.hour, ) | def toString(self): from xml.utils.iso8601 import tostring return tostring(self.date) |
elif isinstance(other, (int, float)): return cmp(self.date, other) | elif isinstance(other, (datetime.datetime, float, int, basestring)): return cmp(self.date, Date(other).date) | def __cmp__(self, other): if isinstance(other, self.__class__): return cmp(self.date, other.date) elif isinstance(other, (int, float)): return cmp(self.date, other) else: return cmp(id(self), id(other)) |
def parse(self, file): | def parse(self, fileobj): | def parse(self, file): from xml.parsers.expat import ParserCreate parser = ParserCreate() parser.StartElementHandler = self.handleBeginElement parser.EndElementHandler = self.handleEndElement parser.CharacterDataHandler = self.handleData parser.ParseFile(file) return self.root |
parser.ParseFile(file) | parser.ParseFile(fileobj) | def parse(self, file): from xml.parsers.expat import ParserCreate parser = ParserCreate() parser.StartElementHandler = self.handleBeginElement parser.EndElementHandler = self.handleEndElement parser.CharacterDataHandler = self.handleData parser.ParseFile(file) return self.root |
compile_dir(dir, maxlevels, None, force) | success = success and compile_dir(dir, maxlevels, None, force) return success | 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) """ for dir in sys.path: if (not dir or dir == os.c... |
compile_dir(dir, maxlevels, ddir, force) | success = success and compile_dir(dir, maxlevels, ddir, force) | def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu... |
compile_path() | success = compile_path() | def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu... |
main() | sys.exit(not main()) | def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: pu... |
f = codecs.getwriter(self.encoding)(s) | f = codecs.getreader(self.encoding)(s) | def test_badbom(self): s = StringIO.StringIO("\xff\xff") f = codecs.getwriter(self.encoding)(s) self.assertRaises(UnicodeError, f.read) |
def addwork(self, job): if not job: raise TypeError, 'cannot add null job' | def addwork(self, func, args): job = (func, args) | def addwork(self, job): if not job: raise TypeError, 'cannot add null job' self.mutex.acquire() self.work.append(job) self.mutex.release() if len(self.work) == 1: self.todo.release() |
Ctrl-E Go to right edge (nospaces off) or end of line (nospaces on). | Ctrl-E Go to right edge (stripspaces off) or end of line (stripspaces on). | def rectangle(win, uly, ulx, lry, lrx): "Draw a rectangle." win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER)... |
Ctrl-L Refresh screen | Ctrl-L Refresh screen. | def rectangle(win, uly, ulx, lry, lrx): "Draw a rectangle." win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER)... |
def firstblank(self, y): | def _end_of_line(self, y): | def firstblank(self, y): "Go to the location of the first blank on the given line." last = self.maxx while 1: if ascii.ascii(self.win.inch(y, last)) != ascii.SP: last = last + 1 break elif last == 0: break last = last - 1 return last |
self.win.move(y-1, self.firstblank(y-1)) | self.win.move(y-1, self._end_of_line(y-1)) | def do_command(self, ch): "Process a single editing command." (y, x) = self.win.getyx() self.lastcmd = ch if ascii.isprint(ch): if y < self.maxy or x < self.maxx: # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the self.window. try: self.wi... |
self.win.move(y, self.firstblank(y)) | self.win.move(y, self._end_of_line(y)) | def do_command(self, ch): "Process a single editing command." (y, x) = self.win.getyx() self.lastcmd = ch if ascii.isprint(ch): if y < self.maxy or x < self.maxx: # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the self.window. try: self.wi... |
if x == 0 and self.firstblank(y) == 0: | if x == 0 and self._end_of_line(y) == 0: | def do_command(self, ch): "Process a single editing command." (y, x) = self.win.getyx() self.lastcmd = ch if ascii.isprint(ch): if y < self.maxy or x < self.maxx: # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the self.window. try: self.wi... |
stop = self.firstblank(y) | stop = self._end_of_line(y) | def gather(self): "Collect and return the contents of the window." result = "" for y in range(self.maxy+1): self.win.move(y, 0) stop = self.firstblank(y) #sys.stderr.write("y=%d, firstblank(y)=%d\n" % (y, stop)) if stop == 0 and self.stripspaces: continue for x in range(self.maxx+1): if self.stripspaces and x == stop: ... |
while not os.path.isdir(":Mac:Plugins"): | while not os.path.isdir(":Mac:PlugIns"): | def gotopluginfolder(): """Go to the plugin folder, assuming we are somewhere in the Python tree""" import os while not os.path.isdir(":Mac:Plugins"): os.chdir("::") os.chdir(":Mac:Plugins") if verbose: print "current directory is", os.getcwd() |
os.chdir(":Mac:Plugins") | os.chdir(":Mac:PlugIns") | def gotopluginfolder(): """Go to the plugin folder, assuming we are somewhere in the Python tree""" import os while not os.path.isdir(":Mac:Plugins"): os.chdir("::") os.chdir(":Mac:Plugins") if verbose: print "current directory is", os.getcwd() |
if not os.path.exists(src): if not os.path.exists(altsrc): | if not os.path.exists(os.path.join(sys.exec_prefix, src)): if not os.path.exists(os.path.join(sys.exec_prefix, altsrc)): | def mkcorealias(src, altsrc): import string import macostools version = string.split(sys.version)[0] dst = getextensiondirfile(src+ ' ' + version) if not os.path.exists(src): if not os.path.exists(altsrc): if verbose: print '*', src, 'not found' return 0 src = altsrc try: os.unlink(dst) except os.error: pass macostool... |
macostools.mkalias(src, dst) | macostools.mkalias(os.path.join(sys.exec_prefix, src), dst) | def mkcorealias(src, altsrc): import string import macostools version = string.split(sys.version)[0] dst = getextensiondirfile(src+ ' ' + version) if not os.path.exists(src): if not os.path.exists(altsrc): if verbose: print '*', src, 'not found' return 0 src = altsrc try: os.unlink(dst) except os.error: pass macostool... |
if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.prompt) self.stdout.flush() ... | if self.use_rawinput and self.completekey: | def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. |
if self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass | pass | def postloop(self): """Hook method executed once when the cmdloop() method is about to return. |
def run_suite(suite): | def run_suite(suite, testclass=None): | def run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2) else: runner = BasicTestRunner() result = runner.run(suite) if not result.wasSuccessful(): if len(result.errors) == 1 and not result.failures: err = result.errors[0][1] e... |
raise TestFailed("errors occurred in %s.%s" % (testclass.__module__, testclass.__name__)) | if testclass is None: msg = "errors occurred; run in verbose mode for details" else: msg = "errors occurred in %s.%s" \ % (testclass.__module__, testclass.__name__) raise TestFailed(msg) | def run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2) else: runner = BasicTestRunner() result = runner.run(suite) if not result.wasSuccessful(): if len(result.errors) == 1 and not result.failures: err = result.errors[0][1] e... |
run_suite(unittest.makeSuite(testclass)) | run_suite(unittest.makeSuite(testclass), testclass) | def run_unittest(testclass): """Run tests from a unittest.TestCase-derived class.""" run_suite(unittest.makeSuite(testclass)) |
return _Dialog._fixresult(widget, result) | return _Dialog._fixresult(self, widget, result) | def _fixresult(self, widget, result): if isinstance(result, tuple): # multiple results: result = tuple([getattr(r, "string", r) for r in result]) if result: import os path, file = os.path.split(result[0]) self.options["initialdir"] = path # don't set initialfile or filename, as we have multiple of these return result i... |
return top_module | if fromlist: return getattr(top_module, parts[1]) else: return top_module | def _import_hook(self, fqname, globals=None, locals=None, fromlist=None): """Python calls this hook to locate and import a module.""" |
self.editFont=tkFont.Font(self,('courier',12,'normal')) | self.editFont=tkFont.Font(self,('courier',10,'normal')) | def CreatePageFontTab(self): #tkVars self.fontSize=StringVar(self) self.fontBold=BooleanVar(self) self.fontName=StringVar(self) self.spaceNum=IntVar(self) #self.tabCols=IntVar(self) self.indentBySpaces=BooleanVar(self) self.editFont=tkFont.Font(self,('courier',12,'normal')) ##widget creation #body frame frame=self.tabP... |
self.fontName.set(self.listFontName.get(ANCHOR)) | font = self.listFontName.get(ANCHOR) self.fontName.set(font.lower()) | def OnListFontButtonRelease(self,event): self.fontName.set(self.listFontName.get(ANCHOR)) self.SetFontSample() |
self.fontName.set(configuredFont) if configuredFont in fonts: currentFontIndex=fonts.index(configuredFont) | lc_configuredFont = configuredFont.lower() self.fontName.set(lc_configuredFont) lc_fonts = [s.lower() for s in fonts] if lc_configuredFont in lc_fonts: currentFontIndex = lc_fonts.index(lc_configuredFont) | def LoadFontCfg(self): ##base editor font selection list fonts=list(tkFont.families(self)) fonts.sort() for font in fonts: self.listFontName.insert(END,font) configuredFont=idleConf.GetOption('main','EditorWindow','font', default='courier') self.fontName.set(configuredFont) if configuredFont in fonts: currentFontIndex=... |
default='12') | default='10') | def LoadFontCfg(self): ##base editor font selection list fonts=list(tkFont.families(self)) fonts.sort() for font in fonts: self.listFontName.insert(END,font) configuredFont=idleConf.GetOption('main','EditorWindow','font', default='courier') self.fontName.set(configuredFont) if configuredFont in fonts: currentFontIndex=... |
self.relative = 0 | def initialize_options (self): self.bdist_dir = None self.plat_name = None self.format = None self.keep_temp = 0 self.dist_dir = None self.skip_build = 0 | |
self.make_archive(os.path.join(self.dist_dir, archive_basename), self.format, root_dir=self.bdist_dir) | pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) if not self.relative: archive_root = self.bdist_dir else: if (self.distribution.has_ext_modules() and (install.install_base != install.install_platbase)): raise DistutilsPlatformError, \ ("can't make a dumb built distribution where " "base and platbase ... | def run (self): |
self.assert_(isinstance(bi[0], int)) | self.assert_(isinstance(bi[0], (int, long))) | def test_buffer_info(self): a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.buffer_info, 42) bi = a.buffer_info() self.assert_(isinstance(bi, tuple)) self.assertEqual(len(bi), 2) self.assert_(isinstance(bi[0], int)) self.assert_(isinstance(bi[1], int)) self.assertEqual(bi[1], len(a)) |
idle_v = Label(frameBg, text='IDLE version ' + idlever.IDLE_VERSION, | idle_v = Label(frameBg, text='IDLE version: ' + idlever.IDLE_VERSION, | def CreateWidgets(self): frameMain = Frame(self, borderwidth=2, relief=SUNKEN) frameButtons = Frame(self) frameButtons.pack(side=BOTTOM, fill=X) frameMain.pack(side=TOP, expand=TRUE, fill=BOTH) self.buttonOk = Button(frameButtons, text='Close', command=self.Ok) self.buttonOk.pack(padx=5, pady=5) #self.picture = Image('... |
parent = readmodule(package, path, inpackage) child = readmodule(submodule, parent['__path__'], 1) | parent = readmodule_ex(package, path, inpackage) child = readmodule_ex(submodule, parent['__path__'], 1) | def readmodule_ex(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' dict = {} i = module.rfind('.') if i >= 0: # Dotted module name pa... |
d = readmodule(n, path, inpackage) | d = readmodule_ex(n, path, inpackage) | def readmodule_ex(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' dict = {} i = module.rfind('.') if i >= 0: # Dotted module name pa... |
d = readmodule(mod, path, inpackage) | d = readmodule_ex(mod, path, inpackage) | def readmodule_ex(module, path=[], inpackage=0): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module.''' dict = {} i = module.rfind('.') if i >= 0: # Dotted module name pa... |
import Plist builder.plist = Plist.fromFile(plistname) | import plistlib builder.plist = plistlib.Plist.fromFile(plistname) | def process_common_macho(template, progress, code, rsrcname, destname, is_update, raw=0, others=[], filename=None): # Check that we have a filename if filename is None: raise BuildError, "Need source filename on MacOSX" # First make sure the name ends in ".app" if destname[-4:] != '.app': destname = destname + '.app' #... |
if row: | if row is not None: | def grid_slaves(self, row=None, column=None): args = () if row: args = args + ('-row', row) if column: args = args + ('-column', column) return map(self._nametowidget, self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args))) |
if column: | if column is not None: | def grid_slaves(self, row=None, column=None): args = () if row: args = args + ('-row', row) if column: args = args + ('-column', column) return map(self._nametowidget, self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args))) |
return self._bind((self._w, 'bind', tagOrId), sequence, func, add) | res = self._bind((self._w, 'bind', tagOrId), sequence, func, add) if sequence and func and res: if self._tagcommands is None: self._tagcommands = {} list = self._tagcommands.get(tagOrId) or [] self._tagcommands[tagOrId] = list list.append(res) return res | def tag_bind(self, tagOrId, sequence=None, func=None, add=None): return self._bind((self._w, 'bind', tagOrId), sequence, func, add) |
def search(self, charset, criteria): | def search(self, charset, *criteria): | def search(self, charset, criteria): """Search mailbox for matching messages. |
(typ, [data]) = <instance>.search(charset, criteria) | (typ, [data]) = <instance>.search(charset, criterium, ...) | def search(self, charset, criteria): """Search mailbox for matching messages. |
typ, dat = self._simple_command(name, charset, criteria) | typ, dat = apply(self._simple_command, (name, charset) + criteria) | def search(self, charset, criteria): """Search mailbox for matching messages. |
import getpass, sys host = '' if sys.argv[1:]: host = sys.argv[1] | import getopt, getpass, sys try: optlist, args = getopt.getopt(sys.argv[1:], 'd:') except getopt.error, val: pass for opt,val in optlist: if opt == '-d': Debug = int(val) if not args: args = ('',) host = args[0] | def print_log(): _mesg('last %d IMAP4 interactions:' % len(_cmd_log)) for secs,line in _cmd_log: _mesg(line, secs) |
('search', (None, '(TO zork)')), | ('search', (None, 'SUBJECT', 'test')), | def print_log(): _mesg('last %d IMAP4 interactions:' % len(_cmd_log)) for secs,line in _cmd_log: _mesg(line, secs) |
Debug = 5 M = IMAP4(host) _mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION) for cmd,args in test_seq1: run(cmd, args) for ml in run('list', ('/tmp/', 'yy%')): mo = re.match(r'.*"([^"]+)"$', ml) if mo: path = mo.group(1) else: path = string.split(ml)[-1] run('delete', (path,)) for cmd,args in test_seq2: dat = run(c... | try: M = IMAP4(host) _mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION) for cmd,args in test_seq1: run(cmd, args) for ml in run('list', ('/tmp/', 'yy%')): mo = re.match(r'.*"([^"]+)"$', ml) if mo: path = mo.group(1) else: path = string.split(ml)[-1] run('delete', (path,)) for cmd,args in test_seq2: dat = run(cmd, a... | def run(cmd, args): _mesg('%s %s' % (cmd, args)) typ, dat = apply(eval('M.%s' % cmd), args) _mesg('%s => %s %s' % (cmd, typ, dat)) return dat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.