bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def set_tabwidth(self, newtabwidth): text = self.text if self.get_tabwidth() != newtabwidth: pixels = text.tk.call("font", "measure", text["font"], "-displayof", text.master, "n" * newtabwith) text.configure(tabs=pixels)
|
def set_tabwidth(self, newtabwidth): text = self.text if self.get_tabwidth() != newtabwidth: pixels = text.tk.call("font", "measure", text["font"], "-displayof", text.master, "n" * newtabwidth) text.configure(tabs=pixels)
| 11,200
|
def _find_module(fullname, path=None): """Version of imp.find_module() that handles hierarchical module names""" file = None for tgt in fullname.split('.'): if file is not None: file.close() # close intermediate files (file, filename, descr) = imp.find_module(tgt, path) if descr[2] == imp.PY_SOURCE: break # find but not load the source file module = imp.load_module(tgt, file, filename, descr) path = module.__path__ return file, filename, descr
|
def _find_module(fullname, path=None): """Version of imp.find_module() that handles hierarchical module names""" file = None for tgt in fullname.split('.'): if file is not None: file.close() # close intermediate files (file, filename, descr) = imp.find_module(tgt, path) if descr[2] == imp.PY_SOURCE: break # find but not load the source file module = imp.load_module(tgt, file, filename, descr) try: path = module.__path__ except AttributeError: raise ImportError, 'No source for module ' + module.__name__ return file, filename, descr
| 11,201
|
def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback.''' if not callback: callback = print_line resp = self.sendcmd('TYPE A') conn = self.transfercmd(cmd) fp = conn.makefile('rb') while 1: line = fp.readline() if self.debugging > 2: print '*retr*', `line` if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) fp.close() conn.close() return self.voidresp()
|
def retrlines(self, cmd, callback = None): '''Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback.''' if not callable(callback): callback = print_line resp = self.sendcmd('TYPE A') conn = self.transfercmd(cmd) fp = conn.makefile('rb') while 1: line = fp.readline() if self.debugging > 2: print '*retr*', `line` if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) fp.close() conn.close() return self.voidresp()
| 11,202
|
def _run_examples_inner(out, fakeout, examples, globs, verbose, name): import sys, traceback OK, BOOM, FAIL = range(3) NADA = "nothing" stderr = _SpoofOut() failures = 0 for source, want, lineno in examples: if verbose: _tag_out(out, ("Trying", source), ("Expecting", want or NADA)) fakeout.clear() try: exec compile(source, "<string>", "single") in globs got = fakeout.get() state = OK except: # See whether the exception was expected. if want.find("Traceback (innermost last):\n") == 0 or \ want.find("Traceback (most recent call last):\n") == 0: # Only compare exception type and value - the rest of # the traceback isn't necessary. want = want.split('\n')[-2] + '\n' exc_type, exc_val, exc_tb = sys.exc_info() got = traceback.format_exception_only(exc_type, exc_val)[-1] state = OK else: # unexpected exception stderr.clear() traceback.print_exc(file=stderr) state = BOOM if state == OK: if got == want: if verbose: out("ok\n") continue state = FAIL assert state in (FAIL, BOOM) failures = failures + 1 out("*" * 65 + "\n") _tag_out(out, ("Failure in example", source)) out("from line #" + `lineno` + " of " + name + "\n") if state == FAIL: _tag_out(out, ("Expected", want or NADA), ("Got", got)) else: assert state == BOOM _tag_out(out, ("Exception raised", stderr.get())) return failures, len(examples)
|
def _run_examples_inner(out, fakeout, examples, globs, verbose, name): import sys, traceback OK, BOOM, FAIL = range(3) NADA = "nothing" stderr = _SpoofOut() failures = 0 for source, want, lineno in examples: if verbose: _tag_out(out, ("Trying", source), ("Expecting", want or NADA)) fakeout.clear() try: exec compile(source, "<string>", "single") in globs got = fakeout.get() state = OK except: # See whether the exception was expected. if want.find("Traceback (innermost last):\n") == 0 or \ want.find("Traceback (most recent call last):\n") == 0: # Only compare exception type and value - the rest of # the traceback isn't necessary. want = want.split('\n')[-2] + '\n' exc_type, exc_val = sys.exc_info()[:2] got = traceback.format_exception_only(exc_type, exc_val)[-1] state = OK else: # unexpected exception stderr.clear() traceback.print_exc(file=stderr) state = BOOM if state == OK: if got == want: if verbose: out("ok\n") continue state = FAIL assert state in (FAIL, BOOM) failures = failures + 1 out("*" * 65 + "\n") _tag_out(out, ("Failure in example", source)) out("from line #" + `lineno` + " of " + name + "\n") if state == FAIL: _tag_out(out, ("Expected", want or NADA), ("Got", got)) else: assert state == BOOM _tag_out(out, ("Exception raised", stderr.get())) return failures, len(examples)
| 11,203
|
def append(self, s, charset=None): """Append a string to the MIME header.
|
def append(self, s, charset=None): """Append a string to the MIME header.
| 11,204
|
def getquotaroot(self, mailbox): """Get the list of quota roots for the named mailbox.
|
def getquotaroot(self, mailbox): """Get the list of quota roots for the named mailbox.
| 11,205
|
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
|
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
| 11,206
|
def dup(self): import posix
|
def dup(self): import posix
| 11,207
|
def dup2(self, fd): import posix
|
def dup2(self, fd): import posix
| 11,208
|
def help_dialog(self, event=None): fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') textView.TextViewer(self.top,'Help',fn)
|
def help_dialog(self, event=None): fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') textView.TextViewer(self.top,'Help',fn)
| 11,209
|
def help_dialog(self, event=None): fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') textView.TextViewer(self.top,'Help',fn)
|
def help_dialog(self, event=None): fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') textView.TextViewer(self.top,'Help',fn)
| 11,210
|
def __init__(self, filename, mode="a"): """ Open the specified file and use it as the stream for logging. """ StreamHandler.__init__(self, open(filename, mode)) self.baseFilename = filename self.mode = mode
|
def __init__(self, filename, mode="a"): """ Open the specified file and use it as the stream for logging. """ StreamHandler.__init__(self, open(filename, mode)) self.baseFilename = os.path.abspath(filename) self.mode = mode
| 11,211
|
def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present.
|
def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present.
| 11,212
|
def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name
|
def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name
| 11,213
|
def __getattr__(self, name): raise error(9, 'Bad file descriptor')
|
def _dummy(*args): raise error(9, 'Bad file descriptor')
| 11,214
|
def __getattr__(self, name): raise error(9, 'Bad file descriptor')
|
def __getattr__(self, name): raise error(9, 'Bad file descriptor')
| 11,215
|
def __len__(self): return self.dict.len()
|
def __len__(self): return len(self.dict)
| 11,216
|
def write(self, data): if DEBUG:
|
def write(self, data): if DEBUG:
| 11,217
|
def realpath(filename): """Return the canonical path of the specified filename, eliminating any
|
def realpath(filename): """Return the canonical path of the specified filename, eliminating any
| 11,218
|
def jabs_op(name, op): opname[op] = name hasjabs.append(op)
|
def jabs_op(name, op): opname[op] = name hasjabs.append(op)
| 11,219
|
def compileproperty(self, prop): [name, code, what] = prop if code == 'c@#!': # Something silly with plurals. Skip it. return pname = identify(name) if self.namemappers[0].hascode('property', code): # plural forms and such othername, dummy, dummy = self.namemappers[0].findcodename('property', code) if pname == othername: return if self.fp: self.fp.write("\n%s = %s\n"%(pname, othername)) else: if self.fp: self.fp.write("class %s(aetools.NProperty):\n" % pname) self.fp.write('\t"""%s - %s """\n' % (ascii(name), ascii(what[1]))) self.fp.write("\twhich = %s\n" % `code`) self.fp.write("\twant = %s\n" % `what[0]`) self.namemappers[0].addnamecode('property', pname, code)
|
def compileproperty(self, prop): [name, code, what] = prop if code == 'c@#!': # Something silly with plurals. Skip it. return pname = identify(name) if self.namemappers[0].hascode('property', code): # plural forms and such othername, dummy, dummy = self.namemappers[0].findcodename('property', code) if pname == othername: return if self.fp: self.fp.write("\n_Prop_%s = _Prop_%s\n"%(pname, othername)) else: if self.fp: self.fp.write("class %s(aetools.NProperty):\n" % pname) self.fp.write('\t"""%s - %s """\n' % (ascii(name), ascii(what[1]))) self.fp.write("\twhich = %s\n" % `code`) self.fp.write("\twant = %s\n" % `what[0]`) self.namemappers[0].addnamecode('property', pname, code)
| 11,220
|
def compileproperty(self, prop): [name, code, what] = prop if code == 'c@#!': # Something silly with plurals. Skip it. return pname = identify(name) if self.namemappers[0].hascode('property', code): # plural forms and such othername, dummy, dummy = self.namemappers[0].findcodename('property', code) if pname == othername: return if self.fp: self.fp.write("\n%s = %s\n"%(pname, othername)) else: if self.fp: self.fp.write("class %s(aetools.NProperty):\n" % pname) self.fp.write('\t"""%s - %s """\n' % (ascii(name), ascii(what[1]))) self.fp.write("\twhich = %s\n" % `code`) self.fp.write("\twant = %s\n" % `what[0]`) self.namemappers[0].addnamecode('property', pname, code)
|
def compileproperty(self, prop): [name, code, what] = prop if code == 'c@#!': # Something silly with plurals. Skip it. return pname = identify(name) if self.namemappers[0].hascode('property', code): # plural forms and such othername, dummy, dummy = self.namemappers[0].findcodename('property', code) if pname == othername: return if self.fp: self.fp.write("\n%s = %s\n"%(pname, othername)) else: if self.fp: self.fp.write("class _Prop_%s(aetools.NProperty):\n" % pname) self.fp.write('\t"""%s - %s """\n' % (ascii(name), ascii(what[1]))) self.fp.write("\twhich = %s\n" % `code`) self.fp.write("\twant = %s\n" % `what[0]`) self.namemappers[0].addnamecode('property', pname, code)
| 11,221
|
def fillclasspropsandelems(self, cls): [name, code, desc, properties, elements] = cls cname = identify(name) if self.namemappers[0].hascode('class', code) and \ self.namemappers[0].findcodename('class', code)[0] != cname: # This is an other name (plural or so) for something else. Skip. if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and properties[0][1] != 'c@#!')): if self.verbose: print >>self.verbose, '** Skip multiple %s of %s (code %s)' % (cname, self.namemappers[0].findcodename('class', code)[0], `code`) raise RuntimeError, "About to skip non-empty class" return plist = [] elist = [] superclasses = [] for prop in properties: [pname, pcode, what] = prop if pcode == "c@#^": superclasses.append(what) if pcode == 'c@#!': continue pname = identify(pname) plist.append(pname)
|
def fillclasspropsandelems(self, cls): [name, code, desc, properties, elements] = cls cname = identify(name) if self.namemappers[0].hascode('class', code) and \ self.namemappers[0].findcodename('class', code)[0] != cname: # This is an other name (plural or so) for something else. Skip. if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and properties[0][1] != 'c@#!')): if self.verbose: print >>self.verbose, '** Skip multiple %s of %s (code %s)' % (cname, self.namemappers[0].findcodename('class', code)[0], `code`) raise RuntimeError, "About to skip non-empty class" return plist = [] elist = [] superclasses = [] for prop in properties: [pname, pcode, what] = prop if pcode == "c@#^": superclasses.append(what) if pcode == 'c@#!': continue pname = identify(pname) plist.append(pname)
| 11,222
|
def dumpindex(self): if not self.fp: return self.fp.write("\n#\n# Indices of types declared in this module\n#\n") self.fp.write("_classdeclarations = {\n") classlist = self.namemappers[0].getall('class') classlist.sort() for k, v in classlist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_propdeclarations = {\n") proplist = self.namemappers[0].getall('property') proplist.sort() for k, v in proplist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_compdeclarations = {\n") complist = self.namemappers[0].getall('comparison') complist.sort() for k, v in complist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_enumdeclarations = {\n") enumlist = self.namemappers[0].getall('enum') enumlist.sort() for k, v in enumlist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n")
|
def dumpindex(self): if not self.fp: return self.fp.write("\n#\n# Indices of types declared in this module\n#\n") self.fp.write("_classdeclarations = {\n") classlist = self.namemappers[0].getall('class') classlist.sort() for k, v in classlist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_propdeclarations = {\n") proplist = self.namemappers[0].getall('property') proplist.sort() for k, v in proplist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_compdeclarations = {\n") complist = self.namemappers[0].getall('comparison') complist.sort() for k, v in complist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n") self.fp.write("\n_enumdeclarations = {\n") enumlist = self.namemappers[0].getall('enum') enumlist.sort() for k, v in enumlist: self.fp.write("\t%s : %s,\n" % (`k`, v)) self.fp.write("}\n")
| 11,223
|
def pack_into(fmt, buf, offset, *args): """ Pack the values v2, v2, ... according to fmt, write the packed bytes into the writable buffer buf starting at offset. See struct.__doc__ for more on format strings. """ try: o = _cache[fmt] except KeyError: o = _compile(fmt) return o.pack_into(buf, offset, *args)
|
def pack_into(fmt, buf, offset, *args): """ Pack the values v1, v2, ... according to fmt, write the packed bytes into the writable buffer buf starting at offset. See struct.__doc__ for more on format strings. """ try: o = _cache[fmt] except KeyError: o = _compile(fmt) return o.pack_into(buf, offset, *args)
| 11,224
|
def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in languages: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None
|
def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages nelangs = [] for lang in languages: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None
| 11,225
|
def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in languages: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None
|
def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in languages: for nelang in _expand_lang(lang): if nelang not in nelangs: nelangs.append(nelang) # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None
| 11,226
|
def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in languages: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in languages: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None
|
def find(domain, localedir=None, languages=None): # Get some reasonable defaults for arguments that were not supplied if localedir is None: localedir = _default_localedir if languages is None: languages = [] for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): val = os.environ.get(envar) if val: languages = val.split(':') break if 'C' not in languages: languages.append('C') # now normalize and expand the languages langdict = {} for lang in nelangs: for nelang in _expand_lang(lang): langdict[nelang] = nelang languages = langdict.keys() # select a language for lang in nelangs: if lang == 'C': break mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) if os.path.exists(mofile): return mofile return None
| 11,227
|
def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2))
|
def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2))
| 11,228
|
def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object.
|
defself.digest_size = digestmod.digest_size __init__(self,self.digest_size = digestmod.digest_size key,self.digest_size = digestmod.digest_size msgself.digest_size = digestmod.digest_size =self.digest_size = digestmod.digest_size None,self.digest_size = digestmod.digest_size digestmodself.digest_size = digestmod.digest_size =self.digest_size = digestmod.digest_size None):self.digest_size = digestmod.digest_size """Createself.digest_size = digestmod.digest_size aself.digest_size = digestmod.digest_size newself.digest_size = digestmod.digest_size HMACself.digest_size = digestmod.digest_size object.
| 11,229
|
def copy(self): """Return a separate copy of this hashing object.
|
def copy(self): """Return a separate copy of this hashing object.
| 11,230
|
def test(): def md5test(key, data, digest): h = HMAC(key, data) assert(h.hexdigest().upper() == digest.upper()) # Test vectors from the RFC md5test(chr(0x0b) * 16, "Hi There", "9294727A3638BB1C13F48EF8158BFC9D") md5test("Jefe", "what do ya want for nothing?", "750c783e6ab0b503eaa86e310a5db738") md5test(chr(0xAA)*16, chr(0xDD)*50, "56be34521d144c88dbb8c733f0e8b3f6")
|
def test(): def md5test(key, data, digest): h = HMAC(key, data) assert(h.hexdigest().upper() == digest.upper()) # Test vectors from the RFC md5test(chr(0x0b) * 16, "Hi There", "9294727A3638BB1C13F48EF8158BFC9D") md5test("Jefe", "what do ya want for nothing?", "750c783e6ab0b503eaa86e310a5db738") md5test(chr(0xAA)*16, chr(0xDD)*50, "56be34521d144c88dbb8c733f0e8b3f6")
| 11,231
|
def _archiveOK(self): """Test an archive. It should exist and the MD5 checksum should be correct.""" if not os.path.exists(self.archiveFilename): return 0 if not self._dict['MD5Sum']: sys.stderr.write("Warning: no MD5Sum for %s\n" % self.fullname()) return 1 data = open(self.archiveFilename, 'rb').read() checksum = md5.new(data).hexdigest() return checksum == self._dict['MD5Sum']
|
def _archiveOK(self): """Test an archive. It should exist and the MD5 checksum should be correct.""" if not os.path.exists(self.archiveFilename): return 0 if not self._dict.get('MD5Sum'): sys.stderr.write("Warning: no MD5Sum for %s\n" % self.fullname()) return 1 data = open(self.archiveFilename, 'rb').read() checksum = md5.new(data).hexdigest() return checksum == self._dict['MD5Sum']
| 11,232
|
def _report_exception(self): """Internal function.""" import sys exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback root = self._root() root.report_callback_exception(exc, val, tb)
|
def _report_exception(self): """Internal function.""" import sys exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback root = self._root() root.report_callback_exception(exc, val, tb)
| 11,233
|
def configure(self, cnf=None, **kw): """Configure resources of a widget.
|
def configure(self, cnf=None, **kw): """Configure resources of a widget.
| 11,234
|
def configure(self, cnf=None, **kw): """Configure resources of a widget.
|
def configure(self, cnf=None, **kw): """Configure resources of a widget.
| 11,235
|
def configure(self, cnf=None, **kw): """Configure resources of a widget.
|
def configure(self, cnf=None, **kw): """Configure resources of a widget.
| 11,236
|
def itemconfigure(self, tagOrId, cnf=None, **kw): """Configure resources of an item TAGORID.
|
def itemconfigure(self, tagOrId, cnf=None, **kw): """Configure resources of an item TAGORID.
| 11,237
|
def itemconfigure(self, index, cnf=None, **kw): """Configure resources of an ITEM.
|
def itemconfigure(self, index, cnf=None, **kw): """Configure resources of an ITEM.
| 11,238
|
def entryconfigure(self, index, cnf=None, **kw): """Configure a menu item at INDEX.""" if cnf is None and not kw: cnf = {} for x in self.tk.split(self.tk.call( (self._w, 'entryconfigure', index))): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if type(cnf) == StringType and not kw: x = self.tk.split(self.tk.call( (self._w, 'entryconfigure', index, '-'+cnf))) return (x[0][1:],) + x[1:] self.tk.call((self._w, 'entryconfigure', index) + self._options(cnf, kw))
|
def entryconfigure(self, index, cnf=None, **kw): """Configure a menu item at INDEX.""" if cnf is None and not kw: cnf = {} for x in self.tk.split(self.tk.call( (self._w, 'entryconfigure', index))): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf if type(cnf) == StringType and not kw: x = self.tk.split(self.tk.call( (self._w, 'entryconfigure', index, '-'+cnf))) return (x[0][1:],) + x[1:] self.tk.call((self._w, 'entryconfigure', index) + self._options(cnf, kw))
| 11,239
|
def image_configure(self, index, cnf={}, **kw): """Configure an embedded image at INDEX.""" if not cnf and not kw: cnf = {} for x in self.tk.split( self.tk.call( self._w, "image", "configure", index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf apply(self.tk.call, (self._w, "image", "configure", index) + self._options(cnf, kw))
|
def image_configure(self, index, cnf=None, **kw): """Configure an embedded image at INDEX.""" if not cnf and not kw: cnf = {} for x in self.tk.split( self.tk.call( self._w, "image", "configure", index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf apply(self.tk.call, (self._w, "image", "configure", index) + self._options(cnf, kw))
| 11,240
|
def image_configure(self, index, cnf={}, **kw): """Configure an embedded image at INDEX.""" if not cnf and not kw: cnf = {} for x in self.tk.split( self.tk.call( self._w, "image", "configure", index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf apply(self.tk.call, (self._w, "image", "configure", index) + self._options(cnf, kw))
|
def image_configure(self, index, cnf={}, **kw): """Configure an embedded image at INDEX.""" if not cnf and not kw: cnf = {} for x in self.tk.split( self.tk.call( self._w, "image", "configure", index)): cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf apply(self.tk.call, (self._w, "image", "configure", index) + self._options(cnf, kw))
| 11,241
|
def tag_configure(self, tagName, cnf={}, **kw): """Configure a tag TAGNAME.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'tag', 'configure', tagName, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'tag', 'configure', tagName) + self._options(cnf, kw))
|
def tag_configure(self, tagName, cnf=None, **kw): """Configure a tag TAGNAME.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'tag', 'configure', tagName, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'tag', 'configure', tagName) + self._options(cnf, kw))
| 11,242
|
def tag_configure(self, tagName, cnf={}, **kw): """Configure a tag TAGNAME.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'tag', 'configure', tagName, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'tag', 'configure', tagName) + self._options(cnf, kw))
|
def tag_configure(self, tagName, cnf={}, **kw): """Configure a tag TAGNAME.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'tag', 'configure', tagName, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'tag', 'configure', tagName) + self._options(cnf, kw))
| 11,243
|
def window_configure(self, index, cnf={}, **kw): """Configure an embedded window at INDEX.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'window', 'configure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'window', 'configure', index) + self._options(cnf, kw))
|
def window_configure(self, index, cnf=None, **kw): """Configure an embedded window at INDEX.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'window', 'configure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'window', 'configure', index) + self._options(cnf, kw))
| 11,244
|
def window_configure(self, index, cnf={}, **kw): """Configure an embedded window at INDEX.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'window', 'configure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'window', 'configure', index) + self._options(cnf, kw))
|
def window_configure(self, index, cnf={}, **kw): """Configure an embedded window at INDEX.""" if type(cnf) == StringType: x = self.tk.split(self.tk.call( self._w, 'window', 'configure', index, '-'+cnf)) return (x[0][1:],) + x[1:] self.tk.call( (self._w, 'window', 'configure', index) + self._options(cnf, kw))
| 11,245
|
def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass
|
def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(host, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass
| 11,246
|
def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass
|
def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = '0' min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass
| 11,247
|
def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[5:8] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass
|
def main(): try: optlist, args = getopt.getopt(sys.argv[1:], 'ls') except getopt.error, msg: sys.stderr.write(msg + '\n') sys.exit(2) player = cd.open() prstatus(player) size = player.bestreadsize() if optlist: for opt, arg in optlist: if opt == '-l': prtrackinfo(player) elif opt == '-s': prstatus(player) return sys.stdout.write('waiting for socket... ') sys.stdout.flush() port = socket(AF_INET, SOCK_DGRAM) port.connect(HOST, PORT) print 'socket connected' parser = cd.createparser() parser.setcallback(0, audiocallback, port) parser.setcallback(1, pnumcallback, player) parser.setcallback(2, indexcallback, None) ## 3 = ptime: too many calls ## 4 = atime: too many calls parser.setcallback(5, catalogcallback, None) parser.setcallback(6, identcallback, None) parser.setcallback(7, controlcallback, None) if len(args) >= 2: if len(args) >= 3: [min, sec, frame] = args[:3] else: [min, sec] = args frame = 0 min, sec, frame = eval(min), eval(sec), eval(frame) print 'Seek to', triple(min, sec, frame) dummy = player.seek(min, sec, frame) elif len(args) == 1: track = eval(args[0]) print 'Seek to track', track dummy = player.seektrack(track) else: min, sec, frame = player.getstatus()[3] print 'Try to seek back to', triple(min, sec, frame) try: player.seek(min, sec, frame) except RuntimeError: print 'Seek failed' try: while 1: frames = player.readda(size) if frames == '': print 'END OF CD' break parser.parseframe(frames) except KeyboardInterrupt: print '[Interrupted]' pass
| 11,248
|
def prtrackinfo(player): info = [] while 1: try: info.append(player.gettrackinfo(len(info) + 1)) except RuntimeError: break for i in range(len(info)): start_min, start_sec, start_frame, \ total_min, total_sec, total_frame = info[i] print 'Track', zfill(i+1), \ triple(start_min, start_sec, start_frame), \ triple(total_min, total_sec, total_frame)
|
def prtrackinfo(player): info = [] while 1: try: info.append(player.gettrackinfo(len(info) + 1)) except RuntimeError: break for i in range(len(info)): start, total = info[i] print 'Track', zfill(i+1), triple(start), triple(total)
| 11,249
|
def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3)
|
def prstatus(player): state, track, curtime, abstime, totaltime, first, last, \ scsi_audio, cur_block, dummy = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3)
| 11,250
|
def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3)
|
def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(curtime) print 'Abs: ', triple(abstime) print 'Total: ', triple(totaltime) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3)
| 11,251
|
def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', (dum1, dum2, dum3)
|
def prstatus(player): state, track, min, sec, frame, abs_min, abs_sec, abs_frame, \ total_min, total_sec, total_frame, first, last, scsi_audio, \ cur_block, dum1, dum2, dum3 = player.getstatus() print 'Status:', if 0 <= state < len(statedict): print statedict[state] else: print state print 'Track: ', track print 'Time: ', triple(min, sec, frame) print 'Abs: ', triple(abs_min, abs_sec, abs_frame) print 'Total: ', triple(total_min, total_sec, total_frame) print 'First: ', first print 'Last: ', last print 'SCSI: ', scsi_audio print 'Block: ', cur_block print 'Future:', dummy
| 11,252
|
def triple(a, b, c): return zfill(a) + ':' + zfill(b) + ':' + zfill(c)
|
def triple((a, b, c)): return zfill(a) + ':' + zfill(b) + ':' + zfill(c)
| 11,253
|
def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: map = socket_map map[self._fileno] = self
|
def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: map = self._map map[self._fileno] = self
| 11,254
|
def del_channel(self, map=None): fd = self._fileno if map is None: map = socket_map if map.has_key(fd): #self.log_info('closing channel %d:%s' % (fd, self)) del map[fd]
|
def del_channel(self, map=None): fd = self._fileno if map is None: map = self._map if map.has_key(fd): #self.log_info('closing channel %d:%s' % (fd, self)) del map[fd]
| 11,255
|
def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_']
|
def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_']
| 11,256
|
def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_']
|
def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_']
| 11,257
|
def copy(self): """Return a separate copy of this hashing object.
|
def copy(self): """Return a separate copy of this hashing object.
| 11,258
|
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
|
def __init__(self, timer=None): self.timings = {} self.cur = None self.cmd = ""
| 11,259
|
def open(self, fullurl, data=None): fullurl = unwrap(fullurl) if self.tempcache and self.tempcache.has_key(fullurl): filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) type, url = splittype(fullurl) if not type: type = 'file' if self.proxies.has_key(type): proxy = self.proxies[type] type, proxy = splittype(proxy) host, selector = splithost(proxy) url = (host, fullurl) # Signal special case to open_*() name = 'open_' + type if '-' in name: # replace - with _ name = string.join(string.split(name, '-'), '_') if not hasattr(self, name): if data is None: return self.open_unknown(fullurl) else: return self.open_unknown(fullurl, data) try: if data is None: return getattr(self, name)(url) else: return getattr(self, name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2]
|
def open(self, fullurl, data=None): fullurl = unwrap(fullurl) if self.tempcache and self.tempcache.has_key(fullurl): filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) type, url = splittype(fullurl) if not type: type = 'file' if self.proxies.has_key(type): proxy = self.proxies[type] type, proxy = splittype(proxy) host, selector = splithost(proxy) url = (host, fullurl) # Signal special case to open_*() name = 'open_' + type if '-' in name: # replace - with _ name = string.join(string.split(name, '-'), '_') if not hasattr(self, name): if data is None: return self.open_unknown(fullurl) else: return self.open_unknown(fullurl, data) try: if data is None: return getattr(self, name)(url) else: return getattr(self, name)(url, data) except socket.error, msg: raise IOError, ('socket error', msg), sys.exc_info()[2]
| 11,260
|
def splithost(url): global _hostprog if _hostprog is None: import re _hostprog = re.compile('^//([^/]+)(.*)$') match = _hostprog.match(url) if match: return match.group(1, 2) return None, url
|
def splithost(url): global _hostprog if _hostprog is None: import re _hostprog = re.compile('^//([^/]+)(.*)$') match = _hostprog.match(url) if match: return match.group(1, 2) return None, url
| 11,261
|
def splituser(host): global _userprog if _userprog is None: import re _userprog = re.compile('^([^@]*)@(.*)$') match = _userprog.match(host) if match: return match.group(1, 2) return None, host
|
def splituser(host): global _userprog if _userprog is None: import re _userprog = re.compile('^([^@]*)@(.*)$') match = _userprog.match(host) if match: return match.group(1, 2) return None, host
| 11,262
|
def splitpasswd(user): global _passwdprog if _passwdprog is None: import re _passwdprog = re.compile('^([^:]*):(.*)$') match = _passwdprog.match(user) if match: return match.group(1, 2) return user, None
|
def splitpasswd(user): global _passwdprog if _passwdprog is None: import re _passwdprog = re.compile('^([^:]*):(.*)$') match = _passwdprog.match(user) if match: return match.group(1, 2) return user, None
| 11,263
|
def splitport(host): global _portprog if _portprog is None: import re _portprog = re.compile('^(.*):([0-9]+)$') match = _portprog.match(host) if match: return match.group(1, 2) return host, None
|
def splitport(host): global _portprog if _portprog is None: import re _portprog = re.compile('^(.*):([0-9]+)$') match = _portprog.match(host) if match: return match.group(1, 2) return host, None
| 11,264
|
def splitnport(host, defport=-1): global _nportprog if _nportprog is None: import re _nportprog = re.compile('^(.*):(.*)$') match = _nportprog.match(host) if match: host, port = match.group(1, 2) try: if not port: raise string.atoi_error, "no digits" nport = string.atoi(port) except string.atoi_error: nport = None return host, nport return host, defport
|
def splitnport(host, defport=-1): global _nportprog if _nportprog is None: import re _nportprog = re.compile('^(.*):(.*)$') match = _nportprog.match(host) if match: host, port = match.group(1, 2) try: if not port: raise string.atoi_error, "no digits" nport = string.atoi(port) except string.atoi_error: nport = None return host, nport return host, defport
| 11,265
|
def splitquery(url): global _queryprog if _queryprog is None: import re _queryprog = re.compile('^(.*)\?([^?]*)$') match = _queryprog.match(url) if match: return match.group(1, 2) return url, None
|
def splitquery(url): global _queryprog if _queryprog is None: import re _queryprog = re.compile('^(.*)\?([^?]*)$') match = _queryprog.match(url) if match: return match.group(1, 2) return url, None
| 11,266
|
def splittag(url): global _tagprog if _tagprog is None: import re _tagprog = re.compile('^(.*)#([^#]*)$') match = _tagprog.match(url) if match: return match.group(1, 2) return url, None
|
def splittag(url): global _tagprog if _tagprog is None: import re _tagprog = re.compile('^(.*)#([^#]*)$') match = _tagprog.match(url) if match: return match.group(1, 2) return url, None
| 11,267
|
def server_activate(self): # No need to call listen() for UDP. pass
|
def server_activate(self): # No need to call listen() for UDP. pass
| 11,268
|
def __init__ (self, verbose=0, dry_run=0):
|
def __init__ (self, verbose=0, dry_run=0):
| 11,269
|
def compile (self, sources, output_dir=None, macros=None, includes=None, extra_preargs=None, extra_postargs=None):
|
def compile (self, sources, output_dir=None, macros=None, includes=None, extra_preargs=None, extra_postargs=None):
| 11,270
|
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=None):
|
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=None):
| 11,271
|
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=None):
|
def link_shared_object (self, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, extra_preargs=None, extra_postargs=None):
| 11,272
|
def library_filename (self, libname): return "lib%s%s" % (libname, self._static_lib_ext )
|
def library_filename (self, libname): return "lib%s%s" % (libname, self._static_lib_ext )
| 11,273
|
def shared_library_filename (self, libname): return "lib%s%s" % (libname, self._shared_lib_ext )
|
def shared_library_filename (self, libname): return "lib%s%s" % (libname, self._shared_lib_ext )
| 11,274
|
def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ tarinfo = cls() tarinfo.name = nts(buf[0:100]) tarinfo.mode = int(buf[100:108], 8) tarinfo.uid = int(buf[108:116],8) tarinfo.gid = int(buf[116:124],8) tarinfo.size = long(buf[124:136], 8) tarinfo.mtime = long(buf[136:148], 8) tarinfo.chksum = int(buf[148:156], 8) tarinfo.type = buf[156:157] tarinfo.linkname = nts(buf[157:257]) tarinfo.uname = nts(buf[265:297]) tarinfo.gname = nts(buf[297:329]) try: tarinfo.devmajor = int(buf[329:337], 8) tarinfo.devminor = int(buf[337:345], 8) except ValueError: tarinfo.devmajor = tarinfo.devmajor = 0
|
def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ tarinfo = cls() tarinfo.name = nts(buf[0:100]) tarinfo.mode = int(buf[100:108], 8) tarinfo.uid = int(buf[108:116],8) tarinfo.gid = int(buf[116:124],8) tarinfo.size = long(buf[124:136], 8) tarinfo.mtime = long(buf[136:148], 8) tarinfo.chksum = int(buf[148:156], 8) tarinfo.type = buf[156:157] tarinfo.linkname = nts(buf[157:257]) tarinfo.uname = nts(buf[265:297]) tarinfo.gname = nts(buf[297:329]) try: tarinfo.devmajor = int(buf[329:337], 8) tarinfo.devminor = int(buf[337:345], 8) except ValueError: tarinfo.devmajor = tarinfo.devmajor = 0
| 11,275
|
def f(*a, **k): print a, k
|
def f(*a, **k): print a, sortdict(k)
| 11,276
|
def g(x, *y, **z): print x, y, z
|
def g(x, *y, **z): print x, y, sortdict(z)
| 11,277
|
def __getitem__(self, i): if i < 3: return i else: raise IndexError, i
|
def __getitem__(self, i): if i < 3: return i else: raise IndexError, i
| 11,278
|
decl = 'def %s(%s): print "ok %s", a, b, d, e, v, k' % ( name, string.join(arglist, ', '), name)
|
decl = 'def %s(%s): print "ok %s", a, b, d, e, v, k' % ( name, string.join(arglist, ', '), name)
| 11,279
|
def __init__(self, msg, filename=None, lineno=None): self.filename = file self.lineno = lineno self.msg = msg Exception.__init__(self, msg)
|
def __init__(self, msg, filename=None, lineno=None): self.filename = filename self.lineno = lineno self.msg = msg Exception.__init__(self, msg)
| 11,280
|
def visitDict(self, node): lineno = getattr(node, 'lineno', None) if lineno: self.emit('SET_LINENO', lineno) self.emit('BUILD_MAP', 0) for k, v in node.items: lineno2 = getattr(node, 'lineno', None) if lineno2 is not None and lineno != lineno2: self.emit('SET_LINENO', lineno2) lineno = lineno2 self.emit('DUP_TOP') self.visit(v) self.emit('ROT_TWO') self.visit(k) self.emit('STORE_SUBSCR')
|
def visitDict(self, node): lineno = getattr(node, 'lineno', None) if lineno: self.emit('SET_LINENO', lineno) self.emit('BUILD_MAP', 0) for k, v in node.items: lineno2 = getattr(node, 'lineno', None) if lineno2 is not None and lineno != lineno2: self.emit('SET_LINENO', lineno2) lineno = lineno2 self.emit('DUP_TOP') self.visit(v) self.emit('ROT_THREE') self.emit('STORE_SUBSCR')
| 11,281
|
def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe().f_back while 1: co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue return filename, f.f_lineno, co.co_name
|
def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe().f_back rv = "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue return filename, f.f_lineno, co.co_name
| 11,282
|
def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe().f_back while 1: co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue return filename, f.f_lineno, co.co_name
|
def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe().f_back while 1: co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue return filename, f.f_lineno, co.co_name
| 11,283
|
def inner(): return y
|
def inner(): return y
| 11,284
|
def main(): global DEBUG DEBUG=1 # Find the template # (there's no point in proceeding if we can't find it) template = findtemplate() if DEBUG: print 'Using template', template # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select Python source file:', 'TEXT') if not ok: return filename = srcfss.as_pathname() tp, tf = os.path.split(filename) if tf[-3:] == '.py': tf = tf[:-3] else: tf = tf + '.applet' dstfss, ok = macfs.StandardPutFile('Save application as:', tf) if not ok: return process(template, filename, dstfss.as_pathname()) else: # Loop over all files to be processed for filename in sys.argv[1:]: process(template, filename, '')
|
def main(): # Find the template # (there's no point in proceeding if we can't find it) template = findtemplate() if DEBUG: print 'Using template', template # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select Python source file:', 'TEXT') if not ok: return filename = srcfss.as_pathname() tp, tf = os.path.split(filename) if tf[-3:] == '.py': tf = tf[:-3] else: tf = tf + '.applet' dstfss, ok = macfs.StandardPutFile('Save application as:', tf) if not ok: return process(template, filename, dstfss.as_pathname()) else: # Loop over all files to be processed for filename in sys.argv[1:]: process(template, filename, '')
| 11,285
|
def subclasspropagation(): if verbose: print "Testing propagation of slot functions to subclasses..." class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass d = D() vereq(hash(d), id(d)) A.__hash__ = lambda self: 42 vereq(hash(d), 42) C.__hash__ = lambda self: 314 vereq(hash(d), 314) B.__hash__ = lambda self: 144 vereq(hash(d), 144) D.__hash__ = lambda self: 100 vereq(hash(d), 100) del D.__hash__ vereq(hash(d), 144) del B.__hash__ vereq(hash(d), 314) del C.__hash__ vereq(hash(d), 42) del A.__hash__ vereq(hash(d), id(d)) d.foo = 42 d.bar = 42 vereq(d.foo, 42) vereq(d.bar, 42) def __getattribute__(self, name): if name == "foo": return 24 return object.__getattribute__(self, name) A.__getattribute__ = __getattribute__ vereq(d.foo, 24) vereq(d.bar, 42) def __getattr__(self, name): if name in ("spam", "foo", "bar"): return "hello" raise AttributeError, name B.__getattr__ = __getattr__ vereq(d.spam, "hello") vereq(d.foo, 24) vereq(d.bar, 42) del A.__getattribute__ vereq(d.foo, 42) del d.foo vereq(d.foo, "hello") vereq(d.bar, 42) del B.__getattr__ try: d.foo except AttributeError: pass else: raise TestFailed, "d.foo should be undefined now" # Test a nasty bug in recurse_down_subclasses() import gc class A(object): pass class B(A): pass del B gc.collect() A.__setitem__ = lambda *a: None # crash
|
def subclasspropagation(): if verbose: print "Testing propagation of slot functions to subclasses..." class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass d = D() orig_hash = hash(d) A.__hash__ = lambda self: 42 vereq(hash(d), 42) C.__hash__ = lambda self: 314 vereq(hash(d), 314) B.__hash__ = lambda self: 144 vereq(hash(d), 144) D.__hash__ = lambda self: 100 vereq(hash(d), 100) del D.__hash__ vereq(hash(d), 144) del B.__hash__ vereq(hash(d), 314) del C.__hash__ vereq(hash(d), 42) del A.__hash__ orig_hash = hash(d) d.foo = 42 d.bar = 42 vereq(d.foo, 42) vereq(d.bar, 42) def __getattribute__(self, name): if name == "foo": return 24 return object.__getattribute__(self, name) A.__getattribute__ = __getattribute__ vereq(d.foo, 24) vereq(d.bar, 42) def __getattr__(self, name): if name in ("spam", "foo", "bar"): return "hello" raise AttributeError, name B.__getattr__ = __getattr__ vereq(d.spam, "hello") vereq(d.foo, 24) vereq(d.bar, 42) del A.__getattribute__ vereq(d.foo, 42) del d.foo vereq(d.foo, "hello") vereq(d.bar, 42) del B.__getattr__ try: d.foo except AttributeError: pass else: raise TestFailed, "d.foo should be undefined now" # Test a nasty bug in recurse_down_subclasses() import gc class A(object): pass class B(A): pass del B gc.collect() A.__setitem__ = lambda *a: None # crash
| 11,286
|
def subclasspropagation(): if verbose: print "Testing propagation of slot functions to subclasses..." class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass d = D() vereq(hash(d), id(d)) A.__hash__ = lambda self: 42 vereq(hash(d), 42) C.__hash__ = lambda self: 314 vereq(hash(d), 314) B.__hash__ = lambda self: 144 vereq(hash(d), 144) D.__hash__ = lambda self: 100 vereq(hash(d), 100) del D.__hash__ vereq(hash(d), 144) del B.__hash__ vereq(hash(d), 314) del C.__hash__ vereq(hash(d), 42) del A.__hash__ vereq(hash(d), id(d)) d.foo = 42 d.bar = 42 vereq(d.foo, 42) vereq(d.bar, 42) def __getattribute__(self, name): if name == "foo": return 24 return object.__getattribute__(self, name) A.__getattribute__ = __getattribute__ vereq(d.foo, 24) vereq(d.bar, 42) def __getattr__(self, name): if name in ("spam", "foo", "bar"): return "hello" raise AttributeError, name B.__getattr__ = __getattr__ vereq(d.spam, "hello") vereq(d.foo, 24) vereq(d.bar, 42) del A.__getattribute__ vereq(d.foo, 42) del d.foo vereq(d.foo, "hello") vereq(d.bar, 42) del B.__getattr__ try: d.foo except AttributeError: pass else: raise TestFailed, "d.foo should be undefined now" # Test a nasty bug in recurse_down_subclasses() import gc class A(object): pass class B(A): pass del B gc.collect() A.__setitem__ = lambda *a: None # crash
|
def subclasspropagation(): if verbose: print "Testing propagation of slot functions to subclasses..." class A(object): pass class B(A): pass class C(A): pass class D(B, C): pass d = D() vereq(hash(d), orig_hash) A.__hash__ = lambda self: 42 vereq(hash(d), 42) C.__hash__ = lambda self: 314 vereq(hash(d), 314) B.__hash__ = lambda self: 144 vereq(hash(d), 144) D.__hash__ = lambda self: 100 vereq(hash(d), 100) del D.__hash__ vereq(hash(d), 144) del B.__hash__ vereq(hash(d), 314) del C.__hash__ vereq(hash(d), 42) del A.__hash__ vereq(hash(d), orig_hash) d.foo = 42 d.bar = 42 vereq(d.foo, 42) vereq(d.bar, 42) def __getattribute__(self, name): if name == "foo": return 24 return object.__getattribute__(self, name) A.__getattribute__ = __getattribute__ vereq(d.foo, 24) vereq(d.bar, 42) def __getattr__(self, name): if name in ("spam", "foo", "bar"): return "hello" raise AttributeError, name B.__getattr__ = __getattr__ vereq(d.spam, "hello") vereq(d.foo, 24) vereq(d.bar, 42) del A.__getattribute__ vereq(d.foo, 42) del d.foo vereq(d.foo, "hello") vereq(d.bar, 42) del B.__getattr__ try: d.foo except AttributeError: pass else: raise TestFailed, "d.foo should be undefined now" # Test a nasty bug in recurse_down_subclasses() import gc class A(object): pass class B(A): pass del B gc.collect() A.__setitem__ = lambda *a: None # crash
| 11,287
|
def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
|
def urljoin(base, url, allow_framents = 1): if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_framents) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_framents) # XXX Unofficial hack: default netloc to bnetloc even if # schemes differ if scheme != bscheme and not netloc and \ scheme in uses_relative and bscheme in uses_relative and \ scheme in uses_netloc and bscheme in uses_netloc: netloc = bnetloc # Strip the port number i = find(netloc, '@') if i < 0: i = 0 i = find(netloc, ':', i) if i >= 0: netloc = netloc[:i] if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) i = rfind(bpath, '/') if i >= 0: path = bpath[:i] + '/' + path segments = splitfields(path, '/') if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, joinfields(segments, '/'), params, query, fragment))
| 11,288
|
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(), '%define release ' + self.release, '', 'Summary: ' + self.distribution.get_description(), ]
|
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.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
| 11,289
|
def dump_long(self, value): val = int(value) self.write("<value><int>%s</int></value>\n" % val)
|
def dump_long(self, value): val = int(value) self.write("<value><int>%s</int></value>\n" % val)
| 11,290
|
def __getaddr(self, keyword, arg): address = None keylen = len(keyword) if arg[:keylen].upper() == keyword: address = arg[keylen:].strip() if address[0] == '<' and address[-1] == '>' and address != '<>': # Addresses can be in the form <person@dom.com> but watch out # for null address, e.g. <> address = address[1:-1] return address
|
def __getaddr(self, keyword, arg): address = None keylen = len(keyword) if arg[:keylen].upper() == keyword: address = arg[keylen:].strip() if not address: pass elif address[0] == '<' and address[-1] == '>' and address != '<>': # Addresses can be in the form <person@dom.com> but watch out # for null address, e.g. <> address = address[1:-1] return address
| 11,291
|
def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) print cmd rc = os.system(cmd) if rc: import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc
|
def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) rc = os.system(cmd) if rc: import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc
| 11,292
|
def open_new(self, url): self.open(url)
|
def open_new(self, url): self.open(url)
| 11,293
|
def open_new(self, url): self.open(url)
|
def open_new(self, url): self.open(url)
| 11,294
|
def open_new(self, url): self.open(url)
|
def open_new(self, url): self.open(url)
| 11,295
|
def open_new(self, url): self.open(url)
|
def open_new(self, url): self.open(url)
| 11,296
|
def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
|
def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
| 11,297
|
def __str__(self): return str(self.test)
|
def __str__(self): return str(self.test)
| 11,298
|
def runsource(self, source): # Extend base class to stuff the source in the line cache filename = "<console#%d>" % self.gid self.gid = self.gid + 1 lines = string.split(source, "\n") linecache.cache[filename] = len(source)+1, 0, lines, filename self.more = 0 return InteractiveInterpreter.runsource(self, source, filename)
|
def runsource(self, source): # Extend base class to stuff the source in the line cache filename = "<console#%d>" % self.gid self.gid = self.gid + 1 lines = string.split(source, "\n") linecache.cache[filename] = len(source)+1, 0, lines, filename self.more = 0 return InteractiveInterpreter.runsource(self, source, filename)
| 11,299
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.