@classmethod
def from_dict(cls, entries, **kwargs):
    """
        Create Catalog from the given set of entries

        Parameters
        ----------
        entries : dict-like
            A mapping of name:entry which supports dict-like functionality,
            e.g., is derived from ``collections.abc.Mapping``.
        kwargs : passed on the constructor
            Things like metadata, name; see ``__init__``.

        Returns
        -------
        Catalog instance
        """
    from dask.base import tokenize
    cat = cls(**kwargs)
    cat._entries = entries
    cat._tok = tokenize(kwargs, entries)
    return cat


def zerocopy_to_dlpack(input):
    """Create a dlpack tensor that shares the input memory.

    Parameters
    ----------
    input : Tensor
        The input tensor

    Returns
    -------
    dlpack capsule
        A dlpack capsule that can be used by other framework.
    """
    pass


def GetNumberOfQubits(cirq_circuit):
    """
    Determine the number of qubits from an unknown Cirq circuit
    :param cirq_circuit:
    :return:
    """
    known_qubits = {}
    size = 0
    for operation in cirq_circuit:
        for qub in operation.qubits:
            if not qub in known_qubits:
                size += 1
                known_qubits[qub] = size
    return size


@classmethod
def type(cls) ->str:
    """Get the type of this adapter. Types must be class-unique and
        consistent.

        :return: The type name
        :rtype: str
        """
    return cls.ConnectionManager.TYPE


def filter_value_to_python(value):
    """
    Turn the string `value` into a python object.
    >>> filter_value_to_python([1, 2, 3])
    [1, 2, 3]
    >>> filter_value_to_python(123)
    123
    >>> filter_value_to_python('true')
    True
    >>> filter_value_to_python('False')
    False
    >>> filter_value_to_python('null')
    >>> filter_value_to_python('None')
    >>> filter_value_to_python('Ø')
    u'O'
    """
    if isinstance(value, list):
        return value
    if isinstance(value, int):
        return value
    if value in ['true', 'True', True]:
        value = True
    elif value in ['false', 'False', False]:
        value = False
    elif value in ('null', 'none', 'None', None):
        value = None
    return value


def cross(v1, v2):
    """
    Return the cross product between two vectors.
    """
    x1, y1 = v1
    x2, y2 = v2
    return x1 * y2 - x2 * y1


def get_eqtype(dev):
    """ It extracts the eqtype from a device name like domain/family/eqtype-serial"""
    try:
        eq = str(dev).split('/')[-1].split('-', 1)[0].upper()
    except:
        eq = ''
    return eq


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


def preprocess_for_cse(expr, optimizations):
    """ Preprocess an expression to optimize for common subexpression
    elimination.

    Parameters
    ----------
    expr : sympy expression
        The target expression to optimize.
    optimizations : list of (callable, callable) pairs
        The (preprocessor, postprocessor) pairs.

    Returns
    -------
    expr : sympy expression
        The transformed expression.
    """
    for pre, post in optimizations:
        if pre is not None:
            expr = pre(expr)
    return expr


def default_can_compose_permission(view, request, template_name):
    """
    Default global permission check.
    """
    return request.user and request.user.is_authenticated and (request.user
        .is_staff or request.user.is_superuser)


@classmethod
def _order(cls, x):
    """Return an integer value for character x"""
    if x == '~':
        return -1
    if cls.re_digit.match(x):
        return int(x) + 1
    if cls.re_alpha.match(x):
        return ord(x)
    return ord(x) + 256


@classmethod
def _from_clips_value(cls, x):
    """ Convert from CLIPS value to Python value """
    return cls.PYTHON_TYPE(x)


def get_encodings(hint_encoding='utf-8'):
    """Used to try different encoding.
    Function copied from Odoo 11.0 (odoo.loglevels.get_encodings).
    This piece of code is licensed under the LGPL-v3 and so it is compatible
    with the LGPL-v3 license of OdooRPC::

        - https://github.com/odoo/odoo/blob/11.0/LICENSE
        - https://github.com/odoo/odoo/blob/11.0/COPYRIGHT
    """
    fallbacks = {'latin1': 'latin9', 'iso-8859-1': 'iso8859-15', 'cp1252':
        '1252'}
    if hint_encoding:
        yield hint_encoding
        if hint_encoding.lower() in fallbacks:
            yield fallbacks[hint_encoding.lower()]
    for charset in ['utf8', 'latin1', 'ascii']:
        if not hint_encoding or charset.lower() != hint_encoding.lower():
            yield charset
    from locale import getpreferredencoding
    prefenc = getpreferredencoding()
    if prefenc and prefenc.lower() != 'utf-8':
        yield prefenc
        prefenc = fallbacks.get(prefenc.lower())
        if prefenc:
            yield prefenc


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


def multihash(obj, *attrs):
    """Generate a hash of the object using the provided attributes.

    31 is a "magic number"; it's the same magic number used by Java
    when hashing multiple objects.
    """
    result = 1
    for attr in attrs:
        result = 31 * result + hash(getattr(obj, attr))
    return result


def run(until=None, loop=None):
    """Run the event loop forever or until the task/future *until* is finished.

    This is an alias to asyncio's ``run_forever()`` if *until* is ``None`` and
    to ``run_until_complete()`` if not.

    """
    if loop is None:
        import asyncio
        loop = asyncio.get_event_loop()
    if until is None:
        loop.run_forever()
    else:
        return loop.run_until_complete(until)


@classmethod
def is_solved(cls, description, line):
    """
        Whether the line already solved.
        Do not solve if so, since the blotted algorithm is computationally heavy.
        """
    raise NotImplementedError()


def start_find():
    """Start searching text

    """
    pass


def unlzw(data):
    """
    This function was adapted for Python from Mark Adler's C implementation
    https://github.com/umeat/unlzw
    Decompress compressed data generated by the Unix compress utility (LZW
    compression, files with .Z suffix). Input can be given as any type which
    can be 'converted' to a bytearray (e.g. string, or bytearray). Returns
    decompressed data as string, or raises error.
    Written by Brandon Owen, May 2016, brandon.owen@hotmail.com
    Adapted from original work by Mark Adler - orginal copyright notice below
    Copyright (C) 2014, 2015 Mark Adler
    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.
    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:
    1. The origin of this software must not be misrepresented; you must not
    claim that you wrote the original software. If you use this software
    in a product, an acknowledgment in the product documentation would be
    appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.
    Mark Adler
    madler@alumni.caltech.edu
    """
    try:
        ba_in = bytearray(data)
    except ValueError:
        raise TypeError('Unable to convert inputted data to bytearray')
    inlen = len(ba_in)
    prefix = [None] * 65536
    suffix = [None] * 65536
    if inlen < 3:
        raise ValueError(
            'Invalid Input: Length of input too short for processing')
    if ba_in[0] != 31 or ba_in[1] != 157:
        raise ValueError('Invalid Header Flags Byte: Incorrect magic bytes')
    flags = ba_in[2]
    if flags & 96:
        raise ValueError(
            'Invalid Header Flags Byte: Flag byte contains invalid data')
    max_ = flags & 31
    if max_ < 9 or max_ > 16:
        raise ValueError(
            'Invalid Header Flags Byte: Max code size bits out of range')
    if max_ == 9:
        max_ = 10
    flags &= 128
    bits = 9
    mask = 511
    end = 256 if flags else 255
    if inlen == 3:
        return 0
    if inlen == 4:
        raise ValueError('Invalid Data: Stream ended in the middle of a code')
    buf = ba_in[3]
    buf += ba_in[4] << 8
    final = prev = buf & mask
    buf >>= bits
    left = 16 - bits
    if prev > 255:
        raise ValueError('Invalid Data: First code must be a literal')
    put = [final]
    mark = 3
    nxt = 5
    while nxt < inlen:
        if end >= mask and bits < max_:
            rem = (nxt - mark) % bits
            if rem:
                rem = bits - rem
                if rem >= inlen - nxt:
                    break
                nxt += rem
            buf = 0
            left = 0
            mark = nxt
            bits += 1
            mask <<= 1
            mask += 1
        buf += ba_in[nxt] << left
        nxt += 1
        left += 8
        if left < bits:
            if nxt == inlen:
                raise ValueError(
                    'Invalid Data: Stream ended in the middle of a code')
            buf += ba_in[nxt] << left
            nxt += 1
            left += 8
        code = buf & mask
        buf >>= bits
        left -= bits
        if code == 256 and flags:
            rem = (nxt - mark) % bits
            if rem:
                rem = bits - rem
                if rem > inlen - nxt:
                    break
                nxt += rem
            buf = 0
            left = 0
            mark = nxt
            bits = 9
            mask = 511
            end = 255
            continue
        temp = code
        stack = []
        if code > end:
            if code != end + 1 or prev > end:
                raise ValueError('Invalid Data: Invalid code detected')
            stack.append(final)
            code = prev
        while code >= 256:
            stack.append(suffix[code])
            code = prefix[code]
        stack.append(code)
        final = code
        if end < mask:
            end += 1
            prefix[end] = prev
            suffix[end] = final
        prev = temp
        put += stack[::-1]
    return bytes(bytearray(put))


def clean_package_data(csv_data):
    """Clean package data preliminarily to initializing package objects."""
    for row in csv_data:
        if row[5] == 'EOD':
            row[5] = None
        row[1] = row[1].replace('South', 'S').replace('North', 'N').replace(
            'East', 'E').replace('West', 'W')
        del row[8:]


def parse_bytes(value, default=0, suffixes='bkmgtp'):
    """Convert a bytes-amount ("500k", "2.5M", ...) to int"""
    try:
        last = value[-1].lower()
    except (TypeError, KeyError, IndexError):
        return default
    if last in suffixes:
        mul = 1024 ** suffixes.index(last)
        value = value[:-1]
    else:
        mul = 1
    try:
        return round(float(value) * mul)
    except ValueError:
        return default


def solar_constant():
    """
    Returns the solar constant. The solar constant is defined as the
    flux density of solar radiation at the mean distance from Sun
    to Earth. The solar constant is estimated to be 1367 W m\\ :sup:`-2`\\

    Parameters
    ----------

    Returns
    -------
    I0 : float
        solar constant
        :math:`I_{0}`
        [W m\\ :sup:`-2`\\]
    """
    return 1367.0


def to_code(objective):
    """
    Create executable Python code fragment that corresponds to the model in the
    GUI.

    Parameters
    ----------
    objective: refnx.analysis.Objective

    Returns
    -------
    code: str
        Python code that can construct a reflectometry fitting system

    """
    header = """import numpy as np
import refnx
from refnx.analysis import Objective, CurveFitter, Transform
from refnx.reflect import SLD, Slab, ReflectModel, Structure
from refnx.dataset import ReflectDataset

print(refnx.version.version)
    """
    code = [header]
    code.append('data = ReflectDataset("{0}")'.format(objective.data.filename))
    slds = ['\n# set up the SLD objects for each layer']
    slabs = ['\n# set up the Slab objects for each layer']
    limits = []
    structure = 'structure = '
    for i, slab in enumerate(objective.model.structure):
        sld = slab.sld
        lims = [(sld.real, 'sld{0}.real'), (sld.imag, 'sld{0}.imag'), (slab
            .thick, 'slab{0}.thick'), (slab.rough, 'slab{0}.rough')]
        slds.append("sld{0} = SLD({1} + {2}j, name='{3}')".format(i, sld.
            real.value, sld.imag.value, slab.name))
        slabs.append("slab{0} = Slab({1}, sld{0}, {2}, name='{3}')".format(
            i, slab.thick.value, slab.rough.value, slab.name))
        for p, temp in lims:
            if p.vary:
                limits.append((temp + '.setp(vary=True, bounds=({1}, {2}))'
                    ).format(i, p.bounds.lb, p.bounds.ub))
        if not i:
            structure += 'slab{0}'.format(i)
        else:
            structure += ' | slab{0}'.format(i)
    code.extend(slds)
    code.extend(slabs)
    code.append("\n# set up the limits for SLD's and Slabs")
    code.extend(limits)
    code.append('\n# set up the Structure object from the Slabs')
    code.append(structure)
    model = objective.model
    code.append('\n# make the reflectometry model')
    code.append('model = ReflectModel(structure, scale={0}, bkg={1}, dq={2})'
        .format(model.scale.value, model.bkg.value, model.dq.value))
    lims = [(model.scale, 'model.scale'), (model.bkg, 'model.bkg'), (model.
        dq, 'model.dq')]
    for p, temp in lims:
        if p.vary:
            code.append((temp + '.setp(vary=True, bounds=({0}, {1}))').
                format(p.bounds.lb, p.bounds.ub))
    code.append('\n# make the objective')
    code.append('transform = {}'.format(repr(objective.transform)))
    code.append(
        'objective = Objective(model, data, transform=transform, use_weights={})'
        .format(objective.weighted))
    code.append('\n# make the curvefitter')
    code.append('fitter = CurveFitter(objective)')
    code.append("fitter.fit('differential_evolution')")
    code.append('print(objective)')
    return '\n'.join(code)


def perpend_to_line(p1, p2, p3):
    """Return the perpendicular line of a point to a line segment
    """
    x1, y1 = p1
    x2, y2 = p2
    x3, y3 = p3
    px = x2 - x1
    py = y2 - y1
    sqr = float(px * px + py * py)
    if sqr == 0:
        return x1, y1
    u = ((x3 - x1) * px + (y3 - y1) * py) / sqr
    if u > 1:
        u = 1
    elif u < 0:
        u = 0
    x = x1 + u * px
    y = y1 + u * py
    return x, y


def is_white_key(note):
    """True if note is represented by a white key"""
    key_pattern = [True, False, True, True, False, True, False, True, True,
        False, True, False]
    return key_pattern[(note - 21) % len(key_pattern)]


@staticmethod
def core_packages():
    """
        Return a list of core packages.

        List of packages that are core of the product. Most importantly,
        if they themselves define add-on/plugin entry points they must
        not be 'uninstalled' via a package manager, they can only be
        updated.

        Return
        ------
        packages : List[str]
            A list of package names (can also contain PEP-440 version
            specifiers).
        """
    return ['orange-canvas-core >= 0.0, < 0.1a']


@staticmethod
def get_item_price_id(core, prices):
    """get item price id"""
    price_id = None
    for price in prices:
        if not price['locationGroupId']:
            capacity_min = int(price.get('capacityRestrictionMinimum', -1))
            capacity_max = int(price.get('capacityRestrictionMaximum', -1))
            if capacity_min == -1 or core is None:
                price_id = price['id']
            elif capacity_min <= int(core) <= capacity_max:
                if 'STORAGE' in price.get('capacityRestrictionType'
                    ) or 'CORE' in price.get('capacityRestrictionType'):
                    price_id = price['id']
    return price_id


def theta_Et4N_H_PK74(T, P):
    """c-c': tetraethylammonium hydrogen [PK74]."""
    theta = 0.0
    valid = T == 298.15
    return theta, valid


def rhr(di):
    """right hand rule - finds the new vector with the same magnitude
    as di but rotated counter clockwise"""
    return di[1], -di[0]


def detach_principal_policy(policyName=None, principal=None):
    """
    Removes the specified policy from the specified certificate.
    See also: AWS API Documentation

    :example: response = client.detach_principal_policy(
        policyName='string',
        principal='string'
    )

    :type policyName: string
    :param policyName: [REQUIRED]
            The name of the policy to detach.

    :type principal: string
    :param principal: [REQUIRED]
            The principal.
            If the principal is a certificate, specify the certificate ARN. If the principal is an Amazon Cognito identity, specify the identity ID.

    """
    pass


def open_range_sublist(the_list, from_index, to_index):
    """
    Returns an open range sublist of 'the_list', 'to_index' is not included.
    :param the_list:
    :param from_index:
    :param to_index:
    :return: sublist of 'the_list' or empty list if indexes are out of range
    """
    tmp = []
    list_len = len(the_list)
    if from_index < 0:
        from_index = 0
    if to_index < 0 or to_index > list_len:
        to_index = list_len
    if to_index < from_index:
        to_index = from_index
    if from_index > list_len - 1:
        return tmp
    for i in range(from_index, to_index):
        tmp.append(the_list[i])
    return tmp


def _sumLists(a, b):
    """
    Algorithm to check validity of NBI and NIF.
    Receives string with a umber to validate.
    """
    val = 0
    for i in map(lambda a, b: a * b, a, b):
        val += i
    return val


def write_contents(path, data):
    """
    Overwrite the contents of the file at `path` with the given data.
    If the file does not exist, it is created.

    Example::

      >>> import tempfile
      >>> (fd, tmpfile) = tempfile.mkstemp()
      >>> write_contents(tmpfile, 'big data here') and None # discard return value on Py3
      >>> read_contents(tmpfile)
      'big data here'

    (If you run this test, remember to clean up afterwards)
    ::

      >>> os.remove(tmpfile)

    """
    mode = 'wb' if isinstance(data, bytes) else 'w'
    with open(path, mode) as stream:
        return stream.write(data)


def mimetype():
    """ return the mime type of the file contents if available, or
            `None` otherwise """


def z_score(data2d, axis=0):
    """Standardize the mean and variance of the data axis Parameters.

    :param data2d: DataFrame to normalize.
    :param axis: int, Which axis to normalize across. If 0, normalize across rows,
                  if 1, normalize across columns.

    :Returns: Normalized DataFrame. Normalized data with a mean of 0 and variance of 1
              across the specified axis.

    """
    if axis == 1:
        z_scored = data2d
    else:
        z_scored = data2d.T
    z_scored = (z_scored - z_scored.mean()) / z_scored.std()
    if axis == 1:
        return z_scored
    else:
        return z_scored.T


def is_double_float_register(index):
    """! Returns true for registers holding double-precision float values"""
    return -64 >= index > -96


def _coerce_match_value(value):
    """
    If a match value was provided it's an exact match by default
    """
    if isinstance(value, dict):
        return value
    return {'value': value, 'method': 'exact'}


@classmethod
def check_args_for_activation(cls, cli_args):
    """ Returns true if the arguments indicate that this extension should be activated otherwise false."""
    return True if cli_args.get('env') or cli_args.get('env_file') else False


def break_args_options(line):
    """Break up the line into an args and options string.  We only want to shlex
    (and then optparse) the options, not the args.  args can contain markers
    which are corrupted by shlex.
    """
    tokens = line.split(' ')
    args = []
    options = tokens[:]
    for token in tokens:
        if token.startswith('-') or token.startswith('--'):
            break
        else:
            args.append(token)
            options.pop(0)
    return ' '.join(args), ' '.join(options)


def _norm_index(dim, index, start, stop):
    """Return an index normalized to an farray start index."""
    length = stop - start
    if -length <= index < 0:
        normindex = index + length
    elif start <= index < stop:
        normindex = index - start
    else:
        fstr = 'expected dim {} index in range [{}, {})'
        raise IndexError(fstr.format(dim, start, stop))
    return normindex


def flat_prior(value, boundaries=[None, None]):
    """
    Set up a flat prior on a paramater.
    Out of the bounds, the prior return 0, else it returns 1.

    Parameters
    ----------
    value : [float]
        The paramater to apply the prior on.

    boundaries : [list[float]]
        Boundaries of the flat prior.

    Returns
    -------
    float
    """
    if boundaries[0] is not None and value < boundaries[0]:
        return 0
    if boundaries[1] is not None and value > boundaries[1]:
        return 0
    return 1


def set_to_zero(df, set_to_zero_if_abs_below):
    """Round values to zero if they are below a cutoff
    Args:
        df: (pd.DataFrame | pd.Series)
        set_to_zero_if_abs_below: (float) round all values below this cutoff in magnitude to zero
    Returns:
        pd.Series of rounded values
    """
    zero_df = df.copy()
    zero_df[zero_df.abs() < set_to_zero_if_abs_below] = 0
    return zero_df


@staticmethod
def _convert_number_to_subscript(num):
    """
        Converts number into subscript

        input = ["a", "a1", "a2", "a3", "be2", "be3", "bad2", "bad3"]
        output = ["a", "a₁", "a₂", "a₃", "be₂", "be₃", "bad₂", "bad₃"]

        :param num: number called after sign
        :return: number in subscript
        """
    subscript = ''
    for character in str(num):
        subscript += chr(8320 + int(character))
    return subscript


def name_for_collection_relationship(base, local_cls, referred_cls, constraint
    ):
    """Return the attribute name that should be used to refer from one
    class to another, for a collection reference.

    The default implementation is::

        return referred_cls.__name__.lower() + "_collection"

    Alternate implementations
    can be specified using the
    :paramref:`.AutomapBase.prepare.name_for_collection_relationship`
    parameter.

    :param base: the :class:`.AutomapBase` class doing the prepare.

    :param local_cls: the class to be mapped on the local side.

    :param referred_cls: the class to be mapped on the referring side.

    :param constraint: the :class:`_schema.ForeignKeyConstraint` that is being
     inspected to produce this relationship.

    """
    return referred_cls.__name__.lower() + '_collection'


def fold_lr(F):
    """
    Takes an unfolded two locus spectrum and folds based on left/right allele
    """
    ns = len(F[:, (0), (0)]) - 1
    for ii in range(ns + 1):
        for jj in range(ns + 1):
            for kk in range(ns + 1):
                if F.mask[ii, jj, kk]:
                    continue
                if kk > jj:
                    F[ii, kk, jj] += F[ii, jj, kk]
                    F[ii, jj, kk] = 0
                    F.mask[ii, jj, kk] = True
    return F


@staticmethod
def find_child_by_uid(child, children):
    """Attempt to find the child by uid"""
    for container in children:
        if container.uid == child.uid:
            return container.id, container.uid, container.label
    return None


def nodata(status_code):
    """Translate NODATA status codes from GnuPG to messages."""
    lookup = {'1': 'No armored data.', '2':
        'Expected a packet but did not find one.', '3':
        'Invalid packet found, this may indicate a non OpenPGP message.',
        '4': 'Signature expected but not found.'}
    for key, value in lookup.items():
        if str(status_code) == key:
            return value


def parse_scoped_name(scoped_name):
    """
    SCHEMA: my.module_name:MyClassName
    EXAMPLE:
        Pyautomators.formatter.plain:PlainFormatter
    """
    scoped_name = scoped_name.strip()
    if '::' in scoped_name:
        scoped_name = scoped_name.replace('::', ':')
    module_name, object_name = scoped_name.rsplit(':', 1)
    return module_name, object_name


def new():
    """Add new palette

    """
    pass


@classmethod
def table_name_col(cls):
    """
        Return the name of the metadata column used to store the feature table
        name.
        """
    return 'f_table_name'


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def MAKEFOURCC(ch0: str, ch1: str, ch2: str, ch3: str) ->int:
    """Implementation of Window's `MAKEFOURCC`.

    This is simply just returning the bytes of the joined characters.
    `MAKEFOURCC(*"DX10")` can also be implemented by `Bytes(b"DX10")`.

    Args:
        ch0 (str): First char
        ch1 (str): Second char
        ch2 (str): Third char
        ch3 (str): Fourth char

    Returns:
        int: The integer representation of given characters.

    **Reference**:
        `Microsoft <https://goo.gl/bjtMFA>`__
    """
    return ord(ch0) << 0 | ord(ch1) << 8 | ord(ch2) << 16 | ord(ch3) << 24


@classmethod
def count(cls, like={}, isin={}, orderby='', where='', limit='', **criteria):
    """return count of data filtered by these criteria
    """
    return cls.list(asObjects=False, like=like, isin=isin, orderby=orderby,
        where=where, limit=limit, what='count(uid)', **criteria)[0][
        'count(uid)']


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def get_github_website():
    """Get the URL for the GitHub project."""
    return 'https://github.com/cloudsmith-io/cloudsmith-cli'


def final_sequence(player, opponent, action, seq):
    """Play the moves in `seq` first, ignoring the strategy's moves until the
    list is exhausted."""
    length = player.match_attributes['length']
    if length < 0:
        return action
    index = length - len(player.history)
    if len(player.history) >= length:
        return action
    if index <= len(seq):
        return seq[-index]
    return action


@staticmethod
def disconnect(workers, verbosity):
    """Interrupt connection."""
    workers.Disconnect()


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

        :param ShowcasePermanentlyDeletedDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_permanently_deleted_details', val)


def getAvgPrecision(args):
    """Get average precision

    Similar notice here as in getRL
    """
    usr2NonzeroCols = args['usr2NonzeroCols']
    u2predictions = args['u2predictions']
    colNums = len(next(usr2NonzeroCols.itervalues()))
    prec = 0.0
    for usrid in u2predictions:
        y_nonzeroCols = usr2NonzeroCols[usrid]
        bestCols = u2predictions[usrid]
        col2AllRank = {}
        score = 0.0
        for cnt in range(0, colNums):
            ind = colNums - 1 - cnt
            if y_nonzeroCols[ind] == bestCols[ind]:
                col2AllRank[y_nonzeroCols[ind]] = ind + 1
            else:
                col = y_nonzeroCols[ind]
                col2AllRank[col] = col + len(filter(lambda v: v > col,
                    bestCols)) + 1
        rankedList = sorted(col2AllRank.items(), key=lambda x: x[1])
        for ind, val in enumerate(rankedList):
            score += float(ind + 1) / val[1]
        prec += score / colNums
    return prec / len(u2predictions)


def sulfate_MR66(Sal):
    """Total sulfate in mol/kg-sw following MR66."""
    return 0.14 / 96.062 * Sal / 1.80655


def _sorted_unique_insert(lst, val):
    """insert an element in a list and keep the list sorted.

    It is also ensured that no element appears in the list twice.
    Here are some examples:

    >>> l=[]
    >>> _sorted_unique_insert(l,4)
    >>> l
    [4]
    >>> _sorted_unique_insert(l,4)
    >>> l
    [4]
    >>> _sorted_unique_insert(l,6)
    >>> l
    [4, 6]
    >>> _sorted_unique_insert(l,6)
    >>> l
    [4, 6]
    >>> _sorted_unique_insert(l,4)
    >>> l
    [4, 6]
    >>> _sorted_unique_insert(l,5)
    >>> l
    [4, 5, 6]
    >>> _sorted_unique_insert(l,5)
    >>> l
    [4, 5, 6]
    >>> _sorted_unique_insert(l,4)
    >>> l
    [4, 5, 6]
    >>> _sorted_unique_insert(l,6)
    >>> l
    [4, 5, 6]
    >>> _sorted_unique_insert(l,2)
    >>> l
    [2, 4, 5, 6]
    >>> _sorted_unique_insert(l,3)
    >>> l
    [2, 3, 4, 5, 6]
    >>> _sorted_unique_insert(l,10)
    >>> l
    [2, 3, 4, 5, 6, 10]
    """
    if not lst:
        lst.append(val)
        return
    l = len(lst)
    for i in range(l):
        if val <= lst[i]:
            if val == lst[i]:
                return
            lst.insert(i, val)
            return
    lst.append(val)


def interval_cover(I):
    """Minimum interval cover

    :param I: list of closed intervals
    :returns: minimum list of points covering all intervals
    :complexity: O(n log n)
    """
    S = []
    for start, end in sorted(I, key=lambda v: (v[1], v[0])):
        if not S or S[-1] < start:
            S.append(end)
    return S


def quote(toquote):
    """quote('abc def') -> 'abc%20def'

    Each part of a URL, e.g. the path info, the query, etc., has a
    different set of reserved characters that must be quoted.

    RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
    the following reserved characters.

    reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
                  "$" | ","

    Each of these characters is reserved in some component of a URL,
    but not necessarily in all of them.

    By default, the quote function is intended for quoting the path
    section of a URL.  Thus, it will not encode '/'.  This character
    is reserved, but in typical usage the quote function is being
    called on a path where the existing slash characters are used as
    reserved characters.
    """
    if not toquote:
        if toquote is None:
            raise TypeError('None object cannot be quoted')
        return toquote
    always_safe = (
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-')
    quoted = []
    for char in toquote:
        ooo = ord(char)
        if ooo < 128 and char in always_safe:
            quoted.append(char)
        elif ooo < 127:
            quoted.append('%{:02X}'.format(ooo))
        elif ooo < 191:
            quoted.append('%C2%{:02X}'.format(ooo))
    return ''.join(quoted)


def fit_to_block_size(sequence, block_size, pad_token_id):
    """ Adapt the source and target sequences' lengths to the block size.
    If the sequence is shorter we append padding token to the right of the sequence.
    """
    if len(sequence) > block_size:
        return sequence[:block_size]
    else:
        sequence.extend([pad_token_id] * (block_size - len(sequence)))
        return sequence


@staticmethod
def _validate_callable(f):
    """
        Validate the callable parameter to `_ValidatedFunction`

        Parameters
        ----------
        f : callable
            The callable parameter that we wish to validate.

        Returns
        -------
        orig_f : callable
            The original callable parameter if it is valid.

        Raises
        ------
        TypeError : the callable input is invalid.
        """
    msg = 'Invalid function parameter provided'
    valid_callable = callable(f) and hasattr(f, '__code__')
    valid_callable = valid_callable and hasattr(f.__code__, 'co_varnames')
    if not valid_callable:
        raise ValueError(msg)
    return f


def _pad_with_singletons(obj, num_singletons_before=0, num_singletons_after=0):
    """
    Pad obj with singleton dimensions on the left and right

    Example:
        >>> x = torch.randn(10, 5)
        >>> _pad_width_singletons(x, 2, 3).shape
        >>> # [1, 1, 10, 5, 1, 1, 1]
    """
    new_shape = [1] * num_singletons_before + list(obj.shape) + [1
        ] * num_singletons_after
    return obj.view(*new_shape)


def reward_self_destruct(old_state, new_state):
    """ Returns reward for plr0 receiving damage """
    reward = new_state.injuries[0] - old_state.injuries[0]
    reward = reward / 5000
    return reward


def default_general():
    """
    Content of General tab.

    Arguments:
    None

    Return:
    Content items as list
    """
    items = [['WIDGETS MAIN', '7', int, '', 'PLAIN', '', ''], [
        'WIDGETS ADVANCED', '7', int, '', 'PLAIN', '', ''], ['WIDGETS RARE',
        '7', int, '', 'PLAIN', '', ''], ['Software', ['EPU >1.9',
        'EPU >1.8'], str, '', 'COMBO', 'Main',
        'Software used for data collection.'], ['Type', ['Stack', 'Frames'],
        str, '', 'COMBO', 'Main', 'Stack type used for data collection.'],
        ['Camera', ['K2', 'Falcon3', 'Falcon2'], str, '', 'COMBO', 'Main',
        'Camera used for data collection.'], ['Search path frames', '', str,
        '', 'DIR', 'Main',
        'Directory path containing the micrograph movie files of the data collection (mrc, tif, tiff, ...)'
        ], ['Search path meta', '', str, '', 'DIR', 'Main',
        'Directory path containing the Meta files of the data collection (jpg, xml, ... files). Can be the same as Serach path frames.'
        ], ['Input extension', ['mrc', 'dm4', 'tif', 'tiff'], str, '',
        'COMBO', 'Main', 'Extension of the original micrograph movies.'], [
        'Project name', '', str, '', 'PLAIN', 'Main', 'Project name.'], [
        'Number of frames', '0', int, '', 'PLAIN', 'Main',
        'Expected number of frames of the input micrograph movies. This is used to verify that the micrograph movie is not corrupted.'
        ], ['Rename micrographs', ['True', 'False'], bool, '', 'COMBO',
        'Main', 'Rename the micrographs.'], ['Rename prefix', '', str,
        'Rename micrographs:True', 'PLAIN', 'Main',
        'prefix for the renamed micrographs prefix_number_suffix.extension; The separator between prefix and number needs to be specified, too.'
        ], ['Rename suffix', '', str, 'Rename micrographs:True', 'PLAIN',
        'Main',
        'Suffix for the renamed micrographs prefix_number_suffix.extension; The separator between number and suffix needs to be specified, too.'
        ], ['Increment number', ['True', 'False'], bool,
        'Rename micrographs:True', 'COMBO', 'Main',
        'Increment the number automatically in continue mode instead of manually.'
        ], ['Start number', '0', int, 'Rename micrographs:True', 'PLAIN',
        'Main', 'First number to use for the renaming process.'], [
        'Estimated mic number', '10000', int, 'Rename micrographs:True',
        'PLAIN', 'Main',
        'Estimated number of micrographs. This is used for the leading number of zeros in the renamed start number.'
        ], ['Project directory', '', str, '', 'DIR', 'Advanced',
        'TranSPHIRE project directory used to store all the project folders.'
        ], ['Scratch directory', '', str, '', 'DIR', 'Advanced',
        'TranSPHIRE scratch directory used for faster IO during the TranSPHIRE run.'
        ]]
    return items


@classmethod
def _from_dict(cls, _dict):
    """Initialize a AnalyticsEngineLoggingConfigStatus object from a json dictionary."""
    return cls.from_dict(_dict)


def force_bytes(s, encoding='utf-8', errors='strict'):
    """
    Similar to smart_bytes, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if isinstance(s, bytes):
        if encoding == 'utf-8':
            return s
        else:
            return s.decode('utf-8', errors).encode(encoding, errors)
    if isinstance(s, memoryview):
        return bytes(s)
    else:
        return s.encode(encoding, errors)


def _read(fh, num_bytes):
    """ Reads a number of bytes, throwing an exception if that many bytes isn't
		available.
	"""
    result = fh.read(num_bytes)
    if len(result) != num_bytes:
        raise IOError('Unexpected end-of-file.')
    return result


@classmethod
def find(cls, query: dict, limit=None, skip=None, sort=None,
    returns_generator=False, db=None, **kwargs) ->list:
    """Find and return instances.

        returns:
            objects (list):  ModelBase instances if found else None.
        """
    results = cls.__find(query, limit=limit, skip=skip, sort=sort, db=db,
        **kwargs)
    if returns_generator:
        return cls.generateInstances(results)
    else:
        return list(cls.generateInstances(results))


@staticmethod
def update_object(obj, **updates):
    """ Update denormalized fields incrementally with F-objects.

        After update receives actual object version from db.
        """
    obj.__dict__.update(updates)
    obj.save(update_fields=set(updates))
    obj.refresh_from_db()


def bech32_polymod(values):
    """Internal function that computes the Bech32 checksum."""
    generator = [996825010, 642813549, 513874426, 1027748829, 705979059]
    chk = 1
    for value in values:
        top = chk >> 25
        chk = (chk & 33554431) << 5 ^ value
        for i in range(5):
            chk ^= generator[i] if top >> i & 1 else 0
    return chk ^ 1


def draw_vertical_span(obj_axis, p, p_span):
    """Draw a vertical span

    Args:
        obj_axis (object): a matplotlib axis object
        p (dict): parameters for locations of the span
        p_span (dict): styles of the span

    Returns:
        a matplotlib.patches.Polygon object
    """
    return obj_axis.axvspan(p['min'], p['max'], ymin=p['bottom'], ymax=p[
        'top'], alpha=p_span['opacity'], facecolor=p_span['color']['face'],
        edgecolor=p_span['color']['edge'], linestyle=p_span['line']['style'
        ], linewidth=p_span['line']['width'], fill=p_span['filled'], zorder
        =p_span['which_layer'])


def area_move(x: int=0, y: int=0, delta: int=0):
    """Move selected area edges

    :param x: X
    :type x: int
    :param y: Y
    :type y: int
    :param delta: Delta
    :type delta: int
    """
    pass


def is_subdir(path, directory):
    """
    Returns true if *path* in a subdirectory of *directory*.
    Both paths must be absolute.

    :arg path: An absolute path.
    :type path: string or bytes
    """
    from os.path import normpath, normcase, sep
    path = normpath(normcase(path))
    directory = normpath(normcase(directory))
    if len(path) > len(directory):
        sep = sep.encode('ascii') if isinstance(directory, bytes) else sep
        if path.startswith(directory.rstrip(sep) + sep):
            return True
    return False


def timedelta_to_milli_time(timedelta):
    """Return the current time in milliseconds"""
    return int(timedelta.total_seconds() * 1000)


def _dict_extends(d1, d2):
    """
    Helper function to create a new dictionary with the contents of the two
    given dictionaries. Does not modify either dictionary, and the values are
    copied shallowly. If there are repeats, the second dictionary wins ties.

    The function is written to ensure Skulpt compatibility.

    Args:
        d1 (dict): The first dictionary
        d2 (dict): The second dictionary
    Returns:
        dict: The new dictionary
    """
    d3 = {}
    for key, value in d1.items():
        d3[key] = value
    for key, value in d2.items():
        d3[key] = value
    return d3


def human_readable_filesize(size_in_bytes):
    """
    Humanize the given file size in bytes.

    Returns a number suffixed with ``B``, ``KB``, ``MB``,
    ``GB`` or ``TB``.

    Examples:

        >>> from cradmin_legacy.utils import crhumanize
        >>> crhumanize.human_readable_filesize(1)
        '1B'
        >>> crhumanize.human_readable_filesize(2344234345)
        '2.34GB'
        >>> crhumanize.human_readable_filesize(23442343451234)
        '23.44TB'
    """
    if size_in_bytes < 1000:
        return '{}B'.format(size_in_bytes)
    if size_in_bytes < 1000000:
        return '{}KB'.format(int(size_in_bytes / 1000.0))
    elif size_in_bytes < 1000000000:
        return '{:.1f}MB'.format(size_in_bytes / 1000000.0)
    elif size_in_bytes < 1000000000000:
        return '{:.2f}GB'.format(size_in_bytes / 1000000000.0)
    else:
        return '{:.2f}TB'.format(size_in_bytes / 1000000000000.0)


def salted(value):
    """
    Protects a value using a random salt. This completely prevents the BREACH
    attack against a salted secret, but stores values in a codified form that
    cannot be directly used.

    The BREACH authors suggest a transform that takes a string P and returns
    (P + (S^P)), where S^P is a XOR operation of each byte. Templates do not
    have a byte-level control of the message, hence salting must be done in
    unicode data. This brings some problems:

    * How to (efficiently) implement XOR for a large alphabet such as unicode?
    * Xor-ing two valid unicode points will not necessarily yield a valid
      unicode value.
    * Client code needs to recover the encoded data, hence the solution must
      be portable to Python and Javascript
    """
    raise NotImplementedError


def _unflatten(fd, sep='_'):
    """
    Unflatten a dictionary or other nested structure into a nested
    dictionary.

    Parameters
    ----------
    fd : dictionary
        Flattend dictionary.
    sep : string
        String at which keys are split.

    Returns
    -------
    Nested dictionary of unflattened structure.

    """
    ud = dict()
    for k, v in fd.items():
        new_ks = k.split(sep)
        d = ud
        for new_k in new_ks[:-1]:
            if new_k not in d:
                d[new_k] = dict()
            d = d[new_k]
        d[new_ks[-1]] = v
    return ud


def n_to_data(n):
    """Convert an integer to one-, four- or eight-unit graph6 sequence.

    This function is undefined if `n` is not in ``range(2 ** 36)``.

    """
    if n <= 62:
        return [n]
    elif n <= 258047:
        return [63, n >> 12 & 63, n >> 6 & 63, n & 63]
    else:
        return [63, 63, n >> 30 & 63, n >> 24 & 63, n >> 18 & 63, n >> 12 &
            63, n >> 6 & 63, n & 63]


def geo_field(queryset):
    """Returns the GeometryField for a django or spillway GeoQuerySet."""
    try:
        return queryset.geo_field
    except AttributeError:
        return queryset._geo_field()


def _unbound_tae_starter(tae, *args, **kwargs):
    """
    Unbound function to be used by joblibs Parallel, since directly passing the
    TAE results in pickling-problems.

    Parameters
    ----------
    tae: ExecuteTARun
        tae to be used
    *args, **kwargs: various
        arguments to the tae

    Returns
    -------
    tae_results: tuple
        return from tae.start
    """
    return tae.start(*args, **kwargs)


def add_arguments_for_wait_operation(parser):
    """
    Add arguments of wait operation in the parser

    :param parser: add arguments to it
    :type parser: argparse.ArgumentParser
    :return: None
    """
    parser.add_argument('--no-wait', action='store_true', help=
        'no wait until scale will be finished')
    parser.add_argument('--timeout', default=300, type=int, help=
        'timeout in s. for wait (if no-wait is off)')


def convert_to_lower(dic):
    """
    把字典中地健值全部转换为小写字母
    :param dic:
    :return:
    """
    lower_dic = {}
    for k, v in dic.items():
        if isinstance(v, list):
            temp_v = []
            for i in v:
                temp_d = {}
                for k2, v2 in i.items():
                    temp_d[k2.lower()] = v2
                temp_v.append(temp_d)
            f_v = temp_v
        elif isinstance(v, dict):
            temp_v = {}
            for k2, v2 in v.items():
                temp_v[k2.lower()] = v2
            f_v = temp_v
        else:
            f_v = v
        lower_dic[k.lower()] = f_v
    return lower_dic


@staticmethod
def run():
    """Get list of instances."""
    return []


def _safe_single_attr(x):
    """Handle cleaning of attributes after extraction:
      - '.'s to indicate None
      - tuples where we expect a single value
    """
    if x is None or x is '.':
        return None
    elif isinstance(x, (list, tuple)):
        return x[0]
    else:
        return x


def _calculate_size_sim(ri, rj, imsize):
    """
        Size similarity boosts joint between small regions, which prevents
        a single region from engulfing other blobs one by one.

        size (ri, rj) = 1 − [size(ri) + size(rj)] / size(image)
    """
    return 1.0 - (ri['size'] + rj['size']) / imsize


def edge_face_add():
    """Add an edge or face to selected

    """
    pass


def is_first_seg_match2(child, seg_data):
    """
    Find the first segment in loop, verify it matches segment

    @param child: child node
    @type child: L{node<map_if.x12_node>}
    @param seg_data: Segment object
    @type seg_data: L{segment<segment.Segment>}
    @rtype: boolean
    """
    if child.is_segment():
        if child.is_match(seg_data):
            return True
        else:
            return False
    return False


def wsgi_to_bytes(s):
    """Convert a native string to a WSGI / HTTP compatible byte string."""
    return s.encode('iso-8859-1')


@staticmethod
def _filter(ftype):
    """
        Internal function to generate text string for setting up default files.
        """
    if ftype == '*':
        return 'AllFiles (*)'
    if ftype == 'dicom':
        return 'Dicom Files (*.dcm, *.ima)'
    if ftype == 'ctx':
        return 'CtxCube Files (*.ctx)'
    if ftype == 'hed':
        return 'Header Files (*.hed)'
    if ftype == 'dos':
        return 'DosCube Files (*.dos)'
    if ftype == 'let':
        return 'LETCube Files (*.dosemlet.dos)'
    return 'AllFiles (*)'


def _format_newlines(prefix, formatted_node, options):
    """
    Convert newlines into U+23EC characters, followed by an actual newline and
    then a tree prefix so as to position the remaining text under the previous
    line.
    """
    replacement = u''.join([options.NEWLINE, u'\n', prefix])
    return formatted_node.replace(u'\n', replacement)


def ParseEnum(field, value):
    """Parse an enum value.

  The value can be specified by a number (the enum value), or by
  a string literal (the enum name).

  Args:
    field: Enum field descriptor.
    value: String value.

  Returns:
    Enum value number.

  Raises:
    ValueError: If the enum value could not be parsed.
  """
    enum_descriptor = field.enum_type
    try:
        number = int(value, 0)
    except ValueError:
        enum_value = enum_descriptor.values_by_name.get(value, None)
        if enum_value is None:
            raise ValueError('Enum type "%s" has no value named %s.' % (
                enum_descriptor.full_name, value))
    else:
        if hasattr(field.file, 'syntax'):
            if field.file.syntax == 'proto3':
                return number
        enum_value = enum_descriptor.values_by_number.get(number, None)
        if enum_value is None:
            raise ValueError('Enum type "%s" has no value with number %d.' %
                (enum_descriptor.full_name, number))
    return enum_value.number


def _test_sampmdsize(t):
    """Check if the size of the sample metadata matches data size"""
    md = t.metadata(axis='sample')
    return t.shape[1] != len(md) if md is not None else False


def assert_unordered_list_eq(expected, actual, message=None):
    """Raises an AssertionError if the objects contained
    in expected are not equal to the objects contained
    in actual  without regard to their order.

    This takes quadratic time in the umber of elements in actual; don't use it for very long lists.

    """
    missing_in_actual = []
    missing_in_expected = list(actual)
    for x in expected:
        try:
            missing_in_expected.remove(x)
        except ValueError:
            missing_in_actual.append(x)
    if missing_in_actual or missing_in_expected:
        if not message:
            message = (
                '%r not equal to %r; missing items: %r in expected, %r in actual.'
                 % (expected, actual, missing_in_expected, missing_in_actual))
        assert False, message


def copy_annotations(src, dest):
    """
    Copy annotations from the tokens listed in src to the tokens in dest
    """
    assert len(src) == len(dest)
    for src_tok, dest_tok in zip(src, dest):
        dest_tok.annotation = src_tok.annotation


def insertion_sort(nums):
    """
    returns sorted list
    """
    for i in range(1, len(nums)):
        value = nums[i]
        for j in range(i - 1, -1, -1):
            if nums[j] > value:
                nums[j + 1] = nums[j]
            else:
                break
        nums[j] = value
    return nums


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['policyType']
    if type == 'threshold':
        return 'UpdateThresholdPolicyDetails'
    else:
        return 'UpdateAutoScalingPolicyDetails'


@staticmethod
def _build_dict(my_dict, keys, values):
    """Build a dictionary from a set of redis hashes.

            keys = ['a', 'b', 'c']
            values = {'value': 'foo'}
            my_dict = {'a': {'b': {'c': {'value': 'foo'}}}}

        Args:
            my_dict (dict): Dictionary to add to
            keys (list[str]): List of keys used to define hierarchy in my_dict
            values (dict): Values to add at to the dictionary at the key
               specified by keys

        Returns:
            dict, new dictionary with values added at keys

        """
    temp = my_dict
    for depth, key in enumerate(keys):
        if depth < len(keys) - 1:
            if key not in temp:
                temp[key] = dict()
            temp = temp[key]
        elif key not in temp:
            temp[key] = values
        else:
            temp[key] = {**temp[key], **values}
    return my_dict


def _get_message(status):
    """
    Given problem status code, return a more detailed message.

    Parameters
    ----------
    status : int
        An integer representing the exit status of the optimization::

         0 : Optimization terminated successfully
         1 : Iteration limit reached
         2 : Problem appears to be infeasible
         3 : Problem appears to be unbounded
         4 : Serious numerical difficulties encountered

    Returns
    -------
    message : str
        A string descriptor of the exit status of the optimization.

    """
    messages = ['Optimization terminated successfully.',
        'The iteration limit was reached before the algorithm converged.',
        'The algorithm terminated successfully and determined that the problem is infeasible.'
        ,
        'The algorithm terminated successfully and determined that the problem is unbounded.'
        ,
        'Numerical difficulties were encountered before the problem converged. Please check your problem formulation for errors, independence of linear equality constraints, and reasonable scaling and matrix condition numbers. If you continue to encounter this error, please submit a bug report.'
        ]
    return messages[status]


def median(data_sorted):
    """
    Finds the median value of a given series of values.

    :param data_sorted:
        The values to find the median of. Must be sorted.
    """
    length = len(data_sorted)
    if length % 2 == 1:
        return data_sorted[(length + 1) // 2 - 1]
    half = length // 2
    a = data_sorted[half - 1]
    b = data_sorted[half]
    return (a + b) / 2


def acceleration_fma(force, mass):
    """Usage: acceleration_fma(force of object, mass of object)"""
    return force / mass


def failure_to_context(report, context):
    """If a twisted_failure key is present, use it to set context['exc_info'].

    This permits using regular python hooks with a twisted failure.
    """
    failure = context.get('twisted_failure')
    if not failure:
        return
    exc_info = failure.type, failure.value, failure.getTraceback()
    context['exc_info'] = exc_info
    del exc_info


def state():
    """
        The state of the workspace
        """


def detach_elastic_load_balancer(ElasticLoadBalancerName=None, LayerId=None):
    """
    Detaches a specified Elastic Load Balancing instance from its layer.
    See also: AWS API Documentation

    :example: response = client.detach_elastic_load_balancer(
        ElasticLoadBalancerName='string',
        LayerId='string'
    )

    :type ElasticLoadBalancerName: string
    :param ElasticLoadBalancerName: [REQUIRED]
            The Elastic Load Balancing instance's name.

    :type LayerId: string
    :param LayerId: [REQUIRED]
            The ID of the layer that the Elastic Load Balancing instance is attached to.

    """
    pass


@classmethod
def cycle_pre_run(cls, context, synergy_manager):
    """

        This class method will be executed each cycle, one time by action class.
        Useful fo apply some tricks before this synergies objects action.

        :param context:
        :param synergy_manager:
        :return:
        """
    pass


def convert_degrees_to_decimal(degrees, minutes, seconds):
    """
    Convert degree-minute-second format to decimal degrees.

    Example:
    >>> convert_degrees_to_decimal(10, 23, 42)
    10.395

    Returns:
         Degrees in decimal format
    """
    return degrees + minutes / 60.0 + seconds / 3600.0


def _get_ltag_pattern():
    """
    Build the big ugly fat regexp for L# numbering. It's based on named
    patterns : (P?<pattern_name>pattern) and decomposed part by part.

    Please have a look on
    https://forum.camptocamp.org/t/question-l/207148/69
    """
    p = '(?P<{}>{})'.format
    raw_label = '[a-zA-Z\'\\"][a-zA-Z\'\\"\\d_]*|_'
    raw_offset = '[+\\-]?\\d*'
    multi_pitch_label = p('multi_pitch_label', raw_label)
    first_offset = p('first_offset', raw_offset)
    last_offset = p('last_offset', raw_offset)
    first_pitch = p('first_pitch', first_offset + multi_pitch_label + '?')
    last_pitch = p('last_pitch', last_offset)
    multi_pitch = p('multi_pitch', first_pitch + '?-' + last_pitch)
    mono_pitch_label = p('mono_pitch_label', raw_label)
    mono_pitch_value = p('mono_pitch_value', '\\+?\\d*')
    mono_pitch = p('mono_pitch', mono_pitch_value + mono_pitch_label + '?')
    local_ref = p('local_ref', '!')
    pitch = '(' + multi_pitch + '|' + mono_pitch + ')'
    numbering = p('numbering', pitch + local_ref + '?')
    text_in_the_middle = p('text_in_the_middle', '~')
    header = p('header', '=')
    typ = p('type', '^[LR]')
    text = '(' + header + '|' + text_in_the_middle + '|' + numbering + ')'
    return p('ltag', typ + '#' + text)


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def p_literal(p):
    """literal : q_STRING
        | NUMBER
        | STRING_VALUE"""
    p[0] = p[1]


def looks_like_issubclass(obj, classname):
    """ Return True if the object has a class or superclass with the given class
    name.

    Ignores old-style classes.
    """
    t = obj
    if t.__name__ == classname:
        return True
    for klass in t.__mro__:
        if klass.__name__ == classname:
            return True
    return False


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 is_response_to_head(response):
    """
    Checks whether the request of a response has been a HEAD-request.
    Handles the quirks of AppEngine.

    :param conn:
    :type conn: :class:`httplib.HTTPResponse`
    """
    method = response._method
    if isinstance(method, int):
        return method == 3
    return method.upper() == 'HEAD'


def new_symbol(grammar, symbol_name='<symbol>'):
    """Return a new symbol for `grammar` based on `symbol_name`"""
    if symbol_name not in grammar:
        return symbol_name
    count = 1
    while True:
        tentative_symbol_name = symbol_name[:-1] + '-' + repr(count) + '>'
        if tentative_symbol_name not in grammar:
            return tentative_symbol_name
        count += 1


@staticmethod
def _get_terminal_code():
    """
        Abstract method that should be over ridden

        :returns: String containing APIC class name for this type of terminal.
        """
    assert NotImplemented('This method needs to be implemented')


@staticmethod
def unpack_conditions(**kwargs) ->dict:
    """
        Parse arguments.

        This is used to form :attr:`conditions` for a distributions, as
        one may desire to have different parametrizations, this all should be done there
        """
    return kwargs


@classmethod
def process(cls, *, context=None, parameter=None):
    """ Evaluate the INPUT[CHARACTER] command. """
    address = context.stack.pop()
    value = context.input('CIN')
    context.heap[address] = ord(value)


def timer(after, repeat=0.0, ref=True, priority=None):
    """
        Create and return a timer watcher that will fire after *after* seconds.

        If *repeat* is given, the timer will continue to fire every *repeat* seconds.
        """


def downsample(values, target_length):
    """Downsamples 1d values to target_length, including start and end.

    Algorithm just rounds index down.

    Values can be any sequence, including a generator.
    """
    assert target_length > 1
    values = list(values)
    if len(values) < target_length:
        return values
    ratio = float(len(values) - 1) / (target_length - 1)
    result = []
    for i in range(target_length):
        result.append(values[int(i * ratio)])
    return result


def fileno(file_or_fd):
    """
    Look for 'fileno' attribute.
    """
    fd = getattr(file_or_fd, 'fileno', lambda : file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError('Expected a file (`.fileno()`) or a file descriptor')
    return fd


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

        :param PaperContentRemoveMemberDetails val:
        :rtype: EventDetails
        """
    return cls('paper_content_remove_member_details', val)


def symmetr_AB(syms, X, atom1, atom2, round_prec=None):
    """
    Tries to transform the tensor projected on one atom to a different atom

    Args:
        syms: The symmmetry operations. Format as outputted by read.py
        X: The input tensor.
        op1: The first operator.
        op2: The second operator.
        atom1: The atom on which X is projected.
        atom2: The atom on which X is transformed.
        T (Optional[matrix]): Coordinate transformation matrix. If it is set, the symmetry operations will be transformed by this matrix.
            Symmetry operations are given in basis A. T transforms from A to B, ie Tx_A = x_B.

    Returns:
        X_trans: The transformed tensor.
    """
    X_trans = []
    found = False
    for sym in syms:
        if sym.permutations[atom1] == atom2 and not found:
            found = True
            for l in range(2):
                X_trans.append(X[l].transform(sym))
    if found:
        if round_prec is not None:
            for X in X_trans:
                X.round(round_prec)
        return X_trans
    else:
        return None


@classmethod
def get_by_key(cls, section, key):
    """ Return specified Ui object, or None if not found. """
    return cls.query().filter_by(ui_section=section, ui_key=key).scalar()


@classmethod
def getGraphClass(cls, name):
    """return a graph class by its name"""
    try:
        return cls.graphClasses[name]
    except KeyError:
        raise KeyError("There's no child of Graph by the name of: %s" % name)


@classmethod
def process_ray_collision_contacts(cls, ray, other_geom, contacts):
    """Process special case of collision between a ray and a regular geom.

		.. seealso::
		   For regular geoms collision, see :meth:`process_collision_contacts`.

		Since rays have no attached body, they can't "really" collide
		with other geoms. However, they do intersect, which is of
		interest to non-physical aspects of the simulation. A common
		use case is that of laser distance sensors.

		.. warning::
		   Collision between two rays is a singularity and should never happen.

		:param ray:
		:type ray: type of :attr:`Ray.inner_object`
		:param other_geom:
		:type other_geom: type of :attr:`Geom.inner_object`
		:param contacts: collision data returned by :meth:`calc_collision`
		:type contacts: list of contact data objects

		"""
    raise NotImplementedError()


def select_linked():
    """Select all curve points linked to already selected ones

    """
    pass


def view_zoom_out(location: float=(0.0, 0.0)):
    """Zoom out the image (centered around 2D cursor)

    :param location: Location, Cursor location in screen coordinates
    :type location: float
    """
    pass


def _is_parsable_header(structure):
    """ Determines if a PDS4 header structure can be parsed into plain text.

    Header structures that can be displayed as text are:
        (1) Plain-text Headers
        (2) Headers that can be turned into plain-text via a parser

    """
    return structure.is_header() and hasattr(structure.parser(), 'to_string')


def getTermByToken(token):
    """Return an ITokenizedTerm for the passed-in token.

        If `token` is not represented in the vocabulary, `LookupError`
        is raised.
        """


def _convert_ceil(builder, node, graph, err):
    """
    convert to CoreML Ceil Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L5018
    """
    builder.add_ceil(name=node.name, input_name=node.inputs[0], output_name
        =node.outputs[0])


def get_match(partial):
    """ Return str value for partial bool. """
    if partial is True:
        return 'partial'
    else:
        return 'full'


def chunkread(f, size):
    """Generator that reads from file like object. May return less
     data than requested on the last read."""
    c = f.read(size)
    while len(c):
        yield c
        c = f.read(size)


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


@classmethod
def input_named(cls, name):
    """Returns an XPath to find an HTML <input> with the given name."""
    return '//input[@name="%s"]' % name


def _list_to_num(l):
    """
    [0x01, 0x02] -> 258
    :param list l:
    :rtype: int
    """
    output = 0
    for i in range(len(l)):
        output += l[i] << 8 * (len(l) - i - 1)
    return output


def hard_update(local_model, target_model) ->None:
    """Hard updates model parameters.

    θ_target = θ_local

    Args:
        local_model (PyTorch model): Weights will be copied from.
        target_model (PyTorch model): Weights will be copied to.
    """
    for target_param, local_param in zip(target_model.parameters(),
        local_model.parameters()):
        target_param.data.copy_(local_param.data)


def validate_boolean(option, value):
    """Validates that 'value' is True or False."""
    if isinstance(value, bool):
        return value
    raise TypeError('%s must be True or False' % (option,))


def handle_comments_pre_delete(sender, **kwargs):
    """
        Delete comments attached to object which is about to be
        deleted b/c django-comments' object_pk is not a FK relationship
        and we can't rely on cascading delete!
    """
    from tcms.core.helpers.comments import get_comments
    if kwargs.get('raw', False):
        return
    instance = kwargs['instance']
    get_comments(instance).delete()


def readInTiffProjection(filename_base, fileNumber):
    """
    * readInTiffProjection *

    Reads and returns a single TIFF image as a NumPy array

    :param filename_base: Base filename of TIFF
    :param fileNumber: Image number
    :return: Image in a 2D NumPy array

    Author: Alan (AJ) Pryor, Jr.
    Jianwei (John) Miao Coherent Imaging Group
    University of California, Los Angeles
    Copyright 2015-2016. All rights reserved.
    """
    from PIL import Image
    import numpy as np
    nextFile = filename_base + str(fileNumber) + '.tif'
    return np.array(Image.open(nextFile))


def discover(isdsAppliance, check_mode=False, force=False):
    """
    Discover available updates
    """
    return isdsAppliance.invoke_get('Discover available updates',
        '/updates/available/discover')


def get_perc_of_qt(dataframe):
    """
    Calculates the percentage of all tweets in the given dataframe that are quotes

    :param pd.Dataframe dataframe: Dataframe containing twitter data

    :return: Either string telling the error or integer telling the percentage

    """
    if 'QT' in dataframe:
        df_stats = dataframe[dataframe.QT == 1]
        if len(df_stats) > 0:
            return round(len(df_stats) / len(dataframe) * 100, 1)
        else:
            return 'No quoting in dataset'
    else:
        return 'No quoting in dataset'


@classmethod
def get(cls, top, parent=None):
    """
        This will get all of the access filters on the
        specified node.  If no node is specified, then
        it will get all of the access rules on all
        of the switches.

        :param parent:
        :param top: the topSystem level json object
        :returns: list of Switch bridge domain
        """
    cls.check_parent(parent)
    result = []
    filter_data = top.get_class('actrlFlt')
    for filter_object in filter_data:
        acc_filter = cls()
        acc_filter._populate_from_attributes(filter_object['actrlFlt'][
            'attributes'])
        acc_filter._get_entries(top)
        acc_filter._get_pod_node()
        result.append(acc_filter)
        if parent:
            acc_filter._parent = parent
            acc_filter._parent.add_child(acc_filter)
    return result


def pack():
    """Pack an image as embedded data into the .blend file

    """
    pass


def SGErrors(IErr):
    """
    Interprets the error message code from SpcGroup. Used in SpaceGroup.

    :param IErr: see SGError in :func:`SpcGroup`
    :returns:
        ErrString - a string with the error message or "Unknown error"
    """
    ErrString = [' ', 'Less than 2 operator fields were found',
        'Illegal Lattice type, not P, A, B, C, I, F or R',
        'Rhombohedral lattice requires a 3-axis',
        'Minus sign does not preceed 1, 2, 3, 4 or 6',
        'Either a 5-axis anywhere or a 3-axis in field not allowed', ' ',
        'I for COMPUTED GO TO out of range.',
        'An a-glide mirror normal to A not allowed',
        'A b-glide mirror normal to B not allowed',
        'A c-glide mirror normal to C not allowed',
        'D-glide in a primitive lattice not allowed',
        'A 4-axis not allowed in the 2nd operator field',
        'A 6-axis not allowed in the 2nd operator field',
        'More than 24 matrices needed to define group', ' ',
        'Improper construction of a rotation operator',
        'Mirror following a / not allowed',
        'A translation conflict between operators',
        'The 2bar operator is not allowed',
        '3 fields are legal only in R & m3 cubic groups',
        'Syntax error. Expected I -4 3 d at this point', ' ',
        'A or B centered tetragonal not allowed', ' ',
        'unknown error in sgroup', ' ', ' ', ' ',
        'Illegal character in the space group symbol']
    try:
        return ErrString[IErr]
    except:
        return 'Unknown error'


def state_request_create():
    """
    Generate a state request message.

    Returns
    -------
    message : list of bytes
        The properly formatted state request message. The first list
        element is by definition the byte sequence ``b'STATE'``.

    """
    return [b'STATE', b'REQUEST']


def try_int(s):
    """Convert to integer if possible."""
    try:
        return int(s)
    except:
        return s


def rule_move_up():
    """Move boid rule up in the list

    """
    pass


def get_parser(func, parent):
    """
    Imposta il parser.
    """
    parser = parent.add_parser(func.__cmd_name__, help=func.__doc__)
    exc_grps = {}
    for args, kwargs in func.__arguments__:
        exc_grp = kwargs.pop('exc_grp', None)
        if exc_grp:
            if isinstance(exc_grp, (list, tuple)):
                name, required = exc_grp
            else:
                name, required = exc_grp, False
            if not name in exc_grps:
                exc_grps[name] = parser.add_mutually_exclusive_group(required
                    =required)
            exc_grps[name].add_argument(*args, **kwargs)
        else:
            parser.add_argument(*args, **kwargs)
    return parser


def associate_node(ServerName=None, NodeName=None, EngineAttributes=None):
    """
    Associates a new node with the Chef server. This command is an alternative to knife bootstrap . For more information about how to disassociate a node, see  DisassociateNode .
    A node can can only be associated with servers that are in a HEALTHY state. Otherwise, an InvalidStateException is thrown. A ResourceNotFoundException is thrown when the server does not exist. A ValidationException is raised when parameters of the request are not valid. The AssociateNode API call can be integrated into Auto Scaling configurations, AWS Cloudformation templates, or the user data of a server's instance.
    Example: aws opsworks-cm associate-node --server-name *MyServer* --node-name *MyManagedNode* --engine-attributes "Name=*MyOrganization* ,Value=default" "Name=*Chef_node_public_key* ,Value=*Public_key_contents* "
    See also: AWS API Documentation

    :example: response = client.associate_node(
        ServerName='string',
        NodeName='string',
        EngineAttributes=[
            {
                'Name': 'string',
                'Value': 'string'
            },
        ]
    )

    :type ServerName: string
    :param ServerName: [REQUIRED]
            The name of the server with which to associate the node.

    :type NodeName: string
    :param NodeName: [REQUIRED]
            The name of the Chef client node.

    :type EngineAttributes: list
    :param EngineAttributes: [REQUIRED]
            Engine attributes used for associating the node.
            Attributes accepted in a AssociateNode request:
            CHEF_ORGANIZATION : The Chef organization with which the node is associated. By default only one organization named default can exist.
            CHEF_NODE_PUBLIC_KEY : A PEM-formatted public key. This key is required for the chef-client agent to access the Chef API.
            (dict) --A name and value pair that is specific to the engine of the server.
            Name (string) --The name of the engine attribute.
            Value (string) --The value of the engine attribute.

    :rtype: dict
    :return: {
        'NodeAssociationStatusToken': 'string'
    }

    """
    pass


def mark_string(string_migration, comment_format, mark):
    """Mark a string migration for proofreading.

    Adds a comment in the beginning of this string.

    :param StringMigration string_migration: the string migration object
        to update
    :param unicode comment_format: the format of the comment,
        compatible with the file type of the migration
    :param str mark: the string to add as a comment
    """
    string_migration.update('', comment_format.format(mark), append=False)


def stis_psf(x, a):
    """Evaluate the cross-dispersion PSF at x.

    Parameters
    ----------
    x : float
        offset in pixels from the center of the profile
    a : float
        a measure of the width of the PSF

    Returns
    -------
    val : float
        the PSF evaluated at x

    """
    return (1.0 + (x / float(a)) ** 2) ** -2


def pytest_runtest_logstart(nodeid, location):
    """ signal the start of running a single test item.

    This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and
    :func:`pytest_runtest_teardown` hooks.

    :param str nodeid: full id of the item
    :param location: a triple of ``(filename, linenum, testname)``
    """


def _create_index_content(words):
    """Create html string of index file.

    Parameters
    ----------
    words : list of str
        List of cached words.

    Returns
    -------
    str
        html string.
    """
    content = ['
Index
', '
']
    for word in words:
        content.append('
{word}
'
            .format(word=word))
    content.append('
')
    if not words:
        content.append('Nothing to see here ...yet!')
    return '\n'.join(content)


def longest_common_prefix(items1, items2):
    """
    Return the longest common prefix.

      >>> longest_common_prefix("abcde", "abcxy")
      'abc'

    :rtype:
      ``type(items1)``
    """
    n = 0
    for x1, x2 in zip(items1, items2):
        if x1 != x2:
            break
        n += 1
    return items1[:n]


def _rewrite_server_name(server_name, new_port):
    """Rewrite server port in ``server_name`` with ``new_port`` value."""
    sep = ':'
    if sep in server_name:
        server_name, port = server_name.split(sep, 1)
    return sep.join((server_name, new_port))


def with_metaclass(meta, base=object):
    """Create a base class with a metaclass."""
    return meta('NewBase', (base,), {})


def compare_results(save, best_hsp, tmp_results, tmp_gene_split):
    """ Function for comparing hits and saving only the best hit """
    hit_id = best_hsp['hit_id']
    new_start_query = best_hsp['query_start']
    new_end_query = best_hsp['query_end']
    new_start_sbjct = int(best_hsp['sbjct_start'])
    new_end_sbjct = int(best_hsp['sbjct_end'])
    new_score = best_hsp['cal_score']
    new_db_hit = best_hsp['sbjct_header']
    new_contig = best_hsp['contig_name']
    new_HSP = best_hsp['HSP_length']
    for hit in list(tmp_results):
        hit_data = tmp_results[hit]
        old_start_query = hit_data['query_start']
        old_end_query = hit_data['query_end']
        old_start_sbjct = int(hit_data['sbjct_start'])
        old_end_sbjct = int(hit_data['sbjct_end'])
        old_score = hit_data['cal_score']
        old_db_hit = hit_data['sbjct_header']
        old_contig = hit_data['contig_name']
        old_HSP = hit_data['HSP_length']
        remove_old = 0
        if new_db_hit == old_db_hit:
            if (new_start_sbjct < old_start_sbjct or new_end_sbjct >
                old_end_sbjct):
                tmp_gene_split[old_db_hit][hit_id] = 1
                if not hit in tmp_gene_split[old_db_hit]:
                    tmp_gene_split[old_db_hit][hit] = 1
            elif new_score > old_score:
                remove_old = 1
                if (new_db_hit in tmp_gene_split and not hit_id in
                    tmp_gene_split[new_db_hit]):
                    tmp_gene_split[new_db_hit][hit_id] = 1
            else:
                save = 0
                if hit_id != hit:
                    if (new_db_hit in tmp_gene_split and hit_id in
                        tmp_gene_split[new_db_hit]):
                        del tmp_gene_split[new_db_hit][hit_id]
                break
        if new_contig == old_contig:
            if (old_start_query == new_start_query and old_end_query ==
                new_end_query):
                if best_hsp['perc_ident'] > hit_data['perc_ident']:
                    remove_old = 1
                    if (new_db_hit in tmp_gene_split and not hit_id in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                elif best_hsp['perc_ident'] == hit_data['perc_ident']:
                    if (new_db_hit in tmp_gene_split and not hit_id in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                else:
                    save = 0
                    if (new_db_hit in tmp_gene_split and hit_id in
                        tmp_gene_split[new_db_hit]):
                        del tmp_gene_split[new_db_hit][hit_id]
                    break
            elif max(old_end_query, new_end_query) - min(old_start_query,
                new_start_query) <= old_end_query - old_start_query + (
                new_end_query - new_start_query):
                if new_score > old_score:
                    remove_old = 1
                    if (new_db_hit in tmp_gene_split and not hit_id in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                elif new_score == old_score:
                    if int(best_hsp['perc_coverage']) == 100 and int(hit_data
                        ['perc_coverage']) == 100 and new_HSP > old_HSP:
                        remove_old = 1
                    if (new_db_hit in tmp_gene_split and not hit_id in
                        tmp_gene_split[new_db_hit]):
                        tmp_gene_split[new_db_hit][hit_id] = 1
                else:
                    if (new_db_hit in tmp_gene_split and hit_id in
                        tmp_gene_split[new_db_hit]):
                        del tmp_gene_split[new_db_hit][hit_id]
                    save = 0
                    break
        if remove_old == 1:
            del tmp_results[hit]
            if old_db_hit in tmp_gene_split and hit in tmp_gene_split[
                old_db_hit]:
                del tmp_gene_split[old_db_hit][hit]
    return save, tmp_gene_split, tmp_results


def odd(number):
    """Determine if number is odd"""
    return number % 2 == 1


def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
    """Unsets a cookie by name, by default over all domains and paths.

    Wraps CookieJar.clear(), is O(n).
    """
    clearables = []
    for cookie in cookiejar:
        if cookie.name == name:
            if domain is None or domain == cookie.domain:
                if path is None or path == cookie.path:
                    clearables.append((cookie.domain, cookie.path, cookie.name)
                        )
    for domain, path, name in clearables:
        cookiejar.clear(domain, path, name)


def HT_TRENDLINE(df, price='Close'):
    """
    Hilbert Transform - Instantaneous Trendline
    """


def theta_Ba_Li_PK74(T, P):
    """c-c': barium lithium [PK74]."""
    theta = -0.07
    valid = T == 298.15
    return theta, valid


def make_atmos_nc(var_dict, filename='atmos.nc'):
    """
   Currently under development
   """
    return -1


def getOutgoingInterface():
    """
        Return interface of outgoing multicast packets.
        """


def _test_method_name(test_id):
    """
        Returns the test method name.
        """
    return test_id.split('.')[-1]


def set_diag(arr, x, i=0, copy=False):
    """
    Rewrite the i-th diagonal of a matrix with a value or an array of values.
    Supports 2D arrays, square or rectangular. In-place by default.

    Parameters
    ----------
    arr : 2-D array
        Array whose diagonal is to be filled.
    x : scalar or 1-D vector of correct length
        Values to be written on the diagonal.
    i : int, optional
        Which diagonal to write to. Default is 0.
        Main diagonal is 0; upper diagonals are positive and
        lower diagonals are negative.
    copy : bool, optional
        Return a copy. Diagonal is written in-place if false.
        Default is True.

    Returns
    -------
    Array with diagonal filled.

    Notes
    -----
    Similar to numpy.fill_diagonal, but allows for kth diagonals as well.
    This solution was borrowed from
    http://stackoverflow.com/questions/9958577/changing-the-values-of-the-diagonal-of-a-matrix-in-numpy

    """
    if copy:
        arr = arr.copy()
    start = max(i, -arr.shape[1] * i)
    stop = max(0, arr.shape[1] - i) * arr.shape[1]
    step = arr.shape[1] + 1
    arr.flat[start:stop:step] = x
    return arr


def mutual_weight(G, u, v, weight=None):
    """Returns the sum of the weights of the edge from `u` to `v` and
    the edge from `v` to `u` in `G`.

    `weight` is the edge data key that represents the edge weight. If
    the specified key is `None` or is not in the edge data for an edge,
    that edge is assumed to have weight 1.

    Pre-conditions: `u` and `v` must both be in `G`.

    """
    try:
        a_uv = G[u][v].get(weight, 1)
    except KeyError:
        a_uv = 0
    try:
        a_vu = G[v][u].get(weight, 1)
    except KeyError:
        a_vu = 0
    return a_uv + a_vu


def add_upload_buffer(GatewayARN=None, DiskIds=None):
    """
    Configures one or more gateway local disks as upload buffer for a specified gateway. This operation is supported for the stored volume, cached volume and tape gateway architectures.
    In the request, you specify the gateway Amazon Resource Name (ARN) to which you want to add upload buffer, and one or more disk IDs that you want to configure as upload buffer.
    See also: AWS API Documentation

    Examples
    Configures one or more gateway local disks as upload buffer for a specified gateway.
    Expected Output:

    :example: response = client.add_upload_buffer(
        GatewayARN='string',
        DiskIds=[
            'string',
        ]
    )

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation to return a list of gateways for your account and region.

    :type DiskIds: list
    :param DiskIds: [REQUIRED]
            (string) --

    :rtype: dict
    :return: {
        'GatewayARN': 'string'
    }

    """
    pass


def class_folder_tex(f, b_matrix, d_matrix):
    """
    Wirte in latex file 3 highest values of brwosing and diversifying matrices
    """
    f.write('\n% 7. Diversifying patterns according to folder classification')
    digit_dic = {'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4':
        'Four', '5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9':
        'Nine'}
    i = 0
    for row in b_matrix.itertuples():
        i += 1
        f.write('\n\\newcommand{\\%s}{%s}' % ('FolderBP%sName' % digit_dic[
            str(i)], '%s$\\rightarrow$%s' % (row.folder_origin, row.
            folder_destination)))
        f.write('\n\\newcommand{\\%s}{%0.1f}' % ('FolderBP%sValue' %
            digit_dic[str(i)], 100.0 * row.data))
    i = 0
    for row in d_matrix.itertuples():
        i += 1
        f.write('\n\\newcommand{\\%s}{%s}' % ('FolderDP%sName' % digit_dic[
            str(i)], '%s$\\rightarrow$%s' % (row.folder_origin, row.
            folder_destination)))
        f.write('\n\\newcommand{\\%s}{%0.1f}' % ('FolderDP%sValue' %
            digit_dic[str(i)], 100.0 * row.data))
    return f


@classmethod
def device_by_name(cls, name):
    """Returns the Device with name from registered devices."""
    for dev in cls.devices:
        if dev.name == name:
            return dev
    raise IndexError('No Device with name ' + name)


def delete_artifact(client, bucket, key='alppbBuilder/alppb.zip'):
    """
    Deletes the artifact from Amazon S3 built by alppb.

    Parameters
    ----------
    client : botocore.client.S3
        A boto3 client for S3.
    bucket : str
        Name of the bucket the artifact exists in.
    key: str
        The S3 key of the artifact to delete from the bucket. Defaults to
        "alppbBuilder/alppb.zip".

    Returns
    -------
    """
    print('Deleting {} from S3 bucket {}...'.format(key, bucket))
    client.delete_object(Bucket=bucket, Key=key)


def do_overlap(start1: int, endex1: int, start2: int, endex2: int) ->bool:
    """Do ranges overlap?

    Arguments:
        start1 (int):
            Inclusive start index of the first range.

        endex1 (int):
            Exclusive end index of the first range.

        start2 (int):
            Inclusive start index of the second range.

        endex2 (int):
            Exclusive end index of the second range.

    Returns:
        bool: Ranges do overlap.

    Note:
        Start and end of each range are sorted before the final comparison.

    Examples:
        >>> do_overlap(0, 4, 4, 8)
        False

        >>> do_overlap(0, 4, 2, 6)
        True

        >>> do_overlap(4, 0, 2, 6)
        True

        >>> do_overlap(8, 4, 4, 0)
        False
    """
    if start1 > endex1:
        start1, endex1 = endex1, start1
    if start2 > endex2:
        start2, endex2 = endex2, start2
    return endex1 > start2 and endex2 > start1


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def set_solid(actor):
    """
    set an actor's look to solid

    :param actor:

    """
    actor.wireframe(value=False)


def check_getattr(ob, name):
    """
        Check whether attribute access is allowed.

        If a checker implements ``__setitem__``, then ``__setitem__``
        will be called rather than ``check`` to ascertain whether an
        operation is allowed. This is a hack that allows significantly
        greater performance due to the fact that low-level operator
        access is much faster than method access.

        :raises: :class:`Unauthorized`
        :raises: :class:`Forbidden`
        :return: Nothing
        """


def minutes(datetime):
    """
    Returns the minutes component for the given datetime value, in local time.
    """
    return datetime.minute()


def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.
    If no true value is found, returns *default*
    http://docs.python.org/3.4/library/itertools.html#itertools-recipes
    """
    return next(filter(pred, iterable), default)


def Shutdown(connection, pipeName):
    """Shutdown debugging messages on the given pipe."""
    cursor = connection.cursor()
    cursor.callproc('pkg_Debug.Shutdown', (pipeName,))


@staticmethod
def get_service_type():
    """Return the service type.

        This returns a list because you can have services with more types,
        like volume, volumev2, volumev3.
        """
    return []


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

    Like 'git describe --tags --dirty --always'.

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


def _distanceFV(v1: list, v2: list) ->float:
    """
        Computes the distance between two feature vectors
    """
    ret = 0
    for i in range(len(v1)):
        ret += abs(v1[i] - v2[i])
    return ret / 2.0


def truecolor(red, green, blue, background):
    """ Produce an RGB color escape sequence to prepend strings in terminal.

    Thanks to Antti Haapala for this answer to an unrelated question:
    https://stackoverflow.com/a/45782972/7846185
    """
    return f'\x1b[{48 if background else 38};2;{red};{green};{blue}m'


@staticmethod
def _prec_param(prec):
    """Determine parameter name for specified precision"""
    return 'with_%s_prec' % prec.replace('-', '_').replace('_precision', '')


def dpt_to_int(dpt: str) ->int:
    """Convert a dpt to an int"""
    if type(dpt) is int:
        return int(dpt)
    if dpt[0] == 'Z':
        return 0
    if dpt[1].upper() == 'A' or dpt[1].upper() == 'B':
        return 20
    else:
        return int(dpt)


def shortened_cmd(cmd: str, length: int) ->str:
    """Shorten the command to the specified length."""
    if len(cmd) + 2 <= length:
        return '`' + cmd + '`'
    return '`' + cmd[:length - 5] + '...`'


def _clear_entity_type_registry(entity, **kwargs):
    """Clear the given database/collection object's type registry."""
    codecopts = entity.codec_options.with_options(type_registry=None)
    return entity.with_options(codec_options=codecopts, **kwargs)


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 '+'


def suppress_output_before_run(app):
    """
    This is a ``post_argument_parsing`` hook that suppresses console output if
    the ``YamlOutputHandler`` is triggered via command line.

    :param app: The application object.

    """
    if not hasattr(app.pargs, 'output_handler_override'):
        return
    elif app.pargs.output_handler_override == 'yaml':
        app._suppress_output()


def create_circle(bm: 'bmesh.types.BMesh', cap_ends: bool, cap_tris: bool,
    segments: int, radius: float, matrix: 'mathutils.Matrix', calc_uvs: bool
    ) ->dict:
    """Creates a Circle.

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param cap_ends: whether or not to fill in the ends with faces
    :type cap_ends: bool
    :param cap_tris: fill ends with triangles instead of ngons
    :type cap_tris: bool
    :param segments: Undocumented.
    :type segments: int
    :param radius: Radius of the circle.
    :type radius: float
    :param matrix: matrix to multiply the new geometry with
    :type matrix: 'mathutils.Matrix'
    :param calc_uvs: calculate default UVs
    :type calc_uvs: bool
    :return:  verts: output vertstype list of (bmesh.types.BMVert)
    """
    pass


def relative_roughness(D, roughness=1.52e-06):
    """Calculates relative roughness `eD` using a diameter and the roughness
    of the material of the wall. Default roughness is that of steel.

    .. math::
        eD=\\frac{\\epsilon}{D}

    Parameters
    ----------
    D : float
        Diameter of pipe, [m]
    roughness : float, optional
        Roughness of pipe wall [m]

    Returns
    -------
    eD : float
        Relative Roughness, [-]

    Examples
    --------
    >>> relative_roughness(0.5, 1E-4)
    0.0002

    References
    ----------
    .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
       Eighth Edition. McGraw-Hill Professional, 2007.
    .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    """
    return roughness / D


def _median(data):
    """Return the median (middle value) of numeric data.

	When the number of data points is odd, return the middle data point.
	When the number of data points is even, the median is interpolated by
	taking the average of the two middle values:

	>>> median([1, 3, 5])
	3
	>>> median([1, 3, 5, 7])
	4.0

	"""
    data = sorted(data)
    n = len(data)
    if n == 0:
        raise ValueError('no median for empty data')
    if n % 2 == 1:
        return data[n // 2]
    else:
        i = n // 2
        return (data[i - 1] + data[i]) / 2


def _friendly_name_to_mate(module_name):
    """Slightly hacky code to convert friendly mo.objects names to the mate4dummies mo.mate format"""
    all_modules = {'channel': '_Channel', 'clock': '_Clock', 'experiment':
        '_Experiment', 'gap_voltage_control': '_GapVoltageControl', 'pll':
        '_PLLControl', 'piezo_control': '_PiezoControl', 'regulator':
        '_Regulator', 'view': '_View', 'xy_scanner': '_XYScanner',
        'spectroscopy': '_Spectroscopy'}
    if module_name in all_modules.keys():
        mate_name = all_modules[module_name]
    elif module_name in all_modules.values():
        mate_name = module_name
    else:
        raise ValueError(
            f'Requested module {module_name} must be one of {all_modules.keys()}'
            )
    return mate_name


def unmangle_name(s: str) ->str:
    """
    Convert a name with ``$uXXXX`` character runs into their original forms, which may not
    necessarily be safe DAML identifiers.

    :param s: The string to interpret.
    :return: A new string with the appropriate substitutions.
    """
    return s.replace('$u002b', '+').replace('$u005b', '[').replace('$u005d',
        ']').replace('$u003c', '<').replace('$u003e', '>').replace('$u003a',
        ':').replace('$u0022', '"').replace('$u0028', '(').replace('$u0029',
        ')').replace('$u002f', '/').replace('$u002c', ',').replace('$u003d',
        '=')


def make_paths_absolute():
    """Make all paths to external files absolute

    """
    pass


@staticmethod
def format_row(row):
    """
        Row formatter, should be implemented in subclasses
        """
    return row


def subtract1D(q, i, ierr, value):
    """
    subtract a background value
    """
    return q, i - value, ierr


def yggtime_lang():
    """Plot timing statistics comparing the different languages."""
    from yggdrasil import timing
    timing.plot_scalings(compare='language')


def space_space_fix(text):
    """Replace "space-space" with "space".

    Args:
        text (str): The string to work with

    Returns:
        The text with the appropriate fix.
    """
    space_space = '  '
    space = ' '
    while space_space in text:
        text = text.replace(space_space, space)
    return text


def setNodeAttribute(node, attrname, value):
    """get named attribute from DOM node"""
    return node.setAttribute(attrname, value)


def document_iters_to_multipart_byteranges(ranges_iter, boundary):
    """
    Takes an iterator of range iters and yields a multipart/byteranges MIME
    document suitable for sending as the body of a multi-range 206 response.

    See document_iters_to_http_response_body for parameter descriptions.
    """
    if not isinstance(boundary, bytes):
        boundary = boundary.encode('ascii')
    divider = b'--' + boundary + b'\r\n'
    terminator = b'--' + boundary + b'--'
    for range_spec in ranges_iter:
        start_byte = range_spec['start_byte']
        end_byte = range_spec['end_byte']
        entity_length = range_spec.get('entity_length', '*')
        content_type = range_spec['content_type']
        part_iter = range_spec['part_iter']
        if not isinstance(content_type, bytes):
            content_type = str(content_type).encode('utf-8')
        if not isinstance(entity_length, bytes):
            entity_length = str(entity_length).encode('utf-8')
        part_header = b''.join((divider, b'Content-Type: ', content_type,
            b'\r\n', b'Content-Range: ', b'bytes %d-%d/%s\r\n' % (
            start_byte, end_byte, entity_length), b'\r\n'))
        yield part_header
        for chunk in part_iter:
            yield chunk
        yield b'\r\n'
    yield terminator


def assert_awaited_once(_mock_self, *args, **kwargs):
    """
        Assert that the mock was awaited exactly once.

        .. versionadded:: 0.12
        """
    self = _mock_self
    if not self.await_count == 1:
        msg = "Expected '%s' to have been awaited once. Awaited %s times." % (
            self._mock_name or 'mock', self.await_count)
        raise AssertionError(msg)


def unicode_sorter(input):
    """ This function implements sort keys for the german language according to
    DIN 5007."""
    key1 = input.lower()
    key1 = key1.replace(u'ä', u'a')
    key1 = key1.replace(u'ö', u'o')
    key1 = key1.replace(u'ü', u'u')
    key1 = key1.replace(u'ß', u'ss')
    return key1


@classmethod
def datablock(cls, o):
    """
            Retrieve datablock from base object
            return
                datablock when found
                None when not found
            usage:
                class_name.datablock(object) from outside world
                self.__class__.datablock(object) from instance
        """
    try:
        return getattr(o.data, cls.__name__)[0]
    except:
        pass
    return None