def execute_query_return_result_proxy(query):
    """
    Execute a query, yield result proxy.

    :param query: :class:`sqlalchemy.orm.Query`,
        has to be created from ``session.query(Object)``

    :return: :class:`sqlalchemy.engine.result.ResultProxy`
    """
    context = query._compile_context()
    context.statement.use_labels = False
    if query._autoflush and not query._populate_existing:
        query.session._autoflush()
    conn = query._get_bind_args(context, query._connection_from_session,
        close_with_result=True)
    return conn.execute(context.statement, query._params)


def pressure_fpa(force, area):
    """Usage: pressure_fpa(force of object, areaof object)"""
    return force / area


def get_querystring_for_page(request, page_number, querystring_key,
    default_number=1):
    """Return a querystring pointing to *page_number*."""
    querydict = request.GET.copy()
    querydict[querystring_key] = page_number
    if page_number == default_number:
        del querydict[querystring_key]
    if 'querystring_key' in querydict:
        del querydict['querystring_key']
    if querydict:
        return '?' + querydict.urlencode()
    return ''


def lifetime(U, Δn):
    """Return the lifetime (seconds) where U is the recombination  and Δn is the excess minority carrier density.
        This is the definition of lifetime"""
    return Δn / U


def _get_item_properties(item, fields):
    """Return a tuple containing the item properties."""
    row = []
    for field in fields:
        row.append(item.get(field, ''))
    return tuple(row)


@classmethod
def get_config_opts(cls):
    """Defines the configuration options to be associated to this loadable

        :return: A list of configuration options relative to this Loadable
        :rtype: list of :class:`oslo_config.cfg.Opt` instances
        """
    return []


def instanceof(obj, classinfo):
    """Wrap isinstance to only return True/False"""
    try:
        return isinstance(obj, classinfo)
    except TypeError:
        return False


def _find(seq, val):
    """
    Search sequence 'seq' for val.  This behaves like str.find(): if not found,
    -1 is returned instead of throwing an exception.

    Args:
        seq: The sequence to search
        val: The value to search for

    Returns:
        int: The index of the value if found, or -1 if not found
    """
    try:
        return seq.index(val)
    except ValueError:
        return -1


def is_perim_link(link, grid):
    """Return True if both nodes are boundaries; False otherwise.

    Examples
    --------
    >>> from landlab import HexModelGrid
    >>> import numpy as np
    >>> mg = HexModelGrid(
    ...     (3, 4), spacing=1.0, orientation="vertical", node_layout="rect"
    ... )
    >>> is_perim_link(1, mg)
    True
    >>> is_perim_link(11, mg)
    False
    """
    return grid.status_at_node[grid.node_at_link_tail[link]
        ] != grid.BC_NODE_IS_CORE and grid.status_at_node[grid.
        node_at_link_head[link]] != grid.BC_NODE_IS_CORE


def load_query_from_file(sql_file_path):
    """
    Read file and return content as string
    """
    file_name = sql_file_path
    if sql_file_path.startswith('@'):
        file_name = sql_file_path[1:]
    with open(file_name, 'r') as file:
        return file.read()


def is_valid_minute(minute):
    """
    Check if minute value is valid
    :param minute: int|string
    :return: boolean
    """
    return minute == '*' or 59 >= minute >= 0


def _get_reason(cluster_or_step):
    """Get state change reason message."""
    return cluster_or_step['Status']['StateChangeReason'].get('Message', '')


def upload_to_gdrive(drive, dl_location, filename, folder_id):
    """Upload file to Google drive.
    Make sure to include the following variables wherever you call upload_to_gdrive():
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication
    drive = GoogleDrive(gauth)
    Keyword arguments:
    drive -- GoogleDrive authorize object
    dl_location -- location of file to be uploaded
    filename -- filename of file to be uploaded
    folder_id -- folder id of Google Drive folder to upload to (gotten from URL)
    """
    f = drive.CreateFile({'title': filename, 'mimeType': 'text/csv',
        'parents': [{'kind': 'drive#fileLink', 'id': folder_id}]})
    f.SetContentFile(dl_location + filename)
    f.Upload()


def change_frame(frame: int=0):
    """Interactively change the current frame number

    :param frame: Frame
    :type frame: int
    """
    pass


def add_marker_slide(CLIP_OT_add_marker=None, TRANSFORM_OT_translate=None):
    """Add new marker and slide it with mouse until mouse button release

    :param CLIP_OT_add_marker: Add Marker, Place new marker at specified location
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def payment_value_colorize(column_data):
    """A helper method for payment value columns used to set different
    colors for negative values
    """
    return (column_data or 0) < 0


def to_int(i):
    """
    convert to integer, if possible
    """
    try:
        return int(i)
    except:
        return i


def autopack_toggle():
    """Automatically pack all external files into the .blend file

    """
    pass


def dot_product(a, b):
    """
    Perform the dot product of a and b.

    This method performs the dot product using a multiply and accumulate. Therefore, it is subject to Python 3's int
    implementation rule when being used with quantized values.

    :param a: Vector of length n.
    :param b: Vector of length n.
    :return:
    """
    if not len(a) == len(b):
        raise ValueError('a and b must have the same length')
    product = 0
    for ia, ib in zip(a, b):
        product += ia * ib
    return product


def get_path(structure, with_time_reversal=True, recipe='hpkot', threshold=
    1e-07, symprec=1e-05, angle_tolerance=-1.0):
    """
    Return the kpoint path information for band structure given a
    crystal structure, using the paths from the chosen recipe/reference.

    If you use this module, please cite the paper of the corresponding
    recipe (see parameter below).

    :param structure: The crystal structure for which we want to obtain
        the suggested path. It should be a tuple in the format
        accepted by spglib: ``(cell, positions, numbers)``, where
        (if N is the number of atoms):

        - ``cell`` is a :math:`3 \\times 3` list of floats (``cell[0]`` is the first lattice
          vector, ...)
        - ``positions`` is a :math:`N \\times 3` list of floats with the atomic coordinates
          in scaled coordinates (i.e., w.r.t. the cell vectors)
        - ``numbers`` is a length-:math:`N` list with integers identifying uniquely
          the atoms in the cell (e.g., the Z number of the atom, but
          any other positive non-zero integer will work - e.g. if you
          want to distinguish two Carbon atoms, you can set one number
          to 6 and the other to 1006)

    :param with_time_reversal: if False, and the group has no inversion
        symmetry, additional lines are returned as described in the HPKOT
        paper.

    :param recipe: choose the reference publication that defines the special
       points and paths.
       Currently, the following value is implemented:

       - ``hpkot``: HPKOT paper:
         Y. Hinuma, G. Pizzi, Y. Kumagai, F. Oba, I. Tanaka, Band structure
         diagram paths based on crystallography, Comp. Mat. Sci. 128, 140 (2017).
         DOI: 10.1016/j.commatsci.2016.10.015

    :param threshold: the threshold to use to verify if we are in
        and edge case (e.g., a tetragonal cell, but ``a==c``). For instance,
        in the tI lattice, if ``abs(a-c) < threshold``, a
        :py:exc:`~seekpath.hpkot.EdgeCaseWarning` is issued.
        Note that depending on the bravais lattice, the meaning of the
        threshold is different (angle, length, ...)

    :param symprec: the symmetry precision used internally by SPGLIB

    :param angle_tolerance: the angle_tolerance used internally by SPGLIB

    :return: a dictionary with the following
      keys:

        - ``point_coords``: a dictionary with label -> float coordinates
        - ``path``: a list of length-2 tuples, with the labels of the starting
          and ending point of each label section
        - ``has_inversion_symmetry``: True or False, depending on whether the
          input crystal structure has inversion symmetry or not.
        - ``augmented_path``: if True, it means that the path was
          augmented with the :math:`-k` points (this happens if both
          has_inversion_symmetry is False, and the user set
          with_time_reversal=False in the input)
        - ``bravais_lattice``: the Bravais lattice string (like ``cP``, ``tI``, ...)
        - ``bravais_lattice_extended``: the specific case used to define labels and
          coordinates (like ``cP1``, ``tI2``, ...)
        - ``cont_lattice``: three real-space vectors for the crystallographic
          conventional cell (``conv_lattice[0,:]`` is the first vector)
        - ``conv_positions``: fractional coordinates of atoms in the
          crystallographic conventional cell
        - ``conv_types``: list of integer types of the atoms in the crystallographic
          conventional cell (typically, the atomic numbers)
        - ``primitive_lattice``: three real-space vectors for the crystallographic
          primitive cell (``primitive_lattice[0,:]`` is the first vector)
        - ``primitive_positions``: fractional coordinates of atoms in the
          crystallographic primitive cell
        - ``primitive_types``: list of integer types of the atoms in the
          crystallographic primitive cell (typically, the atomic numbers)
        - ``reciprocal_primitive_lattice``: reciprocal-cell vectors for the
          primitive cell (vectors are rows: ``reciprocal_primitive_lattice[0,:]``
          is the first vector)
        - ``primitive_transformation_matrix``: the transformation matrix :math:`P` between
          the conventional and the primitive cell
        - ``inverse_primitive_transformation_matrix``: the inverse of the matrix :math:`P`
          (the determinant is integer and gives the ratio in volume between
          the conventional and primitive cells)
        - ``volume_original_wrt_conv``: volume ratio of the user-provided cell
          with respect to the the crystallographic conventional cell
        - ``volume_original_wrt_prim``: volume ratio of the user-provided cell
          with respect to the the crystalloraphic primitive cell

    :note: An :py:exc:`~seekpath.hpkot.EdgeCaseWarning` is issued for
        edge cases (e.g. if ``a==b==c`` for
        orthorhombic systems). In this case, still one of the valid cases
        is picked.
    """
    if recipe == 'hpkot':
        from . import hpkot
        res = hpkot.get_path(structure=structure, with_time_reversal=
            with_time_reversal, threshold=threshold, symprec=symprec,
            angle_tolerance=angle_tolerance)
    else:
        raise ValueError(
            "value for 'recipe' not recognized. The only value currently accepted is 'hpkot'."
            )
    return res


def unlink(address):
    """Unlink this IAddress from the user.

        Raises AddressNotLinkedError if this address is not linked to this
        user, either because it's not linked to any user or it's linked to
        some other user.
        """


def difference():
    """difference between incoming things"""


@classmethod
def handle(cls, value, context, **kwargs):
    """Returns the value of a key for a given hook in hook_data.

        Format of value:

            <hook_name>::<key>
        """
    try:
        hook_name, key = value.split('::')
    except ValueError:
        raise ValueError(
            'Invalid value for hook_data: %s. Must be in <hook_name>::<key> format.'
             % value)
    return context.hook_data[hook_name][key]


def size():
    """Return the size/length of the enclosed file.
       """


def run_func(zelf, *args, **kwargs):
    """ execute command/event pair. """
    cmnd = args[0]
    event = args[1]
    if cmnd not in zelf:
        return
    for functor in zelf[cmnd]:
        functor.func(event)
    event.ready()
    return event


def inverse_relation(dst, rel):
    """
    Similar to :meth:``forwards_relation`` but selects
    the source nodes instead, given a destination node.

    :param dst: The destination node.
    :param rel: The relation.
    """
    statement = 'SELECT src FROM %s WHERE dst = ?'
    return statement % rel, (dst,)


def get_postgres_pid(conn):
    """Helper to get the PostgreSQL connection PID"""
    qr = conn.execute('select pg_backend_pid()')
    pid = qr.fetchone()[0]
    return pid


def initialize():
    """Initialize script."""
    print('Welcome to auto_py_torrent!\n')


def toList(given):
    """
    This will take what is given and wrap it in a list if it is not already
    a list, otherwise it will simply return what it has been given.

    :return: list()
    """
    if not isinstance(given, (tuple, list)):
        given = [given]
    return given


def sql_flush(style, connection, only_server=False, reset_sequences=True,
    allow_cascade=False):
    """
    Return a list of the SQL statements used to flush the database.

    If only_server is True, only include the table names that have associated
    Server models and are in INSTALLED_APPS .
    """
    if only_server:
        tables = connection.introspection.server_table_names(only_existing=
            True, include_views=False)
    else:
        tables = connection.introspection.table_names(include_views=False)
    seqs = connection.introspection.sequence_list() if reset_sequences else ()
    statements = connection.ops.sql_flush(style, tables, seqs, allow_cascade)
    return statements


def fCO2fromCarbHCO3(CARB, HCO3, K0, K1, K2):
    """Calculate CO2 fugacity from carbonate ion and bicarbonate ion."""
    return HCO3 ** 2 * K2 / (CARB * K1 * K0)


def build_tf_to_pytorch_map(model, config):
    """ Build a map from TF variables to PyTorch modules. """
    tf_to_pt_map = {}
    tf_to_pt_map.update({'linear/w/ema_0.9999': model.embeddings.weight,
        'Generator/GenZ/G_linear/b/ema_0.9999': model.generator.gen_z.bias,
        'Generator/GenZ/G_linear/w/ema_0.9999': model.generator.gen_z.
        weight_orig, 'Generator/GenZ/G_linear/u0': model.generator.gen_z.
        weight_u})
    model_layer_idx = 0
    for i, (up, in_channels, out_channels) in enumerate(config.layers):
        if i == config.attention_layer_position:
            model_layer_idx += 1
        layer_str = ('Generator/GBlock_%d/' % i if i > 0 else
            'Generator/GBlock/')
        layer_pnt = model.generator.layers[model_layer_idx]
        for i in range(4):
            batch_str = layer_str + ('BatchNorm_%d/' % i if i > 0 else
                'BatchNorm/')
            batch_pnt = getattr(layer_pnt, 'bn_%d' % i)
            for name in ('offset', 'scale'):
                sub_module_str = batch_str + name + '/'
                sub_module_pnt = getattr(batch_pnt, name)
                tf_to_pt_map.update({(sub_module_str + 'w/ema_0.9999'):
                    sub_module_pnt.weight_orig, (sub_module_str + 'u0'):
                    sub_module_pnt.weight_u})
        for i in range(4):
            conv_str = layer_str + 'conv%d/' % i
            conv_pnt = getattr(layer_pnt, 'conv_%d' % i)
            tf_to_pt_map.update({(conv_str + 'b/ema_0.9999'): conv_pnt.bias,
                (conv_str + 'w/ema_0.9999'): conv_pnt.weight_orig, (
                conv_str + 'u0'): conv_pnt.weight_u})
        model_layer_idx += 1
    layer_str = 'Generator/attention/'
    layer_pnt = model.generator.layers[config.attention_layer_position]
    tf_to_pt_map.update({(layer_str + 'gamma/ema_0.9999'): layer_pnt.gamma})
    for pt_name, tf_name in zip(['snconv1x1_g', 'snconv1x1_o_conv',
        'snconv1x1_phi', 'snconv1x1_theta'], ['g/', 'o_conv/', 'phi/',
        'theta/']):
        sub_module_str = layer_str + tf_name
        sub_module_pnt = getattr(layer_pnt, pt_name)
        tf_to_pt_map.update({(sub_module_str + 'w/ema_0.9999'):
            sub_module_pnt.weight_orig, (sub_module_str + 'u0'):
            sub_module_pnt.weight_u})
    layer_str = 'Generator/BatchNorm/'
    layer_pnt = model.generator.bn
    tf_to_pt_map.update({(layer_str + 'offset/ema_0.9999'): layer_pnt.bias,
        (layer_str + 'scale/ema_0.9999'): layer_pnt.weight})
    layer_str = 'Generator/conv_to_rgb/'
    layer_pnt = model.generator.conv_to_rgb
    tf_to_pt_map.update({(layer_str + 'b/ema_0.9999'): layer_pnt.bias, (
        layer_str + 'w/ema_0.9999'): layer_pnt.weight_orig, (layer_str +
        'u0'): layer_pnt.weight_u})
    return tf_to_pt_map


def create_build(Name=None, Version=None, StorageLocation=None,
    OperatingSystem=None):
    """
    Creates a new Amazon GameLift build from a set of game server binary files stored in an Amazon Simple Storage Service (Amazon S3) location. When using this API call, you must create a .zip file containing all of the build files and store it in an Amazon S3 bucket under your AWS account. For help on packaging your build files and creating a build, see Uploading Your Game to Amazon GameLift .
    To create a new build using CreateBuild , identify the storage location and operating system of your game build. You also have the option of specifying a build name and version. If successful, this action creates a new build record with an unique build ID and in INITIALIZED status. Use the API call  DescribeBuild to check the status of your build. A build must be in READY status before it can be used to create fleets to host your game.
    See also: AWS API Documentation

    :example: response = client.create_build(
        Name='string',
        Version='string',
        StorageLocation={
            'Bucket': 'string',
            'Key': 'string',
            'RoleArn': 'string'
        },
        OperatingSystem='WINDOWS_2012'|'AMAZON_LINUX'
    )

    :type Name: string
    :param Name: Descriptive label that is associated with a build. Build names do not need to be unique. You can use UpdateBuild to change this value later.

    :type Version: string
    :param Version: Version that is associated with this build. Version strings do not need to be unique. You can use UpdateBuild to change this value later.

    :type StorageLocation: dict
    :param StorageLocation: Amazon S3 location of the game build files to be uploaded. The S3 bucket must be owned by the same AWS account that you're using to manage Amazon GameLift. It also must in the same region that you want to create a new build in. Before calling CreateBuild with this location, you must allow Amazon GameLift to access your Amazon S3 bucket (see Create a Build with Files in Amazon S3 ).
            Bucket (string) --Amazon S3 bucket identifier. This is the name of your S3 bucket.
            Key (string) --Name of the zip file containing your build files.
            RoleArn (string) --Amazon Resource Name (ARN ) for the access role that allows Amazon GameLift to access your S3 bucket.

    :type OperatingSystem: string
    :param OperatingSystem: Operating system that the game server binaries are built to run on. This value determines the type of fleet resources that you can use for this build. If your game build contains multiple executables, they all must run on the same operating system.

    :rtype: dict
    :return: {
        'Build': {
            'BuildId': 'string',
            'Name': 'string',
            'Version': 'string',
            'Status': 'INITIALIZED'|'READY'|'FAILED',
            'SizeOnDisk': 123,
            'OperatingSystem': 'WINDOWS_2012'|'AMAZON_LINUX',
            'CreationTime': datetime(2015, 1, 1)
        },
        'UploadCredentials': {
            'AccessKeyId': 'string',
            'SecretAccessKey': 'string',
            'SessionToken': 'string'
        },
        'StorageLocation': {
            'Bucket': 'string',
            'Key': 'string',
            'RoleArn': 'string'
        }
    }

    :returns:
    INITIALIZED  A new build has been defined, but no files have been uploaded. You cannot create fleets for builds that are in this status. When a build is successfully created, the build status is set to this value.
    READY  The game build has been successfully uploaded. You can now create new fleets for this build.
    FAILED  The game build upload failed. You cannot create new fleets for this build.

    """
    pass


def parse_path(path: str):
    """Get the repo path and the file path """
    path_to_list = path.split('/')
    file_path = ''
    for i in range(1, len(path_to_list)):
        file_path += path_to_list[i] + '/'
    return 'fusion/' + path.split('/')[0], file_path[:-1]


def horizons(path, short_circuit=False, validity=None):
    """Validate Horizons.h5 file for BHNS simulation

    """
    import os.path
    import numpy as np
    import h5py
    from . import _Validity
    v = validity or _Validity(short_circuit)
    raise NotImplementedError()
    return v.valid


def remove_stopwords(tokens, language):
    """
    Takes a language (i.e. 'english'), and a set of word tokens.
    Returns the tokenized text with any stopwords removed.
    Stop words are words like "is, the, a, ..."

    Be sure to download the required NLTK corpus before calling this function:
    - from mitoo.utils import nltk_download_corpus
    - nltk_download_corpus('corpora/stopwords')
    """
    from nltk.corpus import stopwords
    stop_words = stopwords.words(language)
    tokens = set(tokens) - set(stop_words)
    return tokens


@classmethod
def build_from_mongo(cls, data, partial=False, use_cls=False):
    """
        Create a document instance from MongoDB data

        :param data: data as retrieved from MongoDB
        :param use_cls: if the data contains a ``_cls`` field,
            use it determine the Document class to instanciate
        """
    if use_cls and '_cls' in data:
        cls = cls.opts.instance.retrieve_document(data['_cls'])
    doc = cls()
    doc.from_mongo(data, partial=partial)
    return doc


def _to_dict(name_value: (dict, tuple)) ->dict:
    """Make sure the name_value a dict object"""
    return dict(name_value) if isinstance(name_value, tuple) else name_value


def pairwise(iterable):
    """s -> (s0, s1), (s2, s3), (s4, s5), ..."""
    a = iter(iterable)
    return zip(a, a)


def _compute_value_diff(df, start, end, groups):
    """
    Compute diff value between start and end
    Args:
        df(dataframe):

    Returns: Dataframe

    """
    start_values = df[df['date'] == start['id']].copy()
    end_values = df[df['date'] == end['id']].copy()
    merge_on = []
    for key, group in groups.items():
        merge_on = merge_on + [key, f'{key}_label', f'{key}_order']
    df = start_values.merge(end_values, on=merge_on, how='outer', suffixes=
        ('_start', '_end'))
    df[['value_start', 'value_end']] = df[['value_start', 'value_end']].fillna(
        0)
    df['value'] = df['value_end'] - df['value_start']
    df.drop(['date_start', 'date_end', 'value_end'], axis=1, inplace=True)
    df.rename(columns={'upperGroup': 'groups'}, inplace=True)
    return df


def gsreshaped(data):
    """
    gridsearch reshape values according to GridSearchCV.fit

    see https://stackoverflow.com/a/49241326
    """
    import pandas as pd
    import numpy as np
    if isinstance(data, (pd.Series, pd.DataFrame)):
        if len(data.shape) == 2 and data.shape[1] == 1:
            data = data.values.reshape(-1)
    elif isinstance(data, np.ndarray):
        if len(data.shape) == 2 and data.shape[1] == 1:
            data = data.reshape(-1)
    return data


def print_string_to_file(filename, string_contents):
    """
    This is a helper method to write the contents of a string into a file.
    Parameters:

    filename -- The name of the file to write the string into
    string_contents -- The string that will be written
    """
    with open(filename, 'w') as file_handle:
        file_handle.write(string_contents)


def upper(text):
    """
    Creates a copy of ``text`` with all the cased characters converted to uppercase.

    Note that ``isupper(upper(s))`` might be False if ``s`` contains uncased characters
    or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase).

    The uppercasing algorithm used is described in section 3.13 of the Unicode Standard.

    :param text: The string to convert
    :type text:  ``str``

    :return: A copy of ``text`` with all the cased characters converted to uppercase.
    :rtype:  ``str``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.upper()


def all_peers(synset):
    """Get the set of all peers of the synset (including the synset).
       If the synset has multiple hypernyms then the peers will be hyponyms of
       multiple synsets."""
    hypernyms = synset.hypernyms()
    peers = []
    for hypernym in hypernyms:
        peers += hypernym.hyponyms()
    return set(peers)


@classmethod
def flatten(cls, change):
    """
        This method will flatten changes and return a list of TaskChange
        """
    changes = list()
    if not change:
        return changes
    changes.append(change)
    for related in change.related_changes:
        changes.extend(cls.flatten(related))
    return changes


def secondYAxis(requestContext, seriesList):
    """
    Graph the series on the secondary Y axis.
    """
    for series in seriesList:
        series.options['secondYAxis'] = True
        series.name = 'secondYAxis(%s)' % series.name
    return seriesList


def _apply_filters(filters, traces):
    """
    Here we make each trace go through the filters configured in the
    tracer. There is no need for a lock since the traces are owned by the
    AgentWriter at that point.
    """
    if filters is not None:
        filtered_traces = []
        for trace in traces:
            for filtr in filters:
                trace = filtr.process_trace(trace)
                if trace is None:
                    break
            if trace is not None:
                filtered_traces.append(trace)
        return filtered_traces
    return traces


def window_accumulator(acc, new, diff=None, window=None, agg=None):
    """ An accumulation binary operator for windowed aggregations

    This is the function that is actually given to the ``Stream.accumulate``
    function.  It performs all of the work given old state, new data, a diff
    function, window value, and aggregation object.

    Parameters
    ----------
    acc: state
    new: DataFrame, Series
        The new data to add to the window.
    diff: callable
        One of ``diff_iloc`` or ``diff_loc``
    window: int, value
        Either an integer for ``n=...`` for a value like ``value='2h'``
    agg: Aggregation
        The aggregation object to apply, like ``Sum()``

    Returns
    -------
    acc: state
    result: newly emitted result

    See Also
    --------
    accumulator
    windowed_groupby_accumulator
    """
    if acc is None:
        acc = {'dfs': [], 'state': agg.initial(new)}
    dfs = acc['dfs']
    state = acc['state']
    dfs, old = diff(dfs, new, window=window)
    if new is not None:
        state, result = agg.on_new(state, new)
    for o in old:
        if len(o):
            state, result = agg.on_old(state, o)
    acc2 = {'dfs': dfs, 'state': state}
    return acc2, result


def select_set():
    """Set the console selection

    """
    pass


def bucket_key_to_s3_path(bucket, key):
    """
    Takes an S3 bucket and key combination and returns the full S3 path to that location.
    """
    return f's3://{bucket}/{key}'


def setSubject(subject):
    """ Set DCMI Subject element - resource keywords.

        o Permission:  Modify portal content
        """


def get_mu(frequencies):
    """
    Calculates the mutation rate for F81 (and JC that is a simplification of it),
    as \\mu = 1 / (1 - sum_i \\pi_i^2). This way the overall rate of mutation -\\mu trace(\\Pi Q) is 1.
    See [Gascuel "Mathematics of Evolution and Phylogeny" 2005] for further details.

    :param frequencies: numpy array of state frequencies \\pi_i
    :return: mutation rate \\mu = 1 / (1 - sum_i \\pi_i^2)
    """
    return 1.0 / (1.0 - frequencies.dot(frequencies))


@staticmethod
def get_state_type():
    """
        This is needed so the service framework knows the
        state type of the current state.
        return::str The state and update type of this state.
        """
    return 'delta_update_in'


def get_default_params(dim: int):
    """
        Returns the default parameters of the L-SHADE-cnEpSin Differential Evolution Algorithm
        :param dim: Size of the problem (or individual).
        :type dim: int
        :return: Dict with the default parameters of the L-SHADE-cnEpSin  Differential
        Evolution Algorithm.
        :rtype dict
    """
    return {'population_size': 18 * dim, 'min_population_size': 4,
        'individual_size': dim, 'memory_size': 5, 'max_evals': 10000 * dim,
        'seed': None, 'callback': None, 'opts': None}


def replace_colon(s, replacewith='__'):
    """replace the colon with something"""
    return s.replace(':', replacewith)


def cnr_amplitude_standardNoise(idealSignal, noiseSignal):
    """
    Calculate the CNR (contrast-to-noise ratio [1]) via the amplitude
    of idealSignal and standard deviation of the noise.

    Parameters
    ----------
    idealSignal: 1-D array-like
        The ideal signal, based in the currentSignal.
    noiseSignal: 1-D array-like
        Noise apply to ideal signal, could be a initial or residual noise.

    Returns
    -------
    float:
        Ratio of maximum distance of zero and standard deviation of the noise.
    """
    import numpy as np
    idealSignal, noiseSignal = np.array(noiseSignal), np.array(noiseSignal)
    return np.maximum(np.abs(idealSignal.max()), np.abs(idealSignal.min())
        ) / noiseSignal.std()


def _get_key_value(string):
    """Return the (key, value) as a tuple from a string."""
    key = ''
    value = ''
    try:
        key, value = string.split(': ')
    except ValueError:
        string = string.lstrip(' ')
        if string.startswith('physicaldrive'):
            fields = string.split(' ')
            key = fields[0] + ' ' + fields[1]
            value = fields[1]
        else:
            return string.strip(' '), None
    return key.strip(' '), value.strip(' ')


def render_git_describe_long(pieces):
    """TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def update_permission(pid: str=None, namespace: str=None, action: str=None):
    """

    DynamoDB Integration:
    ---

    if not pid:
        raise KeyError("PID argument is required.")

    try:
        _update_expression = ", ".join(f"SET {k} = :{k}" for k in perm_data.keys())
        _expression_attr_values = {f":{k}": v for k, v in perm_data.items()}

        permission_table.get_update(Key={"pid": {"S": pid}},
                                    updateExpression=_update_expression,
                                    expressionAttributeValues=_expression_attr_values)

        return permission_table.get_item(Key={"pid": {"S": pid}})

    except Exception as e:
        print(e)

        raise KeyError(e)
    """
    if not pid:
        raise KeyError('PID argument is required.')
    return {'pid': pid, 'namespace': namespace or 'not modified', 'action':
        action or 'not modified'}


def vel_avg_vt(g: float, ve_before: float, ve_after: float, mass: float
    ) ->float:
    """Returns the arithmetic mean of the relative velocity of particles before and after
    a VT transition (using the energy conservation law) **M(i1) + P -> M(i2) + P**

    Parameters
    ----------
    g : float
        the relative dimensional velocity of the particles before the collision
    ve_before : float
        the vibrational energy of the molecule before the transition
    ve_after : float
        the vibrational energy of the molecule after the transition
    mass : float
        the collision-reduced mass :math:`m_{cd}`

    Returns
    -------
    float
        Arithmetic mean of before- and after- velocities for a VT transition

    Notes
    -----
    If the squared after-collision velocity is < 0, then the collision is impossible for such parameters and
    the function returns -1
    """
    gn_sq = (ve_before - ve_after) * (2.0 / mass) + g ** 2
    if gn_sq < 0:
        return -1
    else:
        return 0.5 * (g + gn_sq ** 0.5)


def user_wants_upload():
    """
    Determines whether or not the user wants to upload the extension
    :return: boolean
    """
    choice = input('Do you want to upload your extension right now? :')
    if 'y' in choice or 'Y' in choice:
        return True
    else:
        return False


def unstretch(image, minval, maxval):
    """Perform the inverse of stretch, given a stretched image

    image - an image stretched by stretch or similarly scaled value or values
    minval - minimum of previously stretched image
    maxval - maximum of previously stretched image
    """
    return image * (maxval - minval) + minval


def read_csv(path, sep, line_terminator):
    """Yield a value from a csv file on disk

    Keyword arguments:
    path            (string) -- path to file
    sep             (string) -- separator substring
    line_terminator (string) -- line terminator substring
    """
    with open(path) as fin:
        for line in fin:
            yield line.replace('"', '').replace(line_terminator, '').split(sep)


@staticmethod
def _nullify_flavor_description(flavor_info):
    """Helper method to nullify descriptions from a set of primitive
        flavors.

        Note that we don't remove the flavor description since that would
        make the versioned notification FlavorPayload have to handle the field
        not being set on the embedded instance.flavor.

        :param dict: dict of primitive flavor objects where the values are the
            flavors which get persisted in the instance_extra.flavor table.
        """
    for flavor in flavor_info.values():
        if flavor and 'description' in flavor['nova_object.data']:
            flavor['nova_object.data']['description'] = None


def title_splitter(x):
    """Make tokens from title formatted strings

    :param x: The filepath of string.
    :type x: WindowsFilePath, PosixFilePath, str

    :return: list of tokens (strings)
    :return_type: list
    """
    raise NotImplementedError


def nonempty(iterative):
    """
    True if `iterative` returns at least one element.

    >>> nonempty(iter([1]))
    True
    >>> nonempty(iter([]))
    False

    """
    for _ in iterative:
        return True
    return False


def findObj(objroot, objclass):
    """
    Find all the objects that is instance of objclass belongs to objroot.
    obj
    """
    objfound = []
    for obj in dir(objroot):
        obji = eval('objroot.' + obj)
        if isinstance(obji, objclass):
            objfound.append(obji)
    return objfound


@classmethod
def pairs(cls, fields, order_by=None, _result=None):
    """
            Returns a list of two element tuples.
            [
                (1, 'apple')
                (2, 'banana')
            ]

            fields: string with the name of the fields you want to pair with
                a ":" seperating them.  I.e.:

                Fruit.pairs('id:name')

            order_by = order_by clause or iterable of order_by clauses
        """
    key_field_name, value_field_name = fields.split(':')
    if _result is None:
        _result = cls.list(order_by)
    retval = []
    for obj in _result:
        retval.append((getattr(obj, key_field_name), getattr(obj,
            value_field_name)))
    return retval


def view_center_cursor():
    """Center the view so that the cursor is in the middle of the view

    """
    pass


def get_numpy_include_path():
    """
    Gets the path to the numpy headers.
    """
    import builtins
    if hasattr(builtins, '__NUMPY_SETUP__'):
        del builtins.__NUMPY_SETUP__
    import imp
    import numpy
    imp.reload(numpy)
    try:
        numpy_include = numpy.get_include()
    except AttributeError:
        numpy_include = numpy.get_numpy_include()
    return numpy_include


@staticmethod
def post(*args, **kwargs):
    """Not implemented as TfL doesn't use anything other than GET.
        """
    raise NotImplementedError


def _encode_identifier(asn1_class, constructed, tag):
    """Encode a DER object's identifier"""
    flags = asn1_class << 6 | (32 if constructed else 0)
    if tag < 32:
        identifier = [flags | tag]
    else:
        identifier = [tag & 127]
        while tag >= 128:
            tag >>= 7
            identifier.append(128 | tag & 127)
        identifier.append(flags | 31)
    return bytes(identifier[::-1])


def pop(index=-1):
    """Remove and return item at index (default last)"""


def SwapIndx(Axis, H):
    """needs doc string"""
    if Axis in [1, -1]:
        return H
    elif Axis in [2, -3]:
        return [H[1], H[2], H[0]]
    else:
        return [H[2], H[0], H[1]]


def reverse_entry(invoice_number):
    """Takes a financial entry and reverse it, creating a new instance
        with an oposite value
        """


@classmethod
def is_incomplete_status(cls, status):
    """
        Returns a boolean if the passed in status is in an "incomplete" state.
        """
    return status in [cls.eligible, cls.created, cls.
        download_software_clicked, cls.ready_to_start, cls.started, cls.
        ready_to_submit]


def return_first_col_action(row, action_dict):
    """
    Default action function for tables. This function returns the first data column value for the row of
        data. Used by the **TABLE_RETURN_FIRST_VAL** action.

    :param List row: the data associated with the selected row
    :param Dict action_dict: the dictionary of values associated with the action - ignored in this function

    :return: The first value from the list of data values for the selected row of the table.
    """
    return row.values[0]


def Uij2betaij(Uij, G):
    """
    Convert Uij to beta-ij tensors -- stub for eventual completion

    :param Uij: numpy array [Uij]
    :param G: reciprocal metric tensor
    :returns: beta-ij - numpy array [beta-ij]
    """
    pass


def fitarg_rename(fitarg, ren):
    """Rename variable names in ``fitarg`` with rename function.

    ::

        #simple renaming
        fitarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1},
            lambda pname: 'y' if pname=='x' else pname)
        #{'y':1, 'limit_y':1, 'fix_y':1, 'error_y':1},

        #prefixing
        figarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1},
            lambda pname: 'prefix_'+pname)
        #{'prefix_x':1, 'limit_prefix_x':1, 'fix_prefix_x':1, 'error_prefix_x':1}

    """
    tmp = ren
    if isinstance(ren, str):

        def ren(x):
            return tmp + '_' + x
    ret = {}
    prefix = ['limit_', 'fix_', 'error_']
    for k, v in fitarg.items():
        vn = k
        pf = ''
        for p in prefix:
            if k.startswith(p):
                i = len(p)
                vn = k[i:]
                pf = p
        newvn = pf + ren(vn)
        ret[newvn] = v
    return ret


def KK_RC4(w, Rs, R_values, t_values):
    """
    Kramers-Kronig Function: -RC-

    Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
    """
    return Rs + R_values[0] / (1 + w * 1.0j * t_values[0]) + R_values[1] / (
        1 + w * 1.0j * t_values[1]) + R_values[2] / (1 + w * 1.0j * t_values[2]
        ) + R_values[3] / (1 + w * 1.0j * t_values[3])


def norm_nonFara_Q_C(Rs, Q, n, L='none'):
    """
    Normalziation of a non-faradaic interfacial capacitance (Blocking Electrode)

    Following Brug and Hirschorn's normalization of distribtuion of relaxation times
    Ref.:
        - G.J.Brug et al., J.Electroanal. Chem. Interfacial Electrochem., 176, 275 (1984)

    Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com)

    Inputs
    ------------------
    Q = Constant phase element [s^n/ohm]
    n = Exponent of CPE [-]
    Rs = Series Resistance [ohm]

    Optional Inputs
    ------------------
    L = Thickness/length of electrode, used in Porous Electrode Theory [cm]

    Returns
    ------------------
    C_eff = normalized capacitance for a non-faradaic electrode [s/ohm = F]
    """
    if L == 'none':
        C_eff = (Q * Rs ** (1 - n)) ** (1 / n)
    else:
        C_eff = (Q * L * Rs ** (1 - n)) ** (1 / n)
    return C_eff


def pgcd(a, b):
    """return the highest common divisor of two positive integers
    Method of sequential substractions
    """
    sentenceerror = '%s,%s must be positive integers' % (str(a), str(b))
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError(sentenceerror)
    if a <= 0 or b <= 0:
        raise TypeError(sentenceerror)
    while a != b:
        if a < b:
            a, b = b, a
        a, b = a - b, b
    return a


def strings_equal(s1, s2):
    """
    Timing-attack resistant string comparison.
    Normal comparison using == will short-circuit on the first mismatching
    character. This avoids that by scanning the whole string, though we
    still reveal to a timing attack whether the strings are the same
    length.
    """
    try:
        from hmac import compare_digest
        return compare_digest(s1, s2)
    except ImportError:
        pass
    if len(s1) != len(s2):
        return False
    differences = 0
    for c1, c2 in zip(s1, s2):
        differences |= ord(c1) ^ ord(c2)
    return differences == 0


def application_copyright():
    """Return the name of the copyright holder."""
    return 'Combine Control Systems AB'


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_bool()
    return parameters


def unquote(s):
    """Turn a string in the form =AB to the ASCII character with value 0xab"""
    return chr(int(s[1:3], 16))


def trunc_time_minute(date):
    """
    Truncate an object of type DateTime with time to 00:00:00
    :param date: Date for truncate
    :return: Date truncated
    """
    return date.replace(second=0, microsecond=0)


def get_attrname(name):
    """Return the mangled name of the attribute's underlying storage."""
    return '_obj_' + name


def get_account_id(event):
    """Gets the account id from an event"""
    return event['account']


def shortest_loop(code):
    """Sorts crossing by shortest loop described"""
    return sorted(code, key=lambda x: abs(abs(x[0]) - abs(x[1])))


def build_property_spec(client_factory, type_='VirtualMachine',
    properties_to_collect=None, all_properties=False):
    """Builds the property spec.

    :param client_factory: factory to get API input specs
    :param type_: type of the managed object
    :param properties_to_collect: names of the managed object properties to be
                                  collected while traversal filtering
    :param all_properties: whether all properties of the managed object need
                           to be collected
    :returns: property spec
    """
    if not properties_to_collect:
        properties_to_collect = ['name']
    property_spec = client_factory.create('ns0:PropertySpec')
    property_spec.all = all_properties
    property_spec.pathSet = properties_to_collect
    property_spec.type = type_
    return property_spec


@classmethod
def with_static_publisher(cls, publisher):
    """Construct a ProgressHooks that uses an already-constructed publisher.
        """
    return cls(publisher_factory=lambda : publisher)


def _NDArray(*data, **kwargs):
    """Stub for implementing an operator implemented in native frontend language with ndarray.

    Parameters
    ----------
    data : NDArray[]
        Input data for the custom operator.
    info : ptr, required

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def ceildiv(dividend, divisor):
    """ integer ceiling division """
    return (dividend + divisor - 1) // divisor


def _is_dunder(name):
    """Returns True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2
        ] != '_' and len(name) > 4


@classmethod
def set_task_queueing(cls, enabled: bool):
    """
        Enable queueing mode, which causes tasks to be queued until launched by
        calling `DispatcherInternal.flushQueuedInitialTasks`.

        Args:
            enabled (bool): Whether or not to queue tasks.
        """
    cls._queue_initial_tasks = enabled


def unber(s):
    """ Perl BER unpacking
    Format definition: from http://perldoc.perl.org/functions/pack.html
        (see "w" template description)

    BER is a way to pack several variable-length ints into one
    binary string. Here we do the reverse

    Args:
        s (str): a binary string with packed values

    Returns:
         str: a list of unpacked values

    >>> unber('\\x00\\x83M')
    [0, 461]
    >>> unber('\\x83M\\x96\\x14')
    [461, 2836]
    >>> unber('\\x99a\\x89\\x12')
    [3297, 1170]
    """
    res = []
    acc = 0
    for char in s:
        b = ord(char)
        acc = (acc << 7) + (b & 127)
        if not b & 128:
            res.append(acc)
            acc = 0
    return res


def lev(i):
    """Description of levels."""
    return ['undefined', 'trivial', 'very easy', 'easy', 'normal', 'hard',
        'very hard', 'evil', 'extreme', 'ultimate'][i]


@classmethod
def modify_url_for_impersonation(cls, url, impersonate_user, username):
    """
        Modify the SQL Alchemy URL object with the user to impersonate if applicable.
        :param url: SQLAlchemy URL object
        :param impersonate_user: Bool indicating if impersonation is enabled
        :param username: Effective username
        """
    if impersonate_user is not None and username is not None:
        url.username = username


def column_exists(cr, table, column):
    """ Check whether a certain column exists """
    cr.execute(
        'SELECT count(attname) FROM pg_attribute WHERE attrelid = ( SELECT oid FROM pg_class WHERE relname = %s ) AND attname = %s'
        , (table, column))
    return cr.fetchone()[0] == 1


def get_cached_member(userid, location=None):
    """Get a member object which can be cached of ``userid``, or
        None if no such, searched within the site at the given
        ``location`` if provided.

        :return: an :py:class:`~silva.core.interfaces.auth.IMember`
                 object or None.
        """


def _count_elements_slow(mapping, iterable):
    """Put elements from `iterable` into `mapping`."""
    mapping_get = mapping.get
    for element in iterable:
        mapping[element] = mapping_get(element, 0) + 1


def does_intersection_exist_line2d(line_ray_a, line_ray_b):
    """Boolean denoting whether an intersection exists between Ray2D or LineSegment2D.

    This is slightly faster than actually computing the intersection but should only be
    used in cases where the actual point of intersection is not needed.

    Args:
        line_ray_a: A LineSegment2D or Ray2D object.
        line_ray_b: Another LineSegment2D or Ray2D to intersect.

    Returns:
        True if an intersection exists. False if no intersection exists.
    """
    d = line_ray_b.v.y * line_ray_a.v.x - line_ray_b.v.x * line_ray_a.v.y
    if d == 0:
        return False
    dy = line_ray_a.p.y - line_ray_b.p.y
    dx = line_ray_a.p.x - line_ray_b.p.x
    ua = (line_ray_b.v.x * dy - line_ray_b.v.y * dx) / d
    if not line_ray_a._u_in(ua):
        return False
    ub = (line_ray_a.v.x * dy - line_ray_a.v.y * dx) / d
    if not line_ray_b._u_in(ub):
        return False
    return True


@staticmethod
def compute_bounds(data, pixel_size, center_on):
    """Return image bounds from *pixel_size* (scalar or tuple)"""
    if not isinstance(pixel_size, (tuple, list)):
        pixel_size = [pixel_size, pixel_size]
    dx, dy = pixel_size
    xmin, ymin = 0.0, 0.0
    xmax, ymax = data.shape[1] * dx, data.shape[0] * dy
    if center_on is not None:
        xc, yc = center_on
        dx, dy = 0.5 * (xmax - xmin) - xc, 0.5 * (ymax - ymin) - yc
        xmin -= dx
        xmax -= dx
        ymin -= dy
        ymax -= dy
    return xmin, xmax, ymin, ymax


def GrowInstanceDisk(r, instance, disk, amount, wait_for_sync=False):
    """
    Grows a disk of an instance.

    More details for parameters can be found in the RAPI documentation.

    @type instance: string
    @param instance: Instance name
    @type disk: integer
    @param disk: Disk index
    @type amount: integer
    @param amount: Grow disk by this amount (MiB)
    @type wait_for_sync: bool
    @param wait_for_sync: Wait for disk to synchronize
    @rtype: int
    @return: job id
    """
    body = {'amount': amount, 'wait_for_sync': wait_for_sync}
    return r.request('post', '/2/instances/%s/disk/%s/grow' % (instance,
        disk), content=body)


def curv(xn, zn):
    """ Curvilinear coordinates: test case 1. Physical == numerical. """
    return xn.copy(), zn.copy()


def path_info_pop(environ):
    """
    'Pops' off the next segment of PATH_INFO, pushing it onto
    SCRIPT_NAME, and returning that segment.

    For instance::

        >>> def call_it(script_name, path_info):
        ...     env = {'SCRIPT_NAME': script_name, 'PATH_INFO': path_info}
        ...     result = path_info_pop(env)
        ...     print 'SCRIPT_NAME=%r; PATH_INFO=%r; returns=%r' % (
        ...         env['SCRIPT_NAME'], env['PATH_INFO'], result)
        >>> call_it('/foo', '/bar')
        SCRIPT_NAME='/foo/bar'; PATH_INFO=''; returns='bar'
        >>> call_it('/foo/bar', '')
        SCRIPT_NAME='/foo/bar'; PATH_INFO=''; returns=None
        >>> call_it('/foo/bar', '/')
        SCRIPT_NAME='/foo/bar/'; PATH_INFO=''; returns=''
        >>> call_it('', '/1/2/3')
        SCRIPT_NAME='/1'; PATH_INFO='/2/3'; returns='1'
        >>> call_it('', '//1/2')
        SCRIPT_NAME='//1'; PATH_INFO='/2'; returns='1'

    """
    path = environ.get('PATH_INFO', '')
    if not path:
        return None
    while path.startswith('/'):
        environ['SCRIPT_NAME'] += '/'
        path = path[1:]
    if '/' not in path:
        environ['SCRIPT_NAME'] += path
        environ['PATH_INFO'] = ''
        return path
    else:
        segment, path = path.split('/', 1)
        environ['PATH_INFO'] = '/' + path
        environ['SCRIPT_NAME'] += segment
        return segment


def get_start_end_pl_surr(TMD_start, TMD_end, seqlen, surr):
    """Get start and end of TMD plus surrounding sequence

    Parameters
    ----------
    TMD_start
    TMD_end
    seqlen
    surr

    Returns
    -------

    """
    TMD_start_pl_surr = TMD_start - surr
    if TMD_start_pl_surr < 1:
        TMD_start_pl_surr = 1
    TMD_end_pl_surr = TMD_end + surr
    if TMD_end_pl_surr > seqlen:
        TMD_end_pl_surr = seqlen
    return TMD_start_pl_surr, TMD_end_pl_surr


def cuboid(target, throat_diameter='throat.diameter'):
    """
    Calcuate the throat perimeter assuming a square cross-section

    Parameters
    ----------
    target : OpenPNM Object
        The object which this model is associated with. This controls the
        length of the calculated array, and also provides access to other
        necessary properties.

    throat_diameter : string
        The dictionary key of the array containing the throat diameter values.

    Returns
    -------
    value : NumPy ndarray
        Array containing throat perimeter values.

    """
    return target[throat_diameter] * 4


def converttitled(titledparagraphs):
    """
    Convert titled paragraphs to strings
    """
    string_list = []
    for title, paragraphs in titledparagraphs:
        lines = []
        for para in paragraphs:
            lines.extend(para)
        string_list.append(b' '.join(lines))
    return string_list


def extractLink(model, item):
    """
        Extract a URI for the column from an Item.

        @type model: L{methanal.widgets.Table}

        @type  item: L{axiom.item.Item}
        @param item: Item from which to extract a URI

        @rtype: C{unicode}
        @return: A URI somehow relevant for this column, or C{None}
        """


def set_on(instance, attrname, value):
    """
    A cleaner, slightly shorter way of setting values directly on an instance's
    `__dict__`.
    :param instance: instance to store the value on
    :param attrname: name of the attribute to store the value with
    :param value: value to store on the instance
    """
    instance.__dict__[attrname] = value


@classmethod
def contains(cls, value):
    """
        gets a value indicating that given input existed in
        the enumeration values.

        :param int | str | CoreEnum value: value to be checked for existence.

        :rtype: bool
        """
    return value in cls


def dimensions(fontid: int, text: str):
    """Return the width and height of the text.

    :param fontid: The id of the typeface as returned by blf.load(), for default font use 0.
    :type fontid: int
    :param text: the text to draw.
    :type text: str
    :return:  the width and height of the text.
    """
    pass


def psi_Li_Na_OAc_PK74(T, P):
    """c-c'-a: lithium sodium OAc [PK74]."""
    psi = -0.0043
    valid = T == 298.15
    return psi, valid


def parseStreamClient(reactor, *args, **kwargs):
    """
        This method is invoked by L{endpoints.clientFromString}, if the type of
        endpoint matches the return value from this
        L{IStreamClientEndpointStringParserWithReactor}'s C{prefix} method.

        @param reactor: The reactor passed to L{endpoints.clientFromString}.

        @param args: The byte string arguments, minus the endpoint type, in the
            endpoint description string, parsed according to the rules
            described in L{endpoints.quoteStringArgument}.  For example, if the
            description were C{b"my-type:foo:bar:baz=qux"}, C{args} would be
            C{(b'foo', b'bar')}

        @param kwargs: The byte string arguments from the endpoint description
            passed as keyword arguments.  For example, if the description were
            C{b"my-type:foo:bar:baz=qux"}, C{kwargs} would be
            C{dict(baz=b'qux')}.

        @return: a client endpoint
        @rtype: a provider of L{IStreamClientEndpoint}
        """


def parse_global_arguments(unparsed_arguments, top_level_parser, subparsers):
    """
    Given a sequence of arguments, a top-level parser (containing subparsers), and a subparsers
    object as returned by argparse.ArgumentParser().add_subparsers(), parse and return any global
    arguments as a parsed argparse.Namespace instance.
    """
    remaining_arguments = list(unparsed_arguments)
    present_subparser_names = set()
    for subparser_name, subparser in subparsers.choices.items():
        if subparser_name not in remaining_arguments:
            continue
        present_subparser_names.add(subparser_name)
        unused_parsed, remaining_arguments = subparser.parse_known_args(
            remaining_arguments)
    if (not present_subparser_names and '--help' not in unparsed_arguments and
        '-h' not in unparsed_arguments):
        for subparser_name in ('prune', 'create', 'check'):
            subparser = subparsers.choices[subparser_name]
            unused_parsed, remaining_arguments = subparser.parse_known_args(
                remaining_arguments)
    for subparser_name in present_subparser_names:
        if subparser_name in remaining_arguments:
            remaining_arguments.remove(subparser_name)
    return top_level_parser.parse_args(remaining_arguments)


def parentrevs(rev):
    """Like parents() but operates on revision numbers."""


@classmethod
def gcd(cls, *poly_list):
    """
        Computes the greatest common divisor (gcd) of polynomials in a given list.
        """
    gcd = poly_list[0]
    for poly in poly_list[1:]:
        gcd, _, _ = cls.xgcd(gcd, poly)
    return gcd


def to_si(mas, mas_yr, d):
    """Convert from mas -> km and mas/yr -> km/s
        Input:
         mas (array) [mas]: distance in mas
         mas_yr (array) [mas/yr]: velocity in mas/yr
         d (float) [pc]: distance to system in parsecs
        Returns:
         km (array) [km]: distance in km
         km_s (array) [km/s]: velocity in km/s
    """
    import numpy as np
    import astropy.units as u
    km = (mas * u.mas.to(u.arcsec) * d * u.AU).to(u.km)
    km_s = (mas_yr * u.mas.to(u.arcsec) * d * u.AU).to(u.km)
    km_s = km_s.value * (u.km / u.yr).to(u.km / u.s)
    return km.value, km_s


def __strip_line(input_file):
    """
    Removes spaces and newline whitespaces.

    Parameters
    ----------
    input_file : file
        .seq file

    Returns
    -------
    line : str
        First line in input_file after removing spaces and newline whitespaces. Note: File pointer is remembered,
        so successive calls work as expected. Returns -1 for eof.
    """
    line = input_file.readline()
    return line.strip() if line != '' else -1


def ruler_add():
    """Undocumented contribute <https://developer.blender.org/T51061>

    """
    pass


def display_scaffold(scaffold, label):
    """Display a scaffold in a consistent way for listing."""
    return '  {0: <12}| {1}'.format(scaffold, label)


def is_tool(name):
    """Check whether `name` is on PATH and marked as executable."""
    from shutil import which
    return which(name) is not None


def _check_required_parameters(dictionary_of_params, required_params):
    """
    Check that all required parameters are inputted
    :param dictionary_of_params: is a dictionary of parameters from playbook
    :param required_params: is a set of required parameters
    :return: '' if all required parameters are inputted, else string that contains all missing required parameters
    """
    result = ''
    for element in required_params:
        if not dictionary_of_params.get(element):
            result += '{}, '.format(element)
    result = result[:-2]
    return result


def get_visual_distance(c, axis=None):
    """Not implemented."""
    return


def vert_splice(vert: 'bmesh.types.BMVert', vert_target: 'bmesh.types.BMVert'):
    """Splice vert into vert_target.

    :param vert: The vertex to be removed.
    :type vert: 'bmesh.types.BMVert'
    :param vert_target: The vertex to use.
    :type vert_target: 'bmesh.types.BMVert'
    """
    pass


def _symbolic_product_helper():
    """Use SymPy to generate the 3D products for diffusion_stencil_3d."""
    from sympy import symbols, Matrix
    D11, D12, D13, D21, D22, D23, D31, D32, D33 = symbols(
        'D11, D12, D13, D21, D22, D23, D31, D32, D33')
    D = Matrix([[D11, D12, D13], [D21, D22, D23], [D31, D32, D33]])
    grad = Matrix([['dx', 'dy', 'dz']]).T
    div = grad.T
    a = div * D * grad
    print(a[0])


def get_temp(hwmon, id):
    """Return the temperature value for the sensor id."""
    sensors = hwmon.Sensor(['Name', 'Parent', 'Value', 'Identifier'],
        SensorType='Temperature')
    for sensor in sensors:
        if sensor.Identifier == id:
            return sensor.Value


def clonebundles():
    """Obtains the clone bundles manifest for the repo.

        Returns the manifest as unparsed bytes.
        """


def generate_headline(text):
    """
    Genera la cabecer para los titulos formateados en ``.rst``

    :param str text: texto para el que generar la cabecera
    :return: cabecera para el texto
    :rtype: str

    .. code-block:: python

        >> generate_headline('Welcome')
        '==========='

    """
    return '=' * (len(text) + 6)


def get_config_from_options(**options):
    """Get config file fragment reflecting command-line options."""
    data = []
    data.append('[supervisord]\n')
    if options.get('daemonize', False):
        data.append('nodaemon=false\n')
    else:
        data.append('nodaemon=true\n')
    if options.get('pidfile', None):
        data.append('pidfile=%s\n' % (options['pidfile'],))
    if options.get('logfile', None):
        data.append('logfile=%s\n' % (options['logfile'],))
    for progname in (options.get('launch', None) or []):
        data.append('[program:%s]\nautostart=true\n' % (progname,))
    for progname in (options.get('nolaunch', None) or []):
        data.append('[program:%s]\nautostart=false\n' % (progname,))
    for progname in (options.get('include', None) or []):
        data.append('[program:%s]\nexclude=false\n' % (progname,))
    for progname in (options.get('exclude', None) or []):
        data.append('[program:%s]\nexclude=true\n' % (progname,))
    if options.get('autoreload', None):
        data.append('[program:autoreload]\nexclude=false\nautostart=true\n')
        data.append('[program:__defaults__]\nautoreload=false\n')
        for progname in options['autoreload']:
            data.append('[program:%s]\nautoreload=true\n' % (progname,))
    if options.get('noreload', False):
        data.append('[program:autoreload]\nexclude=true\n')
    return ''.join(data)


def p_statement(p):
    """statement : select_statement
        | show_tables_statement
        | create_table_statement
        | create_database_statement
        | show_databases_statement
        | use_database_statement
        | commit_statement
        | set_statement
        | insert_statement
        | delete_statement
        | drop_database_statement
        | drop_table_statement
        | desc_table_statement
        | update_table_statement
        | wait_statement"""
    p[1].success = True
    p[0] = p[1]


@classmethod
def flatten(cls, seq):
    """Return seq so that none of the elements are of type `cls`. This is
        the vanilla routine that will be used if a class derived from AssocOp
        does not define its own flatten routine."""
    new_seq = []
    while seq:
        o = seq.pop()
        if o.__class__ is cls:
            seq.extend(o.args)
        else:
            new_seq.append(o)
    new_seq.reverse()
    return [], new_seq, None


@classmethod
def id_not_found(cls, val):
    """
        Create an instance of this class set to the ``id_not_found`` tag with
        value ``val``.

        :param str val:
        :rtype: GroupsGetInfoItem
        """
    return cls('id_not_found', val)


def safeGetAttribute(node, attribute):
    """Get an attribute froma node, but return None if it does not exist.
    """
    if not node.hasAttribute(attribute):
        return None
    else:
        return node.getAttribute(attribute)


def menu_item(route_name, ctx, req, label=None):
    """Factory function for a menu item specified by route name.

    :return: A pair (URL, label) to create a menu item.
    """
    return req.route_url(route_name), label or req.translate(route_name.
        capitalize())


def _as_range_str(iterable):
    """
    Return a string representing the range as a string span.
    """
    l = list(iterable)
    if len(l) > 1:
        return '{0}-{1}'.format(l[0], l[-1])
    return '{0}'.format(l[0])


def delete():
    """Remove selected bones from the armature

    """
    pass


def find_fully_unique_columns(df):
    """
    Check if a dataframe contains a fully unique column (SUBJ_ID candidate).

    :param df: `pd.DataFrame`
    :return: list of names of unique columns
    """
    unique_cols = df.apply(lambda x: len(x.unique()) == len(df))
    return list(df.columns[unique_cols])


def _entity_corresponds_to_use_path_impl(given, entity):
    """determine if 'given' corresponds to 'entity', in terms
    of a path of loader options where a mapped attribute is taken to
    be a member of a parent entity.

    e.g.::

        someoption(A).someoption(A.b)  # -> fn(A, A) -> True
        someoption(A).someoption(C.d)  # -> fn(A, C) -> False

        a1 = aliased(A)
        someoption(a1).someoption(A.b) # -> fn(a1, A) -> False
        someoption(a1).someoption(a1.b) # -> fn(a1, a1) -> True

        wp = with_polymorphic(A, [A1, A2])
        someoption(wp).someoption(A1.foo)  # -> fn(wp, A1) -> False
        someoption(wp).someoption(wp.A1.foo)  # -> fn(wp, wp.A1) -> True

    """
    if given.is_aliased_class:
        return entity.is_aliased_class and not entity._use_mapper_path and (
            given is entity or given in entity._with_polymorphic_entities)
    elif not entity.is_aliased_class:
        return given.common_parent(entity.mapper)
    else:
        return (entity._use_mapper_path and given in entity.
            with_polymorphic_mappers)


def _transform_iall(degree, bias, XP, X, multiply, final):
    """Computes the polynomial features"""
    if bias:
        XP[:, (0)] = 1
        pos = 1
    else:
        pos = 0
    n = X.shape[1]
    for d in range(0, degree):
        if d == 0:
            XP[:, pos:pos + n] = X
            index = list(range(pos, pos + n))
            pos += n
            index.append(pos)
        else:
            new_index = []
            end = index[-1]
            for i in range(0, n):
                a = index[i]
                new_index.append(pos)
                new_pos = pos + end - a
                multiply(XP[:, a:end], X[:, i:i + 1], XP[:, pos:new_pos])
                pos = new_pos
            new_index.append(pos)
            index = new_index
    return final(XP)


def p_kdelimiter(p):
    """kdelimiter : KDELIMITER
                    | "["
                    | "]" """
    p[0] = p[1]


def serie(z):
    """Puts impedances in serie (yep, simple summation).

    Args:
        z: List of impedances (either complex or real or a combination of both).

    Returns:
        Serie impedance.
    """
    return sum(z)


def _create_default_foo_integral(ir, integral_type):
    """Generate code for create_default_<foo>_integral."""
    ret = format['return']
    classname = ir['create_default_%s_integral' % integral_type]
    if classname is None:
        return ret(0)
    else:
        create = format['create foo']
        return ret(create(classname))


def register_certificate(certificatePem=None, caCertificatePem=None,
    setAsActive=None, status=None):
    """
    Registers a device certificate with AWS IoT. If you have more than one CA certificate that has the same subject field, you must specify the CA certificate that was used to sign the device certificate being registered.
    See also: AWS API Documentation

    :example: response = client.register_certificate(
        certificatePem='string',
        caCertificatePem='string',
        setAsActive=True|False,
        status='ACTIVE'|'INACTIVE'|'REVOKED'|'PENDING_TRANSFER'|'REGISTER_INACTIVE'|'PENDING_ACTIVATION'
    )

    :type certificatePem: string
    :param certificatePem: [REQUIRED]
            The certificate data, in PEM format.

    :type caCertificatePem: string
    :param caCertificatePem: The CA certificate used to sign the device certificate being registered.

    :type setAsActive: boolean
    :param setAsActive: A boolean value that specifies if the CA certificate is set to active.

    :type status: string
    :param status:

    :rtype: dict
    :return: {
        'certificateArn': 'string',
        'certificateId': 'string'
    }

    """
    pass


@classmethod
def get_activity_storage(cls):
    """
        Returns an instance of the activity storage
        """
    options = {}
    options['serializer_class'] = cls.activity_serializer
    options['activity_class'] = cls.activity_class
    if cls.activity_storage_class is not None:
        activity_storage = cls.activity_storage_class(**options)
        return activity_storage


def Reset():
    """Reset global state.  Used by unit tests that end up using
    SConsign multiple times to get a clean slate for each test."""
    global sig_files, DB_sync_list
    sig_files = []
    DB_sync_list = []


def as_bytes(value):
    """
    Returns value as bytes
    """
    if not isinstance(value, bytes):
        return value.encode('UTF-8')
    return value


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


@classmethod
def install(cls, plugin_path, force=False):
    """Installs the package, and creates data in API service

        :param str plugin_path: Name of plugin file
        :param bool force: Updates existent plugin even if it is not updatable
        :return: Plugins information
        :rtype: dict
        """
    plugin = cls.make_obj_by_file(plugin_path)
    name = plugin.name_from_file(plugin_path)
    version = plugin.version_from_file(plugin_path)
    plugin.install(plugin_path, force=force)
    response = cls.register(name, version, force=force)
    return response


def add_loadgraph_args(parser):
    """Common loadgraph argument."""
    parser.add_argument('-l', '--loadgraph', metavar='filename', default=
        None, help='load a precomputed k-mer graph from disk')


@property
def name(cls):
    """
        The name of this model class--equivalent to ``cls.__name__``.

        This attribute is provided for symmetry with the `Model.name` attribute
        of model instances.
        """
    return cls.__name__


def get_indices(w1, w2, header):
    """Returns wavelength layer indices for two given wavelengths in Angstrom.

    Args:
        w1 (float): Lower wavelength, in Angstrom.
        w2 (float): Upper wavelength, in Angstrom.
        header (astropy.io.fits.Header): FITS header for this data cube.

    Returns:
        int tuple: The lower and upper wavelength indices for this range.

    Example:

        To find the indices corresponding to the wavelength range 4100-4200A:

        >>> from astropy.io import fits
        >>> from cwitools import cubes
        >>> mydata,header = fits.getdata("mydata.fits",header=True)
        >>> a,b = cubes.get_band(4100,4200,header)
        >>> mydata_trimmed = mydata[a:b]

    """
    w0, dw, p0 = header['CRVAL3'], header['CD3_3'], header['CRPIX3']
    w0 -= p0 * dw
    return int((w1 - w0) / dw), int((w2 - w0) / dw)


def flag_generator():
    """ A generator which yields success bit flags.

    This should be used when creating flag values for a subclass of
    Object in order to not trample on superclass flags.

    """
    flag = 1
    while True:
        yield flag
        flag <<= 1


def get_all(isamAppliance, check_mode=False, force=False):
    """
    Retrieving all static routes
    """
    return isamAppliance.invoke_get('Retrieving all static routes',
        '/net/routes')


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.nn.ConditionalKNNModel'


def cleanup():
    """Intended to be used by tests to recreate all RPC related objects."""
    global _TRANSPORT
    global _ENGINE_CLIENT
    _TRANSPORT = None
    _ENGINE_CLIENT = None


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def delitem(D, key):
    """delitem(x, key) <==> del x[key]"""
    del D[key]


def get_block_devices(bdms=None):
    """
    @type bdms: list
    """
    ret = ''
    if bdms:
        for bdm in bdms:
            ret += '{0}\n'.format(bdm.get('DeviceName', '-'))
            ebs = bdm.get('Ebs')
            if ebs:
                ret += ' Status: {0}\n'.format(ebs.get('Status', '-'))
                ret += ' Snapshot Id: {0}\n'.format(ebs.get('SnapshotId', '-'))
                ret += ' Volume Size: {0}\n'.format(ebs.get('VolumeSize', '-'))
                ret += ' Volume Type: {0}\n'.format(ebs.get('VolumeType', '-'))
                ret += ' Encrypted: {0}\n'.format(str(ebs.get('Encrypted',
                    '-')))
                ret += ' Delete on Termination: {0}\n'.format(ebs.get(
                    'DeleteOnTermination', '-'))
                ret += ' Attach Time: {0}\n'.format(str(ebs.get(
                    'AttachTime', '-')))
        return ret.rstrip()
    else:
        return ret


def drawSensor(sensor, SYSSIZE, ax):
    """Draw the sensor coordinates

    Parameters
    ----------
    sensor: Sensor
        Sensor to draw
    SYSSIZE : float
        Size of the display system
    ax : [pyplot]
        pyplot canvas to draw on

    """
    from magpylib._lib.mathLib import angleAxisRotation
    M = angleAxisRotation([1, 0, 0], sensor.angle, sensor.axis)
    P = sensor.position
    ax.quiver(P[0], P[1], P[2], M[0], M[1], M[2], normalize=True, length=
        SYSSIZE / 4, color='r')
    ax.text(M[0] + P[0], M[1] + P[1], M[2] + P[2], 'x', None)
    M = angleAxisRotation([0, 1, 0], sensor.angle, sensor.axis)
    ax.quiver(P[0], P[1], P[2], M[0], M[1], M[2], normalize=True, length=
        SYSSIZE / 4, color='g')
    ax.text(M[0] + P[0], M[1] + P[1], M[2] + P[2], 'y', None)
    M = angleAxisRotation([0, 0, 1], sensor.angle, sensor.axis)
    ax.quiver(P[0], P[1], P[2], M[0], M[1], M[2], normalize=True, length=
        SYSSIZE / 4, color='b')
    ax.text(M[0] + P[0], M[1] + P[1], M[2] + P[2], 'z', None)


def __new__(cls, major, minor=0, micro=0, modifier='release'):
    """
        Create new instance of `VersionInfo(major, minor, micro, modifier)`.
        """
    assert isinstance(major, int)
    assert isinstance(minor, int)
    assert isinstance(micro, int)
    assert isinstance(modifier, str)
    return tuple.__new__(cls, (major, minor, micro, modifier))


def load_h5py(finder, module):
    """h5py module has a number of implicit imports"""
    finder.IncludeModule('h5py.defs')
    finder.IncludeModule('h5py.utils')
    finder.IncludeModule('h5py._proxy')
    try:
        import h5py.api_gen
        finder.IncludeModule('h5py.api_gen')
    except ImportError:
        pass
    finder.IncludeModule('h5py._errors')
    finder.IncludeModule('h5py.h5ac')


def tree_post_save_handler(sender, instance, **kwargs):
    """
    Clobber the _ct_inventory attribute of this object and all sub-objects
    on save.
    """
    instance.get_descendants(include_self=True).update(_ct_inventory=None)


def _audience_condition_deserializer(obj_dict):
    """ Deserializer defining how dict objects need to be decoded for audience conditions.

  Args:
    obj_dict: Dict representing one audience condition.

  Returns:
    List consisting of condition key with corresponding value, type and match.
  """
    return [obj_dict.get('name'), obj_dict.get('value'), obj_dict.get(
        'type'), obj_dict.get('match')]


def list_applications(Limit=None, ExclusiveStartApplicationName=None):
    """
    Returns a list of Amazon Kinesis Analytics applications in your account. For each application, the response includes the application name, Amazon Resource Name (ARN), and status. If the response returns the HasMoreApplications value as true, you can send another request by adding the ExclusiveStartApplicationName in the request body, and set the value of this to the last application name from the previous response.
    If you want detailed information about a specific application, use  DescribeApplication .
    This operation requires permissions to perform the kinesisanalytics:ListApplications action.
    See also: AWS API Documentation

    :example: response = client.list_applications(
        Limit=123,
        ExclusiveStartApplicationName='string'
    )

    :type Limit: integer
    :param Limit: Maximum number of applications to list.

    :type ExclusiveStartApplicationName: string
    :param ExclusiveStartApplicationName: Name of the application to start the list with. When using pagination to retrieve the list, you don't need to specify this parameter in the first request. However, in subsequent requests, you add the last application name from the previous response to get the next page of applications.

    :rtype: dict
    :return: {
        'ApplicationSummaries': [
            {
                'ApplicationName': 'string',
                'ApplicationARN': 'string',
                'ApplicationStatus': 'DELETING'|'STARTING'|'STOPPING'|'READY'|'RUNNING'|'UPDATING'
            },
        ],
        'HasMoreApplications': True|False
    }

    """
    pass


def smooth_ts(ts, win=5):
    """
    Underestimate high flows - Overestimate low flows.

    Time series is smoothed by rolling average. Maxima decrease and minima
    decrease.

    Parameters
    ----------
    ts : dataframe
        Time series

    win : int, optional
        Size of window used to apply rolling mean. The default is 5 days.

    Returns
    ----------
    smoothed_ts : series
        Smoothed time series
    """
    smoothed_ts = ts.rolling(window=win).mean()
    smoothed_ts.fillna(method='bfill', inplace=True)
    return smoothed_ts


def stringifyOptionValue(value):
    """
    Convert option value from in-memory representation to a suitable string.

    In particular, boolean values are converted to '0' or '1'.
    """
    if value is True:
        return '1'
    elif value is False:
        return '0'
    else:
        return str(value)


def trap_e_back(w, t, ratio):
    """Return distance centroid–back for trapezoid cross-sections.

    e_back_trap = (w+2W)/(w+W) * t/3
    Source: Lueger 1904

    Args:
        w: width
        t: thickness
        ratio: the ratio of back width to belly width

    Returns:
        A scalar.
    """
    sw = ratio * w
    return (sw + 2 * w) / (sw + w) * t / 3


def ndistinct(data, column):
    """Return number of distinct elements in data[column]."""
    return len(data[column].unique())


def compute_offset_to_first_complete_codon(
    offset_to_first_complete_reference_codon, n_trimmed_from_reference_sequence
    ):
    """
    Once we've aligned the variant sequence to the ReferenceContext, we need
    to transfer reading frame from the reference transcripts to the variant
    sequences.

    Parameters
    ----------
    offset_to_first_complete_reference_codon : int

    n_trimmed_from_reference_sequence : int

    Returns an offset into the variant sequence that starts from a complete
    codon.
    """
    if (n_trimmed_from_reference_sequence <=
        offset_to_first_complete_reference_codon):
        return (offset_to_first_complete_reference_codon -
            n_trimmed_from_reference_sequence)
    else:
        n_nucleotides_trimmed_after_first_codon = (
            n_trimmed_from_reference_sequence -
            offset_to_first_complete_reference_codon)
        frame = n_nucleotides_trimmed_after_first_codon % 3
        return (3 - frame) % 3


def properties_remove(data_path: str='', property: str=''):
    """Internal use (edit a property data_path)

    :param data_path: Property Edit, Property data_path edit
    :type data_path: str
    :param property: Property Name, Property name edit
    :type property: str
    """
    pass


def crop(im, r, c, sz_h, sz_w):
    """
    crop image into a square of size sz,
    """
    return im[r:r + sz_h, c:c + sz_w]


def merge_dicts(d1, d2, merge):
    """
    Merges two dictionaries, non-destructively, combining
    values on duplicate keys as defined by the final *merge*
    argument.

    This function is a modified version of an answer to a
    `Stack Overflow question <http://stackoverflow.com/questions/38987/>`_
    by rcreswick.
    """
    result = dict(d1)
    for k, v in d2.items():
        result[k] = merge(result[k], v) if k in result else v
    return result


def get_templatename(f):
    """
    Assess from hoc file the templatename being specified within

    Arguments
    ---------
    f : file, mode 'r'

    Returns
    -------
    templatename : str

    """
    templatename = None
    f = open('template.hoc', 'r')
    for line in f.readlines():
        if 'begintemplate' in line.split():
            templatename = line.split()[-1]
            continue
    return templatename


def izip_fill(*iterables, **kw):
    """Like itertools.izip but use a default value for the missing elements
       in short lists rather than stopping at the end of the shortest list.

       ``*iterables`` are the iterables to zip.
       ``default`` is the default value (default ``None``, must be a keyword
       arg.
    """
    iterables = map(iter, iterables)
    default = kw.pop('default', None)
    if kw:
        raise TypeError('unrecognized keyword arguments')
    columns = len(iterables)
    columns_range = range(columns)
    while True:
        found_data = False
        row = [None] * columns
        for i in columns_range:
            try:
                row[i] = iterables[i].next()
                found_data = True
            except StopIteration:
                row[i] = default
        if not found_data:
            break
        yield tuple(row)


def _deserialize_object(value):
    """
    Return a original value.

    :return: object.
    """
    return value


def translate_name(name):
    """Translate feature name."""
    return name.translate(str.maketrans('', '', " '"))


def check_between(v_min, v_max, **params):
    """Checks parameters are in a specified range
    Parameters
    ----------
    v_min : float, minimum allowed value (inclusive)
    v_max : float, maximum allowed value (inclusive)
    params : object
        Named arguments, parameters to be checked
    Raises
    ------
    ValueError : unacceptable choice of parameters
    """
    for p in params:
        if params[p] < v_min or params[p] > v_max:
            raise ValueError('Expected {} between {} and {}, got {}'.format
                (p, v_min, v_max, params[p]))


def get_time_from_args(args, prefix, required=True):
    """
    Create an astropy.time.Time value from argument crated via time_parser.

    :param args: The argument parser result
    :param prefix: the argument used.
    :param required:  Was this argument required?
    :return: An astropy.time.Time value
    """
    from astropy.time import Time
    prefix = prefix.replace('-', '_', -1)
    val_name = prefix
    val2_name = prefix + '_val2'
    format_name = prefix + '_format'
    scale_name = prefix + '_scale'
    val = getattr(args, prefix)
    val2 = getattr(args, val2_name)
    format_ = getattr(args, format_name)
    scale = getattr(args, scale_name)
    try:
        val = float(val)
    except:
        pass
    if required and not val:
        raise SystemExit('missing argument %s' % val_name)
    if (val2 or format_) and not val:
        raise SystemExit('%s or %s cannot be used without %s' % (val2_name,
            format_name, val_name))
    if val:
        return Time(val, val2, format=format_, scale=scale)
    return None


def validate_kwargs(kwargs, allowed_kwargs, error_message=
    'Keyword argument not understood:'):
    """Checks that all keyword arguments are in the set of allowed keys."""
    for kwarg in kwargs:
        if kwarg not in allowed_kwargs:
            raise TypeError(error_message, kwarg)


def partition_to_color(partitions):
    """
    Creates a dictionary with for every item in partition for every partition
    in partitions the index of partition in partitions.

    Parameters
    ----------
    partitions: collections.abc.Sequence[collections.abc.Iterable]
        As returned by :func:`make_partitions`.

    Returns
    -------
    dict[collections.abc.Hashable, int]
    """
    colors = dict()
    for color, keys in enumerate(partitions):
        for key in keys:
            colors[key] = color
    return colors


@classmethod
def has_team_selective_sync(cls, val):
    """
        Create an instance of this class set to the ``has_team_selective_sync``
        tag with value ``val``.

        :param HasTeamSelectiveSyncValue val:
        :rtype: FeatureValue
        """
    return cls('has_team_selective_sync', val)


@staticmethod
def _get_title(m_data: dict) ->str:
    """Get title of manga from manga_data"""
    return m_data['manga']['title']


def persist_rmas_user_ethics_user_link(rmas_user_id, ethics_user_id):
    """
        This function persists the link between the unique identifier that is used to identify a user
        in RMAS, to the unique identifier that represents the same user in the OpenEthics system.

        The persistance is carried out using a MongoDB database (oe_rmas_adapter), and the 'people_links'
        collection
    """


def number(num):
    """Валидатор для объектов, приводимых к float"""
    return float(num)


def applyChanges(context, form_fields, data, adapters=None):
    """Apply form data to an object

        For each form field that has data, the data are applied to the
        context argument.  The context is adapter to the schema for
        each field.  If an adapters mapping is passed, it will be used
        as a cache.  Typically, it would be a mapping object populated
        when setUpEditWidgets was called.

        """


def fqx_calc_u1_u2_s1_s2(mul_f, x1_t, y1_t, z1_t, x2_t, y2_t, z2_t):
    """x, y, z inputs of type fq2, returning tuple of fq2 tuples"""
    u1 = mul_f(mul_f(x1_t, z2_t), z2_t)
    u2 = mul_f(mul_f(x2_t, z1_t), z1_t)
    s1 = mul_f(mul_f(mul_f(y1_t, z2_t), z2_t), z2_t)
    s2 = mul_f(mul_f(mul_f(y2_t, z1_t), z1_t), z1_t)
    return u1, u2, s1, s2


def is_iterable(obj):
    """Return if instance is iterable."""
    return isinstance(obj, str) or getattr(obj, '__iter__', False)


def order_case_queryset(cases, field, asc=False):
    """
    Annotate the TestCase queryset
    by calling order_by on it.
    """
    orderable_fields = ('id', 'summary', 'author__username',
        'default_tester__username', 'priority', 'is_automated',
        'category__name', 'case_status', 'create_date')
    if field in orderable_fields:
        order_by = field
        if not asc:
            order_by = '-%s' % order_by
        cases = cases.order_by(order_by)
    return cases


def colors(theme=None):
    """
Return dictionary of colors.

.. code-block:: python

  {
    'selection' : '...',
  }

:options:

  **theme** ([``'dark'``] | ``<str>``)
    Select color-theme.
  """
    if theme == 'dark':
        return {'selection': '1;32;40'}
    return {'selection': ''}


def analyze_result(typ, indicators, indicator_filter):
    """Check response from API"""
    no_of_indicators = len(indicators[typ])
    if no_of_indicators == 0:
        if indicator_filter:
            msg = 'check your filter.'
        else:
            msg = 'are there any?'
        raise SystemExit('No {} found - {}'.format(typ, msg))
    elif indicator_filter:
        msg = 'Found {} {} with filter {}'.format(no_of_indicators, typ,
            indicator_filter)
    else:
        msg = 'Found {} {}'.format(no_of_indicators, typ)
    return msg


def _msg(e):
    """Generate a user friendly error message."""
    return e.message


def describe_pattern(pattern):
    """
    Format the URL pattern for display in warning messages.
    """
    description = "'{}'".format(pattern.regex.pattern)
    if getattr(pattern, 'name', False):
        description += " [name='{}']".format(pattern.name)
    return description


def announce(zelf, txt):
    """ announce on all fleet bots. """
    from midz import kernel
    kernel.announce(txt)


def normRect(rect):
    """Normalize the rectangle so that the following holds:
        xMin <= xMax and yMin <= yMax
    """
    xMin, yMin, xMax, yMax = rect
    return min(xMin, xMax), min(yMin, yMax), max(xMin, xMax), max(yMin, yMax)


def prepare(base_class, engine):
    """
    Reflect base class to current database engine.
    """
    base_class.prepare(engine, reflect=True)


def str2bool(string):
    """It returns True, False or None"""
    if not string:
        return None
    if isinstance(string, (str,)):
        string = string.lower()
        options = ['none', 'null', 'nil']
        if string in options:
            return None
        options = ['false', 'f', 'no', '0']
        return not string in options
    return string


def reset_globals():
    """For async unit test consistency."""
    global _SERVICE_AUTH
    _SERVICE_AUTH = None


def connection_fd():
    """Returns current request file descriptor.

    :rtype: int
    """


@staticmethod
def __toVariant(name, priority):
    """A tab stores its name and priority"""
    if priority is None:
        return ':' + name
    return str(priority) + ':' + name


def create_point(fields, satellite, telemetry, demoddata, version):
    """Create a decoded data point in JSON format that is influxdb compatible

    :returns: a JSON formatted time series data point
    """
    point = [{'time': demoddata.timestamp.strftime('%Y-%m-%dT%H:%M:%SZ'),
        'measurement': satellite.norad_cat_id, 'tags': {'satellite':
        satellite.name, 'decoder': telemetry.decoder, 'station': demoddata.
        station, 'observer': demoddata.observer, 'source': demoddata.
        app_source, 'version': version}, 'fields': fields}]
    return point


@classmethod
def _getters(cls):
    """Return a mapping from field names to getter functions."""
    return {}


def getFullMessage(msgid):
    """Get the message data and meta data as a nice dictionary. More
        advanced implementation might choose to return an object with
        the data, but the object should then implement `IEnumerableMapping`.

        An exception is raised if the message id is not found.
        """


def get_colourstate_nbr(visibility, cloudbase):
    """Returns the colour state for a given cloud base (in ft) and visibility (in metres). A single digit is also
    returned alongside the colour state to assist in colour state comparisons where 7=BLU, 6=WHT, 5=GRN, 4=YLO1, 3=YLO2,
    2=AMB, 1=RED
    :param cloudbase:
    :param visibility:
    """
    colourstate_nbr = 1
    colourstate = 'RED'
    if visibility < 800 or cloudbase < 200:
        colourstate_nbr = 1
        colourstate = 'RED'
    elif visibility < 1600 or cloudbase < 300:
        colourstate_nbr = 2
        colourstate = 'AMB'
    elif visibility < 2500 or cloudbase < 500:
        colourstate_nbr = 3
        colourstate = 'YLO2'
    elif visibility < 3700 or cloudbase < 700:
        colourstate_nbr = 4
        colourstate = 'YLO1'
    elif visibility < 5000 or cloudbase < 1500:
        colourstate_nbr = 5
        colourstate = 'GRN'
    elif visibility < 8000 or cloudbase < 2500:
        colourstate_nbr = 6
        colourstate = 'WHT'
    elif visibility > 7999 and cloudbase > 2499:
        colourstate_nbr = 7
        colourstate = 'BLU'
    return colourstate_nbr, colourstate


def decrypt_mock_datakey(data_key):
    """
    Mock decryption meant to be used for testing or development. Simply returns
    the provided data_key.
    """
    return data_key


@classmethod
def error_payload(cls, message, code, id_):
    """JSON v2 error payload.  result is not present."""
    return {'jsonrpc': '2.0', 'id': id_, 'error': {'message': message,
        'code': code}}


@staticmethod
def ndim(tensor):
    """Return the number of dimensions of a tensor"""
    raise NotImplementedError


def matchTypes(accept_types, have_types):
    """Given the result of parsing an Accept: header, and the
    available MIME types, return the acceptable types with their
    quality markdowns.

    For example:

    >>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5')
    >>> matchTypes(acceptable, ['text/plain', 'text/html', 'image/jpeg'])
    [('text/html', 1.0), ('text/plain', 0.5)]

    Type signature: ([(str, str, float)], [str]) -> [(str, float)]
    """
    if not accept_types:
        default = 1
    else:
        default = 0
    match_main = {}
    match_sub = {}
    for main, sub, q in accept_types:
        if main == '*':
            default = max(default, q)
            continue
        elif sub == '*':
            match_main[main] = max(match_main.get(main, 0), q)
        else:
            match_sub[main, sub] = max(match_sub.get((main, sub), 0), q)
    accepted_list = []
    order_maintainer = 0
    for mtype in have_types:
        main, sub = mtype.split('/')
        if (main, sub) in match_sub:
            q = match_sub[main, sub]
        else:
            q = match_main.get(main, default)
        if q:
            accepted_list.append((1 - q, order_maintainer, q, mtype))
            order_maintainer += 1
    accepted_list.sort()
    return [(mtype, q) for _, _, q, mtype in accepted_list]


def conv(problem):
    """Convert problem to array."""
    s = []
    if problem.find(',') == -1:
        for i in problem:
            if i.isdigit():
                s = s + [int(i)]
            else:
                s = s + [0]
        if len(s) != 81:
            return 'Error in input.', True
    else:
        for line in problem.split(','):
            if len(line) == 9:
                for i in line:
                    if i.isdigit():
                        s = s + [int(i)]
                    else:
                        s = s + [0]
            else:
                return 'Error in input: ' + line, True
    if len(s) == 81:
        return s, False
    else:
        return 'Error in input', True


def rename_app_parameters(app, model):
    """Rename all parameters for a given app."""
    qset = model.objects.filter(name__startswith=app[0])
    for param in qset:
        param.name = param.name.replace('{}.'.format(app[0]), '{}.'.format(
            app[1]))
        param.save()


@classmethod
def get_type_name(cls, reference_IN, *args, **kwargs):
    """
        Accepts a reference to something.  Calls type() on the reference, then
            gets the __name__ of the type.  This is as much a reminder to me as
            it is a genuinely useful method.
        """
    value_OUT = ''
    reference_type = None
    type_name = ''
    reference_type = type(reference_IN)
    type_name = reference_type.__name__
    value_OUT = type_name
    return value_OUT


@classmethod
def _from_dict(cls, _dict):
    """Initialize a SourceOptionsFolder object from a json dictionary."""
    args = {}
    if 'owner_user_id' in _dict:
        args['owner_user_id'] = _dict.get('owner_user_id')
    else:
        raise ValueError(
            "Required property 'owner_user_id' not present in SourceOptionsFolder JSON"
            )
    if 'folder_id' in _dict:
        args['folder_id'] = _dict.get('folder_id')
    else:
        raise ValueError(
            "Required property 'folder_id' not present in SourceOptionsFolder JSON"
            )
    if 'limit' in _dict:
        args['limit'] = _dict.get('limit')
    return cls(**args)


def _visit_or_none(node, attr, visitor, parent, visit='visit', **kws):
    """If the given node has an attribute, visits the attribute, and
    otherwise returns None.

    """
    value = getattr(node, attr, None)
    if value:
        return getattr(visitor, visit)(value, parent, **kws)
    return None


def get_events_restricted(phylo, opt):
    """
    Infer gain/loss where events are restricted to target gain and query loss.
    """
    in_mrca = phylo.get_label_at_root()
    orth_str = 'ambiguous'
    if in_mrca == 0:
        orth_str = 'gain_{}'.format(opt.qname)
    elif in_mrca == 1:
        orth_str = 'loss_{}'.format(opt.tname)
    return orth_str


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming
        """
    return True


@classmethod
def from_file(cls, fname, delimiter='\t', encoding='utf-8'):
    """Create new instance from CSV file *fname*"""
    d = cls()
    with open(fname, 'rb') as fh:
        for line in fh:
            key, score = cls.from_record(line.decode(encoding), delimiter)
            d[key] = score
    return d


@staticmethod
def _keymangle(key):
    """Converts the given key to lowercase."""
    if isinstance(key, str):
        return key.lower()
    return key


def call_aside(f, *args, **kwargs):
    """
    Call a function for its side effect after initialization.

    >>> @call_aside
    ... def func(): print("called")
    called
    >>> func()
    called

    Use functools.partial to pass parameters to the initial call

    >>> @functools.partial(call_aside, name='bingo')
    ... def func(name): print("called with", name)
    called with bingo
    """
    f(*args, **kwargs)
    return f


def overlap(t1, t2):
    """Checks if one interval contains any overlap with another interval.

    Keyword arguments:
    t1 -- First tuple.
    t2 -- Second tuple.

    Returns:
    Returns -1 if i1 is before i2; 1 if i1 is after i2; and 0 if there is any overlap.
    """
    if t1[1] <= t2[0]:
        return -1
    if t2[1] <= t1[0]:
        return 1
    return 0


@staticmethod
def get(_key):
    """Always return None"""
    return None


def broadcast_minus(lhs=None, rhs=None, name=None, attr=None, out=None, **
    kwargs):
    """Returns element-wise difference of the input arrays with broadcasting.

    `broadcast_minus` is an alias to the function `broadcast_sub`.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_sub(x, y) = [[ 1.,  1.,  1.],
                              [ 0.,  0.,  0.]]

       broadcast_minus(x, y) = [[ 1.,  1.,  1.],
                                [ 0.,  0.,  0.]]

    Supported sparse operations:

       broadcast_sub/minus(csr, dense(1D)) = dense
       broadcast_sub/minus(dense(1D), csr) = dense

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L106

    Parameters
    ----------
    lhs : Symbol
        First input to the function
    rhs : Symbol
        Second input to the function

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def view_ndof():
    """Use a 3D mouse device to pan/zoom the view

    """
    pass


def _get_trading_day_end_time(trading_day):
    """给定交易日, 获得交易日结束时间"""
    return trading_day + 64799999999999


@classmethod
def delete_table(cls):
    """
        Delete the table for this model
        """
    return cls._get_connection().delete_table()