rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
host, port = splitport(host) if port is None: port = ftplib.FTP_PORT user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote(passwd or '')
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splita...
host, port = splitport(host) if port is None: port = ftplib.FTP_PORT
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splita...
user = passwd = ''
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splita...
print " setting options:" for (option, (source, value)) in options.items(): print " %s = %s (from %s)" % (option, value, source) if not hasattr(cmd_obj, option): raise DistutilsOptionError, \ ("%s: command '%s' has no such option '%s'") % \ (source, command, option) setattr(cmd_obj, option, value)
self._set_command_options(cmd_obj, options)
def get_command_obj (self, command, create=1): """Return the command object for 'command'. Normally this object is cached on a previous call to 'get_command_obj()'; if no comand object for 'command' is in the cache, then we either create and return it (if 'create' is true) or return None. """ cmd_obj = self.command_ob...
return EOFError, "Reached EOF"
raise EOFError, "Reached EOF"
def _read(self, size=1024): if self.fileobj is None: raise EOFError, "Reached EOF"
install = self.reinitialize_command('install')
install = self.reinitialize_command('install', reinit_subcommands=1)
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")
prefix = PREFIX
prefix = None
def main(): # overridable context prefix = PREFIX # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' # parse command line try: o...
opts, args = getopt.getopt(sys.argv[1:], 'e:p:P:')
opts, args = getopt.getopt(sys.argv[1:], 'e:o:p:P:')
def main(): # overridable context prefix = PREFIX # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' # parse command line try: o...
if exec_prefix is None: exec_prefix = EXEC_PREFIX if exec_prefix is None:
if not exec_prefix: if prefix:
def main(): # overridable context prefix = PREFIX # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' # parse command line try: o...
binlib = os.path.join(exec_prefix, 'lib/python1.4/config') incldir = os.path.join(prefix, 'include/python1.4')
version = sys.version[:3] binlib = os.path.join(exec_prefix, 'lib/python%s/config' % version) incldir = os.path.join(prefix, 'include/python%s' % version)
def main(): # overridable context prefix = PREFIX # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' # parse command line try: o...
files = ['$(OPT)', '$(LDFLAGS)', config_c, frozen_c] + \
files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \
def main(): # overridable context prefix = PREFIX # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' # parse command line try: o...
makemakefile.makemakefile(outfp, somevars, files, target)
makemakefile.makemakefile(outfp, somevars, files, base_target)
def main(): # overridable context prefix = PREFIX # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' # parse command line try: o...
print 'Now run make to build the target:', target
if odir: print 'Now run make in', odir, print 'to build the target:', base_target else: print 'Now run make to build the target:', base_target
def main(): # overridable context prefix = PREFIX # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' # parse command line try: o...
sys.stdout.flush() os.system("/depot/gnu/plat/bin/rlog -r %s </dev/null 2>&1" % self.name)
p = os.popen("/depot/gnu/plat/bin/rlog -r %s </dev/null 2>&1" % self.name) output = p.read() p.close() print cgi.escape(output)
def do_info(self):
sys.stdout.flush() os.system("/depot/gnu/plat/bin/rlog %s </dev/null 2>&1" % self.name)
p = os.popen("/depot/gnu/plat/bin/rlog %s </dev/null 2>&1" % self.name) output = p.read() p.close() print cgi.escape(output)
def do_rlog(self):
print "domain=%s;" % os.environ['HTTP_HOST'],
print "domain=%s;" % hostname,
def set_cookie(self, author, email):
<TEXTAREA COLS=80 ROWS=20 NAME=text>""" % title
<TEXTAREA COLS=80 ROWS=20 NAME=text>""" % self.escape(title)
def showedit(self, name, title, text):
""" % (author, email, self.log)
""" % (self.escape(author), self.escape(email), self.escape(self.log)) def escape(self, s): import regsub if '&' in s: s = regsub.gsub("&", "&amp;", s) if '<' in s: s = regsub.gsub("<", "&lt;", s) if '>' in s: s = regsub.gsub(">", "&gt;", s) if '"' in s: s = regsub.gsub('"', "&quot;", s) return s
def showedit(self, name, title, text):
while url[-1] in ");:,.?":
while url[-1] in ");:,.?'\"":
def translate(self, text):
url = cgi.escape(url)
url = self.escape(url)
def translate(self, text):
pos = f.tell()
pos = int(f.tell())
def _addval(self, val): f = _open(self._datfile, 'rb+') f.seek(0, 2) pos = f.tell()
fp.write("\t\tif _arguments.has_key('errn'):\n")
fp.write("\t\tif _arguments.get('errn', 0):\n")
fp.write("\tdef %s(self, "%funcname)
return split(p)[1]
i = p.rfind('/') + 1 return p[i:]
def basename(p): """Returns the final component of a pathname""" return split(p)[1]
return split(p)[0]
i = p.rfind('/') + 1 head = p[:i] if head and head != '/'*len(head): head = head.rstrip('/') return head
def dirname(p): """Returns the directory component of a pathname""" return split(p)[0]
testclasses = (WichmannHill_TestBasicOps,
testclasses = [WichmannHill_TestBasicOps,
def test_main(verbose=None): testclasses = (WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, HardwareRandom_TestBasicOps, TestDistributions, TestModule) test_support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i i...
HardwareRandom_TestBasicOps,
def test_main(verbose=None): testclasses = (WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, HardwareRandom_TestBasicOps, TestDistributions, TestModule) test_support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i i...
TestModule)
TestModule] if random._urandom is not None: testclasses.append(HardwareRandom_TestBasicOps)
def test_main(verbose=None): testclasses = (WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, HardwareRandom_TestBasicOps, TestDistributions, TestModule) test_support.run_unittest(*testclasses) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i i...
print '\nmorefindertools version %s\nTests coming up' %__version__
print '\nmorefindertools version %s\nTests coming up...' %__version__
def _test2(): print '\nmorefindertools version %s\nTests coming up' %__version__ import os import random # miscellaneous print '\tfilesharing on?', filesharing() # is file sharing on, off, starting up? print '\tOS version', OSversion() # the version of the system software # set the soundvolume in a simple way pri...
if '@' in localename:
if '@' in code:
def _parse_localename(localename): """ Parses the locale code for localename and returns the result as tuple (language code, encoding). The localename is normalized and passed through the locale alias engine. A ValueError is raised in case the locale name cannot be parsed. The language code corresponds to RFC 1766. ...
0x0404: "zh_TW", 0x0804: "zh_CN",
0x0436: "af_ZA", 0x041c: "sq_AL", 0x0401: "ar_SA", 0x0801: "ar_IQ", 0x0c01: "ar_EG", 0x1001: "ar_LY", 0x1401: "ar_DZ", 0x1801: "ar_MA", 0x1c01: "ar_TN", 0x2001: "ar_OM", 0x2401: "ar_YE", 0x2801: "ar_SY", 0x2c01: "ar_JO", 0x3001: "ar_LB", 0x3401: "ar_KW", 0x3801: "ar_AE", 0x3c01: "ar_BH", 0x4001: "ar_QA", 0x042b: "hy_AM...
def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, according to the system configuration.""" if do_setlocale: oldloc = setlocale(LC_CTYPE) setlocale(LC_CTYPE, "") result = nl_langinfo(CODESET) setlocale(LC_CTYPE, oldloc) return result else: return nl_langinfo(CODESET)
0x0413: "nl_NL", 0x0409: "en_US", 0x0809: "en_UK", 0x0c09: "en_AU", 0x1009: "en_CA", 0x1409: "en_NZ", 0x1809: "en_IE", 0x1c09: "en_ZA",
0x048c: "gbz_AF", 0x0465: "div_MV", 0x0413: "nl_NL", 0x0813: "nl_BE", 0x0409: "en_US", 0x0809: "en_GB", 0x0c09: "en_AU", 0x1009: "en_CA", 0x1409: "en_NZ", 0x1809: "en_IE", 0x1c09: "en_ZA", 0x2009: "en_JA", 0x2409: "en_CB", 0x2809: "en_BZ", 0x2c09: "en_TT", 0x3009: "en_ZW", 0x3409: "en_PH", 0x0425: "et_EE", 0x0438: "fo_...
def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, according to the system configuration.""" if do_setlocale: oldloc = setlocale(LC_CTYPE) setlocale(LC_CTYPE, "") result = nl_langinfo(CODESET) setlocale(LC_CTYPE, oldloc) return result else: return nl_langinfo(CODESET)
0x040c: "fr_FR", 0x080c: "fr_BE", 0x0c0c: "fr_CA", 0x100c: "fr_CH", 0x0407: "de_DE",
0x040c: "fr_FR", 0x080c: "fr_BE", 0x0c0c: "fr_CA", 0x100c: "fr_CH", 0x140c: "fr_LU", 0x180c: "fr_MC", 0x0462: "fy_NL", 0x0456: "gl_ES", 0x0437: "ka_GE", 0x0407: "de_DE", 0x0807: "de_CH", 0x0c07: "de_AT", 0x1007: "de_LU", 0x1407: "de_LI",
def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, according to the system configuration.""" if do_setlocale: oldloc = setlocale(LC_CTYPE) setlocale(LC_CTYPE, "") result = nl_langinfo(CODESET) setlocale(LC_CTYPE, oldloc) return result else: return nl_langinfo(CODESET)
0x040d: "iw_IL",
0x0447: "gu_IN", 0x040d: "he_IL", 0x0439: "hi_IN", 0x040e: "hu_HU",
def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, according to the system configuration.""" if do_setlocale: oldloc = setlocale(LC_CTYPE) setlocale(LC_CTYPE, "") result = nl_langinfo(CODESET) setlocale(LC_CTYPE, oldloc) return result else: return nl_langinfo(CODESET)
0x0410: "it_IT", 0x0411: "ja_JA", 0x0414: "no_NO", 0x0816: "pt_PT", 0x0c0a: "es_ES", 0x0441: "sw_KE", 0x041d: "sv_SE", 0x081d: "sv_FI",
0x0421: "id_ID", 0x045d: "iu_CA", 0x085d: "iu_CA", 0x083c: "ga_IE", 0x0434: "xh_ZA", 0x0435: "zu_ZA", 0x0410: "it_IT", 0x0810: "it_CH", 0x0411: "ja_JP", 0x044b: "kn_IN", 0x043f: "kk_KZ", 0x0457: "kok_IN", 0x0412: "ko_KR", 0x0440: "ky_KG", 0x0426: "lv_LV", 0x0427: "lt_LT", 0x046e: "lb_LU", 0x042f: "mk_MK", 0x043e: "ms_M...
def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, according to the system configuration.""" if do_setlocale: oldloc = setlocale(LC_CTYPE) setlocale(LC_CTYPE, "") result = nl_langinfo(CODESET) setlocale(LC_CTYPE, oldloc) return result else: return nl_langinfo(CODESET)
self.close()
try: self.close() except: pass
def __del__(self): self.close()
chars = self.text.get("1.0", "end-1c")
def writefile(self, filename): self.fixlastline() try: f = open(filename, "w") chars = self.text.get("1.0", "end-1c") f.write(chars) f.close() ## print "saved to", `filename` return True except IOError, msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False
finfo = macfs.FSSpec(name).GetFInfo()
finfo = FSSpec(name).FSpGetFInfo()
def getfileinfo(name): finfo = macfs.FSSpec(name).GetFInfo() dir, file = os.path.split(name) # XXXX Get resource/data sizes fp = open(name, 'rb') fp.seek(0, 2) dlen = fp.tell() fp = openrf(name, '*rb') fp.seek(0, 2) rlen = fp.tell() return file, finfo, dlen, rlen
else:
except ImportError:
def openrsrc(name, *mode): if not mode: mode = '*rb' else: mode = '*' + mode[0] return openrf(name, mode)
fss = macfs.FSSpec(ofname)
fss = FSSpec(ofname)
def __init__(self, (name, finfo, dlen, rlen), ofp): if type(ofp) == type(''): ofname = ofp ofp = open(ofname, 'w') if os.name == 'mac': fss = macfs.FSSpec(ofname) fss.SetCreatorType('BnHq', 'TEXT') ofp.write('(This file must be converted with BinHex 4.0)\n\n:') hqxer = _Hqxcoderengine(ofp) self.ofp = _Rlecoderengine(hq...
ofss = macfs.FSSpec(out)
ofss = FSSpec(out)
def hexbin(inp, out): """(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName if os.name == 'mac': ofss = macfs.FSSpec(out) out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems while 1: d = ifp.read(128000) if not d: brea...
self.hashcode = random.randrange(1000000000) def __hash__(self): return self.hashcode
def __hash__(self): return 42
def __init__(self, i): # Comparison outcomes are determined by the value of i. self.i = i
XXX
def test_one(n): global mutate, dict1, dict2, dict1keys, dict2keys # Fill the dicts without mutating them. mutate = 0 dict1keys = fill_dict(dict1, range(n), n) dict2keys = fill_dict(dict2, range(n), n) # Enable mutation, then compare the dicts so long as they have the # same size. mutate = 1 if verbose: print "trying...
referenced = C() a = C()
referenced = A() a = A()
def callback(*args): pass
a = C() a.wrc = weakref.ref(referenced, callback)
a = A() weakref.ref(referenced, callback)
def callback(*args): pass
def writestr(self, zinfo, bytes):
def writestr(self, zinfo_or_arcname, bytes):
def writestr(self, zinfo, bytes): """Write a file into the archive. The contents is the string 'bytes'.""" self._writecheck(zinfo) zinfo.file_size = len(bytes) # Uncompressed size zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum if zinfo.compress_type == ZIP_DEFLATED: co = zlib.compressobj(zlib.Z_D...
'bytes'."""
'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.""" if not isinstance(zinfo_or_arcname, ZipInfo): zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())) zinfo.compress_type = self.compression else: zinfo = zinfo_or_arcname
def writestr(self, zinfo, bytes): """Write a file into the archive. The contents is the string 'bytes'.""" self._writecheck(zinfo) zinfo.file_size = len(bytes) # Uncompressed size zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum if zinfo.compress_type == ZIP_DEFLATED: co = zlib.compressobj(zlib.Z_D...
urllib.urlopen, "http://www.sadflkjsasadf.com/")
urllib.urlopen, "http://www.python.invalid/")
def test_bad_address(self): # Make sure proper exception is raised when connecting to a bogus # address. self.assertRaises(IOError, urllib.urlopen, "http://www.sadflkjsasadf.com/")
for (func, cmd) in self.sub_commands:
for (func, cmd_name) in self.sub_commands:
def run (self):
self.run_peer (cmd)
self.run_peer (cmd_name)
def run (self):
for (func, cmd) in self.sub_commands:
for (func, cmd_name) in self.sub_commands:
def get_outputs (self): # This command doesn't have any outputs of its own, so just # get the outputs of all its sub-commands. outputs = [] for (func, cmd) in self.sub_commands: if func is None or func(): outputs.extend (self.run_peer (cmd))
outputs.extend (self.run_peer (cmd))
cmd = self.find_peer (cmd_name) outputs.extend (cmd.get_outputs())
def get_outputs (self): # This command doesn't have any outputs of its own, so just # get the outputs of all its sub-commands. outputs = [] for (func, cmd) in self.sub_commands: if func is None or func(): outputs.extend (self.run_peer (cmd))
self.write("Unsupported characters in input")
self.write("Unsupported characters in input\n")
def runsource(self, source): "Extend base class method: Stuff the source in the line cache first" filename = self.stuffsource(source) self.more = 0 self.save_warnings_filters = warnings.filters[:] warnings.filterwarnings(action="error", category=SyntaxWarning) if isinstance(source, types.UnicodeType): import IOBinding ...
s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':':
prefix = self.text.get("insert linestart", "insert") if prefix.rstrip().endswith(':'):
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.in...
self.text.insert("insert",lines[0].strip())
prefix = self.text.get("insert linestart", "insert") self.text.insert("insert", lines[0].strip())
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.in...
self.newline_and_indent_event(event)
orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0) new_base_indent = re.search(r'^([ \t]*)', prefix).group(0)
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.in...
self.text.insert("insert", line.strip()) self.newline_and_indent_event(event)
if line.startswith(orig_base_indent): line = new_base_indent + line[len(orig_base_indent):] self.text.insert('insert', '\n'+line.rstrip())
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.in...
import pdb ; pdb.set_trace()
def extractarg(self, part): mode = "InMode" if self.asplit.match(part) < 0: self.error("Indecipherable argument: %s", `part`) import pdb ; pdb.set_trace() return ("unknown", part, mode) type, name, array = self.asplit.group('type', 'name', 'array') if array: # array matches an optional [] after the argument name type =...
t = test()
t = Test()
def str(self): return str(self)
return beta * self.stdgamma(alpha) def stdgamma(self, alpha, *args):
if alpha <= 0.0 or beta <= 0.0: raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
def gammavariate(self, alpha, beta): # beta times standard gamma return beta * self.stdgamma(alpha)
if alpha <= 0.0: raise ValueError, 'stdgamma: alpha must be > 0.0'
def stdgamma(self, alpha, *args): # *args for Py2.2 compatiblity random = self.random if alpha <= 0.0: raise ValueError, 'stdgamma: alpha must be > 0.0'
return x
return x * beta
def stdgamma(self, alpha, *args): # *args for Py2.2 compatiblity random = self.random if alpha <= 0.0: raise ValueError, 'stdgamma: alpha must be > 0.0'
return -_log(u)
return -_log(u) * beta
def stdgamma(self, alpha, *args): # *args for Py2.2 compatiblity random = self.random if alpha <= 0.0: raise ValueError, 'stdgamma: alpha must be > 0.0'
return x
return x * beta def stdgamma(self, alpha, ainv, bbb, ccc): import warnings warnings.warn("The stdgamma function is deprecated; " "use gammavariate() instead", DeprecationWarning) return self.gammavariate(alpha, 1.0)
def stdgamma(self, alpha, *args): # *args for Py2.2 compatiblity random = self.random if alpha <= 0.0: raise ValueError, 'stdgamma: alpha must be > 0.0'
def _test(N=200):
def _test(N=20000):
def _test(N=200): print 'TWOPI =', TWOPI print 'LOG4 =', LOG4 print 'NV_MAGICCONST =', NV_MAGICCONST print 'SG_MAGICCONST =', SG_MAGICCONST _test_generator(N, 'random()') _test_generator(N, 'normalvariate(0.0, 1.0)') _test_generator(N, 'lognormvariate(0.0, 1.0)') _test_generator(N, 'cunifvariate(0.0, 1...
re-inserted are alwyas appended to the header list.
re-inserted are always appended to the header list.
def values(self): """Return a list of all the message's header values.
re-inserted are alwyas appended to the header list.
re-inserted are always appended to the header list.
def items(self): """Get all the message's header fields and values.
compile(file)
compileFile(file)
def wrap_aug(node): return wrapper[node.__class__](node)
port = int(host[i+1:])
try: port = int(host[i+1:]) except ValueError, msg: raise socket.error, str(msg)
def _set_hostport(self, host, port): if port is None: i = host.find(':') if i >= 0: port = int(host[i+1:]) host = host[:i] else: port = self.default_port self.host = host self.port = port
print time.strftime("expires=%a, %d-%b-%x %X GMT", gmt)
print time.strftime("expires=%a, %d-%b-%y %X GMT", gmt)
def send_my_cookie(ui): name = COOKIE_NAME value = "%s/%s/%s" % (ui.author, ui.email, ui.password) import urllib value = urllib.quote(value) then = now + COOKIE_LIFETIME gmt = time.gmtime(then) print "Set-Cookie: %s=%s; path=/cgi-bin/;" % (name, value), print time.strftime("expires=%a, %d-%b-%x %X GMT", gmt)
s = pickle.dumps(d) e = pickle.loads(s) self.assertNotEqual(id(d), id(e)) self.assertEqual(list(d), list(e))
for i in (0, 1, 2): s = pickle.dumps(d, i) e = pickle.loads(s) self.assertNotEqual(id(d), id(e)) self.assertEqual(list(d), list(e)) def test_pickle_recursive(self): d = deque('abc') d.append(d) for i in (0, 1, 2): e = pickle.loads(pickle.dumps(d, i)) self.assertNotEqual(id(d), id(e)) self.assertEqual(id(e), id(e[-1]))
def test_pickle(self): d = deque(xrange(200)) s = pickle.dumps(d) e = pickle.loads(s) self.assertNotEqual(id(d), id(e)) self.assertEqual(list(d), list(e))
test_mesg = 'From: %s@localhost\nSubject: IMAP4 test\n\ndata...\n' % USER
test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':CRLF}
def print_log(): _mesg('last %d IMAP4 interactions:' % len(_cmd_log)) for secs,line in _cmd_log: _mesg(line, secs)
if auth: h.putheader('Authorization: Basic %s' % auth)
if auth: h.putheader('Authorization', 'Basic %s' % auth)
def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if isinstance(url, str): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest user_pass...
sys.stdout.writelines(restored)
for line in restored: print line,
def restore(which): restored = difflib.restore(sys.stdin.readlines(), which) sys.stdout.writelines(restored)
name = string.join(string.split(name, '-'), '_')
name = '_'.join(name.split('-'))
def open(self, fullurl, data=None): """Use URLopener().open(file) instead of open(file, 'r').""" fullurl = unwrap(toBytes(fullurl)) if self.tempcache and self.tempcache.has_key(fullurl): filename, headers = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) urltype, url = splittyp...
if string.lower(urltype) != 'http':
if urltype.lower() != 'http':
def open_http(self, url, data=None): """Use HTTP protocol.""" import httplib user_passwd = None if type(url) is types.StringType: host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest us...
auth = string.strip(base64.encodestring(user_passwd))
auth = base64.encodestring(user_passwd).strip()
def open_http(self, url, data=None): """Use HTTP protocol.""" import httplib user_passwd = None if type(url) is types.StringType: host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest us...
if string.lower(urltype) != 'https':
if urltype.lower() != 'https':
def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if type(url) in types.StringTypes: host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest...
auth = string.strip(base64.encodestring(user_passwd))
auth = base64.encodestring(user_passwd).strip()
def open_https(self, url, data=None): """Use HTTPS protocol.""" import httplib user_passwd = None if type(url) in types.StringTypes: host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url urltype, rest = splittype(selector) url = rest...
dirs = string.splitfields(path, '/')
dirs = path.split('/')
def open_ftp(self, url): """Use FTP protocol.""" host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote...
key = user, host, port, string.join(dirs, '/')
key = user, host, port, '/'.join(dirs)
def open_ftp(self, url): """Use FTP protocol.""" host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote...
if string.lower(attr) == 'type' and \
if attr.lower() == 'type' and \
def open_ftp(self, url): """Use FTP protocol.""" host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote...
type = string.upper(value)
type = value.upper()
def open_ftp(self, url): """Use FTP protocol.""" host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote...
[type, data] = string.split(url, ',', 1)
[type, data] = url.split(',', 1)
def open_data(self, url, data=None): """Use "data" URL.""" # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value import StringIO, mimetools, time try: [ty...
semi = string.rfind(type, ';')
semi = type.rfind(';')
def open_data(self, url, data=None): """Use "data" URL.""" # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value import StringIO, mimetools, time try: [ty...
msg = string.join(msg, '\n')
msg = '\n'.join(msg)
def open_data(self, url, data=None): """Use "data" URL.""" # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value import StringIO, mimetools, time try: [ty...
if string.lower(scheme) == 'basic':
if scheme.lower() == 'basic':
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): """Error 401 -- authentication required. See this URL for a description of the basic authentication scheme: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt""" if headers.has_key('www-authenticate'): stuff = headers['www-authent...
i = string.find(host, '@') + 1
i = host.find('@') + 1
def retry_http_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = 'http://' + host + selector if data is None: re...
i = string.find(host, '@') + 1
i = host.find('@') + 1
def retry_https_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = string.find(host, '@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = '//' + host + selector return self.open_https(...
key = realm + '@' + string.lower(host)
key = realm + '@' + host.lower()
def get_user_passwd(self, host, realm, clear_cache = 0): key = realm + '@' + string.lower(host) if self.auth_cache.has_key(key): if clear_cache: del self.auth_cache[key] else: return self.auth_cache[key] user, passwd = self.prompt_user_passwd(host, realm) if user or passwd: self.auth_cache[key] = (user, passwd) return ...
if reason[:3] != '550':
if str(reason)[:3] != '550':
def retrfile(self, file, type): import ftplib self.endtransfer() if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 else: cmd = 'TYPE ' + type; isdir = 0 try: self.ftp.voidcmd(cmd) except ftplib.all_errors: self.init() self.ftp.voidcmd(cmd) conn = None if file and not isdir: # Use nlst to see if the file exists at all tr...
i = string.rfind(basepath, '/')
i = basepath.rfind('/')
def basejoin(base, url): """Utility to combine a URL with a base URL to form a new URL.""" type, path = splittype(url) if type: # if url is complete (i.e., it contains a type), return it return url host, path = splithost(path) type, basepath = splittype(base) # inherit type from base if host: # if url contains host, ju...
i = string.rfind(basepath[:-1], '/')
i = basepath[:-1].rfind('/')
def basejoin(base, url): """Utility to combine a URL with a base URL to form a new URL.""" type, path = splittype(url) if type: # if url is complete (i.e., it contains a type), return it return url host, path = splithost(path) type, basepath = splittype(base) # inherit type from base if host: # if url contains host, ju...
url = string.strip(url)
url = url.strip()
def unwrap(url): """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" url = string.strip(url) if url[:1] == '<' and url[-1:] == '>': url = string.strip(url[1:-1]) if url[:4] == 'URL:': url = string.strip(url[4:]) return url
url = string.strip(url[1:-1]) if url[:4] == 'URL:': url = string.strip(url[4:])
url = url[1:-1].strip() if url[:4] == 'URL:': url = url[4:].strip()
def unwrap(url): """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" url = string.strip(url) if url[:1] == '<' and url[-1:] == '>': url = string.strip(url[1:-1]) if url[:4] == 'URL:': url = string.strip(url[4:]) return url
if not port: raise string.atoi_error, "no digits" nport = string.atoi(port) except string.atoi_error:
if not port: raise ValueError, "no digits" nport = int(port) except ValueError:
def splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" global _nportprog if _nportprog is None: import re _nportprog = re.compi...
words = string.splitfields(url, ';')
words = url.split(';')
def splitattr(url): """splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].""" words = string.splitfields(url, ';') return words[0], words[1:]
myatoi = string.atoi list = string.split(s, '%')
myatoi = int list = s.split('%')
def unquote(s): """unquote('abc%20def') -> 'abc def'.""" mychr = chr myatoi = string.atoi list = string.split(s, '%') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except: myappend('%' + item) else: myappend('%' + item) return str...
return string.join(res, "")
return "".join(res)
def unquote(s): """unquote('abc%20def') -> 'abc def'.""" mychr = chr myatoi = string.atoi list = string.split(s, '%') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except: myappend('%' + item) else: myappend('%' + item) return str...
s = string.join(string.split(s, '+'), ' ')
s = ' '.join(s.split('+'))
def unquote_plus(s): """unquote('%7e/abc+def') -> '~/abc def'""" if '+' in s: # replace '+' with ' ' s = string.join(string.split(s, '+'), ' ') return unquote(s)
return string.join(res, '')
return ''.join(res)
def _fast_quote(s): global _fast_safe if _fast_safe is None: _fast_safe = {} for c in _fast_safe_test: _fast_safe[c] = c res = list(s) for i in range(len(res)): c = res[i] if not _fast_safe.has_key(c): res[i] = '%%%02x' % ord(c) return string.join(res, '')