rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
return -1 self.handle_data("&") i = self.updatepos(i, i + 1)
|
break elif (i + 1) < n: self.handle_data("&") i = self.updatepos(i, i + 1) else: break
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
|
def parse_comment(self, i):
|
def parse_comment(self, i, report=1):
|
def parse_comment(self, i): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j
|
j = match.start() self.handle_comment(rawdata[i+4: j])
|
if report: j = match.start() self.handle_comment(rawdata[i+4: j])
|
def parse_comment(self, i): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j
|
self.handle_decl(rawdata[i+2:j])
|
data = rawdata[i+2:j] if decltype == "doctype": self.handle_decl(data) else: self.unknown_decl(data)
|
def parse_declaration(self, i): # This is some sort of declaration; in "HTML as # deployed," this should only be the document type # declaration ("<!DOCTYPE html...>"). rawdata = self.rawdata j = i + 2 assert rawdata[i:j] == "<!", "unexpected call to parse_declaration" if rawdata[j:j+1] in ("-", ""): # Start of comment followed by buffer boundary, # or just a buffer boundary. return -1 # in practice, this should look like: ((name|stringlit) S*)+ '>' n = len(rawdata) while j < n: c = rawdata[j] if c == ">": # end of declaration syntax self.handle_decl(rawdata[i+2:j]) return j + 1 if c in "\"'": m = declstringlit.match(rawdata, j) if not m: return -1 # incomplete j = m.end() elif c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": m = declname.match(rawdata, j) if not m: return -1 # incomplete j = m.end() else: raise HTMLParseError( "unexpected char in declaration: %s" % `rawdata[j]`, self.getpos()) return -1 # incomplete
|
window.do_activate(modifiers & 1, event)
|
window.do_activate(message & 1, event)
|
def do_suspendresume(self, event): (what, message, when, where, modifiers) = event wid = FrontWindow() if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_activate(modifiers & 1, event)
|
if (sld.lower() in ( "co", "ac", "com", "edu", "org", "net", "gov", "mil", "int") and len(tld) == 2):
|
if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2:
|
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if (sld.lower() in ( "co", "ac", "com", "edu", "org", "net", "gov", "mil", "int") and len(tld) == 2): # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
|
return addinfo(fp, headers)
|
return addinfourl(fp, headers, self.openedurl)
|
def open_http(self, url): import httplib if type(url) is type(""): host, selector = splithost(url) user_passwd, host = splituser(host) else: host, selector = url urltype, rest = splittype(selector) if string.lower(urltype) == 'http': realhost, rest = splithost(rest) user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) print "proxy via http:", host, selector if not host: raise IOError, ('http error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTP(host) h.putrequest('GET', selector) if auth: h.putheader('Authorization: Basic %s' % auth) for args in self.addheaders: apply(h.putheader, args) h.endheaders() errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfo(fp, headers) else: return self.http_error(url, fp, errcode, errmsg, headers)
|
return addinfo(fp, noheaders())
|
return addinfourl(fp, noheaders(), self.openedurl)
|
def open_gopher(self, url): import gopherlib host, selector = splithost(url) if not host: raise IOError, ('gopher error', 'no host given') type, selector = splitgophertype(selector) selector, query = splitquery(selector) selector = unquote(selector) if query: query = unquote(query) fp = gopherlib.send_query(selector, query, host) else: fp = gopherlib.send_selector(selector, host) return addinfo(fp, noheaders())
|
if not host: return addinfo(open(url2pathname(file), 'r'), noheaders())
|
if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl)
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(url2pathname(file), 'r'), noheaders()) raise IOError, ('local file error', 'not on local host')
|
return addinfo(open(url2pathname(file), 'r'), noheaders())
|
return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl)
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(url2pathname(file), 'r'), noheaders()) raise IOError, ('local file error', 'not on local host')
|
return addinfo(self.ftpcache[key].retrfile(file, type), noheaders())
|
return addinfourl(self.ftpcache[key].retrfile(file, type), noheaders(), self.openedurl)
|
def open_ftp(self, url): 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 = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT path, attrs = splitattr(path) dirs = string.splitfields(path, '/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] key = (user, host, port, string.joinfields(dirs, '/')) try: if not self.ftpcache.has_key(key): self.ftpcache[key] = \ ftpwrapper(user, passwd, host, port, dirs) if not file: type = 'D' else: type = 'I' for attr in attrs: attr, value = splitvalue(attr) if string.lower(attr) == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = string.upper(value) return addinfo(self.ftpcache[key].retrfile(file, type), noheaders()) except ftperrors(), msg: raise IOError, ('ftp error', msg)
|
return addinfo(fp, headers)
|
return addinfourl(fp, headers, self.openedurl)
|
def http_error_default(self, url, fp, errcode, errmsg, headers): return addinfo(fp, headers)
|
print '%s.%s%s =? %s... ' % (repr(input), method, args, output),
|
print '%s.%s%s =? %s... ' % (repr(input), method, args, repr(output)),
|
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, output), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output: if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes'
|
if value != output:
|
if value != output or type(value) is not type(output):
|
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, output), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output: if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes'
|
def __init__(self): self.seq = 'wxyz'
|
def __init__(self, seq): self.seq = seq
|
def __init__(self): self.seq = 'wxyz'
|
test('join', u' ', u'w x y z', Sequence())
|
test('join', u' ', u'w x y z', Sequence('wxyz'))
|
def __getitem__(self, i): return self.seq[i]
|
class BadSeq(Sequence): def __init__(self): self.seq = [7, u'hello', 123L] test('join', u' ', TypeError, BadSeq())
|
test('join', u' ', TypeError, Sequence([7, u'hello', 123L])) test('join', ' ', u'a b c d', [u'a', u'b', u'c', u'd']) test('join', ' ', u'a b c d', ['a', 'b', u'c', u'd']) test('join', '', u'abcd', (u'a', u'b', u'c', u'd')) test('join', ' ', u'w x y z', Sequence(u'wxyz')) test('join', ' ', TypeError, 7)
|
def __getitem__(self, i): return self.seq[i]
|
self.assert_(len(read) == 1024, "Error performing sendall.") read = filter(lambda x: x == 'f', read) self.assert_(len(read) == 1024, "Error performing sendall.")
|
msg += read self.assertEqual(msg, 'f' * 2048)
|
def testSendAll(self): # Testing sendall() with a 2048 byte string over TCP while 1: read = self.cli_conn.recv(1024) if not read: break self.assert_(len(read) == 1024, "Error performing sendall.") read = filter(lambda x: x == 'f', read) self.assert_(len(read) == 1024, "Error performing sendall.")
|
return filename
|
components = string.split(filename, ':') for i in range(1, len(components)): if components[i] == '..': components[i] = '' return string.join(components, ':')
|
def _filename_to_abs(self, filename): # Some filenames seem to be unix-like. Convert to Mac names.
|
def writexml(self, writer): writer.write("<" + self.tagName)
|
def writexml(self, writer, indent="", addindent="", newl=""): writer.write(indent+"<" + self.tagName)
|
def writexml(self, writer): writer.write("<" + self.tagName)
|
writer.write(">")
|
writer.write(">%s"%(newl))
|
def writexml(self, writer): writer.write("<" + self.tagName)
|
node.writexml(writer) writer.write("</%s>" % self.tagName) else: writer.write("/>")
|
node.writexml(writer,indent+addindent,addindent,newl) writer.write("%s</%s>%s" % (indent,self.tagName,newl)) else: writer.write("/>%s"%(newl))
|
def writexml(self, writer): writer.write("<" + self.tagName)
|
def writexml(self, writer): writer.write("<!--%s-->" % self.data)
|
def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s<!--%s-->%s" % (indent,self.data,newl))
|
def writexml(self, writer): writer.write("<!--%s-->" % self.data)
|
def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data))
|
def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
|
def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data))
|
def writexml(self, writer): _write_data(writer, self.data)
|
def writexml(self, writer, indent="", addindent="", newl=""): _write_data(writer, "%s%s%s"%(indent, self.data, newl))
|
def writexml(self, writer): _write_data(writer, self.data)
|
def writexml(self, writer):
|
def writexml(self, writer, indent="", addindent="", newl=""):
|
def writexml(self, writer): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer)
|
node.writexml(writer)
|
node.writexml(writer, indent, addindent, newl)
|
def writexml(self, writer): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer)
|
stats = os.stat(localname)
|
try: stats = os.stat(localname) except OSError, e: raise IOError(e.errno, e.strerror, e.filename)
|
def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, rfc822, StringIO host, file = splithost(url) localname = url2pathname(file) stats = os.stat(localname) size = stats.st_size modified = rfc822.formatdate(stats.st_mtime) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO.StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if not port \ and socket.gethostbyname(host) in (localhost(), thishost()): urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) raise IOError, ('local file error', 'not on local host')
|
if sys.platform in ['unixware7']: testit('atan2(0, 1)', math.atan2(0, 1), math.pi) else: testit('atan2(0, 1)', math.atan2(0, 1), 0)
|
testit('atan2(0, 1)', math.atan2(0, 1), 0)
|
def testit(name, value, expected): if abs(value-expected) > eps: raise TestFailed, '%s returned %f, expected %f'%\ (name, value, expected)
|
self.bytebuffer = ""
|
self.buffer = ""
|
def reset(self): IncrementalDecoder.reset(self) self.bytebuffer = ""
|
suite.addTest(unittest.makeSuite(BasicUDPTest))
|
if sys.platform != 'mac': suite.addTest(unittest.makeSuite(BasicUDPTest))
|
def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(GeneralModuleTests)) suite.addTest(unittest.makeSuite(BasicTCPTest)) suite.addTest(unittest.makeSuite(BasicUDPTest)) suite.addTest(unittest.makeSuite(NonBlockingTCPTests)) suite.addTest(unittest.makeSuite(FileObjectClassTestCase)) suite.addTest(unittest.makeSuite(UnbufferedFileObjectClassTestCase)) suite.addTest(unittest.makeSuite(LineBufferedFileObjectClassTestCase)) suite.addTest(unittest.makeSuite(SmallBufferedFileObjectClassTestCase)) test_support.run_suite(suite)
|
This is the normal interface: it return a stripped
|
This is the normal interface: it returns a stripped
|
def getheader(self, name, default=None): """Get the header value for a name. This is the normal interface: it return a stripped version of the header value for a given header name, or None if it doesn't exist. This uses the dictionary version which finds the *last* such header. """ try: return self.dict[string.lower(name)] except KeyError: return default
|
vereq(iter(T()).next(), '0!!!')
|
vereq(iter(T((1,2))).next(), 1)
|
def __getitem__(self, key): return str(key) + '!!!'
|
vereq(iter(L()).next(), '0!!!')
|
vereq(iter(L([1,2])).next(), 1)
|
def __getitem__(self, key): return str(key) + '!!!'
|
self.sock.send(data)
|
bytes = len(data) while bytes > 0: sent = self.sock.send(data) if sent == bytes: break data = data[sent:] bytes = bytes - sent
|
def send(self, data): """Send data to remote.""" self.sock.send(data)
|
if '\n' in text: if string.find(text, '\r\n') >= 0: self._eoln = '\r\n' else: self._eoln = '\n' text = string.replace(text, self._eoln, '\r') change = 0 else: change = 0 self._eoln = '\r'
|
def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" self._creator = W._signature self._eoln = os.linesep elif os.path.exists(path): path = resolvealiases(path) dir, name = os.path.split(path) self.title = name f = open(path, "rb") text = f.read() f.close() self._creator, filetype = MacOS.GetCreatorAndType(path) self.addrecentfile(path) else: raise IOError, "file '%s' does not exist" % path self.path = path if '\n' in text: if string.find(text, '\r\n') >= 0: self._eoln = '\r\n' else: self._eoln = '\n' text = string.replace(text, self._eoln, '\r') change = 0 else: change = 0 self._eoln = '\r' self.settings = {} if self.path: self.readwindowsettings() if self.settings.has_key("windowbounds"): bounds = self.settings["windowbounds"] else: bounds = defaultwindowsize if self.settings.has_key("fontsettings"): self.fontsettings = self.settings["fontsettings"] else: self.fontsettings = defaultfontsettings if self.settings.has_key("tabsize"): try: self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] except: self.tabsettings = defaulttabsettings else: self.tabsettings = defaulttabsettings W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) self.setupwidgets(text) if change > 0: self.editgroup.editor.textchanged() if self.settings.has_key("selection"): selstart, selend = self.settings["selection"] self.setselection(selstart, selend) self.open() self.setinfotext() self.globals = {} self._buf = "" # for write method self.debugging = 0 self.profiling = 0 self.run_as_main = self.settings.get("run_as_main", 0) self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0)
|
|
if change > 0: self.editgroup.editor.textchanged()
|
def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" self._creator = W._signature self._eoln = os.linesep elif os.path.exists(path): path = resolvealiases(path) dir, name = os.path.split(path) self.title = name f = open(path, "rb") text = f.read() f.close() self._creator, filetype = MacOS.GetCreatorAndType(path) self.addrecentfile(path) else: raise IOError, "file '%s' does not exist" % path self.path = path if '\n' in text: if string.find(text, '\r\n') >= 0: self._eoln = '\r\n' else: self._eoln = '\n' text = string.replace(text, self._eoln, '\r') change = 0 else: change = 0 self._eoln = '\r' self.settings = {} if self.path: self.readwindowsettings() if self.settings.has_key("windowbounds"): bounds = self.settings["windowbounds"] else: bounds = defaultwindowsize if self.settings.has_key("fontsettings"): self.fontsettings = self.settings["fontsettings"] else: self.fontsettings = defaultfontsettings if self.settings.has_key("tabsize"): try: self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] except: self.tabsettings = defaulttabsettings else: self.tabsettings = defaulttabsettings W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) self.setupwidgets(text) if change > 0: self.editgroup.editor.textchanged() if self.settings.has_key("selection"): selstart, selend = self.settings["selection"] self.setselection(selstart, selend) self.open() self.setinfotext() self.globals = {} self._buf = "" # for write method self.debugging = 0 self.profiling = 0 self.run_as_main = self.settings.get("run_as_main", 0) self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0)
|
|
print dir(tas)
|
print fixdir(dir(tas))
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
|
print dir(subpar)
|
print fixdir(dir(subpar))
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
|
print dir(subsubsub)
|
print fixdir(dir(subsubsub))
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
|
if _os.name == "nt":
|
if _os.name in ("nt", "ce"):
|
def wstring_at(ptr, size=0): """wstring_at(addr[, size]) -> string
|
result = -2147221231
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
|
ctcom = __import__("ctypes.com.server", globals(), locals(), ['*'])
|
ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
pass
|
return -2147221231
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
result = ctcom.DllGetClassObject(rclsid, riid, ppv) if result == -2147221231: try: ccom = __import__("comtypes.server", globals(), locals(), ['*']) except ImportError: pass else: result = ccom.DllGetClassObject(rclsid, riid, ppv) return result
|
return ccom.DllGetClassObject(rclsid, riid, ppv)
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
result = 0
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
|
|
ctcom = __import__("ctypes.com.server", globals(), locals(), ['*'])
|
ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
|
pass else: result = ctcom.DllCanUnloadNow() if result != 0: return result try: ccom = __import__("comtypes.server", globals(), locals(), ['*']) except ImportError: return result try: return ccom.DllCanUnloadNow() except AttributeError: pass return result
|
return 0 return ccom.DllCanUnloadNow()
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
|
pat = r'''-..x..x..x
|
pat = r'''[l-]..x..x..x
|
def test_getstatus(self): # This pattern should match 'ls -ld /bin/ls' on any posix # system, however perversely configured. pat = r'''-..x..x..x # It is executable. \s+\d+ # It has some number of links. \s+\w+\s+\w+ # It has a user and group, which may # be named anything. [^/]* # Skip the date. /bin/ls # and end with the name of the file. '''
|
def test(fn = 'f:just samples:just.aif'):
|
def test():
|
def test(fn = 'f:just samples:just.aif'): import aifc af = aifc.open(fn, 'r') print af.getparams() p = Play_Audio_mac() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) p.setnchannels(af.getnchannels()) BUFSIZ = 10000 while 1: data = af.readframes(BUFSIZ) if not data: break p.writeframes(data) p.wait()
|
print "Breakpoint in", filename, "at", lineno
|
def set_break(self, filename, lineno, temporary=0, cond = None): filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) if not self.breaks.has_key(filename): self.breaks[filename] = [] list = self.breaks[filename] if not lineno in list: list.append(lineno) bp = Breakpoint(filename, lineno, temporary, cond) print "Breakpoint in", filename, "at", lineno
|
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
def genrange(*a): """Function to implement 'range' as a generator""" start, stop, step = handleargs(a) value = start while value < stop: yield value value += step
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop.
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
|
class Range:
|
"""
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
def __init__(self, start, stop, step): if step == 0: raise ValueError, 'range() called with zero step' self.start = start self.stop = stop self.step = step self.len = max(0, int((self.stop - self.start) / self.step))
|
def __init__(self, *a): """ Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the range""" self.start, self.stop, self.step = handleargs(a) self.len = max(0, (self.stop - self.start) // self.step)
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
if 0 <= i < self.len:
|
if 0 <= i <= self.len:
|
def __getitem__(self, i): if 0 <= i < self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range'
|
def get_python_inc(plat_specific=0):
|
def get_python_inc(plat_specific=0, prefix=None):
|
def get_python_inc(plat_specific=0): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": return os.path.join(prefix, "include", "python" + sys.version[:3]) elif os.name == "nt": return os.path.join(prefix, "Include") # include or Include? elif os.name == "mac": return os.path.join(prefix, "Include") else: raise DistutilsPlatformError, \ ("I don't know where Python installs its C header files " + "on platform '%s'") % os.name
|
prefix = (plat_specific and EXEC_PREFIX or PREFIX)
|
if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX)
|
def get_python_inc(plat_specific=0): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": return os.path.join(prefix, "include", "python" + sys.version[:3]) elif os.name == "nt": return os.path.join(prefix, "Include") # include or Include? elif os.name == "mac": return os.path.join(prefix, "Include") else: raise DistutilsPlatformError, \ ("I don't know where Python installs its C header files " + "on platform '%s'") % os.name
|
def get_python_lib(plat_specific=0, standard_lib=0):
|
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
|
def get_python_lib(plat_specific=0, standard_lib=0): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
|
prefix = (plat_specific and EXEC_PREFIX or PREFIX)
|
if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX)
|
def get_python_lib(plat_specific=0, standard_lib=0): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
|
_safechars = string.letters + string.digits + '!@%_-+=:,./'
|
_safechars = string.ascii_letters + string.digits + '!@%_-+=:,./'
|
def makepipeline(infile, steps, outfile): # Build a list with for each command: # [input filename or '', command string, kind, output filename or ''] list = [] for cmd, kind in steps: list.append(['', cmd, kind, '']) # # Make sure there is at least one step # if not list: list.append(['', 'cat', '--', '']) # # Take care of the input and output ends # [cmd, kind] = list[0][1:3] if kind[0] == 'f' and not infile: list.insert(0, ['', 'cat', '--', '']) list[0][0] = infile # [cmd, kind] = list[-1][1:3] if kind[1] == 'f' and not outfile: list.append(['', 'cat', '--', '']) list[-1][-1] = outfile # # Invent temporary files to connect stages that need files # garbage = [] for i in range(1, len(list)): lkind = list[i-1][2] rkind = list[i][2] if lkind[1] == 'f' or rkind[0] == 'f': temp = tempfile.mktemp() garbage.append(temp) list[i-1][-1] = list[i][0] = temp # for item in list: [inf, cmd, kind, outf] = item if kind[1] == 'f': cmd = 'OUT=' + quote(outf) + '; ' + cmd if kind[0] == 'f': cmd = 'IN=' + quote(inf) + '; ' + cmd if kind[0] == '-' and inf: cmd = cmd + ' <' + quote(inf) if kind[1] == '-' and outf: cmd = cmd + ' >' + quote(outf) item[1] = cmd # cmdlist = list[0][1] for item in list[1:]: [cmd, kind] = item[1:3] if item[0] == '': if 'f' in kind: cmd = '{ ' + cmd + '; }' cmdlist = cmdlist + ' |\n' + cmd else: cmdlist = cmdlist + '\n' + cmd # if garbage: rmcmd = 'rm -f' for file in garbage: rmcmd = rmcmd + ' ' + quote(file) trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15' cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd # return cmdlist
|
self.flag = 0
|
self.flags[flag] = 0
|
def clear_flags(self): """Reset all flags to zero""" for flag in self.flags: self.flag = 0
|
format = ' %' + directive
|
format = '%' + directive strf_output = time.strftime(format, tt)
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
|
time.strptime(time.strftime(format, tt), format)
|
time.strptime(strf_output, format)
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
|
self.fail('conversion specifier: %r failed.' % format)
|
self.fail("conversion specifier %r failed with '%s' input." % (format, strf_output))
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
|
elif compiler[:3] == "gcc" or compiler[:3] == "g++": return "-Wl,-R" + dir
|
elif sys.platform[:5] == "hp-ux": return "+s -L" + dir elif compiler[:3] == "gcc" or compiler[:3] == "g++": return "-Wl,-R" + dir
|
def runtime_library_dir_option(self, dir): # XXX Hackish, at the very least. See Python bug #445902: # http://sourceforge.net/tracker/index.php # ?func=detail&aid=445902&group_id=5470&atid=105470 # Linkers on different platforms need different options to # specify that directories need to be added to the list of # directories searched for dependencies when a dynamic library # is sought. GCC has to be told to pass the -R option through # to the linker, whereas other compilers just know this. # Other compilers may need something slightly different. At # this time, there's no way to determine this information from # the configuration data stored in the Python installation, so # we use this hack. compiler = os.path.basename(sysconfig.get_config_var("CC")) if sys.platform[:6] == "darwin": # MacOSX's linker doesn't understand the -R flag at all return "-L" + dir elif compiler[:3] == "gcc" or compiler[:3] == "g++": return "-Wl,-R" + dir else: return "-R" + dir
|
wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI:PythonCGISlave.py")
|
wrapper = "PythonCGISlave.py" if not os.path.exists("PythonCGISlave.py"): wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI", wrapper)
|
def buildcgiapplet(): buildtools.DEBUG=1 # Find the template # (there's no point in proceeding if we can't find it) template = buildtools.findtemplate() wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI:PythonCGISlave.py") # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select a CGI script:', 'TEXT', 'APPL') if not ok: return filename = srcfss.as_pathname() dstfilename = mkcgifilename(filename) dstfss, ok = macfs.StandardPutFile('Save application as:', os.path.basename(dstfilename)) if not ok: return dstfilename = dstfss.as_pathname() buildone(template, wrapper, filename, dstfilename) else: # Loop over all files to be processed for filename in sys.argv[1:]: dstfilename = mkcgifilename(filename) buildone(template, wrapper, filename, dstfilename)
|
def makeconfig(infp, outfp, modules):
|
def makeconfig(infp, outfp, modules, with_ifdef=0):
|
def makeconfig(infp, outfp, modules): m1 = regex.compile('-- ADDMODULE MARKER 1 --') m2 = regex.compile('-- ADDMODULE MARKER 2 --') while 1: line = infp.readline() if not line: break outfp.write(line) if m1 and m1.search(line) >= 0: m1 = None for mod in modules: if mod in never: continue outfp.write('extern void init%s();\n' % mod) elif m2 and m2.search(line) >= 0: m2 = None for mod in modules: if mod in never: continue outfp.write('\t{"%s", init%s},\n' % (mod, mod)) if m1: sys.stderr.write('MARKER 1 never found\n') elif m2: sys.stderr.write('MARKER 2 never found\n')
|
return pos, (val)
|
return (pos, len(val))
|
def _setval(self, pos, val): f = _open(self._datfile, 'rb+') f.seek(pos) f.write(val) f.close() return pos, (val)
|
raise socket.error, err
|
raise socket.error, (err, errorcode[err])
|
def connect(self, address): self.connected = False err = self.socket.connect_ex(address) # XXX Should interpret Winsock return values if err in (EINPROGRESS, EALREADY, EWOULDBLOCK): return if err in (0, EISCONN): self.addr = address self.connected = True self.handle_connect() else: raise socket.error, err
|
raise socket.error, why
|
raise
|
def accept(self): # XXX can return either an address pair or None try: conn, addr = self.socket.accept() return conn, addr except socket.error, why: if why[0] == EWOULDBLOCK: pass else: raise socket.error, why
|
raise socket.error, why
|
raise
|
def send(self, data): try: result = self.socket.send(data) return result except socket.error, why: if why[0] == EWOULDBLOCK: return 0 else: raise socket.error, why return 0
|
raise socket.error, why
|
raise
|
def recv(self, buffer_size): try: data = self.socket.recv(buffer_size) if not data: # a closed connection is indicated by signaling # a read condition, and having recv() return 0. self.handle_close() return '' else: return data except socket.error, why: # winsock sometimes throws ENOTCONN if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]: self.handle_close() return '' else: raise socket.error, why
|
sectname = "formatter_%s" % form
|
sectname = "formatter_%s" % string.strip(form)
|
def _create_formatters(cp): """Create and return formatters""" flist = cp.get("formatters", "keys") if not len(flist): return {} flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None c = logging.Formatter if "class" in opts: class_name = cp.get(sectname, "class") if class_name: c = _resolve(class_name) f = c(fs, dfs) formatters[form] = f return formatters
|
sectname = "handler_%s" % hand
|
sectname = "handler_%s" % string.strip(hand)
|
def _install_handlers(cp, formatters): """Install and return handlers""" hlist = cp.get("handlers", "keys") if not len(hlist): return {} hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" klass = eval(klass, vars(logging)) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) #temporary hack for FileHandler and MemoryHandler. if klass == logging.handlers.MemoryHandler: if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for h, t in fixups: h.setTarget(handlers[t]) return handlers
|
log.addHandler(handlers[hand])
|
log.addHandler(handlers[string.strip(hand)])
|
def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers[:]: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1
|
logger.addHandler(handlers[hand])
|
logger.addHandler(handlers[string.strip(hand)])
|
def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers[:]: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1
|
if module not in save_modules:
|
if module not in save_modules and module.startswith("test."):
|
def main(tests=None, testdir=None): """Execute a test suite. This also parses command-line options and modifies its behaviour accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxs') except getopt.error, msg: print msg print __doc__ return 2 verbose = 0 quiet = 0 generate = 0 exclude = 0 single = 0 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] test_support.verbose = verbose # Tell tests to be moderately quiet save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: if not quiet: print "test", test, print "skipped -- an optional feature could not be imported" skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules: test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
|
OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace()
|
if self.returntype.__class__ != OSErrType: OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace()
|
def checkit(self): OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX
|
class ResFunction(ResMixIn, FunctionGenerator): pass class ResMethod(ResMixIn, MethodGenerator): pass
|
class ResFunction(ResMixIn, OSErrFunctionGenerator): pass class ResMethod(ResMixIn, OSErrMethodGenerator): pass
|
def checkit(self): OutLbrace() Output("OSErr _err = ResError();") Output("if (_err != noErr) return PyMac_Error(_err);") OutRbrace() FunctionGenerator.checkit(self) # XXX
|
self._link(body, headers, include_dirs, libraries, library_dirs, lang)
|
src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang)
|
def try_run (self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise. """ from distutils.ccompiler import CompileError, LinkError self._check_compiler() try: self._link(body, headers, include_dirs, libraries, library_dirs, lang) self.spawn([exe]) ok = 1 except (CompileError, LinkError, DistutilsExecError): ok = 0
|
specialsre = re.compile(r'[][\()<>@,:;".]') escapesre = re.compile(r'[][\()"]')
|
specialsre = re.compile(r'[][\\()<>@,:;".]') escapesre = re.compile(r'[][\\()"]')
|
def _qdecode(s): import quopri as _quopri
|
posix.chmod(tempname, statbuf[ST_MODE] & 0x7777)
|
posix.chmod(tempname, statbuf[ST_MODE] & 07777)
|
def fix(filename):
|
self._output = open(self._filename, "w")
|
try: perm = os.fstat(self._file.fileno())[stat.ST_MODE] except: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: os.chmod(self._filename, perm) except: pass
|
def readline(self): if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = 0 self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = 1 else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or ".bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next three lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") self._output = open(self._filename, "w") self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") line = self._file.readline() if line: self._lineno = self._lineno + 1 self._filelineno = self._filelineno + 1 return line self.nextfile() # Recursive call return self.readline()
|
for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']:
|
for pattern in [' at 0x[0-9a-f]{6,}(>+)$', ' at [0-9A-F]{8,}(>+)$']:
|
def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '>', text) return text
|
return re.sub(pattern, '>', text)
|
return re.sub(pattern, '\\1', text)
|
def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent; we check two cases. for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']: if re.search(pattern, repr(Exception)): return re.sub(pattern, '>', text) return text
|
suffix, name = '', None if type(thing) is type(''): try: object = locate(thing, forceload) except ErrorDuringImport, value: print value return if not object: print 'no Python documentation found for %s' % repr(thing) return parts = split(thing, '.') if len(parts) > 1: suffix = ' in ' + join(parts[:-1], '.') name = parts[-1] thing = object desc = describe(thing) module = inspect.getmodule(thing) if not suffix and module and module is not thing: suffix = ' in module ' + module.__name__ pager(title % (desc + suffix) + '\n\n' + text.document(thing, name)) def writedoc(key, forceload=0):
|
try: object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ pager(title % desc + '\n\n' + text.document(object, name)) except (ImportError, ErrorDuringImport), value: print value def writedoc(thing, forceload=0):
|
def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" suffix, name = '', None if type(thing) is type(''): try: object = locate(thing, forceload) except ErrorDuringImport, value: print value return if not object: print 'no Python documentation found for %s' % repr(thing) return parts = split(thing, '.') if len(parts) > 1: suffix = ' in ' + join(parts[:-1], '.') name = parts[-1] thing = object desc = describe(thing) module = inspect.getmodule(thing) if not suffix and module and module is not thing: suffix = ' in module ' + module.__name__ pager(title % (desc + suffix) + '\n\n' + text.document(thing, name))
|
object = locate(key, forceload) except ErrorDuringImport, value:
|
object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) file = open(name + '.html', 'w') file.write(page) file.close() print 'wrote', name + '.html' except (ImportError, ErrorDuringImport), value:
|
def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object = locate(key, forceload) except ErrorDuringImport, value: print value else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key)
|
else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key)
|
def writedoc(key, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object = locate(key, forceload) except ErrorDuringImport, value: print value else: if object: page = html.page(describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key)
|
|
return type(x) is types.StringType and find(x, os.sep) >= 0
|
return isinstance(x, str) and find(x, os.sep) >= 0
|
def ispath(x): return type(x) is types.StringType and find(x, os.sep) >= 0
|
_mesg('untagged responses dump:%s%s' % (t, j(l, t)))
|
_mesg('untagged responses dump:%s%s' % (t, t.join(l)))
|
def _dump_ur(dict): # Dump untagged responses (in `dict'). l = dict.items() if not l: return t = '\n\t\t' l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l) _mesg('untagged responses dump:%s%s' % (t, j(l, t)))
|
def capwords(str, pat):
|
def capwords(str, pat='[^a-zA-Z0-9_]+'):
|
def capwords(str, pat): import string words = split(str, pat, 1) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "")
|
words = split(str, pat, 1)
|
words = splitx(str, pat)
|
def capwords(str, pat): import string words = split(str, pat, 1) for i in range(0, len(words), 2): words[i] = string.capitalize(words[i]) return string.joinfields(words, "")
|
if value < 0: value = value + 0x100000000L
|
def write32u(output, value): if value < 0: value = value + 0x100000000L output.write(struct.pack("<L", value))
|
|
isize = read32(self.fileobj) if crc32%0x100000000L != self.crc%0x100000000L:
|
isize = U32(read32(self.fileobj)) if U32(crc32) != U32(self.crc):
|
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = read32(self.fileobj) if crc32%0x100000000L != self.crc%0x100000000L: raise ValueError, "CRC check failed" elif isize != self.size: raise ValueError, "Incorrect length of data produced"
|
write32(self.fileobj, self.size)
|
write32u(self.fileobj, self.size)
|
def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) write32(self.fileobj, self.crc) write32(self.fileobj, self.size) self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None
|
for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0')
|
for i in range(count // 1024): self.write(1024 * '\0') self.write((count % 1024) * '\0')
|
def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count/1024): self.read(1024) self.read(count % 1024)
|
for i in range(count/1024): self.read(1024)
|
for i in range(count // 1024): self.read(1024)
|
def seek(self, offset): if self.mode == WRITE: if offset < self.offset: raise IOError('Negative seek in write mode') count = offset - self.offset for i in range(count/1024): self.write(1024*'\0') self.write((count%1024)*'\0') elif self.mode == READ: if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count/1024): self.read(1024) self.read(count % 1024)
|
tz_name= time.tzname[0]
|
tz_name = time.tzname[0] if tz_name.lower() in ("UTC", "GMT"): return
|
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name= time.tzname[0] try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime.strptime(tz_name, "%Z")[8] self.failUnlessEqual(tz_value, -1) finally: time.tzname = original_tzname time.daylight = original_daylight
|
self.failUnlessEqual(tz_value, -1)
|
self.failUnlessEqual(tz_value, -1, "%s lead to a timezone value of %s instead of -1 when " "time.daylight set to %s and passing in %s" % (time.tzname, tz_value, time.daylight, tz_name))
|
def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight if sys.platform == "mac": return #MacOS9 has severely broken timezone support. tz_name= time.tzname[0] try: original_tzname = time.tzname original_daylight = time.daylight time.tzname = (tz_name, tz_name) time.daylight = 1 tz_value = _strptime.strptime(tz_name, "%Z")[8] self.failUnlessEqual(tz_value, -1) finally: time.tzname = original_tzname time.daylight = original_daylight
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.