id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
174,404
from .nbbase import nbformat, nbformat_minor def _unbytes(obj): """There should be no bytes objects in a notebook v2 stores png/jpeg as b64 ascii bytes """ if isinstance(obj, dict): for k, v in obj.items(): obj[k] = _unbytes(v) elif isinstance(obj, list): for i, v in enumerate(obj): obj[i] = _unbytes(v) elif isinstance(obj, bytes): # only valid bytes are b64-encoded ascii obj = obj.decode("ascii") return obj from nbformat._struct import Struct nbformat = 3 nbformat_minor = 0 The provided code snippet includes necessary dependencies for implementing the `upgrade` function. Write a Python function `def upgrade(nb, from_version=2, from_minor=0)` to solve the following problem: Convert a notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). Here is the function: def upgrade(nb, from_version=2, from_minor=0): """Convert a notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). """ if from_version == 2: # noqa # Mark the original nbformat so consumers know it has been converted. nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor nb.orig_nbformat = 2 nb = _unbytes(nb) for ws in nb["worksheets"]: for cell in ws["cells"]: cell.setdefault("metadata", {}) return nb elif from_version == 3: # noqa if from_minor != nbformat_minor: nb.orig_nbformat_minor = from_minor nb.nbformat_minor = nbformat_minor return nb else: msg = ( "Cannot convert a notebook directly from v%s to v3. " "Try using the nbformat.convert module." % from_version ) raise ValueError(msg)
Convert a notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3).
174,405
from .nbbase import nbformat, nbformat_minor def heading_to_md(cell): """turn heading cell into corresponding markdown""" cell.cell_type = "markdown" level = cell.pop("level", 1) cell.source = "#" * level + " " + cell.source def raw_to_md(cell): """let raw passthrough as markdown""" cell.cell_type = "markdown" from nbformat._struct import Struct nbformat = 3 The provided code snippet includes necessary dependencies for implementing the `downgrade` function. Write a Python function `def downgrade(nb)` to solve the following problem: Convert a v3 notebook to v2. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. Here is the function: def downgrade(nb): """Convert a v3 notebook to v2. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. """ if nb.nbformat != 3: # noqa return nb nb.nbformat = 2 for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == "heading": heading_to_md(cell) elif cell.cell_type == "raw": raw_to_md(cell) return nb
Convert a v3 notebook to v2. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert.
174,406
from base64 import decodebytes, encodebytes The provided code snippet includes necessary dependencies for implementing the `restore_bytes` function. Write a Python function `def restore_bytes(nb)` to solve the following problem: Restore bytes of image data from unicode-only formats. Base64 encoding is handled elsewhere. Bytes objects in the notebook are always b64-encoded. We DO NOT encode/decode around file formats. Note: this is never used Here is the function: def restore_bytes(nb): """Restore bytes of image data from unicode-only formats. Base64 encoding is handled elsewhere. Bytes objects in the notebook are always b64-encoded. We DO NOT encode/decode around file formats. Note: this is never used """ for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == "code": for output in cell.outputs: if "png" in output: output.png = output.png.encode("ascii", "replace") if "jpeg" in output: output.jpeg = output.jpeg.encode("ascii", "replace") return nb
Restore bytes of image data from unicode-only formats. Base64 encoding is handled elsewhere. Bytes objects in the notebook are always b64-encoded. We DO NOT encode/decode around file formats. Note: this is never used
174,407
from base64 import decodebytes, encodebytes _multiline_outputs = ["text", "html", "svg", "latex", "javascript", "json"] def _join_lines(lines): """join lines that have been written by splitlines() Has logic to protect against `splitlines()`, which should have been `splitlines(True)` """ if lines and lines[0].endswith(("\n", "\r")): # created by splitlines(True) return "".join(lines) else: # created by splitlines() return "\n".join(lines) The provided code snippet includes necessary dependencies for implementing the `rejoin_lines` function. Write a Python function `def rejoin_lines(nb)` to solve the following problem: rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines. Here is the function: def rejoin_lines(nb): """rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines. """ for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == "code": if "input" in cell and isinstance(cell.input, list): cell.input = _join_lines(cell.input) for output in cell.outputs: for key in _multiline_outputs: item = output.get(key, None) if isinstance(item, list): output[key] = _join_lines(item) else: # text, heading cell for key in ["source", "rendered"]: item = cell.get(key, None) if isinstance(item, list): cell[key] = _join_lines(item) return nb
rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines.
174,408
from base64 import decodebytes, encodebytes _multiline_outputs = ["text", "html", "svg", "latex", "javascript", "json"] The provided code snippet includes necessary dependencies for implementing the `split_lines` function. Write a Python function `def split_lines(nb)` to solve the following problem: split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. Here is the function: def split_lines(nb): """split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. """ for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == "code": if "input" in cell and isinstance(cell.input, str): cell.input = cell.input.splitlines(True) for output in cell.outputs: for key in _multiline_outputs: item = output.get(key, None) if isinstance(item, str): output[key] = item.splitlines(True) else: # text, heading cell for key in ["source", "rendered"]: item = cell.get(key, None) if isinstance(item, str): cell[key] = item.splitlines(True) return nb
split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files.
174,411
from base64 import decodebytes, encodebytes The provided code snippet includes necessary dependencies for implementing the `strip_transient` function. Write a Python function `def strip_transient(nb)` to solve the following problem: Strip transient values that shouldn't be stored in files. This should be called in *both* read and write. Here is the function: def strip_transient(nb): """Strip transient values that shouldn't be stored in files. This should be called in *both* read and write. """ nb.pop("orig_nbformat", None) nb.pop("orig_nbformat_minor", None) for ws in nb["worksheets"]: for cell in ws["cells"]: cell.get("metadata", {}).pop("trusted", None) # strip cell.trusted even though it shouldn't be used, # since it's where the transient value used to be stored. cell.pop("trusted", None) return nb
Strip transient values that shouldn't be stored in files. This should be called in *both* read and write.
174,412
import re import warnings from traitlets.log import get_logger from nbformat import v3 as _v_latest from nbformat.v3 import ( NotebookNode, nbformat, nbformat_minor, nbformat_schema, new_author, new_code_cell, new_heading_cell, new_metadata, new_notebook, new_output, new_text_cell, new_worksheet, parse_filename, to_notebook_json, ) from . import versions from .converter import convert from .reader import reads as reader_reads from .validator import ValidationError, validate warnings.warn( """nbformat.current is deprecated since before nbformat 3.0 - use nbformat for read/write/validate public API - use nbformat.vX directly to composing notebooks of a particular version """, DeprecationWarning, ) def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa """Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string to read the notebook from. Returns ------- nb : NotebookNode The notebook that was read. """ if format not in {"DEPRECATED", "json"}: _warn_format() nb = reader_reads(s, **kwargs) nb = convert(nb, version) try: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) validate(nb, repair_duplicate_cell_ids=False) except ValidationError as e: get_logger().error("Notebook JSON is invalid: %s", e) return nb def reads(s, **kwargs): """Read a notebook from a json string and return the NotebookNode object. This function properly reads notebooks of any version. No version conversion is performed. Parameters ---------- s : unicode | bytes The raw string or bytes object to read the notebook from. Returns ------- nb : NotebookNode The notebook that was read. Raises ------ ValidationError Notebook JSON for a given version is missing an expected key and cannot be read. NBFormatError Specified major version is invalid or unsupported. """ from . import NBFormatError, versions nb_dict = parse_json(s, **kwargs) (major, minor) = get_version(nb_dict) if major in versions: try: return versions[major].to_notebook_json(nb_dict, minor=minor) except AttributeError as e: msg = f"The notebook is invalid and is missing an expected key: {e}" raise ValidationError(msg) from None else: raise NBFormatError("Unsupported nbformat version %s" % major) The provided code snippet includes necessary dependencies for implementing the `reads_json` function. Write a Python function `def reads_json(nbjson, **kwargs)` to solve the following problem: DEPRECATED, use reads Here is the function: def reads_json(nbjson, **kwargs): """DEPRECATED, use reads""" warnings.warn( "reads_json is deprecated since nbformat 3.0, use reads", DeprecationWarning, stacklevel=2, ) return reads(nbjson)
DEPRECATED, use reads
174,413
import re import warnings from traitlets.log import get_logger from nbformat import v3 as _v_latest from nbformat.v3 import ( NotebookNode, nbformat, nbformat_minor, nbformat_schema, new_author, new_code_cell, new_heading_cell, new_metadata, new_notebook, new_output, new_text_cell, new_worksheet, parse_filename, to_notebook_json, ) from . import versions from .converter import convert from .reader import reads as reader_reads from .validator import ValidationError, validate class NBFormatError(ValueError): """An error raised for an nbformat error.""" pass def _warn_format(): warnings.warn( """Non-JSON file support in nbformat is deprecated since nbformat 1.0. Use nbconvert to create files of other formats.""" ) def parse_py(s, **kwargs): """Parse a string into a (nbformat, string) tuple.""" nbf = current_nbformat nbm = current_nbformat_minor pattern = r"# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>" m = re.search(pattern, s) if m is not None: digits = m.group("nbformat").split(".") nbf = int(digits[0]) if len(digits) > 1: nbm = int(digits[1]) return nbf, nbm, s The provided code snippet includes necessary dependencies for implementing the `reads_py` function. Write a Python function `def reads_py(s, **kwargs)` to solve the following problem: DEPRECATED: use nbconvert Here is the function: def reads_py(s, **kwargs): """DEPRECATED: use nbconvert""" _warn_format() nbf, nbm, s = parse_py(s, **kwargs) if nbf in (2, 3): nb = versions[nbf].to_notebook_py(s, **kwargs) else: raise NBFormatError("Unsupported PY nbformat version: %i" % nbf) return nb
DEPRECATED: use nbconvert
174,414
import re import warnings from traitlets.log import get_logger from nbformat import v3 as _v_latest from nbformat.v3 import ( NotebookNode, nbformat, nbformat_minor, nbformat_schema, new_author, new_code_cell, new_heading_cell, new_metadata, new_notebook, new_output, new_text_cell, new_worksheet, parse_filename, to_notebook_json, ) from . import versions from .converter import convert from .reader import reads as reader_reads from .validator import ValidationError, validate def _warn_format(): warnings.warn( """Non-JSON file support in nbformat is deprecated since nbformat 1.0. Use nbconvert to create files of other formats.""" ) The provided code snippet includes necessary dependencies for implementing the `writes_py` function. Write a Python function `def writes_py(nb, **kwargs)` to solve the following problem: DEPRECATED: use nbconvert Here is the function: def writes_py(nb, **kwargs): """DEPRECATED: use nbconvert""" _warn_format() return versions[3].writes_py(nb, **kwargs)
DEPRECATED: use nbconvert
174,415
import re import warnings from traitlets.log import get_logger from nbformat import v3 as _v_latest from nbformat.v3 import ( NotebookNode, nbformat, nbformat_minor, nbformat_schema, new_author, new_code_cell, new_heading_cell, new_metadata, new_notebook, new_output, new_text_cell, new_worksheet, parse_filename, to_notebook_json, ) from . import versions from .converter import convert from .reader import reads as reader_reads from .validator import ValidationError, validate def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa """Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string to read the notebook from. Returns ------- nb : NotebookNode The notebook that was read. """ if format not in {"DEPRECATED", "json"}: _warn_format() nb = reader_reads(s, **kwargs) nb = convert(nb, version) try: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) validate(nb, repair_duplicate_cell_ids=False) except ValidationError as e: get_logger().error("Notebook JSON is invalid: %s", e) return nb def reads(s, **kwargs): """Read a notebook from a json string and return the NotebookNode object. This function properly reads notebooks of any version. No version conversion is performed. Parameters ---------- s : unicode | bytes The raw string or bytes object to read the notebook from. Returns ------- nb : NotebookNode The notebook that was read. Raises ------ ValidationError Notebook JSON for a given version is missing an expected key and cannot be read. NBFormatError Specified major version is invalid or unsupported. """ from . import NBFormatError, versions nb_dict = parse_json(s, **kwargs) (major, minor) = get_version(nb_dict) if major in versions: try: return versions[major].to_notebook_json(nb_dict, minor=minor) except AttributeError as e: msg = f"The notebook is invalid and is missing an expected key: {e}" raise ValidationError(msg) from None else: raise NBFormatError("Unsupported nbformat version %s" % major) The provided code snippet includes necessary dependencies for implementing the `read` function. Write a Python function `def read(fp, format="DEPRECATED", **kwargs)` to solve the following problem: Read a notebook from a file and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was read. Here is the function: def read(fp, format="DEPRECATED", **kwargs): # noqa """Read a notebook from a file and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was read. """ return reads(fp.read(), **kwargs)
Read a notebook from a file and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was read.
174,416
import re import warnings from traitlets.log import get_logger from nbformat import v3 as _v_latest from nbformat.v3 import ( NotebookNode, nbformat, nbformat_minor, nbformat_schema, new_author, new_code_cell, new_heading_cell, new_metadata, new_notebook, new_output, new_text_cell, new_worksheet, parse_filename, to_notebook_json, ) from . import versions from .converter import convert from .reader import reads as reader_reads from .validator import ValidationError, validate def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa """Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. version : int The nbformat version to write. Used for downgrading notebooks. Returns ------- s : unicode The notebook string. """ if format not in {"DEPRECATED", "json"}: _warn_format() nb = convert(nb, version) try: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) validate(nb, repair_duplicate_cell_ids=False) except ValidationError as e: get_logger().error("Notebook JSON is invalid: %s", e) return versions[version].writes_json(nb, **kwargs) The provided code snippet includes necessary dependencies for implementing the `write` function. Write a Python function `def write(nb, fp, format="DEPRECATED", **kwargs)` to solve the following problem: Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. Here is the function: def write(nb, fp, format="DEPRECATED", **kwargs): # noqa """Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. """ s = writes(nb, **kwargs) if isinstance(s, bytes): s = s.decode("utf8") return fp.write(s)
Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method.
174,417
from nbformat.corpus.words import generate_corpus_id as random_cell_id from nbformat.notebooknode import NotebookNode def new_output(output_type, data=None, **kwargs): """Create a new output, to go in the ``cell.outputs`` list of a code cell.""" output = NotebookNode(output_type=output_type) # populate defaults: if output_type == "stream": output.name = "stdout" output.text = "" elif output_type == "display_data": output.metadata = NotebookNode() output.data = NotebookNode() elif output_type == "execute_result": output.metadata = NotebookNode() output.data = NotebookNode() output.execution_count = None elif output_type == "error": output.ename = "NotImplementedError" output.evalue = "" output.traceback = [] # load from args: output.update(kwargs) if data is not None: output.data = data # validate validate(output, output_type) return output The provided code snippet includes necessary dependencies for implementing the `output_from_msg` function. Write a Python function `def output_from_msg(msg)` to solve the following problem: Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message. Here is the function: def output_from_msg(msg): """Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message. """ msg_type = msg["header"]["msg_type"] content = msg["content"] if msg_type == "execute_result": return new_output( output_type=msg_type, metadata=content["metadata"], data=content["data"], execution_count=content["execution_count"], ) elif msg_type == "stream": return new_output( output_type=msg_type, name=content["name"], text=content["text"], ) elif msg_type == "display_data": return new_output( output_type=msg_type, metadata=content["metadata"], data=content["data"], ) elif msg_type == "error": return new_output( output_type=msg_type, ename=content["ename"], evalue=content["evalue"], traceback=content["traceback"], ) else: raise ValueError("Unrecognized output msg type: %r" % msg_type)
Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message.
174,418
from nbformat.corpus.words import generate_corpus_id as random_cell_id from nbformat.notebooknode import NotebookNode def validate(node, ref=None): """validate a v4 node""" from nbformat import validate as validate_orig return validate_orig(node, ref=ref, version=nbformat) class NotebookNode(Struct): """A dict-like node with attribute-access""" def __setitem__(self, key, value): """Set an item on the notebook.""" if isinstance(value, Mapping) and not isinstance(value, NotebookNode): value = from_dict(value) super().__setitem__(key, value) def update(self, *args, **kwargs): """ A dict-like update method based on CPython's MutableMapping `update` method. """ if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) if args: other = args[0] if isinstance(other, Mapping): # noqa for key in other: self[key] = other[key] elif hasattr(other, "keys"): for key in other: self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwargs.items(): self[key] = value The provided code snippet includes necessary dependencies for implementing the `new_code_cell` function. Write a Python function `def new_code_cell(source="", **kwargs)` to solve the following problem: Create a new code cell Here is the function: def new_code_cell(source="", **kwargs): """Create a new code cell""" cell = NotebookNode( id=random_cell_id(), cell_type="code", metadata=NotebookNode(), execution_count=None, source=source, outputs=[], ) cell.update(kwargs) validate(cell, "code_cell") return cell
Create a new code cell
174,419
from nbformat.corpus.words import generate_corpus_id as random_cell_id from nbformat.notebooknode import NotebookNode def validate(node, ref=None): """validate a v4 node""" from nbformat import validate as validate_orig return validate_orig(node, ref=ref, version=nbformat) class NotebookNode(Struct): """A dict-like node with attribute-access""" def __setitem__(self, key, value): """Set an item on the notebook.""" if isinstance(value, Mapping) and not isinstance(value, NotebookNode): value = from_dict(value) super().__setitem__(key, value) def update(self, *args, **kwargs): """ A dict-like update method based on CPython's MutableMapping `update` method. """ if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) if args: other = args[0] if isinstance(other, Mapping): # noqa for key in other: self[key] = other[key] elif hasattr(other, "keys"): for key in other: self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwargs.items(): self[key] = value The provided code snippet includes necessary dependencies for implementing the `new_markdown_cell` function. Write a Python function `def new_markdown_cell(source="", **kwargs)` to solve the following problem: Create a new markdown cell Here is the function: def new_markdown_cell(source="", **kwargs): """Create a new markdown cell""" cell = NotebookNode( id=random_cell_id(), cell_type="markdown", source=source, metadata=NotebookNode(), ) cell.update(kwargs) validate(cell, "markdown_cell") return cell
Create a new markdown cell
174,420
from nbformat.corpus.words import generate_corpus_id as random_cell_id from nbformat.notebooknode import NotebookNode def validate(node, ref=None): """validate a v4 node""" from nbformat import validate as validate_orig return validate_orig(node, ref=ref, version=nbformat) class NotebookNode(Struct): """A dict-like node with attribute-access""" def __setitem__(self, key, value): """Set an item on the notebook.""" if isinstance(value, Mapping) and not isinstance(value, NotebookNode): value = from_dict(value) super().__setitem__(key, value) def update(self, *args, **kwargs): """ A dict-like update method based on CPython's MutableMapping `update` method. """ if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) if args: other = args[0] if isinstance(other, Mapping): # noqa for key in other: self[key] = other[key] elif hasattr(other, "keys"): for key in other: self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwargs.items(): self[key] = value The provided code snippet includes necessary dependencies for implementing the `new_raw_cell` function. Write a Python function `def new_raw_cell(source="", **kwargs)` to solve the following problem: Create a new raw cell Here is the function: def new_raw_cell(source="", **kwargs): """Create a new raw cell""" cell = NotebookNode( id=random_cell_id(), cell_type="raw", source=source, metadata=NotebookNode(), ) cell.update(kwargs) validate(cell, "raw_cell") return cell
Create a new raw cell
174,421
from nbformat.corpus.words import generate_corpus_id as random_cell_id from nbformat.notebooknode import NotebookNode nbformat = 4 nbformat_minor = 5 def validate(node, ref=None): """validate a v4 node""" from nbformat import validate as validate_orig return validate_orig(node, ref=ref, version=nbformat) class NotebookNode(Struct): """A dict-like node with attribute-access""" def __setitem__(self, key, value): """Set an item on the notebook.""" if isinstance(value, Mapping) and not isinstance(value, NotebookNode): value = from_dict(value) super().__setitem__(key, value) def update(self, *args, **kwargs): """ A dict-like update method based on CPython's MutableMapping `update` method. """ if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) if args: other = args[0] if isinstance(other, Mapping): # noqa for key in other: self[key] = other[key] elif hasattr(other, "keys"): for key in other: self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwargs.items(): self[key] = value The provided code snippet includes necessary dependencies for implementing the `new_notebook` function. Write a Python function `def new_notebook(**kwargs)` to solve the following problem: Create a new notebook Here is the function: def new_notebook(**kwargs): """Create a new notebook""" nb = NotebookNode( nbformat=nbformat, nbformat_minor=nbformat_minor, metadata=NotebookNode(), cells=[], ) nb.update(kwargs) validate(nb) return nb
Create a new notebook
174,422
import json import re from traitlets.log import get_logger from nbformat import v3, validator from .nbbase import NotebookNode, nbformat, nbformat_minor, random_cell_id def _warn_if_invalid(nb, version): """Log validation errors, if there are any.""" from nbformat import ValidationError, validate try: validate(nb, version=version) except ValidationError as e: get_logger().error("Notebook JSON is not valid v%i: %s", version, e) def upgrade_cell(cell): """upgrade a cell from v3 to v4 heading cell: - -> markdown heading code cell: - remove language metadata - cell.input -> cell.source - cell.prompt_number -> cell.execution_count - update outputs """ cell.setdefault("metadata", NotebookNode()) cell.id = random_cell_id() if cell.cell_type == "code": cell.pop("language", "") if "collapsed" in cell: cell.metadata["collapsed"] = cell.pop("collapsed") cell.source = cell.pop("input", "") cell.execution_count = cell.pop("prompt_number", None) cell.outputs = upgrade_outputs(cell.outputs) elif cell.cell_type == "heading": cell.cell_type = "markdown" level = cell.pop("level", 1) cell.source = "{hashes} {single_line}".format( hashes="#" * level, single_line=" ".join(cell.get("source", "").splitlines()), ) elif cell.cell_type == "html": # Technically, this exists. It will never happen in practice. cell.cell_type = "markdown" return cell from nbformat.corpus.words import generate_corpus_id as random_cell_id from nbformat.notebooknode import NotebookNode nbformat = 4 nbformat_minor = 5 The provided code snippet includes necessary dependencies for implementing the `upgrade` function. Write a Python function `def upgrade(nb, from_version=None, from_minor=None)` to solve the following problem: Convert a notebook to latest v4. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). Here is the function: def upgrade(nb, from_version=None, from_minor=None): # noqa """Convert a notebook to latest v4. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). """ if not from_version: from_version = nb["nbformat"] if not from_minor: if "nbformat_minor" not in nb: if from_version == 4: # noqa msg = "The v4 notebook does not include the nbformat minor, which is needed." raise validator.ValidationError(msg) else: from_minor = 0 else: from_minor = nb["nbformat_minor"] if from_version == 3: # noqa # Validate the notebook before conversion _warn_if_invalid(nb, from_version) # Mark the original nbformat so consumers know it has been converted orig_nbformat = nb.pop("orig_nbformat", None) orig_nbformat_minor = nb.pop("orig_nbformat_minor", None) nb.metadata.orig_nbformat = orig_nbformat or 3 nb.metadata.orig_nbformat_minor = orig_nbformat_minor or 0 # Mark the new format nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor # remove worksheet(s) nb["cells"] = cells = [] # In the unlikely event of multiple worksheets, # they will be flattened for ws in nb.pop("worksheets", []): # upgrade each cell for cell in ws["cells"]: cells.append(upgrade_cell(cell)) # upgrade metadata nb.metadata.pop("name", "") nb.metadata.pop("signature", "") # Validate the converted notebook before returning it _warn_if_invalid(nb, nbformat) return nb elif from_version == 4: # noqa if from_minor == nbformat_minor: return nb # other versions migration code e.g. # if from_minor < 3: # if from_minor < 4: if from_minor < 5: # noqa for cell in nb.cells: cell.id = random_cell_id() nb.metadata.orig_nbformat_minor = from_minor nb.nbformat_minor = nbformat_minor return nb else: raise ValueError( "Cannot convert a notebook directly from v%s to v4. " "Try using the nbformat.convert module." % from_version )
Convert a notebook to latest v4. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3).
174,423
import json import re from traitlets.log import get_logger from nbformat import v3, validator from .nbbase import NotebookNode, nbformat, nbformat_minor, random_cell_id def _warn_if_invalid(nb, version): """Log validation errors, if there are any.""" from nbformat import ValidationError, validate try: validate(nb, version=version) except ValidationError as e: get_logger().error("Notebook JSON is not valid v%i: %s", version, e) def downgrade_cell(cell): """downgrade a cell from v4 to v3 code cell: - set cell.language - cell.input <- cell.source - cell.prompt_number <- cell.execution_count - update outputs markdown cell: - single-line heading -> heading cell """ if cell.cell_type == "code": cell.language = "python" cell.input = cell.pop("source", "") cell.prompt_number = cell.pop("execution_count", None) cell.collapsed = cell.metadata.pop("collapsed", False) cell.outputs = downgrade_outputs(cell.outputs) elif cell.cell_type == "markdown": source = cell.get("source", "") if "\n" not in source and source.startswith("#"): match = re.match(r"(#+)\s*(.*)", source) assert match is not None # noqa prefix, text = match.groups() cell.cell_type = "heading" cell.source = text cell.level = len(prefix) cell.pop("id", None) cell.pop("attachments", None) return cell from nbformat.corpus.words import generate_corpus_id as random_cell_id from nbformat.notebooknode import NotebookNode nbformat = 4 nbformat_minor = 5 The provided code snippet includes necessary dependencies for implementing the `downgrade` function. Write a Python function `def downgrade(nb)` to solve the following problem: Convert a v4 notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. Here is the function: def downgrade(nb): """Convert a v4 notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. """ if nb.nbformat != nbformat: return nb # Validate the notebook before conversion _warn_if_invalid(nb, nbformat) nb.nbformat = v3.nbformat nb.nbformat_minor = v3.nbformat_minor cells = [downgrade_cell(cell) for cell in nb.pop("cells")] nb.worksheets = [v3.new_worksheet(cells=cells)] nb.metadata.setdefault("name", "") # Validate the converted notebook before returning it _warn_if_invalid(nb, v3.nbformat) nb.orig_nbformat = nb.metadata.pop("orig_nbformat", nbformat) nb.orig_nbformat_minor = nb.metadata.pop("orig_nbformat_minor", nbformat_minor) return nb
Convert a v4 notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert.
174,424
def _rejoin_mimebundle(data): """Rejoin the multi-line string fields in a mimebundle (in-place)""" for key, value in list(data.items()): if ( not _is_json_mime(key) and isinstance(value, list) and all(isinstance(line, str) for line in value) ): data[key] = "".join(value) return data The provided code snippet includes necessary dependencies for implementing the `rejoin_lines` function. Write a Python function `def rejoin_lines(nb)` to solve the following problem: rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines. Here is the function: def rejoin_lines(nb): """rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines. """ for cell in nb.cells: if "source" in cell and isinstance(cell.source, list): cell.source = "".join(cell.source) attachments = cell.get("attachments", {}) for _, attachment in attachments.items(): _rejoin_mimebundle(attachment) if cell.get("cell_type", None) == "code": for output in cell.get("outputs", []): output_type = output.get("output_type", "") if output_type in {"execute_result", "display_data"}: _rejoin_mimebundle(output.get("data", {})) elif output_type and isinstance(output.get("text", ""), list): output.text = "".join(output.text) return nb
rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines.
174,425
def _split_mimebundle(data): """Split multi-line string fields in a mimebundle (in-place)""" for key, value in list(data.items()): if isinstance(value, str) and (key.startswith("text/") or key in _non_text_split_mimes): data[key] = value.splitlines(True) return data The provided code snippet includes necessary dependencies for implementing the `split_lines` function. Write a Python function `def split_lines(nb)` to solve the following problem: split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. Here is the function: def split_lines(nb): """split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. """ for cell in nb.cells: source = cell.get("source", None) if isinstance(source, str): cell["source"] = source.splitlines(True) attachments = cell.get("attachments", {}) for _, attachment in attachments.items(): _split_mimebundle(attachment) if cell.cell_type == "code": for output in cell.outputs: if output.output_type in {"execute_result", "display_data"}: _split_mimebundle(output.get("data", {})) elif output.output_type == "stream" and isinstance(output.text, str): output.text = output.text.splitlines(True) return nb
split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files.
174,426
The provided code snippet includes necessary dependencies for implementing the `strip_transient` function. Write a Python function `def strip_transient(nb)` to solve the following problem: Strip transient values that shouldn't be stored in files. This should be called in *both* read and write. Here is the function: def strip_transient(nb): """Strip transient values that shouldn't be stored in files. This should be called in *both* read and write. """ nb.metadata.pop("orig_nbformat", None) nb.metadata.pop("orig_nbformat_minor", None) nb.metadata.pop("signature", None) for cell in nb.cells: cell.metadata.pop("trusted", None) return nb
Strip transient values that shouldn't be stored in files. This should be called in *both* read and write.
174,427
import json from .validator import ValidationError def reads(s, **kwargs): """Read a notebook from a json string and return the NotebookNode object. This function properly reads notebooks of any version. No version conversion is performed. Parameters ---------- s : unicode | bytes The raw string or bytes object to read the notebook from. Returns ------- nb : NotebookNode The notebook that was read. Raises ------ ValidationError Notebook JSON for a given version is missing an expected key and cannot be read. NBFormatError Specified major version is invalid or unsupported. """ from . import NBFormatError, versions nb_dict = parse_json(s, **kwargs) (major, minor) = get_version(nb_dict) if major in versions: try: return versions[major].to_notebook_json(nb_dict, minor=minor) except AttributeError as e: msg = f"The notebook is invalid and is missing an expected key: {e}" raise ValidationError(msg) from None else: raise NBFormatError("Unsupported nbformat version %s" % major) The provided code snippet includes necessary dependencies for implementing the `read` function. Write a Python function `def read(fp, **kwargs)` to solve the following problem: Read a notebook from a file and return the NotebookNode object. This function properly reads notebooks of any version. No version conversion is performed. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was read. Here is the function: def read(fp, **kwargs): """Read a notebook from a file and return the NotebookNode object. This function properly reads notebooks of any version. No version conversion is performed. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was read. """ return reads(fp.read(), **kwargs)
Read a notebook from a file and return the NotebookNode object. This function properly reads notebooks of any version. No version conversion is performed. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was read.
174,428
from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass The provided code snippet includes necessary dependencies for implementing the `from_dict` function. Write a Python function `def from_dict(d)` to solve the following problem: Create notebook node(s) from an object. Here is the function: def from_dict(d): """Create notebook node(s) from an object.""" if isinstance(d, dict): newd = NotebookNode() for k, v in d.items(): newd[k] = from_dict(v) return newd elif isinstance(d, (tuple, list)): return [from_dict(i) for i in d] else: return d
Create notebook node(s) from an object.
174,429
from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass The provided code snippet includes necessary dependencies for implementing the `new_code_cell` function. Write a Python function `def new_code_cell(code=None, prompt_number=None)` to solve the following problem: Create a new code cell with input and output Here is the function: def new_code_cell(code=None, prompt_number=None): """Create a new code cell with input and output""" cell = NotebookNode() cell.cell_type = "code" if code is not None: cell.code = str(code) if prompt_number is not None: cell.prompt_number = int(prompt_number) return cell
Create a new code cell with input and output
174,430
from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass The provided code snippet includes necessary dependencies for implementing the `new_text_cell` function. Write a Python function `def new_text_cell(text=None)` to solve the following problem: Create a new text cell. Here is the function: def new_text_cell(text=None): """Create a new text cell.""" cell = NotebookNode() if text is not None: cell.text = str(text) cell.cell_type = "text" return cell
Create a new text cell.
174,431
from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass The provided code snippet includes necessary dependencies for implementing the `new_notebook` function. Write a Python function `def new_notebook(cells=None)` to solve the following problem: Create a notebook by name, id and a list of worksheets. Here is the function: def new_notebook(cells=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() if cells is not None: nb.cells = cells else: nb.cells = [] return nb
Create a notebook by name, id and a list of worksheets.
174,432
The provided code snippet includes necessary dependencies for implementing the `upgrade` function. Write a Python function `def upgrade(nb, orig_version=None)` to solve the following problem: Upgrade a notebook. Here is the function: def upgrade(nb, orig_version=None): """Upgrade a notebook.""" msg = "Cannot convert to v1 notebook format" raise ValueError(msg)
Upgrade a notebook.
174,433
import hashlib import os import sys import typing as t from collections import OrderedDict from contextlib import contextmanager from datetime import datetime, timezone from hmac import HMAC from base64 import encodebytes from jupyter_core.application import JupyterApp, base_flags from traitlets import Any, Bool, Bytes, Callable, Enum, Instance, Integer, Unicode, default, observe from traitlets.config import LoggingConfigurable, MultipleInstanceError from . import NO_CONVERT, __version__, read, reads The provided code snippet includes necessary dependencies for implementing the `yield_everything` function. Write a Python function `def yield_everything(obj)` to solve the following problem: Yield every item in a container as bytes Allows any JSONable object to be passed to an HMAC digester without having to serialize the whole thing. Here is the function: def yield_everything(obj): """Yield every item in a container as bytes Allows any JSONable object to be passed to an HMAC digester without having to serialize the whole thing. """ if isinstance(obj, dict): for key in sorted(obj): value = obj[key] assert isinstance(key, str) # noqa yield key.encode() yield from yield_everything(value) elif isinstance(obj, (list, tuple)): for element in obj: yield from yield_everything(element) elif isinstance(obj, str): yield obj.encode("utf8") else: yield str(obj).encode("utf8")
Yield every item in a container as bytes Allows any JSONable object to be passed to an HMAC digester without having to serialize the whole thing.
174,434
import hashlib import os import sys import typing as t from collections import OrderedDict from contextlib import contextmanager from datetime import datetime, timezone from hmac import HMAC from base64 import encodebytes from jupyter_core.application import JupyterApp, base_flags from traitlets import Any, Bool, Bytes, Callable, Enum, Instance, Integer, Unicode, default, observe from traitlets.config import LoggingConfigurable, MultipleInstanceError from . import NO_CONVERT, __version__, read, reads The provided code snippet includes necessary dependencies for implementing the `yield_code_cells` function. Write a Python function `def yield_code_cells(nb)` to solve the following problem: Iterator that yields all cells in a notebook nbformat version independent Here is the function: def yield_code_cells(nb): """Iterator that yields all cells in a notebook nbformat version independent """ if nb.nbformat >= 4: # noqa for cell in nb["cells"]: if cell["cell_type"] == "code": yield cell elif nb.nbformat == 3: # noqa for ws in nb["worksheets"]: for cell in ws["cells"]: if cell["cell_type"] == "code": yield cell
Iterator that yields all cells in a notebook nbformat version independent
174,435
import hashlib import os import sys import typing as t from collections import OrderedDict from contextlib import contextmanager from datetime import datetime, timezone from hmac import HMAC from base64 import encodebytes from jupyter_core.application import JupyterApp, base_flags from traitlets import Any, Bool, Bytes, Callable, Enum, Instance, Integer, Unicode, default, observe from traitlets.config import LoggingConfigurable, MultipleInstanceError from . import NO_CONVERT, __version__, read, reads The provided code snippet includes necessary dependencies for implementing the `signature_removed` function. Write a Python function `def signature_removed(nb)` to solve the following problem: Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature. Here is the function: def signature_removed(nb): """Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature. """ save_signature = nb["metadata"].pop("signature", None) try: yield finally: if save_signature is not None: nb["metadata"]["signature"] = save_signature
Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature.
174,436
from collections.abc import Mapping, Hashable from itertools import chain from pyrsistent._pvector import pvector from pyrsistent._transformations import transform def pmap(initial={}, pre_size=0): """ Create new persistent map, inserts all elements in initial into the newly created map. The optional argument pre_size may be used to specify an initial size of the underlying bucket vector. This may have a positive performance impact in the cases where you know beforehand that a large number of elements will be inserted into the map eventually since it will reduce the number of reallocations required. >>> pmap({'a': 13, 'b': 14}) == {'a': 13, 'b': 14} True """ if not initial and pre_size == 0: return _EMPTY_PMAP return _turbo_mapping(initial, pre_size) The provided code snippet includes necessary dependencies for implementing the `m` function. Write a Python function `def m(**kwargs)` to solve the following problem: Creates a new persistent map. Inserts all key value arguments into the newly created map. >>> m(a=13, b=14) == {'a': 13, 'b': 14} True Here is the function: def m(**kwargs): """ Creates a new persistent map. Inserts all key value arguments into the newly created map. >>> m(a=13, b=14) == {'a': 13, 'b': 14} True """ return pmap(kwargs)
Creates a new persistent map. Inserts all key value arguments into the newly created map. >>> m(a=13, b=14) == {'a': 13, 'b': 14} True
174,437
import operator from functools import reduce def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... The provided code snippet includes necessary dependencies for implementing the `get_in` function. Write a Python function `def get_in(keys, coll, default=None, no_default=False)` to solve the following problem: NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless ``no_default`` is specified, then it raises KeyError or IndexError. ``get_in`` is a generalization of ``operator.getitem`` for nested data structures such as dictionaries and lists. >>> from pyrsistent import freeze >>> transaction = freeze({'name': 'Alice', ... 'purchase': {'items': ['Apple', 'Orange'], ... 'costs': [0.50, 1.25]}, ... 'credit card': '5555-1234-1234-1234'}) >>> get_in(['purchase', 'items', 0], transaction) 'Apple' >>> get_in(['name'], transaction) 'Alice' >>> get_in(['purchase', 'total'], transaction) >>> get_in(['purchase', 'items', 'apple'], transaction) >>> get_in(['purchase', 'items', 10], transaction) >>> get_in(['purchase', 'total'], transaction, 0) 0 >>> get_in(['y'], {}, no_default=True) Traceback (most recent call last): ... KeyError: 'y' Here is the function: def get_in(keys, coll, default=None, no_default=False): """ NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless ``no_default`` is specified, then it raises KeyError or IndexError. ``get_in`` is a generalization of ``operator.getitem`` for nested data structures such as dictionaries and lists. >>> from pyrsistent import freeze >>> transaction = freeze({'name': 'Alice', ... 'purchase': {'items': ['Apple', 'Orange'], ... 'costs': [0.50, 1.25]}, ... 'credit card': '5555-1234-1234-1234'}) >>> get_in(['purchase', 'items', 0], transaction) 'Apple' >>> get_in(['name'], transaction) 'Alice' >>> get_in(['purchase', 'total'], transaction) >>> get_in(['purchase', 'items', 'apple'], transaction) >>> get_in(['purchase', 'items', 10], transaction) >>> get_in(['purchase', 'total'], transaction, 0) 0 >>> get_in(['y'], {}, no_default=True) Traceback (most recent call last): ... KeyError: 'y' """ try: return reduce(operator.getitem, keys, coll) except (KeyError, IndexError, TypeError): if no_default: raise return default
NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless ``no_default`` is specified, then it raises KeyError or IndexError. ``get_in`` is a generalization of ``operator.getitem`` for nested data structures such as dictionaries and lists. >>> from pyrsistent import freeze >>> transaction = freeze({'name': 'Alice', ... 'purchase': {'items': ['Apple', 'Orange'], ... 'costs': [0.50, 1.25]}, ... 'credit card': '5555-1234-1234-1234'}) >>> get_in(['purchase', 'items', 0], transaction) 'Apple' >>> get_in(['name'], transaction) 'Alice' >>> get_in(['purchase', 'total'], transaction) >>> get_in(['purchase', 'items', 'apple'], transaction) >>> get_in(['purchase', 'items', 10], transaction) >>> get_in(['purchase', 'total'], transaction, 0) 0 >>> get_in(['y'], {}, no_default=True) Traceback (most recent call last): ... KeyError: 'y'
174,438
import sys def namedtuple( typename: Union[str, unicode], field_names: Union[str, unicode, Iterable[Union[str, unicode]]], verbose: bool = ..., rename: bool = ..., ) -> Type[Tuple[Any, ...]]: ... The provided code snippet includes necessary dependencies for implementing the `immutable` function. Write a Python function `def immutable(members='', name='Immutable', verbose=False)` to solve the following problem: Produces a class that either can be used standalone or as a base class for persistent classes. This is a thin wrapper around a named tuple. Constructing a type and using it to instantiate objects: >>> Point = immutable('x, y', name='Point') >>> p = Point(1, 2) >>> p2 = p.set(x=3) >>> p Point(x=1, y=2) >>> p2 Point(x=3, y=2) Inheriting from a constructed type. In this case no type name needs to be supplied: >>> class PositivePoint(immutable('x, y')): ... __slots__ = tuple() ... def __new__(cls, x, y): ... if x > 0 and y > 0: ... return super(PositivePoint, cls).__new__(cls, x, y) ... raise Exception('Coordinates must be positive!') ... >>> p = PositivePoint(1, 2) >>> p.set(x=3) PositivePoint(x=3, y=2) >>> p.set(y=-3) Traceback (most recent call last): Exception: Coordinates must be positive! The persistent class also supports the notion of frozen members. The value of a frozen member cannot be updated. For example it could be used to implement an ID that should remain the same over time. A frozen member is denoted by a trailing underscore. >>> Point = immutable('x, y, id_', name='Point') >>> p = Point(1, 2, id_=17) >>> p.set(x=3) Point(x=3, y=2, id_=17) >>> p.set(id_=18) Traceback (most recent call last): AttributeError: Cannot set frozen members id_ Here is the function: def immutable(members='', name='Immutable', verbose=False): """ Produces a class that either can be used standalone or as a base class for persistent classes. This is a thin wrapper around a named tuple. Constructing a type and using it to instantiate objects: >>> Point = immutable('x, y', name='Point') >>> p = Point(1, 2) >>> p2 = p.set(x=3) >>> p Point(x=1, y=2) >>> p2 Point(x=3, y=2) Inheriting from a constructed type. In this case no type name needs to be supplied: >>> class PositivePoint(immutable('x, y')): ... __slots__ = tuple() ... def __new__(cls, x, y): ... if x > 0 and y > 0: ... return super(PositivePoint, cls).__new__(cls, x, y) ... raise Exception('Coordinates must be positive!') ... >>> p = PositivePoint(1, 2) >>> p.set(x=3) PositivePoint(x=3, y=2) >>> p.set(y=-3) Traceback (most recent call last): Exception: Coordinates must be positive! The persistent class also supports the notion of frozen members. The value of a frozen member cannot be updated. For example it could be used to implement an ID that should remain the same over time. A frozen member is denoted by a trailing underscore. >>> Point = immutable('x, y, id_', name='Point') >>> p = Point(1, 2, id_=17) >>> p.set(x=3) Point(x=3, y=2, id_=17) >>> p.set(id_=18) Traceback (most recent call last): AttributeError: Cannot set frozen members id_ """ if isinstance(members, str): members = members.replace(',', ' ').split() def frozen_member_test(): frozen_members = ["'%s'" % f for f in members if f.endswith('_')] if frozen_members: return """ frozen_fields = fields_to_modify & set([{frozen_members}]) if frozen_fields: raise AttributeError('Cannot set frozen members %s' % ', '.join(frozen_fields)) """.format(frozen_members=', '.join(frozen_members)) return '' quoted_members = ', '.join("'%s'" % m for m in members) template = """ class {class_name}(namedtuple('ImmutableBase', [{quoted_members}])): __slots__ = tuple() def __repr__(self): return super({class_name}, self).__repr__().replace('ImmutableBase', self.__class__.__name__) def set(self, **kwargs): if not kwargs: return self fields_to_modify = set(kwargs.keys()) if not fields_to_modify <= {member_set}: raise AttributeError("'%s' is not a member" % ', '.join(fields_to_modify - {member_set})) {frozen_member_test} return self.__class__.__new__(self.__class__, *map(kwargs.pop, [{quoted_members}], self)) """.format(quoted_members=quoted_members, member_set="set([%s])" % quoted_members if quoted_members else 'set()', frozen_member_test=frozen_member_test(), class_name=name) if verbose: print(template) from collections import namedtuple namespace = dict(namedtuple=namedtuple, __name__='pyrsistent_immutable') try: exec(template, namespace) except SyntaxError as e: raise SyntaxError(str(e) + ':\n' + template) from e return namespace[name]
Produces a class that either can be used standalone or as a base class for persistent classes. This is a thin wrapper around a named tuple. Constructing a type and using it to instantiate objects: >>> Point = immutable('x, y', name='Point') >>> p = Point(1, 2) >>> p2 = p.set(x=3) >>> p Point(x=1, y=2) >>> p2 Point(x=3, y=2) Inheriting from a constructed type. In this case no type name needs to be supplied: >>> class PositivePoint(immutable('x, y')): ... __slots__ = tuple() ... def __new__(cls, x, y): ... if x > 0 and y > 0: ... return super(PositivePoint, cls).__new__(cls, x, y) ... raise Exception('Coordinates must be positive!') ... >>> p = PositivePoint(1, 2) >>> p.set(x=3) PositivePoint(x=3, y=2) >>> p.set(y=-3) Traceback (most recent call last): Exception: Coordinates must be positive! The persistent class also supports the notion of frozen members. The value of a frozen member cannot be updated. For example it could be used to implement an ID that should remain the same over time. A frozen member is denoted by a trailing underscore. >>> Point = immutable('x, y, id_', name='Point') >>> p = Point(1, 2, id_=17) >>> p.set(x=3) Point(x=3, y=2, id_=17) >>> p.set(id_=18) Traceback (most recent call last): AttributeError: Cannot set frozen members id_
174,439
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect class _PField(object): __slots__ = ('type', 'invariant', 'initial', 'mandatory', '_factory', 'serializer') def __init__(self, type, invariant, initial, mandatory, factory, serializer): self.type = type self.invariant = invariant self.initial = initial self.mandatory = mandatory self._factory = factory self.serializer = serializer def factory(self): # If no factory is specified and the type is another CheckedType use the factory method of that CheckedType if self._factory is PFIELD_NO_FACTORY and len(self.type) == 1: typ = get_type(tuple(self.type)[0]) if issubclass(typ, CheckedType): return typ.create return self._factory def set_fields(dct, bases, name): dct[name] = dict(sum([list(b.__dict__.get(name, {}).items()) for b in bases], [])) for k, v in list(dct.items()): if isinstance(v, _PField): dct[name][k] = v del dct[k]
null
174,440
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect class InvariantException(Exception): """ Exception raised from a :py:class:`CheckedType` when invariant tests fail or when a mandatory field is missing. Contains two fields of interest: invariant_errors, a tuple of error data for the failing invariants missing_fields, a tuple of strings specifying the missing names """ def __init__(self, error_codes=(), missing_fields=(), *args, **kwargs): self.invariant_errors = tuple(e() if callable(e) else e for e in error_codes) self.missing_fields = missing_fields super(InvariantException, self).__init__(*args, **kwargs) def __str__(self): return super(InvariantException, self).__str__() + \ ", invariant_errors=[{invariant_errors}], missing_fields=[{missing_fields}]".format( invariant_errors=', '.join(str(e) for e in self.invariant_errors), missing_fields=', '.join(self.missing_fields)) def check_global_invariants(subject, invariants): error_codes = tuple(error_code for is_ok, error_code in (invariant(subject) for invariant in invariants) if not is_ok) if error_codes: raise InvariantException(error_codes, (), 'Global invariant failed')
null
174,441
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect PFIELD_NO_SERIALIZER = lambda _, value: value class CheckedType(object): def create(cls, source_data, _factory_fields=None): def serialize(self, format=None): def serialize(serializer, format, value): if isinstance(value, CheckedType) and serializer is PFIELD_NO_SERIALIZER: return value.serialize(format) return serializer(format, value)
null
174,442
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect def is_type_cls(type_cls, field_type): if type(field_type) is set: return True types = tuple(field_type) if len(types) == 0: return False return issubclass(get_type(types[0]), type_cls) def is_field_ignore_extra_complaint(type_cls, field, ignore_extra): # ignore_extra param has default False value, for speed purpose no need to propagate False if not ignore_extra: return False if not is_type_cls(type_cls, field.type): return False return 'ignore_extra' in inspect.signature(field.factory).parameters
null
174,443
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect PFIELD_NO_INVARIANT = lambda _: (True, None) def _sequence_field(checked_class, item_type, optional, initial, invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT): """ Create checked field for either ``PSet`` or ``PVector``. :param checked_class: ``CheckedPSet`` or ``CheckedPVector``. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory. :return: A ``field`` containing a checked class. """ TheType = _make_seq_field_type(checked_class, item_type, item_invariant) if optional: def factory(argument, _factory_fields=None, ignore_extra=False): if argument is None: return None else: return TheType.create(argument, _factory_fields=_factory_fields, ignore_extra=ignore_extra) else: factory = TheType.create return field(type=optional_type(TheType) if optional else TheType, factory=factory, mandatory=True, invariant=invariant, initial=factory(initial)) class CheckedPSet(PSet, CheckedType, metaclass=_CheckedTypeMeta): """ A CheckedPSet is a PSet which allows specifying type and invariant checks. >>> class Positives(CheckedPSet): ... __type__ = (int, float) ... __invariant__ = lambda n: (n >= 0, 'Negative') ... >>> Positives([1, 2, 3]) Positives([1, 2, 3]) """ __slots__ = () def __new__(cls, initial=()): if type(initial) is PMap: return super(CheckedPSet, cls).__new__(cls, initial) evolver = CheckedPSet.Evolver(cls, pset()) for e in initial: evolver.add(e) return evolver.persistent() def __repr__(self): return self.__class__.__name__ + super(CheckedPSet, self).__repr__()[4:] def __str__(self): return self.__repr__() def serialize(self, format=None): serializer = self.__serializer__ return set(serializer(format, v) for v in self) create = classmethod(_checked_type_create) def __reduce__(self): # Pickling support return _restore_pickle, (self.__class__, list(self),) def evolver(self): return CheckedPSet.Evolver(self.__class__, self) class Evolver(PSet._Evolver): __slots__ = ('_destination_class', '_invariant_errors') def __init__(self, destination_class, original_set): super(CheckedPSet.Evolver, self).__init__(original_set) self._destination_class = destination_class self._invariant_errors = [] def _check(self, it): _check_types(it, self._destination_class._checked_types, self._destination_class) error_data = _invariant_errors_iterable(it, self._destination_class._checked_invariants) self._invariant_errors.extend(error_data) def add(self, element): self._check([element]) self._pmap_evolver[element] = True return self def persistent(self): if self._invariant_errors: raise InvariantException(error_codes=self._invariant_errors) if self.is_dirty() or self._destination_class != type(self._original_pset): return self._destination_class(self._pmap_evolver.persistent()) return self._original_pset The provided code snippet includes necessary dependencies for implementing the `pset_field` function. Write a Python function `def pset_field(item_type, optional=False, initial=(), invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT)` to solve the following problem: Create checked ``PSet`` field. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPSet`` of the given type. Here is the function: def pset_field(item_type, optional=False, initial=(), invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT): """ Create checked ``PSet`` field. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPSet`` of the given type. """ return _sequence_field(CheckedPSet, item_type, optional, initial, invariant=invariant, item_invariant=item_invariant)
Create checked ``PSet`` field. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPSet`` of the given type.
174,444
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect PFIELD_NO_INVARIANT = lambda _: (True, None) def _sequence_field(checked_class, item_type, optional, initial, invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT): """ Create checked field for either ``PSet`` or ``PVector``. :param checked_class: ``CheckedPSet`` or ``CheckedPVector``. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory. :return: A ``field`` containing a checked class. """ TheType = _make_seq_field_type(checked_class, item_type, item_invariant) if optional: def factory(argument, _factory_fields=None, ignore_extra=False): if argument is None: return None else: return TheType.create(argument, _factory_fields=_factory_fields, ignore_extra=ignore_extra) else: factory = TheType.create return field(type=optional_type(TheType) if optional else TheType, factory=factory, mandatory=True, invariant=invariant, initial=factory(initial)) class CheckedPVector(PythonPVector, CheckedType, metaclass=_CheckedTypeMeta): """ A CheckedPVector is a PVector which allows specifying type and invariant checks. >>> class Positives(CheckedPVector): ... __type__ = (int, float) ... __invariant__ = lambda n: (n >= 0, 'Negative') ... >>> Positives([1, 2, 3]) Positives([1, 2, 3]) """ __slots__ = () def __new__(cls, initial=()): if type(initial) == PythonPVector: return super(CheckedPVector, cls).__new__(cls, initial._count, initial._shift, initial._root, initial._tail) return CheckedPVector.Evolver(cls, python_pvector()).extend(initial).persistent() def set(self, key, value): return self.evolver().set(key, value).persistent() def append(self, val): return self.evolver().append(val).persistent() def extend(self, it): return self.evolver().extend(it).persistent() create = classmethod(_checked_type_create) def serialize(self, format=None): serializer = self.__serializer__ return list(serializer(format, v) for v in self) def __reduce__(self): # Pickling support return _restore_pickle, (self.__class__, list(self),) class Evolver(PythonPVector.Evolver): __slots__ = ('_destination_class', '_invariant_errors') def __init__(self, destination_class, vector): super(CheckedPVector.Evolver, self).__init__(vector) self._destination_class = destination_class self._invariant_errors = [] def _check(self, it): _check_types(it, self._destination_class._checked_types, self._destination_class) error_data = _invariant_errors_iterable(it, self._destination_class._checked_invariants) self._invariant_errors.extend(error_data) def __setitem__(self, key, value): self._check([value]) return super(CheckedPVector.Evolver, self).__setitem__(key, value) def append(self, elem): self._check([elem]) return super(CheckedPVector.Evolver, self).append(elem) def extend(self, it): it = list(it) self._check(it) return super(CheckedPVector.Evolver, self).extend(it) def persistent(self): if self._invariant_errors: raise InvariantException(error_codes=self._invariant_errors) result = self._orig_pvector if self.is_dirty() or (self._destination_class != type(self._orig_pvector)): pv = super(CheckedPVector.Evolver, self).persistent().extend(self._extra_tail) result = self._destination_class(pv) self._reset(result) return result def __repr__(self): return self.__class__.__name__ + "({0})".format(self.tolist()) __str__ = __repr__ def evolver(self): return CheckedPVector.Evolver(self.__class__, self) The provided code snippet includes necessary dependencies for implementing the `pvector_field` function. Write a Python function `def pvector_field(item_type, optional=False, initial=(), invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT)` to solve the following problem: Create checked ``PVector`` field. :param item_type: The required type for the items in the vector. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPVector`` of the given type. Here is the function: def pvector_field(item_type, optional=False, initial=(), invariant=PFIELD_NO_INVARIANT, item_invariant=PFIELD_NO_INVARIANT): """ Create checked ``PVector`` field. :param item_type: The required type for the items in the vector. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPVector`` of the given type. """ return _sequence_field(CheckedPVector, item_type, optional, initial, invariant=invariant, item_invariant=item_invariant)
Create checked ``PVector`` field. :param item_type: The required type for the items in the vector. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPVector`` of the given type.
174,445
from pyrsistent._checked_types import ( CheckedPMap, CheckedPSet, CheckedPVector, CheckedType, InvariantException, _restore_pickle, get_type, maybe_parse_user_type, maybe_parse_many_user_types, ) from pyrsistent._checked_types import optional as optional_type from pyrsistent._checked_types import wrap_invariant import inspect PFIELD_NO_INVARIANT = lambda _: (True, None) def field(type=PFIELD_NO_TYPE, invariant=PFIELD_NO_INVARIANT, initial=PFIELD_NO_INITIAL, mandatory=False, factory=PFIELD_NO_FACTORY, serializer=PFIELD_NO_SERIALIZER): """ Field specification factory for :py:class:`PRecord`. :param type: a type or iterable with types that are allowed for this field :param invariant: a function specifying an invariant that must hold for the field :param initial: value of field if not specified when instantiating the record :param mandatory: boolean specifying if the field is mandatory or not :param factory: function called when field is set. :param serializer: function that returns a serialized version of the field """ # NB: We have to check this predicate separately from the predicates in # `maybe_parse_user_type` et al. because this one is related to supporting # the argspec for `field`, while those are related to supporting the valid # ways to specify types. # Multiple types must be passed in one of the following containers. Note # that a type that is a subclass of one of these containers, like a # `collections.namedtuple`, will work as expected, since we check # `isinstance` and not `issubclass`. if isinstance(type, (list, set, tuple)): types = set(maybe_parse_many_user_types(type)) else: types = set(maybe_parse_user_type(type)) invariant_function = wrap_invariant(invariant) if invariant != PFIELD_NO_INVARIANT and callable(invariant) else invariant field = _PField(type=types, invariant=invariant_function, initial=initial, mandatory=mandatory, factory=factory, serializer=serializer) _check_field_parameters(field) return field def _make_pmap_field_type(key_type, value_type): """Create a subclass of CheckedPMap with the given key and value types.""" type_ = _pmap_field_types.get((key_type, value_type)) if type_ is not None: return type_ class TheMap(CheckedPMap): __key_type__ = key_type __value_type__ = value_type def __reduce__(self): return (_restore_pmap_field_pickle, (self.__key_type__, self.__value_type__, dict(self))) TheMap.__name__ = "{0}To{1}PMap".format( _types_to_names(TheMap._checked_key_types), _types_to_names(TheMap._checked_value_types)) _pmap_field_types[key_type, value_type] = TheMap return TheMap The provided code snippet includes necessary dependencies for implementing the `pmap_field` function. Write a Python function `def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT)` to solve the following problem: Create a checked ``PMap`` field. :param key: The required type for the keys of the map. :param value: The required type for the values of the map. :param optional: If true, ``None`` can be used as a value for this field. :param invariant: Pass-through to ``field``. :return: A ``field`` containing a ``CheckedPMap``. Here is the function: def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT): """ Create a checked ``PMap`` field. :param key: The required type for the keys of the map. :param value: The required type for the values of the map. :param optional: If true, ``None`` can be used as a value for this field. :param invariant: Pass-through to ``field``. :return: A ``field`` containing a ``CheckedPMap``. """ TheMap = _make_pmap_field_type(key_type, value_type) if optional: def factory(argument): if argument is None: return None else: return TheMap.create(argument) else: factory = TheMap.create return field(mandatory=True, initial=TheMap(), type=optional_type(TheMap) if optional else TheMap, factory=factory, invariant=invariant)
Create a checked ``PMap`` field. :param key: The required type for the keys of the map. :param value: The required type for the values of the map. :param optional: If true, ``None`` can be used as a value for this field. :param invariant: Pass-through to ``field``. :return: A ``field`` containing a ``CheckedPMap``.
174,446
from functools import wraps from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PVector, pvector class PMap(object): """ Persistent map/dict. Tries to follow the same naming conventions as the built in dict where feasible. Do not instantiate directly, instead use the factory functions :py:func:`m` or :py:func:`pmap` to create an instance. Was originally written as a very close copy of the Clojure equivalent but was later rewritten to closer re-assemble the python dict. This means that a sparse vector (a PVector) of buckets is used. The keys are hashed and the elements inserted at position hash % len(bucket_vector). Whenever the map size exceeds 2/3 of the containing vectors size the map is reallocated to a vector of double the size. This is done to avoid excessive hash collisions. This structure corresponds most closely to the built in dict type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments and deletion of values. PMap implements the Mapping protocol and is Hashable. It also supports dot-notation for element access. Random access and insert is log32(n) where n is the size of the map. The following are examples of some common operations on persistent maps >>> m1 = m(a=1, b=3) >>> m2 = m1.set('c', 3) >>> m3 = m2.remove('a') >>> m1 == {'a': 1, 'b': 3} True >>> m2 == {'a': 1, 'b': 3, 'c': 3} True >>> m3 == {'b': 3, 'c': 3} True >>> m3['c'] 3 >>> m3.c 3 """ __slots__ = ('_size', '_buckets', '__weakref__', '_cached_hash') def __new__(cls, size, buckets): self = super(PMap, cls).__new__(cls) self._size = size self._buckets = buckets return self def _get_bucket(buckets, key): index = hash(key) % len(buckets) bucket = buckets[index] return index, bucket def _getitem(buckets, key): _, bucket = PMap._get_bucket(buckets, key) if bucket: for k, v in bucket: if k == key: return v raise KeyError(key) def __getitem__(self, key): return PMap._getitem(self._buckets, key) def _contains(buckets, key): _, bucket = PMap._get_bucket(buckets, key) if bucket: for k, _ in bucket: if k == key: return True return False return False def __contains__(self, key): return self._contains(self._buckets, key) get = Mapping.get def __iter__(self): return self.iterkeys() # If this method is not defined, then reversed(pmap) will attempt to reverse # the map using len() and getitem, usually resulting in a mysterious # KeyError. def __reversed__(self): raise TypeError("Persistent maps are not reversible") def __getattr__(self, key): try: return self[key] except KeyError as e: raise AttributeError( "{0} has no attribute '{1}'".format(type(self).__name__, key) ) from e def iterkeys(self): for k, _ in self.iteritems(): yield k # These are more efficient implementations compared to the original # methods that are based on the keys iterator and then calls the # accessor functions to access the value for the corresponding key def itervalues(self): for _, v in self.iteritems(): yield v def iteritems(self): for bucket in self._buckets: if bucket: for k, v in bucket: yield k, v def values(self): return PMapValues(self) def keys(self): from ._pset import PSet return PSet(self) def items(self): return PMapItems(self) def __len__(self): return self._size def __repr__(self): return 'pmap({0})'.format(str(dict(self))) def __eq__(self, other): if self is other: return True if not isinstance(other, Mapping): return NotImplemented if len(self) != len(other): return False if isinstance(other, PMap): if (hasattr(self, '_cached_hash') and hasattr(other, '_cached_hash') and self._cached_hash != other._cached_hash): return False if self._buckets == other._buckets: return True return dict(self.iteritems()) == dict(other.iteritems()) elif isinstance(other, dict): return dict(self.iteritems()) == other return dict(self.iteritems()) == dict(other.items()) __ne__ = Mapping.__ne__ def __lt__(self, other): raise TypeError('PMaps are not orderable') __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ def __str__(self): return self.__repr__() def __hash__(self): if not hasattr(self, '_cached_hash'): self._cached_hash = hash(frozenset(self.iteritems())) return self._cached_hash def set(self, key, val): """ Return a new PMap with key and val inserted. >>> m1 = m(a=1, b=2) >>> m2 = m1.set('a', 3) >>> m3 = m1.set('c' ,4) >>> m1 == {'a': 1, 'b': 2} True >>> m2 == {'a': 3, 'b': 2} True >>> m3 == {'a': 1, 'b': 2, 'c': 4} True """ return self.evolver().set(key, val).persistent() def remove(self, key): """ Return a new PMap without the element specified by key. Raises KeyError if the element is not present. >>> m1 = m(a=1, b=2) >>> m1.remove('a') pmap({'b': 2}) """ return self.evolver().remove(key).persistent() def discard(self, key): """ Return a new PMap without the element specified by key. Returns reference to itself if element is not present. >>> m1 = m(a=1, b=2) >>> m1.discard('a') pmap({'b': 2}) >>> m1 is m1.discard('c') True """ try: return self.remove(key) except KeyError: return self def update(self, *maps): """ Return a new PMap with the items in Mappings inserted. If the same key is present in multiple maps the rightmost (last) value is inserted. >>> m1 = m(a=1, b=2) >>> m1.update(m(a=2, c=3), {'a': 17, 'd': 35}) == {'a': 17, 'b': 2, 'c': 3, 'd': 35} True """ return self.update_with(lambda l, r: r, *maps) def update_with(self, update_fn, *maps): """ Return a new PMap with the items in Mappings maps inserted. If the same key is present in multiple maps the values will be merged using merge_fn going from left to right. >>> from operator import add >>> m1 = m(a=1, b=2) >>> m1.update_with(add, m(a=2)) == {'a': 3, 'b': 2} True The reverse behaviour of the regular merge. Keep the leftmost element instead of the rightmost. >>> m1 = m(a=1) >>> m1.update_with(lambda l, r: l, m(a=2), {'a':3}) pmap({'a': 1}) """ evolver = self.evolver() for map in maps: for key, value in map.items(): evolver.set(key, update_fn(evolver[key], value) if key in evolver else value) return evolver.persistent() def __add__(self, other): return self.update(other) __or__ = __add__ def __reduce__(self): # Pickling support return pmap, (dict(self),) def transform(self, *transformations): """ Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True """ return transform(self, transformations) def copy(self): return self class _Evolver(object): __slots__ = ('_buckets_evolver', '_size', '_original_pmap') def __init__(self, original_pmap): self._original_pmap = original_pmap self._buckets_evolver = original_pmap._buckets.evolver() self._size = original_pmap._size def __getitem__(self, key): return PMap._getitem(self._buckets_evolver, key) def __setitem__(self, key, val): self.set(key, val) def set(self, key, val): kv = (key, val) index, bucket = PMap._get_bucket(self._buckets_evolver, key) reallocation_required = len(self._buckets_evolver) < 0.67 * self._size if bucket: for k, v in bucket: if k == key: if v is not val: new_bucket = [(k2, v2) if k2 != k else (k2, val) for k2, v2 in bucket] self._buckets_evolver[index] = new_bucket return self # Only check and perform reallocation if not replacing an existing value. # This is a performance tweak, see #247. if reallocation_required: self._reallocate() return self.set(key, val) new_bucket = [kv] new_bucket.extend(bucket) self._buckets_evolver[index] = new_bucket self._size += 1 else: if reallocation_required: self._reallocate() return self.set(key, val) self._buckets_evolver[index] = [kv] self._size += 1 return self def _reallocate(self): new_size = 2 * len(self._buckets_evolver) new_list = new_size * [None] buckets = self._buckets_evolver.persistent() for k, v in chain.from_iterable(x for x in buckets if x): index = hash(k) % new_size if new_list[index]: new_list[index].append((k, v)) else: new_list[index] = [(k, v)] # A reallocation should always result in a dirty buckets evolver to avoid # possible loss of elements when doing the reallocation. self._buckets_evolver = pvector().evolver() self._buckets_evolver.extend(new_list) def is_dirty(self): return self._buckets_evolver.is_dirty() def persistent(self): if self.is_dirty(): self._original_pmap = PMap(self._size, self._buckets_evolver.persistent()) return self._original_pmap def __len__(self): return self._size def __contains__(self, key): return PMap._contains(self._buckets_evolver, key) def __delitem__(self, key): self.remove(key) def remove(self, key): index, bucket = PMap._get_bucket(self._buckets_evolver, key) if bucket: new_bucket = [(k, v) for (k, v) in bucket if k != key] if len(bucket) > len(new_bucket): self._buckets_evolver[index] = new_bucket if new_bucket else None self._size -= 1 return self raise KeyError('{0}'.format(key)) def evolver(self): """ Create a new evolver for this pmap. For a discussion on evolvers in general see the documentation for the pvector evolver. Create the evolver and perform various mutating updates to it: >>> m1 = m(a=1, b=2) >>> e = m1.evolver() >>> e['c'] = 3 >>> len(e) 3 >>> del e['a'] The underlying pmap remains the same: >>> m1 == {'a': 1, 'b': 2} True The changes are kept in the evolver. An updated pmap can be created using the persistent() function on the evolver. >>> m2 = e.persistent() >>> m2 == {'b': 2, 'c': 3} True The new pmap will share data with the original pmap in the same way that would have been done if only using operations on the pmap. """ return self._Evolver(self) class PSet(object): """ Persistent set implementation. Built on top of the persistent map. The set supports all operations in the Set protocol and is Hashable. Do not instantiate directly, instead use the factory functions :py:func:`s` or :py:func:`pset` to create an instance. Random access and insert is log32(n) where n is the size of the set. Some examples: >>> s = pset([1, 2, 3, 1]) >>> s2 = s.add(4) >>> s3 = s2.remove(2) >>> s pset([1, 2, 3]) >>> s2 pset([1, 2, 3, 4]) >>> s3 pset([1, 3, 4]) """ __slots__ = ('_map', '__weakref__') def __new__(cls, m): self = super(PSet, cls).__new__(cls) self._map = m return self def __contains__(self, element): return element in self._map def __iter__(self): return iter(self._map) def __len__(self): return len(self._map) def __repr__(self): if not self: return 'p' + str(set(self)) return 'pset([{0}])'.format(str(set(self))[1:-1]) def __str__(self): return self.__repr__() def __hash__(self): return hash(self._map) def __reduce__(self): # Pickling support return pset, (list(self),) def _from_iterable(cls, it, pre_size=8): return PSet(pmap(dict((k, True) for k in it), pre_size=pre_size)) def add(self, element): """ Return a new PSet with element added >>> s1 = s(1, 2) >>> s1.add(3) pset([1, 2, 3]) """ return self.evolver().add(element).persistent() def update(self, iterable): """ Return a new PSet with elements in iterable added >>> s1 = s(1, 2) >>> s1.update([3, 4, 4]) pset([1, 2, 3, 4]) """ e = self.evolver() for element in iterable: e.add(element) return e.persistent() def remove(self, element): """ Return a new PSet with element removed. Raises KeyError if element is not present. >>> s1 = s(1, 2) >>> s1.remove(2) pset([1]) """ if element in self._map: return self.evolver().remove(element).persistent() raise KeyError("Element '%s' not present in PSet" % repr(element)) def discard(self, element): """ Return a new PSet with element removed. Returns itself if element is not present. """ if element in self._map: return self.evolver().remove(element).persistent() return self class _Evolver(object): __slots__ = ('_original_pset', '_pmap_evolver') def __init__(self, original_pset): self._original_pset = original_pset self._pmap_evolver = original_pset._map.evolver() def add(self, element): self._pmap_evolver[element] = True return self def remove(self, element): del self._pmap_evolver[element] return self def is_dirty(self): return self._pmap_evolver.is_dirty() def persistent(self): if not self.is_dirty(): return self._original_pset return PSet(self._pmap_evolver.persistent()) def __len__(self): return len(self._pmap_evolver) def copy(self): return self def evolver(self): """ Create a new evolver for this pset. For a discussion on evolvers in general see the documentation for the pvector evolver. Create the evolver and perform various mutating updates to it: >>> s1 = s(1, 2, 3) >>> e = s1.evolver() >>> _ = e.add(4) >>> len(e) 4 >>> _ = e.remove(1) The underlying pset remains the same: >>> s1 pset([1, 2, 3]) The changes are kept in the evolver. An updated pmap can be created using the persistent() function on the evolver. >>> s2 = e.persistent() >>> s2 pset([2, 3, 4]) The new pset will share data with the original pset in the same way that would have been done if only using operations on the pset. """ return PSet._Evolver(self) # All the operations and comparisons you would expect on a set. # # This is not very beautiful. If we avoid inheriting from PSet we can use the # __slots__ concepts (which requires a new style class) and hopefully save some memory. __le__ = Set.__le__ __lt__ = Set.__lt__ __gt__ = Set.__gt__ __ge__ = Set.__ge__ __eq__ = Set.__eq__ __ne__ = Set.__ne__ __and__ = Set.__and__ __or__ = Set.__or__ __sub__ = Set.__sub__ __xor__ = Set.__xor__ issubset = __le__ issuperset = __ge__ union = __or__ intersection = __and__ difference = __sub__ symmetric_difference = __xor__ isdisjoint = Set.isdisjoint class PVector(metaclass=ABCMeta): """ Persistent vector implementation. Meant as a replacement for the cases where you would normally use a Python list. Do not instantiate directly, instead use the factory functions :py:func:`v` and :py:func:`pvector` to create an instance. Heavily influenced by the persistent vector available in Clojure. Initially this was more or less just a port of the Java code for the Clojure vector. It has since been modified and to some extent optimized for usage in Python. The vector is organized as a trie, any mutating method will return a new vector that contains the changes. No updates are done to the original vector. Structural sharing between vectors are applied where possible to save space and to avoid making complete copies. This structure corresponds most closely to the built in list type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments. The PVector implements the Sequence protocol and is Hashable. Inserts are amortized O(1). Random access is log32(n) where n is the size of the vector. The following are examples of some common operations on persistent vectors: >>> p = v(1, 2, 3) >>> p2 = p.append(4) >>> p3 = p2.extend([5, 6, 7]) >>> p pvector([1, 2, 3]) >>> p2 pvector([1, 2, 3, 4]) >>> p3 pvector([1, 2, 3, 4, 5, 6, 7]) >>> p3[5] 6 >>> p.set(1, 99) pvector([1, 99, 3]) >>> """ def __len__(self): """ >>> len(v(1, 2, 3)) 3 """ def __getitem__(self, index): """ Get value at index. Full slicing support. >>> v1 = v(5, 6, 7, 8) >>> v1[2] 7 >>> v1[1:3] pvector([6, 7]) """ def __add__(self, other): """ >>> v1 = v(1, 2) >>> v2 = v(3, 4) >>> v1 + v2 pvector([1, 2, 3, 4]) """ def __mul__(self, times): """ >>> v1 = v(1, 2) >>> 3 * v1 pvector([1, 2, 1, 2, 1, 2]) """ def __hash__(self): """ >>> v1 = v(1, 2, 3) >>> v2 = v(1, 2, 3) >>> hash(v1) == hash(v2) True """ def evolver(self): """ Create a new evolver for this pvector. The evolver acts as a mutable view of the vector with "transaction like" semantics. No part of the underlying vector i updated, it is still fully immutable. Furthermore multiple evolvers created from the same pvector do not interfere with each other. You may want to use an evolver instead of working directly with the pvector in the following cases: * Multiple updates are done to the same vector and the intermediate results are of no interest. In this case using an evolver may be a more efficient and easier to work with. * You need to pass a vector into a legacy function or a function that you have no control over which performs in place mutations of lists. In this case pass an evolver instance instead and then create a new pvector from the evolver once the function returns. The following example illustrates a typical workflow when working with evolvers. It also displays most of the API (which i kept small by design, you should not be tempted to use evolvers in excess ;-)). Create the evolver and perform various mutating updates to it: >>> v1 = v(1, 2, 3, 4, 5) >>> e = v1.evolver() >>> e[1] = 22 >>> _ = e.append(6) >>> _ = e.extend([7, 8, 9]) >>> e[8] += 1 >>> len(e) 9 The underlying pvector remains the same: >>> v1 pvector([1, 2, 3, 4, 5]) The changes are kept in the evolver. An updated pvector can be created using the persistent() function on the evolver. >>> v2 = e.persistent() >>> v2 pvector([1, 22, 3, 4, 5, 6, 7, 8, 10]) The new pvector will share data with the original pvector in the same way that would have been done if only using operations on the pvector. """ def mset(self, *args): """ Return a new vector with elements in specified positions replaced by values (multi set). Elements on even positions in the argument list are interpreted as indexes while elements on odd positions are considered values. >>> v1 = v(1, 2, 3) >>> v1.mset(0, 11, 2, 33) pvector([11, 2, 33]) """ def set(self, i, val): """ Return a new vector with element at position i replaced with val. The original vector remains unchanged. Setting a value one step beyond the end of the vector is equal to appending. Setting beyond that will result in an IndexError. >>> v1 = v(1, 2, 3) >>> v1.set(1, 4) pvector([1, 4, 3]) >>> v1.set(3, 4) pvector([1, 2, 3, 4]) >>> v1.set(-1, 4) pvector([1, 2, 4]) """ def append(self, val): """ Return a new vector with val appended. >>> v1 = v(1, 2) >>> v1.append(3) pvector([1, 2, 3]) """ def extend(self, obj): """ Return a new vector with all values in obj appended to it. Obj may be another PVector or any other Iterable. >>> v1 = v(1, 2, 3) >>> v1.extend([4, 5]) pvector([1, 2, 3, 4, 5]) """ def index(self, value, *args, **kwargs): """ Return first index of value. Additional indexes may be supplied to limit the search to a sub range of the vector. >>> v1 = v(1, 2, 3, 4, 3) >>> v1.index(3) 2 >>> v1.index(3, 3, 5) 4 """ def count(self, value): """ Return the number of times that value appears in the vector. >>> v1 = v(1, 4, 3, 4) >>> v1.count(4) 2 """ def transform(self, *transformations): """ Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True """ def delete(self, index, stop=None): """ Delete a portion of the vector by index or range. >>> v1 = v(1, 2, 3, 4, 5) >>> v1.delete(1) pvector([1, 3, 4, 5]) >>> v1.delete(1, 3) pvector([1, 4, 5]) """ def remove(self, value): """ Remove the first occurrence of a value from the vector. >>> v1 = v(1, 2, 3, 2, 1) >>> v2 = v1.remove(1) >>> v2 pvector([2, 3, 2, 1]) >>> v2.remove(1) pvector([2, 3, 2]) """ PVector.register(PythonPVector) The provided code snippet includes necessary dependencies for implementing the `thaw` function. Write a Python function `def thaw(o, strict=True)` to solve the following problem: Recursively convert pyrsistent containers into simple Python containers. - pvector is converted to list, recursively - pmap is converted to dict, recursively on values (but not keys) - pset is converted to set, but not recursively - tuple is converted to tuple, recursively. If strict == True (the default): - thaw is called on elements of lists - thaw is called on values in dicts >>> from pyrsistent import s, m, v >>> thaw(s(1, 2)) {1, 2} >>> thaw(v(1, m(a=3))) [1, {'a': 3}] >>> thaw((1, v())) (1, []) Here is the function: def thaw(o, strict=True): """ Recursively convert pyrsistent containers into simple Python containers. - pvector is converted to list, recursively - pmap is converted to dict, recursively on values (but not keys) - pset is converted to set, but not recursively - tuple is converted to tuple, recursively. If strict == True (the default): - thaw is called on elements of lists - thaw is called on values in dicts >>> from pyrsistent import s, m, v >>> thaw(s(1, 2)) {1, 2} >>> thaw(v(1, m(a=3))) [1, {'a': 3}] >>> thaw((1, v())) (1, []) """ typ = type(o) if isinstance(o, PVector) or (strict and typ is list): curried_thaw = lambda x: thaw(x, strict) return list(map(curried_thaw, o)) if isinstance(o, PMap) or (strict and typ is dict): return {k: thaw(v, strict) for k, v in o.items()} if typ is tuple: curried_thaw = lambda x: thaw(x, strict) return tuple(map(curried_thaw, o)) if isinstance(o, PSet): # impossible to thaw inside psets or sets return set(o) return o
Recursively convert pyrsistent containers into simple Python containers. - pvector is converted to list, recursively - pmap is converted to dict, recursively on values (but not keys) - pset is converted to set, but not recursively - tuple is converted to tuple, recursively. If strict == True (the default): - thaw is called on elements of lists - thaw is called on values in dicts >>> from pyrsistent import s, m, v >>> thaw(s(1, 2)) {1, 2} >>> thaw(v(1, m(a=3))) [1, {'a': 3}] >>> thaw((1, v())) (1, [])
174,447
from functools import wraps from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PVector, pvector def freeze(o, strict=True): """ Recursively convert simple Python containers into pyrsistent versions of those containers. - list is converted to pvector, recursively - dict is converted to pmap, recursively on values (but not keys) - set is converted to pset, but not recursively - tuple is converted to tuple, recursively. If strict == True (default): - freeze is called on elements of pvectors - freeze is called on values of pmaps Sets and dict keys are not recursively frozen because they do not contain mutable data by convention. The main exception to this rule is that dict keys and set elements are often instances of mutable objects that support hash-by-id, which this function can't convert anyway. >>> freeze(set([1, 2])) pset([1, 2]) >>> freeze([1, {'a': 3}]) pvector([1, pmap({'a': 3})]) >>> freeze((1, [])) (1, pvector([])) """ typ = type(o) if typ is dict or (strict and isinstance(o, PMap)): return pmap({k: freeze(v, strict) for k, v in o.items()}) if typ is list or (strict and isinstance(o, PVector)): curried_freeze = lambda x: freeze(x, strict) return pvector(map(curried_freeze, o)) if typ is tuple: curried_freeze = lambda x: freeze(x, strict) return tuple(map(curried_freeze, o)) if typ is set: # impossible to have anything that needs freezing inside a set or pset return pset(o) return o def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... The provided code snippet includes necessary dependencies for implementing the `mutant` function. Write a Python function `def mutant(fn)` to solve the following problem: Convenience decorator to isolate mutation to within the decorated function (with respect to the input arguments). All arguments to the decorated function will be frozen so that they are guaranteed not to change. The return value is also frozen. Here is the function: def mutant(fn): """ Convenience decorator to isolate mutation to within the decorated function (with respect to the input arguments). All arguments to the decorated function will be frozen so that they are guaranteed not to change. The return value is also frozen. """ @wraps(fn) def inner_f(*args, **kwargs): return freeze(fn(*[freeze(e) for e in args], **dict(freeze(item) for item in kwargs.items()))) return inner_f
Convenience decorator to isolate mutation to within the decorated function (with respect to the input arguments). All arguments to the decorated function will be frozen so that they are guaranteed not to change. The return value is also frozen.
174,448
from collections.abc import Sequence, Hashable from itertools import islice, chain from numbers import Integral from pyrsistent._plist import plist def pdeque(iterable=(), maxlen=None): """ Return deque containing the elements of iterable. If maxlen is specified then len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen. >>> pdeque([1, 2, 3]) pdeque([1, 2, 3]) >>> pdeque([1, 2, 3, 4], maxlen=2) pdeque([3, 4], maxlen=2) """ t = tuple(iterable) if maxlen is not None: t = t[-maxlen:] length = len(t) pivot = int(length / 2) left = plist(t[:pivot]) right = plist(t[pivot:], reverse=True) return PDeque(left, right, length, maxlen) The provided code snippet includes necessary dependencies for implementing the `dq` function. Write a Python function `def dq(*elements)` to solve the following problem: Return deque containing all arguments. >>> dq(1, 2, 3) pdeque([1, 2, 3]) Here is the function: def dq(*elements): """ Return deque containing all arguments. >>> dq(1, 2, 3) pdeque([1, 2, 3]) """ return pdeque(elements)
Return deque containing all arguments. >>> dq(1, 2, 3) pdeque([1, 2, 3])
174,449
from pyrsistent._checked_types import (InvariantException, CheckedType, _restore_pickle, store_invariants) from pyrsistent._field_common import ( set_fields, check_type, is_field_ignore_extra_complaint, PFIELD_NO_INITIAL, serialize, check_global_invariants ) from pyrsistent._transformations import transform class CheckedType(object): def create(cls, source_data, _factory_fields=None): def serialize(self, format=None): def _is_pclass(bases): return len(bases) == 1 and bases[0] == CheckedType
null
174,450
from pyrsistent._checked_types import (InvariantException, CheckedType, _restore_pickle, store_invariants) from pyrsistent._field_common import ( set_fields, check_type, is_field_ignore_extra_complaint, PFIELD_NO_INITIAL, serialize, check_global_invariants ) from pyrsistent._transformations import transform def check_type(destination_cls, field, name, value): if field.type and not any(isinstance(value, get_type(t)) for t in field.type): actual_type = type(value) message = "Invalid type for field {0}.{1}, was {2}".format(destination_cls.__name__, name, actual_type.__name__) raise PTypeError(destination_cls, name, field.type, actual_type, message) def _check_and_set_attr(cls, field, name, value, result, invariant_errors): check_type(cls, field, name, value) is_ok, error_code = field.invariant(value) if not is_ok: invariant_errors.append(error_code) else: setattr(result, name, value)
null
174,451
from collections.abc import Sequence, Hashable from numbers import Integral from functools import reduce def plist(iterable=(), reverse=False): """ Creates a new persistent list containing all elements of iterable. Optional parameter reverse specifies if the elements should be inserted in reverse order or not. >>> plist([1, 2, 3]) plist([1, 2, 3]) >>> plist([1, 2, 3], reverse=True) plist([3, 2, 1]) """ if not reverse: iterable = list(iterable) iterable.reverse() return reduce(lambda pl, elem: pl.cons(elem), iterable, _EMPTY_PLIST) The provided code snippet includes necessary dependencies for implementing the `l` function. Write a Python function `def l(*elements)` to solve the following problem: Creates a new persistent list containing all arguments. >>> l(1, 2, 3) plist([1, 2, 3]) Here is the function: def l(*elements): """ Creates a new persistent list containing all arguments. >>> l(1, 2, 3) plist([1, 2, 3]) """ return plist(elements)
Creates a new persistent list containing all arguments. >>> l(1, 2, 3) plist([1, 2, 3])
174,452
from enum import Enum from abc import abstractmethod, ABCMeta from collections.abc import Iterable from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector def maybe_parse_many_user_types(ts): def _store_types(dct, bases, destination_name, source_name): maybe_types = maybe_parse_many_user_types([ d[source_name] for d in ([dct] + [b.__dict__ for b in bases]) if source_name in d ]) dct[destination_name] = maybe_types
null
174,453
from enum import Enum from abc import abstractmethod, ABCMeta from collections.abc import Iterable from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector def wrap_invariant(invariant): def _all_dicts(bases, seen=None): def store_invariants(dct, bases, destination_name, source_name): # Invariants are inherited invariants = [] for ns in [dct] + list(_all_dicts(bases)): try: invariant = ns[source_name] except KeyError: continue invariants.append(invariant) if not all(callable(invariant) for invariant in invariants): raise TypeError('Invariants must be callable') dct[destination_name] = tuple(wrap_invariant(inv) for inv in invariants)
null
174,454
from enum import Enum from abc import abstractmethod, ABCMeta from collections.abc import Iterable from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector class CheckedValueTypeError(CheckedTypeError): """ Raised when trying to set a value using a key with a type that doesn't match the declared type. Attributes: source_class -- The class of the collection expected_types -- Allowed types actual_type -- The non matching type actual_value -- Value of the variable with the non matching type """ pass def get_type(typ): if isinstance(typ, type): return typ return _get_class(typ) def _check_types(it, expected_types, source_class, exception_type=CheckedValueTypeError): if expected_types: for e in it: if not any(isinstance(e, get_type(t)) for t in expected_types): actual_type = type(e) msg = "Type {source_class} can only be used with {expected_types}, not {actual_type}".format( source_class=source_class.__name__, expected_types=tuple(get_type(et).__name__ for et in expected_types), actual_type=actual_type.__name__) raise exception_type(source_class, expected_types, actual_type, e, msg)
null
174,455
from enum import Enum from abc import abstractmethod, ABCMeta from collections.abc import Iterable from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector def _invariant_errors(elem, invariants): return [data for valid, data in (invariant(elem) for invariant in invariants) if not valid] def _invariant_errors_iterable(it, invariants): return sum([_invariant_errors(elem, invariants) for elem in it], [])
null
174,456
from enum import Enum from abc import abstractmethod, ABCMeta from collections.abc import Iterable from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector The provided code snippet includes necessary dependencies for implementing the `optional` function. Write a Python function `def optional(*typs)` to solve the following problem: Convenience function to specify that a value may be of any of the types in type 'typs' or None Here is the function: def optional(*typs): """ Convenience function to specify that a value may be of any of the types in type 'typs' or None """ return tuple(typs) + (type(None),)
Convenience function to specify that a value may be of any of the types in type 'typs' or None
174,457
from enum import Enum from abc import abstractmethod, ABCMeta from collections.abc import Iterable from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PythonPVector, python_pvector class CheckedType(object): """ Marker class to enable creation and serialization of checked object graphs. """ __slots__ = () def create(cls, source_data, _factory_fields=None): raise NotImplementedError() def serialize(self, format=None): raise NotImplementedError() def get_types(typs): return [get_type(typ) for typ in typs] def _checked_type_create(cls, source_data, _factory_fields=None, ignore_extra=False): if isinstance(source_data, cls): return source_data # Recursively apply create methods of checked types if the types of the supplied data # does not match any of the valid types. types = get_types(cls._checked_types) checked_type = next((t for t in types if issubclass(t, CheckedType)), None) if checked_type: return cls([checked_type.create(data, ignore_extra=ignore_extra) if not any(isinstance(data, t) for t in types) else data for data in source_data]) return cls(source_data)
null
174,458
from collections.abc import Set, Hashable import sys from pyrsistent._pmap import pmap def pset(iterable=(), pre_size=8): """ Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that used for :py:func:`pmap`. >>> s1 = pset([1, 2, 3, 2]) >>> s1 pset([1, 2, 3]) """ if not iterable: return _EMPTY_PSET return PSet._from_iterable(iterable, pre_size=pre_size) The provided code snippet includes necessary dependencies for implementing the `s` function. Write a Python function `def s(*elements)` to solve the following problem: Create a persistent set. Takes an arbitrary number of arguments to insert into the new set. >>> s1 = s(1, 2, 3, 2) >>> s1 pset([1, 2, 3]) Here is the function: def s(*elements): """ Create a persistent set. Takes an arbitrary number of arguments to insert into the new set. >>> s1 = s(1, 2, 3, 2) >>> s1 pset([1, 2, 3]) """ return pset(elements)
Create a persistent set. Takes an arbitrary number of arguments to insert into the new set. >>> s1 = s(1, 2, 3, 2) >>> s1 pset([1, 2, 3])
174,459
import re The provided code snippet includes necessary dependencies for implementing the `inc` function. Write a Python function `def inc(x)` to solve the following problem: Add one to the current value Here is the function: def inc(x): """ Add one to the current value """ return x + 1
Add one to the current value
174,460
import re The provided code snippet includes necessary dependencies for implementing the `dec` function. Write a Python function `def dec(x)` to solve the following problem: Subtract one from the current value Here is the function: def dec(x): """ Subtract one from the current value """ return x - 1
Subtract one from the current value
174,461
import re The provided code snippet includes necessary dependencies for implementing the `rex` function. Write a Python function `def rex(expr)` to solve the following problem: Regular expression matcher to use together with transform functions Here is the function: def rex(expr): """ Regular expression matcher to use together with transform functions """ r = re.compile(expr) return lambda key: isinstance(key, str) and r.match(key)
Regular expression matcher to use together with transform functions
174,462
import re The provided code snippet includes necessary dependencies for implementing the `ny` function. Write a Python function `def ny(_)` to solve the following problem: Matcher that matches any value Here is the function: def ny(_): """ Matcher that matches any value """ return True
Matcher that matches any value
174,463
import re def _chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] def _do_to_path(structure, path, command): if not path: return command(structure) if callable(command) else command kvs = _get_keys_and_values(structure, path[0]) return _update_structure(structure, kvs, path[1:], command) def transform(structure, transformations): r = structure for path, command in _chunks(transformations, 2): r = _do_to_path(r, path, command) return r
null
174,464
from collections.abc import Container, Iterable, Sized, Hashable from functools import reduce from pyrsistent._pmap import pmap def pbag(elements): """ Convert an iterable to a persistent bag. Takes an iterable with elements to insert. >>> pbag([1, 2, 3, 2]) pbag([1, 2, 2, 3]) """ if not elements: return _EMPTY_PBAG return PBag(reduce(_add_to_counters, elements, pmap())) The provided code snippet includes necessary dependencies for implementing the `b` function. Write a Python function `def b(*elements)` to solve the following problem: Construct a persistent bag. Takes an arbitrary number of arguments to insert into the new persistent bag. >>> b(1, 2, 3, 2) pbag([1, 2, 2, 3]) Here is the function: def b(*elements): """ Construct a persistent bag. Takes an arbitrary number of arguments to insert into the new persistent bag. >>> b(1, 2, 3, 2) pbag([1, 2, 2, 3]) """ return pbag(elements)
Construct a persistent bag. Takes an arbitrary number of arguments to insert into the new persistent bag. >>> b(1, 2, 3, 2) pbag([1, 2, 2, 3])
174,465
from abc import abstractmethod, ABCMeta from collections.abc import Sequence, Hashable from numbers import Integral import operator from pyrsistent._transformations import transform def _bitcount(val): return bin(val).count("1")
null
174,466
from abc import abstractmethod, ABCMeta from collections.abc import Sequence, Hashable from numbers import Integral import operator from pyrsistent._transformations import transform class PVector(metaclass=ABCMeta): """ Persistent vector implementation. Meant as a replacement for the cases where you would normally use a Python list. Do not instantiate directly, instead use the factory functions :py:func:`v` and :py:func:`pvector` to create an instance. Heavily influenced by the persistent vector available in Clojure. Initially this was more or less just a port of the Java code for the Clojure vector. It has since been modified and to some extent optimized for usage in Python. The vector is organized as a trie, any mutating method will return a new vector that contains the changes. No updates are done to the original vector. Structural sharing between vectors are applied where possible to save space and to avoid making complete copies. This structure corresponds most closely to the built in list type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments. The PVector implements the Sequence protocol and is Hashable. Inserts are amortized O(1). Random access is log32(n) where n is the size of the vector. The following are examples of some common operations on persistent vectors: >>> p = v(1, 2, 3) >>> p2 = p.append(4) >>> p3 = p2.extend([5, 6, 7]) >>> p pvector([1, 2, 3]) >>> p2 pvector([1, 2, 3, 4]) >>> p3 pvector([1, 2, 3, 4, 5, 6, 7]) >>> p3[5] 6 >>> p.set(1, 99) pvector([1, 99, 3]) >>> """ def __len__(self): """ >>> len(v(1, 2, 3)) 3 """ def __getitem__(self, index): """ Get value at index. Full slicing support. >>> v1 = v(5, 6, 7, 8) >>> v1[2] 7 >>> v1[1:3] pvector([6, 7]) """ def __add__(self, other): """ >>> v1 = v(1, 2) >>> v2 = v(3, 4) >>> v1 + v2 pvector([1, 2, 3, 4]) """ def __mul__(self, times): """ >>> v1 = v(1, 2) >>> 3 * v1 pvector([1, 2, 1, 2, 1, 2]) """ def __hash__(self): """ >>> v1 = v(1, 2, 3) >>> v2 = v(1, 2, 3) >>> hash(v1) == hash(v2) True """ def evolver(self): """ Create a new evolver for this pvector. The evolver acts as a mutable view of the vector with "transaction like" semantics. No part of the underlying vector i updated, it is still fully immutable. Furthermore multiple evolvers created from the same pvector do not interfere with each other. You may want to use an evolver instead of working directly with the pvector in the following cases: * Multiple updates are done to the same vector and the intermediate results are of no interest. In this case using an evolver may be a more efficient and easier to work with. * You need to pass a vector into a legacy function or a function that you have no control over which performs in place mutations of lists. In this case pass an evolver instance instead and then create a new pvector from the evolver once the function returns. The following example illustrates a typical workflow when working with evolvers. It also displays most of the API (which i kept small by design, you should not be tempted to use evolvers in excess ;-)). Create the evolver and perform various mutating updates to it: >>> v1 = v(1, 2, 3, 4, 5) >>> e = v1.evolver() >>> e[1] = 22 >>> _ = e.append(6) >>> _ = e.extend([7, 8, 9]) >>> e[8] += 1 >>> len(e) 9 The underlying pvector remains the same: >>> v1 pvector([1, 2, 3, 4, 5]) The changes are kept in the evolver. An updated pvector can be created using the persistent() function on the evolver. >>> v2 = e.persistent() >>> v2 pvector([1, 22, 3, 4, 5, 6, 7, 8, 10]) The new pvector will share data with the original pvector in the same way that would have been done if only using operations on the pvector. """ def mset(self, *args): """ Return a new vector with elements in specified positions replaced by values (multi set). Elements on even positions in the argument list are interpreted as indexes while elements on odd positions are considered values. >>> v1 = v(1, 2, 3) >>> v1.mset(0, 11, 2, 33) pvector([11, 2, 33]) """ def set(self, i, val): """ Return a new vector with element at position i replaced with val. The original vector remains unchanged. Setting a value one step beyond the end of the vector is equal to appending. Setting beyond that will result in an IndexError. >>> v1 = v(1, 2, 3) >>> v1.set(1, 4) pvector([1, 4, 3]) >>> v1.set(3, 4) pvector([1, 2, 3, 4]) >>> v1.set(-1, 4) pvector([1, 2, 4]) """ def append(self, val): """ Return a new vector with val appended. >>> v1 = v(1, 2) >>> v1.append(3) pvector([1, 2, 3]) """ def extend(self, obj): """ Return a new vector with all values in obj appended to it. Obj may be another PVector or any other Iterable. >>> v1 = v(1, 2, 3) >>> v1.extend([4, 5]) pvector([1, 2, 3, 4, 5]) """ def index(self, value, *args, **kwargs): """ Return first index of value. Additional indexes may be supplied to limit the search to a sub range of the vector. >>> v1 = v(1, 2, 3, 4, 3) >>> v1.index(3) 2 >>> v1.index(3, 3, 5) 4 """ def count(self, value): """ Return the number of times that value appears in the vector. >>> v1 = v(1, 4, 3, 4) >>> v1.count(4) 2 """ def transform(self, *transformations): """ Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True """ def delete(self, index, stop=None): """ Delete a portion of the vector by index or range. >>> v1 = v(1, 2, 3, 4, 5) >>> v1.delete(1) pvector([1, 3, 4, 5]) >>> v1.delete(1, 3) pvector([1, 4, 5]) """ def remove(self, value): """ Remove the first occurrence of a value from the vector. >>> v1 = v(1, 2, 3, 2, 1) >>> v2 = v1.remove(1) >>> v2 pvector([2, 3, 2, 1]) >>> v2.remove(1) pvector([2, 3, 2]) """ PVector.register(PythonPVector) def compare_pvector(v, other, operator): return operator(v.tolist(), other.tolist() if isinstance(other, PVector) else other)
null
174,467
from abc import abstractmethod, ABCMeta from collections.abc import Sequence, Hashable from numbers import Integral import operator from pyrsistent._transformations import transform def _index_or_slice(index, stop): if stop is None: return index return slice(index, stop)
null
174,468
from abc import abstractmethod, ABCMeta from collections.abc import Sequence, Hashable from numbers import Integral import operator from pyrsistent._transformations import transform _EMPTY_PVECTOR = PythonPVector(0, SHIFT, [], []) The provided code snippet includes necessary dependencies for implementing the `python_pvector` function. Write a Python function `def python_pvector(iterable=())` to solve the following problem: Create a new persistent vector containing the elements in iterable. >>> v1 = pvector([1, 2, 3]) >>> v1 pvector([1, 2, 3]) Here is the function: def python_pvector(iterable=()): """ Create a new persistent vector containing the elements in iterable. >>> v1 = pvector([1, 2, 3]) >>> v1 pvector([1, 2, 3]) """ return _EMPTY_PVECTOR.extend(iterable)
Create a new persistent vector containing the elements in iterable. >>> v1 = pvector([1, 2, 3]) >>> v1 pvector([1, 2, 3])
174,469
def nofollow(attrs, new=False): href_key = (None, "href") if href_key not in attrs: return attrs if attrs[href_key].startswith("mailto:"): return attrs rel_key = (None, "rel") rel_values = [val for val in attrs.get(rel_key, "").split(" ") if val] if "nofollow" not in [rel_val.lower() for rel_val in rel_values]: rel_values.append("nofollow") attrs[rel_key] = " ".join(rel_values) return attrs
null
174,470
def target_blank(attrs, new=False): href_key = (None, "href") if href_key not in attrs: return attrs if attrs[href_key].startswith("mailto:"): return attrs attrs[(None, "target")] = "_blank" return attrs
null
174,471
import re from urllib.parse import quote from bleach import callbacks as linkify_callbacks from bleach import html5lib_shim TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat cc cd cf cg ch ci ck cl cm cn co com coop cr cu cv cx cy cz de dj dk dm do dz ec edu ee eg er es et eu fi fj fk fm fo fr ga gb gd ge gf gg gh gi gl gm gn gov gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il im in info int io iq ir is it je jm jo jobs jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mil mk ml mm mn mo mobi mp mq mr ms mt mu museum mv mw mx my mz na name nc ne net nf ng ni nl no np nr nu nz om org pa pe pf pg ph pk pl pm pn post pr pro ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl sm sn so sr ss st su sv sx sy sz tc td tel tf tg th tj tk tl tm tn to tp tr travel tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws xn xxx ye yt yu za zm zw""".split() TLDS.reverse() The provided code snippet includes necessary dependencies for implementing the `build_url_re` function. Write a Python function `def build_url_re(tlds=TLDS, protocols=html5lib_shim.allowed_protocols)` to solve the following problem: Builds the url regex used by linkifier If you want a different set of tlds or allowed protocols, pass those in and stomp on the existing ``url_re``:: from bleach import linkifier my_url_re = linkifier.build_url_re(my_tlds_list, my_protocols) linker = LinkifyFilter(url_re=my_url_re) Here is the function: def build_url_re(tlds=TLDS, protocols=html5lib_shim.allowed_protocols): """Builds the url regex used by linkifier If you want a different set of tlds or allowed protocols, pass those in and stomp on the existing ``url_re``:: from bleach import linkifier my_url_re = linkifier.build_url_re(my_tlds_list, my_protocols) linker = LinkifyFilter(url_re=my_url_re) """ return re.compile( r"""\(* # Match any opening parentheses. \b(?<![@.])(?:(?:{0}):/{{0,3}}(?:(?:\w+:)?\w+@)?)? # http:// ([\w-]+\.)+(?:{1})(?:\:[0-9]+)?(?!\.\w)\b # xx.yy.tld(:##)? (?:[/?][^\s\{{\}}\|\\\^\[\]`<>"]*)? # /path/zz (excluding "unsafe" chars from RFC 1738, # except for # and ~, which happen in practice) """.format( "|".join(sorted(protocols)), "|".join(sorted(tlds)) ), re.IGNORECASE | re.VERBOSE | re.UNICODE, )
Builds the url regex used by linkifier If you want a different set of tlds or allowed protocols, pass those in and stomp on the existing ``url_re``:: from bleach import linkifier my_url_re = linkifier.build_url_re(my_tlds_list, my_protocols) linker = LinkifyFilter(url_re=my_url_re)
174,472
import re from urllib.parse import quote from bleach import callbacks as linkify_callbacks from bleach import html5lib_shim TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat cc cd cf cg ch ci ck cl cm cn co com coop cr cu cv cx cy cz de dj dk dm do dz ec edu ee eg er es et eu fi fj fk fm fo fr ga gb gd ge gf gg gh gi gl gm gn gov gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il im in info int io iq ir is it je jm jo jobs jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mil mk ml mm mn mo mobi mp mq mr ms mt mu museum mv mw mx my mz na name nc ne net nf ng ni nl no np nr nu nz om org pa pe pf pg ph pk pl pm pn post pr pro ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl sm sn so sr ss st su sv sx sy sz tc td tel tf tg th tj tk tl tm tn to tp tr travel tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws xn xxx ye yt yu za zm zw""".split() TLDS.reverse() The provided code snippet includes necessary dependencies for implementing the `build_email_re` function. Write a Python function `def build_email_re(tlds=TLDS)` to solve the following problem: Builds the email regex used by linkifier If you want a different set of tlds, pass those in and stomp on the existing ``email_re``:: from bleach import linkifier my_email_re = linkifier.build_email_re(my_tlds_list) linker = LinkifyFilter(email_re=my_url_re) Here is the function: def build_email_re(tlds=TLDS): """Builds the email regex used by linkifier If you want a different set of tlds, pass those in and stomp on the existing ``email_re``:: from bleach import linkifier my_email_re = linkifier.build_email_re(my_tlds_list) linker = LinkifyFilter(email_re=my_url_re) """ # open and closing braces doubled below for format string return re.compile( r"""(?<!//) (([-!#$%&'*+/=?^_`{{}}|~0-9A-Z]+ (\.[-!#$%&'*+/=?^_`{{}}|~0-9A-Z]+)* # dot-atom |^"([\001-\010\013\014\016-\037!#-\[\]-\177] |\\[\001-\011\013\014\016-\177])*" # quoted-string )@(?:[A-Z0-9](?:[A-Z0-9-]{{0,61}}[A-Z0-9])?\.)+(?:{0})) # domain """.format( "|".join(tlds) ), re.IGNORECASE | re.MULTILINE | re.VERBOSE, )
Builds the email regex used by linkifier If you want a different set of tlds, pass those in and stomp on the existing ``email_re``:: from bleach import linkifier my_email_re = linkifier.build_email_re(my_tlds_list) linker = LinkifyFilter(email_re=my_url_re)
174,473
import re import string import warnings from bleach._vendor.html5lib import ( # noqa: E402 module level import not at top of file HTMLParser, getTreeWalker, ) from bleach._vendor.html5lib import ( constants, ) from bleach._vendor.html5lib.constants import ( # noqa: E402 module level import not at top of file namespaces, prefixes, ) from bleach._vendor.html5lib.constants import ( _ReparseException as ReparseException, ) from bleach._vendor.html5lib.filters.base import ( Filter, ) from bleach._vendor.html5lib.filters.sanitizer import ( allowed_protocols, allowed_css_properties, allowed_svg_properties, attr_val_is_uri, svg_attr_val_allows_ref, svg_allow_local_href, ) from bleach._vendor.html5lib.filters.sanitizer import ( Filter as SanitizerFilter, ) from bleach._vendor.html5lib._inputstream import ( HTMLInputStream, ) from bleach._vendor.html5lib.serializer import ( escape, HTMLSerializer, ) from bleach._vendor.html5lib._tokenizer import ( attributeMap, HTMLTokenizer, ) from bleach._vendor.html5lib._trie import ( Trie, ) def convert_entity(value): """Convert an entity (minus the & and ; part) into what it represents This handles numeric, hex, and text entities. :arg value: the string (minus the ``&`` and ``;`` part) to convert :returns: unicode character or None if it's an ambiguous ampersand that doesn't match a character entity """ if value[0] == "#": if len(value) < 2: return None if value[1] in ("x", "X"): # hex-encoded code point int_as_string, base = value[2:], 16 else: # decimal code point int_as_string, base = value[1:], 10 if int_as_string == "": return None code_point = int(int_as_string, base) if 0 < code_point < 0x110000: return chr(code_point) else: return None return ENTITIES.get(value, None) def match_entity(stream): """Returns first entity in stream or None if no entity exists Note: For Bleach purposes, entities must start with a "&" and end with a ";". This ignores ambiguous character entities that have no ";" at the end. :arg stream: the character stream :returns: the entity string without "&" or ";" if it's a valid character entity; ``None`` otherwise """ # Nix the & at the beginning if stream[0] != "&": raise ValueError('Stream should begin with "&"') stream = stream[1:] stream = list(stream) possible_entity = "" end_characters = "<&=;" + string.whitespace # Handle number entities if stream and stream[0] == "#": possible_entity = "#" stream.pop(0) if stream and stream[0] in ("x", "X"): allowed = "0123456789abcdefABCDEF" possible_entity += stream.pop(0) else: allowed = "0123456789" # FIXME(willkg): Do we want to make sure these are valid number # entities? This doesn't do that currently. while stream and stream[0] not in end_characters: c = stream.pop(0) if c not in allowed: break possible_entity += c if possible_entity and stream and stream[0] == ";": return possible_entity return None # Handle character entities while stream and stream[0] not in end_characters: c = stream.pop(0) possible_entity += c if not ENTITIES_TRIE.has_keys_with_prefix(possible_entity): # If it's not a prefix, then it's not an entity and we're # out return None if possible_entity and stream and stream[0] == ";": return possible_entity return None def next_possible_entity(text): """Takes a text and generates a list of possible entities :arg text: the text to look at :returns: generator where each part (except the first) starts with an "&" """ for i, part in enumerate(AMP_SPLIT_RE.split(text)): if i == 0: yield part elif i % 2 == 0: yield "&" + part The provided code snippet includes necessary dependencies for implementing the `convert_entities` function. Write a Python function `def convert_entities(text)` to solve the following problem: Converts all found entities in the text :arg text: the text to convert entities in :returns: unicode text with converted entities Here is the function: def convert_entities(text): """Converts all found entities in the text :arg text: the text to convert entities in :returns: unicode text with converted entities """ if "&" not in text: return text new_text = [] for part in next_possible_entity(text): if not part: continue if part.startswith("&"): entity = match_entity(part) if entity is not None: converted = convert_entity(entity) # If it's not an ambiguous ampersand, then replace with the # unicode character. Otherwise, we leave the entity in. if converted is not None: new_text.append(converted) remainder = part[len(entity) + 2 :] if part: new_text.append(remainder) continue new_text.append(part) return "".join(new_text)
Converts all found entities in the text :arg text: the text to convert entities in :returns: unicode text with converted entities
174,474
from itertools import chain import re import warnings from xml.sax.saxutils import unescape from bleach import html5lib_shim from bleach import parse_shim The provided code snippet includes necessary dependencies for implementing the `attribute_filter_factory` function. Write a Python function `def attribute_filter_factory(attributes)` to solve the following problem: Generates attribute filter function for the given attributes value The attributes value can take one of several shapes. This returns a filter function appropriate to the attributes value. One nice thing about this is that there's less if/then shenanigans in the ``allow_token`` method. Here is the function: def attribute_filter_factory(attributes): """Generates attribute filter function for the given attributes value The attributes value can take one of several shapes. This returns a filter function appropriate to the attributes value. One nice thing about this is that there's less if/then shenanigans in the ``allow_token`` method. """ if callable(attributes): return attributes if isinstance(attributes, dict): def _attr_filter(tag, attr, value): if tag in attributes: attr_val = attributes[tag] if callable(attr_val): return attr_val(tag, attr, value) if attr in attr_val: return True if "*" in attributes: attr_val = attributes["*"] if callable(attr_val): return attr_val(tag, attr, value) return attr in attr_val return False return _attr_filter if isinstance(attributes, list): def _attr_filter(tag, attr, value): return attr in attributes return _attr_filter raise ValueError("attributes needs to be a callable, a list or a dict")
Generates attribute filter function for the given attributes value The attributes value can take one of several shapes. This returns a filter function appropriate to the attributes value. One nice thing about this is that there's less if/then shenanigans in the ``allow_token`` method.
174,475
from __future__ import absolute_import, division, unicode_literals import re import warnings from .constants import DataLossWarning reChar = re.compile(r"#x([\d|A-F]{4,4})") reCharRange = re.compile(r"\[#x([\d|A-F]{4,4})-#x([\d|A-F]{4,4})\]") def normaliseCharList(charList): def hexToInt(hex_str): def charStringToList(chars): charRanges = [item.strip() for item in chars.split(" | ")] rv = [] for item in charRanges: foundMatch = False for regexp in (reChar, reCharRange): match = regexp.match(item) if match is not None: rv.append([hexToInt(item) for item in match.groups()]) if len(rv[-1]) == 1: rv[-1] = rv[-1] * 2 foundMatch = True break if not foundMatch: assert len(item) == 1 rv.append([ord(item)] * 2) rv = normaliseCharList(rv) return rv
null
174,478
from __future__ import absolute_import, division, unicode_literals from types import ModuleType from six import text_type, PY3 class ModuleType: __doc__: Optional[str] __file__: Optional[str] __name__: str __package__: Optional[str] __path__: Optional[Iterable[str]] __dict__: Dict[str, Any] def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... def moduleFactoryFactory(factory): moduleCache = {} def moduleFactory(baseModule, *args, **kwargs): if isinstance(ModuleType.__name__, type("")): name = "_%s_factory" % baseModule.__name__ else: name = b"_%s_factory" % baseModule.__name__ kwargs_tuple = tuple(kwargs.items()) try: return moduleCache[name][args][kwargs_tuple] except KeyError: mod = ModuleType(name) objs = factory(baseModule, *args, **kwargs) mod.__dict__.update(objs) if "name" not in moduleCache: moduleCache[name] = {} if "args" not in moduleCache[name]: moduleCache[name][args] = {} if "kwargs" not in moduleCache[name][args]: moduleCache[name][args][kwargs_tuple] = {} moduleCache[name][args][kwargs_tuple] = mod return mod return moduleFactory
null
174,480
from __future__ import absolute_import, division, unicode_literals from collections import OrderedDict import re from six import string_types from . import base from .._utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") class OrderedDict(dict): def __init__(self, data=None, **kwargs): self._keys = self.keys(data, kwargs.get("keys")) self._default_factory = kwargs.get("default_factory") if data is None: dict.__init__(self) else: dict.__init__(self, data) def __delitem__(self, key): dict.__delitem__(self, key) self._keys.remove(key) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __iter__(self): return (key for key in self.keys()) def __missing__(self, key): if not self._default_factory and key not in self._keys: raise KeyError() return self._default_factory() def __setitem__(self, key, item): dict.__setitem__(self, key, item) if key not in self._keys: self._keys.append(key) def clear(self): dict.clear(self) self._keys.clear() def copy(self): d = dict.copy(self) d._keys = self._keys return d def items(self): # returns iterator under python 3 and list under python 2 return zip(self.keys(), self.values()) def keys(self, data=None, keys=None): if data: if keys: assert isinstance(keys, list) assert len(data) == len(keys) return keys else: assert ( isinstance(data, dict) or isinstance(data, OrderedDict) or isinstance(data, list) ) if isinstance(data, dict) or isinstance(data, OrderedDict): return data.keys() elif isinstance(data, list): return [key for (key, value) in data] elif "_keys" in self.__dict__: return self._keys else: return [] def popitem(self): if not self._keys: raise KeyError() key = self._keys.pop() value = self[key] del self[key] return (key, value) def setdefault(self, key, failobj=None): dict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) def update(self, data): dict.update(self, data) for key in self.keys(data): if key not in self._keys: self._keys.append(key) def values(self): # returns iterator under python 3 return map(self.get, self._keys) string_types = (str,) def getETreeBuilder(ElementTreeImplementation): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag class TreeWalker(base.NonRecursiveTreeWalker): # pylint:disable=unused-variable """Given the particular ElementTree representation, this implementation, to avoid using recursion, returns "nodes" as tuples with the following content: 1. The current element 2. The index of the element relative to its parent 3. A stack of ancestor elements 4. A flag "text", "tail" or None to indicate if the current node is a text node; either the text or tail of the current element (1) """ def getNodeDetails(self, node): if isinstance(node, tuple): # It might be the root Element elt, _, _, flag = node if flag in ("text", "tail"): return base.TEXT, getattr(elt, flag) else: node = elt if not(hasattr(node, "tag")): node = node.getroot() if node.tag in ("DOCUMENT_ROOT", "DOCUMENT_FRAGMENT"): return (base.DOCUMENT,) elif node.tag == "<!DOCTYPE>": return (base.DOCTYPE, node.text, node.get("publicId"), node.get("systemId")) elif node.tag == ElementTreeCommentType: return base.COMMENT, node.text else: assert isinstance(node.tag, string_types), type(node.tag) # This is assumed to be an ordinary element match = tag_regexp.match(node.tag) if match: namespace, tag = match.groups() else: namespace = None tag = node.tag attrs = OrderedDict() for name, value in list(node.attrib.items()): match = tag_regexp.match(name) if match: attrs[(match.group(1), match.group(2))] = value else: attrs[(None, name)] = value return (base.ELEMENT, namespace, tag, attrs, len(node) or node.text) def getFirstChild(self, node): if isinstance(node, tuple): element, key, parents, flag = node else: element, key, parents, flag = node, None, [], None if flag in ("text", "tail"): return None else: if element.text: return element, key, parents, "text" elif len(element): parents.append(element) return element[0], 0, parents, None else: return None def getNextSibling(self, node): if isinstance(node, tuple): element, key, parents, flag = node else: return None if flag == "text": if len(element): parents.append(element) return element[0], 0, parents, None else: return None else: if element.tail and flag != "tail": return element, key, parents, "tail" elif key < len(parents[-1]) - 1: return parents[-1][key + 1], key + 1, parents, None else: return None def getParentNode(self, node): if isinstance(node, tuple): element, key, parents, flag = node else: return None if flag == "text": if not parents: return element else: return element, key, parents, None else: parent = parents.pop() if not parents: return parent else: assert list(parents[-1]).count(parent) == 1 return parent, list(parents[-1]).index(parent), parents, None return locals()
null
174,481
from __future__ import absolute_import, division, unicode_literals from six import text_type from collections import OrderedDict from lxml import etree from ..treebuilders.etree import tag_regexp from . import base from .. import _ihatexml text_type = str def ensure_str(s): if s is None: return None elif isinstance(s, text_type): return s else: return s.decode("ascii", "strict")
null
174,484
from __future__ import absolute_import, division, unicode_literals from six import text_type from six.moves import http_client, urllib import codecs import re from io import BytesIO, StringIO import webencodings from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase from .constants import _ReparseException from . import _utils class HTMLUnicodeInputStream(object): """Provides a unicode stream of characters to the HTMLTokenizer. This class takes care of character encoding and removing or replacing incorrect byte-sequences and also provides column and line tracking. """ _defaultChunkSize = 10240 def __init__(self, source): """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 of any BOM or later declaration (such as in a meta element) """ if not _utils.supports_lone_surrogates: # Such platforms will have already checked for such # surrogate errors, so no need to do this checking. self.reportCharacterErrors = None elif len("\U0010FFFF") == 1: self.reportCharacterErrors = self.characterErrorsUCS4 else: self.reportCharacterErrors = self.characterErrorsUCS2 # List of where new lines occur self.newLines = [0] self.charEncoding = (lookupEncoding("utf-8"), "certain") self.dataStream = self.openStream(source) self.reset() def reset(self): self.chunk = "" self.chunkSize = 0 self.chunkOffset = 0 self.errors = [] # number of (complete) lines in previous chunks self.prevNumLines = 0 # number of columns in the last line of the previous chunk self.prevNumCols = 0 # Deal with CR LF and surrogates split over chunk boundaries self._bufferedCharacter = None def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = StringIO(source) return stream def _position(self, offset): chunk = self.chunk nLines = chunk.count('\n', 0, offset) positionLine = self.prevNumLines + nLines lastLinePos = chunk.rfind('\n', 0, offset) if lastLinePos == -1: positionColumn = self.prevNumCols + offset else: positionColumn = offset - (lastLinePos + 1) return (positionLine, positionColumn) def position(self): """Returns (line, col) of the current position in the stream.""" line, col = self._position(self.chunkOffset) return (line + 1, col) def char(self): """ Read one character from the stream or queue if available. Return EOF when EOF is reached. """ # Read a new chunk from the input stream if necessary if self.chunkOffset >= self.chunkSize: if not self.readChunk(): return EOF chunkOffset = self.chunkOffset char = self.chunk[chunkOffset] self.chunkOffset = chunkOffset + 1 return char def readChunk(self, chunkSize=None): if chunkSize is None: chunkSize = self._defaultChunkSize self.prevNumLines, self.prevNumCols = self._position(self.chunkSize) self.chunk = "" self.chunkSize = 0 self.chunkOffset = 0 data = self.dataStream.read(chunkSize) # Deal with CR LF and surrogates broken across chunks if self._bufferedCharacter: data = self._bufferedCharacter + data self._bufferedCharacter = None elif not data: # We have no more data, bye-bye stream return False if len(data) > 1: lastv = ord(data[-1]) if lastv == 0x0D or 0xD800 <= lastv <= 0xDBFF: self._bufferedCharacter = data[-1] data = data[:-1] if self.reportCharacterErrors: self.reportCharacterErrors(data) # Replace invalid characters data = data.replace("\r\n", "\n") data = data.replace("\r", "\n") self.chunk = data self.chunkSize = len(data) return True def characterErrorsUCS4(self, data): for _ in range(len(invalid_unicode_re.findall(data))): self.errors.append("invalid-codepoint") def characterErrorsUCS2(self, data): # Someone picked the wrong compile option # You lose skip = False for match in invalid_unicode_re.finditer(data): if skip: continue codepoint = ord(match.group()) pos = match.start() # Pretty sure there should be endianness issues here if _utils.isSurrogatePair(data[pos:pos + 2]): # We have a surrogate pair! char_val = _utils.surrogatePairToCodepoint(data[pos:pos + 2]) if char_val in non_bmp_invalid_codepoints: self.errors.append("invalid-codepoint") skip = True elif (codepoint >= 0xD800 and codepoint <= 0xDFFF and pos == len(data) - 1): self.errors.append("invalid-codepoint") else: skip = False self.errors.append("invalid-codepoint") def charsUntil(self, characters, opposite=False): """ 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. """ # Use a cache of regexps to find the required characters try: chars = charsUntilRegEx[(characters, opposite)] except KeyError: if __debug__: for c in characters: assert(ord(c) < 128) regex = "".join(["\\x%02x" % ord(c) for c in characters]) if not opposite: regex = "^%s" % regex chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex) rv = [] while True: # Find the longest matching prefix m = chars.match(self.chunk, self.chunkOffset) if m is None: # If nothing matched, and it wasn't because we ran out of chunk, # then stop if self.chunkOffset != self.chunkSize: break else: end = m.end() # If not the whole chunk matched, return everything # up to the part that didn't match if end != self.chunkSize: rv.append(self.chunk[self.chunkOffset:end]) self.chunkOffset = end break # If the whole remainder of the chunk matched, # use it all and read the next chunk rv.append(self.chunk[self.chunkOffset:]) if not self.readChunk(): # Reached EOF break r = "".join(rv) return r def unget(self, char): # Only one character is allowed to be ungotten at once - it must # be consumed again before any further call to unget if char is not EOF: if self.chunkOffset == 0: # unget is called quite rarely, so it's a good idea to do # more work here if it saves a bit of work in the frequently # called char and charsUntil. # So, just prepend the ungotten character onto the current # chunk: self.chunk = char + self.chunk self.chunkSize += 1 else: self.chunkOffset -= 1 assert self.chunk[self.chunkOffset] == char class HTMLBinaryInputStream(HTMLUnicodeInputStream): """Provides a unicode stream of characters to the HTMLTokenizer. This class takes care of character encoding and removing or replacing incorrect byte-sequences and also provides column and line tracking. """ def __init__(self, source, override_encoding=None, transport_encoding=None, same_origin_parent_encoding=None, likely_encoding=None, default_encoding="windows-1252", useChardet=True): """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 of any BOM or later declaration (such as in a meta element) """ # Raw Stream - for unicode objects this will encode to utf-8 and set # self.charEncoding as appropriate self.rawStream = self.openStream(source) HTMLUnicodeInputStream.__init__(self, self.rawStream) # Encoding Information # Number of bytes to use when looking for a meta element with # encoding information self.numBytesMeta = 1024 # Number of bytes to use when using detecting encoding using chardet self.numBytesChardet = 100 # Things from args self.override_encoding = override_encoding self.transport_encoding = transport_encoding self.same_origin_parent_encoding = same_origin_parent_encoding self.likely_encoding = likely_encoding self.default_encoding = default_encoding # Determine encoding self.charEncoding = self.determineEncoding(useChardet) assert self.charEncoding[0] is not None # Call superclass self.reset() def reset(self): self.dataStream = self.charEncoding[0].codec_info.streamreader(self.rawStream, 'replace') HTMLUnicodeInputStream.reset(self) def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = BytesIO(source) try: stream.seek(stream.tell()) except Exception: stream = BufferedStream(stream) return stream def determineEncoding(self, chardet=True): # BOMs take precedence over everything # This will also read past the BOM if present charEncoding = self.detectBOM(), "certain" if charEncoding[0] is not None: return charEncoding # If we've been overridden, we've been overridden charEncoding = lookupEncoding(self.override_encoding), "certain" if charEncoding[0] is not None: return charEncoding # Now check the transport layer charEncoding = lookupEncoding(self.transport_encoding), "certain" if charEncoding[0] is not None: return charEncoding # Look for meta elements with encoding information charEncoding = self.detectEncodingMeta(), "tentative" if charEncoding[0] is not None: return charEncoding # Parent document encoding charEncoding = lookupEncoding(self.same_origin_parent_encoding), "tentative" if charEncoding[0] is not None and not charEncoding[0].name.startswith("utf-16"): return charEncoding # "likely" encoding charEncoding = lookupEncoding(self.likely_encoding), "tentative" if charEncoding[0] is not None: return charEncoding # Guess with chardet, if available if chardet: try: from chardet.universaldetector import UniversalDetector except ImportError: pass else: buffers = [] detector = UniversalDetector() while not detector.done: buffer = self.rawStream.read(self.numBytesChardet) assert isinstance(buffer, bytes) if not buffer: break buffers.append(buffer) detector.feed(buffer) detector.close() encoding = lookupEncoding(detector.result['encoding']) self.rawStream.seek(0) if encoding is not None: return encoding, "tentative" # Try the default encoding charEncoding = lookupEncoding(self.default_encoding), "tentative" if charEncoding[0] is not None: return charEncoding # Fallback to html5lib's default if even that hasn't worked return lookupEncoding("windows-1252"), "tentative" def changeEncoding(self, newEncoding): assert self.charEncoding[1] != "certain" newEncoding = lookupEncoding(newEncoding) if newEncoding is None: return if newEncoding.name in ("utf-16be", "utf-16le"): newEncoding = lookupEncoding("utf-8") assert newEncoding is not None elif newEncoding == self.charEncoding[0]: self.charEncoding = (self.charEncoding[0], "certain") else: self.rawStream.seek(0) self.charEncoding = (newEncoding, "certain") self.reset() raise _ReparseException("Encoding changed from %s to %s" % (self.charEncoding[0], newEncoding)) def detectBOM(self): """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""" bomDict = { codecs.BOM_UTF8: 'utf-8', codecs.BOM_UTF16_LE: 'utf-16le', codecs.BOM_UTF16_BE: 'utf-16be', codecs.BOM_UTF32_LE: 'utf-32le', codecs.BOM_UTF32_BE: 'utf-32be' } # Go to beginning of file and read in 4 bytes string = self.rawStream.read(4) assert isinstance(string, bytes) # Try detecting the BOM using bytes from the string encoding = bomDict.get(string[:3]) # UTF-8 seek = 3 if not encoding: # Need to detect UTF-32 before UTF-16 encoding = bomDict.get(string) # UTF-32 seek = 4 if not encoding: encoding = bomDict.get(string[:2]) # UTF-16 seek = 2 # Set the read position past the BOM if one was found, otherwise # set it to the start of the stream if encoding: self.rawStream.seek(seek) return lookupEncoding(encoding) else: self.rawStream.seek(0) return None def detectEncodingMeta(self): """Report the encoding declared by the meta element """ buffer = self.rawStream.read(self.numBytesMeta) assert isinstance(buffer, bytes) parser = EncodingParser(buffer) self.rawStream.seek(0) encoding = parser.getEncoding() if encoding is not None and encoding.name in ("utf-16be", "utf-16le"): encoding = lookupEncoding("utf-8") return encoding text_type = str def HTMLInputStream(source, **kwargs): # Work around Python bug #20007: read(0) closes the connection. # http://bugs.python.org/issue20007 if (isinstance(source, http_client.HTTPResponse) or # Also check for addinfourl wrapping HTTPResponse (isinstance(source, urllib.response.addbase) and isinstance(source.fp, http_client.HTTPResponse))): isUnicode = False elif hasattr(source, "read"): isUnicode = isinstance(source.read(0), text_type) else: isUnicode = isinstance(source, text_type) if isUnicode: encodings = [x for x in kwargs if x.endswith("_encoding")] if encodings: raise TypeError("Cannot set an encoding with a unicode input, set %r" % encodings) return HTMLUnicodeInputStream(source, **kwargs) else: return HTMLBinaryInputStream(source, **kwargs)
null
174,487
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from copy import copy from . import base from .. import _ihatexml from .. import constants from ..constants import namespaces from .._utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") text_type = str def copy(x: _T) -> _T: ... namespaces = { "html": "http://www.w3.org/1999/xhtml", "mathml": "http://www.w3.org/1998/Math/MathML", "svg": "http://www.w3.org/2000/svg", "xlink": "http://www.w3.org/1999/xlink", "xml": "http://www.w3.org/XML/1998/namespace", "xmlns": "http://www.w3.org/2000/xmlns/" } def getETreeBuilder(ElementTreeImplementation, fullTree=False): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag class Element(base.Node): def __init__(self, name, namespace=None): self._name = name self._namespace = namespace self._element = ElementTree.Element(self._getETreeTag(name, namespace)) if namespace is None: self.nameTuple = namespaces["html"], self._name else: self.nameTuple = self._namespace, self._name self.parent = None self._childNodes = [] self._flags = [] def _getETreeTag(self, name, namespace): if namespace is None: etree_tag = name else: etree_tag = "{%s}%s" % (namespace, name) return etree_tag def _setName(self, name): self._name = name self._element.tag = self._getETreeTag(self._name, self._namespace) def _getName(self): return self._name name = property(_getName, _setName) def _setNamespace(self, namespace): self._namespace = namespace self._element.tag = self._getETreeTag(self._name, self._namespace) def _getNamespace(self): return self._namespace namespace = property(_getNamespace, _setNamespace) def _getAttributes(self): return self._element.attrib def _setAttributes(self, attributes): el_attrib = self._element.attrib el_attrib.clear() if attributes: # calling .items _always_ allocates, and the above truthy check is cheaper than the # allocation on average for key, value in attributes.items(): if isinstance(key, tuple): name = "{%s}%s" % (key[2], key[1]) else: name = key el_attrib[name] = value attributes = property(_getAttributes, _setAttributes) def _getChildNodes(self): return self._childNodes def _setChildNodes(self, value): del self._element[:] self._childNodes = [] for element in value: self.insertChild(element) childNodes = property(_getChildNodes, _setChildNodes) def hasContent(self): """Return true if the node has children or text""" return bool(self._element.text or len(self._element)) def appendChild(self, node): self._childNodes.append(node) self._element.append(node._element) node.parent = self def insertBefore(self, node, refNode): index = list(self._element).index(refNode._element) self._element.insert(index, node._element) node.parent = self def removeChild(self, node): self._childNodes.remove(node) self._element.remove(node._element) node.parent = None def insertText(self, data, insertBefore=None): if not(len(self._element)): if not self._element.text: self._element.text = "" self._element.text += data elif insertBefore is None: # Insert the text as the tail of the last child element if not self._element[-1].tail: self._element[-1].tail = "" self._element[-1].tail += data else: # Insert the text before the specified node children = list(self._element) index = children.index(insertBefore._element) if index > 0: if not self._element[index - 1].tail: self._element[index - 1].tail = "" self._element[index - 1].tail += data else: if not self._element.text: self._element.text = "" self._element.text += data def cloneNode(self): element = type(self)(self.name, self.namespace) if self._element.attrib: element._element.attrib = copy(self._element.attrib) return element def reparentChildren(self, newParent): if newParent.childNodes: newParent.childNodes[-1]._element.tail += self._element.text else: if not newParent._element.text: newParent._element.text = "" if self._element.text is not None: newParent._element.text += self._element.text self._element.text = "" base.Node.reparentChildren(self, newParent) class Comment(Element): def __init__(self, data): # Use the superclass constructor to set all properties on the # wrapper element self._element = ElementTree.Comment(data) self.parent = None self._childNodes = [] self._flags = [] def _getData(self): return self._element.text def _setData(self, value): self._element.text = value data = property(_getData, _setData) class DocumentType(Element): def __init__(self, name, publicId, systemId): Element.__init__(self, "<!DOCTYPE>") self._element.text = name self.publicId = publicId self.systemId = systemId def _getPublicId(self): return self._element.get("publicId", "") def _setPublicId(self, value): if value is not None: self._element.set("publicId", value) publicId = property(_getPublicId, _setPublicId) def _getSystemId(self): return self._element.get("systemId", "") def _setSystemId(self, value): if value is not None: self._element.set("systemId", value) systemId = property(_getSystemId, _setSystemId) class Document(Element): def __init__(self): Element.__init__(self, "DOCUMENT_ROOT") class DocumentFragment(Element): def __init__(self): Element.__init__(self, "DOCUMENT_FRAGMENT") def testSerializer(element): rv = [] def serializeElement(element, indent=0): if not(hasattr(element, "tag")): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": rv.append("#document") if element.text is not None: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") elif element.tag == ElementTreeCommentType: rv.append("|%s<!-- %s -->" % (' ' * indent, element.text)) else: assert isinstance(element.tag, text_type), \ "Expected unicode, got %s, %s" % (type(element.tag), element.tag) nsmatch = tag_regexp.match(element.tag) if nsmatch is None: name = element.tag else: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] name = "%s %s" % (prefix, name) rv.append("|%s<%s>" % (' ' * indent, name)) if hasattr(element, "attrib"): attributes = [] for name, value in element.attrib.items(): nsmatch = tag_regexp.match(name) if nsmatch is not None: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] attr_string = "%s %s" % (prefix, name) else: attr_string = name attributes.append((attr_string, value)) for name, value in sorted(attributes): rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value)) if element.text: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) indent += 2 for child in element: serializeElement(child, indent) if element.tail: rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail)) serializeElement(element, 0) return "\n".join(rv) def tostring(element): # pylint:disable=unused-variable """Serialize an element and its child nodes to a string""" rv = [] filter = _ihatexml.InfosetFilter() def serializeElement(element): if isinstance(element, ElementTree.ElementTree): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s PUBLIC "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": if element.text is not None: rv.append(element.text) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") for child in element: serializeElement(child) elif element.tag == ElementTreeCommentType: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (filter.fromXmlName(element.tag),)) else: attr = " ".join(["%s=\"%s\"" % ( filter.fromXmlName(name), value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if element.tail: rv.append(element.tail) serializeElement(element) return "".join(rv) class TreeBuilder(base.TreeBuilder): # pylint:disable=unused-variable documentClass = Document doctypeClass = DocumentType elementClass = Element commentClass = Comment fragmentClass = DocumentFragment implementation = ElementTreeImplementation def testSerializer(self, element): return testSerializer(element) def getDocument(self): if fullTree: return self.document._element else: if self.defaultNamespace is not None: return self.document._element.find( "{%s}html" % self.defaultNamespace) else: return self.document._element.find("html") def getFragment(self): return base.TreeBuilder.getFragment(self)._element return locals()
null
174,491
from __future__ import absolute_import, division, unicode_literals from six import with_metaclass, viewkeys import types from . import _inputstream from . import _tokenizer from . import treebuilders from .treebuilders.base import Marker from . import _utils from .constants import ( spaceCharacters, asciiUpper2Lower, specialElements, headingElements, cdataElements, rcdataElements, tokenTypes, tagTokenTypes, namespaces, htmlIntegrationPointElements, mathmlTextIntegrationPointElements, adjustForeignAttributes as adjustForeignAttributesMap, adjustMathMLAttributes, adjustSVGAttributes, E, _ReparseException ) def parse(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs): def method_decorator_metaclass(function): def impliedTagToken(name, type="EndTag", attributes=None, selfClosing=False): def with_metaclass(meta, *bases): Marker = None namespaces = { "html": "http://www.w3.org/1999/xhtml", "mathml": "http://www.w3.org/1998/Math/MathML", "svg": "http://www.w3.org/2000/svg", "xlink": "http://www.w3.org/1999/xlink", "xml": "http://www.w3.org/XML/1998/namespace", "xmlns": "http://www.w3.org/2000/xmlns/" } specialElements = frozenset([ (namespaces["html"], "address"), (namespaces["html"], "applet"), (namespaces["html"], "area"), (namespaces["html"], "article"), (namespaces["html"], "aside"), (namespaces["html"], "base"), (namespaces["html"], "basefont"), (namespaces["html"], "bgsound"), (namespaces["html"], "blockquote"), (namespaces["html"], "body"), (namespaces["html"], "br"), (namespaces["html"], "button"), (namespaces["html"], "caption"), (namespaces["html"], "center"), (namespaces["html"], "col"), (namespaces["html"], "colgroup"), (namespaces["html"], "command"), (namespaces["html"], "dd"), (namespaces["html"], "details"), (namespaces["html"], "dir"), (namespaces["html"], "div"), (namespaces["html"], "dl"), (namespaces["html"], "dt"), (namespaces["html"], "embed"), (namespaces["html"], "fieldset"), (namespaces["html"], "figure"), (namespaces["html"], "footer"), (namespaces["html"], "form"), (namespaces["html"], "frame"), (namespaces["html"], "frameset"), (namespaces["html"], "h1"), (namespaces["html"], "h2"), (namespaces["html"], "h3"), (namespaces["html"], "h4"), (namespaces["html"], "h5"), (namespaces["html"], "h6"), (namespaces["html"], "head"), (namespaces["html"], "header"), (namespaces["html"], "hr"), (namespaces["html"], "html"), (namespaces["html"], "iframe"), # Note that image is commented out in the spec as "this isn't an # element that can end up on the stack, so it doesn't matter," (namespaces["html"], "image"), (namespaces["html"], "img"), (namespaces["html"], "input"), (namespaces["html"], "isindex"), (namespaces["html"], "li"), (namespaces["html"], "link"), (namespaces["html"], "listing"), (namespaces["html"], "marquee"), (namespaces["html"], "menu"), (namespaces["html"], "meta"), (namespaces["html"], "nav"), (namespaces["html"], "noembed"), (namespaces["html"], "noframes"), (namespaces["html"], "noscript"), (namespaces["html"], "object"), (namespaces["html"], "ol"), (namespaces["html"], "p"), (namespaces["html"], "param"), (namespaces["html"], "plaintext"), (namespaces["html"], "pre"), (namespaces["html"], "script"), (namespaces["html"], "section"), (namespaces["html"], "select"), (namespaces["html"], "style"), (namespaces["html"], "table"), (namespaces["html"], "tbody"), (namespaces["html"], "td"), (namespaces["html"], "textarea"), (namespaces["html"], "tfoot"), (namespaces["html"], "th"), (namespaces["html"], "thead"), (namespaces["html"], "title"), (namespaces["html"], "tr"), (namespaces["html"], "ul"), (namespaces["html"], "wbr"), (namespaces["html"], "xmp"), (namespaces["svg"], "foreignObject") ]) adjustForeignAttributes = { "xlink:actuate": ("xlink", "actuate", namespaces["xlink"]), "xlink:arcrole": ("xlink", "arcrole", namespaces["xlink"]), "xlink:href": ("xlink", "href", namespaces["xlink"]), "xlink:role": ("xlink", "role", namespaces["xlink"]), "xlink:show": ("xlink", "show", namespaces["xlink"]), "xlink:title": ("xlink", "title", namespaces["xlink"]), "xlink:type": ("xlink", "type", namespaces["xlink"]), "xml:base": ("xml", "base", namespaces["xml"]), "xml:lang": ("xml", "lang", namespaces["xml"]), "xml:space": ("xml", "space", namespaces["xml"]), "xmlns": (None, "xmlns", namespaces["xmlns"]), "xmlns:xlink": ("xmlns", "xlink", namespaces["xmlns"]) } spaceCharacters = frozenset([ "\t", "\n", "\u000C", " ", "\r" ]) asciiUpper2Lower = {ord(c): ord(c.lower()) for c in string.ascii_uppercase} headingElements = ( "h1", "h2", "h3", "h4", "h5", "h6" ) tokenTypes = { "Doctype": 0, "Characters": 1, "SpaceCharacters": 2, "StartTag": 3, "EndTag": 4, "EmptyTag": 5, "Comment": 6, "ParseError": 7 } tagTokenTypes = frozenset([tokenTypes["StartTag"], tokenTypes["EndTag"], tokenTypes["EmptyTag"]]) def getPhases(debug): def log(function): """Logger that records which phase processes each token""" type_names = {value: key for key, value in tokenTypes.items()} def wrapped(self, *args, **kwargs): if function.__name__.startswith("process") and len(args) > 0: token = args[0] info = {"type": type_names[token['type']]} if token['type'] in tagTokenTypes: info["name"] = token['name'] self.parser.log.append((self.parser.tokenizer.state.__name__, self.parser.phase.__class__.__name__, self.__class__.__name__, function.__name__, info)) return function(self, *args, **kwargs) else: return function(self, *args, **kwargs) return wrapped def getMetaclass(use_metaclass, metaclass_func): if use_metaclass: return method_decorator_metaclass(metaclass_func) else: return type # pylint:disable=unused-argument class Phase(with_metaclass(getMetaclass(debug, log))): """Base class for helper object that implements each phase of processing """ __slots__ = ("parser", "tree", "__startTagCache", "__endTagCache") def __init__(self, parser, tree): self.parser = parser self.tree = tree self.__startTagCache = {} self.__endTagCache = {} def processEOF(self): raise NotImplementedError def processComment(self, token): # For most phases the following is correct. Where it's not it will be # overridden. self.tree.insertComment(token, self.tree.openElements[-1]) def processDoctype(self, token): self.parser.parseError("unexpected-doctype") def processCharacters(self, token): self.tree.insertText(token["data"]) def processSpaceCharacters(self, token): self.tree.insertText(token["data"]) def processStartTag(self, token): # Note the caching is done here rather than BoundMethodDispatcher as doing it there # requires a circular reference to the Phase, and this ends up with a significant # (CPython 2.7, 3.8) GC cost when parsing many short inputs name = token["name"] # In Py2, using `in` is quicker in general than try/except KeyError # In Py3, `in` is quicker when there are few cache hits (typically short inputs) if name in self.__startTagCache: func = self.__startTagCache[name] else: func = self.__startTagCache[name] = self.startTagHandler[name] # bound the cache size in case we get loads of unknown tags while len(self.__startTagCache) > len(self.startTagHandler) * 1.1: # this makes the eviction policy random on Py < 3.7 and FIFO >= 3.7 self.__startTagCache.pop(next(iter(self.__startTagCache))) return func(token) def startTagHtml(self, token): if not self.parser.firstStartTag and token["name"] == "html": self.parser.parseError("non-html-root") # XXX Need a check here to see if the first start tag token emitted is # this token... If it's not, invoke self.parser.parseError(). for attr, value in token["data"].items(): if attr not in self.tree.openElements[0].attributes: self.tree.openElements[0].attributes[attr] = value self.parser.firstStartTag = False def processEndTag(self, token): # Note the caching is done here rather than BoundMethodDispatcher as doing it there # requires a circular reference to the Phase, and this ends up with a significant # (CPython 2.7, 3.8) GC cost when parsing many short inputs name = token["name"] # In Py2, using `in` is quicker in general than try/except KeyError # In Py3, `in` is quicker when there are few cache hits (typically short inputs) if name in self.__endTagCache: func = self.__endTagCache[name] else: func = self.__endTagCache[name] = self.endTagHandler[name] # bound the cache size in case we get loads of unknown tags while len(self.__endTagCache) > len(self.endTagHandler) * 1.1: # this makes the eviction policy random on Py < 3.7 and FIFO >= 3.7 self.__endTagCache.pop(next(iter(self.__endTagCache))) return func(token) class InitialPhase(Phase): __slots__ = tuple() def processSpaceCharacters(self, token): pass def processComment(self, token): self.tree.insertComment(token, self.tree.document) def processDoctype(self, token): name = token["name"] publicId = token["publicId"] systemId = token["systemId"] correct = token["correct"] if (name != "html" or publicId is not None or systemId is not None and systemId != "about:legacy-compat"): self.parser.parseError("unknown-doctype") if publicId is None: publicId = "" self.tree.insertDoctype(token) if publicId != "": publicId = publicId.translate(asciiUpper2Lower) if (not correct or token["name"] != "html" or publicId.startswith( ("+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//")) or publicId in ("-//w3o//dtd w3 html strict 3.0//en//", "-/w3c/dtd html 4.0 transitional/en", "html") or publicId.startswith( ("-//w3c//dtd html 4.01 frameset//", "-//w3c//dtd html 4.01 transitional//")) and systemId is None or systemId and systemId.lower() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"): self.parser.compatMode = "quirks" elif (publicId.startswith( ("-//w3c//dtd xhtml 1.0 frameset//", "-//w3c//dtd xhtml 1.0 transitional//")) or publicId.startswith( ("-//w3c//dtd html 4.01 frameset//", "-//w3c//dtd html 4.01 transitional//")) and systemId is not None): self.parser.compatMode = "limited quirks" self.parser.phase = self.parser.phases["beforeHtml"] def anythingElse(self): self.parser.compatMode = "quirks" self.parser.phase = self.parser.phases["beforeHtml"] def processCharacters(self, token): self.parser.parseError("expected-doctype-but-got-chars") self.anythingElse() return token def processStartTag(self, token): self.parser.parseError("expected-doctype-but-got-start-tag", {"name": token["name"]}) self.anythingElse() return token def processEndTag(self, token): self.parser.parseError("expected-doctype-but-got-end-tag", {"name": token["name"]}) self.anythingElse() return token def processEOF(self): self.parser.parseError("expected-doctype-but-got-eof") self.anythingElse() return True class BeforeHtmlPhase(Phase): __slots__ = tuple() # helper methods def insertHtmlElement(self): self.tree.insertRoot(impliedTagToken("html", "StartTag")) self.parser.phase = self.parser.phases["beforeHead"] # other def processEOF(self): self.insertHtmlElement() return True def processComment(self, token): self.tree.insertComment(token, self.tree.document) def processSpaceCharacters(self, token): pass def processCharacters(self, token): self.insertHtmlElement() return token def processStartTag(self, token): if token["name"] == "html": self.parser.firstStartTag = True self.insertHtmlElement() return token def processEndTag(self, token): if token["name"] not in ("head", "body", "html", "br"): self.parser.parseError("unexpected-end-tag-before-html", {"name": token["name"]}) else: self.insertHtmlElement() return token class BeforeHeadPhase(Phase): __slots__ = tuple() def processEOF(self): self.startTagHead(impliedTagToken("head", "StartTag")) return True def processSpaceCharacters(self, token): pass def processCharacters(self, token): self.startTagHead(impliedTagToken("head", "StartTag")) return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagHead(self, token): self.tree.insertElement(token) self.tree.headPointer = self.tree.openElements[-1] self.parser.phase = self.parser.phases["inHead"] def startTagOther(self, token): self.startTagHead(impliedTagToken("head", "StartTag")) return token def endTagImplyHead(self, token): self.startTagHead(impliedTagToken("head", "StartTag")) return token def endTagOther(self, token): self.parser.parseError("end-tag-after-implied-root", {"name": token["name"]}) startTagHandler = _utils.MethodDispatcher([ ("html", startTagHtml), ("head", startTagHead) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ (("head", "body", "html", "br"), endTagImplyHead) ]) endTagHandler.default = endTagOther class InHeadPhase(Phase): __slots__ = tuple() # the real thing def processEOF(self): self.anythingElse() return True def processCharacters(self, token): self.anythingElse() return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagHead(self, token): self.parser.parseError("two-heads-are-not-better-than-one") def startTagBaseLinkCommand(self, token): self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True def startTagMeta(self, token): self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True attributes = token["data"] if self.parser.tokenizer.stream.charEncoding[1] == "tentative": if "charset" in attributes: self.parser.tokenizer.stream.changeEncoding(attributes["charset"]) elif ("content" in attributes and "http-equiv" in attributes and attributes["http-equiv"].lower() == "content-type"): # Encoding it as UTF-8 here is a hack, as really we should pass # the abstract Unicode string, and just use the # ContentAttrParser on that, but using UTF-8 allows all chars # to be encoded and as a ASCII-superset works. data = _inputstream.EncodingBytes(attributes["content"].encode("utf-8")) parser = _inputstream.ContentAttrParser(data) codec = parser.parse() self.parser.tokenizer.stream.changeEncoding(codec) def startTagTitle(self, token): self.parser.parseRCDataRawtext(token, "RCDATA") def startTagNoFramesStyle(self, token): # Need to decide whether to implement the scripting-disabled case self.parser.parseRCDataRawtext(token, "RAWTEXT") def startTagNoscript(self, token): if self.parser.scripting: self.parser.parseRCDataRawtext(token, "RAWTEXT") else: self.tree.insertElement(token) self.parser.phase = self.parser.phases["inHeadNoscript"] def startTagScript(self, token): self.tree.insertElement(token) self.parser.tokenizer.state = self.parser.tokenizer.scriptDataState self.parser.originalPhase = self.parser.phase self.parser.phase = self.parser.phases["text"] def startTagOther(self, token): self.anythingElse() return token def endTagHead(self, token): node = self.parser.tree.openElements.pop() assert node.name == "head", "Expected head got %s" % node.name self.parser.phase = self.parser.phases["afterHead"] def endTagHtmlBodyBr(self, token): self.anythingElse() return token def endTagOther(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def anythingElse(self): self.endTagHead(impliedTagToken("head")) startTagHandler = _utils.MethodDispatcher([ ("html", startTagHtml), ("title", startTagTitle), (("noframes", "style"), startTagNoFramesStyle), ("noscript", startTagNoscript), ("script", startTagScript), (("base", "basefont", "bgsound", "command", "link"), startTagBaseLinkCommand), ("meta", startTagMeta), ("head", startTagHead) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("head", endTagHead), (("br", "html", "body"), endTagHtmlBodyBr) ]) endTagHandler.default = endTagOther class InHeadNoscriptPhase(Phase): __slots__ = tuple() def processEOF(self): self.parser.parseError("eof-in-head-noscript") self.anythingElse() return True def processComment(self, token): return self.parser.phases["inHead"].processComment(token) def processCharacters(self, token): self.parser.parseError("char-in-head-noscript") self.anythingElse() return token def processSpaceCharacters(self, token): return self.parser.phases["inHead"].processSpaceCharacters(token) def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagBaseLinkCommand(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagHeadNoscript(self, token): self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) def startTagOther(self, token): self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) self.anythingElse() return token def endTagNoscript(self, token): node = self.parser.tree.openElements.pop() assert node.name == "noscript", "Expected noscript got %s" % node.name self.parser.phase = self.parser.phases["inHead"] def endTagBr(self, token): self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) self.anythingElse() return token def endTagOther(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def anythingElse(self): # Caller must raise parse error first! self.endTagNoscript(impliedTagToken("noscript")) startTagHandler = _utils.MethodDispatcher([ ("html", startTagHtml), (("basefont", "bgsound", "link", "meta", "noframes", "style"), startTagBaseLinkCommand), (("head", "noscript"), startTagHeadNoscript), ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("noscript", endTagNoscript), ("br", endTagBr), ]) endTagHandler.default = endTagOther class AfterHeadPhase(Phase): __slots__ = tuple() def processEOF(self): self.anythingElse() return True def processCharacters(self, token): self.anythingElse() return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagBody(self, token): self.parser.framesetOK = False self.tree.insertElement(token) self.parser.phase = self.parser.phases["inBody"] def startTagFrameset(self, token): self.tree.insertElement(token) self.parser.phase = self.parser.phases["inFrameset"] def startTagFromHead(self, token): self.parser.parseError("unexpected-start-tag-out-of-my-head", {"name": token["name"]}) self.tree.openElements.append(self.tree.headPointer) self.parser.phases["inHead"].processStartTag(token) for node in self.tree.openElements[::-1]: if node.name == "head": self.tree.openElements.remove(node) break def startTagHead(self, token): self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) def startTagOther(self, token): self.anythingElse() return token def endTagHtmlBodyBr(self, token): self.anythingElse() return token def endTagOther(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def anythingElse(self): self.tree.insertElement(impliedTagToken("body", "StartTag")) self.parser.phase = self.parser.phases["inBody"] self.parser.framesetOK = True startTagHandler = _utils.MethodDispatcher([ ("html", startTagHtml), ("body", startTagBody), ("frameset", startTagFrameset), (("base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "title"), startTagFromHead), ("head", startTagHead) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([(("body", "html", "br"), endTagHtmlBodyBr)]) endTagHandler.default = endTagOther class InBodyPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#parsing-main-inbody # the really-really-really-very crazy mode __slots__ = ("processSpaceCharacters",) def __init__(self, *args, **kwargs): super(InBodyPhase, self).__init__(*args, **kwargs) # Set this to the default handler self.processSpaceCharacters = self.processSpaceCharactersNonPre def isMatchingFormattingElement(self, node1, node2): return (node1.name == node2.name and node1.namespace == node2.namespace and node1.attributes == node2.attributes) # helper def addFormattingElement(self, token): self.tree.insertElement(token) element = self.tree.openElements[-1] matchingElements = [] for node in self.tree.activeFormattingElements[::-1]: if node is Marker: break elif self.isMatchingFormattingElement(node, element): matchingElements.append(node) assert len(matchingElements) <= 3 if len(matchingElements) == 3: self.tree.activeFormattingElements.remove(matchingElements[-1]) self.tree.activeFormattingElements.append(element) # the real deal def processEOF(self): allowed_elements = frozenset(("dd", "dt", "li", "p", "tbody", "td", "tfoot", "th", "thead", "tr", "body", "html")) for node in self.tree.openElements[::-1]: if node.name not in allowed_elements: self.parser.parseError("expected-closing-tag-but-got-eof") break # Stop parsing def processSpaceCharactersDropNewline(self, token): # Sometimes (start of <pre>, <listing>, and <textarea> blocks) we # want to drop leading newlines data = token["data"] self.processSpaceCharacters = self.processSpaceCharactersNonPre if (data.startswith("\n") and self.tree.openElements[-1].name in ("pre", "listing", "textarea") and not self.tree.openElements[-1].hasContent()): data = data[1:] if data: self.tree.reconstructActiveFormattingElements() self.tree.insertText(data) def processCharacters(self, token): if token["data"] == "\u0000": # The tokenizer should always emit null on its own return self.tree.reconstructActiveFormattingElements() self.tree.insertText(token["data"]) # This must be bad for performance if (self.parser.framesetOK and any([char not in spaceCharacters for char in token["data"]])): self.parser.framesetOK = False def processSpaceCharactersNonPre(self, token): self.tree.reconstructActiveFormattingElements() self.tree.insertText(token["data"]) def startTagProcessInHead(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagBody(self, token): self.parser.parseError("unexpected-start-tag", {"name": "body"}) if (len(self.tree.openElements) == 1 or self.tree.openElements[1].name != "body"): assert self.parser.innerHTML else: self.parser.framesetOK = False for attr, value in token["data"].items(): if attr not in self.tree.openElements[1].attributes: self.tree.openElements[1].attributes[attr] = value def startTagFrameset(self, token): self.parser.parseError("unexpected-start-tag", {"name": "frameset"}) if (len(self.tree.openElements) == 1 or self.tree.openElements[1].name != "body"): assert self.parser.innerHTML elif not self.parser.framesetOK: pass else: if self.tree.openElements[1].parent: self.tree.openElements[1].parent.removeChild(self.tree.openElements[1]) while self.tree.openElements[-1].name != "html": self.tree.openElements.pop() self.tree.insertElement(token) self.parser.phase = self.parser.phases["inFrameset"] def startTagCloseP(self, token): if self.tree.elementInScope("p", variant="button"): self.endTagP(impliedTagToken("p")) self.tree.insertElement(token) def startTagPreListing(self, token): if self.tree.elementInScope("p", variant="button"): self.endTagP(impliedTagToken("p")) self.tree.insertElement(token) self.parser.framesetOK = False self.processSpaceCharacters = self.processSpaceCharactersDropNewline def startTagForm(self, token): if self.tree.formPointer: self.parser.parseError("unexpected-start-tag", {"name": "form"}) else: if self.tree.elementInScope("p", variant="button"): self.endTagP(impliedTagToken("p")) self.tree.insertElement(token) self.tree.formPointer = self.tree.openElements[-1] def startTagListItem(self, token): self.parser.framesetOK = False stopNamesMap = {"li": ["li"], "dt": ["dt", "dd"], "dd": ["dt", "dd"]} stopNames = stopNamesMap[token["name"]] for node in reversed(self.tree.openElements): if node.name in stopNames: self.parser.phase.processEndTag( impliedTagToken(node.name, "EndTag")) break if (node.nameTuple in specialElements and node.name not in ("address", "div", "p")): break if self.tree.elementInScope("p", variant="button"): self.parser.phase.processEndTag( impliedTagToken("p", "EndTag")) self.tree.insertElement(token) def startTagPlaintext(self, token): if self.tree.elementInScope("p", variant="button"): self.endTagP(impliedTagToken("p")) self.tree.insertElement(token) self.parser.tokenizer.state = self.parser.tokenizer.plaintextState def startTagHeading(self, token): if self.tree.elementInScope("p", variant="button"): self.endTagP(impliedTagToken("p")) if self.tree.openElements[-1].name in headingElements: self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) self.tree.openElements.pop() self.tree.insertElement(token) def startTagA(self, token): afeAElement = self.tree.elementInActiveFormattingElements("a") if afeAElement: self.parser.parseError("unexpected-start-tag-implies-end-tag", {"startName": "a", "endName": "a"}) self.endTagFormatting(impliedTagToken("a")) if afeAElement in self.tree.openElements: self.tree.openElements.remove(afeAElement) if afeAElement in self.tree.activeFormattingElements: self.tree.activeFormattingElements.remove(afeAElement) self.tree.reconstructActiveFormattingElements() self.addFormattingElement(token) def startTagFormatting(self, token): self.tree.reconstructActiveFormattingElements() self.addFormattingElement(token) def startTagNobr(self, token): self.tree.reconstructActiveFormattingElements() if self.tree.elementInScope("nobr"): self.parser.parseError("unexpected-start-tag-implies-end-tag", {"startName": "nobr", "endName": "nobr"}) self.processEndTag(impliedTagToken("nobr")) # XXX Need tests that trigger the following self.tree.reconstructActiveFormattingElements() self.addFormattingElement(token) def startTagButton(self, token): if self.tree.elementInScope("button"): self.parser.parseError("unexpected-start-tag-implies-end-tag", {"startName": "button", "endName": "button"}) self.processEndTag(impliedTagToken("button")) return token else: self.tree.reconstructActiveFormattingElements() self.tree.insertElement(token) self.parser.framesetOK = False def startTagAppletMarqueeObject(self, token): self.tree.reconstructActiveFormattingElements() self.tree.insertElement(token) self.tree.activeFormattingElements.append(Marker) self.parser.framesetOK = False def startTagXmp(self, token): if self.tree.elementInScope("p", variant="button"): self.endTagP(impliedTagToken("p")) self.tree.reconstructActiveFormattingElements() self.parser.framesetOK = False self.parser.parseRCDataRawtext(token, "RAWTEXT") def startTagTable(self, token): if self.parser.compatMode != "quirks": if self.tree.elementInScope("p", variant="button"): self.processEndTag(impliedTagToken("p")) self.tree.insertElement(token) self.parser.framesetOK = False self.parser.phase = self.parser.phases["inTable"] def startTagVoidFormatting(self, token): self.tree.reconstructActiveFormattingElements() self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True self.parser.framesetOK = False def startTagInput(self, token): framesetOK = self.parser.framesetOK self.startTagVoidFormatting(token) if ("type" in token["data"] and token["data"]["type"].translate(asciiUpper2Lower) == "hidden"): # input type=hidden doesn't change framesetOK self.parser.framesetOK = framesetOK def startTagParamSource(self, token): self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True def startTagHr(self, token): if self.tree.elementInScope("p", variant="button"): self.endTagP(impliedTagToken("p")) self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True self.parser.framesetOK = False def startTagImage(self, token): # No really... self.parser.parseError("unexpected-start-tag-treated-as", {"originalName": "image", "newName": "img"}) self.processStartTag(impliedTagToken("img", "StartTag", attributes=token["data"], selfClosing=token["selfClosing"])) def startTagIsIndex(self, token): self.parser.parseError("deprecated-tag", {"name": "isindex"}) if self.tree.formPointer: return form_attrs = {} if "action" in token["data"]: form_attrs["action"] = token["data"]["action"] self.processStartTag(impliedTagToken("form", "StartTag", attributes=form_attrs)) self.processStartTag(impliedTagToken("hr", "StartTag")) self.processStartTag(impliedTagToken("label", "StartTag")) # XXX Localization ... if "prompt" in token["data"]: prompt = token["data"]["prompt"] else: prompt = "This is a searchable index. Enter search keywords: " self.processCharacters( {"type": tokenTypes["Characters"], "data": prompt}) attributes = token["data"].copy() if "action" in attributes: del attributes["action"] if "prompt" in attributes: del attributes["prompt"] attributes["name"] = "isindex" self.processStartTag(impliedTagToken("input", "StartTag", attributes=attributes, selfClosing=token["selfClosing"])) self.processEndTag(impliedTagToken("label")) self.processStartTag(impliedTagToken("hr", "StartTag")) self.processEndTag(impliedTagToken("form")) def startTagTextarea(self, token): self.tree.insertElement(token) self.parser.tokenizer.state = self.parser.tokenizer.rcdataState self.processSpaceCharacters = self.processSpaceCharactersDropNewline self.parser.framesetOK = False def startTagIFrame(self, token): self.parser.framesetOK = False self.startTagRawtext(token) def startTagNoscript(self, token): if self.parser.scripting: self.startTagRawtext(token) else: self.startTagOther(token) def startTagRawtext(self, token): """iframe, noembed noframes, noscript(if scripting enabled)""" self.parser.parseRCDataRawtext(token, "RAWTEXT") def startTagOpt(self, token): if self.tree.openElements[-1].name == "option": self.parser.phase.processEndTag(impliedTagToken("option")) self.tree.reconstructActiveFormattingElements() self.parser.tree.insertElement(token) def startTagSelect(self, token): self.tree.reconstructActiveFormattingElements() self.tree.insertElement(token) self.parser.framesetOK = False if self.parser.phase in (self.parser.phases["inTable"], self.parser.phases["inCaption"], self.parser.phases["inColumnGroup"], self.parser.phases["inTableBody"], self.parser.phases["inRow"], self.parser.phases["inCell"]): self.parser.phase = self.parser.phases["inSelectInTable"] else: self.parser.phase = self.parser.phases["inSelect"] def startTagRpRt(self, token): if self.tree.elementInScope("ruby"): self.tree.generateImpliedEndTags() if self.tree.openElements[-1].name != "ruby": self.parser.parseError() self.tree.insertElement(token) def startTagMath(self, token): self.tree.reconstructActiveFormattingElements() self.parser.adjustMathMLAttributes(token) self.parser.adjustForeignAttributes(token) token["namespace"] = namespaces["mathml"] self.tree.insertElement(token) # Need to get the parse error right for the case where the token # has a namespace not equal to the xmlns attribute if token["selfClosing"]: self.tree.openElements.pop() token["selfClosingAcknowledged"] = True def startTagSvg(self, token): self.tree.reconstructActiveFormattingElements() self.parser.adjustSVGAttributes(token) self.parser.adjustForeignAttributes(token) token["namespace"] = namespaces["svg"] self.tree.insertElement(token) # Need to get the parse error right for the case where the token # has a namespace not equal to the xmlns attribute if token["selfClosing"]: self.tree.openElements.pop() token["selfClosingAcknowledged"] = True def startTagMisplaced(self, token): """ Elements that should be children of other elements that have a different insertion mode; here they are ignored "caption", "col", "colgroup", "frame", "frameset", "head", "option", "optgroup", "tbody", "td", "tfoot", "th", "thead", "tr", "noscript" """ self.parser.parseError("unexpected-start-tag-ignored", {"name": token["name"]}) def startTagOther(self, token): self.tree.reconstructActiveFormattingElements() self.tree.insertElement(token) def endTagP(self, token): if not self.tree.elementInScope("p", variant="button"): self.startTagCloseP(impliedTagToken("p", "StartTag")) self.parser.parseError("unexpected-end-tag", {"name": "p"}) self.endTagP(impliedTagToken("p", "EndTag")) else: self.tree.generateImpliedEndTags("p") if self.tree.openElements[-1].name != "p": self.parser.parseError("unexpected-end-tag", {"name": "p"}) node = self.tree.openElements.pop() while node.name != "p": node = self.tree.openElements.pop() def endTagBody(self, token): if not self.tree.elementInScope("body"): self.parser.parseError() return elif self.tree.openElements[-1].name != "body": for node in self.tree.openElements[2:]: if node.name not in frozenset(("dd", "dt", "li", "optgroup", "option", "p", "rp", "rt", "tbody", "td", "tfoot", "th", "thead", "tr", "body", "html")): # Not sure this is the correct name for the parse error self.parser.parseError( "expected-one-end-tag-but-got-another", {"gotName": "body", "expectedName": node.name}) break self.parser.phase = self.parser.phases["afterBody"] def endTagHtml(self, token): # We repeat the test for the body end tag token being ignored here if self.tree.elementInScope("body"): self.endTagBody(impliedTagToken("body")) return token def endTagBlock(self, token): # Put us back in the right whitespace handling mode if token["name"] == "pre": self.processSpaceCharacters = self.processSpaceCharactersNonPre inScope = self.tree.elementInScope(token["name"]) if inScope: self.tree.generateImpliedEndTags() if self.tree.openElements[-1].name != token["name"]: self.parser.parseError("end-tag-too-early", {"name": token["name"]}) if inScope: node = self.tree.openElements.pop() while node.name != token["name"]: node = self.tree.openElements.pop() def endTagForm(self, token): node = self.tree.formPointer self.tree.formPointer = None if node is None or not self.tree.elementInScope(node): self.parser.parseError("unexpected-end-tag", {"name": "form"}) else: self.tree.generateImpliedEndTags() if self.tree.openElements[-1] != node: self.parser.parseError("end-tag-too-early-ignored", {"name": "form"}) self.tree.openElements.remove(node) def endTagListItem(self, token): if token["name"] == "li": variant = "list" else: variant = None if not self.tree.elementInScope(token["name"], variant=variant): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) else: self.tree.generateImpliedEndTags(exclude=token["name"]) if self.tree.openElements[-1].name != token["name"]: self.parser.parseError( "end-tag-too-early", {"name": token["name"]}) node = self.tree.openElements.pop() while node.name != token["name"]: node = self.tree.openElements.pop() def endTagHeading(self, token): for item in headingElements: if self.tree.elementInScope(item): self.tree.generateImpliedEndTags() break if self.tree.openElements[-1].name != token["name"]: self.parser.parseError("end-tag-too-early", {"name": token["name"]}) for item in headingElements: if self.tree.elementInScope(item): item = self.tree.openElements.pop() while item.name not in headingElements: item = self.tree.openElements.pop() break def endTagFormatting(self, token): """The much-feared adoption agency algorithm""" # http://svn.whatwg.org/webapps/complete.html#adoptionAgency revision 7867 # XXX Better parseError messages appreciated. # Step 1 outerLoopCounter = 0 # Step 2 while outerLoopCounter < 8: # Step 3 outerLoopCounter += 1 # Step 4: # Let the formatting element be the last element in # the list of active formatting elements that: # - is between the end of the list and the last scope # marker in the list, if any, or the start of the list # otherwise, and # - has the same tag name as the token. formattingElement = self.tree.elementInActiveFormattingElements( token["name"]) if (not formattingElement or (formattingElement in self.tree.openElements and not self.tree.elementInScope(formattingElement.name))): # If there is no such node, then abort these steps # and instead act as described in the "any other # end tag" entry below. self.endTagOther(token) return # Otherwise, if there is such a node, but that node is # not in the stack of open elements, then this is a # parse error; remove the element from the list, and # abort these steps. elif formattingElement not in self.tree.openElements: self.parser.parseError("adoption-agency-1.2", {"name": token["name"]}) self.tree.activeFormattingElements.remove(formattingElement) return # Otherwise, if there is such a node, and that node is # also in the stack of open elements, but the element # is not in scope, then this is a parse error; ignore # the token, and abort these steps. elif not self.tree.elementInScope(formattingElement.name): self.parser.parseError("adoption-agency-4.4", {"name": token["name"]}) return # Otherwise, there is a formatting element and that # element is in the stack and is in scope. If the # element is not the current node, this is a parse # error. In any case, proceed with the algorithm as # written in the following steps. else: if formattingElement != self.tree.openElements[-1]: self.parser.parseError("adoption-agency-1.3", {"name": token["name"]}) # Step 5: # Let the furthest block be the topmost node in the # stack of open elements that is lower in the stack # than the formatting element, and is an element in # the special category. There might not be one. afeIndex = self.tree.openElements.index(formattingElement) furthestBlock = None for element in self.tree.openElements[afeIndex:]: if element.nameTuple in specialElements: furthestBlock = element break # Step 6: # If there is no furthest block, then the UA must # first pop all the nodes from the bottom of the stack # of open elements, from the current node up to and # including the formatting element, then remove the # formatting element from the list of active # formatting elements, and finally abort these steps. if furthestBlock is None: element = self.tree.openElements.pop() while element != formattingElement: element = self.tree.openElements.pop() self.tree.activeFormattingElements.remove(element) return # Step 7 commonAncestor = self.tree.openElements[afeIndex - 1] # Step 8: # The bookmark is supposed to help us identify where to reinsert # nodes in step 15. We have to ensure that we reinsert nodes after # the node before the active formatting element. Note the bookmark # can move in step 9.7 bookmark = self.tree.activeFormattingElements.index(formattingElement) # Step 9 lastNode = node = furthestBlock innerLoopCounter = 0 index = self.tree.openElements.index(node) while innerLoopCounter < 3: innerLoopCounter += 1 # Node is element before node in open elements index -= 1 node = self.tree.openElements[index] if node not in self.tree.activeFormattingElements: self.tree.openElements.remove(node) continue # Step 9.6 if node == formattingElement: break # Step 9.7 if lastNode == furthestBlock: bookmark = self.tree.activeFormattingElements.index(node) + 1 # Step 9.8 clone = node.cloneNode() # Replace node with clone self.tree.activeFormattingElements[ self.tree.activeFormattingElements.index(node)] = clone self.tree.openElements[ self.tree.openElements.index(node)] = clone node = clone # Step 9.9 # Remove lastNode from its parents, if any if lastNode.parent: lastNode.parent.removeChild(lastNode) node.appendChild(lastNode) # Step 9.10 lastNode = node # Step 10 # Foster parent lastNode if commonAncestor is a # table, tbody, tfoot, thead, or tr we need to foster # parent the lastNode if lastNode.parent: lastNode.parent.removeChild(lastNode) if commonAncestor.name in frozenset(("table", "tbody", "tfoot", "thead", "tr")): parent, insertBefore = self.tree.getTableMisnestedNodePosition() parent.insertBefore(lastNode, insertBefore) else: commonAncestor.appendChild(lastNode) # Step 11 clone = formattingElement.cloneNode() # Step 12 furthestBlock.reparentChildren(clone) # Step 13 furthestBlock.appendChild(clone) # Step 14 self.tree.activeFormattingElements.remove(formattingElement) self.tree.activeFormattingElements.insert(bookmark, clone) # Step 15 self.tree.openElements.remove(formattingElement) self.tree.openElements.insert( self.tree.openElements.index(furthestBlock) + 1, clone) def endTagAppletMarqueeObject(self, token): if self.tree.elementInScope(token["name"]): self.tree.generateImpliedEndTags() if self.tree.openElements[-1].name != token["name"]: self.parser.parseError("end-tag-too-early", {"name": token["name"]}) if self.tree.elementInScope(token["name"]): element = self.tree.openElements.pop() while element.name != token["name"]: element = self.tree.openElements.pop() self.tree.clearActiveFormattingElements() def endTagBr(self, token): self.parser.parseError("unexpected-end-tag-treated-as", {"originalName": "br", "newName": "br element"}) self.tree.reconstructActiveFormattingElements() self.tree.insertElement(impliedTagToken("br", "StartTag")) self.tree.openElements.pop() def endTagOther(self, token): for node in self.tree.openElements[::-1]: if node.name == token["name"]: self.tree.generateImpliedEndTags(exclude=token["name"]) if self.tree.openElements[-1].name != token["name"]: self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) while self.tree.openElements.pop() != node: pass break else: if node.nameTuple in specialElements: self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) break startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), (("base", "basefont", "bgsound", "command", "link", "meta", "script", "style", "title"), startTagProcessInHead), ("body", startTagBody), ("frameset", startTagFrameset), (("address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "main", "menu", "nav", "ol", "p", "section", "summary", "ul"), startTagCloseP), (headingElements, startTagHeading), (("pre", "listing"), startTagPreListing), ("form", startTagForm), (("li", "dd", "dt"), startTagListItem), ("plaintext", startTagPlaintext), ("a", startTagA), (("b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u"), startTagFormatting), ("nobr", startTagNobr), ("button", startTagButton), (("applet", "marquee", "object"), startTagAppletMarqueeObject), ("xmp", startTagXmp), ("table", startTagTable), (("area", "br", "embed", "img", "keygen", "wbr"), startTagVoidFormatting), (("param", "source", "track"), startTagParamSource), ("input", startTagInput), ("hr", startTagHr), ("image", startTagImage), ("isindex", startTagIsIndex), ("textarea", startTagTextarea), ("iframe", startTagIFrame), ("noscript", startTagNoscript), (("noembed", "noframes"), startTagRawtext), ("select", startTagSelect), (("rp", "rt"), startTagRpRt), (("option", "optgroup"), startTagOpt), (("math"), startTagMath), (("svg"), startTagSvg), (("caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr"), startTagMisplaced) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("body", endTagBody), ("html", endTagHtml), (("address", "article", "aside", "blockquote", "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "main", "menu", "nav", "ol", "pre", "section", "summary", "ul"), endTagBlock), ("form", endTagForm), ("p", endTagP), (("dd", "dt", "li"), endTagListItem), (headingElements, endTagHeading), (("a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"), endTagFormatting), (("applet", "marquee", "object"), endTagAppletMarqueeObject), ("br", endTagBr), ]) endTagHandler.default = endTagOther class TextPhase(Phase): __slots__ = tuple() def processCharacters(self, token): self.tree.insertText(token["data"]) def processEOF(self): self.parser.parseError("expected-named-closing-tag-but-got-eof", {"name": self.tree.openElements[-1].name}) self.tree.openElements.pop() self.parser.phase = self.parser.originalPhase return True def startTagOther(self, token): assert False, "Tried to process start tag %s in RCDATA/RAWTEXT mode" % token['name'] def endTagScript(self, token): node = self.tree.openElements.pop() assert node.name == "script" self.parser.phase = self.parser.originalPhase # The rest of this method is all stuff that only happens if # document.write works def endTagOther(self, token): self.tree.openElements.pop() self.parser.phase = self.parser.originalPhase startTagHandler = _utils.MethodDispatcher([]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("script", endTagScript)]) endTagHandler.default = endTagOther class InTablePhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-table __slots__ = tuple() # helper methods def clearStackToTableContext(self): # "clear the stack back to a table context" while self.tree.openElements[-1].name not in ("table", "html"): # self.parser.parseError("unexpected-implied-end-tag-in-table", # {"name": self.tree.openElements[-1].name}) self.tree.openElements.pop() # When the current node is <html> it's an innerHTML case # processing methods def processEOF(self): if self.tree.openElements[-1].name != "html": self.parser.parseError("eof-in-table") else: assert self.parser.innerHTML # Stop parsing def processSpaceCharacters(self, token): originalPhase = self.parser.phase self.parser.phase = self.parser.phases["inTableText"] self.parser.phase.originalPhase = originalPhase self.parser.phase.processSpaceCharacters(token) def processCharacters(self, token): originalPhase = self.parser.phase self.parser.phase = self.parser.phases["inTableText"] self.parser.phase.originalPhase = originalPhase self.parser.phase.processCharacters(token) def insertText(self, token): # If we get here there must be at least one non-whitespace character # Do the table magic! self.tree.insertFromTable = True self.parser.phases["inBody"].processCharacters(token) self.tree.insertFromTable = False def startTagCaption(self, token): self.clearStackToTableContext() self.tree.activeFormattingElements.append(Marker) self.tree.insertElement(token) self.parser.phase = self.parser.phases["inCaption"] def startTagColgroup(self, token): self.clearStackToTableContext() self.tree.insertElement(token) self.parser.phase = self.parser.phases["inColumnGroup"] def startTagCol(self, token): self.startTagColgroup(impliedTagToken("colgroup", "StartTag")) return token def startTagRowGroup(self, token): self.clearStackToTableContext() self.tree.insertElement(token) self.parser.phase = self.parser.phases["inTableBody"] def startTagImplyTbody(self, token): self.startTagRowGroup(impliedTagToken("tbody", "StartTag")) return token def startTagTable(self, token): self.parser.parseError("unexpected-start-tag-implies-end-tag", {"startName": "table", "endName": "table"}) self.parser.phase.processEndTag(impliedTagToken("table")) if not self.parser.innerHTML: return token def startTagStyleScript(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagInput(self, token): if ("type" in token["data"] and token["data"]["type"].translate(asciiUpper2Lower) == "hidden"): self.parser.parseError("unexpected-hidden-input-in-table") self.tree.insertElement(token) # XXX associate with form self.tree.openElements.pop() else: self.startTagOther(token) def startTagForm(self, token): self.parser.parseError("unexpected-form-in-table") if self.tree.formPointer is None: self.tree.insertElement(token) self.tree.formPointer = self.tree.openElements[-1] self.tree.openElements.pop() def startTagOther(self, token): self.parser.parseError("unexpected-start-tag-implies-table-voodoo", {"name": token["name"]}) # Do the table magic! self.tree.insertFromTable = True self.parser.phases["inBody"].processStartTag(token) self.tree.insertFromTable = False def endTagTable(self, token): if self.tree.elementInScope("table", variant="table"): self.tree.generateImpliedEndTags() if self.tree.openElements[-1].name != "table": self.parser.parseError("end-tag-too-early-named", {"gotName": "table", "expectedName": self.tree.openElements[-1].name}) while self.tree.openElements[-1].name != "table": self.tree.openElements.pop() self.tree.openElements.pop() self.parser.resetInsertionMode() else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def endTagIgnore(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def endTagOther(self, token): self.parser.parseError("unexpected-end-tag-implies-table-voodoo", {"name": token["name"]}) # Do the table magic! self.tree.insertFromTable = True self.parser.phases["inBody"].processEndTag(token) self.tree.insertFromTable = False startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), ("caption", startTagCaption), ("colgroup", startTagColgroup), ("col", startTagCol), (("tbody", "tfoot", "thead"), startTagRowGroup), (("td", "th", "tr"), startTagImplyTbody), ("table", startTagTable), (("style", "script"), startTagStyleScript), ("input", startTagInput), ("form", startTagForm) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("table", endTagTable), (("body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"), endTagIgnore) ]) endTagHandler.default = endTagOther class InTableTextPhase(Phase): __slots__ = ("originalPhase", "characterTokens") def __init__(self, *args, **kwargs): super(InTableTextPhase, self).__init__(*args, **kwargs) self.originalPhase = None self.characterTokens = [] def flushCharacters(self): data = "".join([item["data"] for item in self.characterTokens]) if any([item not in spaceCharacters for item in data]): token = {"type": tokenTypes["Characters"], "data": data} self.parser.phases["inTable"].insertText(token) elif data: self.tree.insertText(data) self.characterTokens = [] def processComment(self, token): self.flushCharacters() self.parser.phase = self.originalPhase return token def processEOF(self): self.flushCharacters() self.parser.phase = self.originalPhase return True def processCharacters(self, token): if token["data"] == "\u0000": return self.characterTokens.append(token) def processSpaceCharacters(self, token): # pretty sure we should never reach here self.characterTokens.append(token) # assert False def processStartTag(self, token): self.flushCharacters() self.parser.phase = self.originalPhase return token def processEndTag(self, token): self.flushCharacters() self.parser.phase = self.originalPhase return token class InCaptionPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-caption __slots__ = tuple() def ignoreEndTagCaption(self): return not self.tree.elementInScope("caption", variant="table") def processEOF(self): self.parser.phases["inBody"].processEOF() def processCharacters(self, token): return self.parser.phases["inBody"].processCharacters(token) def startTagTableElement(self, token): self.parser.parseError() # XXX Have to duplicate logic here to find out if the tag is ignored ignoreEndTag = self.ignoreEndTagCaption() self.parser.phase.processEndTag(impliedTagToken("caption")) if not ignoreEndTag: return token def startTagOther(self, token): return self.parser.phases["inBody"].processStartTag(token) def endTagCaption(self, token): if not self.ignoreEndTagCaption(): # AT this code is quite similar to endTagTable in "InTable" self.tree.generateImpliedEndTags() if self.tree.openElements[-1].name != "caption": self.parser.parseError("expected-one-end-tag-but-got-another", {"gotName": "caption", "expectedName": self.tree.openElements[-1].name}) while self.tree.openElements[-1].name != "caption": self.tree.openElements.pop() self.tree.openElements.pop() self.tree.clearActiveFormattingElements() self.parser.phase = self.parser.phases["inTable"] else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def endTagTable(self, token): self.parser.parseError() ignoreEndTag = self.ignoreEndTagCaption() self.parser.phase.processEndTag(impliedTagToken("caption")) if not ignoreEndTag: return token def endTagIgnore(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def endTagOther(self, token): return self.parser.phases["inBody"].processEndTag(token) startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), (("caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"), startTagTableElement) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("caption", endTagCaption), ("table", endTagTable), (("body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"), endTagIgnore) ]) endTagHandler.default = endTagOther class InColumnGroupPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-column __slots__ = tuple() def ignoreEndTagColgroup(self): return self.tree.openElements[-1].name == "html" def processEOF(self): if self.tree.openElements[-1].name == "html": assert self.parser.innerHTML return else: ignoreEndTag = self.ignoreEndTagColgroup() self.endTagColgroup(impliedTagToken("colgroup")) if not ignoreEndTag: return True def processCharacters(self, token): ignoreEndTag = self.ignoreEndTagColgroup() self.endTagColgroup(impliedTagToken("colgroup")) if not ignoreEndTag: return token def startTagCol(self, token): self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True def startTagOther(self, token): ignoreEndTag = self.ignoreEndTagColgroup() self.endTagColgroup(impliedTagToken("colgroup")) if not ignoreEndTag: return token def endTagColgroup(self, token): if self.ignoreEndTagColgroup(): # innerHTML case assert self.parser.innerHTML self.parser.parseError() else: self.tree.openElements.pop() self.parser.phase = self.parser.phases["inTable"] def endTagCol(self, token): self.parser.parseError("no-end-tag", {"name": "col"}) def endTagOther(self, token): ignoreEndTag = self.ignoreEndTagColgroup() self.endTagColgroup(impliedTagToken("colgroup")) if not ignoreEndTag: return token startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), ("col", startTagCol) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("colgroup", endTagColgroup), ("col", endTagCol) ]) endTagHandler.default = endTagOther class InTableBodyPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-table0 __slots__ = tuple() # helper methods def clearStackToTableBodyContext(self): while self.tree.openElements[-1].name not in ("tbody", "tfoot", "thead", "html"): # self.parser.parseError("unexpected-implied-end-tag-in-table", # {"name": self.tree.openElements[-1].name}) self.tree.openElements.pop() if self.tree.openElements[-1].name == "html": assert self.parser.innerHTML # the rest def processEOF(self): self.parser.phases["inTable"].processEOF() def processSpaceCharacters(self, token): return self.parser.phases["inTable"].processSpaceCharacters(token) def processCharacters(self, token): return self.parser.phases["inTable"].processCharacters(token) def startTagTr(self, token): self.clearStackToTableBodyContext() self.tree.insertElement(token) self.parser.phase = self.parser.phases["inRow"] def startTagTableCell(self, token): self.parser.parseError("unexpected-cell-in-table-body", {"name": token["name"]}) self.startTagTr(impliedTagToken("tr", "StartTag")) return token def startTagTableOther(self, token): # XXX AT Any ideas on how to share this with endTagTable? if (self.tree.elementInScope("tbody", variant="table") or self.tree.elementInScope("thead", variant="table") or self.tree.elementInScope("tfoot", variant="table")): self.clearStackToTableBodyContext() self.endTagTableRowGroup( impliedTagToken(self.tree.openElements[-1].name)) return token else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def startTagOther(self, token): return self.parser.phases["inTable"].processStartTag(token) def endTagTableRowGroup(self, token): if self.tree.elementInScope(token["name"], variant="table"): self.clearStackToTableBodyContext() self.tree.openElements.pop() self.parser.phase = self.parser.phases["inTable"] else: self.parser.parseError("unexpected-end-tag-in-table-body", {"name": token["name"]}) def endTagTable(self, token): if (self.tree.elementInScope("tbody", variant="table") or self.tree.elementInScope("thead", variant="table") or self.tree.elementInScope("tfoot", variant="table")): self.clearStackToTableBodyContext() self.endTagTableRowGroup( impliedTagToken(self.tree.openElements[-1].name)) return token else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def endTagIgnore(self, token): self.parser.parseError("unexpected-end-tag-in-table-body", {"name": token["name"]}) def endTagOther(self, token): return self.parser.phases["inTable"].processEndTag(token) startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), ("tr", startTagTr), (("td", "th"), startTagTableCell), (("caption", "col", "colgroup", "tbody", "tfoot", "thead"), startTagTableOther) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ (("tbody", "tfoot", "thead"), endTagTableRowGroup), ("table", endTagTable), (("body", "caption", "col", "colgroup", "html", "td", "th", "tr"), endTagIgnore) ]) endTagHandler.default = endTagOther class InRowPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-row __slots__ = tuple() # helper methods (XXX unify this with other table helper methods) def clearStackToTableRowContext(self): while self.tree.openElements[-1].name not in ("tr", "html"): self.parser.parseError("unexpected-implied-end-tag-in-table-row", {"name": self.tree.openElements[-1].name}) self.tree.openElements.pop() def ignoreEndTagTr(self): return not self.tree.elementInScope("tr", variant="table") # the rest def processEOF(self): self.parser.phases["inTable"].processEOF() def processSpaceCharacters(self, token): return self.parser.phases["inTable"].processSpaceCharacters(token) def processCharacters(self, token): return self.parser.phases["inTable"].processCharacters(token) def startTagTableCell(self, token): self.clearStackToTableRowContext() self.tree.insertElement(token) self.parser.phase = self.parser.phases["inCell"] self.tree.activeFormattingElements.append(Marker) def startTagTableOther(self, token): ignoreEndTag = self.ignoreEndTagTr() self.endTagTr(impliedTagToken("tr")) # XXX how are we sure it's always ignored in the innerHTML case? if not ignoreEndTag: return token def startTagOther(self, token): return self.parser.phases["inTable"].processStartTag(token) def endTagTr(self, token): if not self.ignoreEndTagTr(): self.clearStackToTableRowContext() self.tree.openElements.pop() self.parser.phase = self.parser.phases["inTableBody"] else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def endTagTable(self, token): ignoreEndTag = self.ignoreEndTagTr() self.endTagTr(impliedTagToken("tr")) # Reprocess the current tag if the tr end tag was not ignored # XXX how are we sure it's always ignored in the innerHTML case? if not ignoreEndTag: return token def endTagTableRowGroup(self, token): if self.tree.elementInScope(token["name"], variant="table"): self.endTagTr(impliedTagToken("tr")) return token else: self.parser.parseError() def endTagIgnore(self, token): self.parser.parseError("unexpected-end-tag-in-table-row", {"name": token["name"]}) def endTagOther(self, token): return self.parser.phases["inTable"].processEndTag(token) startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), (("td", "th"), startTagTableCell), (("caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr"), startTagTableOther) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("tr", endTagTr), ("table", endTagTable), (("tbody", "tfoot", "thead"), endTagTableRowGroup), (("body", "caption", "col", "colgroup", "html", "td", "th"), endTagIgnore) ]) endTagHandler.default = endTagOther class InCellPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-cell __slots__ = tuple() # helper def closeCell(self): if self.tree.elementInScope("td", variant="table"): self.endTagTableCell(impliedTagToken("td")) elif self.tree.elementInScope("th", variant="table"): self.endTagTableCell(impliedTagToken("th")) # the rest def processEOF(self): self.parser.phases["inBody"].processEOF() def processCharacters(self, token): return self.parser.phases["inBody"].processCharacters(token) def startTagTableOther(self, token): if (self.tree.elementInScope("td", variant="table") or self.tree.elementInScope("th", variant="table")): self.closeCell() return token else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def startTagOther(self, token): return self.parser.phases["inBody"].processStartTag(token) def endTagTableCell(self, token): if self.tree.elementInScope(token["name"], variant="table"): self.tree.generateImpliedEndTags(token["name"]) if self.tree.openElements[-1].name != token["name"]: self.parser.parseError("unexpected-cell-end-tag", {"name": token["name"]}) while True: node = self.tree.openElements.pop() if node.name == token["name"]: break else: self.tree.openElements.pop() self.tree.clearActiveFormattingElements() self.parser.phase = self.parser.phases["inRow"] else: self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def endTagIgnore(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def endTagImply(self, token): if self.tree.elementInScope(token["name"], variant="table"): self.closeCell() return token else: # sometimes innerHTML case self.parser.parseError() def endTagOther(self, token): return self.parser.phases["inBody"].processEndTag(token) startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), (("caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"), startTagTableOther) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ (("td", "th"), endTagTableCell), (("body", "caption", "col", "colgroup", "html"), endTagIgnore), (("table", "tbody", "tfoot", "thead", "tr"), endTagImply) ]) endTagHandler.default = endTagOther class InSelectPhase(Phase): __slots__ = tuple() # http://www.whatwg.org/specs/web-apps/current-work/#in-select def processEOF(self): if self.tree.openElements[-1].name != "html": self.parser.parseError("eof-in-select") else: assert self.parser.innerHTML def processCharacters(self, token): if token["data"] == "\u0000": return self.tree.insertText(token["data"]) def startTagOption(self, token): # We need to imply </option> if <option> is the current node. if self.tree.openElements[-1].name == "option": self.tree.openElements.pop() self.tree.insertElement(token) def startTagOptgroup(self, token): if self.tree.openElements[-1].name == "option": self.tree.openElements.pop() if self.tree.openElements[-1].name == "optgroup": self.tree.openElements.pop() self.tree.insertElement(token) def startTagSelect(self, token): self.parser.parseError("unexpected-select-in-select") self.endTagSelect(impliedTagToken("select")) def startTagInput(self, token): self.parser.parseError("unexpected-input-in-select") if self.tree.elementInScope("select", variant="select"): self.endTagSelect(impliedTagToken("select")) return token else: assert self.parser.innerHTML def startTagScript(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagOther(self, token): self.parser.parseError("unexpected-start-tag-in-select", {"name": token["name"]}) def endTagOption(self, token): if self.tree.openElements[-1].name == "option": self.tree.openElements.pop() else: self.parser.parseError("unexpected-end-tag-in-select", {"name": "option"}) def endTagOptgroup(self, token): # </optgroup> implicitly closes <option> if (self.tree.openElements[-1].name == "option" and self.tree.openElements[-2].name == "optgroup"): self.tree.openElements.pop() # It also closes </optgroup> if self.tree.openElements[-1].name == "optgroup": self.tree.openElements.pop() # But nothing else else: self.parser.parseError("unexpected-end-tag-in-select", {"name": "optgroup"}) def endTagSelect(self, token): if self.tree.elementInScope("select", variant="select"): node = self.tree.openElements.pop() while node.name != "select": node = self.tree.openElements.pop() self.parser.resetInsertionMode() else: # innerHTML case assert self.parser.innerHTML self.parser.parseError() def endTagOther(self, token): self.parser.parseError("unexpected-end-tag-in-select", {"name": token["name"]}) startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), ("option", startTagOption), ("optgroup", startTagOptgroup), ("select", startTagSelect), (("input", "keygen", "textarea"), startTagInput), ("script", startTagScript) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("option", endTagOption), ("optgroup", endTagOptgroup), ("select", endTagSelect) ]) endTagHandler.default = endTagOther class InSelectInTablePhase(Phase): __slots__ = tuple() def processEOF(self): self.parser.phases["inSelect"].processEOF() def processCharacters(self, token): return self.parser.phases["inSelect"].processCharacters(token) def startTagTable(self, token): self.parser.parseError("unexpected-table-element-start-tag-in-select-in-table", {"name": token["name"]}) self.endTagOther(impliedTagToken("select")) return token def startTagOther(self, token): return self.parser.phases["inSelect"].processStartTag(token) def endTagTable(self, token): self.parser.parseError("unexpected-table-element-end-tag-in-select-in-table", {"name": token["name"]}) if self.tree.elementInScope(token["name"], variant="table"): self.endTagOther(impliedTagToken("select")) return token def endTagOther(self, token): return self.parser.phases["inSelect"].processEndTag(token) startTagHandler = _utils.MethodDispatcher([ (("caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"), startTagTable) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ (("caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"), endTagTable) ]) endTagHandler.default = endTagOther class InForeignContentPhase(Phase): __slots__ = tuple() breakoutElements = frozenset(["b", "big", "blockquote", "body", "br", "center", "code", "dd", "div", "dl", "dt", "em", "embed", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "i", "img", "li", "listing", "menu", "meta", "nobr", "ol", "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table", "tt", "u", "ul", "var"]) def adjustSVGTagNames(self, token): replacements = {"altglyph": "altGlyph", "altglyphdef": "altGlyphDef", "altglyphitem": "altGlyphItem", "animatecolor": "animateColor", "animatemotion": "animateMotion", "animatetransform": "animateTransform", "clippath": "clipPath", "feblend": "feBlend", "fecolormatrix": "feColorMatrix", "fecomponenttransfer": "feComponentTransfer", "fecomposite": "feComposite", "feconvolvematrix": "feConvolveMatrix", "fediffuselighting": "feDiffuseLighting", "fedisplacementmap": "feDisplacementMap", "fedistantlight": "feDistantLight", "feflood": "feFlood", "fefunca": "feFuncA", "fefuncb": "feFuncB", "fefuncg": "feFuncG", "fefuncr": "feFuncR", "fegaussianblur": "feGaussianBlur", "feimage": "feImage", "femerge": "feMerge", "femergenode": "feMergeNode", "femorphology": "feMorphology", "feoffset": "feOffset", "fepointlight": "fePointLight", "fespecularlighting": "feSpecularLighting", "fespotlight": "feSpotLight", "fetile": "feTile", "feturbulence": "feTurbulence", "foreignobject": "foreignObject", "glyphref": "glyphRef", "lineargradient": "linearGradient", "radialgradient": "radialGradient", "textpath": "textPath"} if token["name"] in replacements: token["name"] = replacements[token["name"]] def processCharacters(self, token): if token["data"] == "\u0000": token["data"] = "\uFFFD" elif (self.parser.framesetOK and any(char not in spaceCharacters for char in token["data"])): self.parser.framesetOK = False Phase.processCharacters(self, token) def processStartTag(self, token): currentNode = self.tree.openElements[-1] if (token["name"] in self.breakoutElements or (token["name"] == "font" and set(token["data"].keys()) & {"color", "face", "size"})): self.parser.parseError("unexpected-html-element-in-foreign-content", {"name": token["name"]}) while (self.tree.openElements[-1].namespace != self.tree.defaultNamespace and not self.parser.isHTMLIntegrationPoint(self.tree.openElements[-1]) and not self.parser.isMathMLTextIntegrationPoint(self.tree.openElements[-1])): self.tree.openElements.pop() return token else: if currentNode.namespace == namespaces["mathml"]: self.parser.adjustMathMLAttributes(token) elif currentNode.namespace == namespaces["svg"]: self.adjustSVGTagNames(token) self.parser.adjustSVGAttributes(token) self.parser.adjustForeignAttributes(token) token["namespace"] = currentNode.namespace self.tree.insertElement(token) if token["selfClosing"]: self.tree.openElements.pop() token["selfClosingAcknowledged"] = True def processEndTag(self, token): nodeIndex = len(self.tree.openElements) - 1 node = self.tree.openElements[-1] if node.name.translate(asciiUpper2Lower) != token["name"]: self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) while True: if node.name.translate(asciiUpper2Lower) == token["name"]: # XXX this isn't in the spec but it seems necessary if self.parser.phase == self.parser.phases["inTableText"]: self.parser.phase.flushCharacters() self.parser.phase = self.parser.phase.originalPhase while self.tree.openElements.pop() != node: assert self.tree.openElements new_token = None break nodeIndex -= 1 node = self.tree.openElements[nodeIndex] if node.namespace != self.tree.defaultNamespace: continue else: new_token = self.parser.phase.processEndTag(token) break return new_token class AfterBodyPhase(Phase): __slots__ = tuple() def processEOF(self): # Stop parsing pass def processComment(self, token): # This is needed because data is to be appended to the <html> element # here and not to whatever is currently open. self.tree.insertComment(token, self.tree.openElements[0]) def processCharacters(self, token): self.parser.parseError("unexpected-char-after-body") self.parser.phase = self.parser.phases["inBody"] return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagOther(self, token): self.parser.parseError("unexpected-start-tag-after-body", {"name": token["name"]}) self.parser.phase = self.parser.phases["inBody"] return token def endTagHtml(self, name): if self.parser.innerHTML: self.parser.parseError("unexpected-end-tag-after-body-innerhtml") else: self.parser.phase = self.parser.phases["afterAfterBody"] def endTagOther(self, token): self.parser.parseError("unexpected-end-tag-after-body", {"name": token["name"]}) self.parser.phase = self.parser.phases["inBody"] return token startTagHandler = _utils.MethodDispatcher([ ("html", startTagHtml) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([("html", endTagHtml)]) endTagHandler.default = endTagOther class InFramesetPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-frameset __slots__ = tuple() def processEOF(self): if self.tree.openElements[-1].name != "html": self.parser.parseError("eof-in-frameset") else: assert self.parser.innerHTML def processCharacters(self, token): self.parser.parseError("unexpected-char-in-frameset") def startTagFrameset(self, token): self.tree.insertElement(token) def startTagFrame(self, token): self.tree.insertElement(token) self.tree.openElements.pop() def startTagNoframes(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagOther(self, token): self.parser.parseError("unexpected-start-tag-in-frameset", {"name": token["name"]}) def endTagFrameset(self, token): if self.tree.openElements[-1].name == "html": # innerHTML case self.parser.parseError("unexpected-frameset-in-frameset-innerhtml") else: self.tree.openElements.pop() if (not self.parser.innerHTML and self.tree.openElements[-1].name != "frameset"): # If we're not in innerHTML mode and the current node is not a # "frameset" element (anymore) then switch. self.parser.phase = self.parser.phases["afterFrameset"] def endTagOther(self, token): self.parser.parseError("unexpected-end-tag-in-frameset", {"name": token["name"]}) startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), ("frameset", startTagFrameset), ("frame", startTagFrame), ("noframes", startTagNoframes) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("frameset", endTagFrameset) ]) endTagHandler.default = endTagOther class AfterFramesetPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#after3 __slots__ = tuple() def processEOF(self): # Stop parsing pass def processCharacters(self, token): self.parser.parseError("unexpected-char-after-frameset") def startTagNoframes(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagOther(self, token): self.parser.parseError("unexpected-start-tag-after-frameset", {"name": token["name"]}) def endTagHtml(self, token): self.parser.phase = self.parser.phases["afterAfterFrameset"] def endTagOther(self, token): self.parser.parseError("unexpected-end-tag-after-frameset", {"name": token["name"]}) startTagHandler = _utils.MethodDispatcher([ ("html", Phase.startTagHtml), ("noframes", startTagNoframes) ]) startTagHandler.default = startTagOther endTagHandler = _utils.MethodDispatcher([ ("html", endTagHtml) ]) endTagHandler.default = endTagOther class AfterAfterBodyPhase(Phase): __slots__ = tuple() def processEOF(self): pass def processComment(self, token): self.tree.insertComment(token, self.tree.document) def processSpaceCharacters(self, token): return self.parser.phases["inBody"].processSpaceCharacters(token) def processCharacters(self, token): self.parser.parseError("expected-eof-but-got-char") self.parser.phase = self.parser.phases["inBody"] return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagOther(self, token): self.parser.parseError("expected-eof-but-got-start-tag", {"name": token["name"]}) self.parser.phase = self.parser.phases["inBody"] return token def processEndTag(self, token): self.parser.parseError("expected-eof-but-got-end-tag", {"name": token["name"]}) self.parser.phase = self.parser.phases["inBody"] return token startTagHandler = _utils.MethodDispatcher([ ("html", startTagHtml) ]) startTagHandler.default = startTagOther class AfterAfterFramesetPhase(Phase): __slots__ = tuple() def processEOF(self): pass def processComment(self, token): self.tree.insertComment(token, self.tree.document) def processSpaceCharacters(self, token): return self.parser.phases["inBody"].processSpaceCharacters(token) def processCharacters(self, token): self.parser.parseError("expected-eof-but-got-char") def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagNoFrames(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagOther(self, token): self.parser.parseError("expected-eof-but-got-start-tag", {"name": token["name"]}) def processEndTag(self, token): self.parser.parseError("expected-eof-but-got-end-tag", {"name": token["name"]}) startTagHandler = _utils.MethodDispatcher([ ("html", startTagHtml), ("noframes", startTagNoFrames) ]) startTagHandler.default = startTagOther # pylint:enable=unused-argument return { "initial": InitialPhase, "beforeHtml": BeforeHtmlPhase, "beforeHead": BeforeHeadPhase, "inHead": InHeadPhase, "inHeadNoscript": InHeadNoscriptPhase, "afterHead": AfterHeadPhase, "inBody": InBodyPhase, "text": TextPhase, "inTable": InTablePhase, "inTableText": InTableTextPhase, "inCaption": InCaptionPhase, "inColumnGroup": InColumnGroupPhase, "inTableBody": InTableBodyPhase, "inRow": InRowPhase, "inCell": InCellPhase, "inSelect": InSelectPhase, "inSelectInTable": InSelectInTablePhase, "inForeignContent": InForeignContentPhase, "afterBody": AfterBodyPhase, "inFrameset": InFramesetPhase, "afterFrameset": AfterFramesetPhase, "afterAfterBody": AfterAfterBodyPhase, "afterAfterFrameset": AfterAfterFramesetPhase, # XXX after after frameset }
null
174,492
from __future__ import absolute_import, division, unicode_literals from six import with_metaclass, viewkeys import types from . import _inputstream from . import _tokenizer from . import treebuilders from .treebuilders.base import Marker from . import _utils from .constants import ( spaceCharacters, asciiUpper2Lower, specialElements, headingElements, cdataElements, rcdataElements, tokenTypes, tagTokenTypes, namespaces, htmlIntegrationPointElements, mathmlTextIntegrationPointElements, adjustForeignAttributes as adjustForeignAttributesMap, adjustMathMLAttributes, adjustSVGAttributes, E, _ReparseException ) def viewkeys(d: Mapping[_K, _V]) -> KeysView[_K]: ... def adjust_attributes(token, replacements): needs_adjustment = viewkeys(token['data']) & viewkeys(replacements) if needs_adjustment: token['data'] = type(token['data'])((replacements.get(k, k), v) for k, v in token['data'].items())
null
174,493
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from codecs import register_error, xmlcharrefreplace_errors from .constants import voidElements, booleanAttributes, spaceCharacters from .constants import rcdataElements, entities, xmlEntities from . import treewalkers, _utils from xml.sax.saxutils import escape _encode_entity_map = {} def xmlcharrefreplace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... def htmlentityreplace_errors(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): res = [] codepoints = [] skip = False for i, c in enumerate(exc.object[exc.start:exc.end]): if skip: skip = False continue index = i + exc.start if _utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]): codepoint = _utils.surrogatePairToCodepoint(exc.object[index:index + 2]) skip = True else: codepoint = ord(c) codepoints.append(codepoint) for cp in codepoints: e = _encode_entity_map.get(cp) if e: res.append("&") res.append(e) if not e.endswith(";"): res.append(";") else: res.append("&#x%s;" % (hex(cp)[2:])) return ("".join(res), exc.end) else: return xmlcharrefreplace_errors(exc)
null
174,497
import re import sys import collections from collections import namedtuple class DefragResult(_DefragResultBase, _ResultMixinStr): __slots__ = () def geturl(self): if self.fragment: return self.url + '#' + self.fragment else: return self.url class SplitResult(_SplitResultBase, _NetlocResultMixinStr): __slots__ = () def geturl(self): return urlunsplit(self) class ParseResult(_ParseResultBase, _NetlocResultMixinStr): __slots__ = () def geturl(self): return urlunparse(self) class DefragResultBytes(_DefragResultBase, _ResultMixinBytes): __slots__ = () def geturl(self): if self.fragment: return self.url + b'#' + self.fragment else: return self.url class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes): __slots__ = () def geturl(self): return urlunsplit(self) class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes): __slots__ = () def geturl(self): return urlunparse(self) def _fix_result_transcoding(): _result_pairs = ( (DefragResult, DefragResultBytes), (SplitResult, SplitResultBytes), (ParseResult, ParseResultBytes), ) for _decoded, _encoded in _result_pairs: _decoded._encoded_counterpart = _encoded _encoded._decoded_counterpart = _decoded
null
174,498
import re import sys import collections uses_netloc = ['', 'ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh', 'ws', 'wss'] def _coerce_args(*args): # Invokes decode if necessary to create str args # and returns the coerced inputs along with # an appropriate result coercion function # - noop for str inputs # - encoding function otherwise str_input = isinstance(args[0], str) for arg in args[1:]: # We special-case the empty string to support the # "scheme=''" default argument to some functions if arg and isinstance(arg, str) != str_input: raise TypeError("Cannot mix str and non-str arguments") if str_input: return args + (_noop,) return _decode_args(args) + (_encode_result,) from collections import namedtuple def urlparse(url, scheme='', allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Return a 6-tuple: (scheme, netloc, path, params, query, fragment). Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) splitresult = urlsplit(url, scheme, allow_fragments) scheme, netloc, url, query, fragment = splitresult if scheme in uses_params and ';' in url: url, params = _splitparams(url) else: params = '' result = ParseResult(scheme, netloc, url, params, query, fragment) return _coerce_result(result) def urlunparse(components): """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent).""" scheme, netloc, url, params, query, fragment, _coerce_result = ( _coerce_args(*components)) if params: url = "%s;%s" % (url, params) return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment))) The provided code snippet includes necessary dependencies for implementing the `urljoin` function. Write a Python function `def urljoin(base, url, allow_fragments=True)` to solve the following problem: Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. Here is the function: def urljoin(base, url, allow_fragments=True): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url if not url: return base base, url, _coerce_result = _coerce_args(base, url) bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return _coerce_result(url) if scheme in uses_netloc: if netloc: return _coerce_result(urlunparse((scheme, netloc, path, params, query, fragment))) netloc = bnetloc if not path and not params: path = bpath params = bparams if not query: query = bquery return _coerce_result(urlunparse((scheme, netloc, path, params, query, fragment))) base_parts = bpath.split('/') if base_parts[-1] != '': # the last item is not a directory, so will not be taken into account # in resolving the relative path del base_parts[-1] # for rfc3986, ignore all base path should the first character be root. if path[:1] == '/': segments = path.split('/') else: segments = base_parts + path.split('/') # filter out elements that would cause redundant slashes on re-joining # the resolved_path segments[1:-1] = filter(None, segments[1:-1]) resolved_path = [] for seg in segments: if seg == '..': try: resolved_path.pop() except IndexError: # ignore any .. segments that would otherwise cause an IndexError # when popped from resolved_path if resolving for rfc3986 pass elif seg == '.': continue else: resolved_path.append(seg) if segments[-1] in ('.', '..'): # do some post-processing here. if the last segment was a relative dir, # then we need to append the trailing '/' resolved_path.append('') return _coerce_result(urlunparse((scheme, netloc, '/'.join( resolved_path) or '/', params, query, fragment)))
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.
174,499
import re import sys import collections def _coerce_args(*args): # Invokes decode if necessary to create str args # and returns the coerced inputs along with # an appropriate result coercion function # - noop for str inputs # - encoding function otherwise str_input = isinstance(args[0], str) for arg in args[1:]: # We special-case the empty string to support the # "scheme=''" default argument to some functions if arg and isinstance(arg, str) != str_input: raise TypeError("Cannot mix str and non-str arguments") if str_input: return args + (_noop,) return _decode_args(args) + (_encode_result,) from collections import namedtuple class DefragResult(_DefragResultBase, _ResultMixinStr): __slots__ = () def geturl(self): if self.fragment: return self.url + '#' + self.fragment else: return self.url def urlparse(url, scheme='', allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Return a 6-tuple: (scheme, netloc, path, params, query, fragment). Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) splitresult = urlsplit(url, scheme, allow_fragments) scheme, netloc, url, query, fragment = splitresult if scheme in uses_params and ';' in url: url, params = _splitparams(url) else: params = '' result = ParseResult(scheme, netloc, url, params, query, fragment) return _coerce_result(result) def urlunparse(components): """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent).""" scheme, netloc, url, params, query, fragment, _coerce_result = ( _coerce_args(*components)) if params: url = "%s;%s" % (url, params) return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment))) The provided code snippet includes necessary dependencies for implementing the `urldefrag` function. Write a Python function `def urldefrag(url)` to solve the following problem: Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the empty string. Here is the function: def urldefrag(url): """Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the empty string. """ url, _coerce_result = _coerce_args(url) if '#' in url: s, n, p, a, q, frag = urlparse(url) defrag = urlunparse((s, n, p, a, q, '')) else: frag = '' defrag = url return _coerce_result(DefragResult(defrag, frag))
Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the empty string.
174,500
import re import sys import collections from collections import namedtuple def parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&'): """Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. max_num_fields: int. If set, then throws a ValueError if there are more than n fields read by parse_qsl(). separator: str. The symbol to use for separating the query arguments. Defaults to &. Returns a list, as G-d intended. """ qs, _coerce_result = _coerce_args(qs) if not separator or (not isinstance(separator, (str, bytes))): raise ValueError("Separator must be of type string or bytes.") # If max_num_fields is defined then check that the number of fields # is less than max_num_fields. This prevents a memory exhaustion DOS # attack via post bodies with many fields. if max_num_fields is not None: num_fields = 1 + qs.count(separator) if max_num_fields < num_fields: raise ValueError('Max number of fields exceeded') pairs = [s1 for s1 in qs.split(separator)] r = [] for name_value in pairs: if not name_value and not strict_parsing: continue nv = name_value.split('=', 1) if len(nv) != 2: if strict_parsing: raise ValueError("bad query field: %r" % (name_value,)) # Handle case of a control-name with no equal sign if keep_blank_values: nv.append('') else: continue if len(nv[1]) or keep_blank_values: name = nv[0].replace('+', ' ') name = unquote(name, encoding=encoding, errors=errors) name = _coerce_result(name) value = nv[1].replace('+', ' ') value = unquote(value, encoding=encoding, errors=errors) value = _coerce_result(value) r.append((name, value)) return r The provided code snippet includes necessary dependencies for implementing the `parse_qs` function. Write a Python function `def parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')` to solve the following problem: Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. max_num_fields: int. If set, then throws a ValueError if there are more than n fields read by parse_qsl(). separator: str. The symbol to use for separating the query arguments. Defaults to &. Returns a dictionary. Here is the function: def parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&'): """Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. max_num_fields: int. If set, then throws a ValueError if there are more than n fields read by parse_qsl(). separator: str. The symbol to use for separating the query arguments. Defaults to &. Returns a dictionary. """ parsed_result = {} pairs = parse_qsl(qs, keep_blank_values, strict_parsing, encoding=encoding, errors=errors, max_num_fields=max_num_fields, separator=separator) for name, value in pairs: if name in parsed_result: parsed_result[name].append(value) else: parsed_result[name] = [value] return parsed_result
Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. max_num_fields: int. If set, then throws a ValueError if there are more than n fields read by parse_qsl(). separator: str. The symbol to use for separating the query arguments. Defaults to &. Returns a dictionary.
174,501
import re import sys import collections from collections import namedtuple def unquote(string, encoding='utf-8', errors='replace'): """Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-encoded sequences are decoded with UTF-8, and invalid sequences are replaced by a placeholder character. unquote('abc%20def') -> 'abc def'. """ if '%' not in string: string.split return string if encoding is None: encoding = 'utf-8' if errors is None: errors = 'replace' bits = _asciire.split(string) res = [bits[0]] append = res.append for i in range(1, len(bits), 2): append(unquote_to_bytes(bits[i]).decode(encoding, errors)) append(bits[i + 1]) return ''.join(res) The provided code snippet includes necessary dependencies for implementing the `unquote_plus` function. Write a Python function `def unquote_plus(string, encoding='utf-8', errors='replace')` to solve the following problem: Like unquote(), but also replace plus signs by spaces, as required for unquoting HTML form values. unquote_plus('%7e/abc+def') -> '~/abc def' Here is the function: def unquote_plus(string, encoding='utf-8', errors='replace'): """Like unquote(), but also replace plus signs by spaces, as required for unquoting HTML form values. unquote_plus('%7e/abc+def') -> '~/abc def' """ string = string.replace('+', ' ') return unquote(string, encoding, errors)
Like unquote(), but also replace plus signs by spaces, as required for unquoting HTML form values. unquote_plus('%7e/abc+def') -> '~/abc def'
174,502
import re import sys import collections from collections import namedtuple def quote_plus(string, safe='', encoding=None, errors=None): """Like quote(), but also replace ' ' with '+', as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'. """ # Check if ' ' in string, where string may either be a str or bytes. If # there are no spaces, the regular quote will produce the right answer. if ((isinstance(string, str) and ' ' not in string) or (isinstance(string, bytes) and b' ' not in string)): return quote(string, safe, encoding, errors) if isinstance(safe, str): space = ' ' else: space = b' ' string = quote(string, safe + space, encoding, errors) return string.replace(' ', '+') The provided code snippet includes necessary dependencies for implementing the `urlencode` function. Write a Python function `def urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)` to solve the following problem: Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. The components of a query arg may each be either a string or a bytes type. The safe, encoding, and errors parameters are passed down to the function specified by quote_via (encoding and errors only if a component is a str). Here is the function: def urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus): """Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. The components of a query arg may each be either a string or a bytes type. The safe, encoding, and errors parameters are passed down to the function specified by quote_via (encoding and errors only if a component is a str). """ if hasattr(query, "items"): query = query.items() else: # It's a bother at times that strings and string-like objects are # sequences. try: # non-sequence items should not work with len() # non-empty strings will fail this if len(query) and not isinstance(query[0], tuple): raise TypeError # Zero-length sequences of all types will get here and succeed, # but that's a minor nit. Since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty, va, tb = sys.exc_info() raise TypeError("not a valid non-string sequence " "or mapping object").with_traceback(tb) l = [] if not doseq: for k, v in query: if isinstance(k, bytes): k = quote_via(k, safe) else: k = quote_via(str(k), safe, encoding, errors) if isinstance(v, bytes): v = quote_via(v, safe) else: v = quote_via(str(v), safe, encoding, errors) l.append(k + '=' + v) else: for k, v in query: if isinstance(k, bytes): k = quote_via(k, safe) else: k = quote_via(str(k), safe, encoding, errors) if isinstance(v, bytes): v = quote_via(v, safe) l.append(k + '=' + v) elif isinstance(v, str): v = quote_via(v, safe, encoding, errors) l.append(k + '=' + v) else: try: # Is this a sufficient test for sequence-ness? x = len(v) except TypeError: # not a sequence v = quote_via(str(v), safe, encoding, errors) l.append(k + '=' + v) else: # loop over the sequence for elt in v: if isinstance(elt, bytes): elt = quote_via(elt, safe) else: elt = quote_via(str(elt), safe, encoding, errors) l.append(k + '=' + elt) return '&'.join(l)
Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. The components of a query arg may each be either a string or a bytes type. The safe, encoding, and errors parameters are passed down to the function specified by quote_via (encoding and errors only if a component is a str).
174,503
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `to_bytes` function. Write a Python function `def to_bytes(url)` to solve the following problem: to_bytes(u"URL") --> 'URL'. Here is the function: def to_bytes(url): """to_bytes(u"URL") --> 'URL'.""" # Most URL schemes require ASCII. If that changes, the conversion # can be relaxed. # XXX get rid of to_bytes() if isinstance(url, str): try: url = url.encode("ASCII").decode() except UnicodeError: raise UnicodeError("URL " + repr(url) + " contains non-ASCII characters") return url
to_bytes(u"URL") --> 'URL'.
174,504
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `unwrap` function. Write a Python function `def unwrap(url)` to solve the following problem: unwrap('<URL:type://host/path>') --> 'type://host/path'. Here is the function: def unwrap(url): """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" url = str(url).strip() if url[:1] == '<' and url[-1:] == '>': url = url[1:-1].strip() if url[:4] == 'URL:': url = url[4:].strip() return url
unwrap('<URL:type://host/path>') --> 'type://host/path'.
174,505
import re import sys import collections from collections import namedtuple _typeprog = None The provided code snippet includes necessary dependencies for implementing the `splittype` function. Write a Python function `def splittype(url)` to solve the following problem: splittype('type:opaquestring') --> 'type', 'opaquestring'. Here is the function: def splittype(url): """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" global _typeprog if _typeprog is None: _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL) match = _typeprog.match(url) if match: scheme, data = match.groups() return scheme.lower(), data return None, url
splittype('type:opaquestring') --> 'type', 'opaquestring'.
174,506
import re import sys import collections from collections import namedtuple _hostprog = None The provided code snippet includes necessary dependencies for implementing the `splithost` function. Write a Python function `def splithost(url)` to solve the following problem: splithost('//host[:port]/path') --> 'host[:port]', '/path'. Here is the function: def splithost(url): """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" global _hostprog if _hostprog is None: _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL) match = _hostprog.match(url) if match: host_port, path = match.groups() if path and path[0] != '/': path = '/' + path return host_port, path return None, url
splithost('//host[:port]/path') --> 'host[:port]', '/path'.
174,507
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `splituser` function. Write a Python function `def splituser(host)` to solve the following problem: splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'. Here is the function: def splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" user, delim, host = host.rpartition('@') return (user if delim else None), host
splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.
174,508
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `splitpasswd` function. Write a Python function `def splitpasswd(user)` to solve the following problem: splitpasswd('user:passwd') -> 'user', 'passwd'. Here is the function: def splitpasswd(user): """splitpasswd('user:passwd') -> 'user', 'passwd'.""" user, delim, passwd = user.partition(':') return user, (passwd if delim else None)
splitpasswd('user:passwd') -> 'user', 'passwd'.
174,509
import re import sys import collections from collections import namedtuple _portprog = None The provided code snippet includes necessary dependencies for implementing the `splitport` function. Write a Python function `def splitport(host)` to solve the following problem: splitport('host:port') --> 'host', 'port'. Here is the function: def splitport(host): """splitport('host:port') --> 'host', 'port'.""" global _portprog if _portprog is None: _portprog = re.compile('(.*):([0-9]*)$', re.DOTALL) match = _portprog.match(host) if match: host, port = match.groups() if port: return host, port return host, None
splitport('host:port') --> 'host', 'port'.
174,510
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `splitnport` function. Write a Python function `def splitnport(host, defport=-1)` to solve the following problem: Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number. Here is the function: def splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" host, delim, port = host.rpartition(':') if not delim: host = port elif port: try: nport = int(port) except ValueError: nport = None return host, nport return host, defport
Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.
174,511
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `splitquery` function. Write a Python function `def splitquery(url)` to solve the following problem: splitquery('/path?query') --> '/path', 'query'. Here is the function: def splitquery(url): """splitquery('/path?query') --> '/path', 'query'.""" path, delim, query = url.rpartition('?') if delim: return path, query return url, None
splitquery('/path?query') --> '/path', 'query'.
174,512
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `splittag` function. Write a Python function `def splittag(url)` to solve the following problem: splittag('/path#tag') --> '/path', 'tag'. Here is the function: def splittag(url): """splittag('/path#tag') --> '/path', 'tag'.""" path, delim, tag = url.rpartition('#') if delim: return path, tag return url, None
splittag('/path#tag') --> '/path', 'tag'.
174,513
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `splitattr` function. Write a Python function `def splitattr(url)` to solve the following problem: splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...]. Here is the function: def splitattr(url): """splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].""" words = url.split(';') return words[0], words[1:]
splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].
174,514
import re import sys import collections from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `splitvalue` function. Write a Python function `def splitvalue(attr)` to solve the following problem: splitvalue('attr=value') --> 'attr', 'value'. Here is the function: def splitvalue(attr): """splitvalue('attr=value') --> 'attr', 'value'.""" attr, delim, value = attr.partition('=') return attr, (value if delim else None)
splitvalue('attr=value') --> 'attr', 'value'.
174,515
from html.entities import codepoint2name from collections import defaultdict import codecs import re import logging import string chardet_module = None if chardet_module: else: from html.entities import html5 def chardet_dammit(s): if isinstance(s, str): return None return chardet_module.detect(s)['encoding']
null
174,516
from html.entities import codepoint2name from collections import defaultdict import codecs import re import logging import string from html.entities import html5 def chardet_dammit(s): return None
null
174,517
from io import BytesIO from io import StringIO from lxml import etree from bs4.element import ( Comment, Doctype, NamespacedAttribute, ProcessingInstruction, XMLProcessingInstruction, ) from bs4.builder import ( DetectsXMLParsedAsHTML, FAST, HTML, HTMLTreeBuilder, PERMISSIVE, ParserRejectedMarkup, TreeBuilder, XML) from bs4.dammit import EncodingDetector The provided code snippet includes necessary dependencies for implementing the `_invert` function. Write a Python function `def _invert(d)` to solve the following problem: Invert a dictionary. Here is the function: def _invert(d): "Invert a dictionary." return dict((v,k) for k, v in list(d.items()))
Invert a dictionary.
174,518
import re import sys import warnings from bs4.css import CSS from bs4.formatter import ( Formatter, HTMLFormatter, XMLFormatter, ) The provided code snippet includes necessary dependencies for implementing the `_alias` function. Write a Python function `def _alias(attr)` to solve the following problem: Alias one attribute name to another for backward compatibility Here is the function: def _alias(attr): """Alias one attribute name to another for backward compatibility""" @property def alias(self): return getattr(self, attr) @alias.setter def alias(self): return setattr(self, attr) return alias
Alias one attribute name to another for backward compatibility