desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set\'s ``.entries`` (if it wasn\'t already present).
`dist` is only added to the working set if it\'s for a project that
doesn\... | def add(self, dist, entry=None, insert=True, replace=False):
| if insert:
dist.insert_on(self.entries, entry)
if (entry is None):
entry = dist.location
keys = self.entry_keys.setdefault(entry, [])
keys2 = self.entry_keys.setdefault(dist.location, [])
if ((not replace) and (dist.key in self.by_key)):
return
self.by_key[dist.key] = dis... |
'List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all distributions available within any
entry or distribution in the working set. `installer`, if... | def resolve(self, requirements, env=None, installer=None, replace_conflicting=False):
| requirements = list(requirements)[::(-1)]
processed = {}
best = {}
to_activate = []
required_by = collections.defaultdict(set)
while requirements:
req = requirements.pop(0)
if (req in processed):
continue
dist = best.get(req.key)
if (dist is None):
... |
'Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
# add plugins+libs to sys.path
map(working_set.add, distributions)
# display errors
print(\'Could not load\', errors)
The `plugin_env` should be an ``Environment`` instance t... | def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True):
| plugin_projects = list(plugin_env)
plugin_projects.sort()
error_info = {}
distributions = {}
if (full_env is None):
env = Environment(self.entries)
env += plugin_env
else:
env = (full_env + plugin_env)
shadow_set = self.__class__([])
list(map(shadow_set.add, self)... |
'Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that needed to be
activated to fulfill the requirements; all relevant distrib... | def require(self, *requirements):
| needed = self.resolve(parse_requirements(requirements))
for dist in needed:
self.add(dist)
return needed
|
'Invoke `callback` for all distributions (including existing ones)'
| def subscribe(self, callback):
| if (callback in self.callbacks):
return
self.callbacks.append(callback)
for dist in self:
callback(dist)
|
'Snapshot distributions available on a search path
Any distributions found on `search_path` are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used.
`platform` is an optional string specifying the name of the platform
that platform-specific distribu... | def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
| self._distmap = {}
self.platform = platform
self.python = python
self.scan(search_path)
|
'Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned.'
| def can_add(self, dist):
| return (((self.python is None) or (dist.py_version is None) or (dist.py_version == self.python)) and compatible_platforms(dist.platform, self.platform))
|
'Remove `dist` from the environment'
| def remove(self, dist):
| self._distmap[dist.key].remove(dist)
|
'Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
the platform/python version defined at initialization are added.'
| def scan(self, search_path=None):
| if (search_path is None):
search_path = sys.path
for item in search_path:
for dist in find_distributions(item):
self.add(dist)
|
'Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project\'s distributions use their project\'s name converted to all
lowercase as their key.'
| def __getitem__(self, project_name):
| distribution_key = project_name.lower()
return self._distmap.get(distribution_key, [])
|
'Add `dist` if we ``can_add()`` it and it has not already been added'
| def add(self, dist):
| if (self.can_add(dist) and dist.has_version()):
dists = self._distmap.setdefault(dist.key, [])
if (dist not in dists):
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
|
'Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable ... | def best_match(self, req, working_set, installer=None):
| dist = working_set.find(req)
if (dist is not None):
return dist
for dist in self[req.key]:
if (dist in req):
return dist
return self.obtain(req, installer)
|
'Obtain a distribution matching `requirement` (e.g. via download)
Obtain a distro that matches requirement (e.g. via download). In the
base ``Environment`` class, this routine just returns
``installer(requirement)``, unless `installer` is None, in which case
None is returned instead. This method is a hook that allows... | def obtain(self, requirement, installer=None):
| if (installer is not None):
return installer(requirement)
|
'Yield the unique project names of the available distributions'
| def __iter__(self):
| for key in self._distmap.keys():
if self[key]:
(yield key)
|
'In-place addition of a distribution or environment'
| def __iadd__(self, other):
| if isinstance(other, Distribution):
self.add(other)
elif isinstance(other, Environment):
for project in other:
for dist in other[project]:
self.add(dist)
else:
raise TypeError(("Can't add %r to environment" % (other,)))
return self
|
'Add an environment or distribution to an environment'
| def __add__(self, other):
| new = self.__class__([], platform=None, python=None)
for env in (self, other):
new += env
return new
|
'Does the named resource exist?'
| def resource_exists(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).has_resource(resource_name)
|
'Is the named resource an existing directory?'
| def resource_isdir(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).resource_isdir(resource_name)
|
'Return a true filesystem path for specified resource'
| def resource_filename(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_filename(self, resource_name)
|
'Return a readable file-like object for specified resource'
| def resource_stream(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_stream(self, resource_name)
|
'Return specified resource as a string'
| def resource_string(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_string(self, resource_name)
|
'List the contents of the named resource directory'
| def resource_listdir(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).resource_listdir(resource_name)
|
'Give an error message for problems extracting file(s)'
| def extraction_error(self):
| old_exc = sys.exc_info()[1]
cache_path = (self.extraction_path or get_default_cache())
err = ExtractionError(("Can't extract file(s) to egg cache\n\nThe following error occurred while trying to extract file(s) to the Python egg\ncache:\n\n %s\n\nThe ... |
'Return absolute location in cache for `archive_name` and `names`
The parent directory of the resulting path will be created if it does
not already exist. `archive_name` should be the base filename of the
enclosing egg (which may not be the name of the enclosing zipfile!),
including its ".egg" extension. `names`, if ... | def get_cache_path(self, archive_name, names=()):
| extract_path = (self.extraction_path or get_default_cache())
target_path = os.path.join(extract_path, (archive_name + '-tmp'), *names)
try:
_bypass_ensure_directory(target_path)
except:
self.extraction_error()
self._warn_unsafe_extraction_path(extract_path)
self.cached_files[targ... |
'If the default extraction path is overridden and set to an insecure
location, such as /tmp, it opens up an opportunity for an attacker to
replace an extracted file with an unauthorized payload. Warn the user
if a known insecure location is used.
See Distribute #375 for more details.'
| @staticmethod
def _warn_unsafe_extraction_path(path):
| if ((os.name == 'nt') and (not path.startswith(os.environ['windir']))):
return
mode = os.stat(path).st_mode
if ((mode & stat.S_IWOTH) or (mode & stat.S_IWGRP)):
msg = ('%s is writable by group/others and vulnerable to attack when used with get_resource_fil... |
'Perform any platform-specific postprocessing of `tempname`
This is where Mac header rewrites should be done; other platforms don\'t
have anything special they should do.
Resource providers should call this method ONLY after successfully
extracting a compressed resource. They must NOT call it on resources
that are alr... | def postprocess(self, tempname, filename):
| if (os.name == 'posix'):
mode = ((os.stat(tempname).st_mode | 365) & 4095)
os.chmod(tempname, mode)
|
'Set the base path where resources will be extracted to, if needed.
If you do not call this routine before any extractions take place, the
path defaults to the return value of ``get_default_cache()``. (Which
is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
platform-specific fallbacks. See that ... | def set_extraction_path(self, path):
| if self.cached_files:
raise ValueError("Can't change extraction path, files already extracted")
self.extraction_path = path
|
'Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.'
| @classmethod
def is_invalid_marker(cls, text):
| try:
cls.evaluate_marker(text)
except SyntaxError:
return cls.normalize_exception(sys.exc_info()[1])
return False
|
'Given a SyntaxError from a marker evaluation, normalize the error
message:
- Remove indications of filename and line number.
- Replace platform-specific error messages with standard error
messages.'
| @staticmethod
def normalize_exception(exc):
| subs = {'unexpected EOF while parsing': 'invalid syntax', 'parenthesis is never closed': 'invalid syntax'}
exc.filename = None
exc.lineno = None
exc.msg = subs.get(exc.msg, exc.msg)
return exc
|
'Evaluate a PEP 426 environment marker on CPython 2.4+.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the \'parser\' module, which is not implemented
on
Jython and has been superseded by the \'ast\' module in Python 2.6 and
later.'
| @classmethod
def evaluate_marker(cls, text, extra=None):
| return cls.interpret(parser.expr(text).totuple(1)[1])
|
'Evaluate a PEP 426 environment marker using markerlib.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.'
| @classmethod
def _markerlib_evaluate(cls, text):
| import _markerlib
env = _markerlib.default_environment()
for key in env.keys():
new_key = key.replace('.', '_')
env[new_key] = env.pop(key)
try:
result = _markerlib.interpret(text, env)
except NameError:
e = sys.exc_info()[1]
raise SyntaxError(e.args[0])
r... |
'Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects.
Use a platform-specific path separator (os.sep) for the path keys
for compatibility with pypy on Windows.'
| @classmethod
def build(cls, path):
| with ContextualZipFile(path) as zfile:
items = ((name.replace('/', os.sep), zfile.getinfo(name)) for name in zfile.namelist())
return dict(items)
|
'Load a manifest at path or return a suitable manifest already loaded.'
| def load(self, path):
| path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if ((path not in self) or (self[path].mtime != mtime)):
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest
|
'Construct a ZipFile or ContextualZipFile as appropriate'
| def __new__(cls, *args, **kwargs):
| if hasattr(zipfile.ZipFile, '__exit__'):
return zipfile.ZipFile(*args, **kwargs)
return super(ContextualZipFile, cls).__new__(cls)
|
'Return True if the file_path is current for this zip_path'
| def _is_current(self, file_path, zip_path):
| (timestamp, size) = self._get_date_and_size(self.zipinfo[zip_path])
if (not os.path.isfile(file_path)):
return False
stat = os.stat(file_path)
if ((stat.st_size != size) or (stat.st_mtime != timestamp)):
return False
zip_contents = self.loader.get_data(zip_path)
with open(file_pa... |
'Create a metadata provider from a zipimporter'
| def __init__(self, importer):
| self.zip_pre = (importer.archive + os.sep)
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
else:
self.module_path = importer.archive
self._setup_prefix()
|
'Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional'
| @classmethod
def parse(cls, src, dist=None):
| try:
attrs = extras = ()
(name, value) = src.split('=', 1)
if ('[' in value):
(value, extras) = value.split('[', 1)
req = Requirement.parse(('x[' + extras))
if req.specs:
raise ValueError
extras = req.extras
if (':' in v... |
'Parse an entry point group'
| @classmethod
def parse_group(cls, group, lines, dist=None):
| if (not MODULE(group)):
raise ValueError('Invalid group name', group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if (ep.name in this):
raise ValueError('Duplicate entry point', group, ep.name)
this[ep.name] = ep
return thi... |
'Parse a map of entry point groups'
| @classmethod
def parse_map(cls, data, dist=None):
| if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for (group, lines) in data:
if (group is None):
if (not lines):
continue
raise ValueError('Entry points must be listed in groups')
... |
'List of Requirements needed for this distro if `extras` are used'
| def requires(self, extras=()):
| dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(('%s has no such extra feature %r' % (self, ext)))
return deps
|
'Ensure distribution is importable on `path` (default=sys.path)'
| def activate(self, path=None):
| if (path is None):
path = sys.path
self.insert_on(path)
if (path is sys.path):
fixup_namespace_packages(self.location)
for pkg in self._get_metadata('namespace_packages.txt'):
if (pkg in sys.modules):
declare_namespace(pkg)
|
'Return what this distribution\'s standard .egg filename should be'
| def egg_name(self):
| filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR)))
if self.platform:
filename += ('-' + self.platform)
return filename
|
'Delegate all unrecognized public attributes to .metadata provider'
| def __getattr__(self, attr):
| if attr.startswith('_'):
raise AttributeError(attr)
return getattr(self._provider, attr)
|
'Return a ``Requirement`` that matches this distribution exactly'
| def as_requirement(self):
| return Requirement.parse(('%s==%s' % (self.project_name, self.version)))
|
'Return the `name` entry point of `group` or raise ImportError'
| def load_entry_point(self, group, name):
| ep = self.get_entry_info(group, name)
if (ep is None):
raise ImportError(('Entry point %r not found' % ((group, name),)))
return ep.load()
|
'Return the entry point map for `group`, or the full entry map'
| def get_entry_map(self, group=None):
| try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self)
if (group is not None):
return ep_map.get(group, {})
return ep_map
|
'Return the EntryPoint object for `group`+`name`, or ``None``'
| def get_entry_info(self, group, name):
| return self.get_entry_map(group).get(name)
|
'Insert self.location in path before its nearest parent directory'
| def insert_on(self, path, loc=None):
| loc = (loc or self.location)
if (not loc):
return
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
npath = [((p and _normalize_cached(p)) or p) for p in path]
for (p, item) in enumerate(npath):
if (item == nloc):
break
elif ((item == bdir) and (self.... |
'Copy this distribution, substituting in any changed keyword args'
| def clone(self, **kw):
| names = 'project_name version py_version platform location precedence'
for attr in names.split():
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provider)
return self.__class__(**kw)
|
'Parse and cache metadata'
| @property
def _parsed_pkg_info(self):
| try:
return self._pkg_info
except AttributeError:
metadata = self.get_metadata(self.PKG_INFO)
self._pkg_info = email.parser.Parser().parsestr(metadata)
return self._pkg_info
|
'Convert \'Foobar (1); baz\' to (\'Foobar ==1\', \'baz\')
Split environment marker, add == prefix to version specifiers as
necessary, and remove parenthesis.'
| def _preparse_requirement(self, requires_dist):
| parts = (requires_dist.split(';', 1) + [''])
distvers = parts[0].strip()
mark = parts[1].strip()
distvers = re.sub(self.EQEQ, '\\1==\\2\\3', distvers)
distvers = distvers.replace('(', '').replace(')', '')
return (distvers, mark)
|
'Recompute this distribution\'s dependencies.'
| def _compute_dependencies(self):
| from _markerlib import compile as compile_marker
dm = self.__dep_map = {None: []}
reqs = []
for req in (self._parsed_pkg_info.get_all('Requires-Dist') or []):
(distvers, mark) = self._preparse_requirement(req)
parsed = next(parse_requirements(distvers))
parsed.marker_fn = compile... |
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
| def __init__(self, project_name, specs, extras):
| (self.unsafe_name, project_name) = (project_name, safe_name(project_name))
(self.project_name, self.key) = (project_name, project_name.lower())
index = [(parse_version(v), state_machine[op], op, v) for (op, v) in specs]
index.sort()
self.specs = [(op, ver) for (parsed, trans, op, ver) in index]
... |
'This is where the magic happens.
We do our usually processing through the states and when we have a token
to return we yield the token which pauses processing until the next token
is requested.'
| def __iter__(self):
| self.tokenQueue = deque([])
while self.state():
while self.stream.errors:
(yield {u'type': tokenTypes[u'ParseError'], u'data': self.stream.errors.pop(0)})
while self.tokenQueue:
(yield self.tokenQueue.popleft())
|
'This function returns either U+FFFD or the character based on the
decimal or hexadecimal representation. It also discards ";" if present.
If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.'
| def consumeNumberEntity(self, isHex):
| allowed = digits
radix = 10
if isHex:
allowed = hexDigits
radix = 16
charStack = []
c = self.stream.char()
while ((c in allowed) and (c is not EOF)):
charStack.append(c)
c = self.stream.char()
charAsInt = int(u''.join(charStack), radix)
if (charAsInt in re... |
'This method replaces the need for "entityInAttributeValueState".'
| def processEntityInAttribute(self, allowedChar):
| self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
|
'This method is a generic handler for emitting the tags. It also sets
the state to "data" because that\'s what\'s needed after a token has been
emitted.'
| def emitCurrentToken(self):
| token = self.currentToken
if (token[u'type'] in tagTokenTypes):
if self.lowercaseElementName:
token[u'name'] = token[u'name'].translate(asciiUpper2Lower)
if (token[u'type'] == tokenTypes[u'EndTag']):
if token[u'data']:
self.tokenQueue.append({u'type': toke... |
'Initialize HTMLSerializer.
Keyword options (default given first unless specified) include:
inject_meta_charset=True|False
Whether it insert a meta element to define the character set of the
document.
quote_attr_values=True|False
Whether to quote attribute values that don\'t require quoting
per HTML5 parsing rules.
quo... | def __init__(self, **kwargs):
| if (u'quote_char' in kwargs):
self.use_best_quote_char = False
for attr in self.options:
setattr(self, attr, kwargs.get(attr, getattr(self, attr)))
self.errors = []
self.strict = False
|
'Node representing an item in the tree.
name - The tag name associated with the node
parent - The parent of the current node (or None for the document node)
value - The value of the current node (applies to text nodes and
comments
attributes - a dict holding name, value pairs for attributes of the node
childNodes - a l... | def __init__(self, name):
| self.name = name
self.parent = None
self.value = None
self.attributes = {}
self.childNodes = []
self._flags = []
|
'Insert node as a child of the current node'
| def appendChild(self, node):
| raise NotImplementedError
|
'Insert data as text in the current node, positioned before the
start of node insertBefore or to the end of the node\'s text.'
| def insertText(self, data, insertBefore=None):
| raise NotImplementedError
|
'Insert node as a child of the current node, before refNode in the
list of child nodes. Raises ValueError if refNode is not a child of
the current node'
| def insertBefore(self, node, refNode):
| raise NotImplementedError
|
'Remove node from the children of the current node'
| def removeChild(self, node):
| raise NotImplementedError
|
'Move all the children of the current node to newParent.
This is needed so that trees that don\'t store text as nodes move the
text in the correct way'
| def reparentChildren(self, newParent):
| for child in self.childNodes:
newParent.appendChild(child)
self.childNodes = []
|
'Return a shallow copy of the current node i.e. a node with the same
name and attributes but with no parent or child nodes'
| def cloneNode(self):
| raise NotImplementedError
|
'Return true if the node has children or text, false otherwise'
| def hasContent(self):
| raise NotImplementedError
|
'Check if an element exists between the end of the active
formatting elements and the last marker. If it does, return it, else
return false'
| def elementInActiveFormattingElements(self, name):
| for item in self.activeFormattingElements[::(-1)]:
if (item == Marker):
break
elif (item.name == name):
return item
return False
|
'Create an element but don\'t insert it anywhere'
| def createElement(self, token):
| name = token[u'name']
namespace = token.get(u'namespace', self.defaultNamespace)
element = self.elementClass(name, namespace)
element.attributes = token[u'data']
return element
|
'Switch the function used to insert an element from the
normal one to the misnested table one and back again'
| def _setInsertFromTable(self, value):
| self._insertFromTable = value
if value:
self.insertElement = self.insertElementTable
else:
self.insertElement = self.insertElementNormal
|
'Create an element and insert it into the tree'
| def insertElementTable(self, token):
| element = self.createElement(token)
if (self.openElements[(-1)].name not in tableInsertModeElements):
return self.insertElementNormal(token)
else:
(parent, insertBefore) = self.getTableMisnestedNodePosition()
if (insertBefore is None):
parent.appendChild(element)
... |
'Insert text data.'
| def insertText(self, data, parent=None):
| if (parent is None):
parent = self.openElements[(-1)]
if ((not self.insertFromTable) or (self.insertFromTable and (self.openElements[(-1)].name not in tableInsertModeElements))):
parent.insertText(data)
else:
(parent, insertBefore) = self.getTableMisnestedNodePosition()
paren... |
'Get the foster parent element, and sibling to insert before
(or None) when inserting a misnested table node'
| def getTableMisnestedNodePosition(self):
| lastTable = None
fosterParent = None
insertBefore = None
for elm in self.openElements[::(-1)]:
if (elm.name == u'table'):
lastTable = elm
break
if lastTable:
if lastTable.parent:
fosterParent = lastTable.parent
insertBefore = lastTable
... |
'Return the final tree'
| def getDocument(self):
| return self.document
|
'Return the final fragment'
| def getFragment(self):
| fragment = self.fragmentClass()
self.openElements[0].reparentChildren(fragment)
return fragment
|
'Serialize the subtree of node in the format required by unit tests
node - the node from which to start serializing'
| def testSerializer(self, node):
| raise NotImplementedError
|
'Create the document root'
| def insertRoot(self, token):
| docStr = u''
if self.doctype:
assert self.doctype.name
docStr += (u'<!DOCTYPE %s' % self.doctype.name)
if ((self.doctype.publicId is not None) or (self.doctype.systemId is not None)):
docStr += (u' PUBLIC "%s" ' % self.infosetFilter.coercePubid((self.doctype.publi... |
'strict - raise an exception when a parse error is encountered
tree - a treebuilder class controlling the type of tree that will be
returned. Built in treebuilders can be accessed through
html5lib.treebuilders.getTreeBuilder(treeType)
tokenizer - a class that provides a stream of tokens to the treebuilder.
This may be ... | def __init__(self, tree=None, tokenizer=tokenizer.HTMLTokenizer, strict=False, namespaceHTMLElements=True, debug=False):
| self.strict = strict
if (tree is None):
tree = treebuilders.getTreeBuilder(u'etree')
self.tree = tree(namespaceHTMLElements)
self.tokenizer_class = tokenizer
self.errors = []
self.phases = dict([(name, cls(self, self.tree)) for (name, cls) in getPhases(debug).items()])
|
'The name of the character encoding
that was used to decode the input stream,
or :obj:`None` if that is not determined yet.'
| @property
def documentEncoding(self):
| if (not hasattr(self, u'tokenizer')):
return None
return self.tokenizer.stream.charEncoding[0]
|
'Parse a HTML document into a well-formed tree
stream - a filelike object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)'
| def parse(self, stream, encoding=None, parseMeta=True, useChardet=True):
| self._parse(stream, innerHTML=False, encoding=encoding, parseMeta=parseMeta, useChardet=useChardet)
return self.tree.getDocument()
|
'Parse a HTML fragment into a well-formed tree fragment
container - name of the element we\'re setting the innerHTML property
if set to None, default to \'div\'
stream - a filelike object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specifi... | def parseFragment(self, stream, container=u'div', encoding=None, parseMeta=False, useChardet=True):
| self._parse(stream, True, container=container, encoding=encoding)
return self.tree.getFragment()
|
'HTML5 specific normalizations to the token stream'
| def normalizeToken(self, token):
| if (token[u'type'] == tokenTypes[u'StartTag']):
token[u'data'] = dict(token[u'data'][::(-1)])
return token
|
'Generic RCDATA/RAWTEXT Parsing algorithm
contentType - RCDATA or RAWTEXT'
| def parseRCDataRawtext(self, token, contentType):
| assert (contentType in (u'RAWTEXT', u'RCDATA'))
self.tree.insertElement(token)
if (contentType == u'RAWTEXT'):
self.tokenizer.state = self.tokenizer.rawtextState
else:
self.tokenizer.state = self.tokenizer.rcdataState
self.originalPhase = self.phase
self.phase = self.phases[u'tex... |
'Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless ... | def __init__(self, source):
| if (not utils.supports_lone_surrogates):
self.reportCharacterErrors = None
self.replaceCharactersRegexp = None
elif (len(u'\U0010ffff') == 1):
self.reportCharacterErrors = self.characterErrorsUCS4
self.replaceCharactersRegexp = re.compile(eval(u'"[\\uD800-\\uDFFF]"'))
else:
... |
'Produces a file object from source.
source can be either a file object, local filename or a string.'
| def openStream(self, source):
| if hasattr(source, u'read'):
stream = source
else:
stream = StringIO(source)
return stream
|
'Returns (line, col) of the current position in the stream.'
| def position(self):
| (line, col) = self._position(self.chunkOffset)
return ((line + 1), col)
|
'Read one character from the stream or queue if available. Return
EOF when EOF is reached.'
| def char(self):
| if (self.chunkOffset >= self.chunkSize):
if (not self.readChunk()):
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = (chunkOffset + 1)
return char
|
'Returns a string of characters from the stream up to but not
including any character in \'characters\' or EOF. \'characters\' must be
a container that supports the \'in\' method and iteration over its
characters.'
| def charsUntil(self, characters, opposite=False):
| try:
chars = charsUntilRegEx[(characters, opposite)]
except KeyError:
if __debug__:
for c in characters:
assert (ord(c) < 128)
regex = u''.join([(u'\\x%02x' % ord(c)) for c in characters])
if (not opposite):
regex = (u'^%s' % regex)
... |
'Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless ... | def __init__(self, source, encoding=None, parseMeta=True, chardet=True):
| self.rawStream = self.openStream(source)
HTMLUnicodeInputStream.__init__(self, self.rawStream)
self.charEncoding = (codecName(encoding), u'certain')
self.numBytesMeta = 512
self.numBytesChardet = 100
self.defaultEncoding = u'windows-1252'
if (self.charEncoding[0] is None):
self.charE... |
'Produces a file object from source.
source can be either a file object, local filename or a string.'
| def openStream(self, source):
| if hasattr(source, u'read'):
stream = source
else:
stream = BytesIO(source)
try:
stream.seek(stream.tell())
except:
stream = BufferedStream(stream)
return stream
|
'Attempts to detect at BOM at the start of the stream. If
an encoding can be determined from the BOM return the name of the
encoding otherwise return None'
| def detectBOM(self):
| bomDict = {codecs.BOM_UTF8: u'utf-8', codecs.BOM_UTF16_LE: u'utf-16-le', codecs.BOM_UTF16_BE: u'utf-16-be', codecs.BOM_UTF32_LE: u'utf-32-le', codecs.BOM_UTF32_BE: u'utf-32-be'}
string = self.rawStream.read(4)
assert isinstance(string, bytes)
encoding = bomDict.get(string[:3])
seek = 3
if (not e... |
'Report the encoding declared by the meta element'
| def detectEncodingMeta(self):
| buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
if (encoding in (u'utf-16', u'utf-16-be', u'utf-16-le')):
encoding = u'utf-8'
return encoding
|
'Skip past a list of characters'
| def skip(self, chars=spaceCharactersBytes):
| p = self.position
while (p < len(self)):
c = self[p:(p + 1)]
if (c not in chars):
self._position = p
return c
p += 1
self._position = p
return None
|
'Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone'
| def matchBytes(self, bytes):
| p = self.position
data = self[p:(p + len(bytes))]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv
|
'Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match'
| def jumpTo(self, bytes):
| newPosition = self[self.position:].find(bytes)
if (newPosition > (-1)):
if (self._position == (-1)):
self._position = 0
self._position += ((newPosition + len(bytes)) - 1)
return True
else:
raise StopIteration
|
'string - the data to work on for encoding detection'
| def __init__(self, data):
| self.data = EncodingBytes(data)
self.encoding = None
|
'Skip over comments'
| def handleComment(self):
| return self.data.jumpTo('-->')
|
'Return a name,value pair for the next attribute in the stream,
if one is found, or None'
| def getAttribute(self):
| data = self.data
c = data.skip((spaceCharactersBytes | frozenset(['/'])))
assert ((c is None) or (len(c) == 1))
if (c in ('>', None)):
return None
attrName = []
attrValue = []
while True:
if ((c == '=') and attrName):
break
elif (c in spaceCharactersBytes)... |
'A hack to get around the deprecation errors in 2.6.'
| @property
def message(self):
| return self._message
|
'Returns this token as a plain string, suitable for storage.
The resulting string includes the token\'s secret, so you should never
send or store this string where a third party can read it.'
| def to_string(self):
| data = {'oauth_token': self.key, 'oauth_token_secret': self.secret}
if (self.callback_confirmed is not None):
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
|
'Deserializes a token from a string like one returned by
`to_string()`.'
| @staticmethod
def from_string(s):
| if (not len(s)):
raise ValueError('Invalid parameter string.')
params = parse_qs(s, keep_blank_values=False)
if (not len(params)):
raise ValueError('Invalid parameter string.')
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.