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_manga_url_by_id(manga_id) ->str:
    """
    Returns manga url by id.

    :param manga_id: a manga id.

    :return: the manga url.
    """
    return 'http://www.anime-planet.com/manga/' + str(manga_id)


@staticmethod
def p_tp_data(p):
    """tp_data : generic_parameter_list"""
    p[0] = p[1]


def sign(x):
    """Return ``1.0`` if ``x`` is positive, ``-1.0`` otherwise."""
    if x > 0.0:
        return 1.0
    else:
        return -1.0


def __new__(mcs, name, bases, attrs):
    """
        Validate state definition
        """
    if bases != (object,):
        if name.lower() != name and not attrs.get('abstract', False):
            raise Exception(
                'Please use lowercase names for state definitions (instead of {})'
                .format(name))
        if 'description' not in attrs and not attrs.get('abstract', False):
            raise Exception(
                'Please give a description to this state definition')
    if 'handler' in attrs and len(attrs['handler'].__code__.co_varnames) < 2:
        raise Exception('StateDefinition handler needs at least two arguments')
    if 'handler' in attrs:
        attrs['handler'] = classmethod(attrs['handler'])
    return type.__new__(mcs, name, bases, attrs)


def file_content(file_name: str) ->str:
    """ returning content of the file specified by file_name arg as string.

    :param file_name:   file name to load into a string.
    :return:            file content string.
    """
    with open(file_name) as file_handle:
        return file_handle.read()


def vertex_weight_copy():
    """Copy weights from active to selected

    """
    pass


@classmethod
def randsample(cls, a, shape=None, replace=False, random_state=None):
    """Generates a random sample from a given array."""
    raise NotImplementedError


def _format_lines(lines):
    """Format the individual lines

    This will replace the '{', '}' and '~' characters of our mini
    formatting language with the proper 'where ...', 'and ...' and ' +
    ...' text, taking care of indentation along the way.

    Return a list of formatted lines.
    """
    result = lines[:1]
    stack = [0]
    stackcnt = [0]
    for line in lines[1:]:
        if line.startswith('{'):
            if stackcnt[-1]:
                s = 'and   '
            else:
                s = 'where '
            stack.append(len(result))
            stackcnt[-1] += 1
            stackcnt.append(0)
            result.append(' +' + '  ' * (len(stack) - 1) + s + line[1:])
        elif line.startswith('}'):
            stack.pop()
            stackcnt.pop()
            result[stack[-1]] += line[1:]
        else:
            assert line[0] in ['~', '>']
            stack[-1] += 1
            indent = len(stack) if line.startswith('~') else len(stack) - 1
            result.append('  ' * indent + line[1:])
    assert len(stack) == 1
    return result


def str_to_bool(string):
    """ Used as a type in argparse so that we get back a proper
    bool instead of always True
    """
    return string.lower() in ('y', 'yes', '1', 'true')


@property
def is_numberish(G):
    """
        A Game is numberish if it is infinitesimally close to a number. All Numbers are numberish.

        Returns
        -------
        numberish : bool
            Whether G is numberish or not (it is).
        """
    return True


def GetVersion(header):
    """

    gets the version of the header

    """
    pass


@classmethod
def from_mat_file(cls, file_name, cont_time=True, state_id='STATE',
    solver_options=None, estimator=None, visualizer=None, cache_region=
    'memory', name=None):
    """Create |LTIModel| from matrices stored in a .mat file.

        Parameters
        ----------
        file_name
            The name of the .mat file (extension .mat does not need to be included) containing A, B,
            C, and optionally D and E.
        cont_time
            `True` if the system is continuous-time, otherwise `False`.
        state_id
            Id of the state space.
        solver_options
            The solver options to use to solve the Lyapunov equations.
        estimator
            An error estimator for the problem. This can be any object with an
            `estimate(U, mu, model)` method. If `estimator` is not `None`, an `estimate(U, mu)`
            method is added to the model which will call `estimator.estimate(U, mu, self)`.
        visualizer
            A visualizer for the problem. This can be any object with a `visualize(U, model, ...)`
            method. If `visualizer` is not `None`, a `visualize(U, *args, **kwargs)` method is added
            to the model which forwards its arguments to the visualizer's `visualize` method.
        cache_region
            `None` or name of the cache region to use. See :mod:`pymor.core.cache`.
        name
            Name of the system.

        Returns
        -------
        lti
            The |LTIModel| with operators A, B, C, D, and E.
        """
    import scipy.io as spio
    mat_dict = spio.loadmat(file_name)
    assert 'A' in mat_dict and 'B' in mat_dict and 'C' in mat_dict
    A = mat_dict['A']
    B = mat_dict['B']
    C = mat_dict['C']
    D = mat_dict['D'] if 'D' in mat_dict else None
    E = mat_dict['E'] if 'E' in mat_dict else None
    return cls.from_matrices(A, B, C, D, E, cont_time=cont_time, state_id=
        state_id, solver_options=solver_options, estimator=estimator,
        visualizer=visualizer, cache_region=cache_region, name=name)


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

        :param NoteShareReceiveType val:
        :rtype: EventType
        """
    return cls('note_share_receive', val)


def per_section(it, is_delimiter=lambda x: x.isspace()):
    """
    From http://stackoverflow.com/a/25226944/610569
    """
    ret = []
    for line in it:
        if is_delimiter(line):
            if ret:
                yield ret
                ret = []
        else:
            ret.append(line.rstrip())
    if ret:
        yield ret


def find_module(root, predicate):
    """Find a (sub) module using a predicate.

    :param predicate:
        a callable with arguments ``(name, module)``.
    :returns:
        the first module for which the predicate is true or raises
        a ``RuntimeError``.
    """
    for k, v in root.named_modules():
        if predicate(k, v):
            return v
    else:
        raise RuntimeError('could not find module')


@staticmethod
def join_uid(prefix, sep, number, digits):
    """Join the parts of an item's UID into a string.
        >>> UID.join_uid('ABC', '', 123, 5)
        'ABC00123'
        >>> UID.join_uid('REQ.H', '-', 42, 4)
        'REQ.H-0042'
        >>> UID.join_uid('ABC', '-', 123, 0)
        'ABC-123'
        """
    return '{}{}{}'.format(prefix, sep, str(number).zfill(digits))


def get_basename(obj, remove_namespace=True, remove_attribute=False):
    """
    Get the base name in a hierarchy name (a|b|c -> returns c)
    :param obj: str, name to get base name from
    :param remove_namespace: bool, Whether to remove or not namespace from the base name
    :param remove_attribute: bool, Whether to remove or not attribute from the base name
    :return: str
    """
    split_name = obj.split('|')
    base_name = split_name[-1]
    if remove_attribute:
        base_name_split = base_name.split('.')
        base_name = base_name_split[0]
    if remove_namespace:
        split_base_name = base_name.split(':')
        return split_base_name[-1]
    return base_name


def filter_blackwhitelist(l, key):
    """
    Filter black/whitelist for the keys that belong to the
    subdirectory which is embedded into the nested dictionary
    structure with the given key.

    Three different cases:
    - if l is None, then return none
    - if key is None, then we are at the top-level dictionary, thus
      include all scalar keys and the first element of tuples.
    - if key is not None, then return only the keys that are tuples
      where the first element of the tuple matches the given key

    Parameters
    ----------
    l : list
        Black- or whitelist to filter
    key : scalar variable or None
        Key to filter for. See above for the behavior if key is None
    """
    if l is None:
        return None
    else:
        fl = []
        for k in l:
            if isinstance(k, tuple):
                if key is not None and k[0] == key:
                    if len(k) == 2:
                        fl.append(k[1])
                    else:
                        fl.append(k[1:])
                elif key is None:
                    fl.append(k[0])
            elif key is None:
                fl.append(k)
        if len(fl) == 0:
            return None
        else:
            return fl


@classmethod
def from_value(cls, value):
    """Convert a value to corresponding Enum member

        :param value: The value to compare to Enum members
           If it is already a member of Enum, it is returned directly.
        :return: The corresponding enum member
        :rtype: Enum
        :raise ValueError: In case the conversion is not possible
        """
    if isinstance(value, cls):
        return value
    for member in cls:
        if value == member.value:
            return member
    raise ValueError('Cannot convert: %s' % value)


def Dot2(a, b):
    """Return the dot product of two 2d vectors, a . b."""
    return a[0] * b[0] + a[1] * b[1]


def __init__(context):
    """Constructor. Takes the instance whose schema we are frobbing."""


def manifest_header(type_name, version='1.0'):
    """Returns a header, suitable for use in a manifest.

    >>> manifest_header("signature")
    "Signature-Version: 1.0"

    :param type_name: The kind of manifest which needs a header:
        "manifest", "signature".
    :param version: The manifest version to encode in the header
        (default: '1.0')
    """
    return u'{}-Version: {}'.format(type_name.title(), version)


def get_activation_by_name(activation_name, activation_id=None):
    """ Convert to a bigdl activation layer
        given the name of the activation as a string  """
    import bigdl.nn.layer as BLayer
    activation = None
    activation_name = activation_name.lower()
    if activation_name == 'tanh':
        activation = BLayer.Tanh()
    elif activation_name == 'sigmoid':
        activation = BLayer.Sigmoid()
    elif activation_name == 'hard_sigmoid':
        activation = BLayer.HardSigmoid()
    elif activation_name == 'relu':
        activation = BLayer.ReLU()
    elif activation_name == 'softmax':
        activation = BLayer.SoftMax()
    elif activation_name == 'softplus':
        activation = BLayer.SoftPlus(beta=1.0)
    elif activation_name == 'softsign':
        activation = BLayer.SoftSign()
    elif activation_name == 'linear':
        activation = BLayer.Identity()
    else:
        raise Exception('Unsupported activation type: %s' % activation_name)
    if not activation_id:
        activation.set_name(activation_id)
    return activation


def escape_search(term):
    """Wraps a search term in " and escape term's " and \\ characters"""
    strip_term = term.strip()
    return u'"%s"' % strip_term.replace('\\', '\\\\').replace('"', '\\"')


def calc_M20SS(peaks, HKL):
    """needs a doc string"""
    diff = 0
    X20 = 0
    for Nobs20, peak in enumerate(peaks):
        if peak[3]:
            Qobs = 1.0 / peak[8] ** 2
            Qcalc = 1.0 / peak[9] ** 2
            diff += abs(Qobs - Qcalc)
        elif peak[2]:
            X20 += 1
        if Nobs20 == 19:
            d20 = peak[8]
            break
    else:
        d20 = peak[8]
        Nobs20 = len(peaks)
    for N20, hkl in enumerate(HKL):
        if hkl[4] < d20:
            break
    Q20 = 1.0 / d20 ** 2
    if diff:
        M20 = Q20 / (2.0 * diff)
    else:
        M20 = 0
    M20 /= 1.0 + X20
    return M20, X20


def int_to_port_map(name, offset, number_of_interfaces):
    """
    Create a dict of interfaces to port maps
    :param name: Name of the base interface without the port number eg: swp
    :param offset: Number of the first interfaces eg: 0 or 1
    :param number_of_interfaces: Number of interfaces to create
    :return: Dictionary of interface to data port mappings
    """
    mapping = {}
    for i in range(offset, number_of_interfaces + offset):
        mapping.update({i: f'{name}{i}'})
    return mapping


@classmethod
def suggest(value, reversed=False, limit=None):
    """Suggest possible variants (some sort of auto-complete).

        :param str value:
        :param int limit: Limit number of suggested variants.
        :return list:
        """


def _compare_root(root):
    """
    Allow root comparison.

    Args:
        root (str or re.Pattern): Root.

    Returns:
        str: Comparable root string.
    """
    try:
        return root.pattern
    except AttributeError:
        return root


def compact_dict_none(dct):
    """
        Compacts a dct by removing pairs with a None value. Other nil values pass
    :param dct:
    :return: The filtered dict
    """
    return dict(filter(lambda key_value: key_value[1] != None, dct.items()))


@staticmethod
def metadata_updated_on(item):
    """Extracts the update time from a StackExchange item.

        The timestamp is extracted from 'last_activity_date' field.
        This date is a UNIX timestamp but needs to be converted to
        a float value.

        :param item: item generated by the backend

        :returns: a UNIX timestamp
        """
    return float(item['last_activity_date'])


@classmethod
def _decode(cls, packet, key_handler):
    """Decode an SSH certificate"""
    raise NotImplementedError


@classmethod
def Satisfies(cls, counter_values, update_instructions):
    """Return C{True} iff the counter values satisfy the update
        instructions.

        @param counter_values: A map from L{CounterCondition} to
        integer counter values

        @param update_instructions: A set of L{UpdateInstruction}
        instances

        @return: C{True} iff all instructions are satisfied by the
        values and limits."""
    for psi in update_instructions:
        if not psi.satisfiedBy(counter_values):
            return False
    return True


@classmethod
def get_asset_sensors(cls, session, asset_key):
    """Get sensors that belong to a particular asset

        Args:
            session: database session
            asset_key: key of the asset sensors belong to
        Returns:
            list: of sensor dictionaries
        """
    results = session.run(
        """
            MATCH (a:Asset { key: $key })-[:HAS_SENSOR]->(sensor:Sensor)
            OPTIONAL MATCH (sensor)-[:HAS_ADDRESS_SPACE]->(addr)
            RETURN sensor, addr
            """
        , key=int(asset_key))
    sensors = []
    for record in results:
        sensor = dict(record['sensor'])
        sensors.append({'specs': sensor, 'address_space': dict(record[
            'addr']) if 'index' in sensor else None})
    return sensors


def add_named(linked: bool=False, name: str=''):
    """Add named object

    :param linked: Linked, Duplicate object but not object data, linking to the original data
    :type linked: bool
    :param name: Name, Object name to add
    :type name: str
    """
    pass


def data_iter(dataset, vis_limit, vis_load, start_channel, stop_channel):
    """Wrapper around :py:meth:`katsdpimager.loader_core.LoaderBase.data_iter`
    that handles truncation to a number of visibilities specified on the
    command line.
    """
    N = vis_limit
    it = dataset.data_iter(start_channel, stop_channel, vis_load)
    for chunk in it:
        if N is not None:
            if N < len(chunk['uvw']):
                for key in ['uvw', 'baselines']:
                    if key in chunk:
                        chunk[key] = chunk[key][:N]
                for key in ['weights', 'vis']:
                    if key in chunk:
                        chunk[key] = chunk[key][:, :N]
                chunk['progress'] = chunk['total']
        yield chunk
        if N is not None:
            N -= len(chunk['uvw'])
            if N == 0:
                it.close()
                return


def merge_ranges(ranges):
    """
    Merge variables data range in a list to return a range of minimal min range
    value and maximal max range value extended of 10% for keeping a padding
    around graph in canvas
    @param ranges: [(range_min_value, range_max_value),...]
    @return: merged_range_min_value, merged_range_max_value
    """
    min_value = max_value = None
    for range_min, range_max in ranges:
        if min_value is None:
            min_value = range_min
        elif range_min is not None:
            min_value = min(min_value, range_min)
        if max_value is None:
            max_value = range_max
        elif range_min is not None:
            max_value = max(max_value, range_max)
    if min_value is not None and max_value is not None:
        center = (min_value + max_value) / 2.0
        range_size = max(1.0, max_value - min_value)
    else:
        center = 0.5
        range_size = 1.0
    return center - range_size * 0.55, center + range_size * 0.55


def serialize_graftpoints(graftpoints):
    """Convert a dictionary of grafts into string

    The graft dictionary is:
        <commit sha1>: [<parent sha1>*]

    Each line is formatted as:
        <commit sha1> <parent sha1> [<parent sha1>]*

    https://git.wiki.kernel.org/index.php/GraftPoint

    """
    graft_lines = []
    for commit, parents in graftpoints.items():
        if parents:
            graft_lines.append(commit + b' ' + b' '.join(parents))
        else:
            graft_lines.append(commit)
    return b'\n'.join(graft_lines)


def get_file_mapping(syn, release_folder_synid):
    """
    Get file mapping between important files needed for dashboard and
    their synapse ids

    Args:
        syn:  synapse object
        release_folder_synid: synapse id of release

    """
    files = syn.getChildren(release_folder_synid)
    file_mapping = dict()
    for metadata in files:
        filename = metadata['name']
        synid = metadata['id']
        if not filename.startswith('meta'):
            if filename.startswith('data_clinical_sample'):
                file_mapping['clinical'] = synid
            elif filename.endswith('fusions.txt'):
                file_mapping['fusion'] = synid
            elif filename.endswith('CNA.txt'):
                file_mapping['cna'] = synid
            elif filename.endswith('.seg'):
                file_mapping['seg'] = synid
    return file_mapping


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 load_notebook(library_db, path, notebook, library, raw_url=None):
    """load a notebook into the library db"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(library_db)
    cur = conn.cursor()
    load_library = (
        'INSERT OR IGNORE INTO "Notebooks"(Path, Notebook, Library, RawUrl) VALUES(?, ?, ?, ?)'
        )
    cur.execute(load_library, (path, notebook, library, raw_url))
    conn.commit()
    conn.close()


def get_distance_formatted(cls, loc):
    """
        Return the distance in nautical miles formatted to two decimal places, after calculating the distance between
        two different geographical location
        """
    return format(cls.get_distance(loc), '.2f')


@staticmethod
def plurality(probabilities, predictions):
    """Calculate the Plurality score for a mayor.

        Keyword arguments:
            probabilities -- a list of instances' probabilities,
                i.e, [ [voter's 1 instances' probabilities],
                       [voter's 2 instances' probabilities],
                       [voter's 3 instances' probabilities] ... ]
            predictions -- a list of instances' classes,
                i.e, [ [voter's 1 instances' classes],
                       [voter's 2 instances' classes],
                       [voter's 3 instances' classes] ... ]

        Score is calculated as the mean of class' probabilities.
        """
    ranking = list()
    n_classifiers = len(probabilities)
    n_instances = len(probabilities[0])
    for i in range(n_instances):
        class_count = dict()
        for c in range(n_classifiers):
            p = predictions[c][i]
            class_count[p] = class_count.get(p, 0) + 1
        class_rank = sorted(class_count.items(), key=lambda x: x[1],
            reverse=True)
        voted_class, n_votes = class_rank[0]
        sum_probabilities = 0
        for c in range(n_classifiers):
            if predictions[c][i] == voted_class:
                sum_probabilities += probabilities[c][i]
        prob_mean = sum_probabilities / n_votes
        ranking.append((i, prob_mean))
    ranking.sort(key=lambda x: x[0])
    return ranking


def copy():
    """Return a copy of this manifest."""


def set_headers(response, headers):
    """Sets the specified headers on the specified response.

    `response` is a Flask response object, and `headers` is a dictionary of
    headers to set on the specified response. Any existing headers that
    conflict with `headers` will be overwritten.

    """
    for key, value in headers.items():
        response.headers[key] = value


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

    The ".dev0" means dirty.

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


def get_versions():
    """
        Wait for a valid VERSION message to arrive, then return the peer's
        "versions" dictionary.  This dictionary comes from the ``versions=``
        argument to the peer's ``wormhole()`` constructor, and is meant to
        assist with capability-negotiation between the two peers.  In
        particular, the ``versions`` dictionary is delivered before either
        side has called ``send_message()``, so it can influence the first
        message sent to a peer that is too old to use that first message for
        negotiation purposes.

        If we receive any invalid encrypted message (such as what would
        happen if an attacker tried and failed to guess the wormhole code),
        this will instead errback with a ``WrongPasswordError``.

        :return: the verisions dictionary
        :rtype: ``Deferred[dict]``
        """


def _fd(f):
    """Get a filedescriptor from something which could be a file or an fd."""
    return f.fileno() if hasattr(f, 'fileno') else f


def write_file(path, content):
    """ Write a heap of bytes into a file found at path """
    if not isinstance(content, bytes):
        content = bytes(content)
    with open(path, 'wb') as device_file:
        device_file.write(content)
    return content


def copy_tracks():
    """Copy selected tracks to clipboard

    """
    pass


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))


def d2kvlist(d):
    "\n        d = {'GPSImgDirectionRef': 'M', 'GPSVersionID': b'\x02\x03\x00\x00', 'GPSImgDirection': (21900, 100)}\n        pobj(d)\n        kl,vl = d2kvlist(d)\n        pobj(kl)\n        pobj(vl)\n    "
    kl = list(d.keys())
    vl = list(d.values())
    return kl, vl


def get_prop_spec(client_factory, spec_type, properties):
    """Builds the Property Spec Object."""
    prop_spec = client_factory.create('ns0:PropertySpec')
    prop_spec.type = spec_type
    prop_spec.pathSet = properties
    return prop_spec


def finished():
    """
    A token value meaning that L{SiphonPendingValues} has no more values in its
    queue.
    """


def minute_trend_times(start, end):
    """Expand a [start, end) interval for use in querying for minute trends

    NDS2 requires start and end times for minute trends to be a multiple of
    60 (to exactly match the time of a minute-trend sample), so this function
    expands the given ``[start, end)`` interval to the nearest multiples.

    Parameters
    ----------
    start : `int`
        GPS start time of query

    end : `int`
        GPS end time of query

    Returns
    -------
    mstart : `int`
        ``start`` rounded down to nearest multiple of 60
    mend : `int`
        ``end`` rounded up to nearest multiple of 60
    """
    if start % 60:
        start = int(start) // 60 * 60
    if end % 60:
        end = int(end) // 60 * 60 + 60
    return int(start), int(end)


def is_int(obj):
    """
    True & False is not considered valid integers even if python considers them 1 & 0 in some versions
    """
    return isinstance(obj, int) and not isinstance(obj, bool)


def is_read_on_correct_strand(strand, read):
    """Check if read is on expected strand."""
    if strand == '+' and (read.is_read1 and read.is_reverse or read.
        is_read2 and not read.is_reverse):
        return True
    elif strand == '-' and (read.is_read1 and not read.is_reverse or read.
        is_read2 and read.is_reverse):
        return True
    return False


@staticmethod
def remove_duplicates(df):
    """ Sort the dataframe and remove duplicates -- note, not extensively tested """
    p1 = df[['p1', 'p2']].values.min(1)
    p2 = df[['p1', 'p2']].values.max(1)
    df['p1'] = p1
    df['p2'] = p2
    df.sort_values(['p1', 'p2'], inplace=True)
    df.drop_duplicates(['p1', 'p2'], inplace=True)
    df = df[df['p1'] != df['p2']]
    df.reset_index(inplace=True, drop=True)
    return df


def remove_batch_management_id(doc):
    """
    removes all batch id from doc/token
    """
    if 'wms_job_id' in doc:
        del doc['wms_job_id']
    if 'cream_job_id' in doc:
        del doc['cream_job_id']
    if 'pbs_job_id' in doc:
        del doc['pbs_job_id']


@classmethod
def list_types(cls):
    """
        List all available array types.

        """
    array_types = cls.get_types()
    for array_id, array in array_types.items():
        print(array_id)
        print(f"\tName: {array['name']}")
        print(f"\tType: {array['array_type']}")
        print(f"\tCompany: {array['company']}")
        print(f"\tSource: {array['source']}\n")


def get_schedules(api, params=None):
    """
    Get all schedules for user.

    :type api: :class:`mortar.api.v2.api.API`
    :param api: API

    :raises: requests.exception.HTTPError: if a 40x or 50x error occurs

    :rtype: dict:
    :returns: schedules
    """
    return api.get('schedules', params)


def register(introspector, action_info):
    """ Register this IIntrospectable with an introspector.  This method
        is invoked during action execution.  Adds the introspectable and its
        relations to the introspector.  ``introspector`` should be an object
        implementing IIntrospector.  ``action_info`` should be a object
        implementing the interface :class:`pyramid.interfaces.IActionInfo`
        representing the call that registered this introspectable.
        Pseudocode for an implementation of this method:

        .. code-block:: python

            def register(self, introspector, action_info):
                self.action_info = action_info
                introspector.add(self)
                for methodname, category_name, discriminator in self._relations:
                    method = getattr(introspector, methodname)
                    method((i.category_name, i.discriminator),
                           (category_name, discriminator))
        """


def items():
    """Return a list of (id, object) pairs."""


@staticmethod
def format_sizeof(num, suffix='', divisor=1000):
    """
        Formats a number (greater than unity) with SI Order of Magnitude
        prefixes.

        Parameters
        ----------
        num  : float
            Number ( >= 1) to format.
        suffix  : str, optional
            Post-postfix [default: ''].
        divisor  : float, optional
            Divisor between prefixes [default: 1000].

        Returns
        -------
        out  : str
            Number with Order of Magnitude SI unit postfix.
        """
    for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 999.5:
            if abs(num) < 99.95:
                if abs(num) < 9.995:
                    return '{0:1.2f}'.format(num) + unit + suffix
                return '{0:2.1f}'.format(num) + unit + suffix
            return '{0:3.0f}'.format(num) + unit + suffix
        num /= divisor
    return '{0:3.1f}Y'.format(num) + suffix


@classmethod
def _subclass_specific_config(cls, settings, common_config):
    """ Method to allow subclasses to extract configuration parameters
            specific to them and not covered in the common configuration
            in this class.
        """
    return {}


def _get_archive():
    """http://www.exploit-db.com/archive.tar.bz2"""


def is_in(value, values_set):
    """
    Computes whether an object is present in, or has at least one element that is present in, values_set. This is equivalent to computing whether two sets intersect (not disjoint), but where value does not have to be a set.

    Parameters
    ---------
    value : object
        data dictionary

    values_set : set
        set of values

    Returns
    -------
    bool
    """
    try:
        iter(value)
        is_iterable = True
    except TypeError:
        is_iterable = False
    if is_iterable and not isinstance(value, (str, bytes)):
        return not set(value).isdisjoint(values_set)
    else:
        return value in values_set


def serialize_func_name(func):
    """
    Returns the dotted serialized path to the passed function.
    """
    if func.__module__ == '__main__':
        raise ValueError(
            'Functions from the __main__ module cannot be processed by workers.'
            )
    try:
        func_name = func.__qualname__
    except AttributeError:
        func_name = func.__name__
    return ':'.join([func.__module__, func_name])


@classmethod
def _parse_bool(cls, value):
    """Represents value as boolean.

        :param value:
        :rtype: bool
        """
    value = value.lower()
    return value in ('1', 'true', 'yes')


def addon_enable(module: str=''):
    """Enable an add-on

    :param module: Module, Module name of the add-on to enable
    :type module: str
    """
    pass


@classmethod
def highlightRect(cls):
    """Highlights given rectangle.
        """
    return cls.build_send_payload('highlightRect', {}), None


def string_list(argument):
    """Parse a list of strings. If no argument is given, return an empty
    list."""
    return argument.split() if argument is not None else []


def make_parsnp_tree(fasta_files, reference_fasta=None, logfile=None):
    """
    For this one - get a list of fasta files, and then run parsnp
    :param fasta_files:
    :param reference_fasta:
    :return:
    """
    pass


def _set_symbol_class(cls):
    """Set the symbolic class to be cls"""
    global _symbol_cls
    _symbol_cls = cls


def is_bytes(data):
    """
    checks if the given data are of types `bytes` or `bytearray`
    """
    return isinstance(data, (bytes, bytearray))


def __call__():
    """Do the actual upgrade work."""


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 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 test_failover(ReplicationGroupId=None, NodeGroupId=None):
    """
    Represents the input of a TestFailover operation which test automatic failover on a specified node group (called shard in the console) in a replication group (called cluster in the console).
    For more information see:
    Also see, Testing Multi-AZ with Automatic Failover in the ElastiCache User Guide .
    See also: AWS API Documentation

    :example: response = client.test_failover(
        ReplicationGroupId='string',
        NodeGroupId='string'
    )

    :type ReplicationGroupId: string
    :param ReplicationGroupId: [REQUIRED]
            The name of the replication group (console: cluster) whose automatic failover is being tested by this operation.

    :type NodeGroupId: string
    :param NodeGroupId: [REQUIRED]
            The name of the node group (called shard in the console) in this replication group on which automatic failover is to be tested. You may test automatic failover on up to 5 node groups in any rolling 24-hour period.

    :rtype: dict
    :return: {
        'ReplicationGroup': {
            'ReplicationGroupId': 'string',
            'Description': 'string',
            'Status': 'string',
            'PendingModifiedValues': {
                'PrimaryClusterId': 'string',
                'AutomaticFailoverStatus': 'enabled'|'disabled'
            },
            'MemberClusters': [
                'string',
            ],
            'NodeGroups': [
                {
                    'NodeGroupId': 'string',
                    'Status': 'string',
                    'PrimaryEndpoint': {
                        'Address': 'string',
                        'Port': 123
                    },
                    'Slots': 'string',
                    'NodeGroupMembers': [
                        {
                            'CacheClusterId': 'string',
                            'CacheNodeId': 'string',
                            'ReadEndpoint': {
                                'Address': 'string',
                                'Port': 123
                            },
                            'PreferredAvailabilityZone': 'string',
                            'CurrentRole': 'string'
                        },
                    ]
                },
            ],
            'SnapshottingClusterId': 'string',
            'AutomaticFailover': 'enabled'|'disabled'|'enabling'|'disabling',
            'ConfigurationEndpoint': {
                'Address': 'string',
                'Port': 123
            },
            'SnapshotRetentionLimit': 123,
            'SnapshotWindow': 'string',
            'ClusterEnabled': True|False,
            'CacheNodeType': 'string'
        }
    }

    :returns:
    Viewing ElastiCache Events in the ElastiCache User Guide
    DescribeEvents in the ElastiCache API Reference

    """
    pass


def missing_gdk(finder, caller):
    """the gdk module is buried inside gtk so there is no need to concern
       ourselves with an error saying that it cannot be found"""
    caller.IgnoreName('gdk')


@staticmethod
def _create_axis_label_string(axis):
    """Create axis label conforming to conventions used in science

        This method is called automatically and indirectly by :meth:`plot`.

        If you ever need to change the appearance of your axes labels,
        override this method in a child class.
        """
    label = ''
    if axis.quantity:
        label = '$' + axis.quantity + '$' + ' / ' + axis.unit
    return label


@classmethod
def get_redirect_field_name(cls):
    """This method can be overwritten to implement custom user/session mechanizms
        currently it uses standard django.contrib.auth"""
    from django.contrib.auth import REDIRECT_FIELD_NAME
    return REDIRECT_FIELD_NAME


def groupby(x, key):
    """Like `itertools.groupby` but doesn't need to be sorted, and isn't lazy"""
    res = {}
    for o in x:
        res.setdefault(key(o), []).append(o)
    return res


def describe_rules_packages(rulesPackageArns=None, locale=None):
    """
    Describes the rules packages that are specified by the ARNs of the rules packages.
    See also: AWS API Documentation

    Examples
    Describes the rules packages that are specified by the ARNs of the rules packages.
    Expected Output:

    :example: response = client.describe_rules_packages(
        rulesPackageArns=[
            'string',
        ],
        locale='EN_US'
    )

    :type rulesPackageArns: list
    :param rulesPackageArns: [REQUIRED]
            The ARN that specifies the rules package that you want to describe.
            (string) --

    :type locale: string
    :param locale: The locale that you want to translate a rules package description into.

    :rtype: dict
    :return: {
        'rulesPackages': [
            {
                'arn': 'string',
                'name': 'string',
                'version': 'string',
                'provider': 'string',
                'description': 'string'
            },
        ],
        'failedItems': {
            'string': {
                'failureCode': 'INVALID_ARN'|'DUPLICATE_ARN'|'ITEM_DOES_NOT_EXIST'|'ACCESS_DENIED'|'LIMIT_EXCEEDED'|'INTERNAL_ERROR',
                'retryable': True|False
            }
        }
    }

    """
    pass


def _normalize(header):
    """Replace empty spaces with '-' and lower all chars
    """
    return header.replace(' ', '-').lower()


@classmethod
def fifteen_minute_EWMA(cls):
    """Creates a new EWMA which is equivalent to the UNIX fifteen minute
        load average and which expects to be ticked every 5 seconds.
        """
    return cls(cls.M15_ALPHA, cls.TICK_INTERVAL_S)


def extend_overstrand_backward(overstrand, start_cep):
    """
    Starting at a crossing (under or over), extend overstrand in the backwards
    direction until you hit another undercrossing.
    """
    cep = start_cep.previous()
    overstrand.insert(0, start_cep)
    while start_cep.is_over_crossing():
        overstrand.insert(0, cep)
        cep = cep.previous()
        if cep == overstrand[-1]:
            break


def _build_null_type(var, property_path=None):
    """ Builds schema definitions for null type values.

    :param var: The null type value
    :param List[str] property_path: The property path of the current type,
        defaults to None, optional
    :return: The built schema definition
    :rtype: Dict[str, Any]
    """
    if not property_path:
        property_path = []
    return {'type': 'null'}


def get_cal_data(data_df, cal_dict, param):
    """Get data along specified axis during calibration intervals

    Args
    ----
    data_df: pandas.DataFrame
        Pandas dataframe with lleo data
    cal_dict: dict
        Calibration dictionary

    Returns
    -------
    lower: pandas dataframe
        slice of lleo datafram containing points at -1g calibration position
    upper: pandas dataframe
        slice of lleo datafram containing points at -1g calibration position

    See also
    --------
    lleoio.read_data: creates pandas dataframe `data_df`
    read_cal: creates `cal_dict` and describes fields
    """
    param = param.lower().replace(' ', '_').replace('-', '_')
    idx_lower_start = cal_dict['parameters'][param]['lower']['start']
    idx_lower_end = cal_dict['parameters'][param]['lower']['end']
    idx_upper_start = cal_dict['parameters'][param]['upper']['start']
    idx_upper_end = cal_dict['parameters'][param]['upper']['end']
    idx_lower = (data_df.index >= idx_lower_start) & (data_df.index <=
        idx_lower_end)
    idx_upper = (data_df.index >= idx_upper_start) & (data_df.index <=
        idx_upper_end)
    return data_df[param][idx_lower], data_df[param][idx_upper]


def _positive_slice(slicer):
    """ Return full slice `slicer` enforcing positive step size

    `slicer` assumed full in the sense of :func:`fill_slicer`
    """
    start, stop, step = slicer.start, slicer.stop, slicer.step
    if step > 0:
        return slicer
    if stop is None:
        stop = -1
    gap = stop - start
    n = gap / step
    n = int(n) - 1 if int(n) == n else int(n)
    end = start + n * step
    return slice(end, start + 1, -step)


def sign(value):
    """
    Returns the sign of the given value
    :param value: float
    :return: -1 of the value is negative; 1 if the value is positive; 0 if the value is zero
    """
    return value and (1, -1)[value < 0]


def get_firmware_version(device_key: str) ->str:
    """
    Return device's current firmware version.

    :param device_key: Device identifier
    :type device_key: str
    :returns: version
    :rtype: str
    """
    pass


def get_phase_names(phase_name):
    """
    Called by parse_phase_list to replace e.g. ttall with the relevant phases.
    """
    lphase = phase_name.lower()
    names = []
    if lphase in ('ttp', 'tts', 'ttbasic', 'tts+', 'ttp+', 'ttall'):
        if lphase in ('ttp', 'ttp+', 'ttbasic', 'ttall'):
            names.extend(['p', 'P', 'Pn', 'Pdiff', 'PKP', 'PKiKP', 'PKIKP'])
        if lphase in ('tts', 'tts+', 'ttbasic', 'ttall'):
            names.extend(['s', 'S', 'Sn', 'Sdiff', 'SKS', 'SKIKS'])
        if lphase in ('ttp+', 'ttbasic', 'ttall'):
            names.extend(['PcP', 'pP', 'pPdiff', 'pPKP', 'pPKIKP', 'pPKiKP',
                'sP', 'sPdiff', 'sPKP', 'sPKIKP', 'sPKiKP'])
        if lphase in ('tts+', 'ttbasic', 'ttall'):
            names.extend(['sS', 'sSdiff', 'sSKS', 'sSKIKS', 'ScS', 'pS',
                'pSdiff', 'pSKS', 'pSKIKS'])
        if lphase in ('ttbasic', 'ttall'):
            names.extend(['ScP', 'SKP', 'SKIKP', 'PKKP', 'PKIKKIKP', 'SKKP',
                'SKIKKIKP', 'PP', 'PKPPKP', 'PKIKPPKIKP'])
        if lphase == 'ttall':
            names.extend(['SKiKP', 'PP', 'ScS', 'PcS', 'PKS', 'PKIKS',
                'PKKS', 'PKIKKIKS', 'SKKS', 'SKIKKIKS', 'SKSSKS',
                'SKIKSSKIKS', 'SS', 'SP', 'PS'])
    else:
        names.append(phase_name)
    return names


def leaders_to_left(iterable):
    """
     Leaders-to-left in the iterable is defined as if an element in the iterable
     is greater than all other elements to it's left side
    :param iterable: It should be of either list or tuple types containing numbers
    :return: list of tuples containing leader element and its index

        Eg: leaders_to_left([8, 3, 6, 10, 24, 3]) gives [(8, 0), (10, 3), (24, 4)]
            Here the elements at the indexes 0, 3, 4 are greater than all the elements to its left.
    """
    if type(iterable) == list or type(iterable) == tuple:
        pass
    else:
        raise TypeError('Iterable should be of either list or tuple')
    for item in iterable:
        if not isinstance(item, int):
            raise ValueError('Only numbers are accepted in the iterable')
    leaders_list = []
    if len(iterable) > 0:
        leaders_list.append((iterable[0], 0))
    for i in range(1, len(iterable)):
        if iterable[i] >= leaders_list[-1][0]:
            leaders_list.append((iterable[i], i))
    return leaders_list


def _is_colorbar_heuristic(obj):
    """Find out if the object is in fact a color bar.
    """
    try:
        aspect = float(obj.get_aspect())
    except ValueError:
        return False
    limit_ratio = 5.0
    return aspect >= limit_ratio and len(obj.get_xticks()
        ) == 0 or aspect <= 1.0 / limit_ratio and len(obj.get_yticks()) == 0


def __iter__():
    """return iterator of relations in catalog"""


@staticmethod
def process_source_covariates(covariates):
    """Process source covariates before saving them.

        This method is applied to the source covariates before they are saved.
        The method can be used to compute derived covariates

        Parameters
        ----------
        covariates : float[]
            Covariates describing the repulsiveness of sources

        """
    return covariates


def _parse_variable(v_xml):
    """Parse a variable given the xml representation of it.
    """
    mem_dict = {}
    mem_dd = v_xml.find('detaileddescription')
    try:
        mem_ddstr = mem_dd.find('para').text
    except AttributeError:
        mem_ddstr = ''
    mem_dict['detaileddescription'] = mem_ddstr
    mem_dict['type'] = v_xml.find('type').text
    return mem_dict


def _linear_interpolation(x, X, Y):
    """Given two data points [X,Y], linearly interpolate those at x.
    """
    return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])


def _resolve_key(key):
    """Helper to resolve key into /feature/setting

    :param key:
    :return:
    """
    map = {'metricsEnabled': '/metrics/enabled', 'loggingLevel':
        '/logging/loglevel', 'dataTraceEnabled': '/logging/dataTrace',
        'throttlingBurstLimit': '/throttling/burstLimit',
        'throttlingRateLimit': '/throttling/rateLimit', 'cachingEnabled':
        '/caching/enabled', 'cacheTtlInSeconds': '/caching/ttlInSeconds',
        'cacheDataEncrypted': '/caching/dataEncrypted',
        'requireAuthorizationForCacheControl':
        '/caching/requireAuthorizationForCacheControl',
        'unauthorizedCacheControlHeaderStrategy':
        '/caching/unauthorizedCacheControlHeaderStrategy'}
    return map[key]


def sj2(x, meanx, N):
    """
    The variance of a set of data points in one bin.

    Args:
        x (array): The flux array (defined as x in Stellingwerf, 1978).
        meanx (float): The mean of x.
        N (int): The number of data points

    Returns:
        The variance of x.

    """
    return sum((x - meanx) ** 2) / (N - 1)


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

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

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


def fix_value(value, split_stock_dates, today=None):
    """
    Need to convert by split stock dates
    """
    for date in split_stock_dates:
        if today < date.date:
            value *= date.from_number / float(date.to_number)
    return value


@classmethod
def add_handler(cls, handler):
    """Append a handler in the handlers list.

        Args:
            handler: Metrics handler.
        """
    cls.handlers.append(handler)


@classmethod
def from_string(cls, txt):
    """Convert a string to a encryption type constant"""
    if txt is None:
        return None
    t = txt.upper()
    if t in ('AES-256', 'AES_256'):
        return cls.CBC_AES_256_HMAC_SHA_256
    return getattr(cls, t, None)


def batch_iterable(iterable, count):
    """
    Yield batches of `count` items from the given iterable.

    >>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
    >>>   print(x)
    [1, 2, 3]
    [4, 5, 6]
    [7]

    :param iterable: An iterable
    :type iterable: Iterable
    :param count: Number of items per batch. If <= 0, nothing is yielded.
    :type count: int
    :return: Iterable of lists of items
    :rtype: Iterable[list[object]]
    """
    if count <= 0:
        return
    current_batch = []
    for item in iterable:
        if len(current_batch) == count:
            yield current_batch
            current_batch = []
        current_batch.append(item)
    if current_batch:
        yield current_batch


def create_socket(ctx, socket_type):
    """Creates zmq socket with default attributes
    """
    sock = ctx.socket(socket_type)
    sock.linger = 1000
    sock.rcvtimeo = 1000
    sock.sndhwm = 0
    sock.rcvhwm = 0
    return sock


def path(path=''):
    """
	Will return the specified path joined with os.getcwd().
	"""
    import os
    return os.path.join(os.getcwd(), path)


def remove_articles(text: str) ->str:
    """
    Removes articles from a given text. Not particularly fast, but since
    we are dealing with titles, no need to prematurely optimize.

    Note: currently, ITAD removes only 'the'...

    :param text: string from which articles (currently only 'the') need to be
                 removed
    :return: formatted string
    """
    articles = {'the': ''}
    remaining = []
    for word in text.split():
        if word not in articles:
            remaining.append(word)
    return ' '.join(remaining)


def rotword(w):
    """
    Function used in the Key Expansion routine that takes a four-byte word and
    performs a cyclic permutation.
    """
    w = w.reshape(4, 8)
    return w[1] + w[2] + w[3] + w[0]


def aa(codon):
    """
    This function converts a codon to an amino acid. If the codon is not
    valid an error message is given, or else, the amino acid is returned.
    """
    codon = codon.upper()
    aa = {'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'CTT': 'L', 'CTC': 'L', 'CTA':
        'L', 'CTG': 'L', 'TTA': 'L', 'TTG': 'L', 'GTT': 'V', 'GTC': 'V',
        'GTA': 'V', 'GTG': 'V', 'TTT': 'F', 'TTC': 'F', 'ATG': 'M', 'TGT':
        'C', 'TGC': 'C', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A',
        'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G', 'CCT': 'P', 'CCC':
        'P', 'CCA': 'P', 'CCG': 'P', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T',
        'ACG': 'T', 'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'AGT':
        'S', 'AGC': 'S', 'TAT': 'Y', 'TAC': 'Y', 'TGG': 'W', 'CAA': 'Q',
        'CAG': 'Q', 'AAT': 'N', 'AAC': 'N', 'CAT': 'H', 'CAC': 'H', 'GAA':
        'E', 'GAG': 'E', 'GAT': 'D', 'GAC': 'D', 'AAA': 'K', 'AAG': 'K',
        'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'AGA': 'R', 'AGG':
        'R', 'TAA': '*', 'TAG': '*', 'TGA': '*'}
    try:
        amino_a = aa[codon]
    except KeyError:
        amino_a = '?'
    return amino_a


@staticmethod
def toggle_sysinfo(_model, gui):
    """Turn system info panel on/off."""
    gui.sysinfo.toggle()


def shutdown_consumers(num_workers=2, tasks=None, shutdown_msg='SHUTDOWN'):
    """shutdown_consumers

    :param num_workers:
    :param tasks:
    :param shutdown_msg:
    """
    if tasks:
        for i in range(num_workers):
            tasks.put(shutdown_msg)


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

    The ".dev0" means dirty.

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


def split_method_call(handler_call_details):
    """
  Infers the grpc service and method name from the handler_call_details.
  """
    parts = handler_call_details.method.split('/')
    if len(parts) < 3:
        return '', '', False
    grpc_service_name, grpc_method_name = parts[1:3]
    return grpc_service_name, grpc_method_name, True


@staticmethod
def __split_key(key):
    """ Break the requested key into a list of items

        :param key: The config key to be validated
        :return:    List of items to traverse for the requested config value.
        """
    return key.split(u'.')


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

        :param SharedFolderMetadata val:
        :rtype: SharePathError
        """
    return cls('already_shared', val)


def get_extra_mimetypes():
    """Augment the Mimeview system with new mimetypes associations.

        This is an optional method. Not implementing the method or
        returning nothing is fine, the component will still be asked
        via `get_quality_ratio` if it supports a known mimetype.  But
        implementing it can be useful when the component knows about
        additional mimetypes which may augment the list of already
        mimetype to keywords associations.

        Generate ``(mimetype, keywords)`` pairs for each additional
        mimetype, with ``keywords`` being a list of keywords or
        extensions that can be used as aliases for the mimetype
        (typically file suffixes or Wiki processor keys).

        .. versionadded:: 1.0
        """


def scheduled_time(timestamp):
    """Specify a time for the delivery of this push.

    :param timestamp: A ``datetime.datetime`` object.

    """
    return {'scheduled_time': timestamp.strftime('%Y-%m-%dT%H:%M:%S')}


@classmethod
def get_by_email(cls, email):
    """
        Return a User by email address
        """
    return cls.query().filter(cls.email == email).first()


def render_template(template, context):
    """
    Generate an HTML test report.

    Args:
        template (Template): Jinja2 Template object containing the template to render
        context (dict): the context to pass to the template

    Returns:
        str: the contents of the rendered template
    """
    return template.render(context)


def parse_egg(egg):
    """Parses an egg and returns fields"""
    pres_list = egg.get_pres_items().values[0]
    rec_list = egg.get_rec_items().values[0]
    feature_list = egg.get_pres_features().values[0]
    dist_funcs = egg.dist_funcs
    return pres_list, rec_list, feature_list, dist_funcs


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

        :param NoPasswordLinkGenReportFailedDetails val:
        :rtype: EventDetails
        """
    return cls('no_password_link_gen_report_failed_details', val)


def down(ri, row_index):
    """ Starting at the row corresponding to ``row_index``, return the down.

        Given a root ideal ``ri`` and a starting position ``row_index``, move right on that row until you hit the root ideal (you are now standing ontop of a cell of the root ideal), then move straight down until you hit the diagonal, and return the new index.

        EXAMPLES:

        The picture below represents the root ideal ``ri``:

        .. image:: _static/root-ideal.JPG
            :width: 180px
            :align: center
            :alt: The root ideal [(0,2), (0,3), (0,4), (1,3), (1,4), (2,4)]

        ::

            sage: ri = RootIdeals().init_from_partition([3, 2, 1], 5)
            sage: ri.down(0)
            2
            sage: ri.down(1)
            3
            sage: ri.down(2)
            4
            sage: ri.down(3) == None
            True
            sage: ri.down(4) == None
            True

        ..  SEEALSO::

            :meth:`up`, :meth:`down_path`, :meth:`up_path`, :meth:`top`, :meth:`bottom`
        """
    for r, c in ri:
        if r == row_index:
            return c
    return None


@classmethod
def from_pubkey_file(cls, path):
    """ Constructor from a public key file.

        :param str path: public key filepath
        """
    with open(path, 'r') as f_in:
        return cls.from_pubkey_string(f_in.read())


def HiWord(value):
    """Return the high word from a long"""
    return value >> 16 & 65535


def read_genome(path):
    """Reads in FASTA formatted genome file.

    Arguments:
        path (str): Path to .galign file.

    Returns:
        string: String with the genomic sequence.
    """
    seq = ''
    for line in open(path):
        if line.startswith('>'):
            continue
        seq += line.strip()
    return seq


def get_limited_to(headers):
    """Return the user and project the request should be limited to.

    :param headers: HTTP headers dictionary
    :return: A tuple of (user, project), set to None if there's no limit on
    one of these.

    """
    return headers.get('X-User-Id'), headers.get('X-Project-Id')


def read_sys_file(path, default=None):
    """
    Read a file and return the contents as a string.

    This is best suited for files that store a single line of text such as
    files in /sys/.

    Returns the default value if an error occurs.
    """
    try:
        with open(path, 'r') as source:
            return source.read().strip()
    except:
        return default


def get_post_tags(post_id: str, posts_tags: list) ->list:
    """ Get associated tags by post_id """
    post_tags = list(filter(lambda tag: tag['post_id'] == post_id, posts_tags))
    return list(map(lambda tag: tag['tag_id'], post_tags))


def region_to_bin(chr_start_bin, bin_size, chr, start):
    """Translate genomic region to Cooler bin idx.

    Parameters:
    ----------
    chr_start_bin : dict
        Dictionary translating chromosome id to bin start index
    bin_size : int
        Size of the bin
    chr : str
        Chromosome
    start : int
        Start of the genomic region
    """
    return chr_start_bin[chr] + start // bin_size


def paz_to_sacpz_string(paz, instrument_sensitivity):
    """
    Returns SACPZ ASCII text representation of Response.

    :type paz: :class:`PolesZerosResponseStage`
    :param paz: Poles and Zeros response information
    :type instrument_sensitivity: :class:`InstrumentSensitivity`
    :param paz: Overall instrument sensitivity of response
    :rtype: str
    :returns: Textual SACPZ representation of poles and zeros response stage.
    """
    out = []
    out.append('ZEROS %i' % len(paz.zeros))
    for c in paz.zeros:
        out.append(' %+.6e %+.6e' % (c.real, c.imag))
    out.append('POLES %i' % len(paz.poles))
    for c in paz.poles:
        out.append(' %+.6e %+.6e' % (c.real, c.imag))
    constant = paz.normalization_factor * instrument_sensitivity.value
    out.append('CONSTANT %.6e' % constant)
    return '\n'.join(out)


def write_tabbed_excel(filepath, dict_df, **kwargs):
    """ Write each df in `dict_df` in a tab of the Excel spreadsheet in `filepath`.

    Parameters
    ----------
    filepath: str

    dict_df: Dict[pandas.DataFrame]

    kwargs:
        columns: list of str
            List of the columns of `df` to be written in the sheet.

        other arguments to be passed to the df.to_excel function.
    """
    from pandas import ExcelWriter
    with ExcelWriter(filepath) as writer:
        for key, df in dict_df.items():
            df.to_excel(writer, sheet_name=key, **kwargs)


@staticmethod
def get_dns_challenge_change_batch(action, domain, txt_challenge):
    """
        Given action, domain and challenge, return a change batch to use with
        route53 call.

        :param action: DELETE | UPSERT
        :param domain: domain name
        :param txt_challenge: challenge
        :return: change set for a given action, domain and TXT challenge.
        """
    return {'Changes': [{'Action': action, 'ResourceRecordSet': {'Name':
        '_acme-challenge.{0}'.format(domain), 'Type': 'TXT', 'TTL': 60,
        'ResourceRecords': [{'Value': '"{0}"'.format(txt_challenge)}]}}]}


def longest_non_overlapping_matches(sorted_matches):
    """Return a generator of the longest non-overlapping matches from a sorted
    list of matches."""
    start = -1
    for match in sorted_matches:
        if match.start < start:
            continue
        yield match
        start = match.end


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 unitary_test():
    """ Unitary test for vectors.py script.
    """


def echo_worker(data):
    """
    Example of worker that simply echoes back the received data.

    :param data: Request data dict.
    :returns: True, data
    """
    print('echo worker running')
    return data


def min_max_auto_replaced(box):
    """Resolve {min,max}-{width,height} constraints on replaced elements
    that have 'auto' width and heights.
    """
    width = box.width
    height = box.height
    min_width = box.min_width
    min_height = box.min_height
    max_width = max(min_width, box.max_width)
    max_height = max(min_height, box.max_height)
    violations = ('min' if width < min_width else 'max' if width >
        max_width else '', 'min' if height < min_height else 'max' if
        height > max_height else '')
    if width == 0:
        width = 1e-06
    if height == 0:
        height = 1e-06
    if violations == ('max', ''):
        box.width = max_width
        box.height = max(max_width * height / width, min_height)
    elif violations == ('min', ''):
        box.width = min_width
        box.height = min(min_width * height / width, max_height)
    elif violations == ('', 'max'):
        box.width = max(max_height * width / height, min_width)
        box.height = max_height
    elif violations == ('', 'min'):
        box.width = min(min_height * width / height, max_width)
        box.height = min_height
    elif violations == ('max', 'max'):
        if max_width / width <= max_height / height:
            box.width = max_width
            box.height = max(min_height, max_width * height / width)
        else:
            box.width = max(min_width, max_height * width / height)
            box.height = max_height
    elif violations == ('min', 'min'):
        if min_width / width <= min_height / height:
            box.width = min(max_width, min_height * width / height)
            box.height = min_height
        else:
            box.width = min_width
            box.height = min(max_height, min_width * height / width)
    elif violations == ('min', 'max'):
        box.width = min_width
        box.height = max_height
    elif violations == ('max', 'min'):
        box.width = max_width
        box.height = min_height


@classmethod
def from_swift_resp(cls, sw_resp):
    """
        Create a new S3 response object based on the given Swift response.
        """
    if sw_resp.app_iter:
        body = None
        app_iter = sw_resp.app_iter
    else:
        body = sw_resp.body
        app_iter = None
    resp = cls(status=sw_resp.status, headers=sw_resp.headers, request=
        sw_resp.request, body=body, app_iter=app_iter, conditional_response
        =sw_resp.conditional_response)
    resp.environ.update(sw_resp.environ)
    return resp


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 is_less_than(val_a, val_b):
    """Return True if val_a is less than val_b (evaluate as integer)"""
    size = len(val_a)
    if size != len(val_b):
        return False
    for i in reversed(range(size)):
        if val_a[i] < val_b[i]:
            return True
        elif val_a[i] > val_b[i]:
            return False
    return False


def next_method(it):
    """
    Get the method that yields next value from the given
    sync or async iterable. Returns (method, is_sync) tuple of
    the method and a boolean of whether the iterable is synchronous or not.
    """
    if hasattr(it, '__next__'):
        nxt = it.__next__
        is_sync = True
    elif hasattr(it, '__iter__'):
        nxt = it.__iter__().__next__
        is_sync = True
    elif hasattr(it, '__anext__'):
        nxt = it.__anext__
        is_sync = False
    elif hasattr(it, '__aiter__'):
        nxt = it.__aiter__().__anext__
        is_sync = False
    else:
        raise ValueError(f'{it} is not iterable')
    return nxt, is_sync


def extract_yaml(txt, sep):
    """Extracts YAML and returns it along with leftover."""
    tks = txt.split(sep)
    return tks[1], ''.join(tks[2:])


def zero_op(*args, **kws):
    """
    this is a zero op. It takes any arguments, keyword
    or positional, and returns zero.
    """
    return 0


def case_2(node, op_nodes):
    """ Case when node have only operator's like children.
    In that case choice operator with one node as top node.

    Example:
    E->[*->[a,a], +->[a]] to [+->[*->[a,a],a]]"""
    parent = node.parent
    if len(op_nodes[0].children) in (0, 1):
        top_op_node = op_nodes[0]
        buttom_op_node = op_nodes[1]
    elif len(op_nodes[1].children) in (0, 1):
        top_op_node = op_nodes[1]
        buttom_op_node = op_nodes[0]
    else:
        import pdb
        pdb.set_trace()
        raise BaseException('case_2 no top node error')
    top_op_node.add_child(buttom_op_node)
    if parent is not None:
        parent.replace_child(node, top_op_node)
        return parent
    else:
        top_op_node.parent = parent
        return top_op_node


def pad(coll, size, padding, left=True):
    """
    Pad the collection `coll` with `padding` items
    until it reaches the length of `size`.
    By default do padding in the beginning (on the left side).
    """
    padding_size = size - len(coll)
    if padding_size <= 0:
        return coll
    padding = [padding] * padding_size
    new_list = list(coll)
    return padding + new_list if left else new_list + padding


def _diff_attribute_values(old_value, new_value):
    """Returns True if the attribute values are different."""
    are_different = len(old_value) != len(new_value)
    if not are_different:
        old_value_dict = dict.fromkeys(old_value)
        new_value_dict = dict.fromkeys(new_value)
        for v in old_value:
            if v not in new_value_dict:
                are_different = True
                break
        if not are_different:
            for v in new_value:
                if v not in old_value_dict:
                    are_different = True
                    break
    return are_different


def _validate_yaml_dict(yaml_dict):
    """Validate dict parsed from yaml configuration file
    :param yaml_dict: dict parsed from yaml configuration file
    :raises TypeError: if configuration file has several levels of nesting or param is not dict
    """
    if not isinstance(yaml_dict, dict):
        raise TypeError(f'configuration file has several levels of nesting.')
    for key, value in yaml_dict.items():
        if not isinstance(key, str) or isinstance(value, dict):
            raise TypeError(
                f'configuration file has several levels of nesting.')


def checksubstate(repo, baserev=None):
    """return list of subrepos at a different revision than substate.
    Abort if any subrepos have uncommitted changes."""
    inclsubs = []
    wctx = repo[None]
    if baserev:
        bctx = repo[baserev]
    else:
        bctx = wctx.p1()
    for s in sorted(wctx.substate):
        wctx.sub(s).bailifchanged(True)
        if s not in bctx.substate or bctx.sub(s).dirty():
            inclsubs.append(s)
    return inclsubs


def str_to_numeric(s):
    """
    Convert a string to a numeric type.

    Returns either an int or a float depending on the apparent type of the
    string.
    """
    try:
        return int(s)
    except ValueError:
        return float(s)


@classmethod
def add_hook(cls, hook_type, hook_func):
    """Add a new hook of specified type.

        :param cls: class that registers hooks
        :param hook_type: hook type, e.g., '__pre_parse_args__'
        :param hook_func: hook function
        """
    if hook_type not in cls._hooks_map:
        cls._hooks_map[hook_type] = []
    cls._hooks_map[hook_type].append(hook_func)


def superValues(t):
    """Return all of the objects of a given type located in this object
        and containing objects.
        """


def get_list_transpose(list):
    """
    Take the transpose of a list of tuples.

    Parameters
    ----------
    list: list
        List of tuples. Ex. [(1,2),(2,3),(3,4)].

    Returns
    -------
    list
        Transpose of the list. Ex [[1,2,3],[2,3,4]].
    """
    verso = [[], []]
    for x, y in list:
        verso[0].append(x)
        verso[1].append(y)
    return verso


@staticmethod
def run_metadata(pathfmt):
    """Execute the postprocessor for a file"""


def mass_to_volume_mixing_ratio(mass_mixing_ratio, molecular_weight=None,
    molecular_weight_air=28.964):
    """
    g/g or g/kg to mole/mole

    Converts from mass mixing ratio (mass per unit mass) to volume
    mixing ratio (volume per unit volume)

    Args:

        mass_mixing_ratio (array):
            The quantity to be transformed in units of :math:`g/g`.

        molecular_weight (float):
            The molecular weight of the gas in :math:`g/mol`.

        molecular_weight_air (float,optional):
            The molecular weight of dry air.
            If it is not provided, the value for dry air on earth (28.964 g/mol)
            is used.

    Returns:

        volume_mixing_ratio (array):
            The volume mixing ratio of the gas.

    Raises:

        ValueError:
            if the molecular weight is not provided.

    """
    if molecular_weight is None:
        raise ValueError('The molecular weight must be provided')
    volume_mixing_ratio = (mass_mixing_ratio * molecular_weight_air /
        molecular_weight)
    return volume_mixing_ratio


def _collect_missing_target_counter(counter_name, lookup_counter_values,
    anchor_name, missing_target_counters):
    """Collect missing target counters.

    The corresponding TargetLookupItem caches the target's page based
    counter values during pagination.

    """
    if counter_name not in lookup_counter_values:
        missing_counters = missing_target_counters.setdefault(anchor_name, [])
        if counter_name not in missing_counters:
            missing_counters.append(counter_name)


@classmethod
def get_result(cls, response):
    """
        Retrieve a result from the HTTP response
        :param response: a response object
        :return: either the 'result' dict, or None if no result is returned
        """
    j = response.json()
    no_results = j.get('result', None) is None
    if response.ok and j.get('success', False) and not no_results:
        return j.get('result', j)
    else:
        return None


def force_sequence(var, sequence_type=list):
    """
    Returns the given variable as sequence
    If the given variable is list or tuple and sequence_type is different, a conversion will be forced
    :param var: variant
    :return: sequence (tuple || list)
    """
    if type is not list or not tuple:
        sequence_type = list
    if type(var) == list and sequence_type == tuple:
        var = tuple(var)
    if type(var) == tuple and sequence_type == list:
        var = list(var)
    if not type(var) == sequence_type:
        return sequence_type(var)
    return var


def map_base(available_items, id_):
    """Basemapping for attributes in ticketbox
    """
    for available_item in available_items:
        if id_ == available_item.get('id'):
            return available_item.get('title')
    return ''


def loc_clear():
    """Reset locations of selected bones to their default values

    """
    pass


def columns_from_dict(df, dict_col):
    """Takes in a Pandas Series that contains only dictionaries with the same keys.
    Will Create New Columns with the dictionaries keys"""
    df = df.copy()
    index = 0
    for i in range(len(dict_col)):
        if isinstance(dict_col[i], dict):
            index = i
            break
    try:
        dict_col[index].keys()
    except:
        return df
    for key in dict_col[index].keys():
        df[dict_col.name + '_' + key] = dict_col.apply(lambda x: x[key] if
            isinstance(x, dict) else x)
    return df.drop(dict_col.name, axis=1)


def image_registration_methodv4(*args, **kwargs):
    """Procedural interface for ImageRegistrationMethodv4"""
    import itk
    instance = itk.ImageRegistrationMethodv4.New(*args, **kwargs)
    return instance.__internal_call__()


def available():
    """ Whether this notification is available
        """


def isfloat(value):
    """
    Check input for float conversion.

    :param value: input value
    :type value:str
    :return: True if input_value is a number and False otherwise
    """
    try:
        float(value)
        return True
    except ValueError:
        return False


def isreal(obj):
    """
    Test if the argument is a real number (float or integer).

    :param obj: Object
    :type  obj: any

    :rtype: boolean
    """
    return obj is not None and not isinstance(obj, bool) and isinstance(obj,
        (int, float))


def kama(df, price, kama, n, fast_ema=2, slow_ema=30):
    """
    Kaufman's Adaptive Moving Average (KAMA) is a moving average designed to
    account for market noise or volatility. KAMA will closely follow prices when
    the price swings are relatively small and the noise is low. KAMA will adjust
    when the price swings widen and follow prices from a greater distance.

    Parameters:
        df (pd.DataFrame): DataFrame which contain the asset information.
        price (string): the column name for the series type of the asset.
        kama (string): the column name for the kama results.
        n (int): the total number of periods.
        fast_ema (int): the time period of the fast exponential moving average.
        slow_ema (int): the time period of the slow exponential moving average.

    Returns:
        df (pd.DataFrame): Dataframe with kama of the asset calculated.

    """
    er = df[price].diff(n).abs() / df[price].diff().abs().rolling(window=n
        ).sum()
    fast_sc = 2 / (fast_ema + 1)
    slow_sc = 2 / (slow_ema + 1)
    df[kama + '_sc'] = (er * (fast_sc - slow_sc) + slow_sc) ** 2
    prev_kama = list(df[:n][price].rolling(window=n).mean())[-1]
    df.loc[n - 1, kama] = prev_kama
    df.loc[n:, (kama)] = 0.0
    kamas = [(0.0) for i in range(n)]
    for row in df.loc[n:, ([price, kama + '_sc'])].itertuples(index=False):
        kamas.append(prev_kama + row[1] * (row[0] - prev_kama))
        prev_kama = kamas[-1]
    df[kama] += kamas
    df = df.dropna().reset_index(drop=True)
    df.drop([kama + '_sc'], axis=1, inplace=True)
    return df


def isPyPy():
    """Returns either scapy is running under PyPy or not"""
    try:
        import __pypy__
        return True
    except ImportError:
        return False


def nodesep(ligne):
    """
    Défini les valeurs nodesep : 0 pour une extrémité, -0.5 pour une continuité
    @param ligne: droite, demi-droite, segment
    @type ligne: string
    """
    if ligne == 'une droite':
        retour = ['-6', '-6']
    elif ligne == 'une demi-droite':
        retour = ['0', '-6']
    else:
        retour = ['0', '0']
    return retour


def _have_cython():
    """
    Return True if Cython can be imported.
    """
    cython_impl = 'Cython.Distutils.build_ext'
    try:
        __import__(cython_impl, fromlist=['build_ext']).build_ext
        return True
    except Exception:
        pass
    return False


def clear_xml(tree):
    """
    Removes comments and executes xinclude tags of an
    xml tree.

    :param tree: an xml-tree which will be processes
    :return cleared_tree: an xml-tree without comments and with replaced xinclude tags
    """
    import copy
    cleared_tree = copy.deepcopy(tree)
    cleared_tree.xinclude()
    comments = cleared_tree.xpath('//comment()')
    for comment in comments:
        com_parent = comment.getparent()
        com_parent.remove(comment)
    return cleared_tree


def theta_Cl_HCO3_PP82(T, P):
    """a-a': chloride bicarbonate [PP82]."""
    theta = 0.0359
    valid = T == 298.15
    return theta, valid


@staticmethod
def format_finger_print(fingerprint):
    """
        Formats a fingerprint.

        :param fingerprint: fingerprint
        :type: string

        :returns: Formatted fingerprint
        :rtype: string
        """
    formatted_fingerprint = fingerprint.replace(':', '')
    return formatted_fingerprint.lower()


def default_tc_k_factor_curve():
    """
    Returns a default k factor curve for a generic torque converter.

    :return:
        k factor curve.
    :rtype: callable
    """
    from ..defaults import dfl
    par = dfl.functions.default_tc_k_factor_curve
    a = par.STAND_STILL_TORQUE_RATIO, par.LOCKUP_SPEED_RATIO
    from . import define_k_factor_curve
    return define_k_factor_curve(*a)


def _routes_definitions(df):
    """
    Append GTFS definitions for route columns to route dataframe

    Parameters
    ----------
    df : pandas:DataFrame
        routes dataframe

    Returns
    -------
    df : pandas.DataFrame
    """
    if 'route_type' in df.columns:
        routes_route_type = {(0):
            'Street Level Rail: Tram Streetcar Light rail', (1):
            'Underground rail: Subway or Metro', (2):
            'Rail: intercity or long-distance ', (3): 'Bus', (4): 'Ferry',
            (5): 'Cable Car', (6): 'Gondola or Suspended cable car', (7):
            'Steep incline: Funicular'}
        df['route_type_desc'] = df['route_type'].map(routes_route_type.get)
    return df


def IRAD(val):
    """InvestigatorAffiliation"""
    return val