rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
Message("Thank you,\n%s" % `s`)
s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None") if not s2: Message("%s has no secret nickname"%s) else: Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2))
def test(): import time Message("Testing EasyDialogs.") ok = AskYesNoCancel("Do you want to proceed?") ok = AskYesNoCancel("Do you want to identify?", yes="Indentify", no="Don't identify") if ok > 0: s = AskString("Enter your first name", "Joe") Message("Thank you,\n%s" % `s`) text = ( "Working Hard...", "Hardly Working..." , "So far, so good!", "Keep on truckin'" ) bar = ProgressBar("Progress, progress...", 100) try: appsw = MacOS.SchedParams(1, 0) for i in range(100): bar.set(i) time.sleep(0.1) if i % 10 == 0: bar.label(text[(i/10) % 4]) bar.label("Done.") time.sleep(0.3) # give'em a chance to see the done. finally: del bar apply(MacOS.SchedParams, appsw)
if not _urandomfd:
if _urandomfd is None:
def urandom(n): """urandom(n) -> str
pos = [-42] def negposreturn(exc): pos[0] += 1 return (u"?", pos[0]) codecs.register_error("test.negposreturn", negposreturn) "\xff".decode("ascii", "test.negposreturn") def hugeposreturn(exc): return (u"?", 424242) codecs.register_error("test.hugeposreturn", hugeposreturn) "\xff".decode("ascii", "test.hugeposreturn") "\\uyyyy".decode("raw-unicode-escape", "test.hugeposreturn")
handler = PosReturn() codecs.register_error("test.posreturn", handler.handle) handler.pos = -1 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0") handler.pos = -2 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?><?>") handler.pos = -3 self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn") handler.pos = 1 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0") handler.pos = 2 self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>") handler.pos = 3 self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn") handler.pos = 6 self.assertEquals("\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), u"<?>0")
def baddecodereturn2(exc): return (u"?", None)
pos = [-42] def negposreturn(exc): pos[0] += 1 return (u"?", pos[0]) codecs.register_error("test.negposreturn", negposreturn) u"\xff".encode("ascii", "test.negposreturn") def hugeposreturn(exc): return (u"?", 424242) codecs.register_error("test.hugeposreturn", hugeposreturn) u"\xff".encode("ascii", "test.hugeposreturn")
handler = PosReturn() codecs.register_error("test.posreturn", handler.handle) handler.pos = -1 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0") handler.pos = -2 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?><?>") handler.pos = -3 self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn") handler.pos = 1 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0") handler.pos = 2 self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>") handler.pos = 3 self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn") handler.pos = 0
def badencodereturn2(exc): return (u"?", None)
for err in ("strict", "replace", "xmlcharrefreplace", "backslashreplace", "test.hugeposreturn"):
for err in ("strict", "replace", "xmlcharrefreplace", "backslashreplace", "test.posreturn"):
def __getitem__(self, key): raise ValueError
class String: x = '' def __str__(self): return self.x o = String() o.x = 'abc' verify(unicode(o) == u'abc') verify(str(o) == 'abc') o.x = u'abc' verify(unicode(o) == u'abc') verify(str(o) == 'abc') for obj in (123, 123.45, 123L): verify(unicode(obj) == unicode(str(obj)))
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2)
if c == ESCAPE: return ESCAPE * 2 else: i = ord(c) return ESCAPE + HEX[i/16] + HEX[i%16]
i = ord(c) return ESCAPE + HEX[i/16] + HEX[i%16]
def quote(c): """Quote a single character.""" if c == ESCAPE: return ESCAPE * 2 else: i = ord(c) return ESCAPE + HEX[i/16] + HEX[i%16]
""+ _LegalCharsPatt +"+"
""+ _LegalCharsPatt +"+?"
def OutputString(self, attrs=None): # Build up our result # result = [] RA = result.append
if sys.platform == 'win32':
if sys.platform == 'win32' or sys.platform.startswith('os2'):
def getpager(): """Decide what method to use for paging through text.""" if type(sys.stdout) is not types.FileType: return plainpager if not sys.stdin.isatty() or not sys.stdout.isatty(): return plainpager if os.environ.get('TERM') in ['dumb', 'emacs']: return plainpager if os.environ.has_key('PAGER'): if sys.platform == 'win32': # pipes completely broken in Windows return lambda text: tempfilepager(plain(text), os.environ['PAGER']) elif os.environ.get('TERM') in ['dumb', 'emacs']: return lambda text: pipepager(plain(text), os.environ['PAGER']) else: return lambda text: pipepager(text, os.environ['PAGER']) if sys.platform == 'win32': return lambda text: tempfilepager(plain(text), 'more <') if hasattr(os, 'system') and os.system('less 2>/dev/null') == 0: return lambda text: pipepager(text, 'less') import tempfile filename = tempfile.mktemp() open(filename, 'w').close() try: if hasattr(os, 'system') and os.system('more %s' % filename) == 0: return lambda text: pipepager(text, 'more') else: return ttypager finally: os.unlink(filename)
initialcolor = None,
def __init__(self, master = None, initialcolor = None, databasefile = None, initfile = None, ignore = None, wantspec = None): self.__master = master self.__initialcolor = initialcolor self.__databasefile = databasefile self.__initfile = initfile or os.path.expanduser('~/.pynche') self.__ignore = ignore self.__pw = None self.__wantspec = wantspec
self.__initialcolor = initialcolor
def __init__(self, master = None, initialcolor = None, databasefile = None, initfile = None, ignore = None, wantspec = None): self.__master = master self.__initialcolor = initialcolor self.__databasefile = databasefile self.__initfile = initfile or os.path.expanduser('~/.pynche') self.__ignore = ignore self.__pw = None self.__wantspec = wantspec
def show(self):
def show(self, color=None): if not self.__master: from Tkinter import Tk self.__master = Tk()
def show(self): if not self.__pw: self.__pw, self.__sb = \ Main.build(master = self.__master, initialcolor = self.__initialcolor, initfile = self.__initfile, ignore = self.__ignore) Main.run(self.__pw, self.__sb) rgbtuple = self.__sb.current_rgb() self.__pw.withdraw() # check to see if the cancel button was pushed if self.__sb.canceled_p(): return None, None colordb = self.__sb.colordb() # try to return the color name from the database if there is an exact # match, otherwise use the "#rrggbb" spec. TBD: Forget about color # aliases for now, maybe later we should return these too. name = None if not self.__wantspec: try: name = colordb.find_byrgb(rgbtuple)[0] except ColorDB.BadColor: pass if name is None: name = ColorDB.triplet_to_rrggbb(rgbtuple) return rgbtuple, name
initialcolor = self.__initialcolor,
def show(self): if not self.__pw: self.__pw, self.__sb = \ Main.build(master = self.__master, initialcolor = self.__initialcolor, initfile = self.__initfile, ignore = self.__ignore) Main.run(self.__pw, self.__sb) rgbtuple = self.__sb.current_rgb() self.__pw.withdraw() # check to see if the cancel button was pushed if self.__sb.canceled_p(): return None, None colordb = self.__sb.colordb() # try to return the color name from the database if there is an exact # match, otherwise use the "#rrggbb" spec. TBD: Forget about color # aliases for now, maybe later we should return these too. name = None if not self.__wantspec: try: name = colordb.find_byrgb(rgbtuple)[0] except ColorDB.BadColor: pass if name is None: name = ColorDB.triplet_to_rrggbb(rgbtuple) return rgbtuple, name
colordb = self.__sb.colordb()
def show(self): if not self.__pw: self.__pw, self.__sb = \ Main.build(master = self.__master, initialcolor = self.__initialcolor, initfile = self.__initfile, ignore = self.__ignore) Main.run(self.__pw, self.__sb) rgbtuple = self.__sb.current_rgb() self.__pw.withdraw() # check to see if the cancel button was pushed if self.__sb.canceled_p(): return None, None colordb = self.__sb.colordb() # try to return the color name from the database if there is an exact # match, otherwise use the "#rrggbb" spec. TBD: Forget about color # aliases for now, maybe later we should return these too. name = None if not self.__wantspec: try: name = colordb.find_byrgb(rgbtuple)[0] except ColorDB.BadColor: pass if name is None: name = ColorDB.triplet_to_rrggbb(rgbtuple) return rgbtuple, name
return apply(Chooser, (), options).show()
global _chooser if not _chooser: _chooser = apply(Chooser, (), options) return _chooser.show(color)
def askcolor(color = None, **options): """Ask for a color""" return apply(Chooser, (), options).show()
exts.append( Extension('_locale', ['_localemodule.c']) )
if platform in ['cygwin']: locale_libs = ['intl'] else: locale_libs = [] exts.append( Extension('_locale', ['_localemodule.c'], libraries=locale_libs ) )
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
if sys.platform == 'darwin' and g.has_key('CONFIGURE_MACOSX_DEPLOYMENT_TARGET'): cfg_target = g['CONFIGURE_MACOSX_DEPLOYMENT_TARGET'] cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '') if cfg_target != cur_target: my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure' % (cur_target, cfg_target)) raise DistutilsPlatformError(my_msg)
def _init_posix(): """Initialize the module as appropriate for POSIX systems.""" g = {} # load the installed Makefile: try: filename = get_makefile_filename() parse_makefile(filename, g) except IOError, msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror raise DistutilsPlatformError(my_msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if python_build: g['LDSHARED'] = g['BLDSHARED'] elif sys.version < '2.1': # The following two branches are for 1.5.2 compatibility. if sys.platform == 'aix4': # what about AIX 3.x ? # Linker script is in the config directory, not in Modules as the # Makefile says. python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp) elif sys.platform == 'beos': # Linker script is in the config directory. In the Makefile it is # relative to the srcdir, which after installation no longer makes # sense. python_lib = get_python_lib(standard_lib=1) linkerscript_path = string.split(g['LDSHARED'])[0] linkerscript_name = os.path.basename(linkerscript_path) linkerscript = os.path.join(python_lib, 'config', linkerscript_name) # XXX this isn't the right place to do this: adding the Python # library to the link, if needed, should be in the "build_ext" # command. (It's also needed for non-MS compilers on Windows, and # it's taken care of for them by the 'build_ext.get_libraries()' # method.) g['LDSHARED'] = ("%s -L%s/lib -lpython%s" % (linkerscript, PREFIX, sys.version[0:3])) global _config_vars _config_vars = g
rounding = context.rounding
def __pow__(self, n, modulo = None, context=None): """Return self ** n (mod modulo)
shouldround = context._rounding_decision == ALWAYS_ROUND
def __pow__(self, n, modulo = None, context=None): """Return self ** n (mod modulo)
if shouldround:
if context._rounding_decision == ALWAYS_ROUND:
def __pow__(self, n, modulo = None, context=None): """Return self ** n (mod modulo)
out = 0
def _rescale(self, exp, rounding=None, context=None, watchexp=1): """Rescales so that the exponent is exp.
prevexact = context.flags[Inexact]
def _rescale(self, exp, rounding=None, context=None, watchexp=1): """Rescales so that the exponent is exp.
count = 1
def sqrt(self, context=None): """Return the square root of self.
context._rounding_decision == ALWAYS_ROUND return ans._fix(context)
if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans
def max(self, other, context=None): """Returns the larger value.
context._rounding_decision == ALWAYS_ROUND return ans._fix(context)
if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans
def min(self, other, context=None): """Returns the smaller value.
if c not in '123': raise error_proto, resp return resp
raise error_proto, resp
def getresp(self): resp = self.getmultiline() if self.debugging: print '*resp*', self.sanitize(resp) self.lastresp = resp[:3] c = resp[:1] if c == '4': raise error_temp, resp if c == '5': raise error_perm, resp if c not in '123': raise error_proto, resp return resp
if resp[:3] <> '229':
if resp[:3] != '229':
def parse229(resp, peer): '''Parse the '229' response for a EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] <> '229': raise error_reply, resp left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp # should contain '(|||port|)' if resp[left + 1] <> resp[right - 1]: raise error_proto, resp parts = resp[left + 1:right].split(resp[left+1]) if len(parts) <> 5: raise error_proto, resp host = peer[0] port = int(parts[3]) return host, port
if resp[left + 1] <> resp[right - 1]:
if resp[left + 1] != resp[right - 1]:
def parse229(resp, peer): '''Parse the '229' response for a EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] <> '229': raise error_reply, resp left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp # should contain '(|||port|)' if resp[left + 1] <> resp[right - 1]: raise error_proto, resp parts = resp[left + 1:right].split(resp[left+1]) if len(parts) <> 5: raise error_proto, resp host = peer[0] port = int(parts[3]) return host, port
if len(parts) <> 5:
if len(parts) != 5:
def parse229(resp, peer): '''Parse the '229' response for a EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] <> '229': raise error_reply, resp left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp # should contain '(|||port|)' if resp[left + 1] <> resp[right - 1]: raise error_proto, resp parts = resp[left + 1:right].split(resp[left+1]) if len(parts) <> 5: raise error_proto, resp host = peer[0] port = int(parts[3]) return host, port
Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...'''
Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ... -d dir -l list -p password ''' if len(sys.argv) < 2: print test.__doc__ sys.exit(0)
def test(): '''Test program. Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...''' debugging = 0 rcfile = None while sys.argv[1] == '-d': debugging = debugging+1 del sys.argv[1] if sys.argv[1][:2] == '-r': # get name of alternate ~/.netrc file: rcfile = sys.argv[1][2:] del sys.argv[1] host = sys.argv[1] ftp = FTP(host) ftp.set_debuglevel(debugging) userid = passwd = acct = '' try: netrc = Netrc(rcfile) except IOError: if rcfile is not None: sys.stderr.write("Could not open account file" " -- using anonymous login.") else: try: userid, passwd, acct = netrc.get_account(host) except KeyError: # no account for host sys.stderr.write( "No account -- using anonymous login.") ftp.login(userid, passwd, acct) for file in sys.argv[2:]: if file[:2] == '-l': ftp.dir(file[2:]) elif file[:2] == '-d': cmd = 'CWD' if file[2:]: cmd = cmd + ' ' + file[2:] resp = ftp.sendcmd(cmd) elif file == '-p': ftp.set_pasv(not ftp.passiveserver) else: ftp.retrbinary('RETR ' + file, \ sys.stdout.write, 1024) ftp.quit()
archive_basename = os.path.join(self.bdist_dir, "%s.win32" % fullname)
def run (self): if (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform")
if audioop.lin2ulaw(data[0], 1) != '\377\347\333' or \ audioop.lin2ulaw(data[1], 2) != '\377\377\377' or \ audioop.lin2ulaw(data[2], 4) != '\377\377\377':
if audioop.lin2ulaw(data[0], 1) != '\xff\xe7\xdb' or \ audioop.lin2ulaw(data[1], 2) != '\xff\xff\xff' or \ audioop.lin2ulaw(data[2], 4) != '\xff\xff\xff':
def testlin2ulaw(data): if verbose: print 'lin2ulaw' if audioop.lin2ulaw(data[0], 1) != '\377\347\333' or \ audioop.lin2ulaw(data[1], 2) != '\377\377\377' or \ audioop.lin2ulaw(data[2], 4) != '\377\377\377': return 0 return 1
testme[:42] testme[:42] = "The Answer" del testme[:42]
import sys if sys.platform[:4] != 'java': testme[:42] testme[:42] = "The Answer" del testme[:42] else: print "__getitem__: (slice(0, 42, None),)" print "__setitem__: (slice(0, 42, None), 'The Answer')" print "__delitem__: (slice(0, 42, None),)"
exec """def __%(method)s__(self, *args): print "__%(method)s__:", args
int(testme) long(testme) float(testme) oct(testme) hex(testme)
if sys.platform[:4] != 'java': int(testme) long(testme) float(testme) oct(testme) hex(testme) else: print "__int__: ()" print "__long__: ()" print "__float__: ()" print "__oct__: ()" print "__hex__: ()"
exec """def __%(method)s__(self, *args): print "__%(method)s__:", args
if sys.platform[:4] == 'java': import java java.lang.System.gc()
exec """def __%(method)s__(self, *args): print "__%(method)s__:", args
raise DistutilsFileErorr, \
raise DistutilsFileError, \
def check_package (self, package, package_dir):
if self._debugging > 1: print '*put*', `line`
def _putline(self, line): #if self._debugging > 1: print '*put*', `line` self.sock.send('%s%s' % (line, CRLF))
if self._debugging: print '*cmd*', `line`
def _putcmd(self, line): #if self._debugging: print '*cmd*', `line` self._putline(line)
if self._debugging > 1: print '*get*', `line`
def _getline(self): line = self.file.readline() #if self._debugging > 1: print '*get*', `line` if not line: raise error_proto('-ERR EOF') octets = len(line) # server can send any combination of CR & LF # however, 'readline()' returns lines ending in LF # so only possibilities are ...LF, ...CRLF, CR...LF if line[-2:] == CRLF: return line[:-2], octets if line[0] == CR: return line[1:-1], octets return line[:-1], octets
if self._debugging > 1: print '*resp*', `resp`
def _getresp(self): resp, o = self._getline() #if self._debugging > 1: print '*resp*', `resp` c = resp[:1] if c != '+': raise error_proto(resp) return resp
if self._debugging: print '*stat*', `rets`
def stat(self): """Get mailbox status.
self.assertRaises(OverflowError, xrange, 1e100, 1e101, 1e101)
self.assertRaises(TypeError, xrange, 0.0, 2, 1) self.assertRaises(TypeError, xrange, 1, 2.0, 1) self.assertRaises(TypeError, xrange, 1, 2, 1.0) self.assertRaises(TypeError, xrange, 1e100, 1e101, 1e101)
def test_xrange(self): self.assertEqual(list(xrange(3)), [0, 1, 2]) self.assertEqual(list(xrange(1, 5)), [1, 2, 3, 4]) self.assertEqual(list(xrange(0)), []) self.assertEqual(list(xrange(-3)), []) self.assertEqual(list(xrange(1, 10, 3)), [1, 4, 7]) self.assertEqual(list(xrange(5, -5, -3)), [5, 2, -1, -4])
self.ldflags_shared_debug = [ '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG' ]
if self.__version >= 7: self.ldflags_shared_debug = [ '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG' ] else: self.ldflags_shared_debug = [ '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG' ]
def __init__ (self, verbose=0, dry_run=0, force=0): CCompiler.__init__ (self, verbose, dry_run, force) self.__version = get_build_version() if self.__version >= 7: self.__root = r"Software\Microsoft\VisualStudio" self.__macros = MacroExpander(self.__version) else: self.__root = r"Software\Microsoft\Devstudio" self.__paths = self.get_msvc_paths("path")
return codecs.mbs_encode(input,self.errors)[0]
return codecs.mbcs_encode(input,self.errors)[0]
def encode(self, input, final=False): return codecs.mbs_encode(input,self.errors)[0]
return codecs.mbs_decode(input,self.errors)[0]
return codecs.mbcs_decode(input,self.errors)[0]
def decode(self, input, final=False): return codecs.mbs_decode(input,self.errors)[0]
delimiter string. If maxsplit is given, splits into at most maxsplit words. If sep is not specified, any whitespace string is a separator.
delimiter string. If maxsplit is given, splits at no more than maxsplit places (resulting in at most maxsplit+1 words). If sep is not specified, any whitespace string is a separator.
def split(s, sep=None, maxsplit=-1): """split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, splits into at most maxsplit words. If sep is not specified, any whitespace string is a separator. (split and splitfields are synonymous) """ return s.split(sep, maxsplit)
suffixes_map).
suffix_map).
def guess_type(url): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffixes_map). """ if not inited: init() base, ext = posixpath.splitext(url) while suffix_map.has_key(ext): base, ext = posixpath.splitext(base + suffix_map[ext]) if encodings_map.has_key(ext): encoding = encodings_map[ext] base, ext = posixpath.splitext(base) else: encoding = None if types_map.has_key(ext): return types_map[ext], encoding elif types_map.has_key(string.lower(ext)): return types_map[string.lower(ext)], encoding else: return None, encoding
def __init__(self, sock):
def __init__(self, sock, debuglevel=0):
def __init__(self, sock): self.fp = sock.makefile('rb', 0)
if self.length == 0: self.close()
def begin(self): if self.msg is not None: # we've already started reading the response return
if self.length == 0 or len(s) < amt: self.close()
def read(self, amt=None): if self.fp is None: return ''
response = self.response_class(self.sock)
if self.debuglevel > 0: response = self.response_class(self.sock, self.debuglevel) else: response = self.response_class(self.sock)
def getresponse(self): "Get the response from the server."
"The class no longer supports the debuglevel." pass
self._conn.set_debuglevel(debuglevel)
def set_debuglevel(self, debuglevel): "The class no longer supports the debuglevel." pass
if __debug__: class Foo: version = 1 class Foo: version = 2 class Foo: version = 3 def execfunc(x): exec x in y
def get_namespace(self): """Returns the single namespace bound to this name.
def writeln(self, *args): if args: self.write(*args)
def writeln(self, arg=None): if arg: self.write(arg)
def writeln(self, *args): if args: self.write(*args) self.write('\n') # text-mode streams translate to \r\n if needed
return encode_base64("%s\0%s\0%s" % (user, user, password), eol="")
return encode_base64("\0%s\0%s" % (user, password), eol="")
def encode_plain(user, password): return encode_base64("%s\0%s\0%s" % (user, user, password), eol="")
fp = open(temp_filename, 'wt')
mode = 'w' if sys.platform not in ['cygwin']: mode += 't' fp = open(temp_filename, mode)
def setUp (self): fp = open(temp_filename, 'wt') fp.write(TEST_NETRC) fp.close() self.netrc = netrc.netrc(temp_filename)
del dirs_in_sys_path
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
data = self.rfile.read(int(self.headers["content-length"]))
max_chunk_size = 10*1024*1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L)
def do_POST(self): """Handles the HTTP POST request.
elif _isfunction(v) or _isclass(v):
elif _isfunction(v) or _isclass(v) or _ismethod(v):
def run__test__(self, d, name): """d, name -> Treat dict d like module.__test__.
"dict must be strings, functions "
"dict must be strings, functions, methods, "
def run__test__(self, d, name): """d, name -> Treat dict d like module.__test__.
if verbose: print "compiling string with syntax error"
def test_complex_args(self):
exec 'def f(a, a): pass'
try: compile("1+*3", "filename", "exec") except SyntaxError, detail: if not detail.filename == "filename": raise TestFailed, "expected 'filename', got %r" % detail.filename
def comp_args((a, b)): return a,b self.assertEqual(comp_args((1, 2)), (1, 2))
exec 'def f(a, a): pass'
try: exec 'def f(a = 0, a = 1): pass' raise TestFailed, "duplicate keyword arguments" except SyntaxError: pass
def comp_args((a, b)=(3, 4)): return a, b self.assertEqual(comp_args((1, 2)), (1, 2)) self.assertEqual(comp_args(), (3, 4))
exec 'def f(a, a): pass'
try: exec 'def f(a): global a; a = 1' raise TestFailed, "variable is global and local" except SyntaxError: pass
def comp_args(a, (b, c)): return a, b, c self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
exec 'def f(a = 0, a = 1): pass'
if verbose: print "testing complex args"
def comp_args(a=2, (b, c)=(3, 4)): return a, b, c self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3)) self.assertEqual(comp_args(), (2, 3, 4))
exec 'def f(a): global a; a = 1'
def comp_args((a, b)): print a,b
def test_argument_order(self): try: exec 'def f(a=1, (b, c)): pass' self.fail("non-default args after default") except SyntaxError: pass
def comp_args((a, b)): print a,b
comp_args((1, 2))
def test_float_literals(self): self.assertRaises(SyntaxError, eval, "2e") self.assertRaises(SyntaxError, eval, "2.0e+") self.assertRaises(SyntaxError, eval, "1e-") self.assertRaises(SyntaxError, eval, "3-4e/21")
def comp_args((a, b)): print a,b
def comp_args((a, b)=(3, 4)): print a, b comp_args((1, 2)) comp_args() def comp_args(a, (b, c)): print a, b, c comp_args(1, (2, 3)) def comp_args(a=2, (b, c)=(3, 4)): print a, b, c comp_args(1, (2, 3)) comp_args() try: exec 'def f(a=1, (b, c)): pass' raise TestFailed, "non-default args after default" except SyntaxError: pass if verbose: print "testing bad float literals" def expect_error(s): try: eval(s) raise TestFailed("%r accepted" % s) except SyntaxError: pass expect_error("2e") expect_error("2.0e+") expect_error("1e-") expect_error("3-4e/21") if verbose: print "testing compile() of indented block w/o trailing newline" s = """
def test_indentation(self): s = """
def comp_args((a, b)=(3, 4)): print a, b
compile(s, "<string>", "exec")
compile(s, "<string>", "exec") def test_literals_with_leading_zeroes(self): for arg in ["077787", "0xj", "0x.", "0e", "090000000000000", "080000000000000", "000000000000009", "000000000000008"]: self.assertRaises(SyntaxError, eval, arg) self.assertEqual(eval("0777"), 511) self.assertEqual(eval("0777L"), 511) self.assertEqual(eval("000777"), 511) self.assertEqual(eval("0xff"), 255) self.assertEqual(eval("0xffL"), 255) self.assertEqual(eval("0XfF"), 255) self.assertEqual(eval("0777."), 777) self.assertEqual(eval("0777.0"), 777) self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777) self.assertEqual(eval("0777e1"), 7770) self.assertEqual(eval("0e0"), 0) self.assertEqual(eval("0000E-012"), 0) self.assertEqual(eval("09.5"), 9.5) self.assertEqual(eval("0777j"), 777j) self.assertEqual(eval("00j"), 0j) self.assertEqual(eval("00.0"), 0) self.assertEqual(eval("0e3"), 0) self.assertEqual(eval("090000000000000."), 90000000000000.) self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.) self.assertEqual(eval("090000000000000e0"), 90000000000000.) self.assertEqual(eval("090000000000000e-0"), 90000000000000.) self.assertEqual(eval("090000000000000j"), 90000000000000j) self.assertEqual(eval("000000000000007"), 7) self.assertEqual(eval("000000000000008."), 8.) self.assertEqual(eval("000000000000009."), 9.) def test_unary_minus(self): warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning) warnings.filterwarnings("ignore", "hex.* of negative int", FutureWarning) all_one_bits = '0xffffffff' if sys.maxint != 2147483647: all_one_bits = '0xffffffffffffffff' self.assertEqual(eval(all_one_bits), -1) self.assertEqual(eval("-" + all_one_bits), 1) def test_sequence_unpacking_error(self): i,j = (1, -1) or (-1, 1) self.assertEqual(i, 1) self.assertEqual(j, -1)
def expect_error(s): try: eval(s) raise TestFailed("%r accepted" % s) except SyntaxError: pass
if verbose: print "testing literals with leading zeroes"
def test_main(): test_support.run_unittest(TestSpecifics)
def expect_error(s): try: eval(s) raise TestFailed("%r accepted" % s) except SyntaxError: pass
def expect_same(test_source, expected): got = eval(test_source) if got != expected: raise TestFailed("eval(%r) gave %r, but expected %r" % (test_source, got, expected)) expect_error("077787") expect_error("0xj") expect_error("0x.") expect_error("0e") expect_same("0777", 511) expect_same("0777L", 511) expect_same("000777", 511) expect_same("0xff", 255) expect_same("0xffL", 255) expect_same("0XfF", 255) expect_same("0777.", 777) expect_same("0777.0", 777) expect_same("000000000000000000000000000000000000000000000000000777e0", 777) expect_same("0777e1", 7770) expect_same("0e0", 0) expect_same("0000E-012", 0) expect_same("09.5", 9.5) expect_same("0777j", 777j) expect_same("00j", 0j) expect_same("00.0", 0) expect_same("0e3", 0) expect_same("090000000000000.", 90000000000000.) expect_same("090000000000000.0000000000000000000000", 90000000000000.) expect_same("090000000000000e0", 90000000000000.) expect_same("090000000000000e-0", 90000000000000.) expect_same("090000000000000j", 90000000000000j) expect_error("090000000000000") expect_error("080000000000000") expect_error("000000000000009") expect_error("000000000000008") expect_same("000000000000007", 7) expect_same("000000000000008.", 8.) expect_same("000000000000009.", 9.) import warnings warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning) warnings.filterwarnings("ignore", "hex.* of negative int", FutureWarning) import sys all_one_bits = '0xffffffff' if sys.maxint != 2147483647: all_one_bits = '0xffffffffffffffff' exec """ expect_same(all_one_bits, -1) expect_same("-" + all_one_bits, 1) """ i,j = (1, -1) or (-1, 1) if i != 1 or j != -1: raise TestFailed, "Sequence packing/unpacking"
if __name__ == "__main__": test_main()
def expect_same(test_source, expected): got = eval(test_source) if got != expected: raise TestFailed("eval(%r) gave %r, but expected %r" % (test_source, got, expected))
import warnings warnings.warn("cookielib bug!", stacklevel=2) import traceback traceback.print_exc()
import warnings, traceback, StringIO f = StringIO.StringIO() traceback.print_exc(None, f) msg = f.getvalue() warnings.warn("cookielib bug!\n%s" % msg, stacklevel=2)
def reraise_unmasked_exceptions(unmasked=()): # There are a few catch-all except: statements in this module, for # catching input that's bad in unexpected ways. # This function re-raises some exceptions we don't want to trap. unmasked = unmasked + (KeyboardInterrupt, SystemExit, MemoryError) etype = sys.exc_info()[0] if issubclass(etype, unmasked): raise # swallowed an exception import warnings warnings.warn("cookielib bug!", stacklevel=2) import traceback traceback.print_exc()
if timeout is None: waiter.acquire() if __debug__: self._note("%s.wait(): got it", self) else: endtime = _time() + timeout delay = 0.000001 while 1: gotit = waiter.acquire(0) if gotit or _time() >= endtime: break _sleep(delay) if delay < 1.0: delay = delay * 2.0 if not gotit:
try: if timeout is None: waiter.acquire()
def wait(self, timeout=None): me = currentThread() assert self._is_owned(), "wait() of un-acquire()d lock" waiter = _allocate_lock() waiter.acquire() self.__waiters.append(waiter) saved_state = self._release_save() if timeout is None: waiter.acquire() if __debug__: self._note("%s.wait(): got it", self) else: endtime = _time() + timeout delay = 0.000001 # 1 usec while 1: gotit = waiter.acquire(0) if gotit or _time() >= endtime: break _sleep(delay) if delay < 1.0: delay = delay * 2.0 if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) try: self.__waiters.remove(waiter) except ValueError: pass else: if __debug__: self._note("%s.wait(%s): got it", self, timeout) self._acquire_restore(saved_state)
self._note("%s.wait(%s): timed out", self, timeout) try: self.__waiters.remove(waiter) except ValueError: pass
self._note("%s.wait(): got it", self)
def wait(self, timeout=None): me = currentThread() assert self._is_owned(), "wait() of un-acquire()d lock" waiter = _allocate_lock() waiter.acquire() self.__waiters.append(waiter) saved_state = self._release_save() if timeout is None: waiter.acquire() if __debug__: self._note("%s.wait(): got it", self) else: endtime = _time() + timeout delay = 0.000001 # 1 usec while 1: gotit = waiter.acquire(0) if gotit or _time() >= endtime: break _sleep(delay) if delay < 1.0: delay = delay * 2.0 if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) try: self.__waiters.remove(waiter) except ValueError: pass else: if __debug__: self._note("%s.wait(%s): got it", self, timeout) self._acquire_restore(saved_state)
if __debug__: self._note("%s.wait(%s): got it", self, timeout) self._acquire_restore(saved_state)
endtime = _time() + timeout delay = 0.000001 while 1: gotit = waiter.acquire(0) if gotit or _time() >= endtime: break _sleep(delay) if delay < 1.0: delay = delay * 2.0 if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) try: self.__waiters.remove(waiter) except ValueError: pass else: if __debug__: self._note("%s.wait(%s): got it", self, timeout) finally: self._acquire_restore(saved_state)
def wait(self, timeout=None): me = currentThread() assert self._is_owned(), "wait() of un-acquire()d lock" waiter = _allocate_lock() waiter.acquire() self.__waiters.append(waiter) saved_state = self._release_save() if timeout is None: waiter.acquire() if __debug__: self._note("%s.wait(): got it", self) else: endtime = _time() + timeout delay = 0.000001 # 1 usec while 1: gotit = waiter.acquire(0) if gotit or _time() >= endtime: break _sleep(delay) if delay < 1.0: delay = delay * 2.0 if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) try: self.__waiters.remove(waiter) except ValueError: pass else: if __debug__: self._note("%s.wait(%s): got it", self, timeout) self._acquire_restore(saved_state)
"".join(map(lambda i: "0123456789ABCDEF"[i], digits)) + "L"
"".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L"
def slow_format(self, x, base): if (x, base) == (0, 8): # this is an oddball! return "0L" digits = [] sign = 0 if x < 0: sign, x = 1, -x while x: x, r = divmod(x, base) digits.append(int(r)) digits.reverse() digits = digits or [0] return '-'[:sign] + \ {8: '0', 10: '', 16: '0x'}[base] + \ "".join(map(lambda i: "0123456789ABCDEF"[i], digits)) + "L"
def flush(self):
def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH): if self.mode == WRITE: self.fileobj.write(self.compress.flush(zlib_mode))
def flush(self): self.fileobj.flush()
(?: \s+ | ( [^\s[\](){} )+
[^[\](){}
def dump(*stuff): sys.__stdout__.write(string.join(map(str, stuff), " ") + "\n")
i = m.end(1) - 1
p = m.end() i = p-1 while i >= 0 and str[i] in " \t\n": i = i-1
def _study2(self, _rfind=string.rfind, _find=string.find, _ws=string.whitespace): if self.study_level >= 2: return self._study1() self.study_level = 2
p = m.end()
def _study2(self, _rfind=string.rfind, _find=string.find, _ws=string.whitespace): if self.study_level >= 2: return self._study1() self.study_level = 2
prefix = PREFIX prefix_len = len(prefix)
def main(): rcfile = os.path.join(os.path.dirname(refcounts.__file__), os.pardir, "api", "refcounts.dat") outfile = "-" opts, args = getopt.getopt(sys.argv[1:], "o:r:", ["output=", "refcounts="]) for opt, arg in opts: if opt in ("-o", "--output"): outfile = arg elif opt in ("-r", "--refcounts"): rcfile = arg rcdict = refcounts.load(rcfile) if outfile == "-": output = sys.stdout else: output = open(outfile, "w") if not args: args = ["-"] prefix = PREFIX prefix_len = len(prefix) for infile in args: if infile == "-": input = sys.stdin else: input = open(infile) while 1: line = input.readline() if not line: break if line[:prefix_len] == prefix: s = string.split(line[prefix_len:], '}', 1)[0] try: info = rcdict[s] except KeyError: sys.stderr.write("No refcount data for %s\n" % s) else: if info.result_type in ("PyObject*", "PyVarObject*"): if info.result_refs is None: rc = "Always \NULL{}" else: rc = info.result_refs and "New" or "Borrowed" rc = rc + " reference" line = (r"\begin{cfuncdesc}[%s]{%s}{" % (rc, info.result_type)) \ + line[prefix_len:] output.write(line) if infile != "-": input.close() if outfile != "-": output.close()
if line[:prefix_len] == prefix: s = string.split(line[prefix_len:], '}', 1)[0]
prefix = None if line.startswith(PREFIX_1): prefix = PREFIX_1 elif line.startswith(PREFIX_2): prefix = PREFIX_2 if prefix: s = line[len(prefix):].split('}', 1)[0]
def main(): rcfile = os.path.join(os.path.dirname(refcounts.__file__), os.pardir, "api", "refcounts.dat") outfile = "-" opts, args = getopt.getopt(sys.argv[1:], "o:r:", ["output=", "refcounts="]) for opt, arg in opts: if opt in ("-o", "--output"): outfile = arg elif opt in ("-r", "--refcounts"): rcfile = arg rcdict = refcounts.load(rcfile) if outfile == "-": output = sys.stdout else: output = open(outfile, "w") if not args: args = ["-"] prefix = PREFIX prefix_len = len(prefix) for infile in args: if infile == "-": input = sys.stdin else: input = open(infile) while 1: line = input.readline() if not line: break if line[:prefix_len] == prefix: s = string.split(line[prefix_len:], '}', 1)[0] try: info = rcdict[s] except KeyError: sys.stderr.write("No refcount data for %s\n" % s) else: if info.result_type in ("PyObject*", "PyVarObject*"): if info.result_refs is None: rc = "Always \NULL{}" else: rc = info.result_refs and "New" or "Borrowed" rc = rc + " reference" line = (r"\begin{cfuncdesc}[%s]{%s}{" % (rc, info.result_type)) \ + line[prefix_len:] output.write(line) if infile != "-": input.close() if outfile != "-": output.close()
+ line[prefix_len:]
+ line[len(prefix):]
def main(): rcfile = os.path.join(os.path.dirname(refcounts.__file__), os.pardir, "api", "refcounts.dat") outfile = "-" opts, args = getopt.getopt(sys.argv[1:], "o:r:", ["output=", "refcounts="]) for opt, arg in opts: if opt in ("-o", "--output"): outfile = arg elif opt in ("-r", "--refcounts"): rcfile = arg rcdict = refcounts.load(rcfile) if outfile == "-": output = sys.stdout else: output = open(outfile, "w") if not args: args = ["-"] prefix = PREFIX prefix_len = len(prefix) for infile in args: if infile == "-": input = sys.stdin else: input = open(infile) while 1: line = input.readline() if not line: break if line[:prefix_len] == prefix: s = string.split(line[prefix_len:], '}', 1)[0] try: info = rcdict[s] except KeyError: sys.stderr.write("No refcount data for %s\n" % s) else: if info.result_type in ("PyObject*", "PyVarObject*"): if info.result_refs is None: rc = "Always \NULL{}" else: rc = info.result_refs and "New" or "Borrowed" rc = rc + " reference" line = (r"\begin{cfuncdesc}[%s]{%s}{" % (rc, info.result_type)) \ + line[prefix_len:] output.write(line) if infile != "-": input.close() if outfile != "-": output.close()
seq, request = rpc.request_queue.get(0)
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
def main(del_exitfunc=False): """Start the Python execution server in a subprocess In the Python subprocess, RPCServer is instantiated with handlerclass MyHandler, which inherits register/unregister methods from RPCHandler via the mix-in class SocketIO. When the RPCServer 'server' is instantiated, the TCPServer initialization creates an instance of run.MyHandler and calls its handle() method. handle() instantiates a run.Executive object, passing it a reference to the MyHandler object. That reference is saved as attribute rpchandler of the Executive instance. The Executive methods have access to the reference and can pass it on to entities that they command (e.g. RemoteDebugger.Debugger.start_debugger()). The latter, in turn, can call MyHandler(SocketIO) register/unregister methods via the reference to register and unregister themselves. """ global exit_now global quitting global no_exitfunc no_exitfunc = del_exitfunc port = 8833 #time.sleep(15) # test subprocess not responding if sys.argv[1:]: port = int(sys.argv[1]) sys.argv[:] = [""] sockthread = threading.Thread(target=manage_socket, name='SockThread', args=((LOCALHOST, port),)) sockthread.setDaemon(True) sockthread.start() while 1: try: if exit_now: try: exit() except KeyboardInterrupt: # exiting but got an extra KBI? Try again! continue try: seq, request = rpc.request_queue.get(0) except Queue.Empty: time.sleep(0.05) continue method, args, kwargs = request ret = method(*args, **kwargs) rpc.response_queue.put((seq, ret)) except KeyboardInterrupt: if quitting: exit_now = True continue except SystemExit: raise except: type, value, tb = sys.exc_info() try: print_exception() rpc.response_queue.put((seq, None)) except: # Link didn't work, print same exception to __stderr__ traceback.print_exception(type, value, tb, file=sys.__stderr__) exit() else: continue
time.sleep(0.05)
def main(del_exitfunc=False): """Start the Python execution server in a subprocess In the Python subprocess, RPCServer is instantiated with handlerclass MyHandler, which inherits register/unregister methods from RPCHandler via the mix-in class SocketIO. When the RPCServer 'server' is instantiated, the TCPServer initialization creates an instance of run.MyHandler and calls its handle() method. handle() instantiates a run.Executive object, passing it a reference to the MyHandler object. That reference is saved as attribute rpchandler of the Executive instance. The Executive methods have access to the reference and can pass it on to entities that they command (e.g. RemoteDebugger.Debugger.start_debugger()). The latter, in turn, can call MyHandler(SocketIO) register/unregister methods via the reference to register and unregister themselves. """ global exit_now global quitting global no_exitfunc no_exitfunc = del_exitfunc port = 8833 #time.sleep(15) # test subprocess not responding if sys.argv[1:]: port = int(sys.argv[1]) sys.argv[:] = [""] sockthread = threading.Thread(target=manage_socket, name='SockThread', args=((LOCALHOST, port),)) sockthread.setDaemon(True) sockthread.start() while 1: try: if exit_now: try: exit() except KeyboardInterrupt: # exiting but got an extra KBI? Try again! continue try: seq, request = rpc.request_queue.get(0) except Queue.Empty: time.sleep(0.05) continue method, args, kwargs = request ret = method(*args, **kwargs) rpc.response_queue.put((seq, ret)) except KeyboardInterrupt: if quitting: exit_now = True continue except SystemExit: raise except: type, value, tb = sys.exc_info() try: print_exception() rpc.response_queue.put((seq, None)) except: # Link didn't work, print same exception to __stderr__ traceback.print_exception(type, value, tb, file=sys.__stderr__) exit() else: continue
if len(result) > 1:
if use_all or len(result) > 1:
def group(self, *groups):
if (type!=float):
if type != float:
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (pow(type(i),0)!=1):
if pow(type(i), 0) != 1:
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (pow(type(i),1)!=type(i)):
if pow(type(i), 1) != type(i):
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (pow(type(0),1)!=type(0)):
if pow(type(0), 1) != type(0):
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (pow(type(1),1)!=type(1)):
if pow(type(1), 1) != type(1):
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (pow(type(i),3)!=i*i*i):
if pow(type(i), 3) != i*i*i:
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (pow(2,i)!=pow2):
if pow(2, i) != pow2:
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (i!=30): pow2=pow2*2
if i != 30 : pow2 = pow2*2 for othertype in int, long: for i in range(-10, 0) + range(1, 10): ii = type(i) for j in range(1, 11): jj = -othertype(j) try: pow(ii, jj) except ValueError: pass else: raise ValueError, "pow(%s, %s) did not fail" % (ii, jj) for othertype in int, long, float: for i in range(1, 100): zero = type(0) exp = -othertype(i/10.0) if exp == 0: continue try: pow(zero, exp) except ZeroDivisionError: pass else: raise ValueError, "pow(%s, %s) did not fail" % (zero, exp)
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (type==float): il=1
if type == float: il = 1
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15
elif type == int: jl = 0 elif type == long: jl, jh = 0, 15
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (k!=0):
if k != 0:
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
if (j>=0 and k!=0): o=pow(i,j) % k n=pow(i,j,k) if (o!=n): print 'Integer mismatch:', i,j,k if (j>=0 and k<>0): o=pow(long(i),j) % k n=pow(long(i),j,k) if (o!=n): print 'Long mismatch:', i,j,k if (i>=0 and k<>0): o=pow(float(i),j) % k n=pow(float(i),j,k) if (o!=n): print 'Float mismatch:', i,j,k
if j >= 0 and k != 0: o = pow(i,j) % k n = pow(i,j,k) if o != n: print 'Integer mismatch:', i,j,k if j >= 0 and k <> 0: o = pow(long(i),j) % k n = pow(long(i),j,k) if o != n: print 'Long mismatch:', i,j,k if i >= 0 and k <> 0: o = pow(float(i),j) % k n = pow(float(i),j,k) if o != n: print 'Float mismatch:', i,j,k
def powtest(type): if (type!=float): print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if (pow(type(i),0)!=1): raise ValueError, 'pow('+str(i)+',0) != 1' if (pow(type(i),1)!=type(i)): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if (pow(type(0),1)!=type(0)): raise ValueError, 'pow(0,'+str(i)+') != 0' if (pow(type(1),1)!=type(1)): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if (pow(type(i),3)!=i*i*i): raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2=1 for i in range(0,31): if (pow(2,i)!=pow2): raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if (i!=30): pow2=pow2*2 print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if (type==float): il=1 compare = test_support.fcmp elif (type==int): jl=0 elif (type==long): jl,jh = 0, 15 for i in range(il, ih+1): for j in range(jl,jh+1): for k in range(kl, kh+1): if (k!=0): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
self.file = self.sock.makefile('rb')
if self.file is None: self.file = self.sock.makefile('rb')
def getreply(self): """Get a reply from the server. Returns a tuple consisting of:
try: errcode = string.atoi(code) except ValueError: errcode = -1 break
def getreply(self): """Get a reply from the server. Returns a tuple consisting of: