Update the unique matching element to have a given set of fields.

        Parameters
        ----------
        table_name: str

        fields: dict or function[dict -> None]
            new data/values to insert into the unique element
            or a method that will update the elements.

        data: dict
            Sample data for query

        cond: tinydb.Query
            which elements to update

        unique_fields: list of str

        raise_if_not_found: bool
            Will raise an exception if the element is not found for update.

        Returns
        -------
        eid: int
            The eid of the updated element if found, None otherwise.


Return the number of items that match the `sample` field values
        in table `table_name`.
        Check function search_sample for more details.


Check for get_data and get_affine method in an object

    Parameters
    ----------
    obj: any object
        Tested object

    Returns
    -------
    is_img: boolean
        True if get_data and get_affine methods are present and callable,
        False otherwise.


Return true if one_img and another_img have the same shape.
    False otherwise.
    If both are nibabel.Nifti1Image will also check for affine matrices.

    Parameters
    ----------
    one_img: nibabel.Nifti1Image or np.ndarray

    another_img: nibabel.Nifti1Image  or np.ndarray

    only_check_3d: bool
        If True will check only the 3D part of the affine matrices when they have more dimensions.

    Raises
    ------
    NiftiFilesNotCompatible


Returns true if array1 and array2 have the same shapes, false
    otherwise.

    Parameters
    ----------
    array1: numpy.ndarray

    array2: numpy.ndarray

    nd_to_check: int
        Number of the dimensions to check, i.e., if == 3 then will check only the 3 first numbers of array.shape.
    Returns
    -------
    bool


Run as sample test server.


Dump current profiler statistics into a file.


Clear profiler statistics.


Create a list of regex matches that result from the match_regex
    of all file names within wd.
    The list of files will have wd as path prefix.

    @param regex: string
    @param wd: string
    working directory
    @return:


Returns absolute paths of folders that match the regex within folder_path and
    all its children folders.

    Note: The regex matching is done using the match function
    of the re module.

    Parameters
    ----------
    folder_path: string

    regex: string

    Returns
    -------
    A list of strings.


Returns absolute paths of files that match the regex within file_dir and
    all its children folders.

    Note: The regex matching is done using the search function
    of the re module.

    Parameters
    ----------
    folder_path: string

    regex: string

    Returns
    -------
    A list of strings.


Returns absolute paths of files that match the regexs within folder_path and
    all its children folders.

    This is an iterator function that will use yield to return each set of
    file_paths in one iteration.

    Will only return value if all the strings in regex match a file name.

    Note: The regex matching is done using the search function
    of the re module.

    Parameters
    ----------
    folder_path: string

    regex: strings

    Returns
    -------
    A list of strings.


Generator that loops through all absolute paths of the files within folder

    Parameters
    ----------
    folder: str
    Root folder start point for recursive search.

    Yields
    ------
    fpath: str
    Absolute path of one file in the folders


Load user from data dump.

    NOTE: This task takes into account the possible duplication of emails and
    usernames, hence it should be called synchronously.
    In such case of collision it will raise UserEmailExistsError or
    UserUsernameExistsError, if email or username are already existing in
    the database. Caller of this task should take care to to resolve those
    collisions beforehand or after catching an exception.

    :param data: Dictionary containing user data.
    :type data: dict


Calculate image translations in parallel.

    Parameters
    ----------
    images : ImageCollection
        Images as instance of ImageCollection.

    Returns
    -------
    2d array, (ty, tx)
        ty and tx is translation to previous image in respectively
        x or y direction.


Adds a dimensions with ones to array.


Append key-value pairs to msg, for display.

    Parameters
    ----------
    msg: string
        arbitrary message
    kwargs: dict
        arbitrary dictionary

    Returns
    -------
    updated_msg: string
        msg, with "key: value" appended. Only string values are appended.

    Example
    -------
    >>> compose_err_msg('Error message with arguments...', arg_num=123, \
        arg_str='filename.nii', arg_bool=True)
    'Error message with arguments...\\narg_str: filename.nii'
    >>>


Copy the DICOM file groups to folder_path. Each group will be copied into
    a subfolder with named given by groupby_field.

    Parameters
    ----------
    dicom_groups: boyle.dicom.sets.DicomFileSet

    folder_path: str
     Path to where copy the DICOM files.

    groupby_field_name: str
     DICOM field name. Will get the value of this field to name the group
     folder.


Calculates the DicomFileDistance between all files in dicom_files, using an
    weighted Levenshtein measure between all field names in field_weights and
    their corresponding weights.

    Parameters
    ----------
    dicom_files: iterable of str
        Dicom file paths

    field_weights: dict of str to float
        A dict with header field names to float scalar values, that
        indicate a distance measure ratio for the levenshtein distance
        averaging of all the header field names in it. e.g., {'PatientID': 1}

    dist_method_cls: DicomFileDistance class
        Distance method object to compare the files.
        If None, the default DicomFileDistance method using Levenshtein
        distance between the field_wieghts will be used.

    kwargs: DicomFileDistance instantiation named arguments
        Apart from the field_weitghts argument.

    Returns
    -------
    file_dists: np.ndarray or scipy.sparse.lil_matrix of shape NxN
        Levenshtein distances between each of the N items in dicom_files.


Check the field values in self.dcmf1 and self.dcmf2 and returns True
        if all the field values are the same, False otherwise.

        Returns
        -------
        bool


Updates the status of the file clusters comparing the cluster
        key files with a levenshtein weighted measure using either the
        header_fields or self.header_fields.

        Parameters
        ----------
        field_weights: dict of strings with floats
            A dict with header field names to float scalar values, that indicate a distance measure
            ratio for the levenshtein distance averaging of all the header field names in it.
            e.g., {'PatientID': 1}


Returns a list of 2-tuples with pairs of dicom groups that
        are in the same folder within given depth.

        Parameters
        ----------
        folder_depth: int
        Path depth to check for folder equality.

        Returns
        -------
        list of tuples of str


Extend the lists within the DICOM groups dictionary.
        The indices will indicate which list have to be extended by which
        other list.

        Parameters
        ----------
        indices: list or tuple of 2 iterables of int, bot having the same len
             The indices of the lists that have to be merged, both iterables
             items will be read pair by pair, the first is the index to the
             list that will be extended with the list of the second index.
             The indices can be constructed with Numpy e.g.,
             indices = np.where(square_matrix)


Copy the file groups to folder_path. Each group will be copied into
        a subfolder with named given by groupby_field.

        Parameters
        ----------
        folder_path: str
         Path to where copy the DICOM files.

        groupby_field_name: str
         DICOM field name. Will get the value of this field to name the group
         folder. If empty or None will use the basename of the group key file.


Set a config by name to a value.


Set AAD token cache.


Set certificate usage paths


Returns a list with of the objects in olist that have a fieldname valued as fieldval

    Parameters
    ----------
    olist: list of objects

    fieldname: string

    fieldval: anything

    Returns
    -------
    list of objets


Return index of the nth match found of pattern in strings

    Parameters
    ----------
    strings: list of str
        List of strings

    pattern: str
        Pattern to be matched

    nth: int
        Number of times the match must happen to return the item index.

    lookup_func: callable
        Function to match each item in strings to the pattern, e.g., re.match or re.search.

    Returns
    -------
    index: int
        Index of the nth item that matches the pattern.
        If there are no n matches will return -1


Generate a dcm2nii configuration file that disable the interactive
    mode.


Call MRICron's `dcm2nii` to convert the DICOM files inside `input_dir`
    to Nifti and save the Nifti file in `output_dir` with a `filename` prefix.

    Parameters
    ----------
    input_dir: str
        Path to the folder that contains the DICOM files

    output_dir: str
        Path to the folder where to save the NifTI file

    filename: str
        Output file basename

    Returns
    -------
    filepaths: list of str
        List of file paths created in `output_dir`.


Return a subset of `filepaths`. Keep only the files that have a basename longer than the
    others with same suffix.
    This works based on that dcm2nii appends a preffix character for each processing
    step it does automatically in the DICOM to NifTI conversion.

    Parameters
    ----------
    filepaths: iterable of str

    Returns
    -------
    cleaned_paths: iterable of str


Extend the within a dict of lists. The indices will indicate which
    list have to be extended by which other list.

    Parameters
    ----------
    adict: OrderedDict
        An ordered dictionary of lists

    indices: list or tuple of 2 iterables of int, bot having the same length
        The indices of the lists that have to be merged, both iterables items
         will be read pair by pair, the first is the index to the list that
         will be extended with the list of the second index.
         The indices can be constructed with Numpy e.g.,
         indices = np.where(square_matrix)

    pop_later: bool
        If True will oop out the lists that are indicated in the second
         list of indices.

    copy: bool
        If True will perform a deep copy of the input adict before
         modifying it, hence not changing the original input.

    Returns
    -------
    Dictionary of lists

    Raises
    ------
    IndexError
        If the indices are out of range


Return a dict of lists from a list of dicts with the same keys.
    For each dict in list_of_dicts with look for the values of the
    given keys and append it to the output dict.

    Parameters
    ----------
    list_of_dicts: list of dicts

    keys: list of str
        List of keys to create in the output dict
        If None will use all keys in the first element of list_of_dicts
    Returns
    -------
    DefaultOrderedDict of lists


Imports the contents of filepath as a Python module.

    :param filepath: string

    :param mod_name: string
    Name of the module when imported

    :return: module
    Imported module


Copies the files in the built file tree map
    to despath.

    :param configfile: string
     Path to the FileTreeMap config file

    :param destpath: string
     Path to the files destination

    :param overwrite: bool
     Overwrite files if they already exist.

    :param sub_node: string
     Tree map configuration sub path.
     Will copy only the contents within this sub-node


Transforms the input .sav SPSS file into other format.
    If you don't specify an outputfile, it will use the
    inputfile and change its extension to .csv


Load a Nifti mask volume.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    allow_empty: boolean, optional
        Allow loading an empty mask (full of 0 values)

    Returns
    -------
    nibabel.Nifti1Image with boolean data.


Load a Nifti mask volume and return its data matrix as boolean and affine.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    allow_empty: boolean, optional
        Allow loading an empty mask (full of 0 values)

    Returns
    -------
    numpy.ndarray with dtype==bool, numpy.ndarray of affine transformation


Creates a binarised mask with the union of the files in filelist.

    Parameters
    ----------
    filelist: list of img-like object or boyle.nifti.NeuroImage or str
        List of paths to the volume files containing the ROIs.
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    Returns
    -------
    ndarray of bools
        Mask volume

    Raises
    ------
    ValueError


Read a Nifti file nii_file and a mask Nifti file.
    Returns the voxels in nii_file that are within the mask, the mask indices
    and the mask shape.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    mask_img: img-like object or boyle.nifti.NeuroImage or str
        3D mask array: True where a voxel should be used.
        See img description.

    Returns
    -------
    vol[mask_indices], mask_indices

    Note
    ----
    nii_file and mask_file must have the same shape.

    Raises
    ------
    NiftiFilesNotCompatible, ValueError


Read a Nifti file nii_file and a mask Nifti file.
    Extract the signals in nii_file that are within the mask, the mask indices
    and the mask shape.

    Parameters
    ----------
    image: img-like object or boyle.nifti.NeuroImage or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    mask_img: img-like object or boyle.nifti.NeuroImage or str
        3D mask array: True where a voxel should be used.
        See img description.

    smooth_mm: float #TBD
        (optional) The size in mm of the FWHM Gaussian kernel to smooth the signal.
        If True, remove_nans is True.

    remove_nans: bool #TBD
        If remove_nans is True (default), the non-finite values (NaNs and
        infs) found in the images will be replaced by zeros.

    Returns
    -------
    session_series, mask_data

    session_series: numpy.ndarray
        2D array of series with shape (voxel number, image number)

    Note
    ----
    nii_file and mask_file must have the same shape.

    Raises
    ------
    FileNotFound, NiftiFilesNotCompatible


Transform a given vector to a volume. This is a reshape function for
    4D flattened masked matrices where the second dimension of the matrix
    corresponds to the original 4th dimension.

    Parameters
    ----------
    arr: numpy.array
        2D numpy.array

    mask: numpy.ndarray
        Mask image. Must have 3 dimensions, bool dtype.

    dtype: return type
        If None, will get the type from vector

    Returns
    -------
    data: numpy.ndarray
        Unmasked data.
        Shape: (mask.shape[0], mask.shape[1], mask.shape[2], X.shape[1])


From the list of absolute paths to nifti files, creates a Numpy array
    with the masked data.

    Parameters
    ----------
    img_filelist: list of str
        List of absolute file paths to nifti files. All nifti files must have
        the same shape.

    mask_file: str
        Path to a Nifti mask file.
        Should be the same shape as the files in nii_filelist.

    outdtype: dtype
        Type of the elements of the array, if not set will obtain the dtype from
        the first nifti file.

    Returns
    -------
    outmat:
        Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors.

    mask_indices:
        Tuple with the 3D spatial indices of the masking voxels, for reshaping
        with vol_shape and remapping.

    vol_shape:
        Tuple with shape of the volumes, for reshaping.


Create record based on dump.


Update an existing record.


Create persistent identifiers.


Create files.

        This method is currently limited to a single bucket per record.


Delete the bucket.


Filter persistent identifiers.


Prepare data.


Get files from data dump.


Load community from data dump.

    :param data: Dictionary containing community data.
    :type data: dict
    :param logos_dir: Path to a local directory with community logos.
    :type logos_dir: str


Load community featuring from data dump.

    :param data: Dictionary containing community featuring data.
    :type data: dict


Create a client for Service Fabric APIs.


Check data in Invenio legacy.


Pipeable aggregation method.

    Takes either
     - a dataframe and a tuple of arguments required for aggregation,
     - a tuple of arguments if a dataframe has already been piped into.
    In any case one argument has to be a class that extends callable.

    :Example:

    aggregate(dataframe, Function, "new_col_name", "old_col_name")

    :Example:

    dataframe >> aggregate(Function, "new_col_name", "old_col_name")

    :param args: tuple of arguments
    :type args: tuple
    :return: returns a dataframe object
    :rtype: DataFrame


Pipeable subsetting method.

    Takes either
     - a dataframe and a tuple of arguments required for subsetting,
     - a tuple of arguments if a dataframe has already been piped into.

    :Example:

    subset(dataframe, "column")

    :Example:

    dataframe >> subset("column")

    :param args: tuple of arguments
    :type args: tuple
    :return: returns a dataframe object
    :rtype: DataFrame


Pipeable modification method

    Takes either
     - a dataframe and a tuple of arguments required for modification,
     - a tuple of arguments if a dataframe has already been piped into.
    In any case one argument has to be a class that extends callable.

    :Example:

    modify(dataframe, Function, "new_col_name", "old_col_name")

    :Example:

    dataframe >> modify(Function, "new_col_name", "old_col_name")

    :param args: tuple of arguments
    :type args: tuple
    :return: returns a dataframe object
    :rtype: DataFrame


Deletes resources of this widget that require manual cleanup.

        Currently removes all actions, event handlers and the background.

        The background itself should automatically remove all vertex lists to avoid visual artifacts.

        Note that this method is currently experimental, as it seems to have a memory leak.


Simple vector helper function returning the length of a vector.

    ``v`` may be any vector, with any number of dimensions


Normalizes the given vector.

    The vector given may have any number of dimensions.


Transforms the given texture coordinates using the internal texture coordinates.

        Currently, the dimensionality of the input texture coordinates must always be 2 and the output is 3-dimensional with the last coordinate always being zero.

        The given texture coordinates are fitted to the internal texture coordinates. Note that values higher than 1 or lower than 0 may result in unexpected visual glitches.

        The length of the given texture coordinates should be divisible by the dimensionality.


Helper method ensuring per-entity bone data has been properly initialized.

        Should be called at the start of every method accessing per-entity data.

        ``data`` is the entity to check in dictionary form.


Sets the length of this bone on the given entity.

        ``data`` is the entity to modify in dictionary form.

        ``blength`` is the new length of the bone.


Sets the parent of this bone for all entities.

        Note that this method must be called before many other methods to ensure internal state has been initialized.

        This method also registers this bone as a child of its parent.


Returns the point this bone pivots around on the given entity.

        This method works recursively by calling its parent and then adding its own offset.

        The resulting coordinate is relative to the entity, not the world.


Callback that is called to initialize this animation on a specific actor.

        Internally sets the ``_anidata`` key of the given dict ``data``\ .

        ``jumptype`` is either ``jump`` or ``animate`` to define how to switch to this animation.


Sets the state required for this actor.

        Currently translates the matrix to the position of the actor.


Resets the state required for this actor to the default state.

        Currently resets the matrix to its previous translation.


Sets the state required for this vertex region.

        Currently binds and enables the texture of the material of the region.


Resets the state required for this actor to the default state.

        Currently only disables the target of the texture of the material, it may still be bound.


Ensures that the given ``obj`` has been initialized to be used with this model.

        If the object is found to not be initialized, it will be initialized.


Redraws the model of the given object.

        Note that currently this method probably won't change any data since all movement and animation is done through pyglet groups.


Actually draws the model of the given object to the render target.

        Note that if the batch used for this object already existed, drawing will be skipped as the batch should be drawn by the owner of it.


Sets the model this actor should use when drawing.

        This method also automatically initializes the new model and removes the old, if any.


write the collection of reports to the given path


Escape a single character


Escape a string so that it only contains characters in a safe set.

    Characters outside the safe list will be escaped with _%x_,
    where %x is the hex value of the character.

    If `allow_collisions` is True, occurrences of `escape_char`
    in the input will not be escaped.

    In this case, `unescape` cannot be used to reverse the transform
    because occurrences of the escape char in the resulting string are ambiguous.
    Only use this mode when:

    1. collisions cannot occur or do not matter, and
    2. unescape will never be called.

    .. versionadded: 1.0
        allow_collisions argument.
        Prior to 1.0, behavior was the same as allow_collisions=False (default).


Determines whether this backend is allowed to send a notification to
        the given user and notice_type.


Copy the attributes from a source object to a destination object.


Returns DataFrameRow of the DataFrame given its index.

        :param idx: the index of the row in the DataFrame.
        :return: returns a DataFrameRow


The notice settings view.

    Template: :template:`notification/notice_settings.html`

    Context:

        notice_types
            A list of all :model:`notification.NoticeType` objects.

        notice_settings
            A dictionary containing ``column_headers`` for each ``NOTICE_MEDIA``
            and ``rows`` containing a list of dictionaries: ``notice_type``, a
            :model:`notification.NoticeType` object and ``cells``, a list of
            tuples whose first value is suitable for use in forms and the second
            value is ``True`` or ``False`` depending on a ``request.POST``
            variable called ``form_label``, whose valid value is ``on``.


Re-draws the text by calculating its position.

        Currently, the text will always be centered on the position of the label.


Re-draws the label by calculating its position.

        Currently, the label will always be centered on the position of the label.


Deletes the widget by the given name.

        Note that this feature is currently experimental as there seems to be a memory leak with this method.


Query Wolfram Alpha and return a Result object


Return list of all Pod objects in result


Registers the motion and drag handlers.

        Note that because of the way pyglet treats mouse dragging, there is also an handler registered to the on_mouse_drag event.


Adds the main label of the dialog.

        This widget can be triggered by setting the label ``label_main`` to a string.

        This widget will be centered on the screen.


Adds an OK button to allow the user to exit the dialog.

        This widget can be triggered by setting the label ``label_ok`` to a string.

        This widget will be mostly centered on the screen, but below the main label
        by the double of its height.


Adds a confirm button to let the user confirm whatever action they were presented with.

        This widget can be triggered by setting the label ``label_confirm`` to a string.

        This widget will be positioned slightly below the main label and to the left
        of the cancel button.


Updates the progressbar by re-calculating the label.

        It is not required to manually call this method since setting any of the
        properties of this class will automatically trigger a re-calculation.


Find a node in the tree. If the node is not found it is added first and then returned.

        :param args: a tuple
        :return: returns the node


Returns site-specific notification language for this user. Raises
    LanguageStoreNotAvailable if this site does not use translated
    notifications.


A basic interface around both queue and send_now. This honors a global
    flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should
    be queued or not. A per call ``queue`` or ``now`` keyword argument can be
    used to always override the default global behavior.


A helper function to write lammps pair potentials to string. Assumes that
    functions are vectorized.

    Parameters
    ----------
    func: function
       A function that will be evaluated for the force at each radius. Required to
       be numpy vectorizable.
    dfunc: function
       Optional. A function that will be evaluated for the energy at each
       radius. If not supplied the centered difference method will be
       used. Required to be numpy vectorizable.
    bounds: tuple, list
       Optional. specifies min and max radius to evaluate the
       potential. Default 1 length unit, 10 length unit.
    samples: int
       Number of points to evaluate potential. Default 1000. Note that
       a low number of sample points will reduce accuracy.
    tollerance: float
       Value used to centered difference differentiation.
    keyword: string
       Lammps keyword to use to pair potential. This keyword will need
       to be used in the lammps pair_coeff. Default ``PAIR``
    filename: string
       Optional. filename to write lammps table potential as. Default
       ``lammps.table`` it is highly recomended to change the value.

    A file for each unique pair potential is required.


Renders the world in 3d-mode.

        If you want to render custom terrain, you may override this method. Be careful that you still call the original method or else actors may not be rendered.


Renders the world.


Start a new step. returns a context manager which allows you to
        report an error


Adds a new texture category with the given name.

        If the category already exists, it will be overridden.


Gets the model object by the given name.

        If it was loaded previously, a cached version will be returned.
        If it was not loaded, it will be loaded and inserted into the cache.


Gets the model data associated with the given name.

        If it was loaded, a cached copy will be returned.
        It it was not loaded, it will be loaded and cached.


Loads the model data of the given name.

        The model file must always be a .json file.


Draws the submenu and its background.

        Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.


Redraws the background and any child widgets.


AABB Collision checker that can be used for most axis-aligned collisions.

    Intended for use in widgets to check if the mouse is within the bounds of a particular widget.


Adds a new layer to the stack, optionally at the specified z-value.

        ``layer`` must be an instance of Layer or subclasses.

        ``z`` can be used to override the index of the layer in the stack. Defaults to ``-1`` for appending.


Checks if elements of set2 are in set1.

    :param set1: a set of values
    :param set2: a set of values
    :param warn: the error message that should be thrown
     when the sets are NOT disjoint
    :return: returns true no elements of set2 are in set1


Checks if all elements from set2 are in set1.

    :param set1:  a set of values
    :param set2:  a set of values
    :param warn: the error message that should be thrown
     when the sets are not containd
    :return: returns true if all values of set2 are in set1


Map a buffer region using this attribute as an accessor.

        The returned region can be modified as if the buffer was a contiguous
        array of this attribute (though it may actually be interleaved or
        otherwise non-contiguous).

        The returned region consists of a contiguous array of component
        data elements.  For example, if this attribute uses 3 floats per
        vertex, and the `count` parameter is 4, the number of floats mapped
        will be ``3 * 4 = 12``.

        :Parameters:
            `buffer` : `AbstractMappable`
                The buffer to map.
            `start` : int
                Offset of the first vertex to map.
            `count` : int
                Number of vertices to map

        :rtype: `AbstractBufferRegion`


Draw vertices in the domain.

        If `vertex_list` is not specified, all vertices in the domain are
        drawn.  This is the most efficient way to render primitives.

        If `vertex_list` specifies a `VertexList`, only primitives in that
        list will be drawn.

        :Parameters:
            `mode` : int
                OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc.
            `vertex_list` : `VertexList`
                Vertex list to draw, or ``None`` for all lists in this domain.


Helper method that calls all callbacks registered for the given action.


Registers a name to the registry.

        ``name`` is the name of the object and must be a string.

        ``force_id`` can be optionally set to override the automatic ID generation
        and force a specific ID.

        Note that using ``force_id`` is discouraged, since it may cause problems when ``reuse_ids`` is false.


Adds the given layer at the given Z Index.

        If ``z_index`` is not given, the Z Index specified by the layer will be used.


Draws all layers of this LayeredWidget.

        This should normally be unneccessary, since it is recommended that layers use Vertex Lists instead of OpenGL Immediate Mode.


Deletes all layers within this LayeredWidget before deleting itself.

        Recommended to call if you are removing the widget, but not yet exiting the interpreter.


Property to be used for setting and getting the border of the layer.

        Note that setting this property causes an immediate redraw.


Property to be used for setting and getting the offset of the layer.

        Note that setting this property causes an immediate redraw.


Serialize object back to XML string.

        Returns:
            str: String which should be same as original input, if everything\
                 works as expected.


Parse MARC XML document to dicts, which are contained in
        self.controlfields and self.datafields.

        Args:
            xml (str or HTMLElement): input data

        Also detect if this is oai marc format or not (see elf.oai_marc).


Parse control fields.

        Args:
            fields (list): list of HTMLElements
            tag_id (str):  parameter name, which holds the information, about
                           field name this is normally "tag", but in case of
                           oai_marc "id".


Parse data fields.

        Args:
            fields (list): of HTMLElements
            tag_id (str): parameter name, which holds the information, about
                          field name this is normally "tag", but in case of
                          oai_marc "id"
            sub_id (str): id of parameter, which holds informations about
                          subfield name this is normally "code" but in case of
                          oai_marc "label"


Return content of given `subfield` in `datafield`.

        Args:
            datafield (str): Section name (for example "001", "100", "700").
            subfield (str):  Subfield name (for example "a", "1", etc..).
            i1 (str, default None): Optional i1/ind1 parameter value, which
               will be used for search.
            i2 (str, default None): Optional i2/ind2 parameter value, which
               will be used for search.
            exception (bool): If ``True``, :exc:`~exceptions.KeyError` is
                      raised when method couldn't found given `datafield` /
                      `subfield`. If ``False``, blank array ``[]`` is returned.

        Returns:
            list: of :class:`.MARCSubrecord`.

        Raises:
            KeyError: If the subfield or datafield couldn't be found.

        Note:
            MARCSubrecord is practically same thing as string, but has defined
            :meth:`.MARCSubrecord.i1` and :attr:`.MARCSubrecord.i2`
            methods.

            You may need to be able to get this, because MARC XML depends on
            i/ind parameters from time to time (names of authors for example).


Connectivity builder using Numba for speed boost.


Add the fields into the list of fields.


Returns the dimension of the embedded space of each element.


Returns a dataframe containing volume and centroids of all the elements.


Returns the internal angles of all elements and the associated statistics


Returns the aspect ratio of all elements.


Returns mesh quality and geometric stats.


Makes a node set from an element set.


Creates elements sets corresponding to a surface.


Returns metadata as a dataframe.


Set the given param for each of the DOFs for a joint.


Given an angle and an axis, create a quaternion.


Given a set of bodies, compute their center of mass in world coordinates.


Set the state of this body.

        Parameters
        ----------
        state : BodyState tuple
            The desired state of the body.


Convert a body-relative offset to world coordinates.

        Parameters
        ----------
        position : 3-tuple of float
            A tuple giving body-relative offsets.

        Returns
        -------
        position : 3-tuple of float
            A tuple giving the world coordinates of the given offset.


Convert a point in world coordinates to a body-relative offset.

        Parameters
        ----------
        position : 3-tuple of float
            A world coordinates position.

        Returns
        -------
        offset : 3-tuple of float
            A tuple giving the body-relative offset of the given position.


Convert a relative body offset to world coordinates.

        Parameters
        ----------
        offset : 3-tuple of float
            The offset of the desired point, given as a relative fraction of the
            size of this body. For example, offset (0, 0, 0) is the center of
            the body, while (0.5, -0.2, 0.1) describes a point halfway from the
            center towards the maximum x-extent of the body, 20% of the way from
            the center towards the minimum y-extent, and 10% of the way from the
            center towards the maximum z-extent.

        Returns
        -------
        position : 3-tuple of float
            A position in world coordinates of the given body offset.


Add a force to this body.

        Parameters
        ----------
        force : 3-tuple of float
            A vector giving the forces along each world or body coordinate axis.
        relative : bool, optional
            If False, the force values are assumed to be given in the world
            coordinate frame. If True, they are assumed to be given in the
            body-relative coordinate frame. Defaults to False.
        position : 3-tuple of float, optional
            If given, apply the force at this location in world coordinates.
            Defaults to the current position of the body.
        relative_position : 3-tuple of float, optional
            If given, apply the force at this relative location on the body. If
            given, this method ignores the ``position`` parameter.


Connect this body to another one using a joint.

        This method creates a joint to fasten this body to the other one. See
        :func:`World.join`.

        Parameters
        ----------
        joint : str
            The type of joint to use when connecting these bodies.
        other_body : :class:`Body` or str, optional
            The other body to join with this one. If not given, connects this
            body to the world.


Move another body next to this one and join them together.

        This method will move the ``other_body`` so that the anchor points for
        the joint coincide. It then creates a joint to fasten the two bodies
        together. See :func:`World.move_next_to` and :func:`World.join`.

        Parameters
        ----------
        joint : str
            The type of joint to use when connecting these bodies.
        other_body : :class:`Body` or str
            The other body to join with this one.
        offset : 3-tuple of float, optional
            The body-relative offset where the anchor for the joint should be
            placed. Defaults to (0, 0, 0). See :func:`World.move_next_to` for a
            description of how offsets are specified.
        other_offset : 3-tuple of float, optional
            The offset on the second body where the joint anchor should be
            placed. Defaults to (0, 0, 0). Like ``offset``, this is given as an
            offset relative to the size and shape of ``other_body``.


List of positions for linear degrees of freedom.


List of position rates for linear degrees of freedom.


List of angles for rotational degrees of freedom.


List of angle rates for rotational degrees of freedom.


List of axes for this object's degrees of freedom.


Set the lo stop values for this object's degrees of freedom.

        Parameters
        ----------
        lo_stops : float or sequence of float
            A lo stop value to set on all degrees of freedom, or a list
            containing one such value for each degree of freedom. For rotational
            degrees of freedom, these values must be in radians.


Set the hi stop values for this object's degrees of freedom.

        Parameters
        ----------
        hi_stops : float or sequence of float
            A hi stop value to set on all degrees of freedom, or a list
            containing one such value for each degree of freedom. For rotational
            degrees of freedom, these values must be in radians.


Set the target velocities for this object's degrees of freedom.

        Parameters
        ----------
        velocities : float or sequence of float
            A target velocity value to set on all degrees of freedom, or a list
            containing one such value for each degree of freedom. For rotational
            degrees of freedom, these values must be in radians / second.


Set the CFM values for this object's degrees of freedom.

        Parameters
        ----------
        cfms : float or sequence of float
            A CFM value to set on all degrees of freedom, or a list
            containing one such value for each degree of freedom.


Set the CFM values for this object's DOF limits.

        Parameters
        ----------
        stop_cfms : float or sequence of float
            A CFM value to set on all degrees of freedom limits, or a list
            containing one such value for each degree of freedom limit.


Set the ERP values for this object's DOF limits.

        Parameters
        ----------
        stop_erps : float or sequence of float
            An ERP value to set on all degrees of freedom limits, or a list
            containing one such value for each degree of freedom limit.


Set the linear axis of displacement for this joint.

        Parameters
        ----------
        axes : list containing one 3-tuple of floats
            A list of the axes for this joint. For a slider joint, which has one
            degree of freedom, this must contain one 3-tuple specifying the X,
            Y, and Z axis for the joint.


Set the angular axis of rotation for this joint.

        Parameters
        ----------
        axes : list containing one 3-tuple of floats
            A list of the axes for this joint. For a hinge joint, which has one
            degree of freedom, this must contain one 3-tuple specifying the X,
            Y, and Z axis for the joint.


Create a new body.

        Parameters
        ----------
        shape : str
            The "shape" of the body to be created. This should name a type of
            body object, e.g., "box" or "cap".
        name : str, optional
            The name to use for this body. If not given, a default name will be
            constructed of the form "{shape}{# of objects in the world}".

        Returns
        -------
        body : :class:`Body`
            The created body object.


Create a new joint that connects two bodies together.

        Parameters
        ----------
        shape : str
            The "shape" of the joint to use for joining together two bodies.
            This should name a type of joint, such as "ball" or "piston".
        body_a : str or :class:`Body`
            The first body to join together with this joint. If a string is
            given, it will be used as the name of a body to look up in the
            world.
        body_b : str or :class:`Body`, optional
            If given, identifies the second body to join together with
            ``body_a``. If not given, ``body_a`` is joined to the world.
        name : str, optional
            If given, use this name for the created joint. If not given, a name
            will be constructed of the form
            "{body_a.name}^{shape}^{body_b.name}".

        Returns
        -------
        joint : :class:`Joint`
            The joint object that was created.


Move one body to be near another one.

        After moving, the location described by ``offset_a`` on ``body_a`` will
        be coincident with the location described by ``offset_b`` on ``body_b``.

        Parameters
        ----------
        body_a : str or :class:`Body`
            The body to use as a reference for moving the other body. If this is
            a string, it is treated as the name of a body to look up in the
            world.
        body_b : str or :class:`Body`
            The body to move next to ``body_a``. If this is a string, it is
            treated as the name of a body to look up in the world.
        offset_a : 3-tuple of float
            The offset of the anchor point, given as a relative fraction of the
            size of ``body_a``. See :func:`Body.relative_offset_to_world`.
        offset_b : 3-tuple of float
            The offset of the anchor point, given as a relative fraction of the
            size of ``body_b``.

        Returns
        -------
        anchor : 3-tuple of float
            The location of the shared point, which is often useful to use as a
            joint anchor.


Set the states of some bodies in the world.

        Parameters
        ----------
        states : sequence of states
            A complete state tuple for one or more bodies in the world. See
            :func:`get_body_states`.


Step the world forward by one frame.

        Parameters
        ----------
        substeps : int, optional
            Split the step into this many sub-steps. This helps to prevent the
            time delta for an update from being too large.


Determine whether the given bodies are currently connected.

        Parameters
        ----------
        body_a : str or :class:`Body`
            One body to test for connectedness. If this is a string, it is
            treated as the name of a body to look up.
        body_b : str or :class:`Body`
            One body to test for connectedness. If this is a string, it is
            treated as the name of a body to look up.

        Returns
        -------
        connected : bool
            Return True iff the two bodies are connected.


Traverse the bone hierarchy and create physics bodies.


Parse informations about corporations from given field identified
        by `datafield` parameter.

        Args:
            datafield (str): MARC field ID ("``110``", "``610``", etc..)
            subfield (str):  MARC subfield ID with name, which is typically
                             stored in "``a``" subfield.
            roles (str): specify which roles you need. Set to ``["any"]`` for
                         any role, ``["dst"]`` for distributors, etc.. For
                         details, see
                         http://www.loc.gov/marc/relators/relaterm.html

        Returns:
            list: :class:`Corporation` objects.


Get list of VALID ISBN.

        Returns:
            list: List with *valid* ISBN strings.


Content of field ``856u42``. Typically URL pointing to producers
        homepage.

        Returns:
            list: List of URLs defined by producer.


URL's, which may point to edeposit, aleph, kramerius and so on.

        Fields ``856u40``, ``998a`` and ``URLu``.

        Returns:
            list: List of internal URLs.


r'''Create a callable that implements a PID controller.

    A PID controller returns a control signal :math:`u(t)` given a history of
    error measurements :math:`e(0) \dots e(t)`, using proportional (P), integral
    (I), and derivative (D) terms, according to:

    .. math::

       u(t) = kp * e(t) + ki * \int_{s=0}^t e(s) ds + kd * \frac{de(s)}{ds}(t)

    The proportional term is just the current error, the integral term is the
    sum of all error measurements, and the derivative term is the instantaneous
    derivative of the error measurement.

    Parameters
    ----------
    kp : float
        The weight associated with the proportional term of the PID controller.
    ki : float
        The weight associated with the integral term of the PID controller.
    kd : float
        The weight associated with the derivative term of the PID controller.
    smooth : float in [0, 1]
        Derivative values will be smoothed with this exponential average. A
        value of 1 never incorporates new derivative information, a value of 0.5
        uses the mean of the historic and new information, and a value of 0
        discards historic information (i.e., the derivative in this case will be
        unsmoothed). The default is 0.1.

    Returns
    -------
    controller : callable (float, float) -> float
        Returns a function that accepts an error measurement and a delta-time
        value since the previous measurement, and returns a control signal.


Load a skeleton definition from an ASF text file.

        Parameters
        ----------
        source : str or file
            A filename or file-like object that contains text information
            describing a skeleton, in ASF format.


Set PID parameters for all joints in the skeleton.

        Parameters for this method are passed directly to the `pid` constructor.


Get a list of the indices for a specific joint.

        Parameters
        ----------
        name : str
            The name of the joint to look up.

        Returns
        -------
        list of int :
            A list of the index values for quantities related to the named
            joint. Often useful for getting, say, the angles for a specific
            joint in the skeleton.


Get a list of the indices for a specific body.

        Parameters
        ----------
        name : str
            The name of the body to look up.
        step : int, optional
            The number of numbers for each body. Defaults to 3, should be set
            to 4 for body rotation (since quaternions have 4 values).

        Returns
        -------
        list of int :
            A list of the index values for quantities related to the named body.


Get the current joint separations for the skeleton.

        Returns
        -------
        distances : list of float
            A list expressing the distance between the two joint anchor points,
            for each joint in the skeleton. These quantities describe how
            "exploded" the bodies in the skeleton are; a value of 0 indicates
            that the constraints are perfectly satisfied for that joint.


Add torques for each degree of freedom in the skeleton.

        Parameters
        ----------
        torques : list of float
            A list of the torques to add to each degree of freedom in the
            skeleton.


Runs the post-proc script.


Makes the mesh using gmsh.


Reads an history output report.


Reads a field output report.


Converts a list-like to string with given line width.


Returns an Abaqus INP formated string for a given linear equation.


Returns a set as inp string with unsorted option.


Parses the API response and raises appropriate
        errors if raise_errors was set to True

        :param response: response from requests http call
        :returns: dictionary of response
        :rtype: dict


Builds the url for the specified method and arguments and returns
        the response as a dictionary.


Return the names of our marker labels in canonical order.


Load marker data from a CSV file.

        The file will be imported using Pandas, which must be installed to use
        this method. (``pip install pandas``)

        The first line of the CSV file will be used for header information. The
        "time" column will be used as the index for the data frame. There must
        be columns named 'markerAB-foo-x','markerAB-foo-y','markerAB-foo-z', and
        'markerAB-foo-c' for marker 'foo' to be included in the model.

        Parameters
        ----------
        filename : str
            Name of the CSV file to load.


Load attachment configuration from the given text source.

        The attachment configuration file has a simple format. After discarding
        Unix-style comments (any part of a line that starts with the pound (#)
        character), each line in the file is then expected to have the following
        format::

            marker-name body-name X Y Z

        The marker name must correspond to an existing "channel" in our marker
        data. The body name must correspond to a rigid body in the skeleton. The
        X, Y, and Z coordinates specify the body-relative offsets where the
        marker should be attached: 0 corresponds to the center of the body along
        the given axis, while -1 and 1 correspond to the minimal (maximal,
        respectively) extent of the body's bounding box along the corresponding
        dimension.

        Parameters
        ----------
        source : str or file-like
            A filename or file-like object that we can use to obtain text
            configuration that describes how markers are attached to skeleton
            bodies.

        skeleton : :class:`pagoda.skeleton.Skeleton`
            The skeleton to attach our marker data to.


Reposition markers to a specific frame of data.

        Parameters
        ----------
        frame_no : int
            The frame of data where we should reposition marker bodies. Markers
            will be positioned in the appropriate places in world coordinates.
            In addition, linear velocities of the markers will be set according
            to the data as long as there are no dropouts in neighboring frames.


Get a list of the distances between markers and their attachments.

        Returns
        -------
        distances : ndarray of shape (num-markers, 3)
            Array of distances for each marker joint in our attachment setup. If
            a marker does not currently have an associated joint (e.g. because
            it is not currently visible) this will contain NaN for that row.


Return an array of the forces exerted by marker springs.

        Notes
        -----

        The forces exerted by the marker springs can be approximated by::

          F = kp * dx

        where ``dx`` is the current array of marker distances. An even more
        accurate value is computed by approximating the velocity of the spring
        displacement::

          F = kp * dx + kd * (dx - dx_tm1) / dt

        where ``dx_tm1`` is an array of distances from the previous time step.

        Parameters
        ----------
        dx_tm1 : ndarray
            An array of distances from markers to their attachment targets,
            measured at the previous time step.

        Returns
        -------
        F : ndarray
            An array of forces that the markers are exerting on the skeleton.


Create and configure a skeleton in our model.

        Parameters
        ----------
        filename : str
            The name of a file containing skeleton configuration data.
        pid_params : dict, optional
            If given, use this dictionary to set the PID controller
            parameters on each joint in the skeleton. See
            :func:`pagoda.skeleton.pid` for more information.


Load marker data and attachment preferences into the model.

        Parameters
        ----------
        filename : str
            The name of a file containing marker data. This currently needs to
            be either a .C3D or a .CSV file. CSV files must adhere to a fairly
            strict column naming convention; see :func:`Markers.load_csv` for
            more information.
        attachments : str
            The name of a text file specifying how markers are attached to
            skeleton bodies.
        max_frames : number, optional
            Only read in this many frames of marker data. By default, the entire
            data file is read into memory.

        Returns
        -------
        markers : :class:`Markers`
            Returns a markers object containing loaded marker data as well as
            skeleton attachment configuration.


Advance the physics world by one step.

        Typically this is called as part of a :class:`pagoda.viewer.Viewer`, but
        it can also be called manually (or some other stepping mechanism
        entirely can be used).


Settle the skeleton to our marker data at a specific frame.

        Parameters
        ----------
        frame_no : int, optional
            Settle the skeleton to marker data at this frame. Defaults to 0.
        max_distance : float, optional
            The settling process will stop when the mean marker distance falls
            below this threshold. Defaults to 0.1m (10cm). Setting this too
            small prevents the settling process from finishing (it will loop
            indefinitely), and setting it too large prevents the skeleton from
            settling to a stable state near the markers.
        max_iters : int, optional
            Attempt to settle markers for at most this many iterations. Defaults
            to 1000.
        states : list of body states, optional
            If given, set the bodies in our skeleton to these kinematic states
            before starting the settling process.


Iterate over a set of marker data, dragging its skeleton along.

        Parameters
        ----------
        start : int, optional
            Start following marker data after this frame. Defaults to 0.
        end : int, optional
            Stop following marker data after this frame. Defaults to the end of
            the marker data.
        states : list of body states, optional
            If given, set the states of the skeleton bodies to these values
            before starting to follow the marker data.


Follow a set of angle data, yielding dynamic joint torques.

        Parameters
        ----------
        angles : ndarray (num-frames x num-dofs)
            Follow angle data provided by this array of angle values.
        start : int, optional
            Start following angle data after this frame. Defaults to the start
            of the angle data.
        end : int, optional
            Stop following angle data after this frame. Defaults to the end of
            the angle data.
        states : list of body states, optional
            If given, set the states of the skeleton bodies to these values
            before starting to follow the marker data.
        max_force : float, optional
            Allow each degree of freedom in the skeleton to exert at most this
            force when attempting to follow the given joint angles. Defaults to
            100N. Setting this value to be large results in more accurate
            following but can cause oscillations in the PID controllers,
            resulting in noisy torques.

        Returns
        -------
        torques : sequence of torque frames
            Returns a generator of joint torque data for the skeleton. One set
            of joint torques will be generated for each frame of angle data
            between `start` and `end`.


Sort values, but put numbers after alphabetically sorted words.

    This function is here to make outputs diff-compatible with Aleph.

    Example::
        >>> sorted(["b", "1", "a"])
        ['1', 'a', 'b']
        >>> resorted(["b", "1", "a"])
        ['a', 'b', '1']

    Args:
        values (iterable): any iterable object/list/tuple/whatever.

    Returns:
        list of sorted values, but with numbers after words


Draw all bodies in the world.


Writes a field report and rewrites it in a cleaner format.


List components that are available on your machine


Get room stream to listen for messages.

        Kwargs:
            error_callback (func): Callback to call when an error occurred (parameters: exception)
            live (bool): If True, issue a live stream, otherwise an offline stream

        Returns:
            :class:`Stream`. Stream


Set the room name.

        Args:
            name (str): Name

        Returns:
            bool. Success


Returns a list of paths specified by the XDG_CONFIG_DIRS environment
        variable or the appropriate default.

        The list is sorted by precedence, with the most important item coming
        *last* (required by the existing config_resolver logic).


Searches for an appropriate config file. If found, loads the file into
        the current instance. This method can also be used to reload a
        configuration. Note that you may want to set ``reload`` to ``True`` to
        clear the configuration before loading in that case.  Without doing
        that, values will remain available even if they have been removed from
        the config files.

        :param reload: if set to ``True``, the existing values are cleared
                       before reloading.
        :param require_load: If set to ``True`` this will raise a
                             :py:exc:`IOError` if no config file has been found
                             to load.


Return an error message for use in exceptions thrown by
        subclasses.


This method will be called to set Series data


sets the graph ploting options


Get styles.


Create a connection with given settings.

        Args:
            settings (dict): A dictionary of settings

        Returns:
            :class:`Connection`. The connection


Issue a PUT request.

        Kwargs:
            url (str): Destination URL
            post_data (dict): Dictionary of parameter and values
            parse_data (bool): If true, parse response data
            key (string): If parse_data==True, look for this key when parsing data
            parameters (dict): Additional GET parameters to append to the URL

        Returns:
            dict. Response (a dict with keys: success, data, info, body)

        Raises:
            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception


Issue a POST request.

        Kwargs:
            url (str): Destination URL
            post_data (dict): Dictionary of parameter and values
            parse_data (bool): If true, parse response data
            key (string): If parse_data==True, look for this key when parsing data
            parameters (dict): Additional GET parameters to append to the URL
            listener (func): callback called when uploading a file

        Returns:
            dict. Response (a dict with keys: success, data, info, body)

        Raises:
            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception


Issue a GET request.

        Kwargs:
            url (str): Destination URL
            parse_data (bool): If true, parse response data
            key (string): If parse_data==True, look for this key when parsing data
            parameters (dict): Additional GET parameters to append to the URL

        Returns:
            dict. Response (a dict with keys: success, data, info, body)

        Raises:
            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError, Exception


Get headers.

        Returns:
            tuple: Headers


Get URL used for authentication

        Returns:
            string: URL


Parses a response.

        Args:
            text (str): Text to parse

        Kwargs:
            key (str): Key to look for, if any

        Returns:
            Parsed value

        Raises:
            ValueError


Issue a request.

        Args:
            method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None

        Kwargs:
            url (str): Destination URL
            post_data (str): A string of what to POST
            parse_data (bool): If true, parse response data
            key (string): If parse_data==True, look for this key when parsing data
            parameters (dict): Additional GET parameters to append to the URL
            listener (func): callback called when uploading a file
            full_return (bool): If set to True, get a full response (with success, data, info, body)

        Returns:
            dict. Response. If full_return==True, a dict with keys: success, data, info, body, otherwise the parsed data

        Raises:
            AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError


Get rooms list.

        Kwargs:
            sort (bool): If True, sort rooms by name

        Returns:
            array. List of rooms (each room is a dict)


Get room.

        Returns:
            :class:`Room`. Room


Get user.

        Returns:
            :class:`User`. User


Search transcripts.

        Args:
            terms (str): Terms for search

        Returns:
            array. Messages


Called when incoming messages arrive.

        Args:
            messages (tuple): Messages (each message is a dict)


Fetch new messages.


Called when new messages arrive.

        Args:
            messages (tuple): Messages


Callback issued by twisted when new line arrives.

        Args:
            line (str): Incoming line


Process data.

        Args:
            data (str): Incoming data


Cleanup code after asked to stop producing.

        Kwargs:
            forced (bool): If True, we were forced to stop


Send a block of bytes to the consumer.

        Args:
            block (str): Block of bytes


Returns total length for this request.

        Returns:
            int. Length


Build headers for each field.


A strategy which generates filesystem path values.

    The generated values include everything which the builtin
    :func:`python:open` function accepts i.e. which won't lead to
    :exc:`ValueError` or :exc:`TypeError` being raised.

    Note that the range of the returned values depends on the operating
    system, the Python version, and the filesystem encoding as returned by
    :func:`sys.getfilesystemencoding`.

    :param allow_pathlike:
        If :obj:`python:None` makes the strategy include objects implementing
        the :class:`python:os.PathLike` interface when Python >= 3.6 is used.
        If :obj:`python:False` no pathlike objects will be generated. If
        :obj:`python:True` pathlike will be generated (Python >= 3.6 required)

    :type allow_pathlike: :obj:`python:bool` or :obj:`python:None`

    .. versionadded:: 3.15


Convert str_value to an int or a float, depending on the
        numeric value represented by str_value.


Tag to plot graphs into the template


exec compiled code


replace all blocks in extends with current blocks


Processes the texts using TweeboParse and returns them in CoNLL format.

        :param texts: The List of Strings to be processed by TweeboParse.
        :param retry_count: The number of times it has retried for. Default
                            0 does not require setting, main purpose is for
                            recursion.
        :return: A list of CoNLL formated strings.
        :raises ServerError: Caused when the server is not running.
        :raises :py:class:`requests.exceptions.HTTPError`: Caused when the
                input texts is not formated correctly e.g. When you give it a
                String not a list of Strings.
        :raises :py:class:`json.JSONDecodeError`: Caused if after self.retries
                attempts to parse the data it cannot decode the data.

        :Example:


Set entity data

        Args:
            data (dict): Entity data
            datetime_fields (array): Fields that should be parsed as datetimes


validates XML text


validates XML name


Try really really hard to get a Unicode copy of a string.

    First try :class:`BeautifulSoup.UnicodeDammit` to try to force
    to Unicode; if that fails, assume UTF-8 encoding, and ignore
    all errors.

    :param str raw: string to coerce
    :return: Unicode approximation of `raw`
    :returntype: :class:`unicode`


Get a clean text representation of presumed HTML.

    Treat `raw` as though it is HTML, even if we have no idea what it
    really is, and attempt to get a properly formatted HTML document
    with all HTML-escaped characters converted to their unicode.

    This is called below by the `clean_html` transform stage, which
    interprets MIME-type.  If `character_encoding` is not provided,
    and `stream_item` is provided, then this falles back to
    :attr:`streamcorpus.StreamItem.body.encoding`.

    :param str raw: raw text to clean up
    :param stream_item: optional stream item with encoding metadata
    :type stream_item: :class:`streamcorpus.StreamItem`
    :returns: UTF-8-encoded byte string of cleaned HTML text
    :returntype: :class:`str`


Give the actors, the world, and the messaging system a chance to react
        to the end of the game.


extract a lower-case, no-slashes domain name from a raw string
    that might be a URL


returns a list of strings created by splitting the domain on
    '.' and successively cutting off the left most portion


Get a Murmur hash and a normalized token.

        `tok` may be a :class:`unicode` string or a UTF-8-encoded
        byte string.  :data:`DOCUMENT_HASH_KEY`, hash value 0, is
        reserved for the document count, and this function remaps
        that value.

        :param tok: token to hash
        :return: pair of normalized `tok` and its hash


Collect all of the words to be indexed from a stream item.

        This scans `si` for all of the configured tagger IDs.  It
        collects all of the token values (the
        :attr:`streamcorpus.Token.token`) and returns a
        :class:`collections.Counter` of them.

        :param si: stream item to scan
        :type si: :class:`streamcorpus.StreamItem`
        :return: counter of :class:`unicode` words to index
        :returntype: :class:`collections.Counter`


Get stream IDs for a single hash.

        This yields strings that can be retrieved using
        :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`,
        or fed back into :mod:`coordinate` or other job queue systems.

        Note that for common terms this can return a large number of
        stream IDs!  This is a scan over a dense region of a
        :mod:`kvlayer` table so it should be reasonably efficient,
        but be prepared for it to return many documents in a large
        corpus.  Blindly storing the results in a :class:`list`
        may be inadvisable.

        This will return nothing unless the index was written with
        :attr:`hash_docs` set.  No document will correspond to
        :data:`DOCUMENT_HASH_KEY`; use
        :data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead.

        :param int h: Murmur hash to look up


Create a ContentItem from a node in the spinn3r data tree.

    The ContentItem is created with raw data set to ``node.data``,
    decompressed if the node's encoding is 'zlib', and UTF-8
    normalized, with a MIME type from ``node.mime_type``.

    ``node``
      the actual node from the spinn3r protobuf data
    ``mime_type``
      string MIME type to use (defaults to ``node.mime_type``)
    ``alternate_data``
      alternate (compressed) data to use, if ``node.data`` is missing
      or can't be decompressed


Read exactly a varint out of the underlying file.


Change working directory and restore the previous on exit


Removes the suffix, if it's there, otherwise returns input string unchanged.
    If strict is True, also ensures the suffix was present


Are all the elements of needle contained in haystack, and in the same order?
    There may be other elements interspersed throughout


Stop the simple WSGI server running the appliation.


Decorator to add a callback that generates error page.

        The *status* parameter specifies the HTTP response status code
        for which the decorated callback should be invoked. If the
        *status* argument is not specified, then the decorated callable
        is considered to be a fallback callback.

        A fallback callback, when defined, is invoked to generate the
        error page for any HTTP response representing an error when
        there is no error handler defined explicitly for the response
        code of the HTTP response.

        Arguments:
          status(int, optional): HTTP response status code.

        Returns:
          function: Decorator function to add error handler.


Send content of a static file as response.

        The path to the document root directory should be specified as
        the root argument. This is very important to prevent directory
        traversal attack. This method guarantees that only files within
        the document root directory are served and no files outside this
        directory can be accessed by a client.

        The path to the actual file to be returned should be specified
        as the path argument. This path must be relative to the document
        directory.

        The *media_type* and *charset* arguments are used to set the
        Content-Type header of the HTTP response. If *media_type*
        is not specified or specified as ``None`` (the default), then it
        is guessed from the filename of the file to be returned.

        Arguments:
          root (str): Path to document root directory.
          path (str): Path to file relative to document root directory.
          media_type (str, optional): Media type of file.
          charset (str, optional): Character set of file.

        Returns:
          bytes: Content of file to be returned in the HTTP response.


Return an error page for the current response status.


Resolve a request to a route handler.

        Arguments:
          method (str): HTTP method, e.g. GET, POST, etc. (type: str)
          path (str): Request path

        Returns:
          tuple or None: A tuple of three items:

            1. Route handler (callable)
            2. Positional arguments (list)
            3. Keyword arguments (dict)

          ``None`` if no route matches the request.


Return the HTTP response body.

        Returns:
          bytes: HTTP response body as a sequence of bytes


Add a Set-Cookie header to response object.

        For a description about cookie attribute values, see
        https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel.

        Arguments:
          name (str): Name of the cookie
          value (str): Value of the cookie
          attrs (dict): Dicitionary with cookie attribute keys and
                        values.


Return the HTTP response status line.

        The status line is determined from :attr:`status` code. For
        example, if the status code is 200, then '200 OK' is returned.

        Returns:
          str: Status line


Return the value of Content-Type header field.

        The value for the Content-Type header field is determined from
        the :attr:`media_type` and :attr:`charset` data attributes.

        Returns:
          str: Value of Content-Type header field


Return the list of all values for the specified key.

        Arguments:
          key (object): Key
          default (list): Default value to return if the key does not
            exist, defaults to ``[]``, i.e. an empty list.

        Returns:
          list: List of all values for the specified key if the key
          exists, ``default`` otherwise.


Template variables.


return list of open files for current process

    .. warning: will only work on UNIX-like os-es.


get a rejester.WorkUnit with KBA s3 path, fetch it, and save
     some counts about it.


attempt a fetch and iteration over a work_unit.key path in s3


Return a list of non-empty lines from `file_path`.


Return an ordered 2-tuple containing a species and a describer.


Return an ordered 2-tuple containing a species and a describer.
    The letter-count of the pair is guarantee to not exceed `maxlen` if
    it is given. If `prevent_stutter` is True, the last letter of the
    first item of the pair will be different from the first letter of
    the second item.


Use when application is starting.


Catch a connection asyncrounosly.


Initialize self.


Asyncronously wait for a connection from the pool.


Listen for an id from the server.

        At the beginning of a game, each client receives an IdFactory from the
        server.  This factory are used to give id numbers that are guaranteed
        to be unique to tokens that created locally.  This method checks to see if such
        a factory has been received.  If it hasn't, this method does not block
        and immediately returns False.  If it has, this method returns True
        after saving the factory internally.  At this point it is safe to enter
        the GameStage.


Register the given callback to be called whenever the method with the
        given name is called.  You can easily take advantage of this feature in
        token extensions by using the @watch_token decorator.


Morphological analysis for Japanese.


Scoring the similarity of two words.


Convert the Japanese to Hiragana or Katakana.


Extract unique representation from sentence.


Summarize reviews into a short summary.


Extract "keywords" from an input document.


Converts XML tree to event generator


Converts events stream into lXML tree


Parses file content into events stream


locates ENTER peer for each EXIT object. Convenient when selectively
    filtering out XML markup


Create a pipeline stage.

        Instantiates `stage` with `config`.  This essentially
        translates to ``stage(config)``, except that two keys from
        `scp_config` are injected into the configuration:
        ``tmp_dir_path`` is an execution-specific directory from
        combining the top-level ``tmp_dir_path`` configuration with
        :attr:`tmp_dir_suffix`; and ``third_dir_path`` is the same
        path from the top-level configuration.  `stage` may be either
        a callable returning the stage (e.g. its class), or its name
        in the configuration.

        `scp_config` is the configuration for the pipeline as a
        whole, and is required.  `config` is the configuration for
        the stage; if it is :const:`None` then it is extracted
        from `scp_config`.

        If you already have a fully formed configuration block
        and want to create a stage, you can call

        .. code-block:: python

            factory.registry[stage](stage_config)

        In most cases if you have a stage class object and want to
        instantiate it with its defaults you can call

        .. code-block:: python

            stage = stage_cls(stage_cls.default_config)

        .. note:: This mirrors
                  :meth:`yakonfig.factory.AutoFactory.create`, with
                  some thought that this factory class might migrate
                  to using that as a base in the future.

        :param stage: pipeline stage class, or its name in the registry
        :param dict scp_config: configuration block for the pipeline
        :param dict config: configuration block for the stage, or
          :const:`None` to get it from `scp_config`


Run the pipeline.

        This runs all of the steps described in the pipeline constructor,
        reading from some input and writing to some output.

        :param str i_str: name of the input file, or other reader-specific
          description of where to get input
        :param int start_count: index of the first stream item
        :param int start_chunk_time: timestamp for the first stream item


Run all of the writers over some intermediate chunk.

        :param int start_count: index of the first item
        :param int next_idx: index of the next item (after the last
          item in this chunk)
        :param list sources: source strings included in this chunk
          (usually only one source)
        :param str i_str: name of input file or other input
        :param str t_path: location of intermediate chunk on disk
        :return: list of output file paths or other outputs


Run transforms on stream item.
        Item may be discarded by some transform.
        Writes successful items out to current self.t_chunk
        Returns transformed item or None.


construct BusinessDate instance from datetime.date instance,
        raise ValueError exception if not possible

        :param datetime.date datetime_date: calendar day
        :return bool:


construct datetime.date instance represented calendar date of BusinessDate instance

        :return datetime.date:


addition of a period object

        :param BusinessDate d:
        :param p:
        :type p: BusinessPeriod or str
        :param list holiday_obj:
        :return bankdate:


addition of a number of months

        :param BusinessDate d:
        :param int month_int:
        :return bankdate:


Replace the top-level pipeline configurable object.

    This investigates a number of sources, including
    `external_stages_path` and `external_stages_modules` configuration
    and `streamcorpus_pipeline.stages` entry points, and uses these to
    find the actual :data:`sub_modules` for
    :mod:`streamcorpus_pipeline`.


assemble in-doc coref chains by mapping equiv_id to tokens and
    their cleansed name strings

    :param sentences: iterator over token generators
    :returns dict:
        keys are equiv_ids,
        values are tuple(concatentated name string, list of tokens)


For each name string in the target_mentions list, searches through
    all chain_mentions looking for any cleansed Token.token that
    contains the name.  Returns True only if all of the target_mention
    strings appeared as substrings of at least one cleansed
    Token.token.  Otherwise, returns False.

    :type target_mentions: list of basestring
    :type chain_mentions: list of basestring

    :returns bool:


For each name string in the target_mentions list, searches through
    all chain_mentions looking for any cleansed Token.token that
    contains the name.  Returns True if any of the target_mention
    strings appeared as substrings of any cleansed Token.token.
    Otherwise, returns False.

    :type target_mentions: list of basestring
    :type chain_mentions: list of basestring

    :returns bool:


iterate through all tokens looking for matches of cleansed tokens
    or token regexes, skipping tokens left empty by cleansing and
    coping with Token objects that produce multiple space-separated
    strings when cleansed.  Yields tokens that match.


iterate through tokens looking for near-exact matches to strings
    in si.ratings...mentions


run tagger a child process to get XML output


send SIGTERM to the tagger child process


Replace all angle bracket emails with a unique key.


generate strings identified as sentences


make a sortedcollection on body.labels


assemble Sentence and Token objects


Convert any HTML, XML, or numeric entities in the attribute values.
    For example '&' becomes '&'.

    This is adapted from BeautifulSoup, which should be able to do the
    same thing when called like this --- but this fails to convert
    everything for some bug.

    text = unicode(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.XML_ENTITIES))


returns number of days for the given year and month

    :param int year: calendar year
    :param int month: calendar month
    :return int:


Initialize the application.


Register connection's middleware and prepare self database.


Close all connections.


Register a model in self.


Manage a database connection.


make a temp file of cleansed text


Convert a string of text into a lowercase string with no
    punctuation and only spaces for whitespace.

    :param span: string


iterate through the i_chunk and tmp_ner_path to generate a new
    Chunk with body.ner


setup the config and load external modules

    This updates 'config' as follows:

    * All paths are replaced with absolute paths
    * A hash and JSON dump of the config are stored in the config
    * If 'pythonpath' is in the config, it is added to sys.path
    * If 'setup_modules' is in the config, all modules named in it are loaded


This _looks_ like a Chunk only in that it generates StreamItem
    instances when iterated upon.


Takes an HTML-like binary string as input and returns a binary
    string of the same length with all tags replaced by whitespace.
    This also detects script and style tags, and replaces the text
    between them with whitespace.

    Pre-existing whitespace of any kind (newlines, tabs) is converted
    to single spaces ' ', which has the same byte length (and
    character length).

    Note: this does not change any characters like ’ and  ,
    so taggers operating on this text must cope with such symbols.
    Converting them to some other character would change their byte
    length, even if equivalent from a character perspective.

    This is regex based, which can occassionally just hang...


make a temp file of clean_visible text


Convert a unicode string into a lowercase string with no
punctuation and only spaces for whitespace.

Replace PennTreebank escaped brackets with ' ':
-LRB- -RRB- -RSB- -RSB- -LCB- -RCB-
(The acronyms stand for (Left|Right) (Round|Square|Curly) Bracket.)
http://www.cis.upenn.edu/~treebank/tokenization.html

:param span: string


manual test loop for make_clean_visible_from_raw


Try to load a stage into self, ignoring errors.

        If loading a module fails because of some subordinate load
        failure, just give a warning and move on.  On success the
        stage is added to the stage dictionary.

        :param str moduleName: name of the Python module
        :param str functionName: name of the stage constructor
        :param str name: name of the stage, defaults to `functionName`


Add external stages from the Python module in `path`.

        `path` must be a path to a Python module source that contains
        a `Stages` dictionary, which is a map from stage name to callable.

        :param str path: path to the module file


Add external stages from the Python module `mod`.

        If `mod` is a string, then it will be interpreted as the name
        of a module; otherwise it is an actual module object.  The
        module should exist somewhere in :data:`sys.path`.  The module
        must contain a `Stages` dictionary, which is a map from stage
        name to callable.

        :param mod: name of the module or the module itself
        :raise exceptions.ImportError: if `mod` cannot be loaded or does
          not contain ``Stages``


iterates through idx_bytes until a byte in stop_bytes or a byte
    not in run_bytes.

    :rtype (int, string): idx of last byte and all of bytes including
    the terminal byte from stop_bytes or not in run_bytes


Make a list of Labels for 'author' and the filtered hrefs &
        anchors


Runs a series of parsers in sequence passing the result of each parser to the next.
    The result of the last parser is returned.


Returns the current token if it satisfies the guard function provided.

    Fails otherwise.
    This is the a generalisation of one_of.


Applies the parser to input zero or more times.

    Returns a list of parser results.


Consumes as many of these as it can until it term is encountered.

    Returns a tuple of the list of these results and the term result


Like sep but must consume at least one of parser.


fills the internal buffer from the source iterator


Advances to and returns the next token or returns EndOfFile


generate the data objects for every task


get a random key out of the first max_iter rows


Run a game being developed with the kxg game engine.

Usage:
    {exe_name} sandbox [<num_ais>] [-v...]
    {exe_name} client [--host HOST] [--port PORT] [-v...]
    {exe_name} server <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...]
    {exe_name} debug <num_guis> [<num_ais>] [--host HOST] [--port PORT] [-v...]
    {exe_name} --help

Commands:
    sandbox
        Play a single-player game with the specified number of AIs.  None of
        the multiplayer machinery will be used.

    client
        Launch a client that will try to connect to a server on the given host
        and port.  Once it connects and the game starts, the client will allow
        you to play the game against any other connected clients.

    server
        Launch a server that will manage a game between the given number of
        human and AI players.  The human players must connect using this
        command's client mode.

    debug
        Debug a multiplayer game locally.  This command launches a server and
        the given number of clients all in different processes, and configures
        the logging system such that the output from each process can be easily
        distinguished.

Arguments:
    <num_guis>
        The number of human players that will be playing the game.  Only needed
        by commands that will launch some sort of multiplayer server.

    <num_ais>
        The number of AI players that will be playing the game.  Only needed by
        commands that will launch single-player games or multiplayer servers.

Options:
    -x --host HOST          [default: {default_host}]
        The address of the machine running the server.  Must be accessible from
        the machines running the clients.

    -p --port PORT          [default: {default_port}]
        The port that the server should listen on.  Don't specify a value less
        than 1024 unless the server is running with root permissions.

    -v --verbose
        Have the game engine log more information about what it's doing.  You
        can specify this option several times to get more and more information.

This command is provided so that you can start writing your game with the least
possible amount of boilerplate code.  However, the clients and servers provided
by this command are not capable of running a production game.  Once you have
written your game and want to give it a polished set of menus and options,
you'll have to write new Stage subclasses encapsulating that logic and you'll
have to call those stages yourself by interacting more directly with the
Theater class.  The online documentation has more information on this process.


Return database field type.


return True if okay, raise Exception if not


This function is mostly about managing configuration, and then
    finally returns a boto.Bucket object.

    AWS credentials come first from config keys
    aws_access_key_id_path, aws_secret_access_key_path (paths to one
    line files); secondly from environment variables
    AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY; also from $HOME/.aws/credentials
    or the magic Amazon http://169.254.169.254/ service.  If credentials
    are not set in the config then behavior is the same as other AWS-based
    command-line tools.


Given the raw data from s3, return a generator for the items
        contained in that data. A generator is necessary to support
        chunk files, but non-chunk files can be provided by a generator
        that yields exactly one item.

        Decoding works by case analysis on the config option
        ``input_format``. If an invalid ``input_format`` is given, then
        a ``ConfigurationError`` is raised.


return Chunk object full of records
        bucket_name may be None


Convert a text stream ID to a kvlayer key.

    The return tuple can be used directly as a key in the
    :data:`STREAM_ITEMS_TABLE` table.

    :param str stream_id: stream ID to convert
    :return: :mod:`kvlayer` key tuple
    :raise exceptions.KeyError: if `stream_id` is malformed


Convert a kvlayer key to a text stream ID.

    `k` should be of the same form produced by
    :func:`stream_id_to_kvlayer_key`.

    :param k: :mod:`kvlayer` key tuple
    :return: converted stream ID
    :returntype str:


Get a kvlayer key from a stream item.

    The return tuple can be used directly as a key in the
    :data:`STREAM_ITEMS_TABLE` table.  Note that this recalculates the
    stream ID, and if the internal data on the stream item is inconsistent
    then this could return a different result from
    :func:`stream_id_to_kvlayer_key`.

    :param si: stream item to get key for
    :return: :mod:`kvlayer` key tuple


Create a session on the frontier silicon device.


Execute a frontier silicon API call.


Helper method for setting a value by using the fsapi API.


Helper method for fetching a text value.


Helper method for fetching a long value. Result is integer.


Check if the device is muted.


Mute or unmute the device.


Get the play status of the device.


Set device sleep timer.


Serve up some ponies.


Mutably tag tokens with xpath offsets.

    Given some stream item, this will tag all tokens from all taggings
    in the document that contain character offsets. Note that some
    tokens may not have computable xpath offsets, so an xpath offset
    for those tokens will not be set. (See the documentation and
    comments for ``char_offsets_to_xpaths`` for what it means for a
    token to have a computable xpath.)

    If a token can have its xpath offset computed, it is added to its
    set of offsets with a ``OffsetType.XPATH_CHARS`` key.


Convert stream item sentences to character ``Offset``s.


Convert character ``Offset``s to character ranges.


Converts HTML and a sequence of char offsets to xpath offsets.

    Returns a generator of :class:`streamcorpus.XpathRange` objects
    in correspondences with the sequence of ``char_offsets`` given.
    Namely, each ``XpathRange`` should address precisely the same text
    as that ``char_offsets`` (sans the HTML).

    Depending on how ``char_offsets`` was tokenized, it's possible that
    some tokens cannot have their xpaths generated reliably. In this
    case, a ``None`` value is yielded instead of a ``XpathRange``.

    ``char_offsets`` must be a sorted and non-overlapping sequence of
    character ranges. They do not have to be contiguous.


Record that `tag` has been seen at this depth.

        If `tag` is :class:`TextElement`, it records a text node.


Returns the one-based index of the current text node.


Yields all the elements from the source
    source - if an element, yields all child elements in order; if any other iterator yields the elements from that iterator


Yields all the elements with the given name
    source - if an element, starts with all child elements in order; can also be any other iterator
    name - will yield only elements with this name


Yields elements from the source whose name matches the given regular expression pattern
    source - if an element, starts with all child elements in order; can also be any other iterator
    pat - re.pattern object


Yields elements from the source having the given attrivute, optionally with the given attribute value
    source - if an element, starts with all child elements in order; can also be any other iterator
    name - attribute name to check
    val - if None check only for the existence of the attribute, otherwise compare the given value as well


Yields elements and text which have the same parent as elem, but come afterward in document order


Call inkscape CLI with arguments and returns its return value.

    Parameters
    ----------
    args_string: list of str

    inkscape_binpath: str

    Returns
    -------
    return_value
        Inkscape command CLI call return value.


Parse genotype from VCF line data


toIndex - An optional method which will return the value prepped for index.

			By default, "toStorage" will be called. If you provide "hashIndex=True" on the constructor,
			the field will be md5summed for indexing purposes. This is useful for large strings, etc.


copy - Create a copy of this IRField.

			  Each subclass should implement this, as you'll need to pass in the args to constructor.

			@return <IRField (or subclass)> - Another IRField that has all the same values as this one.


Return a Jinja2 environment for where file_path is.

    Parameters
    ----------
    file_path: str

    Returns
    -------
    jinja_env: Jinja2.Environment


Setup self.template

        Parameters
        ----------
        template_file_path: str
            Document template file path.


Fill the content of the document with the information in doc_contents.

        Parameters
        ----------
        doc_contents: dict
            Set of values to set the template document.

        Returns
        -------
        filled_doc: str
            The content of the document with the template information filled.


Save the content of the .txt file in a text file.

        Parameters
        ----------
        file_path: str
            Path to the output file.


Factory function to create a specific document of the
        class given by the `command` or the extension of `template_file_path`.

        See get_doctype_by_command and get_doctype_by_extension.

        Parameters
        ----------
        template_file_path: str

        command: str

        Returns
        -------
        doc


Save the content of the .text file in the PDF.

        Parameters
        ----------
        file_path: str
            Path to the output file.


Convert XML 1.0 to MicroXML

    source - XML 1.0 input
    handler - MicroXML events handler

    Returns uxml, extras

    uxml - MicroXML element extracted from the source
    extras - information to be preserved but not part of MicroXML, e.g. namespaces


objHasUnsavedChanges - Check if any object has unsaved changes, cascading.


Check that a value has a certain JSON type.

    Raise TypeError if the type does not match.

    Supported types: str, int, float, bool, list, dict, and None.
    float will match any number, int will only match numbers without
    fractional part.

    The special type JList(x) will match a list value where each
    item is of type x:

    >>> assert_json_type([1, 2, 3], JList(int))


Parse a fragment if markup in HTML mode, and return a bindery node

    Warning: if you pass a string, you must make sure it's a byte string, not a Unicode object.  You might also want to wrap it with amara.lib.inputsource.text if it's not obviously XML or HTML (for example it could be confused with a file name)

    from amara.lib import inputsource
    from amara.bindery import html
    doc = html.markup_fragment(inputsource.text('XXX
Spam!
Eggs!YYY'))

    See also: http://wiki.xml3k.org/Amara2/Tagsoup


Insert data as text in the current node, positioned before the
        start of node insertBefore or to the end of the node's text.


A script that melody calls with each valid set of options. This
    script runs the required code and returns the results.