@staticmethod
def _primary_keys_as_dict(obj):
    """Turn the primary keys for self into get parameters for web access."""
    ret = {}
    for pkey in obj.get_primary_keys():
        if pkey == 'id':
            ret['_id'] = obj.to_hash()['_id']
        else:
            ret[pkey] = obj.to_hash()[pkey]
    return ret


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def unix_time_stamp_to_matlab_datenum(timestamp):
    """
    convert dtype to maltab class string
    """
    return timestamp / 86400 + 719529


def _move_focus(pymux, cli, get_x, get_y):
    """ Move focus of the active window. """
    window = pymux.arrangement.get_active_window(cli)
    try:
        write_pos = pymux.layout_manager.pane_write_positions[window.
            active_pane]
    except KeyError:
        pass
    else:
        x = get_x(write_pos)
        y = get_y(write_pos)
        for pane, wp in pymux.layout_manager.pane_write_positions.items():
            if (wp.xpos <= x < wp.xpos + wp.width and wp.ypos <= y < wp.
                ypos + wp.height):
                window.active_pane = pane
                return


def drectangle(p, x1, x2, y1, y2):
    """Signed distance function for rectangle with corners (x1,y1), (x2,y1),
    (x1,y2), (x2,y2).

    This has an incorrect distance to the four corners. See drectangle0 for a
    true distance function.
    """
    return -min(min(min(-y1 + p[:, (1)], y2 - p[:, (1)]), -x1 + p[:, (0)]),
        x2 - p[:, (0)])


def npv(rate, flow, time_index, offset=1):
    """"Returns the Net Present Value (NPV) of a cash flow with equally spaced periods. The flow parameter must contain a series of periodic payments (negative values) and inflows (positive values), indexed by time_index.
        The optional offset parameter especifies the offset of the first value relative to the current time period. By default, offset is set to 1, indicating that the first value is discounted as if it is one step in the future
    """
    _number_of_periods = time_index.pos + offset
    _present_values = flow / (1 + rate) ** _number_of_periods
    _npv = _present_values.sum(axis=time_index)
    return _npv


def context_toggle(data_path: str=''):
    """Toggle a context value

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    """
    pass


def batch_delete_limit_error(nodes_requested, max_limit):
    """
    Return validation error string given when nodes > limit are deleted
    in a single call.

    :param int nodes_requested: Number of nodes requested to be deleted
    :param int max_limit: Maximum number of nodes allowed to be deleted
    :rtype: ``str``
    """
    fmt = (
        'Request to delete {} nodes exceeds the account limit BATCH_DELETE_LIMIT of {} please attempt to delete fewer then 10 nodes'
        )
    return fmt.format(nodes_requested, max_limit)


def find_object(mod, path):
    """Finds object among present within module "mod" given path specification within

    Returns
    -------

    parent, obj_name, obj
    """
    obj = mod
    for obj_name in path.split('.'):
        parent = obj
        obj = getattr(parent, obj_name)
    return parent, obj_name, obj


def project_from_view(orthographic: bool=False, camera_bounds: bool=True,
    correct_aspect: bool=True, clip_to_bounds: bool=False, scale_to_bounds:
    bool=False):
    """Project the UV vertices of the mesh as seen in current 3D view

    :param orthographic: Orthographic, Use orthographic projection
    :type orthographic: bool
    :param camera_bounds: Camera Bounds, Map UVs to the camera region taking resolution and aspect into account
    :type camera_bounds: bool
    :param correct_aspect: Correct Aspect, Map UVs taking image aspect ratio into account
    :type correct_aspect: bool
    :param clip_to_bounds: Clip to Bounds, Clip UV coordinates to bounds after unwrapping
    :type clip_to_bounds: bool
    :param scale_to_bounds: Scale to Bounds, Scale UV coordinates to bounds after unwrapping
    :type scale_to_bounds: bool
    """
    pass


def reset_swift_session():
    """Reset the global session variable.

    Mostly useful for unit tests.
    """
    global SWIFT_SESSION
    SWIFT_SESSION = None


def in_range(val, min_val, max_val):
    """Make sure val is within min_val, max_val

    >>> in_range(5, 0, 10)
    5

    >>> in_range(0, -10, 10)
    0

    >>> in_range(0, 10, 20)
    10

    >>> in_range(100, 0, 10)
    10
    """
    return min(max(val, min_val), max_val)


def list_from_setting(config, setting):
    """Split configuration setting"""
    value = config.get(setting)
    if not value:
        return None
    return value.split()


def update_package_data(distribution):
    """update build_py options to get package_data changes"""
    build_py = distribution.get_command_obj('build_py')
    build_py.finalize_options()


def add_arguments(parser):
    """ Adds batcher arguments to the parser

    This function gets the parser containing user inputs
    It adds arguments and returns a parser
    The parsing of args is performed in the main script
    """
    parser.add_argument('--batch-size', dest='batch_size', action='store',
        default=1000, type=int, help='Number of elements in each batch')
    parser.add_argument('--batch-start', dest='batch_start', action='store',
        default=0, type=int, help='starts importing batches from a given batch'
        )
    parser.add_argument('--max-batches', dest='max_batches', action='store',
        default=None, type=int, help='Maximum amount of batches imported')
    parser.add_argument('--percentage', dest='percentage', action='store',
        default=None, type=int, help=
        'Percentage of elements to be randomly sampled (0-100%%)')
    parser.add_argument('--seed', dest='seed', action='store', default=None,
        type=int, help='Seed to reproduce last imported batch')


def H_acceptor_count(mol):
    """Hydrogen bond acceptor count """
    mol.require('Valence')
    return sum(1 for _, a in mol.atoms_iter() if a.H_acceptor)


def product(n=1):
    """
        nested for each loops repeated `n` times

        @param n: number of repetitions (default: 1)
        """


def try_until(*args, **kw):
    """
    try_until(f1, f2, f3...) attempts to return f1(); if this raises an Exception during its
      evaluation, however, it attempts to return f2(); etc. If none of the functions succeed, then
      an exception is raised.

    The following optional arguments may be given:
      * check (default: None) may specify a function of one argument that must return True when the
        passed value is an acceptable return value; for example, an option of
        `check=lambda x: x is not None`  would indicate that a function that returns None should not
        be considered to have succeeded.
    """
    if 'check' in kw:
        check = kw.pop('check')
    else:
        check = None
    if len(kw) > 0:
        raise ValueError('unrecognized options given to try_until')
    for f in args:
        if not hasattr(f, '__call__'):
            raise ValueError('function given to try_until is not callable')
        try:
            rval = f()
            if check is None or check(rval):
                return rval
        except Exception:
            raise
    raise ValueError('try_until failed to find a successful function return')


def _remove_duplicates(objects):
    """Removes duplicate objects from collection.

    http://www.peterbe.com/plog/uniqifiers-benchmark.
    """
    seen, uniq = set(), []
    for obj in objects:
        obj_id = id(obj)
        if obj_id in seen:
            continue
        seen.add(obj_id)
        uniq.append(obj)
    return uniq


def boolean_flag(parser, name, default=False, help_msg=None):
    """
    Add a boolean flag to argparse parser.

    :param parser: (argparse.Parser) parser to add the flag to
    :param name: (str) --<name> will enable the flag, while --no-<name> will disable it
    :param default: (bool) default value of the flag
    :param help_msg: (str) help string for the flag
    """
    dest = name.replace('-', '_')
    parser.add_argument('--' + name, action='store_true', default=default,
        dest=dest, help=help_msg)
    parser.add_argument('--no-' + name, action='store_false', dest=dest)


def stop_criteria(index, date, flags):
    """Check stop criteria

    Args:
        index (int): index of current element
        date (datetime): date of current element
        flags (dict): List of flags:
            from_date: use only requests after specified date
            to_date: use only requests before specified date
            limit: use N requests from the beginning of file or specified date

    Returns:
        bool: returns true if stop criteria is achieved
    """
    result = False
    if 'to_date' in flags:
        result = date >= flags['to_date']
    if 'limit' in flags:
        result = index >= flags['limit']
    return result


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 filterGenes(genes, gtf, strand, orientation='sense', singlefeats=False):
    """ filters genes on whether they are sense or anti-sense to a feature """
    filteredgenes = list()
    for gene in genes:
        if gene in gtf.genes:
            if orientation == 'sense':
                if gtf.strand(gene) == strand:
                    filteredgenes.append(gene)
            elif gtf.strand(gene) != strand:
                filteredgenes.append(gene)
            if singlefeats and len(filteredgenes) > 1:
                filteredgenes = list()
    return filteredgenes


def xyz_to_xy(xyz):
    """
    Convert xyz tuple to xy
    """
    total = sum(xyz)
    return xyz[0] / total, xyz[1] / total


def bake_all(bake: bool=True):
    """Bake all physics

    :param bake: Bake
    :type bake: bool
    """
    pass


def _escape_hive(val):
    """HiveParamEscaper

     https://github.com/dropbox/PyHive/blob/master/pyhive/hive.py"""
    return "'{0}'".format(val.replace('\\', '\\\\').replace("'", "\\'").
        replace('\r', '\\r').replace('\n', '\\n').replace('\t', '\\t'))


def __getitem__(node):
    """Obtain a manifest instance for a given binary node.

        Equivalent to calling ``self.get('', node)``.

        The returned object conforms to the ``imanifestrevisionstored``
        interface.
        """


def getValues(currentValues, current, total):
    """
    Return either the current values (for this horizon) or all computed results

    Parameters
    ----------
    currentValues : Boolean
        True: return 'current', False: return 'total'
    current : Pointer
        Pointer to the current values
    total : Pointer
        Pointer to the total values
    """
    if currentValues:
        return current
    else:
        return total


@staticmethod
def truncate_ellipsis(text: str, length: int) ->str:
    """Truncate a string with ellipsis added to the end if needed."""
    if len(text) <= length:
        return text
    return text[:length - 1] + '…'


@classmethod
def from_url(cls, es_url):
    """Initialize an ElasticSearch with single url"""
    hosts = [es_url]
    return cls(hosts=hosts)


def FK_jacobian(robot_parameters, nodes_angles):
    """Retourne le jacobien de la FK"""
    pass


def get_linux_mounts(module, mntinfo_file='/proc/self/mountinfo'):
    """Gather mount information"""
    try:
        f = open(mntinfo_file)
    except IOError:
        return
    lines = map(str.strip, f.readlines())
    try:
        f.close()
    except IOError:
        module.fail_json(msg='Cannot close file %s' % mntinfo_file)
    mntinfo = {}
    for line in lines:
        fields = line.split()
        record = {'id': int(fields[0]), 'parent_id': int(fields[1]), 'root':
            fields[3], 'dst': fields[4], 'opts': fields[5], 'fs': fields[-3
            ], 'src': fields[-2]}
        mntinfo[record['id']] = record
    mounts = {}
    for mnt in mntinfo.values():
        if mnt['parent_id'] != 1 and mnt['parent_id'] in mntinfo:
            m = mntinfo[mnt['parent_id']]
            if len(m['root']) > 1 and mnt['root'].startswith('%s/' % m['root']
                ):
                mnt['root'] = mnt['root'][len(m['root']):]
            if m['dst'] != '/':
                mnt['root'] = '%s%s' % (m['dst'], mnt['root'])
            src = mnt['root']
        else:
            src = mnt['src']
        record = {'dst': mnt['dst'], 'src': src, 'opts': mnt['opts'], 'fs':
            mnt['fs']}
        mounts[mnt['dst']] = record
    return mounts


@staticmethod
def __set_max_window_size(tsocket, command, option):
    """
        Set Window size to resolve line width issue
        Set Windows size command: IAC SB NAWS <16-bit value> <16-bit value> IAC SE
        --> inform the Telnet server of the window width and height.
        Refer to https://www.ietf.org/rfc/rfc1073.txt
        :param tsocket: telnet socket object
        :param command: telnet Command
        :param option: telnet option
        :return: None
        """
    from telnetlib import DO, DONT, IAC, WILL, WONT, NAWS, SB, SE
    import struct
    if option == NAWS:
        width = struct.pack('H', 65000)
        height = struct.pack('H', 5000)
        tsocket.send(IAC + WILL + NAWS)
        tsocket.send(IAC + SB + NAWS + width + height + IAC + SE)
    elif command in (DO, DONT):
        tsocket.send(IAC + WONT + option)
    elif command in (WILL, WONT):
        tsocket.send(IAC + DONT + option)


def split_fields(fields_str, fieldwidth=8):
    """Split `fields_str` into fields of length `fieldwidth`
    """
    fields = []
    for start in range(0, len(fields_str), fieldwidth):
        stop = start + fieldwidth
        fields.append(fields_str[start:stop])
    return fields


def is_dict_type(value):
    """Treat any dict, MergeDict, MultiDict instance as dict type"""
    return isinstance(value, dict) or value.__class__.__name__ in ('MergeDict',
        'MultiDict')


def calculate_engine_idle_fuel_consumption(idle_fuel_consumption_model,
    params=None):
    """
    Calculates fuel consumption at hot idle engine speed [g/s].

    :param idle_fuel_consumption_model:
        Idle fuel consumption model.
    :type idle_fuel_consumption_model: IdleFuelConsumptionModel

    :param params:
        CO2 emission model parameters (a2, b2, a, b, c, l, l2, t, trg).

        The missing parameters are set equal to zero.
    :type params: dict

    :return:
        Fuel consumption at hot idle engine speed [g/s].
    :rtype: float
    """
    return idle_fuel_consumption_model.consumption(params)[0]


def have_pyrex():
    """
    Return True if Cython or Pyrex can be imported.
    """
    pyrex_impls = 'Cython.Distutils.build_ext', 'Pyrex.Distutils.build_ext'
    for pyrex_impl in pyrex_impls:
        try:
            __import__(pyrex_impl, fromlist=['build_ext']).build_ext
            return True
        except Exception:
            pass
    return False


def is_a_sequence(var, allow_none=False):
    """ Returns True if var is a list or a tuple (but not a string!)
    """
    return isinstance(var, (list, tuple)) or var is None and allow_none


def confine(x, low, high):
    """Confine x to [low,high]. Values outside are set to low/high.
See also restrict."""
    y = x.copy()
    y[y < low] = low
    y[y > high] = high
    return y


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

        :param LookupError val:
        :rtype: DownloadError
        """
    return cls('path', val)


def window_hann(N):
    """Hann window (or Hanning). (wrapping of numpy.bartlett)

    :param int N: window length

    The Hanning window is also known as the Cosine Bell. Usually, it is called
    Hann window, to avoid confusion with the Hamming window.

    .. math:: w(n) =  0.5\\left(1- \\cos\\left(\\frac{2\\pi n}{N-1}\\right)\\right)
               \\qquad 0 \\leq n \\leq M-1

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'hanning')

    .. seealso:: numpy.hanning, :func:`create_window`, :class:`Window`.
    """
    from numpy import hanning
    return hanning(N)


@staticmethod
def colored_text(str, color=33):
    """
        format text with color
        """
    return f'\x1b[{color}m{str}\x1b[0m'


@staticmethod
def _parse_coverage(header_str):
    """Attempts to retrieve the coverage value from the header string.

        It splits the header by "_" and then screens the list backwards in
        search of the first float value. This will be interpreted as the
        coverage value. If it cannot find a float value, it returns None.
        This search methodology is based on the strings of assemblers
        like spades and skesa that put the mean kmer coverage for each
        contig in its corresponding fasta header.

        Parameters
        ----------
        header_str : str
            String

        Returns
        -------
        float or None
            The coverage value for the contig. None if it cannot find the
            value in the provide string.
        """
    cov = None
    for i in header_str.split('_')[::-1]:
        try:
            cov = float(i)
            break
        except ValueError:
            continue
    return cov


def update_account(patchOperations=None):
    """
    Changes information about the current  Account resource.
    See also: AWS API Documentation

    :example: response = client.update_account(
        patchOperations=[
            {
                'op': 'add'|'remove'|'replace'|'move'|'copy'|'test',
                'path': 'string',
                'value': 'string',
                'from': 'string'
            },
        ]
    )

    :type patchOperations: list
    :param patchOperations: A list of update operations to be applied to the specified resource and in the order specified in this list.
            (dict) -- A single patch operation to apply to the specified resource. Please refer to http://tools.ietf.org/html/rfc6902#section-4 for an explanation of how each operation is used.
            op (string) --An update operation to be performed with this PATCH request. The valid value can be 'add', 'remove', or 'replace'. Not all valid operations are supported for a given resource. Support of the operations depends on specific operational contexts. Attempts to apply an unsupported operation on a resource will return an error message.
            path (string) --The op operation's target, as identified by a JSON Pointer value that references a location within the targeted resource. For example, if the target resource has an updateable property of {'name':'value'} , the path for this property is /name . If the name property value is a JSON object (e.g., {'name': {'child/name': 'child-value'}} ), the path for the child/name property will be /name/child~1name . Any slash ('/') character appearing in path names must be escaped with '~1', as shown in the example above. Each op operation can have only one path associated with it.
            value (string) --The new target value of the update operation. When using AWS CLI to update a property of a JSON value, enclose the JSON object with a pair of single quotes in a Linux shell, e.g., '{'a': ...}'. In a Windows shell, see Using JSON for Parameters .
            from (string) --Not supported.

    :rtype: dict
    :return: {
        'cloudwatchRoleArn': 'string',
        'throttleSettings': {
            'burstLimit': 123,
            'rateLimit': 123.0
        },
        'features': [
            'string',
        ],
        'apiKeyVersion': 'string'
    }

    :returns:
    (string) --

    """
    pass


@classmethod
def from_activity(cls, activity, commit=None):
    """Create an instance from the activity."""
    from .agents import SoftwareAgent
    agent = SoftwareAgent.from_commit(activity.commit)
    return cls(plan=activity.__association_cls__(commit=commit or activity.
        commit, client=activity.client, path=activity.path, activity=
        activity), agent=agent, id=activity._id + '/association')


def replacing_yield(o, attr, val):
    """Context manager to temporarily replace an attribute"""
    old = getattr(o, attr)
    try:
        yield setattr(o, attr, val)
    finally:
        setattr(o, attr, old)


@classmethod
def get_result(cls, close=None, refresh=None, goto=None, goto_target=None,
    goto_target_type=None, next_action=None):
    """
        The value returned by run(button) will be inspected by callers to
        decide how they should react.
        This helper class method will generate a result matching its args:
            close: (bool)
                Prevent the action dialog to be closed when set to False
            refresh: (bool)
                Force a reload of the parent page avec dialog close
                (This should not be needed anymore thanks to touch() calls...)
            goto: (oid)
                Force the caller to load the given oid page.
            goto_target: (string or "_NEW_")
                The string identifer of the view targeted by the goto directive.
                The default targeted view is the current one or the one that created
                the action dialog. Spcecifying a target can be usefull to alter
                another view. If the specified target is not found, a new view
                will be created with this identifier so that further use of the
                action will affect this new view.
                The special identifier "_NEW_" can be used to force the creation
                of a new view.
            goto_target_type: (string)
                The type of the view targeted by the goto directive.
                Default is 'Flow'
                An easy way to find out the available type names is to use
                a obviously invalid value like "???" and look for the error
                message: it will contain a list of available type names.
            next_action: (oid)
                Force the dialog to not close but load the ui for the action
                with the given oid.
                This is the way to implement "Wizard Pages"

        """
    ret = {}
    if close is not None:
        ret['close'] = close and True or False
    if refresh is not None:
        ret['refresh'] = refresh and True or False
    if goto is not None:
        ret['goto'] = goto
    if goto_target is not None:
        ret['goto_target'] = goto_target
    if goto_target_type is not None:
        ret['goto_target_type'] = goto_target_type
    if next_action is not None:
        ret['next_action'] = next_action
    return ret


@staticmethod
def _find_db_extra(expanded_path):
    """Some browser's profiles require path manipulation"""
    return expanded_path


def validate_tree(G, results):
    """Validate that jobs executed after their dependencies."""
    for node in G:
        started = results[node].metadata.started
        for parent in G.predecessors(node):
            finished = results[parent].metadata.completed
            assert started > finished, '%s should have happened after %s' % (
                node, parent)


@classmethod
def bases(cls):
    """Return all the definitions this defintion is derived from."""
    if not hasattr(cls, '_bases'):
        return {}
    return dict(cls._bases)


@staticmethod
def parent(entry):
    """Determine the parent for a file_id (used as a key method)"""
    if entry is None:
        return None
    return entry.parent_id


def put_flat_sharp(step, acc):
    """get a step and its acc and return the note in tpc notation, return str"""
    ret_note = step
    ret_acc = acc
    if ret_acc > 0:
        for l in range(ret_acc):
            ret_note = ret_note + '#'
    if ret_acc < 0:
        ret_acc = abs(ret_acc)
        for l in range(ret_acc):
            ret_note = ret_note + 'b'
    return ret_note


@classmethod
def block_header(cls, block, height):
    """Return the block header bytes"""
    deserializer = cls.DESERIALIZER(block)
    return deserializer.read_header(height, cls.BASIC_HEADER_SIZE)


def _get_uid(context):
    """Returns a unique context identifier for logging purposes for a plugin.
    """
    if 'uid' in context:
        return context['uid']
    return context.get('ip', '')


def _split_header_entry(entry):
    """
    Split 3ds header entries by '=' character. If multiple values split
    those by ';' character.
    """
    key_str, val_str = entry.split('=', 1)
    if ';' in val_str:
        return key_str, val_str.strip('"').split(';')
    else:
        return key_str, val_str.strip('"')


@classmethod
def field_from_django_field(cls, field_name, django_field, readonly):
    """
        Returns a Resource Field instance for the given Django model field.
        """
    FieldWidget = cls.widget_from_django_field(django_field)
    widget_kwargs = cls.widget_kwargs_for_field(field_name)
    field = cls.DEFAULT_RESOURCE_FIELD(attribute=field_name, column_name=
        field_name, widget=FieldWidget(**widget_kwargs), readonly=readonly,
        default=django_field.default)
    return field


def QMethod(func):
    """Decorator for exposing methods that can be called by clients"""
    func.is_client_accessible = True
    return func


def readGUPPIHeader(filehandle):
    """
    Read in a GUPPI header at the start of a VDIF file from the VLA.  The
    contents of the header are returned as a dictionary.
    """
    header = {}
    while True:
        line = filehandle.read(80)
        if line[:3] == 'END':
            break
        elif line[:8] == 'CONTINUE':
            junk, value2 = line.split(None, 1)
            value = '%s%s' % (value[:-1], value2[:-1])
        else:
            name, value = line.split('=', 1)
            name = name.strip()
        try:
            value = int(value, 10)
        except:
            try:
                value = float(value)
            except:
                value = value.strip().replace("'", '')
        header[name.strip()] = value
    header['OBSBW'] *= 1000000.0
    header['OBSFREQ'] *= 1000000.0
    return header


def underscore_to_camelcase(keyword):
    """Change underscore '_' to CamelCase string in string

    param keyword: string which has to be modified as
            above

    return: string. Example one_two changes to OneTwo
    """
    parts = keyword.split('_')
    keyword = ''
    for part in parts:
        if part == 'db':
            part = 'DB'
        else:
            part = part.capitalize()
        keyword += part
    return keyword


def get_trace_graph(TraceIds=None, NextToken=None):
    """
    Retrieves a service graph for one or more specific trace IDs.
    See also: AWS API Documentation

    :example: response = client.get_trace_graph(
        TraceIds=[
            'string',
        ],
        NextToken='string'
    )

    :type TraceIds: list
    :param TraceIds: [REQUIRED]
            Trace IDs of requests for which to generate a service graph.
            (string) --

    :type NextToken: string
    :param NextToken: Pagination token. Not used.

    :rtype: dict
    :return: {
        'Services': [
            {
                'ReferenceId': 123,
                'Name': 'string',
                'Names': [
                    'string',
                ],
                'Root': True|False,
                'AccountId': 'string',
                'Type': 'string',
                'State': 'string',
                'StartTime': datetime(2015, 1, 1),
                'EndTime': datetime(2015, 1, 1),
                'Edges': [
                    {
                        'ReferenceId': 123,
                        'StartTime': datetime(2015, 1, 1),
                        'EndTime': datetime(2015, 1, 1),
                        'SummaryStatistics': {
                            'OkCount': 123,
                            'ErrorStatistics': {
                                'ThrottleCount': 123,
                                'OtherCount': 123,
                                'TotalCount': 123
                            },
                            'FaultStatistics': {
                                'OtherCount': 123,
                                'TotalCount': 123
                            },
                            'TotalCount': 123,
                            'TotalResponseTime': 123.0
                        },
                        'ResponseTimeHistogram': [
                            {
                                'Value': 123.0,
                                'Count': 123
                            },
                        ],
                        'Aliases': [
                            {
                                'Name': 'string',
                                'Names': [
                                    'string',
                                ],
                                'Type': 'string'
                            },
                        ]
                    },
                ],
                'SummaryStatistics': {
                    'OkCount': 123,
                    'ErrorStatistics': {
                        'ThrottleCount': 123,
                        'OtherCount': 123,
                        'TotalCount': 123
                    },
                    'FaultStatistics': {
                        'OtherCount': 123,
                        'TotalCount': 123
                    },
                    'TotalCount': 123,
                    'TotalResponseTime': 123.0
                },
                'DurationHistogram': [
                    {
                        'Value': 123.0,
                        'Count': 123
                    },
                ]
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


@classmethod
def getTimezone(cls):
    """Returns the pytz timezone for the market session."""
    return cls.timezone


@staticmethod
def __has_colors(stream):
    """
        Is tty output check
        :param object stream: input stream
        :return: bool
        """
    if not hasattr(stream, 'isatty'):
        return False
    if not stream.isatty():
        return False
    try:
        import curses
        curses.setupterm()
        return curses.tigetnum('colors') > 2
    except Exception:
        return False


@staticmethod
def str_to_day_of_year(date_in):
    """
        converts a date given as "mo/day" into a day of year
        """
    daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    month, day = date_in.split('/')
    dayOut = 0
    for m in range(1, int(month)):
        dayOut = dayOut + daysInMonth[m - 1]
    dayOut = dayOut + int(day)
    return dayOut


def get_thumbnail_url():
    """Return the URL of the thumbnail of the first image in the
        document.
        """


def DisableStopButton(*args, **kwargs):
    """ Stub Anduin function."""
    print('DisableStopButton', args, kwargs)


def read_zip(apath, fname, encoding='utf-8', errors='ignore', process_line=None
    ):
    """Read lines from a file in zip archive.

    :param fname: a name of the file in the archive
    :param process_line: a function that will be invoked to process each file's
                         line. If its result is a list, then it will be
                         returned by lines
    :type process_line: callable
    """
    from zipfile import ZipFile
    with ZipFile(apath) as a:
        with a.open(fname) as f:
            for line in f:
                line = line.decode(encoding=encoding, errors=errors)
                if process_line:
                    line = process_line(line)
                    if isinstance(line, list):
                        for line_ in line:
                            yield line_
                        continue
                yield line


def invertPatterns(patterns):
    """Inverts keys and values in dictionary"""
    p2 = {}
    keys = patterns.keys()
    for key in keys:
        p2[patterns[key], key] = key
    return p2


@staticmethod
def recall_pos(y, y_pred):
    """compute recall of the positive class"""
    return (y[y == 1] == y_pred[y == 1]).sum() / float((y == +1).sum())


def iter_except(func, exception, first=None):
    """ Call a function repeatedly until an exception is raised.

    Converts a call-until-exception interface to an iterator interface.
    Like __builtin__.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.

    Example::
        >>> list(iter_except([1, 2, 3].pop, IndexError))
        [3, 2, 1]

    More examples:
        bsddbiter = iter_except(db.next, bsddb.error, db.first)
        heapiter = iter_except(functools.partial(heappop, h), IndexError)
        dictiter = iter_except(d.popitem, KeyError)
        dequeiter = iter_except(d.popleft, IndexError)
        queueiter = iter_except(q.get_nowait, Queue.Empty)
        setiter = iter_except(s.pop, KeyError)

    """
    try:
        if first is not None:
            yield first()
        while 1:
            yield func()
    except exception:
        pass


def mask_between(x, xmin, xmax):
    """Create boolean mask of x between xmin and xmax."""
    return (x >= xmin) & (x < xmax)


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


def parse_item(fmt, fin):
    """
    Read number of bytes from a file and parse the data of a drawing item
    using a format.

    :param fmt: Struct format object.
    :param fin: File object.
    """
    buff = fin.read(fmt.size)
    return fmt.unpack(buff)


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a Twitter item."""
    return str(item['id_str'])


def __delitem__(key):
    """Delete a value from the mapping using the key."""


def build_instance(Model, data, db):
    """
    Build a model instance.

    If the model instance doesn't have a primary key and the model supports
    natural keys, try to retrieve it from the database.
    """
    obj = Model(**data)
    if obj.pk is None and hasattr(Model, 'natural_key') and hasattr(Model.
        _default_manager, 'get_by_natural_key'):
        natural_key = obj.natural_key()
        try:
            obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*
                natural_key).pk
        except Model.DoesNotExist:
            pass
    return obj


@staticmethod
def milliseconds_to_ticks(milliseconds):
    """Converts milliseconds to ticks.

        :param milliseconds: Milliseconds
        :type milliseconds: int
        :returns: Ticks
        :rtype: int
        """
    return milliseconds * 10000


def sign(x):
    """
    Return 1, 0, or -1 depending on the sign of x
    """
    if x > 0.0:
        return 1
    elif x == 0.0:
        return 0
    else:
        return -1


def write_vec_string(vec, prec):
    """Write data vector into string."""
    o = '['
    for n, v in enumerate(vec):
        o += f'{v:.{prec}f}'
        if n < len(vec) - 1:
            o += ','
    return o + ']'


def _delegate(func_name, *query, **kwquery):
    """mognodb operation"""


def _create_combined_words(words, startindex):
    """
    Helper for create_match_bool, used to combine words inside single quotes from a list into a
    single string.
    :param words: List of words.
    :param startindex: Index where search is started.
    :return: (str, int) or (None, 0) if no closing quote is found.
    """
    for i, word in enumerate(words[startindex + 1:]):
        if "'" in word:
            return ' '.join(words[startindex:startindex + i + 2]), i + 1
    return None, 0


def get_child(node, tag, ns=
    '{http://schemas.microsoft.com/win/2004/08/events/event}'):
    """
    @type node: etree.Element
    @type tag: str
    @type ns: str
    """
    return node.find('%s%s' % (ns, tag))


def _kindpatsalwaysmatch(kindpats):
    """"Checks whether the kindspats match everything, as e.g.
    'relpath:.' does.
    """
    for kind, pat, source in kindpats:
        if pat != b'' or kind not in [b'relpath', b'glob']:
            return False
    return True


def create_toc(headlines, hyperlink=True, top_link=False, no_toc_header=False):
    """
    Creates the table of contents from the headline list
    that was returned by the tag_and_collect function.

    Keyword Arguments:
        headlines: list of lists
            e.g., ['Some header lvl3', 'some-header-lvl3', 3]
        hyperlink: Creates hyperlinks in Markdown format if True,
            e.g., '- [Some header lvl1](#some-header-lvl1)'
        top_link: if True, add a id tag for linking the table
            of contents itself (for the back-to-top-links)
        no_toc_header: suppresses TOC header if True.

    Returns  a list of headlines for a table of contents
    in Markdown format,
    e.g., ['        - [Some header lvl3](#some-header-lvl3)', ...]

    """
    processed = []
    if not no_toc_header:
        if top_link:
            processed.append(
                '\n')
        processed.append('# Table of Contents')
    for line in headlines:
        if hyperlink:
            item = '%s- [%s](#%s)' % ((line[2] - 1) * '    ', line[0], line[1])
        else:
            item = '%s- %s' % ((line[2] - 1) * '    ', line[0])
        processed.append(item)
    processed.append('\n')
    return processed


def members():
    """ Returns a list of member ids """


def forward_checking(csp, var, value, assignment, removals):
    """Prune neighbor values inconsistent with var=value."""
    for B in csp.neighbors[var]:
        if B not in assignment:
            for b in csp.curr_domains[B][:]:
                if not csp.constraints(var, value, B, b):
                    csp.prune(B, b, removals)
            if not csp.curr_domains[B]:
                return False
    return True


def include(name, root_package=False, relative_globals=None, level=0):
    """
    overpython.include(name, root_package=False, relative_globals=None, level=0)

    Imports a module. Acts very much like the import statement.
    If the module name given is not found, Python automatically raises ImportError.
    """
    return __import__(name, locals=None, globals=relative_globals, fromlist
        =[] if root_package else [None], level=level)


@staticmethod
def makePattern(regexFilter):
    """
        If regexFilter doesn't already have them, add ^ to the beginning and $
        to the end since these are required by NdnRegexTopMatcher.

        :param str regexFilter: The regex filter.
        :return: The regex pattern with ^ and $.
        :rtype str:
        """
    pattern = regexFilter
    if not (len(pattern) >= 1 and pattern[0] == '^'):
        pattern = '^' + pattern
    if not (len(pattern) >= 1 and pattern[-1] == '$'):
        pattern = pattern + '$'
    return pattern


def mass_kmv(kinetic_energy, velocity):
    """Usage: Find mass from kinetic energy and velocity"""
    result = 2 * kinetic_energy / velocity ** 2
    return result


def get_lowercase_builtin_map(builtin_map_capitalised_dict):
    """Convert the names of the supported built-in operations to lowercase
    for comparison and invoke generation purpose. """
    builtin_map_dict = {}
    for fortran_name in builtin_map_capitalised_dict:
        python_name = builtin_map_capitalised_dict[fortran_name]
        builtin_map_dict[fortran_name.lower()] = python_name
    return builtin_map_dict


def resolve_dotted_name(name, module=None):
    """Adapted from zope.dottedname
    """
    name = name.split('.')
    if not name[0]:
        if module is None:
            raise ValueError('relative name without base module')
        module = module.split('.')
        name.pop(0)
        while not name[0]:
            module.pop()
            name.pop(0)
        name = module + name
    used = name.pop(0)
    found = __import__(used)
    for n in name:
        used += '.' + n
        try:
            found = getattr(found, n)
        except AttributeError:
            __import__(used)
            found = getattr(found, n)
    return found


def get_version():
    """Returns the mutable file protocol version."""


@classmethod
def clean_data(cls, data_dict):
    """Splits the data into formdata and files"""
    files = dict()
    data = dict()
    for key, value in data_dict.items():
        try:
            file = value
            if type(value) == tuple and hasattr(value[1], 'read'):
                file = value[1]
                files.update({key: (value[0].split('/')[-1], file.read())})
            elif hasattr(file, 'read') and hasattr(file, 'name'):
                files.update({key: (file.name, file.read())})
            else:
                data.update({key: value})
        except Exception as e:
            data.update({key: value})
    as_json = not bool(files)
    return data, files, as_json


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


@staticmethod
def _strip_backspaces(output):
    """Strip any backspace characters out of the output"""
    backspace_char = '\x08'
    return output.replace(backspace_char, '')


def get_app_version():
    """Returns full version string including application name
    suitable for putting into Torrent.created_by.

    """
    from torrentool import VERSION
    return 'torrentool/%s' % '.'.join(map(str, VERSION))


@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['type']
    if type == 'INTERNAL_COMPUTE':
        return 'InternalSourceDetails'
    if type == 'OCIC':
        return 'OcicSourceDetails'
    else:
        return 'SourceDetails'


def patch_compat(config):
    """
    Support older config values.
    """
    if 'web_host' in config:
        config['host'] = config.pop('web_host')
    if 'web_port' in config:
        config['port'] = config.pop('web_port')


def t_1(t_nom, fab_tol, t_cor):
    """ Characteristic wall thicknesses (Table 5-6)
    t_1 used where failure is likely to occur in connection with a low
    capacity:
    - Burst
    - Collapse """
    return t_nom - fab_tol - t_cor


def enable_validate_orthogonal():
    """
    Enable the validation whether the volume is orthogonal again (DEFAULT ENABLED)
    """
    global validate_orthogonal
    validate_orthogonal = True


def unrelate(category_name, discriminator):
    """ Indicate an intent to break the relationship between this
        IIntrospectable with another IIntrospectable (the one associated with
        the ``category_name`` and ``discriminator``) during action execution.
        """


def t_CPP_COMMENT1(t):
    """(/\\*(.|\\n)*?\\*/)"""
    ncr = t.value.count('\n')
    t.lexer.lineno += ncr
    t.type = 'CPP_WS'
    t.value = '\n' * ncr if ncr else ' '
    return t


def list_builds(Status=None, Limit=None, NextToken=None):
    """
    Retrieves build records for all builds associated with the AWS account in use. You can limit results to builds that are in a specific status by using the Status parameter. Use the pagination parameters to retrieve results in a set of sequential pages.
    See also: AWS API Documentation

    :example: response = client.list_builds(
        Status='INITIALIZED'|'READY'|'FAILED',
        Limit=123,
        NextToken='string'
    )

    :type Status: string
    :param Status: Build status to filter results by. To retrieve all builds, leave this parameter empty.
            Possible build statuses include the following:
            INITIALIZED   A new build has been defined, but no files have been uploaded. You cannot create fleets for builds that are in this status. When a build is successfully created, the build status is set to this value.
            READY   The game build has been successfully uploaded. You can now create new fleets for this build.
            FAILED   The game build upload failed. You cannot create new fleets for this build.

    :type Limit: integer
    :param Limit: Maximum number of results to return. Use this parameter with NextToken to get results as a set of sequential pages.

    :type NextToken: string
    :param NextToken: Token that indicates the start of the next sequential page of results. Use the token that is returned with a previous call to this action. To specify the start of the result set, do not specify a value.

    :rtype: dict
    :return: {
        'Builds': [
            {
                'BuildId': 'string',
                'Name': 'string',
                'Version': 'string',
                'Status': 'INITIALIZED'|'READY'|'FAILED',
                'SizeOnDisk': 123,
                'OperatingSystem': 'WINDOWS_2012'|'AMAZON_LINUX',
                'CreationTime': datetime(2015, 1, 1)
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    CreateBuild
    ListBuilds
    DescribeBuild
    UpdateBuild
    DeleteBuild

    """
    pass


@classmethod
def show(cls, user_id):
    """Get information about a user.

        Returns a `User` object with information about a single user,
        specified by the `user_id` argument.

        If there's no user with the specified ID, the
        `hipchat.api.NotFoundError` exception will be raised.

        """
    data = cls.api._get('users/show', user_id=str(user_id))
    return cls._parse(data['user'])


def bond_is_in_ring(bond):
    """Get whether the bond is in a ring of any size.
    Parameters
    ----------
    bond : rdkit.Chem.rdchem.Bond
        RDKit bond instance.
    Returns
    -------
    list
        List containing one bool only.
    """
    return [bond.IsInRing()]


def unload_ipython_extension(ip):
    """Unload the extension in IPython."""
    if 'Athena' in ip.magics_manager.registry:
        del ip.magics_manager.registry['Athena']
    if 'Athena' in ip.config:
        del ip.config['Athena']


@classmethod
def get_choice(cls, value):
    """
        Return the underlying :class:`ChoiceItem` for a given value.
        """
    attribute_for_value = cls.attributes[value]
    return cls._fields[attribute_for_value]


def get_app_engine(session, cloud_name, app_engine_id, return_type=None, **
    kwargs):
    """
    Get Application Engine in Cloud

    :type session: zadarapy.session.Session
    :param session: A valid zadarapy.session.Session object.  Required.

    :type cloud_name: str
    :param cloud_name: The cloud 'name' as returned by get_all_clouds.  For
        example: 'zadaralab01'.  Required.

    :type app_engine_id: int
    :param app_engine_id: Application engine ID. Required.

    :type return_type: str
    :param return_type: If this is set to the string 'json', this function
        will return a JSON string.  Otherwise, it will return a Python
        dictionary.  Optional (will return a Python dictionary by default).

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    path = '/api/clouds/{0}/app_engine_types/{1}.json'.format(cloud_name,
        app_engine_id)
    return session.get_api(path=path, return_type=return_type, **kwargs)


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 generate_unspliced_fasta(fasta_path, gtf_path, out_path):
    """Generate a unspliced FASTA using the genome and GTF.

    This function assumes the order in which the chromosomes appear in the
    genome FASTA is identical to the order in which they appear in the GTF.
    Additionally, the GTF must be sorted by start position.
    The spliced FASTA contains entries of length 2 * (k - 1) for k = 31,
    centered around exon-intron splice junctions + full introns
    (any overlapping regions are collapsed).

    :param fasta_path: path to genomic FASTA file
    :type fasta_path: str
    :param gtf_path: path to GTF file
    :type gtf_path: str
    :param out_path: path to unspliced FASTA to generate
    :type out_path: str

    :return: path to generated unspliced FASTA
    :rtype: str
    """
    pass


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


@classmethod
def decode_data(cls, obj, typedef):
    """Decode an object.

        Args:
            obj (string): Encoded object to decode.
            typedef (dict): Type definition that should be used to decode the
                object.

        Returns:
            object: Decoded object.

        """
    return obj


def bC_MgOH_HSO4_HMW84(T, P):
    """c-a: magnesium-hydroxide bisulfate [HMW84]."""
    b0 = 0.0
    b1 = 0.0
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def fib(n):
    """Fibonacci example function

    Args:
      n (int): integer

    Returns:
      int: n-th Fibonacci number
    """
    assert n > 0
    a, b = 1, 1
    for i in range(n - 1):
        a, b = b, a + b
    return a


def character_tokenizer(line):
    """
    Tokenize sentence based on NLTK's WordPunctTokenizer
    :param srt line:
    :rtype: List[str]
    """
    tknzd = list(line)
    return tknzd


def trans_gaul(q):
    """ transposes a tuple """
    y = []
    if len(q) > 0:
        for i in range(len(q[0])):
            elem = []
            for j in range(len(q)):
                elem.append(q[j][i])
            y.append(elem)
    return y


def format_select_option_label_user(item):
    """
    Format option for selection of user accounts.
    """
    return '{} ({})'.format(item.fullname, item.login)


def islist(val):
    """
    check if the entry is a list or is a string of list

    Parameters
    ----------
    val
        an entry of any type

    Returns
    -------
    bool
        True if the input is either a list or a string of list, False otherwise

    """
    text = str(val)
    if text[0] == '[' and text[len(text) - 1] == ']':
        return True
    else:
        return False


def _factors_avg(idadf, columnlist, valuelist):
    """
    Compute the arithmetic average for all columns in a list (valuelist) over
    the IdaDataFrame grouped by a list of columns (columnlist).

    Parameters
    ----------
    columnlist : list
        List of column names that exist in self.
    valuelist : list
        List of column names that exist in self.

    Notes
    -----
    The function assumes the following:

        * The columns given as parameter exists in the IdaDataframe
        * The parameter columnlist and valuelist are array-like
        * Columns are referenced by their own name (character string)

    Returns
    -------
        DataFrame
    """
    column_string = '"' + '", "'.join(columnlist) + '"'
    name = idadf.internal_state.current_state
    agg_list = []
    for value in valuelist:
        agg = (
            'CAST(AVG(CAST("%s" AS DECIMAL(10,6))) AS DECIMAL(10,6)) "%s"' %
            (value, value))
        agg_list.append(agg)
    agg_string = ', '.join(agg_list)
    value_string = '"' + '", "'.join(valuelist) + '"'
    query = 'SELECT %s,%s FROM %s GROUP BY %s ORDER BY %s,%s ASC' % (
        column_string, agg_string, name, column_string, column_string,
        value_string)
    return idadf.ida_query(query)


def bytes_packet(_bytes, termination_string=']'):
    """
    Create a packet containing the amount of bytes for the proceeding data.

    :param _bytes:
    :param termination_string:
    :return:
    """
    return '{}{}'.format(len(_bytes), termination_string)


def warn_regression(jira_plugin, jira_issue, test, message, *, message_format):
    """
    Send a message to mark a regression. And add it to the ``jira_plugin.regressions`` list.

    .. note::

        We call a regression a bug that was once known, then fixed and appeared once again as test run fails.

    :param jira_issue: the jira issue object
    :param test: test case
    :type test: unittest.TestCase
    :param message: the message to send
    :param message_format: the message format. As of 1.0 we use ``str.format`` syntax and accepted keys are ``test``
    and ``message``
    """
    from nose2_contrib.jira.jira_plugin import JiraRegression
    if not jira_plugin.connected:
        return
    jira_plugin.jira_client.add_comment(jira_issue, message_format.format(
        test=test, message=message))
    jira_plugin.regressions.append(JiraRegression(jira_issue.id, test, message)
        )


def gravity(gravitation):
    """ translate gravitation name according to Tk specification"""
    if gravitation == 'N':
        result = 'North'
    if gravitation == 'NW':
        result = 'Northwest'
    if gravitation == 'NE':
        result = 'Northeast'
    if gravitation == 'W':
        result = 'West'
    if gravitation == 'C':
        result = 'Center'
    if gravitation == 'E':
        result = 'East'
    if gravitation == 'SW':
        result = 'Southwest'
    if gravitation == 'S':
        result = 'South'
    if gravitation == 'SE':
        result = 'Southeast'
    return result


def _resolve_rest_format(mode, user_format):
    """Resolve format of submission to JPred REST interface based on provided mode and user format.

    :param str mode: Submission mode, possible values: `single`, `batch`, `msa`.
    :param str user_format: Submission format, possible values: `raw`, `fasta`, `msf`, `blc`.
    :return: Format for JPred REST interface.
    :rtype: :py:class:`str`
    """
    if user_format == 'raw' and mode == 'single':
        rest_format = 'seq'
    elif user_format == 'fasta' and mode == 'single':
        rest_format = 'seq'
    elif user_format == 'fasta' and mode == 'msa':
        rest_format = 'fasta'
    elif user_format == 'msf' and mode == 'msa':
        rest_format = 'msf'
    elif user_format == 'blc' and mode == 'msa':
        rest_format = 'blc'
    elif user_format == 'fasta' and mode == 'batch':
        rest_format = 'batch'
    else:
        raise ValueError(
            """Invalid mode/format combination.
        Valid combinations are: --mode=single --format=raw
                                --mode=single --format=fasta
                                --mode=msa    --format=fasta
                                --mode=msa    --format=msf
                                --mode=msa    --format=blc
                                --mode=batch  --format=fasta"""
            )
    return rest_format


def get_y_offset(read, coords):
    """ get the y-position for the read, within the first row with open space

    This is decidedly less than optimal, but will produce a more compact plot.

    Args:
        read: dictionary with 'position' and 'bases' entries e.g.
            {'position': 15555, bases ['M', 'MTA', 'M']}
        positions: ordered dictionary of max end position at each row, indexed
            by row number e.g. {10: 100, 20: 150, 30: 50}

    Returns:
        y-axis offset.
    """
    if len(coords) == 0:
        return 10
    for key in coords:
        if read['position'] > coords[key] + 1:
            return key
    return max(coords) + 10


def _char_to_unsigned_int(char):
    """
    Convert an ASCII character to an integer 0-63
    """
    i = ord(char)
    if i >= 97 and i <= 122:
        return i - 97
    if i >= 65 and i <= 90:
        return i - 39
    if i >= 48 and i <= 57:
        return i + 4
    if i == 43:
        return 62
    return 63


def version_to_string(v):
    """Convert a 3 part version number encoded as a hexadecimal value to a
    string.
    """
    return '%u.%u.%u' % (v >> 16 & 255, v >> 8 & 255, v & 255)


def sofa_version():
    """
    Returns the corresponding SOFA version
    as defined in configure.ac
    in string format
    """
    return '20190722'


def parse_asrtoolkit_result(res):
    """This function returns the asrtoolkit result (cer or wer) as follow:
	'CER: 4%' --> 4
	@param: res (string): the string that asrtoolkit returns
	@return: res_net (float): only the number
	"""
    res_net = str(res)
    for s in ['WER: ', 'CER: ', '%\\n', "'", 'b']:
        res_net = res_net.replace(s, '')
    return float(res_net)


def count_calls(callers):
    """Sum the caller statistics to get total number of calls received."""
    nc = 0
    for calls in callers.values():
        nc += calls
    return nc


def submit_job(name, jq, jobdef, params):
    """
    Submit an AWS Batch job to the defined job queue
    :param name: the job name
    :param jq: the job queue name
    :param jobdef: the job definition string (e.g. mg-usearch-jobdef:4)
    :param params: dict of container overrides key/value pairs
    :return: dict of return information from aws batch command
    """


@classmethod
def exact(cls, amount):
    """
        Return a :class:`.Dimension` with an exact size. (min, max and
        preferred set to ``amount``).
        """
    return cls(min=amount, max=amount, preferred=amount)


def vertices_of_face(face):
    """
    Return 3 vertices of the given triangle face.
    """
    x, y, w = face
    return [(x + w, y + w), (x + 1, y), (x, y + 1)]


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

        :param MemberSuggestionsChangePolicyDetails val:
        :rtype: EventDetails
        """
    return cls('member_suggestions_change_policy_details', val)


def load_handlers(name):
    """Load the (URL pattern, handler) tuples for each component."""
    mod = __import__(name, fromlist=['default_handlers'])
    return mod.default_handlers


def describe_resource_permissions(ResourceId=None, Limit=None, Marker=None):
    """
    Describes the permissions of a specified resource.
    See also: AWS API Documentation

    :example: response = client.describe_resource_permissions(
        ResourceId='string',
        Limit=123,
        Marker='string'
    )

    :type ResourceId: string
    :param ResourceId: [REQUIRED]
            The ID of the resource.

    :type Limit: integer
    :param Limit: The maximum number of items to return with this call.

    :type Marker: string
    :param Marker: The marker for the next set of results. (You received this marker from a previous call)

    :rtype: dict
    :return: {
        'Principals': [
            {
                'Id': 'string',
                'Type': 'USER'|'GROUP'|'INVITE'|'ANONYMOUS'|'ORGANIZATION',
                'Roles': [
                    {
                        'Role': 'VIEWER'|'CONTRIBUTOR'|'OWNER'|'COOWNER',
                        'Type': 'DIRECT'|'INHERITED'
                    },
                ]
            },
        ],
        'Marker': 'string'
    }

    """
    pass


def checkpoint_iterator(function, interval=100):
    """The iterator will call the given function for every nth invocation """
    counter = 0
    while True:
        counter += 1
        if counter % interval == 0:
            function()
        yield None


def kernel_name(model_info, variant):
    """
    Name of the exported kernel symbol.

    *variant* is "Iq", "Iqxy" or "Imagnetic".
    """
    return model_info.name + '_' + variant


@staticmethod
def print(key, value):
    """ Return a string which is pretty-printing the key+value """
    if isinstance(value, list):
        s = '%block {}'.format(key)
        has_nl = False
        for v in value:
            if '\n' in v:
                has_nl = True
                break
        if has_nl:
            value[-1].replace('\n', '')
            s += '\n{}'.format(''.join(value))
        else:
            s += '\n{} {}'.format(value[0], '\n'.join(value[1:]))
        s += '%endblock {}'.format(key)
    else:
        s = '{} {}'.format(key, value)
    return s


def timeit(func):
    """Attach the `func` a time marker
    """
    func.__dict__['timeit'] = True
    func.__dict__['precision'] = 4
    return func


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


def hexa_to_rgb(color):
    """Convert hexadecimal color to RGB."""
    r = int(color[1:3], 16)
    g = int(color[3:5], 16)
    b = int(color[5:7], 16)
    if len(color) == 7:
        return r, g, b
    elif len(color) == 9:
        return r, g, b, int(color[7:9], 16)
    else:
        raise ValueError('Invalid hexadecimal notation.')


def get_rdf_object(graph, subject, predicate):
    """Takes an rdflib Graph, subject and predicate, and returns the first
    matching object if one exists. If none exist, returns None."""
    objects = list(graph.objects(subject, predicate))
    if len(objects) == 0:
        return None
    else:
        return objects[0].toPython()


def tr(cellContent='', color=False, href=False, popover=False, span=False):
    """
    *Generate a table row - TBS style*

    **Key Arguments:**
        - ``cellContent`` -- the content - either s or s
        - ``color`` -- [ sucess | error | warning | info ]
        - ``href`` -- add a link for the whole table row

    **Return:**
        - ``tr`` -- the table row
    """
    if isinstance(cellContent, list):
        new = ''
        for c in cellContent:
            new += c
        cellContent = new
    if color is False:
        color = ''
    if href is False:
        href = ''
        link = ''
    else:
        href = 'href="%(href)s" ' % locals()
        link = 'link'
    if popover is False:
        popover = ''
    if span is False:
        span = ''
    else:
        span = 'span%(span)s' % locals()
    tr = (
        '
%(cellContent)s
'
         % locals())
    return tr


def add_bulk_items(db, klass, rows):
    """Batched INSERT statements via the ORM "bulk", using dictionaries.
       input: rows is a list of dictionaries """
    db.bulk_insert_mappings(klass, rows)
    db.commit()
    return


def N_(msg):
    """Mark message for translation but don't translate it right away."""
    return msg


def distance_hue(h1: float, h2: float) ->float:
    """HUE based distance
    distance > 0 -> "clockwise"
    distance < 0 -> "counter-clocwise"
    """
    dist = h2 - h1
    if abs(dist) > 0.5:
        dist = (-1 if dist > 0 else 1) * (1 - abs(dist))
    return dist


def indexing_key_expand_implicit_axes(key, shape):
    """Make implicit axes explicit by adding ``slice(None)``.
    Examples
    --------
    >>> shape = (3, 4, 5)
    >>> indexing_key_expand_implicit_axes(np.s_[2, 1, 1], shape)
    (2, 1, 1)
    >>> indexing_key_expand_implicit_axes(np.s_[0], shape)
    (0, slice(None, None, None), slice(None, None, None))
    >>> indexing_key_expand_implicit_axes(np.s_[0, ...], shape)  # equivalent
    (0, slice(None, None, None), slice(None, None, None))
    >>> indexing_key_expand_implicit_axes(np.s_[:2, None, 0, ...], shape)
    (slice(None, 2, None), None, 0, slice(None, None, None))
    """
    if not isinstance(key, tuple):
        key = key,
    ell_idx = None
    num_none = 0
    nonell_key = []
    for i, idx in enumerate(key):
        if idx is Ellipsis:
            if ell_idx is not None:
                raise IndexError(
                    'Cannot use more than one ellipsis (`...`) for indexing')
            ell_idx = i
        else:
            if idx is None:
                num_none += 1
            nonell_key.append(idx)
    nonell_key = tuple(nonell_key)
    if ell_idx is None:
        ell_idx = len(nonell_key)
    ell_ndim = len(shape) + num_none - len(nonell_key)
    expanded_key = nonell_key[:ell_idx] + (slice(None),
        ) * ell_ndim + nonell_key[ell_idx:]
    return expanded_key


def graph_select(location: float=(0.0, 0.0), extend: bool=False):
    """Select graph curves

    :param location: Location, Mouse location to select nearest entity
    :type location: float
    :param extend: Extend, Extend selection rather than clearing the existing selection
    :type extend: bool
    """
    pass


def identity(value):
    """ 直接返回值, 常用于函数式编程中. identity, used in functional programming mostly. """
    return value


def deduplication_run_check(columns, df):
    """
    Check for consistency between parameters and the dataframe, an assertion
    error will incur if the check is not passed.

    :param columns: Columns on which to run the metric
    :type columns: list
    :param df: Dataframe on which to run the metric
    :type df: DataFrame
    """
    if columns is not None:
        for col in columns:
            assert col in df.columns, "Column '%s' is not a column part of the dataframe" % col


@staticmethod
def _wrap_columns(columns):
    """Allows to change the columns names if needed."""
    return columns


def _parse_match_info(match, regex, soccer=False):
    """
    Parse string containing info of a specific match

    :param match: Match data
    :type match: string
    :param regex: Match data pattern
    :type regex: Regex object
    :param soccer: Set to true if match contains soccer data, defaults to False
    :type soccer: bool, optional
    :return: Dictionary containing match information
    :rtype: dict
    """
    match = regex.search(match)
    match_info = {'league': match.group(1), 'home_team': match.group(2),
        'away_team': match.group(3), 'home_score': match.group(4),
        'away_score': match.group(5)}
    if match_info['home_score'] is None:
        match_info['home_score'] = '0'
    if match_info['away_score'] is None:
        match_info['away_score'] = '0'
    if soccer:
        match_info['match_time'] = match[6]
    return match_info


@classmethod
def create_from_genomesize(cls, gsize):
    """Creates a GenomicIndexer object.

        This method constructs a GenomicIndexer from
        a given BED or GFF file.

        Parameters
        ----------
        gsize : dict
            Dictionary with keys and values representing chromosome names
            and lengths, respectively.
        """
    gind = cls(None, None, 0, zero_padding=False, collapse=False)
    for chrom in gsize:
        gind.add_interval(chrom, 0, gsize[chrom], '.')
    return gind


def format_timestamp(timestamp):
    """Returns a string representing a python datetime in LDAP timestamp
    format.

    :param timestamp: An "aware" datetime object
    :return: A timestamp in the format YYYYMMDDhhmmss-0700 (or -0800 in the winter)
    """
    if timestamp.tzinfo is None or timestamp.tzinfo.utcoffset(timestamp
        ) is None:
        raise ValueError('Timestamp has no timezone info')
    return timestamp.strftime('%Y%m%d%H%M%S%z')


def get_atomic_numbers(mol, indices):
    """Get the atomic numbers for the specified atoms.

    Parameters
    ----------
    mol : rdkit.Chem.rdchem.Mol
        RDKit molecule instance.
    indices : list of int
        Specifying atoms.

    Returns
    -------
    list of int
        Atomic numbers computed.
    """
    atomic_numbers = []
    for i in indices:
        atom = mol.GetAtomWithIdx(i)
        atomic_numbers.append(atom.GetAtomicNum())
    return atomic_numbers


def V_Rseries(voltage, I, Rs):
    """Returns the voltage of a solar cells under the effect of series resistance"""
    return voltage - I * Rs


def uninstall(context):
    """Uninstall script"""


def interpret_colour(s, context=None):
    """Convert a raw Color value to a gomill colour.

    Returns 'b' or 'w'.

    """
    colour = s.decode('ascii').lower()
    if colour not in ('b', 'w'):
        raise ValueError
    return colour


def provide_handler(handler, adapts=None):
    """Register a handler

        Handlers are subscription adapter factories that don't produce
        anything.  They do all of their work when called.  Handlers
        are typically used to handle events.

        If the handler has an adapts declaration, then the adapts
        argument can be omitted and the declaration will be used.  (An
        adapts argument can be provided to override the declaration.)

        CAUTION: This API should only be used from test or
        application-setup code. This API shouldn't be used by regular
        library modules, as component registration is a configuration
        activity.
        """


def set_default(cfg):
    """
    Set initial configuration values

    This is used mostly for setting up an initial set of values
    before using the actual config set. It is important to know
    that using this function would result in a total overwrite of
    the whole config set, so it is only meant to be used before
    anything.

    :param cfg: dictionary containing the initial values
    :raises TypeError: if cfg is not a dict
    """
    global _config
    if type(cfg) != dict:
        raise TypeError('cfg must be dict')
    _config = cfg


def rotcopy(item, mat):
    """copy rotation to item from matrix mat depending on item.rotation_mode"""
    if item.rotation_mode == 'QUATERNION':
        item.rotation_quaternion = mat.to_3x3().to_quaternion()
    elif item.rotation_mode == 'AXIS_ANGLE':
        rot = mat.to_3x3().to_quaternion().to_axis_angle()
        axis_angle = rot[1], rot[0][0], rot[0][1], rot[0][2]
        item.rotation_axis_angle = axis_angle
    else:
        item.rotation_euler = mat.to_3x3().to_euler(item.rotation_mode)


def max(raw_metric):
    """
    .. note:: Deprecated use `longMax`, `doubleMax' instead
    """
    return {'type': 'max', 'fieldName': raw_metric}


@classmethod
def from_crawler(cls, crawler):
    """Returns instance from crawler.

        Parameters
        ----------
        crawler : scrapy.crawler.Crawler

        Returns
        -------
        RFPDupeFilter
            Instance of RFPDupeFilter.

        """
    return cls.from_settings(crawler.settings)


@staticmethod
def _union(i1, i2):
    """ Compute the union of *i1* and *i2*. """
    return min((i1.inf, i2.inf)), max((i1.sup, i2.sup))


@staticmethod
def b2_features(variations):
    """
        Generated a b2 requirements list, i.e. <name>value list, from the given 'variations' dict.
        """
    result = []
    for k, v in sorted(variations.items()):
        if v:
            result += ['<%s>%s' % (k, v)]
    return result


@classmethod
def from_bytes(cls, data, nVersion):
    """Instantiate from data and nVersion"""
    if not 0 <= nVersion <= 255:
        raise ValueError(
            'nVersion must be in range 0 to 255 inclusive; got %d' % nVersion)
    self = bytes.__new__(cls, data)
    self.nVersion = nVersion
    return self


def get_stairs(all_results, report_name, min_length=50):
    """
    Given a list of Result objects and the name of a control variable
    time series, return two lists

    - all_vals: all discovered flat plateau values in the report_name time
      series. The plateau valuse for all reults are merged into one ordered
      list with unique values only

    - all_lims: same length as all_vals; each item is a list of the same
      length as all_results and each list inside this inner list is a tuple of
      start and end indices of the flat part; or (0, 0, 0) if there was no such
      flat part in that result object

    The indices returned are (istart_trans, istart, iend):

    - istart_trans: where the unsteady transition starts ("step up")
    - istart: where the steady part of this "stair tread" starts
    - iend: where the steady part of this "stair tread" ends
    """
    all_res = []
    all_vals = set()
    for results in all_results:
        this_res = []
        all_res.append(this_res)
        ts = results.reports.get(report_name, [])
        N = len(ts)
        start = True
        for i in range(N):
            if start and i < N - 2 and ts[i] == ts[i + 1] == ts[i + 2]:
                start = False
                this_res.append([ts[i], i, None])
                all_vals.add(ts[i])
                continue
            elif not start and N - 1 > i > 1 and ts[i - 2] == ts[i - 1] == ts[i
                ] != ts[i + 1]:
                start = True
                this_res[-1][-1] = i
        if not start:
            this_res[-1][-1] = N - 1
    all_vals = sorted(all_vals)
    all_lims = []
    for val in all_vals:
        all_lims.append([])
        for lims in all_res:
            prevend = 0
            for v, istart, iend in lims:
                if v == val and iend - istart > min_length:
                    all_lims[-1].append((prevend, istart, iend))
                    break
                prevend = iend
            else:
                all_lims[-1].append((0, 0, 0))
    all_vals2, all_lims2 = [], []
    for val, lims in zip(all_vals, all_lims):
        all_zero = True
        for i0, i1, i2 in lims:
            if not i0 == i1 == i2 == 0:
                all_zero = False
        if not all_zero:
            all_vals2.append(val)
            all_lims2.append(lims)
    return all_vals2, all_lims2


def rate(currency):
    """Return the rate of exchange from the base currency to currency."""


def reduce_min(input):
    """Returns the min of all elements in the input tensor.

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

    Returns
    -------
    Tensor
        A framework-specific tensor with shape (1,)
    """
    pass


def subtract_modulo(image1, image2):
    """Subtract two images, without clipping the result. At least one of the
    images must have mode "1".

    .. code-block:: python

        out = ((image1 - image2) % MAX)

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image1.load()
    image2.load()
    return image1._new(image1.im.chop_subtract_modulo(image2.im))


def wildcard_match(pattern, text, case_insensitive=True):
    """
    Performs a case-insensitive wildcard match against two strings.
    This method works with pseduo-regex chars; specifically ? and * are supported.
    An asterisk (*) represents any combination of characters.
    A question mark (?) represents any single character.
    :param str pattern: the regex-like pattern to be compared against
    :param str text: the string to compare against the pattern
    :param boolean case_insensitive: dafault is True
    return whether the text matches the pattern
    """
    if pattern is None or text is None:
        return False
    if len(pattern) == 0:
        return len(text) == 0
    if pattern == '*':
        return True
    i = 0
    p = 0
    iStar = len(text)
    pStar = 0
    while i < len(text):
        if p < len(pattern) and text[i] == pattern[p]:
            i = i + 1
            p = p + 1
        elif p < len(pattern) and case_insensitive and text[i].lower(
            ) == pattern[p].lower():
            i = i + 1
            p = p + 1
        elif p < len(pattern) and pattern[p] == '?':
            i = i + 1
            p = p + 1
        elif p < len(pattern) and pattern[p] == '*':
            iStar = i
            pStar = p
            p += 1
        elif iStar != len(text):
            iStar += 1
            i = iStar
            p = pStar + 1
        else:
            return False
    while p < len(pattern) and pattern[p] == '*':
        p = p + 1
    return p == len(pattern) and i == len(text)


@staticmethod
def _split_cluster_host(cluster_host):
    """Split a string with list of hosts and make a list of tuples out of it.
        For example, string
        *192.168.90.2:3306,192.168.90.3:3306,192.168.90.4:3306*
        will be converted into list:

.. code-block:: python

    [
        (192.168.90.2, 3306),
        (192.168.90.3, 3306),
        (192.168.90.4, 3306),
    ]

:param cluster_host: String with list of host:port pairs
:type cluster_host: str
:return: list of tuples (host, port)
:rtype: list(tuple)
        """
    result = []
    for item in cluster_host.split(','):
        host, port = item.split(':')
        result.append((host, int(port)))
    return result


def _letter(x: int):
    """Helper function to convert a number to a unique sequence of letters
    Uses first 10 letters for a base 10 representation"""
    first_10 = {(0): 'a', (1): 'b', (2): 'c', (3): 'd', (4): 'e', (5): 'f',
        (6): 'g', (7): 'h', (8): 'i', (9): 'j'}
    x = str(x)
    rs = ''
    for num in x:
        rs += first_10[int(num)]
    return rs


def __validate_extension(extn):
    """ check for file types that require specialized io libraries / protocols """
    if extn.startswith('.xl') or extn in {'.7z', '.gzip'}:
        raise NotImplementedError("'{}' file type not supported".format(extn))


def duplicate_object_hook(ordered_pairs):
    """Make lists out of duplicate keys."""
    json_dict = {}
    for key, val in ordered_pairs:
        existing_val = json_dict.get(key)
        if not existing_val:
            json_dict[key] = val
        elif isinstance(existing_val, list):
            existing_val.append(val)
        else:
            json_dict[key] = [existing_val, val]
    return json_dict


def left_justify(words, width):
    """
    Left justify words.

    :param words: list of words
    :type words : list
    :param width: width of each line
    :type width: int
    :return: left justified words as list
    """
    return ' '.join(words).ljust(width)


def is_numeral(n):
    """
    Test if ``string n`` can be converted to a numeral.
    """
    try:
        float(n)
        return True
    except ValueError:
        return False


def create_open_id_connect_provider(Url=None, ClientIDList=None,
    ThumbprintList=None):
    """
    Creates an IAM entity to describe an identity provider (IdP) that supports OpenID Connect (OIDC) .
    The OIDC provider that you create with this operation can be used as a principal in a role's trust policy to establish a trust relationship between AWS and the OIDC provider.
    When you create the IAM OIDC provider, you specify the URL of the OIDC identity provider (IdP) to trust, a list of client IDs (also known as audiences) that identify the application or applications that are allowed to authenticate using the OIDC provider, and a list of thumbprints of the server certificate(s) that the IdP uses. You get all of this information from the OIDC IdP that you want to use for access to AWS.
    See also: AWS API Documentation

    Examples
    The following example defines a new OIDC provider in IAM with a client ID of my-application-id and pointing at the server with a URL of https://server.example.com.
    Expected Output:

    :example: response = client.create_open_id_connect_provider(
        Url='string',
        ClientIDList=[
            'string',
        ],
        ThumbprintList=[
            'string',
        ]
    )

    :type Url: string
    :param Url: [REQUIRED]
            The URL of the identity provider. The URL must begin with 'https://' and should correspond to the iss claim in the provider's OpenID Connect ID tokens. Per the OIDC standard, path components are allowed but query parameters are not. Typically the URL consists of only a host name, like 'https://server.example.org' or 'https://example.com'.
            You cannot register the same provider multiple times in a single AWS account. If you try to submit a URL that has already been used for an OpenID Connect provider in the AWS account, you will get an error.

    :type ClientIDList: list
    :param ClientIDList: A list of client IDs (also known as audiences). When a mobile or web app registers with an OpenID Connect provider, they establish a value that identifies the application. (This is the value that's sent as the client_id parameter on OAuth requests.)
            You can register multiple client IDs with the same provider. For example, you might have multiple applications that use the same OIDC provider. You cannot register more than 100 client IDs with a single IAM OIDC provider.
            There is no defined format for a client ID. The CreateOpenIDConnectProviderRequest action accepts client IDs up to 255 characters long.
            (string) --

    :type ThumbprintList: list
    :param ThumbprintList: [REQUIRED]
            A list of server certificate thumbprints for the OpenID Connect (OIDC) identity provider's server certificate(s). Typically this list includes only one entry. However, IAM lets you have up to five thumbprints for an OIDC provider. This lets you maintain multiple thumbprints if the identity provider is rotating certificates.
            The server certificate thumbprint is the hex-encoded SHA-1 hash value of the X.509 certificate used by the domain where the OpenID Connect provider makes its keys available. It is always a 40-character string.
            You must provide at least one thumbprint when creating an IAM OIDC provider. For example, if the OIDC provider is server.example.com and the provider stores its keys at 'https://keys.server.example.com/openid-connect', the thumbprint string would be the hex-encoded SHA-1 hash value of the certificate used by https://keys.server.example.com.
            For more information about obtaining the OIDC provider's thumbprint, see Obtaining the Thumbprint for an OpenID Connect Provider in the IAM User Guide .
            (string) --Contains a thumbprint for an identity provider's server certificate.
            The identity provider's server certificate thumbprint is the hex-encoded SHA-1 hash value of the self-signed X.509 certificate used by the domain where the OpenID Connect provider makes its keys available. It is always a 40-character string.

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

    """
    pass


def symmetric_product(tensor):
    """
    Symmetric outer product of tensor
    """
    shape = tensor.size()
    idx = list(range(len(shape)))
    idx[-1], idx[-2] = idx[-2], idx[-1]
    return 0.5 * (tensor + tensor.permute(*idx))


@classmethod
def get_accounts(cls, store):
    """Get a list of all accounts

        :param store: a store
        :returns all accounts
        :rtype: resultset
        """
    return store.find(cls)


def factorized_quadratic(x, weights):
    """A factorized quadratic interaction.

    :param x:
        shape ``(batch_size, in_features)``
    :param weights:
        shape ``(n_factors, in_features, out_features)``
    """
    x = x[None, ...]
    res = (x @ weights) ** 2.0 - x ** 2.0 @ weights ** 2.0
    res = res.sum(dim=0)
    return 0.5 * res


def daemon_error_print():
    """
    Print error message in case of invalid argument.
    """
    print('[info] Usage: /etc/init.d/ytrss {start|stop|restart|status}')


def ncor(tmp):
    """
    Correct number problems.

    Parameters
    ----------
    tmp : str
        String to correct.

    Returns
    -------
    tmp : str
        Corrected string.

    """
    tmp = tmp.replace('I', '1')
    return tmp


def _has_method(arg, method):
    """Returns true if the given object has a method with the given name.

    :param arg: the object

    :param method: the method name
    :type method: string

    :rtype: bool
    """
    return hasattr(arg, method) and callable(getattr(arg, method))


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

        :param MediaMetadata val:
        :rtype: MediaInfo
        """
    return cls('metadata', val)


def check_connection(connection):
    """
    Check a connection is available

    @Args:
    * [connection] if connection is alive return True

    @Returns:
    * [bool]
    """
    try:
        connection.ping(True)
        return True
    except:
        return False


def nearestPoint(pos):
    """
  Finds the nearest grid point to a position (discretizes).
  """
    current_row, current_col = pos
    grid_row = int(current_row + 0.5)
    grid_col = int(current_col + 0.5)
    return grid_row, grid_col


def process_data_file(file):
    """
    Detects the file type and assign the right format for the
    :param file:
    :return:
    """


def parse_fmt(fmt):
    """given a fmt block BitstreamReader (without the 8 byte header)
    returns (channels, sample_rate, bits_per_sample, channel_mask)
    where channel_mask is a ChannelMask object and the rest are ints
    may raise ValueError if the fmt chunk is invalid
    or IOError if an error occurs parsing the chunk"""
    from audiotools import ChannelMask
    (compression, channels, sample_rate, bytes_per_second, block_align,
        bits_per_sample) = fmt.parse('16u 16u 32u 32u 16u 16u')
    if compression == 1:
        if channels == 1:
            channel_mask = ChannelMask.from_fields(front_center=True)
        elif channels == 2:
            channel_mask = ChannelMask.from_fields(front_left=True,
                front_right=True)
        elif channels == 3:
            channel_mask = ChannelMask.from_fields(front_left=True,
                front_right=True, front_center=True)
        elif channels == 4:
            channel_mask = ChannelMask.from_fields(front_left=True,
                front_right=True, back_left=True, back_right=True)
        elif channels == 5:
            channel_mask = ChannelMask.from_fields(front_left=True,
                front_right=True, back_left=True, back_right=True,
                front_center=True)
        elif channels == 6:
            channel_mask = ChannelMask.from_fields(front_left=True,
                front_right=True, back_left=True, back_right=True,
                front_center=True, low_frequency=True)
        else:
            channel_mask = ChannelMask(0)
        return channels, sample_rate, bits_per_sample, channel_mask
    elif compression == 65534:
        cb_size, valid_bits_per_sample, channel_mask, sub_format = fmt.parse(
            '16u 16u 32u 16b')
        if (sub_format != b'\x01\x00\x00\x00\x00\x00\x10\x00' +
            b'\x80\x00\x00\xaa\x008\x9bq'):
            raise ValueError('invalid WAVE sub-format')
        else:
            channel_mask = ChannelMask(channel_mask)
            return channels, sample_rate, bits_per_sample, channel_mask
    else:
        raise ValueError('unsupported WAVE compression')


@classmethod
def is_type_match(cls, data_type):
    """
        Returns whether the given type is the same type of the file or not
        :param data_type: str
        :return: bool
        """
    return data_type == cls.get_data_type()


def _tint_code(color, place):
    """Get a color's tint code.

    Parameters
    ----------
    color : string
        Color to be coded
        If place is "font", it should be one of the following colors:
            ====================================================================
            "black", "red", "green", "yellow", "blue", "purple", "cyan", "white"
            ====================================================================

        If place is "bg", it should be one of the following colors:
            ====================================================================
            "black", "red", "green", "yellow", "blue", "purple", "cyan", "white"
            ====================================================================

    place : string
        Color's place, should be "font" or "bg"

    Returns
    -------
    tint_code: integer
        Color's tint code.

    """
    code_dict = {'font': {'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
        'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37}, 'bg': {'black':
        40, 'red': 41, 'green': 42, 'yellow': 43, 'blue': 44, 'purple': 45,
        'cyan': 46, 'white': 47}}
    if place not in code_dict:
        raise ValueError('Invalid place %s' % place)
    if color not in code_dict[place]:
        raise ValueError('Invalid color %s for place %s' % (color, place))
    return code_dict[place][color]


def parse_boolean(val):
    """String to boolean type."""
    return True if val and val.lower() == 'true' else False


@classmethod
def get_matching_state_for_esi_state(cls, esi_state_name) ->int:
    """returns matching state for given state name"""
    return cls._STATES_ESI_MAP[esi_state_name
        ] if esi_state_name in cls._STATES_ESI_MAP else cls.STATE_OFFLINE


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``PowerSpectrumControlPanel`` is only intended to be added to
        :class:`.PowerSpectrumPanel` views.
        """
    from fsleyes.views.powerspectrumpanel import PowerSpectrumPanel
    return [PowerSpectrumPanel]


def isnormal(s: str) ->bool:
    """cheap algorithm to detect strings for which escape is an identity"""
    depth = 0
    for part in s.split('{'):
        if depth == 1 and part.startswith('}'):
            return False
        depth -= part.count('}')
        if depth < 0:
            return False
        depth += 1
    return depth == 1


def collect_powers(s, v):
    """
        Collect repeated multiplications of string v in s and replace them by exponentiation.

        **Examples**::

            >>> collect_powers('c*c','c')
            'c**2'
            >>> collect_powers('c*c*c*c*c*c*c*c*c*c','c')
            'c**10'
            >>> collect_powers('d*c*c','c')
            'd*c**2'
    """
    import re
    m = s.count(v)
    for i in range(m, 0, -1):
        pattern = re.compile(v + '(\\*' + v + '){' + str(i) + '}')
        s = pattern.sub(v + '**' + str(i + 1), s)
    return s


def select_more():
    """Select those bones connected to the initial selection

    """
    pass


@classmethod
def from_raw(cls, data):
    """Creates a Response from raw data"""
    try:
        return cls(data['response'], data['status'])
    except KeyError:
        return cls(None, None)


@classmethod
def list(cls, context):
    """Return a list of Device Profile objects."""
    db_devprofs = cls.dbapi.device_profile_list(context)
    obj_dp_list = cls._from_db_object_list(db_devprofs, context)
    return obj_dp_list


def enum_formatter(view, value):
    """
        Return the name of the enumerated member.

        :param value:
            Value to check
    """
    return value.name


def _recipe_type(raw_configuration):
    """
    Given a raw repository configuration, returns its recipe type.

    :param raw_configuration: configuration as returned by the SCRIPT_NAME_GET
        groovy script.
    :type raw_configuration: dict
    :return: Group, Proxy or Hosted
    """
    return raw_configuration['recipeName'].split('-')[1].title()


def CAT(N, rho, k):
    """Criterion Autoregressive Transfer Function :

    .. math::  CAT(k) = \\frac{1}{N} \\sum_{i=1}^k \\frac{1}{\\rho_i} - \\frac{\\rho_i}{\\rho_k}

    .. todo:: validation
    """
    from numpy import zeros, arange
    cat = zeros(len(rho))
    for p in arange(1, len(rho) + 1):
        rho_p = float(N) / (N - p) * rho[p - 1]
        s = 0
        for j in range(1, p + 1):
            rho_j = float(N) / (N - j) * rho[j - 1]
            s = s + 1.0 / rho_j
        cat[p - 1] = s / float(N) - 1.0 / rho_p
    return cat


@classmethod
def global_config(cls, key, *args):
    """ This reads or sets the global settings stored in class.settings. """
    if args:
        cls.settings = cls.settings.copy()
        cls.settings[key] = args[0]
    else:
        return cls.settings[key]


def single_or_plural(attr):
    """ Simple function. Gives versions with 's' at the end and without it. """
    return list(set([attr, attr.rstrip('s'), f'{attr}s']))


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 parse_vcf_line(line):
    """
    Parse a line in the VCF file.
    :param line: a line from the VCF file
    :type line: str
    :return: :class:`.vcf.VCFRecord`
    """
    if isinstance(line, str):
        if line.startswith('#'):
            return None
        elem = line.strip().split('\t')
    elif isinstance(line, list):
        elem = line
    try:
        quality = int(elem[5])
    except ValueError:
        try:
            quality = float(elem[5])
        except ValueError:
            quality = None
    filter_field = None
    if elem[6] != '.':
        filter_field = elem[6].split(';')
    info = elem[7]
    try:
        fmt = elem[8]
    except IndexError:
        fmt = None
    else:
        if fmt == '.':
            fmt = None
    return [elem[0], int(elem[1]), None if elem[2] == '.' else elem[2],
        elem[3], elem[4].split(','), quality, filter_field, info, fmt, elem[9:]
        ]


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

        :param TeamMergeRequestRejectedShownToPrimaryTeamDetails val:
        :rtype: EventDetails
        """
    return cls('team_merge_request_rejected_shown_to_primary_team_details', val
        )


def bbox_flip(bboxes, img_shape):
    """Flip bboxes horizontally.

    Args:
        bboxes(ndarray): shape (..., 4*k)
        img_shape(tuple): (height, width)
    """
    assert bboxes.shape[-1] % 4 == 0
    w = img_shape[1]
    flipped = bboxes.copy()
    flipped[(...), 0::4] = w - bboxes[(...), 2::4] - 1
    flipped[(...), 2::4] = w - bboxes[(...), 0::4] - 1
    return flipped


@staticmethod
def str2bytes(ss):
    """
        Converts a string to a sequence of byte values.
        """
    return bytes(ss)


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

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


def get_doc():
    """Get documentation of this resource

    :return: rst string
    :rtype: str
    """
    return """
    The ``livesynthesis`` model is maintained by the Alignak backend to get an easy overview of
    the monitored system state.

    For hosts and services, the live synthesis stores values computed from the real
    live state, each time an element state is updated:
    - a counter containing the number of host/service not monitored (no active nor
    passive checks enabled)
    - a counter containing the number of host/service in each state
    - a counter containing the number of host/service acknowledged
    - a counter containing the number of host/service in downtime
    - a counter containing the number of host/service flapping
    - the maximum business impact of the host/service in the state
    """


@classmethod
def get_capabilities(cls):
    """Return an dictionary with the capabilities of each driver."""
    return cls.CAPABILITIES


@classmethod
def from_fresh(cls):
    """Construct a fresh position marker.

        This should be the default way of creating a new postion marker, and
        is where we define what the `start` of a file looks like.
        """
    return cls(1, 1, 1, 0)


def get_active_navigation_item(req):
    """This method is only called for the `IRequestHandler` processing
        the request.

        It should return the name of the navigation item to be highlighted
        as active/current.
        """


@classmethod
def focus(cls, appName):
    """ Searches for exact text, case insensitive, anywhere in the window title.

        Brings the matching window to the foreground.

        As a class method, accessible as `App.focus(appName)`. As an instance method,
        accessible as `App(appName).focus()`.
        """
    app = cls(appName)
    return app.focus()


@classmethod
def get(cls, project_id, model_id):
    """ Retrieve a model blueprint chart.

        Parameters
        ----------
        project_id : str
            The project's id.
        model_id : str
            Id of model to retrieve model blueprint chart.

        Returns
        -------
        ModelBlueprintChart
            The queried model blueprint chart.
        """
    url = 'projects/{}/models/{}/blueprintChart/'.format(project_id, model_id)
    return cls.from_location(url)


def _get_type(type_, enum):
    """Handle a type string, or just return an `int`

    Only to be called in relation to FrProcDataType and FrProcDataSubType
    """
    if isinstance(type_, int):
        return type_
    return enum[str(type_).upper()]


def get_user_pin(user_email):
    """
        returns the last pin used for a user's email
        """


def _encode_uvarint(data, n):
    """ Encodes integer into variable-length format into data."""
    if n < 0:
        raise ValueError('only support positive integer')
    while True:
        this_byte = n & 127
        n >>= 7
        if n == 0:
            data.append(this_byte)
            break
        data.append(this_byte | 128)


def delete_flavor(nova, flavor):
    """
    Deletes a flavor
    :param nova: the Nova client
    :param flavor: the SNAPS flavor domain object
    """
    nova.flavors.delete(flavor.id)


def __get_hostname():
    """
    Get the hostname of the worker
    """
    import socket
    return socket.gethostname()