desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned.'
| def get_content_charset(self, failobj=None):
| missing = object()
charset = self.get_param('charset', missing)
if (charset is missing):
return failobj
if isinstance(charset, tuple):
pcharset = (charset[0] or 'us-ascii')
try:
charset = unicode(charset[2], pcharset).encode('us-ascii')
except (LookupError, Un... |
'Return a list containing the charset(s) used in this message.
The returned list of items describes the Content-Type headers\'
charset parameter for this message and all the subparts in its
payload.
Each item will either be a string (the value of the charset parameter
in the Content-Type header of that part) or the val... | def get_charsets(self, failobj=None):
| return [part.get_content_charset(failobj) for part in self.walk()]
|
'Return first release in which this feature was recognized.
This is a 5-tuple, of the same form as sys.version_info.'
| def getOptionalRelease(self):
| return self.optional
|
'Return release in which this feature will become mandatory.
This is a 5-tuple, of the same form as sys.version_info, or, if
the feature was dropped, is None.'
| def getMandatoryRelease(self):
| return self.mandatory
|
'Returns the time the robots.txt file was last fetched.
This is useful for long-running web spiders that need to
check for new robots.txt files periodically.'
| def mtime(self):
| return self.last_checked
|
'Sets the time the robots.txt file was last fetched to the
current time.'
| def modified(self):
| import time
self.last_checked = time.time()
|
'Sets the URL referring to a robots.txt file.'
| def set_url(self, url):
| self.url = url
(self.host, self.path) = urlparse.urlparse(url)[1:3]
|
'Reads the robots.txt URL and feeds it to the parser.'
| def read(self):
| opener = URLopener()
f = opener.open(self.url)
lines = [line.strip() for line in f]
f.close()
self.errcode = opener.errcode
if (self.errcode in (401, 403)):
self.disallow_all = True
elif (self.errcode >= 400):
self.allow_all = True
elif ((self.errcode == 200) and lines):
... |
'parse the input lines from a robots.txt file.
We allow that a user-agent: line is not preceded by
one or more blank lines.'
| def parse(self, lines):
| state = 0
linenumber = 0
entry = Entry()
for line in lines:
linenumber += 1
if (not line):
if (state == 1):
entry = Entry()
state = 0
elif (state == 2):
self._add_entry(entry)
entry = Entry()
... |
'using the parsed robots.txt decide if useragent can fetch url'
| def can_fetch(self, useragent, url):
| if self.disallow_all:
return False
if self.allow_all:
return True
parsed_url = urlparse.urlparse(urllib.unquote(url))
url = urlparse.urlunparse(('', '', parsed_url.path, parsed_url.params, parsed_url.query, parsed_url.fragment))
url = urllib.quote(url)
if (not url):
url =... |
'check if this entry applies to the specified agent'
| def applies_to(self, useragent):
| useragent = useragent.split('/')[0].lower()
for agent in self.useragents:
if (agent == '*'):
return True
agent = agent.lower()
if (agent in useragent):
return True
return False
|
'Preconditions:
- our agent applies to this entry
- filename is URL decoded'
| def allowance(self, filename):
| for line in self.rulelines:
if line.applies_to(filename):
return line.allowance
return True
|
'Specify whether to record warnings and if an alternative module
should be used other than sys.modules[\'warnings\'].
For compatibility with Python 3.0, please consider all arguments to be
keyword-only.'
| def __init__(self, record=False, module=None):
| self._record = record
self._module = (sys.modules['warnings'] if (module is None) else module)
self._entered = False
return
|
'Read up to LEN bytes and return them.
Return zero-length string on EOF.'
| def read(self, len=1024):
| try:
return self._sslobj.read(len)
except SSLError as x:
if ((x.args[0] == SSL_ERROR_EOF) and self.suppress_ragged_eofs):
return ''
raise
|
'Write DATA to the underlying SSL channel. Returns
number of bytes of DATA actually transmitted.'
| def write(self, data):
| return self._sslobj.write(data)
|
'Returns a formatted version of the data in the
certificate provided by the other end of the SSL channel.
Return None if no certificate was provided, {} if a
certificate was provided, but not validated.'
| def getpeercert(self, binary_form=False):
| return self._sslobj.peer_certificate(binary_form)
|
'Perform a TLS/SSL handshake.'
| def do_handshake(self):
| self._sslobj.do_handshake()
|
'Connects to remote ADDR, and then wraps the connection in
an SSL channel.'
| def connect(self, addr):
| self._real_connect(addr, False)
|
'Connects to remote ADDR, and then wraps the connection in
an SSL channel.'
| def connect_ex(self, addr):
| return self._real_connect(addr, True)
|
'Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client.'
| def accept(self):
| (newsock, addr) = socket.accept(self)
return (SSLSocket(newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, ciphers=self.ciphers, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.s... |
'Make and return a file-like object that
works with the SSL connection. Just use the code
from the socket module.'
| def makefile(self, mode='r', bufsize=(-1)):
| self._makefile_refs += 1
return _fileobject(self, mode, bufsize, close=True)
|
'Print a report to stdout, listing the found modules with their
paths, as well as modules that are missing, or seem to be missing.'
| def report(self):
| print
print (' %-25s %s' % ('Name', 'File'))
print (' %-25s %s' % ('----', '----'))
keys = self.modules.keys()
keys.sort()
for key in keys:
m = self.modules[key]
if m.__path__:
print 'P',
else:
print 'm',
print ('%-25s' ... |
'Return a list of modules that appear to be missing. Use
any_missing_maybe() if you want to know which modules are
certain to be missing, and which *may* be missing.'
| def any_missing(self):
| (missing, maybe) = self.any_missing_maybe()
return (missing + maybe)
|
'Return two lists, one with modules that are certainly missing
and one with modules that *may* be missing. The latter names could
either be submodules *or* just global names in the package.
The reason it can\'t always be determined is that it\'s impossible to
tell which names are imported when "from module import *" is... | def any_missing_maybe(self):
| missing = []
maybe = []
for name in self.badmodules:
if (name in self.excludes):
continue
i = name.rfind('.')
if (i < 0):
missing.append(name)
continue
subname = name[(i + 1):]
pkgname = name[:i]
pkg = self.modules.get(pkgna... |
'Return a builtin complex instance. Called for complex(self).'
| @abstractmethod
def __complex__(self):
| pass
|
'True if self != 0. Called for bool(self).'
| def __nonzero__(self):
| return (self != 0)
|
'Retrieve the real component of this number.
This should subclass Real.'
| @abstractproperty
def real(self):
| raise NotImplementedError
|
'Retrieve the imaginary component of this number.
This should subclass Real.'
| @abstractproperty
def imag(self):
| raise NotImplementedError
|
'self + other'
| @abstractmethod
def __add__(self, other):
| raise NotImplementedError
|
'other + self'
| @abstractmethod
def __radd__(self, other):
| raise NotImplementedError
|
'-self'
| @abstractmethod
def __neg__(self):
| raise NotImplementedError
|
'+self'
| @abstractmethod
def __pos__(self):
| raise NotImplementedError
|
'self - other'
| def __sub__(self, other):
| return (self + (- other))
|
'other - self'
| def __rsub__(self, other):
| return ((- self) + other)
|
'self * other'
| @abstractmethod
def __mul__(self, other):
| raise NotImplementedError
|
'other * self'
| @abstractmethod
def __rmul__(self, other):
| raise NotImplementedError
|
'self / other without __future__ division
May promote to float.'
| @abstractmethod
def __div__(self, other):
| raise NotImplementedError
|
'other / self without __future__ division'
| @abstractmethod
def __rdiv__(self, other):
| raise NotImplementedError
|
'self / other with __future__ division.
Should promote to float when necessary.'
| @abstractmethod
def __truediv__(self, other):
| raise NotImplementedError
|
'other / self with __future__ division'
| @abstractmethod
def __rtruediv__(self, other):
| raise NotImplementedError
|
'self**exponent; should promote to float or complex when necessary.'
| @abstractmethod
def __pow__(self, exponent):
| raise NotImplementedError
|
'base ** self'
| @abstractmethod
def __rpow__(self, base):
| raise NotImplementedError
|
'Returns the Real distance from 0. Called for abs(self).'
| @abstractmethod
def __abs__(self):
| raise NotImplementedError
|
'(x+y*i).conjugate() returns (x-y*i).'
| @abstractmethod
def conjugate(self):
| raise NotImplementedError
|
'self == other'
| @abstractmethod
def __eq__(self, other):
| raise NotImplementedError
|
'self != other'
| def __ne__(self, other):
| return (not (self == other))
|
'Any Real can be converted to a native float object.
Called for float(self).'
| @abstractmethod
def __float__(self):
| raise NotImplementedError
|
'trunc(self): Truncates self to an Integral.
Returns an Integral i such that:
* i>0 iff self>0;
* abs(i) <= abs(self);
* for any Integral j satisfying the first two conditions,
abs(i) >= abs(j) [i.e. i has "maximal" abs among those].
i.e. "truncate towards 0".'
| @abstractmethod
def __trunc__(self):
| raise NotImplementedError
|
'divmod(self, other): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations.'
| def __divmod__(self, other):
| return ((self // other), (self % other))
|
'divmod(other, self): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations.'
| def __rdivmod__(self, other):
| return ((other // self), (other % self))
|
'self // other: The floor() of self/other.'
| @abstractmethod
def __floordiv__(self, other):
| raise NotImplementedError
|
'other // self: The floor() of other/self.'
| @abstractmethod
def __rfloordiv__(self, other):
| raise NotImplementedError
|
'self % other'
| @abstractmethod
def __mod__(self, other):
| raise NotImplementedError
|
'other % self'
| @abstractmethod
def __rmod__(self, other):
| raise NotImplementedError
|
'self < other
< on Reals defines a total ordering, except perhaps for NaN.'
| @abstractmethod
def __lt__(self, other):
| raise NotImplementedError
|
'self <= other'
| @abstractmethod
def __le__(self, other):
| raise NotImplementedError
|
'complex(self) == complex(float(self), 0)'
| def __complex__(self):
| return complex(float(self))
|
'Real numbers are their real component.'
| @property
def real(self):
| return (+ self)
|
'Real numbers have no imaginary component.'
| @property
def imag(self):
| return 0
|
'Conjugate is a no-op for Reals.'
| def conjugate(self):
| return (+ self)
|
'float(self) = self.numerator / self.denominator
It\'s important that this conversion use the integer\'s "true"
division rather than casting one side to float before dividing
so that ratios of huge integers convert without overflowing.'
| def __float__(self):
| return (self.numerator / self.denominator)
|
'long(self)'
| @abstractmethod
def __long__(self):
| raise NotImplementedError
|
'index(self)'
| def __index__(self):
| return long(self)
|
'self ** exponent % modulus, but maybe faster.
Accept the modulus argument if you want to support the
3-argument version of pow(). Raise a TypeError if exponent < 0
or any argument isn\'t Integral. Otherwise, just implement the
2-argument version described in Complex.'
| @abstractmethod
def __pow__(self, exponent, modulus=None):
| raise NotImplementedError
|
'self << other'
| @abstractmethod
def __lshift__(self, other):
| raise NotImplementedError
|
'other << self'
| @abstractmethod
def __rlshift__(self, other):
| raise NotImplementedError
|
'self >> other'
| @abstractmethod
def __rshift__(self, other):
| raise NotImplementedError
|
'other >> self'
| @abstractmethod
def __rrshift__(self, other):
| raise NotImplementedError
|
'self & other'
| @abstractmethod
def __and__(self, other):
| raise NotImplementedError
|
'other & self'
| @abstractmethod
def __rand__(self, other):
| raise NotImplementedError
|
'self ^ other'
| @abstractmethod
def __xor__(self, other):
| raise NotImplementedError
|
'other ^ self'
| @abstractmethod
def __rxor__(self, other):
| raise NotImplementedError
|
'self | other'
| @abstractmethod
def __or__(self, other):
| raise NotImplementedError
|
'other | self'
| @abstractmethod
def __ror__(self, other):
| raise NotImplementedError
|
'~self'
| @abstractmethod
def __invert__(self):
| raise NotImplementedError
|
'float(self) == float(long(self))'
| def __float__(self):
| return float(long(self))
|
'Integers are their own numerators.'
| @property
def numerator(self):
| return (+ self)
|
'Integers have a denominator of 1.'
| @property
def denominator(self):
| return 1
|
'Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming unicode ch... | def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None):
| self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if (separators is not None):
(self.item_separator, self.key_separator) = separators
if (default is not None):
... |
'Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return l... | def default(self, o):
| raise TypeError((repr(o) + ' is not JSON serializable'))
|
'Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
\'{"foo": ["bar", "baz"]}\''
| def encode(self, o):
| if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if ((_encoding is not None) and (not (_encoding == 'utf-8'))):
o = o.decode(_encoding)
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
... |
'Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)'
| def iterencode(self, o, _one_shot=False):
| if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
if (self.encoding != 'utf-8'):
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
i... |
'``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook... | def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None):
| self.encoding = encoding
self.object_hook = object_hook
self.object_pairs_hook = object_pairs_hook
self.parse_float = (parse_float or float)
self.parse_int = (parse_int or int)
self.parse_constant = (parse_constant or _CONSTANTS.__getitem__)
self.strict = strict
self.parse_object = JSONO... |
'Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)'
| def decode(self, s, _w=WHITESPACE.match):
| (obj, end) = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if (end != len(s)):
raise ValueError(errmsg('Extra data', s, end, len(s)))
return obj
|
'Decode a JSON document from ``s`` (a ``str`` or ``unicode``
beginning with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.'
| def raw_decode(self, s, idx=0):
| try:
(obj, end) = self.scan_once(s, idx)
except StopIteration:
raise ValueError('No JSON object could be decoded')
return (obj, end)
|
'Create a new directory in the Directory table. There is a current component
at each point in time for the directory, which is either explicitly created
through start_component, or implicitly when files are added for the first
time. Files are added into the current component, and into the cab file.
To create a director... | def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None):
| index = 1
_logical = make_id(_logical)
logical = _logical
while (logical in _directories):
logical = ('%s%d' % (_logical, index))
index += 1
_directories.add(logical)
self.db = db
self.cab = cab
self.basedir = basedir
self.physical = physical
self.logical = logica... |
'Add an entry to the Component table, and make this component the current for this
directory. If no component name is given, the directory name is used. If no feature
is given, the current feature is used. If no flags are given, the directory\'s default
flags are used. If no keyfile is given, the KeyPath is left null i... | def start_component(self, component=None, feature=None, flags=None, keyfile=None, uuid=None):
| if (flags is None):
flags = self.componentflags
if (uuid is None):
uuid = gen_uuid()
else:
uuid = uuid.upper()
if (component is None):
component = self.logical
self.component = component
if Win64:
flags |= 256
if keyfile:
keyid = self.cab.gen_i... |
'Add a file to the current component of the directory, starting a new one
one if there is no current component. By default, the file name in the source
and the file table will be identical. If the src file is specified, it is
interpreted relative to the current directory. Optionally, a version and a
language can be spe... | def add_file(self, file, src=None, version=None, language=None):
| if (not self.component):
self.start_component(self.logical, current_feature, 0)
if (not src):
src = file
file = os.path.basename(file)
absolute = os.path.join(self.absolute, src)
if (file in self.keyfiles):
logical = self.keyfiles[file]
else:
logical = None
... |
'Add a list of files to the current component as specified in the
glob pattern. Individual files can be excluded in the exclude list.'
| def glob(self, pattern, exclude=None):
| files = glob.glob1(self.absolute, pattern)
for f in files:
if (exclude and (f in exclude)):
continue
self.add_file(f)
return files
|
'Remove .pyc/.pyo files on uninstall'
| def remove_pyc(self):
| add_data(self.db, 'RemoveFile', [((self.component + 'c'), self.component, '*.pyc', self.logical, 2), ((self.component + 'o'), self.component, '*.pyo', self.logical, 2)])
|
'Getter for \'message\'; needed only to override deprecation in
BaseException.'
| def _get_message(self):
| return self.__message
|
'Setter for \'message\'; needed only to override deprecation in
BaseException.'
| def _set_message(self, value):
| self.__message = value
|
'Return a list of section names, excluding [DEFAULT]'
| def sections(self):
| return self._sections.keys()
|
'Create a new section in the configuration.
Raise DuplicateSectionError if a section by the specified name
already exists. Raise ValueError if name is DEFAULT or any of it\'s
case-insensitive variants.'
| def add_section(self, section):
| if (section.lower() == 'default'):
raise ValueError, ('Invalid section name: %s' % section)
if (section in self._sections):
raise DuplicateSectionError(section)
self._sections[section] = self._dict()
|
'Indicate whether the named section is present in the configuration.
The DEFAULT section is not acknowledged.'
| def has_section(self, section):
| return (section in self._sections)
|
'Return a list of option names for the given section name.'
| def options(self, section):
| try:
opts = self._sections[section].copy()
except KeyError:
raise NoSectionError(section)
opts.update(self._defaults)
if ('__name__' in opts):
del opts['__name__']
return opts.keys()
|
'Read and parse a filename or a list of filenames.
Files that cannot be opened are silently ignored; this is
designed so that you can specify a list of potential
configuration file locations (e.g. current directory, user\'s
home directory, systemwide directory), and all existing
configuration files in the list will be ... | def read(self, filenames):
| if isinstance(filenames, basestring):
filenames = [filenames]
read_ok = []
for filename in filenames:
try:
fp = open(filename)
except IOError:
continue
self._read(fp, filename)
fp.close()
read_ok.append(filename)
return read_ok
|
'Like read() but the argument must be a file-like object.
The `fp\' argument must have a `readline\' method. Optional
second argument is the `filename\', which if not given, is
taken from fp.name. If fp has no `name\' attribute, `<???>\' is
used.'
| def readfp(self, fp, filename=None):
| if (filename is None):
try:
filename = fp.name
except AttributeError:
filename = '<???>'
self._read(fp, filename)
return
|
'Check for the existence of a given option in a given section.'
| def has_option(self, section, option):
| if ((not section) or (section == DEFAULTSECT)):
option = self.optionxform(option)
return (option in self._defaults)
else:
if (section not in self._sections):
return False
option = self.optionxform(option)
return ((option in self._sections[section]) or (option ... |
'Set an option.'
| def set(self, section, option, value=None):
| if ((not section) or (section == DEFAULTSECT)):
sectdict = self._defaults
else:
try:
sectdict = self._sections[section]
except KeyError:
raise NoSectionError(section)
sectdict[self.optionxform(option)] = value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.