rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
labels = doc.getElementsByTagName("label") for label in labels: id = label.getAttribute("id") if not id: continue parent = label.parentNode if parent.tagName == "title": parent.parentNode.setAttribute("id", id) else: parent.setAttribute("id", id) parent.removeChild(label) | for node in doc.childNodes: if node.nodeType == xml.dom.core.ELEMENT: labels = node.getElementsByTagName("label") for label in labels: id = label.getAttribute("id") if not id: continue parent = label.parentNode if parent.tagName == "title": parent.parentNode.setAttribute("id", id) else: parent.setAttribute("id", id) parent.removeChild(label) | def handle_labels(doc): labels = doc.getElementsByTagName("label") for label in labels: id = label.getAttribute("id") if not id: continue parent = label.parentNode if parent.tagName == "title": parent.parentNode.setAttribute("id", id) else: parent.setAttribute("id", id) # now, remove <label id="..."/> from parent: parent.removeChild(label) |
if a.index(-2,-10) != 0: raise TestFailed, 'list index, negative start argument' | if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument' if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument' | def __getitem__(self, key): return str(key) + '!!!' |
raise TestFailed, 'list index, negative stop argument' | raise TestFailed, 'list index, very -stop argument' | def __getitem__(self, key): return str(key) + '!!!' |
self._file.write(struct.pack('<lsslhhllhhs', | self._file.write(struct.pack('<l4s4slhhllhh4s', | def _write_header(self, initlength): self._file.write('RIFF') if not self._nframes: self._nframes = initlength / (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth self._form_length_pos = self._file.tell() self._file.write(struct.pack('<lsslhhllhhs', 36 + self._datalength, 'WAVE', 'fmt ', 16, WAVE_FORMAT_PCM, self._nchannels, self._framerate, self._nchannels * self._framerate * self._sampwidth, self._nchannels * self._sampwidth, self._sampwidth * 8, 'data')) self._data_length_pos = self._file.tell() self._file.write(struct.pack('<l', self._datalength)) |
return swi.swi('OS_File', '5s;i', p)!=0 | try: return swi.swi('OS_File', '5s;i', p)!=0 except swi.error: return 0 | def exists(p): """ |
return swi.swi('OS_File', '5s;i', p) in [2, 3] | try: return swi.swi('OS_File', '5s;i', p) in [2, 3] except swi.error: return 0 | def isdir(p): """ |
return swi.swi('OS_File', '5s;i', p) in [1, 3] | try: return swi.swi('OS_File', '5s;i', p) in [1, 3] except swi.error: return 0 | def isfile(p): """ |
print mod.__name__, dir(mod) | def parseargs(): global DEBUGSTREAM try: opts, args = getopt.getopt( sys.argv[1:], 'nVhc:d', ['class=', 'nosetuid', 'version', 'help', 'debug']) except getopt.error, e: usage(1, e) options = Options() for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): print >> sys.stderr, __version__ sys.exit(0) elif opt in ('-n', '--nosetuid'): options.setuid = 0 elif opt in ('-c', '--class'): options.classname = arg elif opt in ('-d', '--debug'): DEBUGSTREAM = sys.stderr # parse the rest of the arguments if len(args) < 1: localspec = 'localhost:8025' remotespec = 'localhost:25' elif len(args) < 2: localspec = args[0] remotespec = 'localhost:25' elif len(args) < 3: localspec = args[0] remotespec = args[1] else: usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args)) # split into host/port pairs i = localspec.find(':') if i < 0: usage(1, 'Bad local spec: %s' % localspec) options.localhost = localspec[:i] try: options.localport = int(localspec[i+1:]) except ValueError: usage(1, 'Bad local port: %s' % localspec) i = remotespec.find(':') if i < 0: usage(1, 'Bad remote spec: %s' % remotespec) options.remotehost = remotespec[:i] try: options.remoteport = int(remotespec[i+1:]) except ValueError: usage(1, 'Bad remote port: %s' % remotespec) return options |
|
print "File name %s contains a suspicious null byte!" % filename | def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive |
|
elif platform == 'cygwin': x11_inc = find_file('X11/Xlib.h', [], inc_dirs) if x11_inc is None: return | def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module. |
|
if __name__ == "__main__": import __main__ sys.modules['warnings'] = __main__ _test() else: _processoptions(sys.warnoptions) simplefilter("ignore", category=OverflowWarning, append=1) simplefilter("ignore", category=PendingDeprecationWarning, append=1) | _processoptions(sys.warnoptions) simplefilter("ignore", category=OverflowWarning, append=1) simplefilter("ignore", category=PendingDeprecationWarning, append=1) | def _getcategory(category): import re if not category: return Warning if re.match("^[a-zA-Z0-9_]+$", category): try: cat = eval(category) except NameError: raise _OptionError("unknown warning category: %r" % (category,)) else: i = category.rfind(".") module = category[:i] klass = category[i+1:] try: m = __import__(module, None, None, [klass]) except ImportError: raise _OptionError("invalid module name: %r" % (module,)) try: cat = getattr(m, klass) except AttributeError: raise _OptionError("unknown warning category: %r" % (category,)) if (not isinstance(cat, types.ClassType) or not issubclass(cat, Warning)): raise _OptionError("invalid warning category: %r" % (category,)) return cat |
if 0: def test_timeout(): test_support.requires('network') | def test_timeout(): test_support.requires('network') | def test_basic(): test_support.requires('network') import urllib socket.RAND_status() try: socket.RAND_egd(1) except TypeError: pass else: print "didn't raise TypeError" socket.RAND_add("this is a random string", 75.0) f = urllib.urlopen('https://sf.net') buf = f.read() f.close() |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(30.0) s.connect(("gmail.org", 995)) ss = socket.ssl(s) ss.read(1) ss.read(1) s.close() else: def test_timeout(): pass | if test_support.verbose: print "test_timeout ..." ADDR = "gmail.org", 995 s = socket.socket() s.settimeout(30.0) try: s.connect(ADDR) except socket.timeout: print >> sys.stderr, """\ WARNING: an attempt to connect to %r timed out, in test_timeout. That may be legitimate, but is not the outcome we hoped for. If this message is seen often, test_timeout should be changed to use a more reliable address.""" % (ADDR,) return ss = socket.ssl(s) ss.read(1) ss.read(1) s.close() | def test_timeout(): test_support.requires('network') |
containing the table) showing a side by side, line by line comparision | containing the table) showing a side by side, line by line comparison | def _line_pair_iterator(): """Yields from/to lines of text with a change indication. |
cantset(f, "func_name", "f") cantset(f, "__name__", "f") | f.__name__ = "g" verify(f.__name__ == "g") verify(f.func_name == "g") f.func_name = "h" verify(f.__name__ == "h") verify(f.func_name == "h") cantset(f, "func_globals", 1) cantset(f, "__name__", 1) | def f(): pass |
self._parsing = 0 | def reset(self): if self._namespaces: self._parser = expat.ParserCreate(None, " ") self._parser.StartElementHandler = self.start_element_ns self._parser.EndElementHandler = self.end_element_ns else: self._parser = expat.ParserCreate() self._parser.StartElementHandler = self.start_element self._parser.EndElementHandler = self.end_element |
|
verify(log == [('getattr', '__init__'), ('getattr', '__setattr__'), | verify(log == [('getattr', '__setattr__'), | def __delattr__(self, name): log.append(("delattr", name)) MT.__delattr__(self, name) |
e.delta = getint(D) | try: e.delta = getint(D) except ValueError: e.delta = 0 | def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = int nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() e.serial = getint(nsign) e.num = getint(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint(h) e.keycode = getint(k) # For Visibility events, event state is a string and # not an integer: try: e.state = getint(s) except ValueError: e.state = s e.time = getint(t) e.width = getint(w) e.x = getint(x) e.y = getint(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint(N) e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint(X) e.y_root = getint(Y) e.delta = getint(D) return (e,) |
print socket.getservbyname('telnet', 'tcp') try: socket.getservbyname('telnet', 'udp') except socket.error: pass | if hasattr(socket, 'getservbyname'): print socket.getservbyname('telnet', 'tcp') try: socket.getservbyname('telnet', 'udp') except socket.error: pass | def missing_ok(str): try: getattr(socket, str) except AttributeError: pass |
libraries=[dblib])) | libraries=dblibs)) | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
if platform not in ['cygwin', 'mac']: if (self.compiler.find_library_file(lib_dirs, 'ndbm')): | if platform not in ['cygwin']: if (self.compiler.find_library_file(lib_dirs, 'ndbm') and find_file("ndbm.h", inc_dirs, []) is not None): | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
elif self.compiler.find_library_file(lib_dirs, 'gdbm'): | elif (platform in ['darwin'] and find_file("ndbm.h", inc_dirs, []) is not None): | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
library_dirs=dblib_dir, | library_dirs=[dblib_dir], | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
else: exts.append( Extension('dbm', ['dbmmodule.c']) ) | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
|
frameworkdir = sysconfig.get_config_var('PYTHONFRAMEWORKDIR') exts.append( Extension('gestalt', ['gestaltmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('MacOS', ['macosmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('icglue', ['icgluemodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('macfs', ['macfsmodule.c', '../Python/getapplbycreator.c'], extra_link_args=['-framework', 'Carbon']) ) | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
|
exts.append( Extension('_Res', ['res/_Resmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Snd', ['snd/_Sndmodule.c'], extra_link_args=['-framework', 'Carbon']) ) if frameworkdir: | framework = sysconfig.get_config_var('PYTHONFRAMEWORK') if framework: exts.append( Extension('gestalt', ['gestaltmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('MacOS', ['macosmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('icglue', ['icgluemodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('macfs', ['macfsmodule.c', '../Python/getapplbycreator.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Res', ['res/_Resmodule.c'], extra_link_args=['-framework', 'Carbon']) ) exts.append( Extension('_Snd', ['snd/_Sndmodule.c'], extra_link_args=['-framework', 'Carbon']) ) | def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') |
_keep_alive(args, memo) | def _deepcopy_inst(x, memo): if hasattr(x, '__deepcopy__'): return x.__deepcopy__(memo) if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() _keep_alive(args, memo) args = deepcopy(args, memo) y = apply(x.__class__, args) else: y = _EmptyClass() y.__class__ = x.__class__ memo[id(x)] = y if hasattr(x, '__getstate__'): state = x.__getstate__() _keep_alive(state, memo) else: state = x.__dict__ state = deepcopy(state, memo) if hasattr(y, '__setstate__'): y.__setstate__(state) else: y.__dict__.update(state) return y |
|
_keep_alive(state, memo) | def _deepcopy_inst(x, memo): if hasattr(x, '__deepcopy__'): return x.__deepcopy__(memo) if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() _keep_alive(args, memo) args = deepcopy(args, memo) y = apply(x.__class__, args) else: y = _EmptyClass() y.__class__ = x.__class__ memo[id(x)] = y if hasattr(x, '__getstate__'): state = x.__getstate__() _keep_alive(state, memo) else: state = x.__dict__ state = deepcopy(state, memo) if hasattr(y, '__setstate__'): y.__setstate__(state) else: y.__dict__.update(state) return y |
|
access *: private | if 0: access *: private | def close(self): self._ensure_header_written() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader() self._file.flush() self._file = None |
def copytree(src, dst, symlinks=0): | def copytree(src, dst, symlinks=False): | def copytree(src, dst, symlinks=0): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. Error are reported to standard output. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) os.mkdir(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, why)) if errors: raise Error, errors |
Error are reported to standard output. | If exception(s) occur, an Error is raised with a list of reasons. | def copytree(src, dst, symlinks=0): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. Error are reported to standard output. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) os.mkdir(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, why)) if errors: raise Error, errors |
if issubclass(t, TypeType): | try: issc = issubclass(t, TypeType) except TypeError: issc = 0 if issc: | def save(self, object, pers_save = 0): memo = self.memo |
self.pack_uint(int(x>>32 & 0xffffffff)) self.pack_uint(int(x & 0xffffffff)) | self.pack_uint(x>>32 & 0xffffffffL) self.pack_uint(x & 0xffffffffL) | def pack_uhyper(self, x): |
elif path == '' or path[-1:] in '/\\': | elif path == '' or path[-1:] in '/\\:': | def join(a, *p): """Join two or more pathname components, inserting "\\" as needed""" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\': path = path + b else: path = path + os.sep + b return path |
verify(self.cbcalled == 1, "callback did not properly set 'cbcalled'") verify(ref() is None, "ref2 should be dead after deleting object reference") | self.assert_(self.cbcalled == 1, "callback did not properly set 'cbcalled'") self.assert_(ref() is None, "ref2 should be dead after deleting object reference") | def check_basic_callback(self, factory): self.cbcalled = 0 o = factory() ref = weakref.ref(o, self.callback) del o verify(self.cbcalled == 1, "callback did not properly set 'cbcalled'") verify(ref() is None, "ref2 should be dead after deleting object reference") |
self.assertEqual(grp.getgrgid(e.gr_gid), e) | entriesbygid.setdefault(e.gr_gid, []).append(e) for e in entries: self.assert_(grp.getgrgid(e.gr_gid) in entriesbygid[e.gr_gid]) | def test_values(self): entries = grp.getgrall() |
if type(url) in types.StringTypes: | if type(url) is types.StringType: | def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if type(url) in types.StringTypes: host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest user_passwd = None if urltype.lower() != 'https': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) #print "proxy via https:", host, selector if not host: raise IOError, ('https error', 'no host given') if user_passwd: import base64 auth = base64.encodestring(user_passwd).strip() else: auth = None h = httplib.HTTPS(host, 0, key_file=self.key_file, cert_file=self.cert_file) if data is not None: h.putrequest('POST', selector) h.putheader('Content-type', 'application/x-www-form-urlencoded') h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', selector) if auth: h.putheader('Authorization: Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: apply(h.putheader, args) h.endheaders() if data is not None: h.send(data + '\r\n') errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, url) else: if data is None: return self.http_error(url, fp, errcode, errmsg, headers) else: return self.http_error(url, fp, errcode, errmsg, headers, data) |
while cursel > 0 and selstart[:i] <= self.completions[cursel-1]: | previous_completion = self.completions[cursel - 1] while cursel > 0 and selstart[:i] <= previous_completion: | def _selection_changed(self): """Should be called when the selection of the Listbox has changed. Updates the Listbox display and calls _change_start.""" cursel = int(self.listbox.curselection()[0]) |
print repr(str(err)) | # def __getstate__(self): |
|
return pydoc.getdoc(method) | import pydoc return pydoc.getdoc(method) | def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together" |
sys.stdout.write(reponse) | sys.stdout.write(response) | def handle_get(self): """Handle a single HTTP GET request. |
socket.SOL_SOCKET, socket.SO_REUSEADDR, | socket.SOL_SOCKET, reuse_constant, | def set_reuse_addr(self): # try to re-use a server port if possible try: self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 ) except socket.error: pass |
socket.SO_REUSEADDR) | 1 | reuse_constant) | 1 | def set_reuse_addr(self): # try to re-use a server port if possible try: self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 ) except socket.error: pass |
if os.path.exists (self.build_lib): remove_tree (self.build_lib, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clean it" % self.build_lib) if os.path.exists (self.bdist_base): remove_tree (self.bdist_base, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clean it" % self.bdist_base) | for directory in (self.build_lib, self.bdist_base, self.build_scripts): if os.path.exists (directory): remove_tree (directory, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clean it" % directory) | def run(self): # remove the build/temp.<plat> directory (unless it's already # gone) if os.path.exists (self.build_temp): remove_tree (self.build_temp, self.verbose, self.dry_run) else: self.warn ("'%s' does not exist -- can't clean it" % self.build_temp) |
if netloc: | if netloc or (scheme in uses_netloc and url[:2] == '//'): | def urlunparse((scheme, netloc, url, params, query, fragment)): if netloc: if url[:1] != '/': url = '/' + url url = '//' + netloc + url if scheme: url = scheme + ':' + url if params: url = url + ';' + params if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url |
url = '//' + netloc + url | url = '//' + (netloc or '') + url | def urlunparse((scheme, netloc, url, params, query, fragment)): if netloc: if url[:1] != '/': url = '/' + url url = '//' + netloc + url if scheme: url = scheme + ':' + url if params: url = url + ';' + params if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url |
sys.settrace(gself.lobaltrace) | sys.settrace(self.globaltrace) | def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(gself.lobaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None) |
exec cmd in dict, dict | exec cmd in globals, locals | def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(gself.lobaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None) |
ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print " --- modulename: %s, funcname: %s" % (modulename, funcname,) return self.localtrace | if modulename is not None: ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print " --- modulename: %s, funcname: %s" % (modulename, funcname,) return self.localtrace | def globaltrace_lt(self, frame, why, arg): """ Handles `call' events (why == 'call') and if the code block being entered is to be ignored then it returns `None', else it returns `self.localtrace'. """ if why == 'call': (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0) # if DEBUG_MODE and not filename: # print "%s.globaltrace(frame: %s, why: %s, arg: %s): filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) if filename: modulename = inspect.getmodulename(filename) ignore_it = self.ignore.names(filename, modulename) # if DEBUG_MODE and not self.blabbed.has_key((filename, modulename,)): # self.blabbed[(filename, modulename,)] = None # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s\n" % (self, frame, why, arg, filename, modulename, ignore_it,) if not ignore_it: if self.trace: print " --- modulename: %s, funcname: %s" % (modulename, funcname,) # if DEBUG_MODE: # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s -- about to localtrace\n" % (self, frame, why, arg, filename, modulename, ignore_it,) return self.localtrace else: # XXX why no filename? return None |
try: print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: pass | if context is not None: try: print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: pass else: print "%s(???): ???" % bname | def localtrace_trace(self, frame, why, arg): if why == 'line': # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14 # record the file name and line number of every trace # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame) # if DEBUG_MODE: # print "%s.localtrace_trace(frame: %s, why: %s, arg: %s); filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) # XXX not convinced that this memoizing is a performance win -- I don't know enough about Python guts to tell. --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: # Using setdefault faster than two separate lines? --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) try: print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well. pass return self.localtrace |
if host[0] == '[' and host[-1] == ']': | if host and host[0] == '[' and host[-1] == ']': | def _set_hostport(self, host, port): if port is None: i = host.rfind(':') j = host.rfind(']') # ipv6 addresses have [...] if i > j: try: port = int(host[i+1:]) except ValueError: raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) host = host[:i] else: port = self.default_port if host[0] == '[' and host[-1] == ']': host = host[1:-1] self.host = host self.port = port |
"<function <lambda> at 0x")) | "<function <lambda")) | def test_lambda(self): self.failUnless(repr(lambda x: x).startswith( "<function <lambda> at 0x")) # XXX anonymous functions? see func_repr |
except string.atoi_error: pass | except string.atoi_error: raise socket.error, "nonnumeric port" | def connect(self, host, port = 0): if not port: i = string.find(host, ':') if i >= 0: host, port = host[:i], host[i+1:] try: port = string.atoi(port) except string.atoi_error: pass if not port: port = HTTP_PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.debuglevel > 0: print 'connect:', (host, port) self.sock.connect(host, port) |
gotone, evt = Evt.WaitNextEvent(-1, 0) | gotone, evt = Evt.WaitNextEvent(0xffff, 0) | def main(): print 'hello world' # XXXX # skip the toolbox initializations, already done # XXXX Should use gestalt here to check for quicktime version Qt.EnterMovies() # Get the movie file fss, ok = macfs.StandardGetFile(QuickTime.MovieFileType) if not ok: sys.exit(0) # Open the window bounds = (175, 75, 175+160, 75+120) theWindow = Win.NewCWindow(bounds, fss.as_tuple()[2], 0, 0, -1, 1, 0) # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil) Qd.SetPort(theWindow) # Get the movie theMovie = loadMovie(fss) # Relocate to (0, 0) bounds = theMovie.GetMovieBox() bounds = 0, 0, bounds[2]-bounds[0], bounds[3]-bounds[1] theMovie.SetMovieBox(bounds) # Create a controller theController = theMovie.NewMovieController(bounds, QuickTime.mcTopLeftMovie) # Get movie size and update window parameters rv, bounds = theController.MCGetControllerBoundsRect() theWindow.SizeWindow(bounds[2], bounds[3], 0) # XXXX or [3] [2]? Qt.AlignWindow(theWindow, 0) theWindow.ShowWindow() # XXXX MCDoAction(theController, mcActionSetGrowBoxBounds, &maxBounds) theController.MCDoAction(QuickTime.mcActionSetKeysEnabled, '1') # XXXX MCSetActionFilterWithRefCon(theController, movieControllerEventFilter, (long)theWindow) done = 0 while not done: gotone, evt = Evt.WaitNextEvent(-1, 0) (what, message, when, where, modifiers) = evt |
except (DistutilsExecError, DistutilsFileError, DistutilsOptionError, | except (DistutilsError, | def setup (**attrs): """The gateway to the Distutils: do everything your setup script needs to do, in a highly flexible and user-driven way. Briefly: create a Distribution instance; find and parse config files; parse the command line; run each Distutils command found there, customized by the options supplied to 'setup()' (as keyword arguments), in config files, and on the command line. The Distribution instance might be an instance of a class supplied via the 'distclass' keyword argument to 'setup'; if no such class is supplied, then the Distribution class (in dist.py) is instantiated. All other arguments to 'setup' (except for 'cmdclass') are used to set attributes of the Distribution instance. The 'cmdclass' argument, if supplied, is a dictionary mapping command names to command classes. Each command encountered on the command line will be turned into a command class, which is in turn instantiated; any class found in 'cmdclass' is used in place of the default, which is (for command 'foo_bar') class 'foo_bar' in module 'distutils.command.foo_bar'. The command class must provide a 'user_options' attribute which is a list of option specifiers for 'distutils.fancy_getopt'. Any command-line options between the current and the next command are used to set attributes of the current command object. When the entire command-line has been successfully parsed, calls the 'run()' method on each command object in turn. This method will be driven entirely by the Distribution object (which each command object has a reference to, thanks to its constructor), and the command-specific options that became attributes of each command object. """ global _setup_stop_after, _setup_distribution # Determine the distribution class -- either caller-supplied or # our Distribution (see below). klass = attrs.get('distclass') if klass: del attrs['distclass'] else: klass = Distribution if not attrs.has_key('script_name'): attrs['script_name'] = os.path.basename(sys.argv[0]) if not attrs.has_key('script_args'): attrs['script_args'] = sys.argv[1:] # Create the Distribution instance, using the remaining arguments # (ie. everything except distclass) to initialize it try: _setup_distribution = dist = klass(attrs) except DistutilsSetupError, msg: if attrs.has_key('name'): raise SystemExit, "error in %s setup command: %s" % \ (attrs['name'], msg) else: raise SystemExit, "error in setup command: %s" % msg if _setup_stop_after == "init": return dist # Find and parse the config file(s): they will override options from # the setup script, but be overridden by the command line. dist.parse_config_files() if DEBUG: print "options (after parsing config files):" dist.dump_option_dicts() if _setup_stop_after == "config": return dist # Parse the command line; any command-line errors are the end user's # fault, so turn them into SystemExit to suppress tracebacks. try: ok = dist.parse_command_line() except DistutilsArgError, msg: raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: print "options (after parsing command line):" dist.dump_option_dicts() if _setup_stop_after == "commandline": return dist # And finally, run all the commands found on the command line. if ok: try: dist.run_commands() except KeyboardInterrupt: raise SystemExit, "interrupted" except (IOError, os.error), exc: error = grok_environment_error(exc) if DEBUG: sys.stderr.write(error + "\n") raise else: raise SystemExit, error except (DistutilsExecError, DistutilsFileError, DistutilsOptionError, CCompilerError), msg: if DEBUG: raise else: raise SystemExit, "error: " + str(msg) return dist |
except AttrinuteError: | except AttributeError: | def do_mouseDown(self, event): (what, message, when, where, modifiers) = event partcode, window = FindWindow(where) if partname.has_key(partcode): name = "do_" + partname[partcode] else: name = "do_%d" % partcode try: handler = getattr(self, name) except AttrinuteError: handler = self.do_unknownpartcode handler(partcode, window, event) |
print "Should close window:", window | if DEBUG: print "Should close window:", window | def do_close(self, window): print "Should close window:", window |
print "SystemClick", event, window | MacOS.HandleEvent(event) | def do_inSysWindow(self, partcode, window, event): print "SystemClick", event, window # SystemClick(event, window) # XXX useless, window is None |
print "inDesk" | def do_inDesk(self, partcode, window, event): print "inDesk" # XXX what to do with it? |
|
print "FindControl(%s, %s) -> (%s, %s)" % \ | if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \ | def do_inContent(self, partcode, window, event): (what, message, when, where, modifiers) = event local = GlobalToLocal(where) ctltype, control = FindControl(local, window) if ctltype and control: pcode = control.TrackControl(local) if pcode: self.do_controlhit(window, control, pcode, event) else: print "FindControl(%s, %s) -> (%s, %s)" % \ (local, window, ctltype, control) |
print "control hit in", window, "on", control, "; pcode =", pcode | if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode | def do_controlhit(self, window, control, pcode, event): print "control hit in", window, "on", control, "; pcode =", pcode |
print "Mouse down at global:", where print "\tUnknown part code:", partcode | if DEBUG: print "Mouse down at global:", where if DEBUG: print "\tUnknown part code:", partcode MacOS.HandleEvent(event) | def do_unknownpartcode(self, partcode, window, event): (what, message, when, where, modifiers) = event print "Mouse down at global:", where print "\tUnknown part code:", partcode |
print 'Command-W without front window' | if DEBUG: print 'Command-W without front window' | def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = FrontWindow() if w: self.do_close(w) else: print 'Command-W without front window' else: print "Command-" +`c` else: self.do_char(c, event) |
print "Command-" +`c` | if DEBUG: print "Command-" +`c` | def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = FrontWindow() if w: self.do_close(w) else: print 'Command-W without front window' else: print "Command-" +`c` else: self.do_char(c, event) |
print "Character", `c` | if DEBUG: print "Character", `c` | def do_char(self, c, event): print "Character", `c` |
print "do_update", self.printevent(event) | if DEBUG: print "do_update", self.printevent(event) | def do_updateEvt(self, event): print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: print "no window for do_updateEvt" |
print "no window for do_updateEvt" | MacOS.HandleEvent(event) | def do_updateEvt(self, event): print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: print "no window for do_updateEvt" |
print "raw update for", window | if DEBUG: print "raw update for", window | def do_rawupdate(self, window, event): print "raw update for", window window.BeginUpdate() self.do_update(window, event) DrawControls(window) window.DrawGrowIcon() window.EndUpdate() |
print "High Level Event:", self.printevent(event) | if DEBUG: print "High Level Event:", self.printevent(event) | def do_kHighLevelEvent(self, event): (what, message, when, where, modifiers) = event print "High Level Event:", self.printevent(event) try: AEProcessAppleEvent(event) except: print "AEProcessAppleEvent error:" traceback.print_exc() |
print "MenuBar.dispatch(%d, %d, %s, %s)" % \ | if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ | def dispatch(self, id, item, window, event): if self.menus.has_key(id): self.menus[id].dispatch(id, item, window, event) else: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ (id, item, window, event) |
src_extensions = _c_extensions + _cpp_extensions | src_extensions = (_c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions) res_extension = '.res' | def set_path_env_var (name, version_number): """Set environment variable 'name' to an MSVC path type value obtained from 'get_msvc_paths()'. This is equivalent to a SET command prior to execution of spawned commands.""" p = get_msvc_paths (name, version_number) if p: os.environ[name] = string.join (p,';') |
self.mkpath (os.path.dirname (obj)) | def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None): |
|
status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) | if self.addr == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s %s at %x>' % (self.__class__.__name__, ' '.join (status), id (self)) | def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) except: try: ar = repr(self.addr) except: ar = 'no self.addr!' |
try: ar = repr(self.addr) except: ar = 'no self.addr!' return '<__repr__ (self) failed for object at %x (addr=%s)>' % (id(self),ar) | pass try: ar = repr (self.addr) except AttributeError: ar = 'no self.addr!' return '<__repr__() failed for %s instance at %x (addr=%s)>' % \ (self.__class__.__name__, id (self), ar) | def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) except: try: ar = repr(self.addr) except: ar = 'no self.addr!' |
return os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3], "config", "config.h") | return os.path.join(sys.exec_prefix, "include", "python" + sys.version[:3], "config.h") | def get_config_h_filename(): """Return full pathname of installed config.h file.""" return os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3], "config", "config.h") |
applemenu.AppendMenu("All about cgitest...;(-") | applemenu.AppendMenu("About %s...;(-" % self.__class__.__name__) | def __init__(self): self.quitting = 0 # Initialize menu self.appleid = 1 self.quitid = 2 Menu.ClearMenuBar() self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") applemenu.AppendMenu("All about cgitest...;(-") applemenu.AppendResMenu('DRVR') applemenu.InsertMenu(0) self.quitmenu = Menu.NewMenu(self.quitid, "File") self.quitmenu.AppendMenu("Quit") self.quitmenu.InsertMenu(0) Menu.DrawMenuBar() |
if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" | if modifiers & cmdKey: if c == '.': raise KeyboardInterrupt, "Command-period" if c == 'q': self.quitting = 1 | def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event) |
EasyDialogs.Message("cgitest - First cgi test") return | EasyDialogs.Message(self.getabouttext()) | def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event) |
name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" | name = self.applemenu.GetMenuItemText(item) Menu.OpenDeskAcc(name) elif id == self.quitid and item == 1: | def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event) |
MacOS.HandleEvent(event) | Menu.HiliteMenu(0) else: MacOS.HandleEvent(event) def getabouttext(self): return self.__class__.__name__ | def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event) |
self._version = _read_long(chunk) | self._version = _read_ulong(chunk) | def initfp(self, file): self._version = 0 self._decomp = None self._convert = None self._markers = [] self._soundpos = 0 self._file = Chunk(file) if self._file.getname() != 'FORM': raise Error, 'file does not start with FORM id' formdata = self._file.read(4) if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == 'FVER': self._version = _read_long(chunk) elif chunkname == 'MARK': self._readmark(chunk) elif chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error, 'COMM chunk and/or SSND chunk missing' if self._aifc and self._decomp: import cl params = [cl.ORIGINAL_FORMAT, 0, cl.BITS_PER_COMPONENT, self._sampwidth * 8, cl.FRAME_RATE, self._framerate] if self._nchannels == 1: params[1] = cl.MONO elif self._nchannels == 2: params[1] = cl.STEREO_INTERLEAVED else: raise Error, 'cannot compress more than 2 channels' self._decomp.SetParams(params) |
self.message(" possible to distinguish between from \"package import submodule\" ", 1) | self.message(" possible to distinguish between \"from package " "import submodule\" ", 1) | def reportMissing(self): missing = [name for name in self.missingModules if name not in MAYMISS_MODULES] if self.maybeMissingModules: maybe = self.maybeMissingModules else: maybe = [name for name in missing if "." in name] missing = [name for name in missing if "." not in name] missing.sort() maybe.sort() if maybe: self.message("Warning: couldn't find the following submodules:", 1) self.message(" (Note that these could be false alarms -- " "it's not always", 1) self.message(" possible to distinguish between from \"package import submodule\" ", 1) self.message(" and \"from package import name\")", 1) for name in maybe: self.message(" ? " + name, 1) if missing: self.message("Warning: couldn't find the following modules:", 1) for name in missing: self.message(" ? " + name, 1) |
@bigmemtest(minsize=_2G // 2 + 2, memuse=8) | @bigmemtest(minsize=_2G // 2 + 2, memuse=24) | def basic_test_inplace_concat(self, size): l = [sys.stdout] * size l += l self.assertEquals(len(l), size * 2) self.failUnless(l[0] is l[-1]) self.failUnless(l[size - 1] is l[size + 1]) |
@bigmemtest(minsize=_2G + 2, memuse=8) | @bigmemtest(minsize=_2G + 2, memuse=24) | def test_inplace_concat_small(self, size): return self.basic_test_inplace_concat(size) |
self.__frame = Frame(parent) self.__frame.pack(expand=YES, fill=BOTH) | self.__frame = Frame(parent, relief=GROOVE, borderwidth=2) self.__frame.pack() | def __init__(self, switchboard, parent=None): self.__sb = switchboard self.__frame = Frame(parent) self.__frame.pack(expand=YES, fill=BOTH) # create the chip that will display the currently selected color # exactly self.__sframe = Frame(self.__frame) self.__sframe.grid(row=0, column=0) self.__selected = ChipWidget(self.__sframe, text='Selected') # create the chip that will display the nearest real X11 color # database color name self.__nframe = Frame(self.__frame) self.__nframe.grid(row=0, column=1) self.__nearest = ChipWidget(self.__nframe, text='Nearest', presscmd = self.__buttonpress, releasecmd = self.__buttonrelease) |
attempdirs = ['/var/tmp', '/usr/tmp', '/tmp', pwd] | attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', pwd] | def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/var/tmp', '/usr/tmp', '/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 1) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) if os.name == 'posix': try: fd = os.open(filename, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700) except OSError: pass else: fp = os.fdopen(fd, 'w') fp.write('blat') fp.close() os.unlink(filename) del fp, fd tempdir = dir break else: fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir |
if not iscode(co): raise TypeError, 'arg is not a code object' | if not iscode(co): raise TypeError('arg is not a code object') | def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError, 'arg is not a code object' code = co.co_code nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) step = 0 # The following acrobatics are for anonymous (tuple) arguments. for i in range(nargs): if args[i][:1] in ['', '.']: stack, remain, count = [], [], [] while step < len(code): op = ord(code[step]) step = step + 1 if op >= dis.HAVE_ARGUMENT: opname = dis.opname[op] value = ord(code[step]) + ord(code[step+1])*256 step = step + 2 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: remain.append(value) count.append(value) elif opname == 'STORE_FAST': stack.append(names[value]) remain[-1] = remain[-1] - 1 while remain[-1] == 0: remain.pop() size = count.pop() stack[-size:] = [stack[-size:]] if not remain: break remain[-1] = remain[-1] - 1 if not remain: break args[i] = stack[0] varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, varkw |
'defaults' is an n-tuple of the default values of the last n arguments.""" if not isfunction(func): raise TypeError, 'arg is not a Python function' | 'defaults' is an n-tuple of the default values of the last n arguments. """ if ismethod(func): func = func.im_func if not isfunction(func): raise TypeError('arg is not a Python function') | def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments.""" if not isfunction(func): raise TypeError, 'arg is not a Python function' args, varargs, varkw = getargs(func.func_code) return args, varargs, varkw, func.func_defaults |
'raw_unicode_escape', 'unicode_escape', 'unicode_internal'): | 'unicode_escape', 'unicode_internal'): | def __str__(self): return self.x |
self.headers.update(headers) | for key, value in headers.iteritems(): self.add_header(key, value) | def __init__(self, url, data=None, headers={}): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {} self.headers.update(headers) |
self.headers[key] = val | self.headers[key.capitalize()] = val | def add_header(self, key, val): # useful for something like authentication self.headers[key] = val |
for type, url in proxies.items(): | for type, url in proxies.iteritems(): | def __init__(self, proxies=None): if proxies is None: proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies for type, url in proxies.items(): setattr(self, '%s_open' % type, lambda r, proxy=url, type=type, meth=self.proxy_open: \ meth(r, proxy, type)) |
for uris, authinfo in domains.items(): | for uris, authinfo in domains.iteritems(): | def find_user_password(self, realm, authuri): domains = self.passwd.get(realm, {}) authuri = self.reduce_uri(authuri) for uris, authinfo in domains.items(): for uri in uris: if self.is_suburi(uri, authuri): return authinfo return None, None |
for k, v in req.headers.items(): | for k, v in req.headers.iteritems(): | def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given') |
for k, v in self.timeout.items(): | for k, v in self.timeout.iteritems(): | def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.items(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values()) |
Note: this functions only works if Mark Hammond's win32 | Note: this function only works if Mark Hammond's win32 | def win32_ver(release='',version='',csd='',ptype=''): """ Get additional version information from the Windows Registry and return a tuple (version,csd,ptype) referring to version number, CSD level and OS type (multi/single processor). As a hint: ptype returns 'Uniprocessor Free' on single processor NT machines and 'Multiprocessor Free' on multi processor machines. The 'Free' refers to the OS version being free of debugging code. It could also state 'Checked' which means the OS version uses debugging code, i.e. code that checks arguments, ranges, etc. (Thomas Heller). Note: this functions only works if Mark Hammond's win32 package is installed and obviously only runs on Win32 compatible platforms. """ # XXX Is there any way to find out the processor type on WinXX ? # XXX Is win32 available on Windows CE ? # Adapted from code posted by Karl Putland to comp.lang.python. # Import the needed APIs try: import win32api except ImportError: return release,version,csd,ptype from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\ VER_PLATFORM_WIN32_WINDOWS # Find out the registry key and some general version infos maj,min,buildno,plat,csd = GetVersionEx() version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) if csd[:13] == 'Service Pack ': csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' # Try to guess the release name if maj == 4: if min == 0: release = '95' else: release = '98' elif maj == 5: release = '2000' elif plat == VER_PLATFORM_WIN32_NT: regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' if maj <= 4: release = 'NT' elif maj == 5: release = '2000' else: if not release: # E.g. Win3.1 with win32s release = '%i.%i' % (maj,min) return release,version,csd,ptype # Open the registry key try: keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey) # Get a value to make sure the key exists... RegQueryValueEx(keyCurVer,'SystemRoot') except: return release,version,csd,ptype # Parse values #subversion = _win32_getvalue(keyCurVer, # 'SubVersionNumber', # ('',1))[0] #if subversion: # release = release + subversion # 95a, 95b, etc. build = _win32_getvalue(keyCurVer, 'CurrentBuildNumber', ('',1))[0] ptype = _win32_getvalue(keyCurVer, 'CurrentType', (ptype,1))[0] # Normalize version version = _norm_version(version,build) # Close key RegCloseKey(keyCurVer) return release,version,csd,ptype |
self.__frame.grid(row=3, column=1, sticky='NS') | self.__frame.grid(row=3, column=1, sticky='NSEW') | def __init__(self, switchboard, master=None): # non-gui ivars self.__sb = switchboard optiondb = switchboard.optiondb() self.__hexp = BooleanVar() self.__hexp.set(optiondb.get('HEXTYPE', 0)) self.__uwtyping = BooleanVar() self.__uwtyping.set(optiondb.get('UPWHILETYPE', 0)) # create the gui self.__frame = Frame(master, relief=RAISED, borderwidth=1) self.__frame.grid(row=3, column=1, sticky='NS') # Red self.__xl = Label(self.__frame, text='Red:') self.__xl.grid(row=0, column=0, sticky=E) self.__x = Entry(self.__frame, width=4) self.__x.grid(row=0, column=1) self.__x.bindtags(self.__x.bindtags() + ('Normalize', 'Update')) self.__x.bind_class('Normalize', '<Key>', self.__normalize) self.__x.bind_class('Update' , '<Key>', self.__maybeupdate) # Green self.__yl = Label(self.__frame, text='Green:') self.__yl.grid(row=1, column=0, sticky=E) self.__y = Entry(self.__frame, width=4) self.__y.grid(row=1, column=1) self.__y.bindtags(self.__y.bindtags() + ('Normalize', 'Update')) # Blue self.__zl = Label(self.__frame, text='Blue:') self.__zl.grid(row=2, column=0, sticky=E) self.__z = Entry(self.__frame, width=4) self.__z.grid(row=2, column=1) self.__z.bindtags(self.__z.bindtags() + ('Normalize', 'Update')) # Update while typing? self.__uwt = Checkbutton(self.__frame, text='Update while typing', variable=self.__uwtyping) self.__uwt.grid(row=3, column=0, columnspan=2, sticky=W) # Hex/Dec self.__hex = Checkbutton(self.__frame, text='Hexadecimal', variable=self.__hexp, command=self.__togglehex) self.__hex.grid(row=4, column=0, columnspan=2, sticky=W) |
s = madstring("\x00" * 5) verify(str(s) == "\x00" * 5) | base = "\x00" * 5 s = madstring(base) verify(str(s) == base) | def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev |
contents = contents[:i-1] + contents[i:] | if event.char: contents = contents[:i-1] + contents[i:] icursor = icursor-1 | def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if value is not legal, delete the last character inserted and ring # the bell if v is None or v < 0 or v > 255: i = ew.index(INSERT) contents = contents[:i-1] + contents[i:] ew.bell() icursor = icursor-1 elif self.__hexp.get(): contents = hex(v) else: contents = int(v) ew.delete(0, END) ew.insert(0, contents) ew.icursor(icursor) |
icursor = icursor-1 | def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if value is not legal, delete the last character inserted and ring # the bell if v is None or v < 0 or v > 255: i = ew.index(INSERT) contents = contents[:i-1] + contents[i:] ew.bell() icursor = icursor-1 elif self.__hexp.get(): contents = hex(v) else: contents = int(v) ew.delete(0, END) ew.insert(0, contents) ew.icursor(icursor) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.