rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
try: errcode = string.atoi(code) except(ValueError): errcode = -1
|
def getreply(self): """Get a reply from the server. Returns a tuple consisting of:
|
|
On Unix, there are three possible config files: pydistutils.cfg in the Distutils installation directory (ie. where the top-level Distutils __inst__.py file lives), .pydistutils.cfg in the user's home directory, and setup.cfg in the current directory. On Windows and Mac OS, there are two possible config files: pydistutils.cfg in the Python installation directory (sys.prefix) and setup.cfg in the current directory.
|
There are three possible config files: distutils.cfg in the Distutils installation directory (ie. where the top-level Distutils __inst__.py file lives), a file in the user's home directory named .pydistutils.cfg on Unix and pydistutils.cfg on Windows/Mac, and setup.cfg in the current directory.
|
def find_config_files (self): """Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions).
|
eq(msg.epilogue, '\n\n')
|
eq(msg.epilogue, '\n')
|
def test_mondo_message(self): eq = self.assertEqual neq = self.ndiffAssertEqual msg = self._msgobj('crispin-torture.txt') payload = msg.get_payload() eq(type(payload), ListType) eq(len(payload), 12) eq(msg.preamble, None) eq(msg.epilogue, '\n\n') # Probably the best way to verify the message is parsed correctly is to # dump its structure and compare it against the known structure. fp = StringIO() _structure(msg, fp=fp) neq(fp.getvalue(), """\
|
existed = sectdict.has_key(key)
|
existed = sectdict.has_key(option)
|
def remove_option(self, section, option): """Remove an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) existed = sectdict.has_key(key) if existed: del sectdict[key] return existed
|
del sectdict[key]
|
del sectdict[option]
|
def remove_option(self, section, option): """Remove an option.""" if not section or section == "DEFAULT": sectdict = self.__defaults else: try: sectdict = self.__sections[section] except KeyError: raise NoSectionError(section) existed = sectdict.has_key(key) if existed: del sectdict[key] return existed
|
subconvert(ifp.read(), ofp, table, discards, autoclosing)
|
subconvert(data, ofp, table, discards, autoclosing)
|
def convert(ifp, ofp, table={}, discards=(), autoclosing=()): try: subconvert(ifp.read(), ofp, table, discards, autoclosing) except IOError, (err, msg): if err != errno.EPIPE: raise
|
"calling %s returned %s, not a test" % obj,test
|
"calling %s returned %s, not a test" % (obj,test)
|
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
|
<type 'None'>
|
<type 'NoneType'>
|
... def g():
|
<type 'None'>
|
<type 'NoneType'>
|
... def f(self):
|
file.warn ("exclude (!) doesn't apply to " + "whole directory trees")
|
manifest.warn ("exclude (!) doesn't apply to " + "whole directory trees")
|
def read_manifest (self):
|
file.warn ("can't have multiple words unless first word " + "('%s') is a directory name" % words[0])
|
manifest.warn ("can't have multiple words unless first word " + "('%s') is a directory name" % words[0])
|
def read_manifest (self):
|
file.warn ("no files excluded by '%s'" % pattern)
|
manifest.warn ("no files excluded by '%s'" % pattern)
|
def read_manifest (self):
|
self.sock.send(str)
|
if self.sock: self.sock.send(str) else: raise SMTPServerDisconnected
|
def send(self, str): """Send `str' to the server.""" if self.debuglevel > 0: print 'send:', `str` self.sock.send(str)
|
This method will return normally if the mail is accepted for at least one recipiant .Otherwise it will throw an exception (either SMTPSenderRefused,SMTPRecipientsRefused, or SMTPDataError) That is, if this method does not throw an excception, then someone
|
This method will return normally if the mail is accepted for at least one recipiant. Otherwise it will throw an exception (either SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError) That is, if this method does not throw an exception, then someone
|
def sendmail(self,from_addr,to_addrs,msg): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send.
|
>>> tolist= [ "[email protected]", ... "[email protected]", ... "[email protected]", ... "[email protected]"]
|
>>> tolist=["[email protected]","[email protected]","[email protected]","[email protected]"]
|
def sendmail(self,from_addr,to_addrs,msg): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send.
|
senderr[each]=(code,resp)
|
senderrs[each]=(code,resp)
|
def sendmail(self,from_addr,to_addrs,msg): """ This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. - to_addrs : a list of addresses to send this mail to - msg : the message to send.
|
if self.elements is XMLParser.elements: self.__fixelements()
|
def __init__(self): self.reset() if self.elements is XMLParser.elements: self.__fixelements()
|
|
self.syntax_error('reference to unknown entity')
|
self.syntax_error("reference to unknown entity `&%s;'" % str)
|
def translate_references(self, data, all = 1): i = 0 while 1: res = amp.search(data, i) if res is None: return data res = ref.match(data, res.start(0)) if res is None: self.syntax_error("bogus `&'") i =i+1 continue i = res.end(0) if data[i - 1] != ';': self.syntax_error("`;' missing after entity/char reference") i = i-1 str = res.group(1) pre = data[:res.start(0)] post = data[i:] if str[0] == '#': if str[1] == 'x': str = chr(string.atoi(str[2:], 16)) else: str = chr(string.atoi(str[1:])) data = pre + str + post i = res.start(0)+len(str) elif all: if self.entitydefs.has_key(str): data = pre + self.entitydefs[str] + post i = res.start(0) # rescan substituted text else: self.syntax_error('reference to unknown entity') # can't do it, so keep the entity ref in data = pre + '&' + str + ';' + post i = res.start(0) + len(str) + 2 else: # just translating character references pass # i is already postioned correctly
|
self.syntax_error('reference to unknown entity')
|
self.syntax_error("reference to unknown entity `&%s;'" % name)
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: data = rawdata[i:j] if self.__at_start and space.match(data) is None: self.syntax_error('illegal data at start of file') self.__at_start = 0 if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:i], '\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise RuntimeError, 'only XML version 1.0 supported' if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue elif rawdata[i] == '&': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + string.count(res.group(0), '\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.entitydefs.has_key(name): self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.syntax_error('reference to unknown entity') self.unknown_entityref(name) self.lineno = self.lineno + string.count(res.group(0), '\n') continue elif rawdata[i] == ']': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1][0])
|
childNodeTypes = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
|
def _getElementsByTagNameNSHelper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.tagName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _getElementsByTagNameNSHelper(node, nsURI, localName, rc) return rc
|
|
childNodeTypes = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE)
|
def __delitem__(self, attname_or_tuple): node = self[attname_or_tuple] node.unlink() del self._attrs[node.name] del self._attrsNS[(node.namespaceURI, node.localName)] self.length = len(self._attrs)
|
|
childNodeTypes = ()
|
def _get_attributes(self): return AttributeList(self._attrs, self._attrsNS)
|
|
childNodeTypes = ()
|
def writexml(self, writer): writer.write("<!--%s-->" % self.data)
|
|
childNodeTypes = ()
|
def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data))
|
|
magic = unpack('<i', buf[:4])[0]
|
magic = unpack('<i', buf[:4])[0] & MASK
|
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < len(buf) and tend < len(buf): tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
|
msgcount &= MASK masteridx &= MASK transidx &= MASK
|
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < len(buf) and tend < len(buf): tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
|
|
mend = moff + mlen
|
moff &= MASK mend = moff + (mlen & MASK)
|
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < len(buf) and tend < len(buf): tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
|
tend = toff + tlen if mend < len(buf) and tend < len(buf):
|
toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen:
|
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < len(buf) and tend < len(buf): tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
|
if ((localName == "*" or node.tagName == localName) and
|
if ((localName == "*" or node.localName == localName) and
|
def _getElementsByTagNameNSHelper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.tagName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _getElementsByTagNameNSHelper(node, nsURI, localName, rc) return rc
|
_getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
|
rc = [] _getElementsByTagNameNSHelper(self, namespaceURI, localName, rc) return rc
|
def getElementsByTagNameNS(self, namespaceURI, localName): _getElementsByTagNameNSHelper(self, namespaceURI, localName, [])
|
_getElementsByTagNameNSHelper(self, namespaceURI, localName)
|
rc = [] _getElementsByTagNameNSHelper(self, namespaceURI, localName, rc) return rc
|
def getElementsByTagNameNS(self, namespaceURI, localName): _getElementsByTagNameNSHelper(self, namespaceURI, localName)
|
opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx')
|
opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')
|
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg print __doc__%globals() sys.exit(2) # Begin SLB 2/24/99: Added extra_roots variable to # collect extra roots. extra_roots = [] # End SLB 2/24/99 for o, a in opts: if o == '-R': restart = 1 if o == '-d': dumpfile = a if o == '-m': maxpage = string.atoi(a) if o == '-n': norun = 1 if o == '-q': verbose = 0 if o == '-r': roundsize = string.atoi(a) # Begin SLB 2/24/99: Added processing for # -t option. if o == '-t': extra_roots.append(a) # End SLB 2/24/99 if o == '-v': verbose = verbose + 1 if o == '-x': checkext = not checkext if verbose > 0: print AGENTNAME, "version", __version__ if restart: c = load_pickle(dumpfile=dumpfile, verbose=verbose) else: c = Checker() c.setflags(checkext=checkext, verbose=verbose, maxpage=maxpage, roundsize=roundsize) if not restart and not args: args.append(DEFROOT) for arg in args: c.addroot(arg) # Begin SLB 2/24/99. The -t flag is only needed if external # links are not to be checked. So -t values are ignored unless # -x was specified. if not checkext: for root in extra_roots: # Make sure it's terminated by a slash, # so that addroot doesn't discard the last # directory component. if root[-1] != "/": root = root + "/" c.addroot(root) # End SLB 2/24/99 try: if not norun: try: c.run() except KeyboardInterrupt: if verbose > 0: print "[run interrupted]" try: c.report() except KeyboardInterrupt: if verbose > 0: print "[report interrupted]" finally: if c.save_pickle(dumpfile): if dumpfile == DUMPFILE: print "Use ``%s -R'' to restart." % sys.argv[0] else: print "Use ``%s -R -d %s'' to restart." % (sys.argv[0], dumpfile)
|
if o == '-t': extra_roots.append(a)
|
if o == '-t': extra_roots.append(a) if o == '-a': nonames = not nonames
|
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg print __doc__%globals() sys.exit(2) # Begin SLB 2/24/99: Added extra_roots variable to # collect extra roots. extra_roots = [] # End SLB 2/24/99 for o, a in opts: if o == '-R': restart = 1 if o == '-d': dumpfile = a if o == '-m': maxpage = string.atoi(a) if o == '-n': norun = 1 if o == '-q': verbose = 0 if o == '-r': roundsize = string.atoi(a) # Begin SLB 2/24/99: Added processing for # -t option. if o == '-t': extra_roots.append(a) # End SLB 2/24/99 if o == '-v': verbose = verbose + 1 if o == '-x': checkext = not checkext if verbose > 0: print AGENTNAME, "version", __version__ if restart: c = load_pickle(dumpfile=dumpfile, verbose=verbose) else: c = Checker() c.setflags(checkext=checkext, verbose=verbose, maxpage=maxpage, roundsize=roundsize) if not restart and not args: args.append(DEFROOT) for arg in args: c.addroot(arg) # Begin SLB 2/24/99. The -t flag is only needed if external # links are not to be checked. So -t values are ignored unless # -x was specified. if not checkext: for root in extra_roots: # Make sure it's terminated by a slash, # so that addroot doesn't discard the last # directory component. if root[-1] != "/": root = root + "/" c.addroot(root) # End SLB 2/24/99 try: if not norun: try: c.run() except KeyboardInterrupt: if verbose > 0: print "[run interrupted]" try: c.report() except KeyboardInterrupt: if verbose > 0: print "[report interrupted]" finally: if c.save_pickle(dumpfile): if dumpfile == DUMPFILE: print "Use ``%s -R'' to restart." % sys.argv[0] else: print "Use ``%s -R -d %s'' to restart." % (sys.argv[0], dumpfile)
|
maxpage=maxpage, roundsize=roundsize)
|
maxpage=maxpage, roundsize=roundsize, nonames=nonames )
|
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg print __doc__%globals() sys.exit(2) # Begin SLB 2/24/99: Added extra_roots variable to # collect extra roots. extra_roots = [] # End SLB 2/24/99 for o, a in opts: if o == '-R': restart = 1 if o == '-d': dumpfile = a if o == '-m': maxpage = string.atoi(a) if o == '-n': norun = 1 if o == '-q': verbose = 0 if o == '-r': roundsize = string.atoi(a) # Begin SLB 2/24/99: Added processing for # -t option. if o == '-t': extra_roots.append(a) # End SLB 2/24/99 if o == '-v': verbose = verbose + 1 if o == '-x': checkext = not checkext if verbose > 0: print AGENTNAME, "version", __version__ if restart: c = load_pickle(dumpfile=dumpfile, verbose=verbose) else: c = Checker() c.setflags(checkext=checkext, verbose=verbose, maxpage=maxpage, roundsize=roundsize) if not restart and not args: args.append(DEFROOT) for arg in args: c.addroot(arg) # Begin SLB 2/24/99. The -t flag is only needed if external # links are not to be checked. So -t values are ignored unless # -x was specified. if not checkext: for root in extra_roots: # Make sure it's terminated by a slash, # so that addroot doesn't discard the last # directory component. if root[-1] != "/": root = root + "/" c.addroot(root) # End SLB 2/24/99 try: if not norun: try: c.run() except KeyboardInterrupt: if verbose > 0: print "[run interrupted]" try: c.report() except KeyboardInterrupt: if verbose > 0: print "[report interrupted]" finally: if c.save_pickle(dumpfile): if dumpfile == DUMPFILE: print "Use ``%s -R'' to restart." % sys.argv[0] else: print "Use ``%s -R -d %s'' to restart." % (sys.argv[0], dumpfile)
|
for root in extra_roots: if root[-1] != "/": root = root + "/" c.addroot(root)
|
for root in extra_roots: if root[-1] != "/": root = root + "/" c.addroot(root, add_to_do = 0)
|
def main(): checkext = CHECKEXT verbose = VERBOSE maxpage = MAXPAGE roundsize = ROUNDSIZE dumpfile = DUMPFILE restart = 0 norun = 0 try: # Begin SLB 2/24/99: Added -t option here. opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vx') # End SLB 2/24/99 except getopt.error, msg: sys.stdout = sys.stderr print msg print __doc__%globals() sys.exit(2) # Begin SLB 2/24/99: Added extra_roots variable to # collect extra roots. extra_roots = [] # End SLB 2/24/99 for o, a in opts: if o == '-R': restart = 1 if o == '-d': dumpfile = a if o == '-m': maxpage = string.atoi(a) if o == '-n': norun = 1 if o == '-q': verbose = 0 if o == '-r': roundsize = string.atoi(a) # Begin SLB 2/24/99: Added processing for # -t option. if o == '-t': extra_roots.append(a) # End SLB 2/24/99 if o == '-v': verbose = verbose + 1 if o == '-x': checkext = not checkext if verbose > 0: print AGENTNAME, "version", __version__ if restart: c = load_pickle(dumpfile=dumpfile, verbose=verbose) else: c = Checker() c.setflags(checkext=checkext, verbose=verbose, maxpage=maxpage, roundsize=roundsize) if not restart and not args: args.append(DEFROOT) for arg in args: c.addroot(arg) # Begin SLB 2/24/99. The -t flag is only needed if external # links are not to be checked. So -t values are ignored unless # -x was specified. if not checkext: for root in extra_roots: # Make sure it's terminated by a slash, # so that addroot doesn't discard the last # directory component. if root[-1] != "/": root = root + "/" c.addroot(root) # End SLB 2/24/99 try: if not norun: try: c.run() except KeyboardInterrupt: if verbose > 0: print "[run interrupted]" try: c.report() except KeyboardInterrupt: if verbose > 0: print "[report interrupted]" finally: if c.save_pickle(dumpfile): if dumpfile == DUMPFILE: print "Use ``%s -R'' to restart." % sys.argv[0] else: print "Use ``%s -R -d %s'' to restart." % (sys.argv[0], dumpfile)
|
def addroot(self, root):
|
def addroot(self, root, add_to_do = 1):
|
def addroot(self, root): if root not in self.roots: troot = root scheme, netloc, path, params, query, fragment = \ urlparse.urlparse(root) i = string.rfind(path, "/") + 1 if 0 < i < len(path): path = path[:i] troot = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) self.roots.append(troot) self.addrobot(root) # Begin SLB 2/24/99: Modified this call to respect # the fact that the "done" and "todo" dictionaries # are now (URL, fragment) pairs self.newlink((root, ""), ("<root>", root)) # End SLB 2/24/99
|
self.newlink((root, ""), ("<root>", root))
|
if add_to_do: self.newlink((root, ""), ("<root>", root))
|
def addroot(self, root): if root not in self.roots: troot = root scheme, netloc, path, params, query, fragment = \ urlparse.urlparse(root) i = string.rfind(path, "/") + 1 if 0 < i < len(path): path = path[:i] troot = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) self.roots.append(troot) self.addrobot(root) # Begin SLB 2/24/99: Modified this call to respect # the fact that the "done" and "todo" dictionaries # are now (URL, fragment) pairs self.newlink((root, ""), ("<root>", root)) # End SLB 2/24/99
|
url, local_fragment = url_pair self.name_table[url] = page if local_fragment and local_fragment not in page.getnames(): self.setbad(url_pair, ("Missing name anchor `%s'" % local_fragment)) for info in page.getlinkinfos():
|
self.name_table[url] = page if local_fragment and local_fragment not in page.getnames(): self.setbad(url_pair, ("Missing name anchor `%s'" % local_fragment)) for info in page.getlinkinfos():
|
def dopage(self, url_pair):
|
self.done[url].append(origin)
|
if origin not in self.done[url]: self.done[url].append(origin)
|
def newdonelink(self, url, origin): self.done[url].append(origin)
|
if self.bad.has_key(url): source, rawlink = origin triple = url, rawlink, self.bad[url] self.seterror(source, triple)
|
def newdonelink(self, url, origin): self.done[url].append(origin)
|
|
self.todo[url].append(origin)
|
if origin not in self.todo[url]: self.todo[url].append(origin)
|
def newtodolink(self, url, origin):
|
if path[-1] != os.sep: url = url + '/'
|
def open_file(self, url): path = urllib.url2pathname(urllib.unquote(url)) if path[-1] != os.sep: url = url + '/' if os.path.isdir(path): indexpath = os.path.join(path, "index.html") if os.path.exists(indexpath): return self.open_file(url + "index.html") try: names = os.listdir(path) except os.error, msg: raise IOError, msg, sys.exc_traceback names.sort() s = MyStringIO("file:"+url, {'content-type': 'text/html'}) s.write('<BASE HREF="file:%s">\n' % urllib.quote(os.path.join(path, ""))) for name in names: q = urllib.quote(name) s.write('<A HREF="%s">%s</A>\n' % (q, q)) s.seek(0) return s return urllib.FancyURLopener.open_file(self, path)
|
|
return urllib.FancyURLopener.open_file(self, path)
|
return urllib.FancyURLopener.open_file(self, url)
|
def open_file(self, url): path = urllib.url2pathname(urllib.unquote(url)) if path[-1] != os.sep: url = url + '/' if os.path.isdir(path): indexpath = os.path.join(path, "index.html") if os.path.exists(indexpath): return self.open_file(url + "index.html") try: names = os.listdir(path) except os.error, msg: raise IOError, msg, sys.exc_traceback names.sort() s = MyStringIO("file:"+url, {'content-type': 'text/html'}) s.write('<BASE HREF="file:%s">\n' % urllib.quote(os.path.join(path, ""))) for name in names: q = urllib.quote(name) s.write('<A HREF="%s">%s</A>\n' % (q, q)) s.seek(0) return s return urllib.FancyURLopener.open_file(self, path)
|
sys.stderr.write ("warning: template: %s\n" % msg)
|
sys.stderr.write ("warning: %s\n" % msg)
|
def __warn (self, msg): sys.stderr.write ("warning: template: %s\n" % msg)
|
def process_line(self, line): words = string.split (line) action = words[0] if action in ('include','exclude', 'global-include','global-exclude'): if len (words) < 2:
|
def process_line (self, line): words = string.split (line) action = words[0] if action in ('include','exclude', 'global-include','global-exclude'): if len (words) < 2: self.warn \ ("invalid template line: " + "'%s' expects <pattern1> <pattern2> ..." % action) return pattern_list = map(convert_path, words[1:]) elif action in ('recursive-include','recursive-exclude'): if len (words) < 3: self.warn \ ("invalid template line: " + "'%s' expects <dir> <pattern1> <pattern2> ..." % action) return dir = convert_path(words[1]) pattern_list = map (convert_path, words[2:]) elif action in ('graft','prune'): if len (words) != 2: self.warn \ ("invalid template line: " + "'%s' expects a single <dir_pattern>" % action) return dir_pattern = convert_path (words[1]) else: self.warn ("invalid template line: " + "unknown action '%s'" % action) return if action == 'include': self.debug_print("include " + string.join(pattern_list)) for pattern in pattern_list: if not self.select_pattern (pattern, anchor=1): self.warn ("no files found matching '%s'" % pattern) elif action == 'exclude': self.debug_print("exclude " + string.join(pattern_list)) for pattern in pattern_list: if not self.exclude_pattern (pattern, anchor=1): self.warn ( "no previously-included files found matching '%s'"% pattern) elif action == 'global-include': self.debug_print("global-include " + string.join(pattern_list)) for pattern in pattern_list: if not self.select_pattern (pattern, anchor=0): self.warn (("no files found matching '%s' " + "anywhere in distribution") % pattern) elif action == 'global-exclude': self.debug_print("global-exclude " + string.join(pattern_list)) for pattern in pattern_list: if not self.exclude_pattern (pattern, anchor=0):
|
def process_line(self, line):
|
("invalid template line: " + "'%s' expects <pattern1> <pattern2> ..." % action) return pattern_list = map(convert_path, words[1:]) elif action in ('recursive-include','recursive-exclude'): if len (words) < 3:
|
(("no previously-included files matching '%s' " + "found anywhere in distribution") % pattern) elif action == 'recursive-include': self.debug_print("recursive-include %s %s" % (dir, string.join(pattern_list))) for pattern in pattern_list: if not self.select_pattern (pattern, prefix=dir): self.warn (("no files found matching '%s' " + "under directory '%s'") % (pattern, dir)) elif action == 'recursive-exclude': self.debug_print("recursive-exclude %s %s" % (dir, string.join(pattern_list))) for pattern in pattern_list: if not self.exclude_pattern(pattern, prefix=dir):
|
def process_line(self, line):
|
("invalid template line: " + "'%s' expects <dir> <pattern1> <pattern2> ..." % action) return dir = convert_path(words[1]) pattern_list = map (convert_path, words[2:]) elif action in ('graft','prune'): if len (words) != 2: self.warn \ ("invalid template line: " + "'%s' expects a single <dir_pattern>" % action) return dir_pattern = convert_path (words[1]) else: self.warn ("invalid template line: " + "unknown action '%s'" % action) return if action == 'include': self.debug_print("include " + string.join(pattern_list)) for pattern in pattern_list: if not self.select_pattern (pattern, anchor=1): self.warn ("no files found matching '%s'" % pattern) elif action == 'exclude': self.debug_print("exclude " + string.join(pattern_list)) for pattern in pattern_list: if not self.exclude_pattern (pattern, anchor=1): self.warn ( "no previously-included files found matching '%s'"% pattern) elif action == 'global-include': self.debug_print("global-include " + string.join(pattern_list)) for pattern in pattern_list: if not self.select_pattern (pattern, anchor=0): self.warn (("no files found matching '%s' " + "anywhere in distribution") % pattern) elif action == 'global-exclude': self.debug_print("global-exclude " + string.join(pattern_list)) for pattern in pattern_list: if not self.exclude_pattern (pattern, anchor=0): self.warn \ (("no previously-included files matching '%s' " + "found anywhere in distribution") % pattern) elif action == 'recursive-include': self.debug_print("recursive-include %s %s" % (dir, string.join(pattern_list))) for pattern in pattern_list: if not self.select_pattern (pattern, prefix=dir): self.warn (("no files found matching '%s' " + "under directory '%s'") % (pattern, dir)) elif action == 'recursive-exclude': self.debug_print("recursive-exclude %s %s" % (dir, string.join(pattern_list))) for pattern in pattern_list: if not self.exclude_pattern(pattern, prefix=dir): self.warn \ (("no previously-included files matching '%s' " + "found under directory '%s'") % (pattern, dir)) elif action == 'graft': self.debug_print("graft " + dir_pattern) if not self.select_pattern(None, prefix=dir_pattern): self.warn ("no directories found matching '%s'" % dir_pattern) elif action == 'prune': self.debug_print("prune " + dir_pattern) if not self.exclude_pattern(None, prefix=dir_pattern): self.warn \ (("no previously-included directories found " + "matching '%s'") % dir_pattern) else: raise RuntimeError, \ "this cannot happen: invalid action '%s'" % action
|
(("no previously-included files matching '%s' " + "found under directory '%s'") % (pattern, dir)) elif action == 'graft': self.debug_print("graft " + dir_pattern) if not self.select_pattern(None, prefix=dir_pattern): self.warn ("no directories found matching '%s'" % dir_pattern) elif action == 'prune': self.debug_print("prune " + dir_pattern) if not self.exclude_pattern(None, prefix=dir_pattern): self.warn \ (("no previously-included directories found " + "matching '%s'") % dir_pattern) else: raise RuntimeError, \ "this cannot happen: invalid action '%s'" % action
|
def process_line(self, line):
|
if iconv_incs: if iconv_libs:
|
if platform not in ['darwin'] and iconv_incs is not None: if iconv_libs is not None:
|
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
|
raise TypeError, 'string payload expected'
|
raise TypeError, 'string payload expected: %s' % type(payload)
|
def _handle_text(self, msg): payload = msg.get_payload() if not isinstance(payload, StringType): raise TypeError, 'string payload expected' if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload)
|
g = self.__class__(s)
|
g = self.__class__(s, self._mangle_from_, self.__maxheaderlen)
|
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] for part in msg.get_payload(): s = StringIO() g = self.__class__(s) g(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: self._fp.write(msg.epilogue)
|
def _handle_message_rfc822(self, msg):
|
def _handle_message_delivery_status(self, msg): blocks = [] for part in msg.get_payload(): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g(part, unixfrom=0) text = s.getvalue() lines = text.split('\n') if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.append(text) self._fp.write(NL.join(blocks)) def _handle_message(self, msg):
|
def _handle_message_rfc822(self, msg): s = StringIO() g = self.__class__(s) # A message/rfc822 should contain a scalar payload which is another # Message object. Extract that object, stringify it, and write that # out. g(msg.get_payload(), unixfrom=0) self._fp.write(s.getvalue())
|
g = self.__class__(s)
|
g = self.__class__(s, self._mangle_from_, self.__maxheaderlen)
|
def _handle_message_rfc822(self, msg): s = StringIO() g = self.__class__(s) # A message/rfc822 should contain a scalar payload which is another # Message object. Extract that object, stringify it, and write that # out. g(msg.get_payload(), unixfrom=0) self._fp.write(s.getvalue())
|
if part.get_main_type('text') == 'text':
|
maintype = part.get_main_type('text') if maintype == 'text':
|
def _dispatch(self, msg): for part in msg.walk(): if part.get_main_type('text') == 'text': print >> self, part.get_payload(decode=1) else: print >> self, self._fmt % { 'type' : part.get_type('[no MIME type]'), 'maintype' : part.get_main_type('[no main MIME type]'), 'subtype' : part.get_subtype('[no sub-MIME type]'), 'filename' : part.get_filename('[no filename]'), 'description': part.get('Content-Description', '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), }
|
except IOError, msg:
|
except (OSError, IOError), msg:
|
def addrobot(self, root): root = urlparse.urljoin(root, "/") if self.robots.has_key(root): return url = urlparse.urljoin(root, "/robots.txt") self.robots[root] = rp = robotparser.RobotFileParser() self.note(2, "Parsing %s", url) rp.debug = self.verbose > 3 rp.set_url(url) try: rp.read() except IOError, msg: self.note(1, "I/O error parsing %s: %s", url, msg)
|
except IOError, msg:
|
except (OSError, IOError), msg:
|
def openpage(self, url_pair): url, fragment = url_pair try: return self.urlopener.open(url) except IOError, msg: msg = self.sanitize(msg) self.note(0, "Error %s", msg) if self.verbose > 0: self.show(" HREF ", url, " from", self.todo[url_pair]) self.setbad(url_pair, msg) return None
|
self.addheaders = [('User-Agent', server_version)]
|
self.addheaders = [('User-agent', server_version)]
|
def __init__(self): server_version = "Python-urllib/%s" % __version__ self.addheaders = [('User-Agent', server_version)] # manage the individual handlers self.handlers = [] self.handle_open = {} self.handle_error = {}
|
req.add_header('Proxy-Authorization', 'Basic ' + user_pass)
|
req.add_header('Proxy-authorization', 'Basic ' + user_pass)
|
def proxy_open(self, req, proxy, type): orig_type = req.get_type() type, r_type = splittype(proxy) host, XXX = splithost(r_type) if '@' in host: user_pass, host = host.split('@', 1) if ':' in user_pass: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))) req.add_header('Proxy-Authorization', 'Basic ' + user_pass) host = unquote(host) req.set_proxy(host, type) if orig_type == type: # let other handlers take care of it # XXX this only makes sense if the proxy is before the # other handlers return None else: # need to start over, because the other handlers don't # grok the proxy's URL type return self.parent.open(req)
|
auth_header = 'Proxy-Authorization'
|
auth_header = 'Proxy-authorization'
|
def http_error_401(self, req, fp, code, msg, headers): host = urlparse.urlparse(req.get_full_url())[1] return self.http_error_auth_reqed('www-authenticate', host, req, headers)
|
for args in self.parent.addheaders: name, value = args
|
for name, value in self.parent.addheaders: name = name.capitalize()
|
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
|
h.putheader(*args)
|
h.putheader(name, value)
|
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
|
'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
|
'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
|
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats.st_size modified = rfc822.formatdate(stats.st_mtime) mtype = mimetypes.guess_type(file)[0] headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host')
|
headers += "Content-Type: %s\n" % mtype
|
headers += "Content-type: %s\n" % mtype
|
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 = splitattr(req.get_selector()) path = unquote(path) dirs = path.split('/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] user = passwd = '' # XXX try: fw = self.connect_ftp(user, passwd, host, port, dirs) type = file and 'I' or 'D' for attr in attrs: attr, value = splitattr(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() fp, retrlen = fw.retrfile(file, type) headers = "" mtype = mimetypes.guess_type(req.get_full_url())[0] if mtype: headers += "Content-Type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-Length: %d\n" % retrlen sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors, msg: raise IOError, ('ftp error', msg), sys.exc_info()[2]
|
headers += "Content-Length: %d\n" % retrlen
|
headers += "Content-length: %d\n" % retrlen
|
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 = splitattr(req.get_selector()) path = unquote(path) dirs = path.split('/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] user = passwd = '' # XXX try: fw = self.connect_ftp(user, passwd, host, port, dirs) type = file and 'I' or 'D' for attr in attrs: attr, value = splitattr(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() fp, retrlen = fw.retrfile(file, type) headers = "" mtype = mimetypes.guess_type(req.get_full_url())[0] if mtype: headers += "Content-Type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-Length: %d\n" % retrlen sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors, msg: raise IOError, ('ftp error', msg), sys.exc_info()[2]
|
y = _reconstruct(x, reductor(), 1)
|
y = _reconstruct(x, reductor(), 1, memo)
|
def deepcopy(x, memo = None): """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ if memo is None: memo = {} d = id(x) if memo.has_key(d): return memo[d] try: copierfunction = _deepcopy_dispatch[type(x)] except KeyError: try: copier = x.__deepcopy__ except AttributeError: try: reductor = x.__reduce__ except AttributeError: raise error, \ "un-deep-copyable object of type %s" % type(x) else: y = _reconstruct(x, reductor(), 1) else: y = copier(memo) else: y = copierfunction(x, memo) memo[d] = y return y
|
def _reconstruct(x, info, deep):
|
def _reconstruct(x, info, deep, memo=None):
|
def _reconstruct(x, info, deep): if isinstance(info, str): return x assert isinstance(info, tuple) n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args) y = callable(*args) if state: if deep: state = deepcopy(state) y.__dict__.update(state) return y
|
args = deepcopy(args)
|
args = deepcopy(args, memo)
|
def _reconstruct(x, info, deep): if isinstance(info, str): return x assert isinstance(info, tuple) n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args) y = callable(*args) if state: if deep: state = deepcopy(state) y.__dict__.update(state) return y
|
state = deepcopy(state)
|
state = deepcopy(state, memo)
|
def _reconstruct(x, info, deep): if isinstance(info, str): return x assert isinstance(info, tuple) n = len(info) assert n in (2, 3) callable, args = info[:2] if n > 2: state = info[2] else: state = {} if deep: args = deepcopy(args) y = callable(*args) if state: if deep: state = deepcopy(state) y.__dict__.update(state) return y
|
raise error, "illegal range"
|
raise error, "bad character range"
|
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this == "#": while 1: this = source.get() if this in (None, "\n"): break continue if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, ord(this))) elif this == "[": # character set set = []
|
if max < min: raise error, "bad repeat interval"
|
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this == "#": while 1: this = source.get() if this in (None, "\n"): break continue if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, ord(this))) elif this == "[": # character set set = []
|
|
raise error, "illegal character in group name"
|
raise error, "bad character in group name"
|
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this == "#": while 1: this = source.get() if this in (None, "\n"): break continue if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, ord(this))) elif this == "[": # character set set = []
|
if char is None or char == ")":
|
if char is None: raise error, "unexpected end of pattern" if char == ")":
|
def _parse(source, state): # parse a simple pattern subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this == "#": while 1: this = source.get() if this in (None, "\n"): break continue if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, ord(this))) elif this == "[": # character set set = []
|
raise error, "illegal character in group name"
|
raise error, "bad character in group name"
|
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": # group if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated group name" if char == ">": break name = name + char if not name: raise error, "bad group name" try: index = int(name) except ValueError: if not isname(name): raise error, "illegal character in group name" try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown group name" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: code = None while 1: group = _group(this, pattern.groups+1) if group: if (s.next not in DIGITS or not _group(this + s.next, pattern.groups+1)): code = MARK, int(group) break elif s.next in OCTDIGITS: this = this + s.get() else: break if not code: this = this[1:] code = LITERAL, int(this[-6:], 8) & 0xff a(code) else: try: a(ESCAPES[this]) except KeyError: for c in this: a((LITERAL, ord(c))) else: a((LITERAL, ord(this))) return p
|
def __init__(self, master=None): """Construct a variable with an optional MASTER as master widget. The variable is named PY_VAR_number in Tcl.
|
def __init__(self, master=None, value=None, name=None): """Construct a variable MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained.
|
def __init__(self, master=None): """Construct a variable with an optional MASTER as master widget. The variable is named PY_VAR_number in Tcl. """ global _varnum if not master: master = _default_root self._master = master self._tk = master.tk self._name = 'PY_VAR' + repr(_varnum) _varnum = _varnum + 1 self.set(self._default)
|
self._name = 'PY_VAR' + repr(_varnum) _varnum = _varnum + 1 self.set(self._default)
|
if name: self._name = name else: self._name = 'PY_VAR' + `_varnum` _varnum += 1 if value != None: self.set(value) elif not self._tk.call("info", "exists", self._name): self.set(self._default)
|
def __init__(self, master=None): """Construct a variable with an optional MASTER as master widget. The variable is named PY_VAR_number in Tcl. """ global _varnum if not master: master = _default_root self._master = master self._tk = master.tk self._name = 'PY_VAR' + repr(_varnum) _varnum = _varnum + 1 self.set(self._default)
|
def __init__(self, master=None):
|
def __init__(self, master=None, value=None, name=None):
|
def __init__(self, master=None): """Construct a string variable.
|
MASTER can be given as master widget.""" Variable.__init__(self, master)
|
MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
|
def __init__(self, master=None): """Construct a string variable.
|
def __init__(self, master=None):
|
def __init__(self, master=None, value=None, name=None):
|
def __init__(self, master=None): """Construct an integer variable.
|
MASTER can be given as master widget.""" Variable.__init__(self, master)
|
MASTER can be given as master widget. VALUE is an optional value (defaults to 0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
|
def __init__(self, master=None): """Construct an integer variable.
|
def __init__(self, master=None):
|
def __init__(self, master=None, value=None, name=None):
|
def __init__(self, master=None): """Construct a float variable.
|
MASTER can be given as a master widget.""" Variable.__init__(self, master)
|
MASTER can be given as master widget. VALUE is an optional value (defaults to 0.0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
|
def __init__(self, master=None): """Construct a float variable.
|
_default = "false" def __init__(self, master=None):
|
_default = False def __init__(self, master=None, value=None, name=None):
|
def get(self): """Return the value of the variable as a float.""" return getdouble(self._tk.globalgetvar(self._name))
|
MASTER can be given as a master widget.""" Variable.__init__(self, master)
|
MASTER can be given as master widget. VALUE is an optional value (defaults to False) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name)
|
def __init__(self, master=None): """Construct a boolean variable.
|
if hasattr(self.db, 'close'): self.db.close() self.db = None
|
if hasattr(self.dict, 'close'): self.dict.close() self.dict = None
|
def close(self): if hasattr(self.db, 'close'): self.db.close() self.db = None
|
dict['prefixname'] = 'mwerks_plugin_config.h'
|
if hasattr(MacOS, 'runtimemodel') and MacOS.runtimemodel == "carbon": dict['prefixname'] = 'mwerks_carbonplugin_config.h' else: dict['prefixname'] = 'mwerks_plugin_config.h'
|
def __init__(self, dict, templatelist=TEMPLATELIST, templatename=None): if templatename == None: if hasattr(MacOS, 'runtimemodel'): templatename = 'template-%s'%MacOS.runtimemodel else: templatename = 'template' if os.sep in templatename: templatedir = templatename else: try: packagedir = os.path.split(__file__)[0] except NameError: packagedir = os.curdir templatedir = os.path.join(packagedir, templatename) if not os.path.exists(templatedir): raise Error, "Cannot find templatedir %s"%templatedir self.dict = dict if not dict.has_key('prefixname'): dict['prefixname'] = 'mwerks_plugin_config.h' self.templatelist = templatelist self.templatedir = templatedir
|
testformat("One million is %i", 1000000, grouping=1, output='One million is 1,000,000',
|
testformat("One million is %i", 1000000, grouping=1, output='One million is 1%s000%s000' % (sep, sep),
|
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and result != output: if verbose: print 'no' print "%s %% %s == %s != %s" %\ (repr(formatstr), repr(value), repr(result), repr(output)) else: if verbose: print "yes"
|
testformat("--> %10.2f", 1000.0, grouping=1, output='--> 1,000.00',
|
testformat("--> %10.2f", 1000.0, grouping=1, output='--> 1%s000.00' % sep,
|
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and result != output: if verbose: print 'no' print "%s %% %s == %s != %s" %\ (repr(formatstr), repr(value), repr(result), repr(output)) else: if verbose: print "yes"
|
testformat("%*.*f", (10, 2, 1000.0), grouping=1, output=' 1,000.00',
|
testformat("%*.*f", (10, 2, 1000.0), grouping=1, output=' 1%s000.00' % sep,
|
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and result != output: if verbose: print 'no' print "%s %% %s == %s != %s" %\ (repr(formatstr), repr(value), repr(result), repr(output)) else: if verbose: print "yes"
|
output='int 1,000 float 1,000.00 str str', func=locale.format_string)
|
output='int 1%s000 float 1%s000.00 str str' % (sep, sep), func=locale.format_string)
|
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format): if verbose: if output: print "%s %% %s =? %s ..." %\ (repr(formatstr), repr(value), repr(output)), else: print "%s %% %s works? ..." % (repr(formatstr), repr(value)), result = func(formatstr, value, grouping = grouping) if output and result != output: if verbose: print 'no' print "%s %% %s == %s != %s" %\ (repr(formatstr), repr(value), repr(result), repr(output)) else: if verbose: print "yes"
|
def __init__(self, sock=None): dispatcher.__init__(self, sock)
|
def __init__(self, sock=None, map=None): dispatcher.__init__(self, sock, map)
|
def __init__(self, sock=None): dispatcher.__init__(self, sock) self.out_buffer = ''
|
def __init__(self, fd): dispatcher.__init__(self)
|
def __init__(self, fd, map=None): dispatcher.__init__(self, None, map)
|
def __init__(self, fd): dispatcher.__init__(self) self.connected = True # set it to non-blocking mode flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0) flags = flags | os.O_NONBLOCK fcntl.fcntl(fd, fcntl.F_SETFL, flags) self.set_file(fd)
|
self.assertRaises(TypeError, islice, xrange(10))
|
self.assertEqual(list(islice(xrange(10))), range(10)) self.assertEqual(list(islice(xrange(10), None)), range(10)) self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10)) self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
|
def test_islice(self): for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 3), (20,) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*args))
|
import test_itertools
|
def test_main(verbose=None): import test_itertools suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestBasicOps)) test_support.run_suite(suite) test_support.run_doctest(test_itertools, verbose) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [] for i in xrange(5): test_support.run_suite(suite) counts.append(sys.gettotalrefcount()-i) print counts
|
|
test_support.run_doctest(test_itertools, verbose)
|
def test_main(verbose=None): import test_itertools suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestBasicOps)) test_support.run_suite(suite) test_support.run_doctest(test_itertools, verbose) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [] for i in xrange(5): test_support.run_suite(suite) counts.append(sys.gettotalrefcount()-i) print counts
|
|
exts.append( Extension('nis', ['nismodule.c'], libraries = ['nsl']) )
|
libs = ['nsl'] else: libs = [] exts.append( Extension('nis', ['nismodule.c'], libraries = libs) )
|
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
|
if _arguments.has_key('errn'):
|
if _arguments.get('errn', 0):
|
def run(self, _no_object=None, _attributes={}, **_arguments): """run: Run the Terminal application Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'core' _subcode = 'oapp'
|
if _arguments.has_key('errn'):
|
if _arguments.get('errn', 0):
|
def quit(self, _no_object=None, _attributes={}, **_arguments): """quit: Quit the Terminal application Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'core' _subcode = 'quit'
|
if _arguments.has_key('errn'):
|
if _arguments.get('errn', 0):
|
def count(self, _object=None, _attributes={}, **_arguments): """count: Return the number of elements of a particular class within an object Required argument: a reference to the objects to be counted Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of objects counted """ _code = 'core' _subcode = 'cnte'
|
if _arguments.has_key('errn'):
|
if _arguments.get('errn', 0):
|
def do_script(self, _no_object=None, _attributes={}, **_arguments): """do script: Run a UNIX shell script or command Keyword argument with_command: data to be passed to the Terminal application as the command line Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'core' _subcode = 'dosc'
|
test(r"""sre.match("\%03o" % i, chr(i)) != None""", 1) test(r"""sre.match("\%03o0" % i, chr(i)+"0") != None""", 1) test(r"""sre.match("\%03o8" % i, chr(i)+"8") != None""", 1)
|
test(r"""sre.match(r"\%03o" % i, chr(i)) != None""", 1) test(r"""sre.match(r"\%03o0" % i, chr(i)+"0") != None""", 1) test(r"""sre.match(r"\%03o8" % i, chr(i)+"8") != None""", 1)
|
def test(expression, result, exception=None): try: r = eval(expression) except: if exception: if not isinstance(sys.exc_value, exception): print expression, "FAILED" # display name, not actual value if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got", sys.exc_type.__name__, str(sys.exc_value) else: print expression, "FAILED" traceback.print_exc(file=sys.stdout) else: if exception: print expression, "FAILED" if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got result", repr(r) else: if r != result: print expression, "FAILED" print "expected", repr(result) print "got result", repr(r)
|
test(r"""sre.search('x*', 'axx').span(0)""", (0, 0)) test(r"""sre.search('x*', 'axx').span()""", (0, 0)) test(r"""sre.search('x+', 'axx').span(0)""", (1, 3)) test(r"""sre.search('x+', 'axx').span()""", (1, 3)) test(r"""sre.search('x', 'aaa')""", None) test(r"""sre.match('a*', 'xxx').span(0)""", (0, 0)) test(r"""sre.match('a*', 'xxx').span()""", (0, 0)) test(r"""sre.match('x*', 'xxxa').span(0)""", (0, 3)) test(r"""sre.match('x*', 'xxxa').span()""", (0, 3)) test(r"""sre.match('a+', 'xxx')""", None)
|
test(r"""sre.search(r'x*', 'axx').span(0)""", (0, 0)) test(r"""sre.search(r'x*', 'axx').span()""", (0, 0)) test(r"""sre.search(r'x+', 'axx').span(0)""", (1, 3)) test(r"""sre.search(r'x+', 'axx').span()""", (1, 3)) test(r"""sre.search(r'x', 'aaa')""", None) test(r"""sre.match(r'a*', 'xxx').span(0)""", (0, 0)) test(r"""sre.match(r'a*', 'xxx').span()""", (0, 0)) test(r"""sre.match(r'x*', 'xxxa').span(0)""", (0, 3)) test(r"""sre.match(r'x*', 'xxxa').span()""", (0, 3)) test(r"""sre.match(r'a+', 'xxx')""", None)
|
def test(expression, result, exception=None): try: r = eval(expression) except: if exception: if not isinstance(sys.exc_value, exception): print expression, "FAILED" # display name, not actual value if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got", sys.exc_type.__name__, str(sys.exc_value) else: print expression, "FAILED" traceback.print_exc(file=sys.stdout) else: if exception: print expression, "FAILED" if exception is sre.error: print "expected", "sre.error" else: print "expected", exception.__name__ print "got result", repr(r) else: if r != result: print expression, "FAILED" print "expected", repr(result) print "got result", repr(r)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.