desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown.'
def getByteStream(self):
return self.__bytefile
'Set the character stream for this input source. (The stream must be a Python 2.0 Unicode-wrapped file-like that performs conversion to Unicode strings.) If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier.'
def setCharacterStream(self, charfile):
self.__charfile = charfile
'Get the character stream for this input source.'
def getCharacterStream(self):
return self.__charfile
'Non-NS-aware implementation. attrs should be of the form {name : value}.'
def __init__(self, attrs):
self._attrs = attrs
'NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}.'
def __init__(self, attrs, qnames):
self._attrs = attrs self._qnames = qnames
'Handle a recoverable error.'
def error(self, exception):
raise exception
'Handle a non-recoverable error.'
def fatalError(self, exception):
raise exception
'Handle a warning.'
def warning(self, exception):
print exception
'Called by the parser to give the application a locator for locating the origin of document events. SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in t...
def setDocumentLocator(self, locator):
self._locator = locator
'Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from.'
def resolveEntity(self, publicId, systemId):
return systemId
'Create a new parser object.'
def createParser(self):
return expat.ParserCreate()
'Return the parser object, creating a new one if needed.'
def getParser(self):
if (not self._parser): self._parser = self.createParser() self._intern_setdefault = self._parser.intern.setdefault self._parser.buffer_text = True self._parser.ordered_attributes = True self._parser.specified_attributes = True self.install(self._parser) return sel...
'Free all data structures used during DOM construction.'
def reset(self):
self.document = theDOMImplementation.createDocument(EMPTY_NAMESPACE, None, None) self.curNode = self.document self._elem_info = self.document._elem_info self._cdata = False
'Install the callbacks needed to build the DOM into the parser.'
def install(self, parser):
parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler parser.StartElementHandler = self.first_element_handler parser.EndElementHandler = self.end_element_handler parser.ProcessingInstructionHandler = self.pi_handler if self._options.entities: parser.EntityDeclHandler = self.entity...
'Parse a document from a file object, returning the document node.'
def parseFile(self, file):
parser = self.getParser() first_buffer = True try: while 1: buffer = file.read((16 * 1024)) if (not buffer): break parser.Parse(buffer, 0) if (first_buffer and self.document.documentElement): self._setup_subset(buffer) ...
'Parse a document from a string, returning the document node.'
def parseString(self, string):
parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
'Load the internal subset if there might be one.'
def _setup_subset(self, buffer):
if self.document.doctype: extractor = InternalSubsetExtractor() extractor.parseString(buffer) subset = extractor.getSubset() self.document.doctype.internalSubset = subset
'Parse a document fragment from a file object, returning the fragment node.'
def parseFile(self, file):
return self.parseString(file.read())
'Parse a document fragment from a string, returning the fragment node.'
def parseString(self, string):
self._source = string parser = self.getParser() doctype = self.originalDocument.doctype ident = '' if doctype: subset = (doctype.internalSubset or self._getDeclarations()) if doctype.publicId: ident = ('PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId)) ...
'Re-create the internal subset from the DocumentType node. This is only needed if we don\'t already have the internalSubset as a string.'
def _getDeclarations(self):
doctype = self.context.ownerDocument.doctype s = '' if doctype: for i in range(doctype.notations.length): notation = doctype.notations.item(i) if s: s = (s + '\n ') s = ('%s<!NOTATION %s' % (s, notation.nodeName)) if notation....
'Create a new namespace-handling parser.'
def createParser(self):
parser = expat.ParserCreate(namespace_separator=' ') parser.namespace_prefixes = True return parser
'Insert the namespace-handlers onto the parser.'
def install(self, parser):
ExpatBuilder.install(self, parser) if self._options.namespace_declarations: parser.StartNamespaceDeclHandler = self.start_namespace_decl_handler
'Push this namespace declaration on our storage.'
def start_namespace_decl_handler(self, prefix, uri):
self._ns_ordered_prefixes.append((prefix, uri))
'Return string of namespace attributes from this element and ancestors.'
def _getNSattrs(self):
attrs = '' context = self.context L = [] while context: if hasattr(context, '_ns_prefix_uri'): for (prefix, uri) in context._ns_prefix_uri.items(): if (prefix in L): continue L.append(prefix) if prefix: ...
'Return the internal subset as a string.'
def getSubset(self):
return self.subset
'clear(): Explicitly release parsing structures'
def clear(self):
self.document = None
'Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers).'
def _slurp(self):
self.parser.parse(self.stream) self.getEvent = self._emit return self._emit()
'Fallback replacement for getEvent() that emits the events that _slurp() read previously.'
def _emit(self):
rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc
'clear(): Explicitly release parsing objects'
def clear(self):
self.pulldom.clear() del self.pulldom self.parser = None self.stream = None
'Returns true iff this element is declared to have an EMPTY content model.'
def isEmpty(self):
return False
'Returns true iff the named attribute is a DTD-style ID.'
def isId(self, aname):
return False
'Returns true iff the identified attribute is a DTD-style ID.'
def isIdNS(self, namespaceURI, localName):
return False
'Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. The new class instance is based on fileobj, which can be a regular file, an io.BytesIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file ...
def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None):
if (mode and (('t' in mode) or ('U' in mode))): raise ValueError('Invalid mode: {!r}'.format(mode)) if (mode and ('b' not in mode)): mode += 'b' if (fileobj is None): fileobj = self.myfileobj = builtins.open(filename, (mode or 'rb')) if (filename is None): filename ...
'Raises a ValueError if the underlying file object has been closed.'
def _check_closed(self):
if self.closed: raise ValueError('I/O operation on closed file.')
'Invoke the underlying file object\'s fileno() method. This will raise AttributeError if the underlying file object doesn\'t support fileno().'
def fileno(self):
return self.fileobj.fileno()
'Return the uncompressed stream file position indicator to the beginning of the file'
def rewind(self):
if (self.mode != READ): raise OSError("Can't rewind in write mode") self.fileobj.seek(0) self._new_member = True self.extrabuf = '' self.extrasize = 0 self.extrastart = 0 self.offset = 0
'Push a token onto the stack popped by the get_token method'
def push_token(self, tok):
if (self.debug >= 1): print ('shlex: pushing token ' + repr(tok)) self.pushback.appendleft(tok)
'Push an input source onto the lexer\'s input source stack.'
def push_source(self, newstream, newfile=None):
if isinstance(newstream, str): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 if self.debug: if (newfile is not None): print ('shlex: pushing to...
'Pop the input source stack.'
def pop_source(self):
self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: print ('shlex: popping to %s, line %d' % (self.instream, self.lineno)) self.state = ' '
'Get a token from the input stream (or from stack if it\'s nonempty)'
def get_token(self):
if self.pushback: tok = self.pushback.popleft() if (self.debug >= 1): print ('shlex: popping token ' + repr(tok)) return tok raw = self.read_token() if (self.source is not None): while (raw == self.source): spec = self.sourcehook(self.read_tok...
'Hook called on a filename to be sourced.'
def sourcehook(self, newfile):
if (newfile[0] == '"'): newfile = newfile[1:(-1)] if (isinstance(self.infile, str) and (not os.path.isabs(newfile))): newfile = os.path.join(os.path.dirname(self.infile), newfile) return (newfile, open(newfile, 'r'))
'Emit a C-compiler-like, Emacs-friendly error-message leader.'
def error_leader(self, infile=None, lineno=None):
if (infile is None): infile = self.infile if (lineno is None): lineno = self.lineno return ('"%s", line %d: ' % (infile, lineno))
'Return true if the scope uses exec. Deprecated method.'
def has_exec(self):
return False
'Return true if the scope uses import *'
def has_import_star(self):
return bool((self._table.optimized & OPT_IMPORT_STAR))
'Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a...
def is_namespace(self):
return bool(self.__namespaces)
'Return a list of namespaces bound to this name'
def get_namespaces(self):
return self.__namespaces
'Returns the single namespace bound to this name. Raises ValueError if the name is bound to multiple namespaces.'
def get_namespace(self):
if (len(self.__namespaces) != 1): raise ValueError('name is bound to multiple namespaces') return self.__namespaces[0]
'Template() returns a fresh pipeline template.'
def __init__(self):
self.debugging = 0 self.reset()
't.__repr__() implements repr(t).'
def __repr__(self):
return ('<Template instance, steps=%r>' % (self.steps,))
't.reset() restores a pipeline template to its initial state.'
def reset(self):
self.steps = []
't.clone() returns a new pipeline template with identical initial state as the current one.'
def clone(self):
t = Template() t.steps = self.steps[:] t.debugging = self.debugging return t
't.debug(flag) turns debugging on or off.'
def debug(self, flag):
self.debugging = flag
't.append(cmd, kind) adds a new step at the end.'
def append(self, cmd, kind):
if (type(cmd) is not type('')): raise TypeError('Template.append: cmd must be a string') if (kind not in stepkinds): raise ValueError(('Template.append: bad kind %r' % (kind,))) if (kind == SOURCE): raise ValueError('Template.append: SOURCE can only ...
't.prepend(cmd, kind) adds a new step at the front.'
def prepend(self, cmd, kind):
if (type(cmd) is not type('')): raise TypeError('Template.prepend: cmd must be a string') if (kind not in stepkinds): raise ValueError(('Template.prepend: bad kind %r' % (kind,))) if (kind == SINK): raise ValueError('Template.prepend: SINK can only ...
't.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.'
def open(self, file, rw):
if (rw == 'r'): return self.open_r(file) if (rw == 'w'): return self.open_w(file) raise ValueError(("Template.open: rw must be 'r' or 'w', not %r" % (rw,)))
't.open_r(file) and t.open_w(file) implement t.open(file, \'r\') and t.open(file, \'w\') respectively.'
def open_r(self, file):
if (not self.steps): return open(file, 'r') if (self.steps[(-1)][1] == SINK): raise ValueError('Template.open_r: pipeline ends width SINK') cmd = self.makepipeline(file, '') return os.popen(cmd, 'r')
'Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown.'
def open(self, host='', port=IMAP4_PORT):
self.host = host self.port = port self.sock = self._create_socket() self.file = self.sock.makefile('rb')
'Read \'size\' bytes from remote.'
def read(self, size):
return self.file.read(size)
'Read line from remote.'
def readline(self):
line = self.file.readline((_MAXLINE + 1)) if (len(line) > _MAXLINE): raise self.error(('got more than %d bytes' % _MAXLINE)) return line
'Send data to remote.'
def send(self, data):
self.sock.sendall(data)
'Close I/O established in "open".'
def shutdown(self):
self.file.close() try: self.sock.shutdown(socket.SHUT_RDWR) except OSError as e: if (e.errno != errno.ENOTCONN): raise finally: self.sock.close()
'Return socket instance used to connect to IMAP4 server. socket = <instance>.socket()'
def socket(self):
return self.sock
'Return most recent \'RECENT\' responses if any exist, else prompt server for an update using the \'NOOP\' command. (typ, [data]) = <instance>.recent() \'data\' is None if no new messages, else list of RECENT responses, most recent last.'
def recent(self):
name = 'RECENT' (typ, dat) = self._untagged_response('OK', [None], name) if dat[(-1)]: return (typ, dat) (typ, dat) = self.noop() return self._untagged_response(typ, dat, name)
'Return data for response \'code\' if received, or None. Old value for response \'code\' is cleared. (code, [data]) = <instance>.response(code)'
def response(self, code):
return self._untagged_response(code, [None], code.upper())
'Append message to named mailbox. (typ, [data]) = <instance>.append(mailbox, flags, date_time, message) All args except `message\' can be None.'
def append(self, mailbox, flags, date_time, message):
name = 'APPEND' if (not mailbox): mailbox = 'INBOX' if flags: if ((flags[0], flags[(-1)]) != ('(', ')')): flags = ('(%s)' % flags) else: flags = None if date_time: date_time = Time2Internaldate(date_time) else: date_time = None self.literal...
'Authenticate command - requires response processing. \'mechanism\' specifies which authentication mechanism is to be used - it must appear in <instance>.capabilities in the form AUTH=<mechanism>. \'authobject\' must be a callable object: data = authobject(response) It will be called to process server continuation resp...
def authenticate(self, mechanism, authobject):
mech = mechanism.upper() self.literal = _Authenticator(authobject).process (typ, dat) = self._simple_command('AUTHENTICATE', mech) if (typ != 'OK'): raise self.error(dat[(-1)]) self.state = 'AUTH' return (typ, dat)
'(typ, [data]) = <instance>.capability() Fetch capabilities list from server.'
def capability(self):
name = 'CAPABILITY' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Checkpoint mailbox on server. (typ, [data]) = <instance>.check()'
def check(self):
return self._simple_command('CHECK')
'Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before \'LOGOUT\'. (typ, [data]) = <instance>.close()'
def close(self):
try: (typ, dat) = self._simple_command('CLOSE') finally: self.state = 'AUTH' return (typ, dat)
'Copy \'message_set\' messages onto end of \'new_mailbox\'. (typ, [data]) = <instance>.copy(message_set, new_mailbox)'
def copy(self, message_set, new_mailbox):
return self._simple_command('COPY', message_set, new_mailbox)
'Create new mailbox. (typ, [data]) = <instance>.create(mailbox)'
def create(self, mailbox):
return self._simple_command('CREATE', mailbox)
'Delete old mailbox. (typ, [data]) = <instance>.delete(mailbox)'
def delete(self, mailbox):
return self._simple_command('DELETE', mailbox)
'Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who)'
def deleteacl(self, mailbox, who):
return self._simple_command('DELETEACL', mailbox, who)
'Permanently remove deleted items from selected mailbox. Generates \'EXPUNGE\' response for each deleted message. (typ, [data]) = <instance>.expunge() \'data\' is list of \'EXPUNGE\'d message numbers in order received.'
def expunge(self):
name = 'EXPUNGE' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Fetch (parts of) messages. (typ, [data, ...]) = <instance>.fetch(message_set, message_parts) \'message_parts\' should be a string of selected parts enclosed in parentheses, eg: "(UID BODY[TEXT])". \'data\' are tuples of message part envelope and data.'
def fetch(self, message_set, message_parts):
name = 'FETCH' (typ, dat) = self._simple_command(name, message_set, message_parts) return self._untagged_response(typ, dat, name)
'Get the ACLs for a mailbox. (typ, [data]) = <instance>.getacl(mailbox)'
def getacl(self, mailbox):
(typ, dat) = self._simple_command('GETACL', mailbox) return self._untagged_response(typ, dat, 'ACL')
'(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs.'
def getannotation(self, mailbox, entry, attribute):
(typ, dat) = self._simple_command('GETANNOTATION', mailbox, entry, attribute) return self._untagged_response(typ, dat, 'ANNOTATION')
'Get the quota root\'s resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. (typ, [data]) = <instance>.getquota(root)'
def getquota(self, root):
(typ, dat) = self._simple_command('GETQUOTA', root) return self._untagged_response(typ, dat, 'QUOTA')
'Get the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)'
def getquotaroot(self, mailbox):
(typ, dat) = self._simple_command('GETQUOTAROOT', mailbox) (typ, quota) = self._untagged_response(typ, dat, 'QUOTA') (typ, quotaroot) = self._untagged_response(typ, dat, 'QUOTAROOT') return (typ, [quotaroot, quota])
'List mailbox names in directory matching pattern. (typ, [data]) = <instance>.list(directory=\'""\', pattern=\'*\') \'data\' is list of LIST responses.'
def list(self, directory='""', pattern='*'):
name = 'LIST' (typ, dat) = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name)
'Identify client using plaintext password. (typ, [data]) = <instance>.login(user, password) NB: \'password\' will be quoted.'
def login(self, user, password):
(typ, dat) = self._simple_command('LOGIN', user, self._quote(password)) if (typ != 'OK'): raise self.error(dat[(-1)]) self.state = 'AUTH' return (typ, dat)
'Force use of CRAM-MD5 authentication. (typ, [data]) = <instance>.login_cram_md5(user, password)'
def login_cram_md5(self, user, password):
(self.user, self.password) = (user, password) return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
'Authobject to use with CRAM-MD5 authentication.'
def _CRAM_MD5_AUTH(self, challenge):
import hmac pwd = (self.password.encode('ASCII') if isinstance(self.password, str) else self.password) return ((self.user + ' ') + hmac.HMAC(pwd, challenge, 'md5').hexdigest())
'Shutdown connection to server. (typ, [data]) = <instance>.logout() Returns server \'BYE\' response.'
def logout(self):
self.state = 'LOGOUT' try: (typ, dat) = self._simple_command('LOGOUT') except: (typ, dat) = ('NO', [('%s: %s' % sys.exc_info()[:2])]) self.shutdown() if ('BYE' in self.untagged_responses): return ('BYE', self.untagged_responses['BYE']) return (typ, dat)
'List \'subscribed\' mailbox names in directory matching pattern. (typ, [data, ...]) = <instance>.lsub(directory=\'""\', pattern=\'*\') \'data\' are tuples of message part envelope and data.'
def lsub(self, directory='""', pattern='*'):
name = 'LSUB' (typ, dat) = self._simple_command(name, directory, pattern) return self._untagged_response(typ, dat, name)
'Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = <instance>.myrights(mailbox)'
def myrights(self, mailbox):
(typ, dat) = self._simple_command('MYRIGHTS', mailbox) return self._untagged_response(typ, dat, 'MYRIGHTS')
'Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = <instance>.namespace()'
def namespace(self):
name = 'NAMESPACE' (typ, dat) = self._simple_command(name) return self._untagged_response(typ, dat, name)
'Send NOOP command. (typ, [data]) = <instance>.noop()'
def noop(self):
if __debug__: if (self.debug >= 3): self._dump_ur(self.untagged_responses) return self._simple_command('NOOP')
'Fetch truncated part of a message. (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length) \'data\' is tuple of message part envelope and data.'
def partial(self, message_num, message_part, start, length):
name = 'PARTIAL' (typ, dat) = self._simple_command(name, message_num, message_part, start, length) return self._untagged_response(typ, dat, 'FETCH')
'Assume authentication as "user". Allows an authorised administrator to proxy into any user\'s mailbox. (typ, [data]) = <instance>.proxyauth(user)'
def proxyauth(self, user):
name = 'PROXYAUTH' return self._simple_command('PROXYAUTH', user)
'Rename old mailbox name to new. (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)'
def rename(self, oldmailbox, newmailbox):
return self._simple_command('RENAME', oldmailbox, newmailbox)
'Search mailbox for matching messages. (typ, [data]) = <instance>.search(charset, criterion, ...) \'data\' is space separated list of matching message numbers.'
def search(self, charset, *criteria):
name = 'SEARCH' if charset: (typ, dat) = self._simple_command(name, 'CHARSET', charset, *criteria) else: (typ, dat) = self._simple_command(name, *criteria) return self._untagged_response(typ, dat, name)
'Select a mailbox. Flush all untagged responses. (typ, [data]) = <instance>.select(mailbox=\'INBOX\', readonly=False) \'data\' is count of messages in mailbox (\'EXISTS\' response). Mandated responses are (\'FLAGS\', \'EXISTS\', \'RECENT\', \'UIDVALIDITY\'), so other responses should be obtained via <instance>.response...
def select(self, mailbox='INBOX', readonly=False):
self.untagged_responses = {} self.is_readonly = readonly if readonly: name = 'EXAMINE' else: name = 'SELECT' (typ, dat) = self._simple_command(name, mailbox) if (typ != 'OK'): self.state = 'AUTH' return (typ, dat) self.state = 'SELECTED' if (('READ-ONLY' i...
'Set a mailbox acl. (typ, [data]) = <instance>.setacl(mailbox, who, what)'
def setacl(self, mailbox, who, what):
return self._simple_command('SETACL', mailbox, who, what)
'(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.'
def setannotation(self, *args):
(typ, dat) = self._simple_command('SETANNOTATION', *args) return self._untagged_response(typ, dat, 'ANNOTATION')
'Set the quota root\'s resource limits. (typ, [data]) = <instance>.setquota(root, limits)'
def setquota(self, root, limits):
(typ, dat) = self._simple_command('SETQUOTA', root, limits) return self._untagged_response(typ, dat, 'QUOTA')
'IMAP4rev1 extension SORT command. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)'
def sort(self, sort_criteria, charset, *search_criteria):
name = 'SORT' if ((sort_criteria[0], sort_criteria[(-1)]) != ('(', ')')): sort_criteria = ('(%s)' % sort_criteria) (typ, dat) = self._simple_command(name, sort_criteria, charset, *search_criteria) return self._untagged_response(typ, dat, name)
'Request named status conditions for mailbox. (typ, [data]) = <instance>.status(mailbox, names)'
def status(self, mailbox, names):
name = 'STATUS' (typ, dat) = self._simple_command(name, mailbox, names) return self._untagged_response(typ, dat, name)
'Alters flag dispositions for messages in mailbox. (typ, [data]) = <instance>.store(message_set, command, flags)'
def store(self, message_set, command, flags):
if ((flags[0], flags[(-1)]) != ('(', ')')): flags = ('(%s)' % flags) (typ, dat) = self._simple_command('STORE', message_set, command, flags) return self._untagged_response(typ, dat, 'FETCH')
'Subscribe to new mailbox. (typ, [data]) = <instance>.subscribe(mailbox)'
def subscribe(self, mailbox):
return self._simple_command('SUBSCRIBE', mailbox)