bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def checkit(self): OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX
|
def checkit(self): if self.returntype.__class__ != OSErrType: OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX
| 13,400
|
def checkit(self): OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX
|
def checkit(self): OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX
| 13,401
|
def try_run (self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise. """ from distutils.ccompiler import CompileError, LinkError self._check_compiler() try: self._link(body, headers, include_dirs, libraries, library_dirs, lang) self.spawn([exe]) ok = 1 except (CompileError, LinkError, DistutilsExecError): ok = 0
|
def try_run (self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise. """ from distutils.ccompiler import CompileError, LinkError self._check_compiler() try: src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) self.spawn([exe]) ok = 1 except (CompileError, LinkError, DistutilsExecError): ok = 0
| 13,402
|
def search_function(encoding): # Cache lookup entry = _cache.get(encoding, _unknown) if entry is not _unknown: return entry # Import the module: # # First try to find an alias for the normalized encoding # name and lookup the module using the aliased name, then try to # lookup the module using the standard import scheme, i.e. first # try in the encodings package, then at top-level. # norm_encoding = normalize_encoding(encoding) aliased_encoding = _aliases.get(norm_encoding) or \ _aliases.get(norm_encoding.replace('.', '_')) if aliased_encoding is not None: modnames = [aliased_encoding, norm_encoding] else: modnames = [norm_encoding] for modname in modnames: if not modname: continue try: mod = __import__('encodings.' + modname, globals(), locals(), _import_tail) except ImportError: pass else: break else: mod = None try: getregentry = mod.getregentry except AttributeError: # Not a codec module mod = None if mod is None: # Cache misses _cache[encoding] = None return None # Now ask the module for the registry entry entry = getregentry() if not isinstance(entry, codecs.CodecInfo): if not 4 <= len(entry) <= 7: raise CodecRegistryError,\ 'module "%s" (%s) failed to register' % \ (mod.__name__, mod.__file__) if not callable(entry[0]) or \ not callable(entry[1]) or \ (entry[2] is not None and not callable(entry[2])) or \ (entry[3] is not None and not callable(entry[3])) or \ (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \ (len(entry) > 5 and entry[5] is not None and not callable(entry[5])): raise CodecRegistryError,\ 'incompatible codecs in module "%s" (%s)' % \ (mod.__name__, mod.__file__) if len(entry)<7 or entry[6] is None: entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],) entry = codecs.CodecInfo(*entry) # Cache the codec registry entry _cache[encoding] = entry # Register its aliases (without overwriting previously registered # aliases) try: codecaliases = mod.getaliases() except AttributeError: pass else: for alias in codecaliases: if not _aliases.has_key(alias): _aliases[alias] = modname # Return the registry entry return entry
|
def search_function(encoding): # Cache lookup entry = _cache.get(encoding, _unknown) if entry is not _unknown: return entry # Import the module: # # First try to find an alias for the normalized encoding # name and lookup the module using the aliased name, then try to # lookup the module using the standard import scheme, i.e. first # try in the encodings package, then at top-level. # norm_encoding = normalize_encoding(encoding) aliased_encoding = _aliases.get(norm_encoding) or \ _aliases.get(norm_encoding.replace('.', '_')) if aliased_encoding is not None: modnames = [aliased_encoding, norm_encoding] else: modnames = [norm_encoding] for modname in modnames: if not modname or '.' in modname: continue try: mod = __import__('encodings.' + modname, globals(), locals(), _import_tail) except ImportError: pass else: break else: mod = None try: getregentry = mod.getregentry except AttributeError: # Not a codec module mod = None if mod is None: # Cache misses _cache[encoding] = None return None # Now ask the module for the registry entry entry = getregentry() if not isinstance(entry, codecs.CodecInfo): if not 4 <= len(entry) <= 7: raise CodecRegistryError,\ 'module "%s" (%s) failed to register' % \ (mod.__name__, mod.__file__) if not callable(entry[0]) or \ not callable(entry[1]) or \ (entry[2] is not None and not callable(entry[2])) or \ (entry[3] is not None and not callable(entry[3])) or \ (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \ (len(entry) > 5 and entry[5] is not None and not callable(entry[5])): raise CodecRegistryError,\ 'incompatible codecs in module "%s" (%s)' % \ (mod.__name__, mod.__file__) if len(entry)<7 or entry[6] is None: entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],) entry = codecs.CodecInfo(*entry) # Cache the codec registry entry _cache[encoding] = entry # Register its aliases (without overwriting previously registered # aliases) try: codecaliases = mod.getaliases() except AttributeError: pass else: for alias in codecaliases: if not _aliases.has_key(alias): _aliases[alias] = modname # Return the registry entry return entry
| 13,403
|
def _qdecode(s): import quopri as _quopri
|
def _qdecode(s): import quopri as _quopri
| 13,404
|
def fix(filename):
|
def fix(filename):
| 13,405
|
def readline(self): if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = 1 else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or ".bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next three lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") self._output = open(self._filename, "w") self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") line = self._file.readline() if line: self._lineno = self._lineno + 1 self._filelineno = self._filelineno + 1 return line self.nextfile() # Recursive call return self.readline()
|
def readline(self): if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = 1 else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or ".bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next three lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") self._output = open(self._filename, "w") self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") line = self._file.readline() if line: self._lineno = self._lineno + 1 self._filelineno = self._filelineno + 1 return line self.nextfile() # Recursive call return self.readline()
| 13,406
|
def readline(self): if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = 1 else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or ".bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next three lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") self._output = open(self._filename, "w") self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") line = self._file.readline() if line: self._lineno = self._lineno + 1 self._filelineno = self._filelineno + 1 return line self.nextfile() # Recursive call return self.readline()
|
def readline(self): if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = 1 else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or ".bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next three lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") try: perm = os.fstat(self._file.fileno())[stat.ST_MODE] except: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: os.chmod(self._filename, perm) except: pass self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") line = self._file.readline() if line: self._lineno = self._lineno + 1 self._filelineno = self._filelineno + 1 return line self.nextfile() # Recursive call return self.readline()
| 13,407
|
def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '>', text) return text
|
def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}(>+)$', ' at [0-9A-F]{8,}(>+)$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '>', text) return text
| 13,408
|
def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '>', text) return text
|
def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '\\1', text) return text
| 13,409
|
def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" suffix, name = '', None if type(thing) is type(''): try: object = locate(thing, forceload) except ErrorDuringImport, value: print value return if not object: print 'no Python documentation found for %s' % repr(thing) return parts = split(thing, '.') if len(parts) > 1: suffix = ' in ' + join(parts[:-1], '.') name = parts[-1] thing = object desc = describe(thing) module = inspect.getmodule(thing) if not suffix and module and module is not thing: suffix = ' in module ' + module.__name__ pager(title % (desc + suffix) + '\n\n' + text.document(thing, name))
|
def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" suffix, name = '', None if type(thing) is type(''): try: object = locate(thing, forceload) except ErrorDuringImport, value: print value return if not object: print 'no Python documentation found for %s' % repr(thing) return parts = split(thing, '.') if len(parts) > 1: suffix = ' in ' + join(parts[:-1], '.') name = parts[-1] thing = object desc = describe(thing) module = inspect.getmodule(thing) if not suffix and module and module is not thing: suffix = ' in module ' + module.__name__ pager(title % (desc + suffix) + '\n\n' + text.document(thing, name))
| 13,410
|
def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object = locate(key, forceload) except ErrorDuringImport, value: print value else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key)
|
def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) file = open(name + '.html', 'w') file.write(page) file.close() print 'wrote', name + '.html' except (ImportError, ErrorDuringImport), value: print value else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key)
| 13,411
|
def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object = locate(key, forceload) except ErrorDuringImport, value: print value else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key)
|
def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object = locate(key, forceload) except ErrorDuringImport, value: print value
| 13,412
|
def ispath(x): return type(x) is types.StringType and find(x, os.sep) >= 0
|
def ispath(x): return isinstance(x, str) and find(x, os.sep) >= 0
| 13,413
|
def _dump_ur(dict): # Dump untagged responses (in `dict'). l = dict.items() if not l: return t = '\n\t\t' l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l) _mesg('untagged responses dump:%s%s' % (t, j(l, t)))
|
def _dump_ur(dict): # Dump untagged responses (in `dict'). l = dict.items() if not l: return t = '\n\t\t' l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l) _mesg('untagged responses dump:%s%s' % (t, j(l, t)))
| 13,414
|
def capwords(str, pat): import string words = split(str, pat, 1) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "")
|
def capwords(str, pat='[^a-zA-Z0-9_]+'): import string words = split(str, pat, 1) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "")
| 13,415
|
def capwords(str, pat): import string words = split(str, pat, 1) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "")
|
def capwords(str, pat): import string words = splitx(str, pat) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "")
| 13,416
|
def write32u(output, value): if value < 0: value = value + 0x100000000L output.write(struct.pack("<L", value))
|
def write32u(output, value): output.write(struct.pack("<L", value))
| 13,417
|
def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' method = ord( self.fileobj.read(1) ) if method != 8: raise IOError, 'Unknown compression method' flag = ord( self.fileobj.read(1) ) # modtime = self.fileobj.read(4) # extraflag = self.fileobj.read(1) # os = self.fileobj.read(1) self.fileobj.read(6)
|
def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' method = ord( self.fileobj.read(1) ) if method != 8: raise IOError, 'Unknown compression method' flag = ord( self.fileobj.read(1) ) # modtime = self.fileobj.read(4) # extraflag = self.fileobj.read(1) # os = self.fileobj.read(1) self.fileobj.read(6)
| 13,418
|
def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' method = ord( self.fileobj.read(1) ) if method != 8: raise IOError, 'Unknown compression method' flag = ord( self.fileobj.read(1) ) # modtime = self.fileobj.read(4) # extraflag = self.fileobj.read(1) # os = self.fileobj.read(1) self.fileobj.read(6)
|
def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' method = ord( self.fileobj.read(1) ) if method != 8: raise IOError, 'Unknown compression method' flag = ord( self.fileobj.read(1) ) # modtime = self.fileobj.read(4) # extraflag = self.fileobj.read(1) # os = self.fileobj.read(1) self.fileobj.read(6)
| 13,419
|
def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' method = ord( self.fileobj.read(1) ) if method != 8: raise IOError, 'Unknown compression method' flag = ord( self.fileobj.read(1) ) # modtime = self.fileobj.read(4) # extraflag = self.fileobj.read(1) # os = self.fileobj.read(1) self.fileobj.read(6)
|
def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' method = ord( self.fileobj.read(1) ) if method != 8: raise IOError, 'Unknown compression method' flag = ord( self.fileobj.read(1) ) # modtime = self.fileobj.read(4) # extraflag = self.fileobj.read(1) # os = self.fileobj.read(1) self.fileobj.read(6)
| 13,420
|
def _read(self, size=1024): if self.fileobj is None: raise EOFError, "Reached EOF"
|
def _read(self, size=1024): if self.fileobj is None: raise EOFError, "Reached EOF"
| 13,421
|
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = read32(self.fileobj) if crc32%0x100000000L != self.crc%0x100000000L: raise ValueError, "CRC check failed" elif isize != self.size: raise ValueError, "Incorrect length of data produced"
|
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = U32(read32(self.fileobj)) if U32(crc32) != U32(self.crc): raise ValueError, "CRC check failed" elif isize != self.size: raise ValueError, "Incorrect length of data produced"
| 13,422
|
def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) write32(self.fileobj, self.crc) write32(self.fileobj, self.size) self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None
|
def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) write32(self.fileobj, self.crc) write32u(self.fileobj, self.size) self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None
| 13,423
|
def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count/1024): self.read(1024) self.read(count % 1024)
|
def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count // 1024): self.write(1024 * '\0') self.write((count % 1024) * '\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count/1024): self.read(1024) self.read(count % 1024)
| 13,424
|
def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count/1024): self.read(1024) self.read(count % 1024)
|
def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count // 1024): self.read(1024) self.read(count % 1024)
| 13,425
|
def readlines(self, sizehint=0): # Negative numbers result in reading all the lines if sizehint <= 0: sizehint = sys.maxint L = [] while sizehint > 0: line = self.readline() if line == "": break L.append(line) sizehint = sizehint - len(line)
|
def readlines(self, sizehint=0): # Negative numbers result in reading all the lines if sizehint <= 0: sizehint = sys.maxint L = [] while sizehint > 0: line = self.readline() if line == "": break L.append(line) sizehint = sizehint - len(line)
| 13,426
|
def readlines(self, sizehint=0): # Negative numbers result in reading all the lines if sizehint <= 0: sizehint = sys.maxint L = [] while sizehint > 0: line = self.readline() if line == "": break L.append(line) sizehint = sizehint - len(line)
|
def readlines(self, sizehint=0): # Negative numbers result in reading all the lines if sizehint <= 0: sizehint = sys.maxint L = [] while sizehint > 0: line = self.readline() if line == "": break L.append(line) sizehint = sizehint - len(line)
| 13,427
|
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name= time.tzname[0] try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime.strptime(tz_name, "%Z")[8] self.failUnlessEqual(tz_value, -1) finally: time.tzname = original_tzname time.daylight = original_daylight
|
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name = time.tzname[0] if tz_name.lower() in ("UTC", "GMT"): return try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime.strptime(tz_name, "%Z")[8] self.failUnlessEqual(tz_value, -1) finally: time.tzname = original_tzname time.daylight = original_daylight
| 13,428
|
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name= time.tzname[0] try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime.strptime(tz_name, "%Z")[8] self.failUnlessEqual(tz_value, -1) finally: time.tzname = original_tzname time.daylight = original_daylight
|
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name= time.tzname[0] try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime.strptime(tz_name, "%Z")[8] self.failUnlessEqual(tz_value, -1, "%s lead to a timezone value of %s instead of -1 when " "time.daylight set to %s and passing in %s" % (time.tzname, tz_value, time.daylight, tz_name)) finally: time.tzname = original_tzname time.daylight = original_daylight
| 13,429
|
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
|
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
| 13,430
|
def spawn_subprocess(self): args = self.subprocess_arglist self.rpcpid = os.spawnv(os.P_NOWAIT, args[0], args)
|
def spawn_subprocess(self): args = self.subprocess_arglist self.rpcpid = os.spawnv(os.P_NOWAIT, args[0], args)
| 13,431
|
def build_subprocess_arglist(self): w = ['-W' + s for s in sys.warnoptions] # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') if __name__ == 'idlelib.PyShell': command = "__import__('idlelib.run').run.main(" + `del_exitf` +")" else: command = "__import__('run').main(" + `del_exitf` + ")" return [sys.executable] + w + ["-c", command, str(self.port)]
|
def build_subprocess_arglist(self): w = ['-W' + s for s in sys.warnoptions] # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') if __name__ == 'idlelib.PyShell': command = "__import__('idlelib.run').run.main(" + `del_exitf` +")" else: command = "__import__('run').main(" + `del_exitf` + ")" return [sys.executable] + w + ["-c", command, str(self.port)]
| 13,432
|
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')
|
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')
| 13,433
|
def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. return None if os.path.exists(filename) or hasattr(getmodule(object), '__loader__'): return filename
|
def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) if string.lower(filename[-4:]) in ('.pyc', '.pyo'): filename = filename[:-4] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. return None if os.path.exists(filename): return filename if filename[:1]!='<' and hasattr(getmodule(object), '__loader__'): return filename
| 13,434
|
def testtype(type, example): a = array.array(type) a.append(example) if verbose: print 40*'*' print 'array after append: ', a a.typecode a.itemsize if a.typecode in ('i', 'b', 'h', 'l'): a.byteswap() if a.typecode == 'c': f = open(TESTFN, "w") f.write("The quick brown fox jumps over the lazy dog.\n") f.close() f = open(TESTFN, 'r') a.fromfile(f, 10) f.close() if verbose: print 'char array with 10 bytes of TESTFN appended: ', a a.fromlist(['a', 'b', 'c']) if verbose: print 'char array with list appended: ', a a.insert(0, example) if verbose: print 'array of %s after inserting another:' % a.typecode, a f = open(TESTFN, 'w') a.tofile(f) f.close() a.tolist() a.tostring() if verbose: print 'array of %s converted to a list: ' % a.typecode, a.tolist() if verbose: print 'array of %s converted to a string: ' \ % a.typecode, `a.tostring()` if type == 'c': a = array.array(type, "abcde") a[:-1] = a if a != array.array(type, "abcdee"): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, "abcde") a[1:] = a if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, "abcde") a[1:-1] = a if a != array.array(type, "aabcdee"): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index("e") != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count("a") != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove("e") if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != "a": raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != "b": raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, "xyz")) if a != array.array(type, "acdexyz"): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, "acd"): raise TestFailed, "array(%s) pop-test" % `type` else: a = array.array(type, [1, 2, 3, 4, 5]) a[:-1] = a if a != array.array(type, [1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:] = a if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:-1] = a if a != array.array(type, [1, 1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index(5) != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count(1) != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove(5) if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != 1: raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != 2: raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, [7, 8, 9])) if a != array.array(type, [1, 3, 4, 5, 7, 8, 9]): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, [1, 3, 4]): raise TestFailed, "array(%s) pop-test" % `type` # test that overflow exceptions are raised as expected for assignment # to array of specific integral types from math import pow if type in ('b', 'h', 'i', 'l'): # check signed and unsigned versions a = array.array(type) signedLowerLimit = -1 * long(pow(2, a.itemsize * 8 - 1)) signedUpperLimit = long(pow(2, a.itemsize * 8 - 1)) - 1L unsignedLowerLimit = 0 unsignedUpperLimit = long(pow(2, a.itemsize * 8)) - 1L testoverflow(type, signedLowerLimit, signedUpperLimit) testoverflow(type.upper(), unsignedLowerLimit, unsignedUpperLimit)
|
def testtype(type, example): a = array.array(type) a.append(example) if verbose: print 40*'*' print 'array after append: ', a a.typecode a.itemsize if a.typecode in ('i', 'b', 'h', 'l'): a.byteswap() if a.typecode == 'c': f = open(TESTFN, "w") f.write("The quick brown fox jumps over the lazy dog.\n") f.close() f = open(TESTFN, 'r') a.fromfile(f, 10) f.close() if verbose: print 'char array with 10 bytes of TESTFN appended: ', a a.fromlist(['a', 'b', 'c']) if verbose: print 'char array with list appended: ', a a.insert(0, example) if verbose: print 'array of %s after inserting another:' % a.typecode, a f = open(TESTFN, 'w') a.tofile(f) f.close() a.tolist() a.tostring() if verbose: print 'array of %s converted to a list: ' % a.typecode, a.tolist() if verbose: print 'array of %s converted to a string: ' \ % a.typecode, `a.tostring()` if type == 'c': a = array.array(type, "abcde") a[:-1] = a if a != array.array(type, "abcdee"): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, "abcde") a[1:] = a if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, "abcde") a[1:-1] = a if a != array.array(type, "aabcdee"): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index("e") != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count("a") != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove("e") if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != "a": raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != "b": raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, "xyz")) if a != array.array(type, "acdexyz"): raise TestFailed, "array(%s) extend-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` if a != array.array(type, "acd"): raise TestFailed, "array(%s) pop-test" % `type` else: a = array.array(type, [1, 2, 3, 4, 5]) a[:-1] = a if a != array.array(type, [1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:] = a if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:-1] = a if a != array.array(type, [1, 1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index(5) != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count(1) != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove(5) if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != 1: raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != 2: raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, [7, 8, 9])) if a != array.array(type, [1, 3, 4, 5, 7, 8, 9]): raise TestFailed, "array(%s) extend-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 'e': raise TestFailed, "array(%s) pop-test" % `type` if a != array.array(type, [1, 3, 4]): raise TestFailed, "array(%s) pop-test" % `type` # test that overflow exceptions are raised as expected for assignment # to array of specific integral types from math import pow if type in ('b', 'h', 'i', 'l'): # check signed and unsigned versions a = array.array(type) signedLowerLimit = -1 * long(pow(2, a.itemsize * 8 - 1)) signedUpperLimit = long(pow(2, a.itemsize * 8 - 1)) - 1L unsignedLowerLimit = 0 unsignedUpperLimit = long(pow(2, a.itemsize * 8)) - 1L testoverflow(type, signedLowerLimit, signedUpperLimit) testoverflow(type.upper(), unsignedLowerLimit, unsignedUpperLimit)
| 13,435
|
def testtype(type, example): a = array.array(type) a.append(example) if verbose: print 40*'*' print 'array after append: ', a a.typecode a.itemsize if a.typecode in ('i', 'b', 'h', 'l'): a.byteswap() if a.typecode == 'c': f = open(TESTFN, "w") f.write("The quick brown fox jumps over the lazy dog.\n") f.close() f = open(TESTFN, 'r') a.fromfile(f, 10) f.close() if verbose: print 'char array with 10 bytes of TESTFN appended: ', a a.fromlist(['a', 'b', 'c']) if verbose: print 'char array with list appended: ', a a.insert(0, example) if verbose: print 'array of %s after inserting another:' % a.typecode, a f = open(TESTFN, 'w') a.tofile(f) f.close() a.tolist() a.tostring() if verbose: print 'array of %s converted to a list: ' % a.typecode, a.tolist() if verbose: print 'array of %s converted to a string: ' \ % a.typecode, `a.tostring()` if type == 'c': a = array.array(type, "abcde") a[:-1] = a if a != array.array(type, "abcdee"): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, "abcde") a[1:] = a if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, "abcde") a[1:-1] = a if a != array.array(type, "aabcdee"): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index("e") != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count("a") != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove("e") if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != "a": raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != "b": raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, "xyz")) if a != array.array(type, "acdexyz"): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, "acd"): raise TestFailed, "array(%s) pop-test" % `type` else: a = array.array(type, [1, 2, 3, 4, 5]) a[:-1] = a if a != array.array(type, [1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:] = a if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:-1] = a if a != array.array(type, [1, 1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index(5) != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count(1) != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove(5) if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != 1: raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != 2: raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, [7, 8, 9])) if a != array.array(type, [1, 3, 4, 5, 7, 8, 9]): raise TestFailed, "array(%s) extend-test" % `type` a.pop() a.pop() a.pop() a.pop() if a != array.array(type, [1, 3, 4]): raise TestFailed, "array(%s) pop-test" % `type` # test that overflow exceptions are raised as expected for assignment # to array of specific integral types from math import pow if type in ('b', 'h', 'i', 'l'): # check signed and unsigned versions a = array.array(type) signedLowerLimit = -1 * long(pow(2, a.itemsize * 8 - 1)) signedUpperLimit = long(pow(2, a.itemsize * 8 - 1)) - 1L unsignedLowerLimit = 0 unsignedUpperLimit = long(pow(2, a.itemsize * 8)) - 1L testoverflow(type, signedLowerLimit, signedUpperLimit) testoverflow(type.upper(), unsignedLowerLimit, unsignedUpperLimit)
|
def testtype(type, example): a = array.array(type) a.append(example) if verbose: print 40*'*' print 'array after append: ', a a.typecode a.itemsize if a.typecode in ('i', 'b', 'h', 'l'): a.byteswap() if a.typecode == 'c': f = open(TESTFN, "w") f.write("The quick brown fox jumps over the lazy dog.\n") f.close() f = open(TESTFN, 'r') a.fromfile(f, 10) f.close() if verbose: print 'char array with 10 bytes of TESTFN appended: ', a a.fromlist(['a', 'b', 'c']) if verbose: print 'char array with list appended: ', a a.insert(0, example) if verbose: print 'array of %s after inserting another:' % a.typecode, a f = open(TESTFN, 'w') a.tofile(f) f.close() a.tolist() a.tostring() if verbose: print 'array of %s converted to a list: ' % a.typecode, a.tolist() if verbose: print 'array of %s converted to a string: ' \ % a.typecode, `a.tostring()` if type == 'c': a = array.array(type, "abcde") a[:-1] = a if a != array.array(type, "abcdee"): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, "abcde") a[1:] = a if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, "abcde") a[1:-1] = a if a != array.array(type, "aabcdee"): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index("e") != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count("a") != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove("e") if a != array.array(type, "aabcde"): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != "a": raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != "b": raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, "xyz")) if a != array.array(type, "acdexyz"): raise TestFailed, "array(%s) extend-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` if a != array.array(type, "acd"): raise TestFailed, "array(%s) pop-test" % `type` else: a = array.array(type, [1, 2, 3, 4, 5]) a[:-1] = a if a != array.array(type, [1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (head)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:] = a if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) self-slice-assign (tail)" % `type` a = array.array(type, [1, 2, 3, 4, 5]) a[1:-1] = a if a != array.array(type, [1, 1, 2, 3, 4, 5, 5]): raise TestFailed, "array(%s) self-slice-assign (cntr)" % `type` if a.index(5) != 5: raise TestFailed, "array(%s) index-test" % `type` if a.count(1) != 2: raise TestFailed, "array(%s) count-test" % `type` a.remove(5) if a != array.array(type, [1, 1, 2, 3, 4, 5]): raise TestFailed, "array(%s) remove-test" % `type` if a.pop(0) != 1: raise TestFailed, "array(%s) pop-test" % `type` if a.pop(1) != 2: raise TestFailed, "array(%s) pop-test" % `type` a.extend(array.array(type, [7, 8, 9])) if a != array.array(type, [1, 3, 4, 5, 7, 8, 9]): raise TestFailed, "array(%s) extend-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` x = a.pop() if x != 5: raise TestFailed, "array(%s) pop-test" % `type` if a != array.array(type, [1, 3, 4]): raise TestFailed, "array(%s) pop-test" % `type` # test that overflow exceptions are raised as expected for assignment # to array of specific integral types from math import pow if type in ('b', 'h', 'i', 'l'): # check signed and unsigned versions a = array.array(type) signedLowerLimit = -1 * long(pow(2, a.itemsize * 8 - 1)) signedUpperLimit = long(pow(2, a.itemsize * 8 - 1)) - 1L unsignedLowerLimit = 0 unsignedUpperLimit = long(pow(2, a.itemsize * 8)) - 1L testoverflow(type, signedLowerLimit, signedUpperLimit) testoverflow(type.upper(), unsignedLowerLimit, unsignedUpperLimit)
| 13,436
|
def remove_section(self, section): """Remove a file section.""" if self.__sections.has_key(section): del self.__sections[section] return 1 else: return 0
|
def remove_section(self, section): """Remove a file section.""" if self.__sections.has_key(section): del self.__sections[section] return 1 else: return 0
| 13,437
|
def decode(in_file, out_file=None, mode=None): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr: raise Error, 'No valid begin line found in input file' if hdr[:5] != 'begin': continue hdrfields = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): fp = open(out_file, 'wb') try: os.path.chmod(out_file, mode) except AttributeError: pass out_file = fp # # Main decoding loop # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = binascii.a2b_uu(s[:nbytes]) sys.stderr.write("Warning: %s\n" % str(v)) out_file.write(data) s = in_file.readline() if not str: raise Error, 'Truncated input file'
|
def decode(in_file, out_file=None, mode=None): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif type(in_file) == type(''): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr: raise Error, 'No valid begin line found in input file' if hdr[:5] != 'begin': continue hdrfields = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # if out_file == '-': out_file = sys.stdout elif type(out_file) == type(''): fp = open(out_file, 'wb') try: os.path.chmod(out_file, mode) except AttributeError: pass out_file = fp # # Main decoding loop # s = in_file.readline() while s and s != 'end\n': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = binascii.a2b_uu(s[:nbytes]) sys.stderr.write("Warning: %s\n" % str(v)) out_file.write(data) s = in_file.readline() if not s: raise Error, 'Truncated input file'
| 13,438
|
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
|
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. """ if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if plat_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
| 13,439
|
def __init__(self, environ=os.environ): self.dict = self.data = parse(environ=environ) self.query_string = environ['QUERY_STRING']
|
def __init__(self, environ=os.environ, keep_blank_values=0, strict_parsing=0): self.dict = self.data = parse(environ=environ, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing) self.query_string = environ['QUERY_STRING']
| 13,440
|
def _group(s): conv=localeconv() grouping=conv['grouping'] if not grouping:return s result="" seps = 0 spaces = "" if s[-1] == ' ': sp = s.find(' ') spaces = s[sp:] s = s[:sp] while s and grouping: # if grouping is -1, we are done if grouping[0]==CHAR_MAX: break # 0: re-use last group ad infinitum elif grouping[0]!=0: #process last group group=grouping[0] grouping=grouping[1:] if result: result=s[-group:]+conv['thousands_sep']+result seps += 1 else: result=s[-group:] s=s[:-group] if s and s[-1] not in "0123456789": # the leading string is only spaces and signs return s+result+spaces,seps if not result: return s+spaces,seps if s: result=s+conv['thousands_sep']+result seps += 1 return result+spaces,seps
|
def _group(s): conv=localeconv() grouping=conv['grouping'] if not grouping:return (s, 0) result="" seps = 0 spaces = "" if s[-1] == ' ': sp = s.find(' ') spaces = s[sp:] s = s[:sp] while s and grouping: # if grouping is -1, we are done if grouping[0]==CHAR_MAX: break # 0: re-use last group ad infinitum elif grouping[0]!=0: #process last group group=grouping[0] grouping=grouping[1:] if result: result=s[-group:]+conv['thousands_sep']+result seps += 1 else: result=s[-group:] s=s[:-group] if s and s[-1] not in "0123456789": # the leading string is only spaces and signs return s+result+spaces,seps if not result: return s+spaces,seps if s: result=s+conv['thousands_sep']+result seps += 1 return result+spaces,seps
| 13,441
|
def do1event(self, mask = everyEvent, wait = 0): event = self.getevent(mask, wait) if event: self.dispatch(event)
|
def do1event(self, mask = everyEvent, wait = 0): ok, event = self.getevent(mask, wait) if IsDialogEvent(event): if self.do_dialogevent(event): return if ok: self.dispatch(event)
| 13,442
|
def getevent(self, mask = everyEvent, wait = 0): ok, event = WaitNextEvent(mask, wait) if ok: return event else: return None
|
def getevent(self, mask = everyEvent, wait = 0): ok, event = WaitNextEvent(mask, wait) if ok: return event else: return None
| 13,443
|
def dispatch(self, event): if IsDialogEvent(event): self.do_dialogevent(event) return (what, message, when, where, modifiers) = event if eventname.has_key(what): name = "do_" + eventname[what] else: name = "do_%d" % what try: handler = getattr(self, name) except AttributeError: handler = self.do_unknownevent handler(event)
|
def dispatch(self, event): (what, message, when, where, modifiers) = event if eventname.has_key(what): name = "do_" + eventname[what] else: name = "do_%d" % what try: handler = getattr(self, name) except AttributeError: handler = self.do_unknownevent handler(event)
| 13,444
|
def do_dialogevent(self, event): gotone, window, item = DialogSelect(event) if gotone: if self._windows.has_key(window): window.do_itemhit(item, event) else: print 'Dialog event for unknown dialog'
|
def do_dialogevent(self, event): gotone, window, item = DialogSelect(event) if gotone: if self._windows.has_key(window): self._windows[window].do_itemhit(item, event) else: print 'Dialog event for unknown dialog'
| 13,445
|
def close(self): self.wid.DisposeDialog() self.do_postclose()
|
def close(self): self.do_postclose()
| 13,446
|
def initcmap(ybits,ibits,qbits,chrompack): if ybits+ibits+qbits > 11: raise 'Sorry, 11 bits max' maxy = pow(2,ybits) maxi = pow(2,ibits) maxq = pow(2,qbits) for i in range(2048,4096-256): mapcolor(i, 0, 255, 0) for y in range(maxy): yv = float(y)/float(maxy-1) for i in range(maxi): iv = (float(i)/float(maxi-1))-0.5 for q in range(maxq): qv = (float(q)/float(maxq-1))-0.5 index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) if index < 4096 - 256: mapcolor(index, r,g,b)
|
def initcmap(ybits,ibits,qbits,chrompack): if ybits+ibits+qbits > 11: raise 'Sorry, 11 bits max' maxy = pow(2,ybits) maxi = pow(2,ibits) maxq = pow(2,qbits) for i in range(2048,4096-256): mapcolor(i, 0, 255, 0) for y in range(maxy): yv = float(y)/float(maxy-1) for i in range(maxi): if maxi = 1: iv = 0 else: iv = (float(i)/float(maxi-1))-0.5 for q in range(maxq): qv = (float(q)/float(maxq-1))-0.5 index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) if index < 4096 - 256: mapcolor(index, r,g,b)
| 13,447
|
def initcmap(ybits,ibits,qbits,chrompack): if ybits+ibits+qbits > 11: raise 'Sorry, 11 bits max' maxy = pow(2,ybits) maxi = pow(2,ibits) maxq = pow(2,qbits) for i in range(2048,4096-256): mapcolor(i, 0, 255, 0) for y in range(maxy): yv = float(y)/float(maxy-1) for i in range(maxi): iv = (float(i)/float(maxi-1))-0.5 for q in range(maxq): qv = (float(q)/float(maxq-1))-0.5 index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) if index < 4096 - 256: mapcolor(index, r,g,b)
|
def initcmap(ybits,ibits,qbits,chrompack): if ybits+ibits+qbits > 11: raise 'Sorry, 11 bits max' maxy = pow(2,ybits) maxi = pow(2,ibits) maxq = pow(2,qbits) for i in range(2048,4096-256): mapcolor(i, 0, 255, 0) for y in range(maxy): yv = float(y)/float(maxy-1) for i in range(maxi): iv = (float(i)/float(maxi-1))-0.5 for q in range(maxq): if maxq = 1: qv = 0 else: qv = (float(q)/float(maxq-1))-0.5 index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) if index < 4096 - 256: mapcolor(index, r,g,b)
| 13,448
|
def initcmap(ybits,ibits,qbits,chrompack): if ybits+ibits+qbits > 11: raise 'Sorry, 11 bits max' maxy = pow(2,ybits) maxi = pow(2,ibits) maxq = pow(2,qbits) for i in range(2048,4096-256): mapcolor(i, 0, 255, 0) for y in range(maxy): yv = float(y)/float(maxy-1) for i in range(maxi): iv = (float(i)/float(maxi-1))-0.5 for q in range(maxq): qv = (float(q)/float(maxq-1))-0.5 index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) if index < 4096 - 256: mapcolor(index, r,g,b)
|
definitcmap(ybits,ibits,qbits,chrompack):ifybits+ibits+qbits>11:raise'Sorry,11bitsmax'maxy=pow(2,ybits)maxi=pow(2,ibits)maxq=pow(2,qbits)foriinrange(2048,4096-256):mapcolor(i,0,255,0)foryinrange(maxy):yv=float(y)/float(maxy-1)foriinrange(maxi):iv=(float(i)/float(maxi-1))-0.5forqinrange(maxq):qv=(float(q)/float(maxq-1))-0.5index=2048+y+(i<<ybits)+(q<<(ybits+ibits))rv,gv,bv=colorsys.yiq_to_rgb(yv,iv,qv)r,g,b=int(rv*255.0),int(gv*255.0),int(bv*255.0)ifindex<4096-256:mapcolor(index,r,g,b)
| 13,449
|
def __init__(self, *a, **kw): if a: assert len(a) == 1 self.state = a[0] if kw: for k, v in kw.items(): self[v] = k
|
def __init__(self, *a, **kw): if a: vereq(len(a), 1) self.state = a[0] if kw: for k, v in kw.items(): self[v] = k
| 13,450
|
def __setitem__(self, key, value): assert isinstance(key, type(0)) dict.__setitem__(self, key, value)
|
def __setitem__(self, key, value): verify(isinstance(key, type(0))) dict.__setitem__(self, key, value)
| 13,451
|
def __repr__(self): return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
|
def __repr__(self): return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
| 13,452
|
def __repr__(self): return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
|
def __repr__(self): return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
| 13,453
|
def cmp(f1, f2, shallow=1,use_statcache=0): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name shallow -- Just check stat signature (do not read the files). defaults to 1. use_statcache -- Do not stat() each file directly: go through the statcache module for more efficiency. Return value: integer -- 1 if the files are the same, 0 otherwise. This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. Of course, if 'use_statcache' is true, this mechanism is defeated, and the cache will never grow stale. """ stat_function = (os.stat, statcache.stat)[use_statcache] s1, s2 = _sig(stat_function(f1)), _sig(stat_function(f2)) if s1[0]!=stat.S_IFREG or s2[0]!=stat.S_IFREG: return 0 if shallow and s1 == s2: return 1 if s1[1]!=s2[1]: return 0 result = _cache.get((f1, f2)) if result and (s1, s2)==result[:2]: return result[2] outcome = _do_cmp(f1, f2) _cache[f1, f2] = s1, s2, outcome return outcome
|
def cmp(f1, f2, shallow=1,use_statcache=0): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name shallow -- Just check stat signature (do not read the files). defaults to 1. use_statcache -- Do not stat() each file directly: go through the statcache module for more efficiency. Return value: integer -- 1 if the files are the same, 0 otherwise. This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. Of course, if 'use_statcache' is true, this mechanism is defeated, and the cache will never grow stale. """ stat_function = (os.stat, statcache.stat)[use_statcache] s1, s2 = _sig(stat_function(f1)), _sig(stat_function(f2)) if s1[0]!=stat.S_IFREG or s2[0]!=stat.S_IFREG: return 0 if shallow and s1 == s2: return 1 if s1[1]!=s2[1]: return 0 result = _cache.get((f1, f2)) if result and (s1, s2)==result[:2]: return result[2] outcome = _do_cmp(f1, f2) _cache[f1, f2] = s1, s2, outcome return outcome
| 13,454
|
def _sig(st): return (stat.S_IFMT(st[stat.ST_MODE]), st[stat.ST_SIZE], st[stat.ST_MTIME])
|
def _sig(st): return (stat.S_IFMT(st[stat.ST_MODE]), st[stat.ST_SIZE], st[stat.ST_MTIME])
| 13,455
|
def get_request(self): return self.socket.recvfrom(self.max_packet_size)
|
def get_request(self): return self.socket.recvfrom(self.max_packet_size)
| 13,456
|
typedef struct
|
typedef struct
| 13,457
|
def f(): pass
|
def f(): pass
| 13,458
|
def f(): pass
|
def f(): pass
| 13,459
|
def _getName( item, nameFromNum ): "Helper function -- don't use it directly" if type( item ) == IntType: try: keyname = nameFromNum( item ) except (WindowsError, EnvironmentError): raise IndexError, item elif type( item )==StringType: keyname=item else: raise exceptions.TypeError, \ "Requires integer index or string key name" return keyname
|
def _getName( item, nameFromNum ): "Helper function -- don't use it directly" if type( item ) == IntType: try: keyname = nameFromNum( item ) except (WindowsError, EnvironmentError): raise IndexError, item elif type( item ) in [StringType, UnicodeType]: keyname=item else: raise exceptions.TypeError, \ "Requires integer index or string key name" return keyname
| 13,460
|
def setValue( self, valname, data, regtype=None ): "Set a data value's data (and optionally type)" if regtype: typeint=regtype.intval else: if type( data )==StringType: typeint=_winreg.REG_SZ elif type( data )==IntType: typeint=_winreg.REG_DWORD elif type( data )==array.ArrayType: typeint=_winreg.REG_BINARY data=data.tostring() _winreg.SetValueEx( self.handle, valname, 0, typeint, data )
|
def setValue( self, valname, data, regtype=None ): "Set a data value's data (and optionally type)" if regtype: typeint=regtype.intval else: if type( data ) in [StringType, UnicodeType]: typeint=_winreg.REG_SZ elif type( data )==IntType: typeint=_winreg.REG_DWORD elif type( data )==array.ArrayType: typeint=_winreg.REG_BINARY data=data.tostring() _winreg.SetValueEx( self.handle, valname, 0, typeint, data )
| 13,461
|
def setValue( self, valname, data, regtype=None ): "Set a data value's data (and optionally type)" if regtype: typeint=regtype.intval else: if type( data )==StringType: typeint=_winreg.REG_SZ elif type( data )==IntType: typeint=_winreg.REG_DWORD elif type( data )==array.ArrayType: typeint=_winreg.REG_BINARY data=data.tostring() _winreg.SetValueEx( self.handle, valname, 0, typeint, data )
|
def setValue( self, valname, data, regtype=None ): "Set a data value's data (and optionally type)" if regtype: typeint=regtype.intval else: if type( data )==StringType: typeint=_winreg.REG_SZ elif type( data )==IntType: typeint=_winreg.REG_DWORD elif type( data )==array.ArrayType: typeint=_winreg.REG_BINARY _winreg.SetValueEx( self.handle, valname, 0, typeint, data )
| 13,462
|
def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2 and no funny (non-leap century) years.""" return (y2+3)/4 - (y1+3)/4
|
def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2 and no funny (non-leap century) years.""" return (y2+3)/4 - (y1+3)/4
| 13,463
|
def weekday(year, month, day): """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31).""" secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0)) tuple = localtime(secs) return tuple[6]
|
def weekday(year, month, day): """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12), day (1-31).""" secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0)) tuple = localtime(secs) return tuple[6]
| 13,464
|
def monthrange(year, month): """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.""" if not 1 <= month <= 12: raise ValueError, 'bad month number' day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays
|
def monthrange(year, month): """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.""" if not 1 <= month <= 12: raise ValueError, 'bad month number' day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays
| 13,465
|
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
|
def monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
| 13,466
|
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
|
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
| 13,467
|
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
|
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = (_firstweekday - day1 + 6) % 7 - 5 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
| 13,468
|
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
|
def _monthcalendar(year, month): """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.""" day1, ndays = monthrange(year, month) rows = [] r7 = range(7) day = 1 - day1 while day <= ndays: row = [0, 0, 0, 0, 0, 0, 0] for i in r7: if 1 <= day <= ndays: row[i] = day day = day + 1 rows.append(row) return rows
| 13,469
|
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
|
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
| 13,470
|
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
|
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
| 13,471
|
def prweek(week, width): """Print a single week (no newline).""" for day in week: if day == 0: s = '' else: s = `day` print _center(s, width),
|
def prweek(week, width): """Print a single week (no newline).""" print week(theweek, width), def week(theweek, width): """Returns a single week in a string (no newline).""" days = [] for day in theweek: if day == 0: s = '' else: s = '%2i' % day days.append(_center(s, width)) return ' '.join(days)
| 13,472
|
def weekheader(width): """Return a header for a week.""" str = '' if width >= 9: names = day_name else: names = day_abbr for i in range(7): if str: str = str + ' ' str = str + _center(names[i%7][:width], width) return str
|
def weekheader(width): """Return a header for a week.""" str = '' if width >= 9: names = day_name else: names = day_abbr for i in range(7): if str: str = str + ' ' str = str + _center(names[i%7][:width], width) return str
| 13,473
|
def prmonth(year, month, w = 0, l = 0): """Print a month's calendar.""" w = max(2, w) l = max(1, l) print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print '\n'*l, print weekheader(w), print '\n'*l, for week in monthcalendar(year, month): prweek(week, w) print '\n'*l,
|
def prmonth(year, month, w = 0, l = 0): """Print a month's calendar.""" w = max(2, w) l = max(1, l) print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print '\n'*l, print weekheader(w), print '\n'*l, for week in monthcalendar(year, month): prweek(week, w) print '\n'*l,
| 13,474
|
def prmonth(year, month, w = 0, l = 0): """Print a month's calendar.""" w = max(2, w) l = max(1, l) print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print '\n'*l, print weekheader(w), print '\n'*l, for week in monthcalendar(year, month): prweek(week, w) print '\n'*l,
|
def prmonth(year, month, w = 0, l = 0): """Print a month's calendar.""" w = max(2, w) l = max(1, l) print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print '\n'*l, print weekheader(w), print '\n'*l, for week in monthcalendar(year, month): prweek(week, w) print '\n'*l,
| 13,475
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
|
def prcal(year): """Print a year's calendar.""" print calendar(year, w, l, c), def calendar(year, w=0, l=0, c=_spacing): """Returns a year's calendar as a multi-line string.""" w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip() for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
| 13,476
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): s = (s + '\n' * l + format3cstring(month_name[q], month_name[q+1], month_name[q+2], colwidth, c).rstrip() + '\n' * l + header + '\n' * l) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
| 13,477
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for amonth in range(q, q + 3): cal = monthcalendar(year, amonth) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
| 13,478
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): weeks.append('') else: prweek(cal[i], 2) print _spacing, print
| 13,479
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: prweek(cal[i], 2) print _spacing, print
|
def prcal(year): """Print a year's calendar.""" header = weekheader(2) format3c('', `year`, '') for q in range(January, January+12, 3): print format3c(month_name[q], month_name[q+1], month_name[q+2]) format3c(header, header, header) data = [] height = 0 for month in range(q, q+3): cal = monthcalendar(year, month) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): for cal in data: if i >= len(cal): print ' '*_colwidth, else: weeks.append(week(cal[i], w)) s = s + format3cstring(weeks[0], weeks[1], weeks[2], colwidth, c).rstrip() + '\n' * l return s[:-l] + '\n'
| 13,480
|
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
|
def loop(timeout=30.0, use_poll=False, map=None, count=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
| 13,481
|
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll while map: poll_fun(timeout, map)
|
def loop(timeout=30.0, use_poll=False, map=None): if map is None: map = socket_map if use_poll and hasattr(select, 'poll'): poll_fun = poll2 else: poll_fun = poll if count is None: while map: poll_fun(timeout, map) else: while map and count > 0: poll_fun(timeout, map) count = count - 1
| 13,482
|
def failUnlessEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '!=' operator. """ if first != second: raise self.failureException, \ (msg or '%s != %s' % (`first`, `second`))
|
def failUnlessEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ if first != second: raise self.failureException, \ (msg or '%s != %s' % (`first`, `second`))
| 13,483
|
def failUnlessEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '!=' operator. """ if first != second: raise self.failureException, \ (msg or '%s != %s' % (`first`, `second`))
|
def failUnlessEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '!=' operator. """ if not first == second: raise self.failureException, \ (msg or '%s != %s' % (`first`, `second`))
| 13,484
|
def script_from_examples(s): r"""Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum """ output = [] for piece in DocTestParser().parse(s): if isinstance(piece, Example): # Add the example's source code (strip trailing NL) output.append(piece.source[:-1]) # Add the expected output: want = piece.want if want: output.append('# Expected:') output += ['## '+l for l in want.split('\n')[:-1]] else: # Add non-example text. output += [_comment_line(l) for l in piece.split('\n')[:-1]] # Trim junk on both ends. while output and output[-1] == '#': output.pop() while output and output[0] == '#': output.pop(0) # Combine the output, and return it. return '\n'.join(output)
|
def script_from_examples(s): r"""Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum """ output = [] for piece in DocTestParser().parse(s): if isinstance(piece, Example): # Add the example's source code (strip trailing NL) output.append(piece.source[:-1]) # Add the expected output: want = piece.want if want: output.append('# Expected:') output += ['## '+l for l in want.split('\n')[:-1]] else: # Add non-example text. output += [_comment_line(l) for l in piece.split('\n')[:-1]] # Trim junk on both ends. while output and output[-1] == '#': output.pop() while output and output[0] == '#': output.pop(0) # Combine the output, and return it. return '\n'.join(output) + '\n'
| 13,485
|
def make_gui(self): pyshell = self.pyshell self.flist = pyshell.flist self.root = root = pyshell.root self.top = top =ListedToplevel(root) self.top.wm_title("Debug Control") self.top.wm_iconname("Debug") top.wm_protocol("WM_DELETE_WINDOW", self.close) self.top.bind("<Escape>", self.close) # self.bframe = bframe = Frame(top) self.bframe.pack(anchor="w") self.buttons = bl = [] # self.bcont = b = Button(bframe, text="Go", command=self.cont) bl.append(b) self.bstep = b = Button(bframe, text="Step", command=self.step) bl.append(b) self.bnext = b = Button(bframe, text="Over", command=self.next) bl.append(b) self.bret = b = Button(bframe, text="Out", command=self.ret) bl.append(b) self.bret = b = Button(bframe, text="Quit", command=self.quit) bl.append(b) # for b in bl: b.configure(state="disabled") b.pack(side="left") # self.cframe = cframe = Frame(bframe) self.cframe.pack(side="left") # if not self.vstack: self.__class__.vstack = BooleanVar(top) self.vstack.set(1) self.bstack = Checkbutton(cframe, text="Stack", command=self.show_stack, variable=self.vstack) self.bstack.grid(row=0, column=0) if not self.vsource: self.__class__.vsource = BooleanVar(top) ##self.vsource.set(1) self.bsource = Checkbutton(cframe, text="Source", command=self.show_source, variable=self.vsource) self.bsource.grid(row=0, column=1) if not self.vlocals: self.__class__.vlocals = BooleanVar(top) self.vlocals.set(1) self.blocals = Checkbutton(cframe, text="Locals", command=self.show_locals, variable=self.vlocals) self.blocals.grid(row=1, column=0) if not self.vglobals: self.__class__.vglobals = BooleanVar(top) ##self.vglobals.set(1) self.bglobals = Checkbutton(cframe, text="Globals", command=self.show_globals, variable=self.vglobals) self.bglobals.grid(row=1, column=1) # self.status = Label(top, anchor="w") self.status.pack(anchor="w") self.error = Label(top, anchor="w") self.error.pack(anchor="w", fill="x") self.errorbg = self.error.cget("background") # self.fstack = Frame(top, height=1) self.fstack.pack(expand=1, fill="both") self.flocals = Frame(top) self.flocals.pack(expand=1, fill="both") self.fglobals = Frame(top, height=1) self.fglobals.pack(expand=1, fill="both") # if self.vstack.get(): self.show_stack() if self.vlocals.get(): self.show_locals() if self.vglobals.get(): self.show_globals()
|
defmake_gui(self):pyshell=self.pyshellself.flist=pyshell.flistself.root=root=pyshell.rootself.top=top=ListedToplevel(root)self.top.wm_title("DebugControl")self.top.wm_iconname("Debug")top.wm_protocol("WM_DELETE_WINDOW",self.close)self.top.bind("<Escape>",self.close)#self.bframe=bframe=Frame(top)self.bframe.pack(anchor="w")self.buttons=bl=[]#self.bcont=b=Button(bframe,text="Go",command=self.cont)bl.append(b)self.bstep=b=Button(bframe,text="Step",command=self.step)bl.append(b)self.bnext=b=Button(bframe,text="Over",command=self.next)bl.append(b)self.bret=b=Button(bframe,text="Out",command=self.ret)bl.append(b)self.bret=b=Button(bframe,text="Quit",command=self.quit)bl.append(b)#forbinbl:b.configure(state="disabled")b.pack(side="left")#self.cframe=cframe=Frame(bframe)self.cframe.pack(side="left")#ifnotself.vstack:self.__class__.vstack=BooleanVar(top)self.vstack.set(1)self.bstack=Checkbutton(cframe,text="Stack",command=self.show_stack,variable=self.vstack)self.bstack.grid(row=0,column=0)ifnotself.vsource:self.__class__.vsource=BooleanVar(top)##self.vsource.set(1)self.bsource=Checkbutton(cframe,text="Source",command=self.show_source,variable=self.vsource)self.bsource.grid(row=0,column=1)ifnotself.vlocals:self.__class__.vlocals=BooleanVar(top)self.vlocals.set(1)self.blocals=Checkbutton(cframe,text="Locals",command=self.show_locals,variable=self.vlocals)self.blocals.grid(row=1,column=0)ifnotself.vglobals:self.__class__.vglobals=BooleanVar(top)##self.vglobals.set(1)self.bglobals=Checkbutton(cframe,text="Globals",command=self.show_globals,variable=self.vglobals)self.bglobals.grid(row=1,column=1)#self.status=Label(top,anchor="w")self.status.pack(anchor="w")self.error=Label(top,anchor="w")self.error.pack(anchor="w",fill="x")self.errorbg=self.error.cget("background")#self.fstack=Frame(top,height=1)self.fstack.pack(expand=1,fill="both")self.flocals=Frame(top)self.flocals.pack(expand=1,fill="both")self.fglobals=Frame(top,height=1)self.fglobals.pack(expand=1,fill="both")#ifself.vstack.get():self.show_stack()ifself.vlocals.get():self.show_locals()ifself.vglobals.get():self.show_globals()
| 13,486
|
def make_gui(self): pyshell = self.pyshell self.flist = pyshell.flist self.root = root = pyshell.root self.top = top =ListedToplevel(root) self.top.wm_title("Debug Control") self.top.wm_iconname("Debug") top.wm_protocol("WM_DELETE_WINDOW", self.close) self.top.bind("<Escape>", self.close) # self.bframe = bframe = Frame(top) self.bframe.pack(anchor="w") self.buttons = bl = [] # self.bcont = b = Button(bframe, text="Go", command=self.cont) bl.append(b) self.bstep = b = Button(bframe, text="Step", command=self.step) bl.append(b) self.bnext = b = Button(bframe, text="Over", command=self.next) bl.append(b) self.bret = b = Button(bframe, text="Out", command=self.ret) bl.append(b) self.bret = b = Button(bframe, text="Quit", command=self.quit) bl.append(b) # for b in bl: b.configure(state="disabled") b.pack(side="left") # self.cframe = cframe = Frame(bframe) self.cframe.pack(side="left") # if not self.vstack: self.__class__.vstack = BooleanVar(top) self.vstack.set(1) self.bstack = Checkbutton(cframe, text="Stack", command=self.show_stack, variable=self.vstack) self.bstack.grid(row=0, column=0) if not self.vsource: self.__class__.vsource = BooleanVar(top) ##self.vsource.set(1) self.bsource = Checkbutton(cframe, text="Source", command=self.show_source, variable=self.vsource) self.bsource.grid(row=0, column=1) if not self.vlocals: self.__class__.vlocals = BooleanVar(top) self.vlocals.set(1) self.blocals = Checkbutton(cframe, text="Locals", command=self.show_locals, variable=self.vlocals) self.blocals.grid(row=1, column=0) if not self.vglobals: self.__class__.vglobals = BooleanVar(top) ##self.vglobals.set(1) self.bglobals = Checkbutton(cframe, text="Globals", command=self.show_globals, variable=self.vglobals) self.bglobals.grid(row=1, column=1) # self.status = Label(top, anchor="w") self.status.pack(anchor="w") self.error = Label(top, anchor="w") self.error.pack(anchor="w", fill="x") self.errorbg = self.error.cget("background") # self.fstack = Frame(top, height=1) self.fstack.pack(expand=1, fill="both") self.flocals = Frame(top) self.flocals.pack(expand=1, fill="both") self.fglobals = Frame(top, height=1) self.fglobals.pack(expand=1, fill="both") # if self.vstack.get(): self.show_stack() if self.vlocals.get(): self.show_locals() if self.vglobals.get(): self.show_globals()
|
defmake_gui(self):pyshell=self.pyshellself.flist=pyshell.flistself.root=root=pyshell.rootself.top=top=ListedToplevel(root)self.top.wm_title("DebugControl")self.top.wm_iconname("Debug")top.wm_protocol("WM_DELETE_WINDOW",self.close)self.top.bind("<Escape>",self.close)#self.bframe=bframe=Frame(top)self.bframe.pack(anchor="w")self.buttons=bl=[]#self.bcont=b=Button(bframe,text="Go",command=self.cont)bl.append(b)self.bstep=b=Button(bframe,text="Step",command=self.step)bl.append(b)self.bnext=b=Button(bframe,text="Over",command=self.next)bl.append(b)self.bret=b=Button(bframe,text="Out",command=self.ret)bl.append(b)self.bret=b=Button(bframe,text="Quit",command=self.quit)bl.append(b)#forbinbl:b.configure(state="disabled")b.pack(side="left")#self.cframe=cframe=Frame(bframe)self.cframe.pack(side="left")#ifnotself.vstack:self.__class__.vstack=BooleanVar(top)self.vstack.set(1)self.bstack=Checkbutton(cframe,text="Stack",command=self.show_stack,variable=self.vstack)self.bstack.grid(row=0,column=0)ifnotself.vsource:self.__class__.vsource=BooleanVar(top)##self.vsource.set(1)self.bsource=Checkbutton(cframe,text="Source",command=self.show_source,variable=self.vsource)self.bsource.grid(row=0,column=1)ifnotself.vlocals:self.__class__.vlocals=BooleanVar(top)self.vlocals.set(1)self.blocals=Checkbutton(cframe,text="Locals",command=self.show_locals,variable=self.vlocals)self.blocals.grid(row=1,column=0)ifnotself.vglobals:self.__class__.vglobals=BooleanVar(top)##self.vglobals.set(1)self.bglobals=Checkbutton(cframe,text="Globals",command=self.show_globals,variable=self.vglobals)self.bglobals.grid(row=1,column=1)#self.status=Label(top,anchor="w")self.status.pack(anchor="w")self.error=Label(top,anchor="w")self.error.pack(anchor="w",fill="x")self.errorbg=self.error.cget("background")#self.fstack=Frame(top,height=1)self.fstack.pack(expand=1,fill="both")self.flocals=Frame(top)self.flocals.pack(expand=1,fill="both")self.fglobals=Frame(top,height=1)self.fglobals.pack(expand=1,fill="both")#ifself.vstack.get():self.show_stack()ifself.vlocals.get():self.show_locals()ifself.vglobals.get():self.show_globals()
| 13,487
|
def set_breakpoint_here(self, filename, lineno): msg = self.idb.set_break(filename, lineno) if msg: text.bell() return
|
def set_breakpoint_here(self, filename, lineno): msg = self.idb.set_break(filename, lineno) if msg: text.bell() return
| 13,488
|
def clear_breakpoint_here(self, filename, lineno): msg = self.idb.clear_break(filename, lineno) if msg: text.bell() return
|
def clear_breakpoint_here(self, filename, lineno): msg = self.idb.clear_break(filename, lineno) if msg: text.bell() return
| 13,489
|
def clear_file_breaks(self, filename): msg = self.idb.clear_all_file_breaks(filename) if msg: text.bell() return
|
def clear_file_breaks(self, filename): msg = self.idb.clear_all_file_breaks(filename) if msg: text.bell() return
| 13,490
|
def load_dict(self, dict, force=0, rpc_client=None): if dict is self.dict and not force: return subframe = self.subframe frame = self.frame for c in subframe.children.values(): c.destroy() self.dict = None if not dict: l = Label(subframe, text="None") l.grid(row=0, column=0) else: names = dict.keys() names.sort() row = 0 for name in names: value = dict[name] svalue = self.repr.repr(value) # repr(value) # Strip extra quotes caused by calling repr on the (already) # repr'd value sent across the RPC interface: if rpc_client: svalue = svalue[1:-1] l = Label(subframe, text=name) l.grid(row=row, column=0, sticky="nw")
|
defload_dict(self,dict,force=0,rpc_client=None):ifdictisself.dictandnotforce:returnsubframe=self.subframeframe=self.frameforcinsubframe.children.values():c.destroy()self.dict=Noneifnotdict:l=Label(subframe,text="None")l.grid(row=0,column=0)else:names=dict.keys()names.sort()row=0fornameinnames:value=dict[name]svalue=self.repr.repr(value)#repr(value)#Stripextraquotescausedbycallingrepronthe(already)#repr'dvaluesentacrosstheRPCinterface:ifrpc_client:svalue=svalue[1:-1]l=Label(subframe,text=name)l.grid(row=row,column=0,sticky="nw")
| 13,491
|
def load_dict(self, dict, force=0, rpc_client=None): if dict is self.dict and not force: return subframe = self.subframe frame = self.frame for c in subframe.children.values(): c.destroy() self.dict = None if not dict: l = Label(subframe, text="None") l.grid(row=0, column=0) else: names = dict.keys() names.sort() row = 0 for name in names: value = dict[name] svalue = self.repr.repr(value) # repr(value) # Strip extra quotes caused by calling repr on the (already) # repr'd value sent across the RPC interface: if rpc_client: svalue = svalue[1:-1] l = Label(subframe, text=name) l.grid(row=row, column=0, sticky="nw")
|
defload_dict(self,dict,force=0,rpc_client=None):ifdictisself.dictandnotforce:returnsubframe=self.subframeframe=self.frameforcinsubframe.children.values():c.destroy()self.dict=Noneifnotdict:l=Label(subframe,text="None")l.grid(row=0,column=0)else:names=dict.keys()names.sort()row=0fornameinnames:value=dict[name]svalue=self.repr.repr(value)#repr(value)#Stripextraquotescausedbycallingrepronthe(already)#repr'dvaluesentacrosstheRPCinterface:ifrpc_client:svalue=svalue[1:-1]l=Label(subframe,text=name)l.grid(row=row,column=0,sticky="nw")
| 13,492
|
def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH, dbenv=None, dbname=None): """ A simple factory function for compatibility with the standard shleve.py module. It can be used like this, where key is a string and data is a pickleable object: from bsddb import dbshelve db = dbshelve.open(filename) db[key] = data db.close() """ if type(flags) == type(''): sflag = flags if sflag == 'r': flags = db.DB_RDONLY elif sflag == 'rw': flags = 0 elif sflag == 'w': flags = db.DB_CREATE elif sflag == 'c': flags = db.DB_CREATE elif sflag == 'n': flags = db.DB_TRUNCATE | db.DB_CREATE else: raise error, "flags should be one of 'r', 'w', 'c' or 'n' or use the bsddb.db.DB_* flags" d = DBShelf(dbenv) d.open(filename, dbname, filetype, flags, mode) return d
|
def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH, dbenv=None, dbname=None): """ A simple factory function for compatibility with the standard shleve.py module. It can be used like this, where key is a string and data is a pickleable object: from bsddb import dbshelve db = dbshelve.open(filename) db[key] = data db.close() """ if type(flags) == type(''): sflag = flags if sflag == 'r': flags = db.DB_RDONLY elif sflag == 'rw': flags = 0 elif sflag == 'w': flags = db.DB_CREATE elif sflag == 'c': flags = db.DB_CREATE elif sflag == 'n': flags = db.DB_TRUNCATE | db.DB_CREATE else: raise db.DBError, "flags should be one of 'r', 'w', 'c' or 'n' or use the bsddb.db.DB_* flags" d = DBShelf(dbenv) d.open(filename, dbname, filetype, flags, mode) return d
| 13,493
|
def append(self, value, txn=None): data = cPickle.dumps(value, self.binary) return self.db.append(data, txn)
|
def append(self, value, txn=None): data = cPickle.dumps(value, self.binary) return self.db.append(data, txn)
| 13,494
|
def export_add(self, x, y): return x + y
|
def export_add(self, x, y): return x + y
| 13,495
|
def __repr__(self): return "AugAssign(%s, %s, %s)" % (repr(self.node), repr(self.op), repr(self.expr))
|
def __repr__(self): return "AugAssign(%s, %s, %s)" % (repr(self.node), repr(self.op), repr(self.expr))
| 13,496
|
def __init__(self, host = '', port = 0, local_hostname = None): """Initialize a new instance.
|
def __init__(self, host = '', port = 0, local_hostname = None): """Initialize a new instance.
| 13,497
|
def __init__(self, host = '', port = 0, local_hostname = None): """Initialize a new instance.
|
def __init__(self, host = '', port = 0, local_hostname = None): """Initialize a new instance.
| 13,498
|
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings (???) containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found. (XXX is this correct???)""" try: import win32api import win32con except ImportError: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (win32con.HKEY_CLASSES_ROOT, win32con.HKEY_LOCAL_MACHINE, win32con.HKEY_CURRENT_USER, win32con.HKEY_USERS): try: k = win32api.RegOpenKeyEx(base,K) i = 0 while 1: try: p = win32api.RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except win32api.error: break i = i + 1 except win32api.error: pass L.sort() L.reverse() return L
|
defget_devstudio_versions():"""GetlistofdevstudioversionsfromtheWindowsregistry.Returnalistofstrings(???)containingversionnumbers;thelistwillbeemptyifwewereunabletoaccesstheregistry(eg.couldn'timportaregistry-accessmodule)ortheappropriateregistrykeysweren'tfound.(XXXisthiscorrect???)"""try:importwin32apiimportwin32conexceptImportError:return[]K='Software\\Microsoft\\Devstudio'L=[]forbasein(win32con.HKEY_CLASSES_ROOT,win32con.HKEY_LOCAL_MACHINE,win32con.HKEY_CURRENT_USER,win32con.HKEY_USERS):try:k=win32api.RegOpenKeyEx(base,K)i=0while1:try:p=win32api.RegEnumKey(k,i)ifp[0]in'123456789'andpnotinL:L.append(p)exceptwin32api.error:breaki=i+1exceptwin32api.error:passL.sort()L.reverse()returnL
| 13,499
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.