Convert list of dictionaries to dictionary of lists


Subdivide list into N lists


turns keyword pairs into path or filename

    if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy


Decorator that logs function calls in their self.log


Decorator that adds a runtime profile object to the output


Decorator that prints memory and runtime information at each call of the function


Declare abstract function.

    Requires function to be empty except for docstring describing semantics.
    To apply function, first argument must come with implementation of semantics.


Decorator that prints running time information at each call of the function


A descendant is a child many steps down.


Verify if the file is already downloaded and complete. If they don't
        exists or if are not complete, use homura download function to fetch
        files. Return a list with the path of the downloaded file and the size
        of the remote file.


Validate bands parameter.


Check scene name and whether remote file exists. Raises
        WrongSceneNameError if the scene name is wrong.


Download remote .tar.bz file.


Check whether sceneInfo is valid to download from AWS Storage.


Download each specified band and metadata.


Open an archive on a filesystem.

    This function tries to mimick the behaviour of `fs.open_fs` as closely
    as possible: it accepts either a FS URL or a filesystem instance, and
    will close all resources it had to open.

    Arguments:
        fs_url (FS or text_type): a FS URL, or a filesystem
            instance, where the archive file is located.
        archive (text_type): the path to the archive file on the
            given filesystem.

    Raises:
        `fs.opener._errors.Unsupported`: when the archive type is not supported
            (either the file extension is unknown or the opener requires unmet
            dependencies).

    Example:
        >>> from fs.archive import open_archive
        >>> with open_archive('mem://', 'test.tar.gz') as archive_fs:
        ...     type(archive_fs)
        <class 'fs.archive.tarfs.TarFS'>

    Hint:
        This function finds the entry points defined in group
        ``fs.archive.open_archive``, using the names of the entry point
        as the registered extension.


Slugify a name in the ISO-9660 way.

    Example:
        >>> slugify('épatant')
        "_patant"


Increment an ISO name to avoid name collision.

    Example:
        >>> iso_name_increment('foo.txt')
        'foo1.txt'
        >>> iso_name_increment('bar10')
        'bar11'
        >>> iso_name_increment('bar99', max_length=5)
        'ba100'


Slugify a path, maintaining a map with the previously slugified paths.

    The path table is used to prevent slugified names from collisioning,
    using the `iso_name_increment` function to deduplicate slugs.

    Example:
        >>> path_table = {'/': '/'}
        >>> iso_path_slugify('/ébc.txt', path_table)
        '/_BC.TXT'
        >>> iso_path_slugify('/àbc.txt', path_table)
        '/_BC2.TXT'


Get sqlite_master table information as a list of dictionaries.

        :return: sqlite_master table information.
        :rtype: list

        :Sample Code:
            .. code:: python

                from sqliteschema import SQLiteSchemaExtractor

                print(json.dumps(SQLiteSchemaExtractor("sample.sqlite").fetch_sqlite_master(), indent=4))

        :Output:
            .. code-block:: json

                [
                    {
                        "tbl_name": "sample_table",
                        "sql": "CREATE TABLE 'sample_table' ('a' INTEGER, 'b' REAL, 'c' TEXT, 'd' REAL, 'e' TEXT)",
                        "type": "table",
                        "name": "sample_table",
                        "rootpage": 2
                    },
                    {
                        "tbl_name": "sample_table",
                        "sql": "CREATE INDEX sample_table_a_index ON sample_table('a')",
                        "type": "index",
                        "name": "sample_table_a_index",
                        "rootpage": 3
                    }
                ]


Construct a contour generator from a curvilinear grid.

        Note
        ----
        This is an alias for the default constructor.

        Parameters
        ----------
        x : array_like
            x coordinates of each point in `z`.  Must be the same size as `z`.
        y : array_like
            y coordinates of each point in `z`.  Must be the same size as `z`.
        z : array_like
            The 2-dimensional curvilinear grid of data to compute
            contours for.  Masked arrays are supported.
        formatter : callable
            A conversion function to convert from the internal `Matplotlib`_
            contour format to an external format.  See :ref:`formatters` for
            more information.

        Returns
        -------
        : :class:`QuadContourGenerator`
            Initialized contour generator.


Construct a contour generator from a rectilinear grid.

        Parameters
        ----------
        x : array_like
            x coordinates of each column of `z`.  Must be the same length as
            the number of columns in `z`.  (len(x) == z.shape[1])
        y : array_like
            y coordinates of each row of `z`.  Must be the same length as the
            number of columns in `z`.  (len(y) == z.shape[0])
        z : array_like
            The 2-dimensional rectilinear grid of data to compute contours for.
            Masked arrays are supported.
        formatter : callable
            A conversion function to convert from the internal `Matplotlib`_
            contour format to an external format.  See :ref:`formatters` for
            more information.

        Returns
        -------
        : :class:`QuadContourGenerator`
            Initialized contour generator.


Construct a contour generator from a uniform grid.

        NOTE
        ----
        The default `origin` and `step` values is equivalent to calling
        :meth:`matplotlib.axes.Axes.contour` with only the `z` argument.

        Parameters
        ----------
        z : array_like
            The 2-dimensional uniform grid of data to compute contours for.
            Masked arrays are supported.
        origin : (number.Number, number.Number)
            The (x, y) coordinate of data point `z[0,0]`.
        step :  (number.Number, number.Number)
            The (x, y) distance between data points in `z`.
        formatter : callable
            A conversion function to convert from the internal `Matplotlib`_
            contour format to an external format.  See :ref:`formatters` for
            more information.

        Returns
        -------
        : :class:`QuadContourGenerator`
            Initialized contour generator.


Appy selector to obj and return matching nodes.

    If only one node is found, return it, otherwise return a list of matches.
    Returns False on syntax error. None if no results found.


Accept a list of tokens. Returns matched nodes of self.obj.


Production for a full selector.


Find nodes in rhs having common parents in lhs.


Apply each validator in validators to each node in obj.

        Return each node in obj which matches all validators.


Get a unique token for usage in differentiating test runs that need to
        run in parallel.


Returns the url of the poll. If the poll has not been submitted yet,
        an empty string is returned instead.


Retrieves a poll from strawpoll.

        :param arg: Either the ID of the poll or its strawpoll url.
        :param request_policy: Overrides :attr:`API.requests_policy` for that \
        request.
        :type request_policy: Optional[:class:`RequestsPolicy`]

        :raises HTTPException: Requesting the poll failed.

        :returns: A poll constructed with the requested data.
        :rtype: :class:`Poll`


Submits a poll on strawpoll.

        :param poll: The poll to submit.
        :type poll: :class:`Poll`
        :param request_policy: Overrides :attr:`API.requests_policy` for that \
        request.
        :type request_policy: Optional[:class:`RequestsPolicy`]

        :raises ExistingPoll: This poll instance has already been submitted.
        :raises HTTPException: The submission failed.

        :returns: The given poll updated with the data sent back from the submission.
        :rtype: :class:`Poll`

        .. note::
            Only polls that have a non empty title and between 2 and 30 options
            can be submitted.


`NumPy`_ style contour formatter.

    Contours are returned as a list of Nx2 arrays containing the x and y
    vertices of the contour line.

    For filled contours the direction of vertices matters:

    * CCW (ACW): The vertices give the exterior of a contour polygon.
    * CW: The vertices give a hole of a contour polygon.  This hole will
        always be inside the exterior of the last contour exterior.

    .. note:: This is the fastest format.

    .. _NumPy: http://www.numpy.org


`MATLAB`_ style contour formatter.

    Contours are returned as a single Nx2, `MATLAB`_ style, contour array.
    There are two types of rows in this format:

    * Header: The first element of a header row is the level of the contour
      (the lower level for filled contours) and the second element is the
      number of vertices (to follow) belonging to this contour line.
    * Vertex: x,y coordinate pairs of the vertex.

    A header row is always followed by the coresponding number of vertices.
    Another header row may follow if there are more contour lines.

    For filled contours the direction of vertices matters:

    * CCW (ACW): The vertices give the exterior of a contour polygon.
    * CW: The vertices give a hole of a contour polygon.  This hole will
        always be inside the exterior of the last contour exterior.

    For further explanation of this format see the `Mathworks documentation
    <https://www.mathworks.com/help/matlab/ref/contour-properties.html#prop_ContourMatrix>`_
    noting that the MATLAB format used in the `contours` package is the
    transpose of that used by `MATLAB`_ (since `MATLAB`_ is column-major
    and `NumPy`_ is row-major by default).

    .. _NumPy: http://www.numpy.org

    .. _MATLAB: https://www.mathworks.com/products/matlab.html


`Shapely`_ style contour formatter.

    Contours are returned as a list of :class:`shapely.geometry.LineString`,
    :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
    geometry elements.

    Filled contours return a list of :class:`shapely.geometry.Polygon`
    elements instead.

    .. note:: If possible, `Shapely speedups`_ will be enabled.

    .. _Shapely: http://toblerity.org/shapely/manual.html

    .. _Shapely speedups: http://toblerity.org/shapely/manual.html#performance

    See Also
    --------
    `descartes <https://bitbucket.org/sgillies/descartes/>`_ : Use `Shapely`_
    or GeoJSON-like geometric objects as matplotlib paths and patches.


Get contour lines at the given level.

        Parameters
        ----------
        level : numbers.Number
            The data level to calculate the contour lines for.

        Returns
        -------
        :
            The result of the :attr:`formatter` called on the contour at the
            given `level`.


Get contour polygons between the given levels.

        Parameters
        ----------
        min : numbers.Number or None
            The minimum data level of the contour polygon.  If :obj:`None`,
            ``numpy.finfo(numpy.float64).min`` will be used.
        max : numbers.Number or None
            The maximum data level of the contour polygon.  If :obj:`None`,
            ``numpy.finfo(numpy.float64).max`` will be used.

        Returns
        -------
        :
            The result of the :attr:`formatter` called on the filled contour
            between `min` and `max`.


Add a Node object to nodes dictionary, calculating its coordinates using offset

        Parameters
        ----------
        node   : a Node object
        offset : float
                 number between 0 and 1 that sets the distance
                 from the start point at which the node will be placed


Determine if the given test supports transaction management for
        database rollback test isolation and also whether or not the test has
        opted out of that support.

        Transactions make database rollback much quicker when supported, with
        the caveat that any tests that are explicitly testing transactions
        won't work properly and any tests that depend on external access to the
        test database won't be able to view data created/altered during the
        test.


Clean up any created database and schema.


Makes a `matplotlib.pyplot.Figure` without tooltips or keybindings

    Parameters
    ----------
    figsize : tuple
        Figsize as passed to `matplotlib.pyplot.figure`
    remove_tooltips, remove_keybindings : bool
        Set to True to remove the tooltips bar or any key bindings,
        respectively. Default is False

    Returns
    -------
    fig : `matplotlib.pyplot.Figure`


updates self.field


removes the closest particle in self.pos to ``p``


See `diffusion_correlated` for information related to units, etc


Makes a guess at particle positions using heuristic centroid methods.

    Parameters
    ----------
    st : :class:`peri.states.State`
        The state to check adding particles to.
    rad : Float
        The feature size for featuring.
    invert : {'guess', True, False}, optional
        Whether to invert the image; set to True for there are dark
        particles on a bright background, False for bright particles.
        The default is to guess from the state's current particles.
    minmass : Float or None, optional
        The minimum mass/masscut of a particle. Default is ``None`` =
        calculated internally.
    use_tp : Bool, optional
        Whether or not to use trackpy. Default is ``False``, since trackpy
        cuts out particles at the edge.
    trim_edge : Bool, optional
        Whether to trim particles at the edge pixels of the image. Can be
        useful for initial featuring but is bad for adding missing particles
        as they are frequently at the edge. Default is ``False``.

    Returns
    -------
    guess : [N,3] numpy.ndarray
        The featured positions of the particles, sorted in order of decreasing
        feature mass.
    npart : Int
        The number of added particles.


Workhorse of feature_guess


Checks whether to add particles at a given position by seeing if adding
    the particle improves the fit of the state.

    Parameters
    ----------
    st : :class:`peri.states.State`
        The state to check adding particles to.
    guess : [N,3] list-like
        The positions of particles to check to add.
    rad : {Float, ``'calc'``}, optional.
        The radius of the newly-added particles. Default is ``'calc'``,
        which uses the states current radii's median.
    do_opt : Bool, optional
        Whether to optimize the particle position before checking if it
        should be kept. Default is True (optimizes position).
    im_change_frac : Float
        How good the change in error needs to be relative to the change in
        the difference image. Default is 0.2; i.e. if the error does not
        decrease by 20% of the change in the difference image, do not add
        the particle.
    min_derr : Float or '3sig'
        The minimal improvement in error to add a particle. Default
        is ``'3sig' = 3*st.sigma``.

    Returns
    -------
    accepts : Int
        The number of added particles
    new_poses : [N,3] list
        List of the positions of the added particles. If ``do_opt==True``,
        then these positions will differ from the input 'guess'.


Checks whether or not adding a particle should be present.

    Parameters
    ----------
    absent_err : Float
        The state error without the particle.
    present_err : Float
        The state error with the particle.
    absent_d : numpy.ndarray
        The state residuals without the particle.
    present_d : numpy.ndarray
        The state residuals with the particle.
    im_change_frac : Float, optional
        How good the change in error needs to be relative to the change in
        the residuals. Default is 0.2; i.e. return False if the error does
        not decrease by 0.2 x the change in the residuals.
    min_derr : Float, optional
        The minimal improvement in error. Default is 0.1

    Returns
    -------
    Bool
        True if the errors is better with the particle present.


Attempts to add missing particles to the state.

    Operates by:
    (1) featuring the difference image using feature_guess,
    (2) attempting to add the featured positions using check_add_particles.

    Parameters
    ----------
    st : :class:`peri.states.State`
        The state to check adding particles to.
    rad : Float or 'calc', optional
        The radius of the newly-added particles and of the feature size for
        featuring. Default is 'calc', which uses the median of the state's
        current radii.
    tries : Int, optional
        How many particles to attempt to add. Only tries to add the first
        ``tries`` particles, in order of mass. Default is 50.

    Other Parameters
    ----------------
    invert : Bool, optional
        Whether to invert the image. Default is ``True``, i.e. dark particles
    minmass : Float or None, optionals
        The minimum mass/masscut of a particle. Default is ``None``=calcualted
        by ``feature_guess``.
    use_tp : Bool, optional
        Whether to use trackpy in feature_guess. Default is False, since
        trackpy cuts out particles at the edge.

    do_opt : Bool, optional
        Whether to optimize the particle position before checking if it
        should be kept. Default is True (optimizes position).
    im_change_frac : Float, optional
        How good the change in error needs to be relative to the change
        in the difference image. Default is 0.2; i.e. if the error does
        not decrease by 20% of the change in the difference image, do
        not add the particle.

    min_derr : Float or '3sig', optional
        The minimal improvement in error to add a particle. Default
        is ``'3sig' = 3*st.sigma``.

    Returns
    -------
    accepts : Int
        The number of added particles
    new_poses : [N,3] list
        List of the positions of the added particles. If ``do_opt==True``,
        then these positions will differ from the input 'guess'.


Automatically adds and subtracts missing & extra particles in a region
    of poor fit.

    Parameters
    ----------
    st: :class:`peri.states.State`
        The state to add and subtract particles to.
    tile : :class:`peri.util.Tile`
        The poorly-fit region to examine.
    rad : Float or 'calc', optional
        The initial radius for added particles; added particles radii are
        not fit until the end of add_subtract. Default is ``'calc'``, which
        uses the median radii of active particles.
    max_iter : Int, optional
        The maximum number of loops for attempted adds at one tile location.
        Default is 3.
    invert : {'guess', True, False}, optional
        Whether to invert the image for feature_guess -- True for dark
        particles on a bright background, False for bright particles. The
        default is to guess from the state's current particles.
    max_allowed_remove : Int, optional
        The maximum number of particles to remove. If the misfeatured tile
        contains more than this many particles, raises an error. If it
        contains more than half as many particles, logs a warning. If more
        than this many particles are added, they are optimized in blocks of
        ``max_allowed_remove``. Default is 20.

    Other Parameters
    ----------------
    im_change_frac : Float on [0, 1], optional.
        If adding or removing a particle decreases the error less than
        ``im_change_frac``*the change in the image, the particle is deleted.
        Default is 0.2.

    min_derr : {Float, ``'3sig'``}, optional
        The minimum change in the state's error to keep a particle in the
        image. Default is ``'3sig'`` which uses ``3*st.sigma``.

    do_opt : Bool, optional
        Set to False to avoid optimizing particle positions after adding
        them. Default is True.

    minmass : Float, optional
        The minimum mass for a particle to be identified as a feature, as
        used by trackpy. Defaults to a decent guess.

    use_tp : Bool, optional
        Set to True to use trackpy to find missing particles inside the
        image. Not recommended since trackpy deliberately cuts out particles
        at the edge of the image. Default is False.

    Outputs
    -------
    n_added : Int
        The change in the number of particles, i.e. ``n_added-n_subtracted``
    ainds: List of ints
        The indices of the added particles.

    Notes
    --------
    The added/removed positions returned are whether or not the
    position has been added or removed ever. It's possible/probably that
    a position is added, then removed during a later iteration.

    Algorithm is:
    1.  Remove all particles within the tile.
    2.  Feature and add particles to the tile.
    3.  Optimize the added particles positions only.
    4.  Run 2-3 until no particles have been added.
    5.  Optimize added particle radii
    Because all the particles are removed within a tile, it is important
    to set max_allowed_remove to a reasonable value. Otherwise, if the
    tile is the size of the image it can take a long time to remove all
    the particles and re-add them.


Automatically adds and subtracts missing particles based on local
    regions of poor fit.

    Calls identify_misfeatured_regions to identify regions, then
    add_subtract_misfeatured_tile on the tiles in order of size until
    region_depth tiles have been checked without adding any particles.

    Parameters
    ----------
    st: :class:`peri.states.State`
        The state to add and subtract particles to.
    region_depth : Int
        The minimum amount of regions to try; the algorithm terminates if
        region_depth regions have been tried without adding particles.

    Other Parameters
    ----------------
    filter_size : Int, optional
        The size of the filter for calculating the local standard deviation;
        should approximately be the size of a poorly featured region in each
        dimension. Best if odd. Default is 5.
    sigma_cutoff : Float, optional
        The max allowed deviation of the residuals from what is expected,
        in units of the residuals' standard deviation. Lower means more
        sensitive, higher = less sensitive. Default is 8.0, i.e. one pixel
        out of every ``7*10^11`` is mis-identified randomly. In practice the
        noise is not Gaussian so there are still some regions mis-
        identified as improperly featured.
    rad : Float or 'calc', optional
        The initial radius for added particles; added particles radii are
        not fit until the end of add_subtract. Default is ``'calc'``, which
        uses the median radii of active particles.
    max_iter : Int, optional
        The maximum number of loops for attempted adds at one tile location.
        Default is 3.
    invert : Bool, optional
        Whether to invert the image for feature_guess. Default is ``True``,
        i.e. dark particles on bright background.
    max_allowed_remove : Int, optional
        The maximum number of particles to remove. If the misfeatured tile
        contains more than this many particles, raises an error. If it
        contains more than half as many particles, throws a warning. If more
        than this many particles are added, they are optimized in blocks of
        ``max_allowed_remove``. Default is 20.
    im_change_frac : Float, between 0 and 1.
        If adding or removing a particle decreases the error less than
        ``im_change_frac *`` the change in the image, the particle is deleted.
        Default is 0.2.
    min_derr : Float
        The minimum change in the state's error to keep a particle in the
        image. Default is ``'3sig'`` which uses ``3*st.sigma``.
    do_opt : Bool, optional
        Set to False to avoid optimizing particle positions after adding
        them. Default is True
    minmass : Float, optional
        The minimum mass for a particle to be identified as a feature, as
        used by trackpy. Defaults to a decent guess.
    use_tp : Bool, optional
        Set to True to use trackpy to find missing particles inside the
        image. Not recommended since trackpy deliberately cuts out
        particles at the edge of the image. Default is False.
    max_allowed_remove : Int, optional
        The maximum number of particles to remove. If the misfeatured tile
        contains more than this many particles, raises an error. If it
        contains more than half as many particles, throws a warning. If more
        than this many particles are added, they are optimized in blocks of
        ``max_allowed_remove``. Default is 20.

    Returns
    -------
    n_added : Int
        The change in the number of particles; i.e the number added - number
        removed.
    new_poses : List
        [N,3] element list of the added particle positions.

    Notes
    -----
    Algorithm Description

    1. Identify mis-featured regions by how much the local residuals
       deviate from the global residuals, as measured by the standard
       deviation of both.
    2. Loop over each of those regions, and:

       a. Remove every particle in the current region.
       b. Try to add particles in the current region until no more
          can be added while adequately decreasing the error.
       c. Terminate if at least region_depth regions have been
          checked without successfully adding a particle.

    Because this algorithm is more judicious about chooosing regions to
    check, and more aggressive about removing particles in those regions,
    it runs faster and does a better job than the (global) add_subtract.
    However, this function usually does not work better as an initial add-
    subtract on an image, since (1) it doesn't check for removing small/big
    particles per se, and (2) when the poorly-featured regions of the image
    are large or when the fit is bad, it will remove essentially all of the
    particles, taking a long time. As a result, it's usually best to do a
    normal add_subtract first and using this function for tough missing or
    double-featured particles.


Guesses whether particles are bright on a dark bkg or vice-versa

    Works by checking whether the intensity at the particle centers is
    brighter or darker than the average intensity of the image, by
    comparing the median intensities of each.

    Parameters
    ----------
    st : :class:`peri.states.ImageState`

    Returns
    -------
    invert : bool
        Whether to invert the image for featuring.


Save the acquired 'wisdom' generated by FFTW to file so that future
    initializations of FFTW will be faster.


Take a platonic image and position and create a state which we can
    use to sample the error for peri. Also return the blurred platonic
    image so we can vary the noise on it later


Create a perfect platonic sphere of a given radius R by supersampling by a
    factor scale on a grid of size N.  Scale must be odd.

    We are able to perfectly position these particles up to 1/scale. Therefore,
    let's only allow those types of shifts for now, but return the actual position
    used for the placement.


Translate an image in fourier-space with plane waves


Load default users and groups.


weighting function for Barnes


The first-order Barnes approximation


Correct, normalized version of Barnes


Convert cheb coordinates to windowdow coordinates


Determine admin type.


Validate privacy policy value.


Validate state value.


Delete a group and all associated memberships.


Update group.

        :param name: Name of group.
        :param description: Description of group.
        :param privacy_policy: PrivacyPolicy
        :param subscription_policy: SubscriptionPolicy
        :returns: Updated group


Query group by a list of group names.

        :param list names: List of the group names.
        :returns: Query object.


Query group by user.

        :param user: User object.
        :param bool with_pending: Whether to include pending users.
        :param bool eager: Eagerly fetch group members.
        :returns: Query object.


Modify query as so include only specific group names.

        :param query: Query object.
        :param str q: Search string.
        :returs: Query object.


Invite users to a group by emails.

        :param list emails: Emails of users that shall be invited.
        :returns list: Newly created Memberships or Nones.


Verify if given user is a group member.

        :param user: User to be checked.
        :param bool with_pending: Whether to include pending users or not.
        :returns: True or False.


Determine if given user can see other group members.

        :param user: User to be checked.
        :returns: True or False.


Determine if user can invite people to a group.

        Be aware that this check is independent from the people (users) which
        are going to be invited. The checked user is the one who invites
        someone, NOT who is going to be invited.

        :param user: User to be checked.
        :returns: True or False.


Get membership for given user and group.

        :param group: Group object.
        :param user: User object.
        :returns: Membership or None.


Filter a query result.


Get a user's memberships.


Get all invitations for given user.


Get all pending group requests.


Get a group's members.


Modify query as so to order the results.

        :param query: Query object.
        :param str s: Orderinig: ``asc`` or ``desc``.
        :returs: Query object.


Delete membership.


Get specific GroupAdmin object.


Get all groups for for a specific admin.


Get count of admins per group.


Get all social newtworks profiles


Returns the detailed information on individual interactions with the social
      media update such as favorites, retweets and likes.


Edit an existing, individual status update.


Immediately shares a single pending update and recalculates times for
      updates remaining in the queue.


Permanently delete an existing status update.


Move an existing status update to the top of the queue and recalculate
      times for all updates in the queue. Returns the update with its new
      posting time.


Returns an array of updates that are currently in the buffer for an
      individual social media profile.


Edit the order at which statuses for the specified social media profile will
      be sent out of the buffer.


Create one or more new status updates.


Temporarily do not use any formatter so that text printed is raw


Set the verbosity level of a certain log handler or of all handlers.

        Parameters
        ----------
        verbosity : 'v' to 'vvvvv'
            the level of verbosity, more v's is more verbose

        handlers : string, or list of strings
            handler names can be found in ``peri.logger.types.keys()``
            Current set is::

                ['console-bw', 'console-color', 'rotating-log']


Generates a centered boolean mask of a 3D sphere


Local max featuring to identify bright spherical particles on a
    dark background.

    Parameters
    ----------
        im : numpy.ndarray
            The image to identify particles in.
        radius : Float > 0, optional
            Featuring radius of the particles. Default is 2.5
        noise_size : Float, optional
            Size of Gaussian kernel for smoothing out noise. Default is 1.
        bkg_size : Float or None, optional
            Size of the Gaussian kernel for removing long-wavelength
            background. Default is None, which gives `2 * radius`
        minmass : Float, optional
            Return only particles with a ``mass > minmass``. Default is 1.
        trim_edge : Bool, optional
            Set to True to omit particles identified exactly at the edge
            of the image. False-positive features frequently occur here
            because of the reflected bandpass featuring. Default is
            False, i.e. find particles at the edge of the image.

    Returns
    -------
        pos, mass : numpy.ndarray
            Particle positions and masses


Cumulative distribution function for the traingle distribution


Get the update tile surrounding particle `n`


Translate index info to parameter name


Get the amount of support size required for a particular update.


Update the particles field given new parameter values


Get position and radius of one or more particles


Get position of one or more particles


Get radius of one or more particles


Add a particle or list of particles given by a list of positions and
        radii, both need to be array-like.

        Parameters
        ----------
        pos : array-like [N, 3]
            Positions of all new particles

        rad : array-like [N]
            Corresponding radii of new particles

        Returns
        -------
        inds : N-element numpy.ndarray.
            Indices of the added particles.


Get the tile surrounding particle `n`


A fast j2 defined in terms of other special functions


Returns the wavefront aberration for an aberrated, defocused lens.

    Calculates the portions of the wavefront distortion due to z, theta
    only, for a lens with defocus and spherical aberration induced by
    coverslip mismatch. (The rho portion can be analytically integrated
    to Bessels.)

    Parameters
    ----------
        cos_theta : numpy.ndarray.
            The N values of cos(theta) at which to compute f_theta.
        zint : Float
            The position of the lens relative to the interface.
        z : numpy.ndarray
            The M z-values to compute f_theta at. `z.size` is unrelated
            to `cos_theta.size`
        n2n1: Float, optional
            The ratio of the index of the immersed medium to the optics.
            Default is 0.95
        sph6_ab : Float or None, optional
            Set sph6_ab to a nonzero value to add residual 6th-order
            spherical aberration that is proportional to sph6_ab. Default
            is None (i.e. doesn't calculate).

    Returns
    -------
        wvfront : numpy.ndarray
            The aberrated wavefront, as a function of theta and z.
            Shape is [z.size, cos_theta.size]


Returns a prefactor in the electric field integral.

    This is an internal function called by get_K. The returned prefactor
    in the integrand is independent of which integral is being called;
    it is a combination of the exp(1j*phase) and apodization.

    Parameters
    ----------
        z : numpy.ndarray
            The values of z (distance along optical axis) at which to
            calculate the prefactor. Size is unrelated to the size of
            `cos_theta`
        cos_theta : numpy.ndarray
            The values of cos(theta) (i.e. position on the incoming
            focal spherical wavefront) at which to calculate the
            prefactor. Size is unrelated to the size of `z`
        zint : Float, optional
            The position of the optical interface, in units of 1/k.
            Default is 100.
        n2n1 : Float, optional
            The ratio of the index mismatch between the optics (n1) and
            the sample (n2). Default is 0.95
        get_hdet : Bool, optional
            Set to True to calculate the detection prefactor vs the
            illumination prefactor (i.e. False to include apodization).
            Default is False

    Returns
    -------
        numpy.ndarray
            The prefactor, of size [`z.size`, `cos_theta.size`], sampled
            at the values [`z`, `cos_theta`]


Calculates one of three electric field integrals.

    Internal function for calculating point spread functions. Returns
    one of three electric field integrals that describe the electric
    field near the focus of a lens; these integrals appear in Hell's psf
    calculation.

    Parameters
    ----------
        rho : numpy.ndarray
            Rho in cylindrical coordinates, in units of 1/k.
        z : numpy.ndarray
            Z in cylindrical coordinates, in units of 1/k. `rho` and
            `z` must be the same shape

        alpha : Float, optional
            The acceptance angle of the lens, on (0,pi/2). Default is 1.
        zint : Float, optional
            The distance of the len's unaberrated focal point from the
            optical interface, in units of 1/k. Default is 100.
        n2n1 : Float, optional
            The ratio n2/n1 of the index mismatch between the sample
            (index n2) and the optical train (index n1). Must be on
            [0,inf) but should be near 1. Default is 0.95
        get_hdet : Bool, optional
            Set to True to get the detection portion of the psf; False
            to get the illumination portion of the psf. Default is True
        K : {1, 2, 3}, optional
            Which of the 3 integrals to evaluate. Default is 1
        Kprefactor : numpy.ndarray or None
            This array is calculated internally and optionally returned;
            pass it back to avoid recalculation and increase speed. Default
            is None, i.e. calculate it internally.
        return_Kprefactor : Bool, optional
            Set to True to also return the Kprefactor (parameter above)
            to speed up the calculation for the next values of K. Default
            is False
        npts : Int, optional
            The number of points to use for Gauss-Legendre quadrature of
            the integral. Default is 20, which is a good number for x,y,z
            less than 100 or so.

    Returns
    -------
        kint : numpy.ndarray
            The integral K_i; rho.shape numpy.array
        [, Kprefactor] : numpy.ndarray
            The prefactor that is independent of which integral is being
            calculated but does depend on the parameters; can be passed
            back to the function for speed.

    Notes
    -----
        npts=20 gives double precision (no difference between 20, 30, and
        doing all the integrals with scipy.quad). The integrals are only
        over the acceptance angle of the lens, so for moderate x,y,z they
        don't vary too rapidly. For x,y,z, zint large compared to 100, a
        higher npts might be necessary.


Calculates the symmetric and asymmetric portions of a confocal PSF.

    Parameters
    ----------
        rho : numpy.ndarray
            Rho in cylindrical coordinates, in units of 1/k.
        z : numpy.ndarray
            Z in cylindrical coordinates, in units of 1/k. Must be the
            same shape as `rho`
        get_hdet : Bool, optional
            Set to True to get the detection portion of the psf; False
            to get the illumination portion of the psf. Default is True
        include_K3_det : Bool, optional.
            Flag to not calculate the `K3' component for the detection
            PSF, corresponding to (I think) a low-aperature focusing
            lens and no z-polarization of the focused light. Default
            is True, i.e. calculates the K3 component as if the focusing
            lens is high-aperture

    Other Parameters
    ----------------
        alpha : Float, optional
            The acceptance angle of the lens, on (0,pi/2). Default is 1.
        zint : Float, optional
            The distance of the len's unaberrated focal point from the
            optical interface, in units of 1/k. Default is 100.
        n2n1 : Float, optional
            The ratio n2/n1 of the index mismatch between the sample
            (index n2) and the optical train (index n1). Must be on
            [0,inf) but should be near 1. Default is 0.95

    Returns
    -------
        hsym : numpy.ndarray
            `rho`.shape numpy.array of the symmetric portion of the PSF
        hasym : numpy.ndarray
            `rho`.shape numpy.array of the asymmetric portion of the PSF


Calculates a set of Gauss quadrature points & weights for polydisperse
    light.

    Returns a list of points and weights of the final wavevector's distri-
    bution, in units of the initial wavevector.

    Parameters
    ----------
        kfki : Float
            The mean of the polydisperse outgoing wavevectors.
        sigkf : Float
            The standard dev. of the polydisperse outgoing wavevectors.
        dist_type : {`gaussian`, `gamma`}, optional
            The distribution, gaussian or gamma, of the wavevectors.
            Default is `gaussian`
        nkpts : Int, optional
            The number of quadrature points to use. Default is 3
    Returns
    -------
        kfkipts : numpy.ndarray
            The Gauss quadrature points at which to calculate kfki.
        wts : numpy.ndarray
            The associated Gauss quadrature weights.


Calculates the illumination PSF for a line-scanning confocal with the
    confocal line oriented along the x direction.

    Parameters
    ----------
        y : numpy.ndarray
            The y points (in-plane, perpendicular to the line direction)
            at which to evaluate the illumination PSF, in units of 1/k.
            Arbitrary shape.
        z : numpy.ndarray
            The z points (optical axis) at which to evaluate the illum-
            ination PSF, in units of 1/k. Must be the same shape as `y`
        polar_angle : Float, optional
            The angle of the illuminating light's polarization with
            respect to the line's orientation along x. Default is 0.
        pinhole_width : Float, optional
            The width of the geometric image of the line projected onto
            the sample, in units of 1/k. Default is 1. The perfect line
            image is assumed to be a Gaussian. If `nlpts` is set to 1,
            the line will always be of zero width.
        nlpts : Int, optional
            The number of points to use for Hermite-gauss quadrature over
            the line's width. Default is 1, corresponding to a zero-width
            line.
        use_laggauss : Bool, optional
            Set to True to use a more-accurate sinh'd Laguerre-Gauss
            quadrature for integration over the line's length (more accurate
            in the same amount of time). Default is False for backwards
            compatibility.  FIXME what did we do here?

    Other Parameters
    ----------------
        alpha : Float, optional
            The acceptance angle of the lens, on (0,pi/2). Default is 1.
        zint : Float, optional
            The distance of the len's unaberrated focal point from the
            optical interface, in units of 1/k. Default is 100.
        n2n1 : Float, optional
            The ratio n2/n1 of the index mismatch between the sample
            (index n2) and the optical train (index n1). Must be on
            [0,inf) but should be near 1. Default is 0.95

    Returns
    -------
        hilm : numpy.ndarray
            The line illumination, of the same shape as y and z.


Calculates the point spread function of a line-scanning confocal with
    polydisperse dye emission.

    Make x,y,z  __1D__ numpy.arrays, with x the direction along the
    scan line. (to make the calculation faster since I dont' need the line
    ilm for each x).

    Parameters
    ----------
        x : numpy.ndarray
            _One_dimensional_ array of the x grid points (along the line
            illumination) at which to evaluate the psf. In units of
            1/k_incoming.
        y : numpy.ndarray
            _One_dimensional_ array of the y grid points (in plane,
            perpendicular to the line illumination) at which to evaluate
            the psf. In units of 1/k_incoming.
        z : numpy.ndarray
            _One_dimensional_ array of the z grid points (along the
            optical axis) at which to evaluate the psf. In units of
            1/k_incoming.
        normalize : Bool, optional
            Set to True to include the effects of PSF normalization on
            the image intensity. Default is False.
        kfki : Float, optional
            The mean of the ratio of the final light's wavevector to the
            incoming. Default is 0.889
        sigkf : Float, optional
            The standard deviation of the ratio of the final light's
            wavevector to the incoming. Default is 0.1
        zint : Float, optional
            The position of the optical interface, in units of 1/k_incoming
            Default is 100.
        dist_type : {`gaussian`, `gamma`}, optional
            The distribution of the outgoing light. If 'gaussian' the
            resulting k-values are taken in absolute value. Default
            is `gaussian`
        wrap : Bool, optional
            If True, wraps the psf calculation for speed, assuming that
            the input x, y are regularly-spaced points. If x,y are not
            regularly spaced then `wrap` must be set to False. Default is True.

    Other Parameters
    ----------------
        polar_angle : Float, optional
            The polarization angle of the light (radians) with respect to
            the line direction (x). Default is 0.
        alpha : Float
            The opening angle of the lens. Default is 1.
        n2n1 : Float
            The ratio of the index in the 2nd medium to that in the first.
            Default is 0.95

    Returns
    -------
        numpy.ndarray
            A 3D- numpy.array of the point-spread function. Indexing is
            psf[x,y,z]; shape is [x.size, y,size, z.size]
    Notes
    -----
        Neither distribution type is perfect. If sigkf/k0 is big (>0.5ish)
        then part of the Gaussian is negative. To avoid issues an abs() is
        taken, but then the actual mean and variance are not what is
        supplied. Conversely, if sigkf/k0 is small (<0.0815), then the
        requisite associated Laguerre quadrature becomes unstable. To
        prevent this sigkf/k0 is effectively clipped to be > 0.0815.


Wraps a point-spread function in x and y.

    Speeds up psf calculations by a factor of 4 for free / some broadcasting
    by exploiting the x->-x, y->-y symmetry of a psf function. Pass x and y
    as the positive (say) values of the coordinates at which to evaluate func,
    and it will return the function sampled at [x[::-1]] + x. Note it is not
    wrapped in z.

    Parameters
    ----------
        xpts : numpy.ndarray
            1D N-element numpy.array of the x-points to evaluate func at.
        ypts : numpy.ndarray
            y-points to evaluate func at.
        zpts : numpy.ndarray
            z-points to evaluate func at.
        func : function
            The function to evaluate and wrap around. Syntax must be
            func(x,y,z, **kwargs)
        **kwargs : Any parameters passed to the function.

    Outputs
    -------
        to_return : numpy.ndarray
            The wrapped and calculated psf, of shape
            [2*x.size - x0, 2*y.size - y0, z.size], where x0=1 if x[0]=0, etc.

    Notes
    -----
    The coordinates should be something like numpy.arange(start, stop, diff),
    with start near 0. If x[0]==0, all of x is calcualted but only x[1:]
    is wrapped (i.e. it works whether or not x[0]=0).

    This doesn't work directly for a linescan psf because the illumination
    portion is not like a grid. However, the illumination and detection
    are already combined with wrap_and_calc in calculate_linescan_psf etc.


Convert a scalar ``a`` to a list and all iterables to list as well.

    Examples
    --------
    >>> listify(0)
    [0]

    >>> listify([1,2,3])
    [1, 2, 3]

    >>> listify('a')
    ['a']

    >>> listify(np.array([1,2,3]))
    [1, 2, 3]

    >>> listify('string')
    ['string']


If a single element list, extract the element as an object, otherwise
    leave as it is.

    Examples
    --------
    >>> delistify('string')
    'string'

    >>> delistify(['string'])
    'string'

    >>> delistify(['string', 'other'])
    ['string', 'other']

    >>> delistify(np.array([1.0]))
    1.0

    >>> delistify([1, 2, 3])
    [1, 2, 3]


Convert an integer or iterable list to numpy array of length dim. This func
    is used to allow other methods to take both scalars non-numpy arrays with
    flexibility.

    Parameters
    ----------
    a : number, iterable, array-like
        The object to convert to numpy array

    dim : integer
        The length of the resulting array

    dtype : string or np.dtype
        Type which the resulting array should be, e.g. 'float', np.int8

    Returns
    -------
    arr : numpy array
        Resulting numpy array of length ``dim`` and type ``dtype``

    Examples
    --------
    >>> aN(1, dim=2, dtype='float')
    array([ 1.,  1.])

    >>> aN(1, dtype='int')
    array([1, 1, 1])

    >>> aN(np.array([1,2,3]), dtype='float')
    array([ 1.,  2.,  3.])


Apply the documentation from ``superclass`` to ``subclass`` by filling
    in all overridden member function docstrings with those from the
    parent class


Array slicer object for this tile

        >>> Tile((2,3)).slicer
        (slice(0, 2, None), slice(0, 3, None))

        >>> np.arange(10)[Tile((4,)).slicer]
        array([0, 1, 2, 3])


Iterate the vector of all corners of the hyperrectangles

        >>> Tile(3, dim=2).corners
        array([[0, 0],
               [0, 3],
               [3, 0],
               [3, 3]])


Returns the coordinate vectors associated with the tile.

        Parameters
        -----------
        norm : boolean
            can rescale the coordinates for you. False is no rescaling, True is
            rescaling so that all coordinates are from 0 -> 1.  If a scalar,
            the same norm is applied uniformally while if an iterable, each
            scale is applied to each dimension.

        form : string
            In what form to return the vector array. Can be one of:
                'broadcast' -- return 1D arrays that are broadcasted to be 3D

                'flat' -- return array without broadcasting so each component
                    is 1D and the appropriate length as the tile

                'meshed' -- arrays are explicitly broadcasted and so all have
                    a 3D shape, each the size of the tile.

                'vector' -- array is meshed and combined into one array with
                    the vector components along last dimension [Nz, Ny, Nx, 3]

        Examples
        --------
        >>> Tile(3, dim=2).coords(form='meshed')[0]
        array([[ 0.,  0.,  0.],
               [ 1.,  1.,  1.],
               [ 2.,  2.,  2.]])

        >>> Tile(3, dim=2).coords(form='meshed')[1]
        array([[ 0.,  1.,  2.],
               [ 0.,  1.,  2.],
               [ 0.,  1.,  2.]])

        >>> Tile([4,5]).coords(form='vector').shape
        (4, 5, 2)

        >>> [i.shape for i in Tile((4,5), dim=2).coords(form='broadcast')]
        [(4, 1), (1, 5)]


Test whether coordinates are contained within this tile.

        Parameters
        ----------
        items : ndarray [3] or [N, 3]
            N coordinates to check are within the bounds of the tile

        pad : integer or ndarray [3]
            anisotropic padding to apply in the contain test

        Examples
        --------
        >>> Tile(5, dim=2).contains([[-1, 0], [2, 3], [2, 6]])
        array([False,  True, False], dtype=bool)


Intersection of tiles, returned as a tile

        >>> Tile.intersection(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5]))
        Tile [1, 1] -> [4, 4] ([3, 3])


Translate a tile by an amount dr

        >>> Tile(5).translate(1)
        Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])


Returns a filtered image after applying the Fourier-space filters


Sets Fourier-space filters for the image. The image is filtered by
        subtracting values from the image at slices.

        Parameters
        ----------
        slices : List of indices or slice objects.
            The q-values in Fourier space to filter.
        values : np.ndarray
            The complete array of Fourier space peaks to subtract off.  values
            should be the same size as the FFT of the image; only the portions
            of values at slices will be removed.

        Examples
        --------
        To remove a two Fourier peaks in the data at q=(10, 10, 10) &
        (245, 245, 245), where im is the residuals of a model:

            * slices = [(10,10,10), (245, 245, 245)]
            * values = np.fft.fftn(im)
            * im.set_filter(slices, values)


When given a raw image and the scaled version of the same image, it
        extracts the ``exposure`` parameters associated with those images.
        This is useful when

        Parameters
        ----------
        raw : array_like
            The image loaded fresh from a file

        scaled : array_like
            Image scaled using :func:`peri.initializers.normalize`

        Returns
        -------
        exposure : tuple of numbers
            Returns the exposure parameters (emin, emax) which get mapped to
            (0, 1) in the scaled image. Can be passed to
            :func:`~peri.util.RawImage.__init__`


Interal draw method, simply prints to screen


Update the value of the progress and update progress bar.

        Parameters
        -----------
        value : integer
            The current iteration of the progress


Make sure that the required comps are included in the list of
        components supplied by the user. Also check that the parameters are
        consistent across the many components.


Check that the list of components `comp` is compatible with both the
        varmap and modelstr for this Model


Put a figure label in an axis


Compare the data, model, and residuals of a state.

    Makes an image of any 2D slice of a state that compares the data,
    model, and residuals. The upper left portion of the image is the raw
    data, the central portion the model, and the lower right portion the
    image. Either plots the image using plt.imshow() or returns a
    np.ndarray of the image pixels for later use.

    Parameters
    ----------
        st : peri.ImageState object
            The state to plot.
        tile : peri.util.Tile object
            The slice of the image to plot. Can be any xy, xz, or yz
            projection, but it must return a valid 2D slice (the slice is
            squeezed internally).

        data_vmin : {Float, `calc`}, optional
            vmin for the imshow for the data and generative model (shared).
            Default is 'calc' = 0.5(data.min() + model.min())
        data_vmax : {Float, `calc`}, optional
            vmax for the imshow for the data and generative model (shared).
            Default is 'calc' = 0.5(data.max() + model.max())
        res_vmin : Float, optional
            vmin for the imshow for the residuals. Default is -0.1
            Default is 'calc' = 0.5(data.min() + model.min())
        res_vmax : Float, optional
            vmax for the imshow for the residuals. Default is +0.1
        edgepts : {Nested list-like, Float, 'calc'}, optional.
            The vertices of the triangles which determine the splitting of
            the image. The vertices are at (image corner, (edge, y), and
            (x,edge), where edge is the appropriate edge of the image.
                edgepts[0] : (x,y) points for the upper edge
                edgepts[1] : (x,y) points for the lower edge
            where `x` is the coordinate along the image's 0th axis and `y`
            along the images 1st axis. Default is 'calc,' which calculates
            edge points by splitting the image into 3 regions of equal
            area. If edgepts is a float scalar, calculates the edge points
            based on a constant fraction of distance from the edge.
        do_imshow : Bool
            If True, imshow's and returns the returned handle.
            If False, returns the array as a [M,N,4] array.
        data_cmap : matplotlib colormap instance
            The colormap to use for the data and model.
        res_cmap : matplotlib colormap instance
            The colormap to use for the residuals.

    Returns
    -------
        image : {matplotlib.pyplot.AxesImage, numpy.ndarray}
            If `do_imshow` == True, the returned handle from imshow.
            If `do_imshow` == False, an [M,N,4] np.ndarray of the image
            pixels.


Returns 3 masks that trisect an image into 3 triangular portions.

    Parameters
    ----------
        imshape : 2-element list-like of ints
            The shape of the image. Elements after the first 2 are ignored.

        edgepts : Nested list-like, float, or `calc`, optional.
            The vertices of the triangles which determine the splitting of
            the image. The vertices are at (image corner, (edge, y), and
            (x,edge), where edge is the appropriate edge of the image.
                edgepts[0] : (x,y) points for the upper edge
                edgepts[1] : (x,y) points for the lower edge
            where `x` is the coordinate along the image's 0th axis and `y`
            along the images 1st axis. Default is 'calc,' which calculates
            edge points by splitting the image into 3 regions of equal
            area. If edgepts is a float scalar, calculates the edge points
            based on a constant fraction of distance from the edge.

    Returns
    -------
        upper_mask : numpy.ndarray
            Boolean array; True in the image's upper  region.
        center_mask : numpy.ndarray
            Boolean array; True in the image's center region.
        lower_mask : numpy.ndarray
            Boolean array; True in the image's lower  region.


each element of std0 should correspond with the element of std1


Returns a list of the global parameter names.

    Parameters
    ----------
        s : :class:`peri.states.ImageState`
            The state to name the globals of.
        remove_params : Set or None
            A set of unique additional parameters to remove from the globals
            list.

    Returns
    -------
        all_params : list
            The list of the global parameter names, with each of
            remove_params removed.


Returns a non-constant damping vector, allowing certain parameters to be
    more strongly damped than others.

    Parameters
    ----------
        params : List
            The list of parameter names, in order.
        damping : Float
            The default value of the damping.
        increase_list: List
            A nested 2-element list of the params to increase and their
            scale factors. All parameters containing the string
            increase_list[i][0] are increased by a factor increase_list[i][1].
    Returns
    -------
        damp_vec : np.ndarray
            The damping vector to use.


Finds the particles in a tile, as numpy.ndarray of ints.

    Parameters
    ----------
        positions : `numpy.ndarray`
            [N,3] array of the particle positions to check in the tile
        tile : :class:`peri.util.Tile` instance
            Tile of the region inside which to check for particles.

    Returns
    -------
        numpy.ndarray, int
            The indices of the particles in the tile.


Ensures that all particles are included in exactly 1 group


Finds the biggest region size for LM particle optimization with a
    given memory constraint.

    Input Parameters
    ----------------
        s : :class:`peri.states.ImageState`
            The state with the particles
        region_size : Int or 3-element list-like of ints, optional.
            The initial guess for the region size. Default is 40
        max_mem : Numeric, optional
            The maximum memory for the optimizer to take. Default is 1e9

    Other Parameters
    ----------------
        bounds: 2-element list-like of 3-element lists.
            The sub-region of the image over which to look for particles.
                bounds[0]: The lower-left  corner of the image region.
                bounds[1]: The upper-right corner of the image region.
            Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire
            image size, i.e. the default places every particle in the image
            somewhere in the groups.
    Returns
    -------
        region_size : numpy.ndarray of ints of the region size.


Runs Levenberg-Marquardt optimization on a state.

    Convenience wrapper for LMGlobals. Same keyword args, but the defaults
    have been set to useful values for optimizing globals.
    See LMGlobals and LMEngine for documentation.

    See Also
    --------
        do_levmarq_particles : Levenberg-Marquardt optimization of a
            specified set of particles.

        do_levmarq_all_particle_groups : Levenberg-Marquardt optimization
            of all the particles in the state.

        LMGlobals : Optimizer object; the workhorse of do_levmarq.

        LMEngine : Engine superclass for all the optimizers.


Crawls slowly to the minimum-cost state.

    Blocks the global parameters into small enough sections such that each
    can be optimized separately while including all the pixels (i.e. no
    decimation). Optimizes the globals, then the psf separately if desired,
    then particles, then a line minimization along the step direction to
    speed up convergence.

    Parameters
    ----------
        s : :class:`peri.states.ImageState`
            The state to optimize
        desc : string, optional
            Description to append to the states.save() call every loop.
            Set to `None` to avoid saving. Default is `'finish'`.
        n_loop : Int, optional
            The number of times to loop over in the optimizer. Default is 4.
        max_mem : Numeric, optional
            The maximum amount of memory allowed for the optimizers' J's,
            for both particles & globals. Default is 1e9.
        separate_psf : Bool, optional
            If True, does the psf optimization separately from the rest of
            the globals, since the psf has a more tortuous fit landscape.
            Default is True.
        fractol : Float, optional
            Fractional change in error at which to terminate. Default 1e-4
        errtol : Float, optional
            Absolute change in error at which to terminate. Default 1e-2
        dowarn : Bool, optional
            Whether to log a warning if termination results from finishing
            loops rather than from convergence. Default is True.

    Returns
    -------
        dictionary
            Information about the optimization. Has two keys: ``'converged'``,
            a Bool which of whether optimization stopped due to convergence
            (True) or due to max number of iterations (False), and
            ``'loop_values'``, a [n_loop+1, N] ``numpy.ndarray`` of the
            state's values, at the start of optimization and at the end of
            each loop, before the line minimization.


LM run, evaluating 1 step at a time.

        Broyden or eigendirection updates replace full-J updates until
        a full-J update occurs. Does not run with the calculated J (no
        internal run).


Workhorse for do_run_2


Takes more steps without calculating J again.

        Given a fixed damping, J, JTJ, iterates calculating steps, with
        optional Broyden or eigendirection updates. Iterates either until
        a bad step is taken or for self.run_length times.
        Called internally by do_run_2() but is also useful on its own.

        Parameters
        ----------
            initial_count : Int, optional
                The initial count of the run. Default is 0. Increasing from
                0 effectively temporarily decreases run_length.
            subblock : None or np.ndarray of bools, optional
                If not None, a boolean mask which determines which sub-
                block of parameters to run over. Default is None, i.e.
                all the parameters.
            update_derr : Bool, optional
                Set to False to not update the variable that determines
                delta_err, preventing premature termination through errtol.

        Notes
        -----
        It might be good to do something similar to update_derr with the
        parameter values, but this is trickier because of Broyden updates
        and _fresh_J.


Returns a dict of termination statistics

        Parameters
        ----------
            get_cos : Bool, optional
                Whether or not to calcualte the cosine of the residuals
                with the tangent plane of the model using the current J.
                The calculation may take some time. Default is True

        Returns
        -------
            dict
                Has keys
                    delta_vals  : The last change in parameter values.
                    delta_err   : The last change in the error.
                    exp_err     : The expected (last) change in the error.
                    frac_err    : The fractional change in the error.
                    num_iter    : The number of iterations completed.
                    error       : The current error.


Returns a Bool of whether the algorithm has found a satisfactory minimum


Checks if the full J should be updated.

        Right now, just updates after update_J_frequency loops


Updates J, JTJ, and internal counters.


Execute a Broyden update of J


Execute an eigen update of J


Updates self.J, returns nothing


Takes an array param_vals, updates function, returns the new error


Updates the opt_obj, returns new error.


Resets the particle groups and optionally the region size and damping.

        Parameters
        ----------
            new_region_size : : Int or 3-element list-like of ints, optional
                The region size for sub-blocking particles. Default is 40
            do_calc_size : Bool, optional
                If True, calculates the region size internally based on
                the maximum allowed memory. Default is True
            new_damping : Float or None, optional
                The new damping of the optimizer. Set to None to leave
                as the default for LMParticles. Default is None.
            new_max_mem : Numeric, optional
                The maximum allowed memory for J to occupy. Default is 1e9


workhorse for the self.do_run_xx methods.


Calls LMParticles.do_internal_run for each group of particles.


Resets the initial radii used for updating the particles. Call
        if any of the particle radii or positions have been changed
        external to the augmented state.


Resets the aug_state and the LMEngine


Returns an object with a the numbers of shares a link has had using
      Buffer.

      www will be stripped, but other subdomains will not.


Take a sample from a field given flat indices or a shaped slice

    Parameters
    -----------
    inds : list of indices
        One dimensional (raveled) indices to return from the field

    slicer : slice object
        A shaped (3D) slicer that returns a section of image

    flat : boolean
        Whether to flatten the sampled item before returning


Setup the image model formation equation and corresponding objects into
        their various objects. `mdl` is a `peri.models.Model` object


Switch out the data for the model's recreation of the data.


Get the tiles corresponding to a particular section of image needed to
        be updated. Inputs are the parameters and values. Returned is the
        padded tile, inner tile, and slicer to go between, but accounting for
        wrap with the edge of the image as necessary.


Creates an image, as a `peri.util.Image`, which is similar
    to the image in the tutorial


Set the overall shape of the calculation area. The total shape of that
        the calculation can possibly occupy, in pixels. The second, inner, is
        the region of interest within the image.


Notify parent of a parameter change


Set the shape for all components


Ensure that shared parameters are the same value everywhere


Read all environment variables to see if they contain PERI


List all pending memberships, listed only for group admins.


List all user pending memberships.


Create new group.


Manage your group.


List user group members.


Approve a user.


Get an initial featuring of sphere positions in an image.

    Parameters
    -----------
    image : :class:`peri.util.Image` object
        Image object which defines the image file as well as the region.

    feature_rad : float
        Radius of objects to find, in pixels. This is a featuring radius
        and not a real radius, so a better value is frequently smaller
        than the real radius (half the actual radius is good). If ``use_tp``
        is True, then the twice ``feature_rad`` is passed as trackpy's
        ``diameter`` keyword.

    dofilter : boolean, optional
        Whether to remove the background before featuring. Doing so can
        often greatly increase the success of initial featuring and
        decrease later optimization time. Filtering functions by fitting
        the image to a low-order polynomial and featuring the residuals.
        In doing so, this will change the mean intensity of the featured
        image and hence the good value of ``minmass`` will change when
        ``dofilter`` is True. Default is False.

    order : 3-element tuple, optional
        If `dofilter`, the 2+1D Leg Poly approximation to the background
        illumination field. Default is (3,3,3).

    Other Parameters
    ----------------
    invert : boolean, optional
        Whether to invert the image for featuring. Set to True if the
        image is dark particles on a bright background. Default is True
    minmass : Float or None, optional
        The minimum mass/masscut of a particle. Default is None, which
        calculates internally.
    use_tp : Bool, optional
        Whether or not to use trackpy. Default is False, since trackpy
        cuts out particles at the edge.

    Returns
    --------
    positions : np.ndarray [N,3]
        Positions of the particles in order (z,y,x) in image pixel units.

    Notes
    -----
    Optionally filters the image by fitting the image I(x,y,z) to a
    polynomial, then subtracts this fitted intensity variation and uses
    centroid methods to find the particles.


Completely optimizes a state from an image of roughly monodisperse
    particles.

    The user can interactively select the image. The state is periodically
    saved during optimization, with different filename for different stages
    of the optimization.

    Parameters
    ----------
        statemaker : Function
            A statemaker function. Given arguments `im` (a
            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),
            and any additional `statemaker_kwargs`, must return a
            :class:`~peri.states.ImageState`.  There is an example function in
            scripts/statemaker_example.py
        feature_rad : Int, odd
            The particle radius for featuring, as passed to locate_spheres.
        actual_rad : Float, optional
            The actual radius of the particles. Default is feature_rad
        im_name : string, optional
            The file name of the image to load. If not set, it is selected
            interactively through Tk.
        tile : :class:`peri.util.Tile`, optional
            The tile of the raw image to be analyzed. Default is None, the
            entire image.
        invert : Bool, optional
            Whether to invert the image for featuring, as passed to trackpy.
            Default is True.
        desc : String, optional
            A description to be inserted in saved state. The save name will
            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''
        use_full_path : Bool, optional
            Set to True to use the full path name for the image. Default
            is False.
        featuring_params : Dict, optional
            kwargs-like dict of any additional keyword arguments to pass to
            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.
            Default is ``{}``.
        statemaker_kwargs : Dict, optional
            kwargs-like dict of any additional keyword arguments to pass to
            the statemaker function. Default is ``{}``.

    Other Parameters
    ----------------
        max_mem : Numeric
            The maximum additional memory to use for the optimizers, as
            passed to optimize.burn. Default is 1e9.
        min_rad : Float, optional
            The minimum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius smaller than this are identified
            as fake and removed. Default is 0.5 * actual_rad.
        max_rad : Float, optional
            The maximum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius larger than this are identified
            as fake and removed. Default is 1.5 * actual_rad, however you
            may find better results if you make this more stringent.
        rz_order : int, optional
            If nonzero, the order of an additional augmented rscl(z)
            parameter for optimization. Default is 0; i.e. no rscl(z)
            optimization.
        zscale : Float, optional
            The zscale of the image. Default is 1.0

    Returns
    -------
        s : :class:`peri.states.ImageState`
            The optimized state.

    See Also
    --------
        feature_from_pos_rad    : Using a previous state's globals and
            user-provided positions and radii as an initial guess,
            completely optimizes a state.

        get_particle_featuring  : Using a previous state's globals and
            positions as an initial guess, completely optimizes a state.

        translate_featuring     : Use a previous state's globals and
            centroids methods for an initial particle guess, completely
            optimizes a state.

    Notes
    -----
    Proceeds by centroid-featuring the image for an initial guess of
    particle positions, then optimizing the globals + positions until
    termination as called in _optimize_from_centroid.
    The ``Other Parameters`` are passed to _optimize_from_centroid.


Combines centroid featuring with the globals from a previous state.

    Runs trackpy.locate on an image, sets the globals from a previous state,
    calls _translate_particles

    Parameters
    ----------
        feature_rad : Int, odd
            The particle radius for featuring, as passed to locate_spheres.

        state_name : String or None, optional
            The name of the initially-optimized state. Default is None,
            which prompts the user to select the name interactively
            through a Tk window.
        im_name : String or None, optional
            The name of the new image to optimize. Default is None,
            which prompts the user to select the name interactively
            through a Tk window.
        use_full_path : Bool, optional
            Set to True to use the full path of the state instead of
            partial path names (e.g. /full/path/name/state.pkl vs
            state.pkl). Default is False
        actual_rad : Float or None, optional
            The initial guess for the particle radii. Default is the median
            of the previous state.
        invert : Bool
            Whether to invert the image for featuring, as passed to
            addsubtract.add_subtract and locate_spheres. Set to False
            if the image is bright particles on a dark background.
            Default is True (dark particles on bright background).
        featuring_params : Dict, optional
            kwargs-like dict of any additional keyword arguments to pass to
            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.
            Default is ``{}``.

    Other Parameters
    ----------------
        max_mem : Numeric
            The maximum additional memory to use for the optimizers, as
            passed to optimize.burn. Default is 1e9.
        desc : String, optional
            A description to be inserted in saved state. The save name will
            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''
        min_rad : Float, optional
            The minimum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius smaller than this are identified
            as fake and removed. Default is 0.5 * actual_rad.
        max_rad : Float, optional
            The maximum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius larger than this are identified
            as fake and removed. Default is 1.5 * actual_rad, however you
            may find better results if you make this more stringent.
        rz_order : int, optional
            If nonzero, the order of an additional augmented rscl(z)
            parameter for optimization. Default is 0; i.e. no rscl(z)
            optimization.
        do_polish : Bool, optional
            Set to False to only optimize the particles and add-subtract.
            Default is True, which then runs a polish afterwards.

    Returns
    -------
        s : :class:`peri.states.ImageState`
            The optimized state.

    See Also
    --------
        get_initial_featuring   : Features an image from scratch, using
            centroid methods as initial particle locations.

        feature_from_pos_rad    : Using a previous state's globals and
            user-provided positions and radii as an initial guess,
            completely optimizes a state.

        translate_featuring     : Use a previous state's globals and
            centroids methods for an initial particle guess, completely
            optimizes a state.

    Notes
    -----
        The ``Other Parameters`` are passed to _translate_particles.
    Proceeds by:
        1. Find a guess of the particle positions through centroid methods.
        2. Optimize particle positions only.
        3. Optimize particle positions and radii only.
        4. Add-subtract missing and bad particles.
        5. If polish, optimize the illumination, background, and particles.
        6. If polish, optimize everything.


Links the state ``st`` psf zscale with the global zscale


Workhorse for creating & optimizing states with an initial centroid
    guess.

    This is an example function that works for a particular microscope. For
    your own microscope, you'll need to change particulars such as the psf
    type and the orders of the background and illumination.

    Parameters
    ----------
        im : :class:`~peri.util.RawImage`
            A RawImage of the data.
        pos : [N,3] element numpy.ndarray.
            The initial guess for the N particle positions.
        rad : N element numpy.ndarray.
            The initial guess for the N particle radii.

        slab : :class:`peri.comp.objs.Slab` or None, optional
            If not None, a slab corresponding to that in the image. Default
            is None.
        mem_level : {'lo', 'med-lo', 'med', 'med-hi', 'hi'}, optional
            A valid memory level for the state to control the memory overhead
            at the expense of accuracy. Default is `'hi'`

    Returns
    -------
        :class:`~peri.states.ImageState`
            An ImageState with a linked z-scale, a ConfocalImageModel, and
            all the necessary components with orders at which are useful for
            my particular test case.


Used to check if there is a dict in a dict


Create random parameters for this ILM that mimic experiments
        as closely as possible without real assumptions.


Creates a barnes interpolant & calculates its values


Returns details of the posting schedules associated with a social media
      profile.


Calculates the moments of the probability distribution p with vector v


Calculates the 3D psf at a particular z pixel height

        Parameters
        ----------
        zint : float
            z pixel height in image coordinates , converted to 1/k by the
            function using the slab position as well

        size : int, list, tuple
            The size over which to calculate the psf, can be 1 or 3 elements
            for the different axes in image pixel coordinates

        zoffset : float
            Offset in pixel units to use in the calculation of the psf

        cutval : float
            If not None, the psf will be cut along a curve corresponding to
            p(r) == 0 with exponential damping exp(-d^4)

        getextent : boolean
            If True, also return the extent of the psf in pixels for example
            to get the support size. Can only be used with cutval.


fftshift and pad the field with zeros until it has size finalshape.
        if zpad is off, then no padding is put on the z direction. returns
        the fourier transform of the field


Pack the parameters into the form necessary for the integration
        routines above.  For example, packs for calculate_linescan_psf


Calculates a linescan psf


Sends ICMP echo requests to destination `dst` `count` times.
    Returns a deferred which fires when responses are finished.


Make an HTTP request and return the body


Expire any items in the cache older than `age` seconds


Set a key `k` to value `v`


Return True if key `k` exists


Given a record timestamp, verify the chain integrity.

        :param timestamp: UNIX time / POSIX time / Epoch time
        :return: 'True' if the timestamp fits the chain. 'False' otherwise.


Make request and convert JSON response to python objects


Returns all active bets


Return bets with given filters and ordering.

        :param type: return bets only with this type.
                     Use None to include all (default).
        :param order_by: '-last_stake' or 'last_stake' to sort by stake's
                         created date or None for default ordering.
        :param state: one of 'active', 'closed', 'all' (default 'active').
        :param project_id: return bets associated with given project id in kava
        :param page: default 1.
        :param page_site: page size (default 100).


Subscribe to event for given bet ids.


Convert a string of XML which represents a NIST Randomness Beacon value
        into a 'NistBeaconValue' object.

        :param input_xml: XML to build a 'NistBeaconValue' from
        :return: A 'NistBeaconValue' object, 'None' otherwise


Returns a 'minified' version of the javascript content


Passes each parsed log line to `fn`
        This is a better idea than storing a giant log file in memory


Returns a big list of all log lines since the last run


Validate secret link token.

        :param token: Token value.
        :param expected_data: A dictionary of key/values that must be present
            in the data part of the token (i.e. included via ``extra_data`` in
            ``create_token``).


Get cryptographic engine.


32bit counter aggregator with wrapping


Sets up source objects from the given config


Callback that all event sources call when they have a new event
        or list of events


Watchdog timer function.

        Recreates sources which have not generated events in 10*interval if
        they have watchdog set to true in their configuration


Validate that date is in the future.


Validate message.


Verify token and save in session if it's valid.


Return a basic meaningful name based on device type


Do not warn on external images.


Connect receivers to signals.


Receiver for request-accepted signal.


Receiver for request-accepted signal to send email notification.


Receiver for request-created signal to send email notification.


Receiver for request-rejected signal to send email notification.


Render a template and send as email.


Create a new secret link.


Validate a secret link token.

        Only queries the database if token is valid to determine that the token
        has not been revoked.


Revoken a secret link.


Get access request for a specific receiver.


Confirm that senders email is valid.


Given required properties from a NistBeaconValue,
        compute the SHA512Hash object.

        :param version: NistBeaconValue.version
        :param frequency: NistBeaconValue.frequency
        :param timestamp: NistBeaconValue.timestamp
        :param seed_value: NistBeaconValue.seed_value
        :param prev_output: NistBeaconValue.previous_output_value
        :param status_code: NistBeaconValue.status_code

        :return: SHA512 Hash for NistBeaconValue signature verification


Verify a given NIST message hash and signature for a beacon value.

        :param timestamp: The timestamp of the record being verified.
        :param message_hash:
            The hash that was carried out over the message.
            This is an object belonging to the `Crypto.Hash` module.
        :param signature: The signature that needs to be validated.
        :return: True if verification is correct. False otherwise.


Template filter to check if a record is embargoed.


Create an access request.


Confirm email address.


Creates a generic endpoint connection that doesn't finish


Get reverse direction of ordering.


Get column which is being order by.


Get query with correct ordering.


Open the file referenced in this object, and scrape the version.

        :return:
            The version as a string, an empty string if there is no match
            to the magic_line, or any file exception messages encountered.


Set the version for this given file.

        :param new_version: The new version string to set.


Configure SSH client options


Starts the timer for this source


Called for every timer tick. Calls self.get which can be a deferred
        and passes that result back to the queueBack method

        Returns a deferred


List pending access requests and shared links.


Create a TCP connection to Riemann with automatic reconnection


Remove all or self.queueDepth events from the queue


Create a UDP connection to Riemann


Sets up HTTP connector and starts queue timer


Adapts an Event object to a Riemann protobuf event Event


Encode a list of Tensor events with protobuf


Send a Tensor Event to Riemann


Opens local preview of your blog website


Get the relative path to the API resource collection

        If self.collection_endpoint is not set, it will default to the lowercase name of the resource class plus an "s" and the terminating "/"
        :param cls: Resource class
        :return: Relative path to the resource collection


Looks for errors in source code of your blog


Retreive preview results for ID.


value_class is initially a string with the import path to the resource class, but we need to get the actual class before doing any work

        We do not expect the actual clas to be in value_class since the beginning to avoid nasty import egg-before-chicken errors


Saves changes and sends them to GitHub


Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise.


Show Zebra balance.

    Like the hours balance, vacation left, etc.


Show all messages in the `messages` key of the given dict.


Loop through messages and execute tasks


Return True if it's time to log


Abort an initiated SASL authentication process. The expected result
        state is ``failure``.


Template tag that renders the footer information based on the
    authenticated user's permissions.


Builds the parameters needed to present the user with a datatrans payment form.

    :param amount: The amount and currency we want the user to pay
    :param client_ref: A unique reference for this payment
    :return: The parameters needed to display the datatrans form


Builds the parameters needed to present the user with a datatrans form to register a credit card.
    Contrary to a payment form, datatrans will not show an amount.

    :param client_ref: A unique reference for this alias capture.
    :return: The parameters needed to display the datatrans form


Generates the circle.


Given a string key it returns a long value,
        this long value represents a place on the hash ring.

        md5 is currently used because it mixes well.


Get the ``portMappings`` field for the app container.


Construct widget.


Perform post-construction operations.


Handle activation of item in listing.


Handle selection of path segment.


Raises a `requests.exceptions.HTTPError` if the response has a non-200
    status code.


Sometimes we need the protocol object so that we can manipulate the
    underlying transport in tests.


Callback to collect the Server-Sent Events content of a response. Callbacks
    passed will receive event data.

    :param response:
        The response from the SSE request.
    :param handler:
        The handler for the SSE protocol.


Recursively make requests to each endpoint in ``endpoints``.


Get a JSON field from the response JSON.

        :param: response_json:
            The parsed JSON content of the response.
        :param: field_name:
            The name of the field in the JSON to get.


Parse value from string.

        Convert :code:`value` to

        .. code-block:: python

           >>> parser = Config()
           >>> parser.parse('12345', type_=int)
           <<< 12345
           >>>
           >>> parser.parse('1,2,3,4', type_=list, subtype=int)
           <<< [1, 2, 3, 4]

        :param value: string
        :param type\\_: the type to return
        :param subtype: subtype for iterator types
        :return: the parsed config value


Parse a value from an environment variable.

        .. code-block:: python

           >>> os.environ['FOO']
           <<< '12345'
           >>>
           >>> os.environ['BAR']
           <<< '1,2,3,4'
           >>>
           >>> 'BAZ' in os.environ
           <<< False
           >>>
           >>> parser = Config()
           >>> parser.get('FOO', type_=int)
           <<< 12345
           >>>
           >>> parser.get('BAR', type_=list, subtype=int)
           <<< [1, 2, 3, 4]
           >>>
           >>> parser.get('BAZ', default='abc123')
           <<< 'abc123'
           >>>
           >>> parser.get('FOO', type_=int, mapper=lambda x: x*10)
           <<< 123450

        :param key: the key to look up the value under
        :param default: default value to return when when no value is present
        :param type\\_: the type to return
        :param subtype: subtype for iterator types
        :param mapper: a function to post-process the value with
        :return: the parsed config value


Perform a request to a specific endpoint. Raise an error if the status
        code indicates a client or server error.


Check the result of each request that we made. If a failure occurred,
        but some requests succeeded, log and count the failures. If all
        requests failed, raise an error.

        :return:
            The list of responses, with a None value for any requests that
            failed.


Finalize options to be used.


Run clean.


Set up a client key if one does not exist already.

    https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50

    :type pem_path: twisted.python.filepath.FilePath
    :param pem_path:
        The path to the certificate directory to use.
    :rtype: twisted.internet.defer.Deferred


Set up a client key in Vault if one does not exist already.

    :param client:
        The Vault API client to use.
    :param mount_path:
        The Vault key/value mount path to use.
    :rtype: twisted.internet.defer.Deferred


Get a single value for the given key out of the given set of headers.

    :param twisted.web.http_headers.Headers headers:
        The set of headers in which to look for the header value
    :param str key:
        The header key


Perform a request.

        :param: method:
            The HTTP method to use (example is `GET`).
        :param: url:
            The URL to use. The default value is the URL this client was
            created with (`self.url`) (example is `http://localhost:8080`)
        :param: kwargs:
            Any other parameters that will be passed to `treq.request`, for
            example headers. Or any URL parameters to override, for example
            path, query or fragment.


Fetch and return new children.

        Will only fetch children whilst canFetchMore is True.

        .. note::

            It is the caller's responsibility to add each fetched child to this
            parent if desired using :py:meth:`Item.addChild`.


Run the server, i.e. start listening for requests on the given host and
        port.

        :param reactor: The ``IReactorTCP`` to use.
        :param endpoint_description:
            The Twisted description for the endpoint to listen on.
        :return:
            A deferred that returns an object that provides ``IListeningPort``.


Create a marathon-acme instance.

    :param client_creator:
        The txacme client creator function.
    :param cert_store:
        The txacme certificate store instance.
    :param acme_email:
        Email address to use when registering with the ACME service.
    :param allow_multiple_certs:
        Whether to allow multiple certificates per app port.
    :param marathon_addr:
        Address for the Marathon instance to find app domains that require
        certificates.
    :param marathon_timeout:
        Amount of time in seconds to wait for response headers to be received
        from Marathon.
    :param sse_timeout:
        Amount of time in seconds to wait for some event data to be received
        from Marathon.
    :param mlb_addrs:
        List of addresses for marathon-lb instances to reload when a new
        certificate is issued.
    :param group:
        The marathon-lb group (``HAPROXY_GROUP``) to consider when finding
        app domains.
    :param reactor: The reactor to use.


Initialise the storage directory with the certificates directory and a
    default wildcard self-signed certificate for HAProxy.

    :return: the storage path and certs path


Parse the field and value from a line.


Translates bytes into lines, and calls lineReceived.

        Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using
        str.splitlines() to split on ``\r\n``, ``\n``, and ``\r``.


Dispatch the event to the handler.


Fetch the list of apps from Marathon, find the domains that require
        certificates, and issue certificates for any domains that don't already
        have a certificate.


Issue a certificate for the given domain.


When removing an object, other objects with references to the current
    object should remove those references. This function identifies objects
    with forward references to the current object, then removes those
    references.

    :param obj: Object to which forward references should be removed


Ensure that all forward references on the provided object have the
    appropriate backreferences.

    :param StoredObject obj: Database record
    :param list fields: Optional list of field names to check


Initializes the bot, plugins, and everything.


Connects to slack and enters the main loop.

        * start - If True, rtm.start API is used. Else rtm.connect API is used

        For more info, refer to
        https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect


Does cleanup of bot and plugins.


Sends a message to the specified channel

        * channel - The channel to send to.  This can be a SlackChannel object, a channel id, or a channel name
        (without the #)
        * text - String to send
        * thread - reply to the thread. See https://api.slack.com/docs/message-threading#threads_party
        * reply_broadcast - Set to true to indicate your reply is germane to all members of a channel


Sends a message to a user as an IM

        * user - The user to send to.  This can be a SlackUser object, a user id, or the username (without the @)
        * text - String to send


Run an external command in a separate process and detach it from the current process. Excepting
    `stdout`, `stderr`, and `stdin` all file descriptors are closed after forking. If `daemonize`
    is True then the parent process exits. All stdio is redirected to `os.devnull` unless
    specified. The `preexec_fn`, `shell`, `cwd`, and `env` parameters are the same as their `Popen`
    counterparts. Return the PID of the child process if not daemonized.


Close open file descriptors.


Redirect a system stream to the provided target.


Takes a SlackEvent, parses it for a command, and runs against registered plugin


Show current allow and deny blocks for the given acl.


Create a new acl.


Delete an acl.


Applies a given HTML attributes to each field widget of a given form.

    Example:

        set_form_widgets_attrs(my_form, {'class': 'clickable'})


Returns a module from a given app by its name.

    :param str app_name:
    :param str module_name:
    :rtype: module or None


Run the mongod process.


Create a proxy to a class instance stored in ``proxies``.

    :param class BaseSchema: Base schema (e.g. ``StoredObject``)
    :param str label: Name of class variable to set
    :param class ProxiedClass: Class to get or create
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request


Class decorator factory; adds proxy class variables to target class.

    :param dict proxy_map: Mapping between class variable labels and proxied
        classes
    :param function get_key: Extension-specific key function; may return e.g.
        the current Flask request


Return primary key; if value is StoredObject, verify
        that it is loaded.


Assign to a nested dictionary.

    :param dict data: Dictionary to mutate
    :param value: Value to set
    :param list *keys: List of nested keys

    >>> data = {}
    >>> set_nested(data, 'hi', 'k0', 'k1', 'k2')
    >>> data
    {'k0': {'k1': {'k2': 'hi'}}}


Retrieve user by username


Sets permissions on user object


Schedules a function to be called after some period of time.

        * duration - time in seconds to wait before firing
        * func - function to be called
        * args - arguments to pass to the function


Returns Gravatar image URL for a given string or UserModel.

    Example:

        {% load gravatar %}
        {% gravatar_get_url user_model %}

    :param UserModel, str obj:
    :param int size:
    :param str default:
    :return:


Returns Gravatar image HTML tag for a given string or UserModel.

    Example:

        {% load gravatar %}
        {% gravatar_get_img user_model %}

    :param UserModel, str obj:
    :param int size:
    :param str default:
    :return:


Causes the bot to gracefully shutdown.