def format_signature_validity(rev_id, branch):
    """get the signature validity

    :param rev_id: revision id to validate
    :param branch: branch of revision
    :return: human readable string to print to log
    """
    from breezy import gpg
    gpg_strategy = gpg.GPGStrategy(branch.get_config_stack())
    result = branch.repository.verify_revision_signature(rev_id, gpg_strategy)
    if result[0] == gpg.SIGNATURE_VALID:
        return u'valid signature from {0}'.format(result[1])
    if result[0] == gpg.SIGNATURE_KEY_MISSING:
        return 'unknown key {0}'.format(result[1])
    if result[0] == gpg.SIGNATURE_NOT_VALID:
        return 'invalid signature!'
    if result[0] == gpg.SIGNATURE_NOT_SIGNED:
        return 'no signature'


def worry(x):
    """
    :param x [x, y, z, k, g] history record

    Neuron sense, worry will focus on relation between
    x[2] and x[5] where first is a batch size and second the
    percentage of omitted objects according to total objects
    """
    y = x[2] - x[5]
    if y == x[2]:
        return 0
    else:
        return y / 10


def compute_error(res_1, res_2):
    """
    Compute the error between two set of data.

    Parameters
    ----------
    res_1 : numpy array or pandas DataFrame
        The reference results.
    res_2 : numpy array or pandas DataFrame
        The new results.

    Returns
    -------
    abs_err : numpy array or pandas DataFrame
        The absolute error between the results.
    rel_err : numpy array or pandas DataFrame
        The relative error between the results.

    """
    abs_err = res_2 - res_1
    rel_err = res_2 / res_1 - 1.0
    return abs_err, rel_err


def drawAsInfinite(requestContext, seriesList):
    """
    Takes one metric or a wildcard seriesList.
    If the value is zero, draw the line at 0. If the value is above zero, draw
    the line at infinity. If the value is null or less than zero, do not draw
    the line.

    Useful for displaying on/off metrics, such as exit codes. (0 = success,
    anything else = failure.)

    Example::

        drawAsInfinite(Testing.script.exitCode)

    """
    for series in seriesList:
        series.options['drawAsInfinite'] = True
        series.name = 'drawAsInfinite(%s)' % series.name
    return seriesList


@staticmethod
def _construct_range_header(boundaries):
    """
        Construct the correct value for the Range header, given a closed or open-ended range.

        :param boundaries:
            The range of bytes (inclusive)
        :type boundaries:
            (`int`) or (`int`, `int`)
        :returns:
            The value for the Range header
        :rtype:
            `unicode`
        :raises ValueError:
        """
    if len(boundaries) == 1:
        return 'bytes={0}-'.format(*boundaries)
    elif len(boundaries) == 2:
        return 'bytes={0}-{1}'.format(*boundaries)
    else:
        raise ValueError('Expected a 1-tuple or 2-tuple for byte range')


def type_str(v):
    """
    Return a type string of the form module.name for the input value v
    """
    if not isinstance(v, type):
        v = type(v)
    return "'{module}.{name}'".format(module=v.__module__, name=v.__name__)


def _predict_output_scikit_MLPRegressor(model, input):
    """
    Predict output function for scikit-learn MLPRegressor objects.
    """
    output = model.predict(input)
    if output.ndim == 1:
        output = output.reshape(-1, 1)
    return output


def filter_whitespace(source):
    """A generator to filter out whitespace from text read from
    a file-like source.

    """
    for line in source:
        for c in line:
            if not c.isspace():
                yield c


def setOfflineUsername(_name, _key):
    """
    Sets the username and key for the session

    Equivalent of the setDBUsername function in database.py
    """
    global name
    global key
    name = _name
    key = _key


def addon_userpref_show(module: str=''):
    """Show add-on user preferences

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


def get_notation(notation_def):
    """
    Auxiliar function ro retrieve notation
    """
    if notation_def != None:
        return notation_def
    else:
        from .. import notation
        return notation


@classmethod
def _create(cls, model_class, *args, **kwargs):
    """
        Create a new user instance.

        Args:
            model_class:
                The type of model to create an instance of.
            args:
                Positional arguments to create the instance with.
            kwargs:
                Keyword arguments to create the instance with.

        Returns:
            A new user instance of the type specified by
            ``model_class``.
        """
    manager = cls._get_manager(model_class)
    return manager.create_user(*args, **kwargs)


@classmethod
def insert(cls, obj):
    """Insert a row into the database

        :param obj: the object model to insert
        :returns:
        :rtype:
        """
    if obj.__tablename__ not in cls.Base.metadata.tables.keys():
        cls.create_model()
    cls.session.add(obj)
    cls.session.commit()


def hashfile(file_path, hash, key=None, digest_size=None):
    """
    Gets the hash of a file.
    file_path = Absolute path of the file

    Usage:

    """
    with open(file_path, 'r') as file:
        contents = file.read()
        contents = ''.join(contents)
        file.close()
    contents = bytes(contents)
    import hashlib
    if hash == 'md5':
        re = hashlib.md5(contents)
        return re.hexdigest()
    elif hash == 'sha256':
        returnEncoded = hashlib.sha256()
        returnEncoded.update(contents)
        return returnEncoded.hexdigest()
    elif hash == 'sha224':
        returnEncoded = hashlib.sha224(contents)
        return returnEncoded.hexdigest()
    elif hash == 'ripemd160':
        returnEncoded = hashlib.new('ripemd160')
        returnEncoded.update(contents)
        return returnEncoded.hexdigest()
    elif hash == 'blake2b':
        h = hashlib.blake2b(key=key, digest_size=digest_size)
        h.update(contents)
        return h.hexdigest()
    elif hash == 'sha512':
        h = hashlib.sha512()
        h.update(contents)
        return h.hexdigest()
    elif hash == 'blake2s':
        h = hashlib.blake2s(key=key, digest_size=digest_size)
        h.update(contents)
        return h.hexdigest()
    else:
        raise SyntaxError(
            'Specify a valid hash (md5, sha256, sha224, ripemd160, blake2b, blake2s or sha512)'
            )


def listen_queue(socket_num=0):
    """Returns listen queue (backlog size) of the given socket.

    :param int socket_num: Socket number.

    :rtype: int

    :raises ValueError: If socket is not found
    """
    return 0


def calculate_checksum(bytes_):
    """
    Calculates the checksum for bytes_.

    :param bytes_: A string of bytes representing the raw header and body of a FIX message.
    :return: The checksum value calculated over bytes_.
    """
    return sum(bytes_) % 256


def max_len_list_dict_item(list_dict, attr):
    """
    Returns max length of a given attribute from a list of dict items.
    """
    length = 0
    for item in list_dict:
        length = length if length > len(item[attr]) else len(item[attr])
    return length


def lineupPos(i, num, spacing):
    """
    use to line up a series of 'num' objects, in one dimension,
    centered around zero
    'i' is the index of the object in the lineup
    'spacing' is the amount of space between objects in the lineup
    """
    assert num >= 1
    assert i >= 0 and i < num
    pos = float(i) * spacing
    return pos - float(spacing) * (num - 1) / 2.0


def reverse_array(arr):
    """
    Reverse an array along all axes, so arr[i,j] -> arr[-(i+1),-(j+1)].
    """
    reverse_slice = tuple(slice(None, None, -1) for ii in arr.shape)
    return arr[reverse_slice]


@staticmethod
def basal_apical_axis(eptm, cell):
    """
        Returns a unit vector allong the apical-basal axis of the cell
        """
    edges = eptm.edge_df[eptm.edge_df['cell'] == cell]
    srce_segments = eptm.vert_df.loc[edges['srce'], 'segment']
    srce_segments.index = edges.index
    trgt_segments = eptm.vert_df.loc[edges['trgt'], 'segment']
    trgt_segments.index = edges.index
    ba_edges = edges[(srce_segments == 'apical') & (trgt_segments == 'basal')]
    return ba_edges[eptm.dcoords].mean()


def colormap_select(base_colormap, start=0, end=1.0, reverse=False):
    """
    Given a colormap in the form of a list, such as a Bokeh palette,
    return a version of the colormap reversed if requested, and selecting
    a subset (on a scale 0,1.0) of the elements in the colormap list.

    For instance:

    >>> cmap = ["#000000", "#969696", "#d9d9d9", "#ffffff"]
    >>> colormap_select(cmap,reverse=True)
    ['#ffffff', '#d9d9d9', '#969696', '#000000']
    >>> colormap_select(cmap,0.3,reverse=True)
    ['#d9d9d9', '#969696', '#000000']
    """
    full = list(reversed(base_colormap) if reverse else base_colormap)
    num = len(full)
    return full[int(start * num):int(end * num)]


def remote_field(field):
    """
    https://docs.djangoproject.com/en/1.9/releases/1.9/#field-rel-changes
    """
    return field.remote_field


def get_lomb_signif(lomb_model):
    """
    Get the significance (in sigmas) of the first frequency from a fitted
    Lomb-Scargle model.
    """
    return lomb_model['freq_fits'][0]['signif']


def point_orientation(a, b, c):
    """Returns the orientation of the triangle a, b, c.

    Return True if a,b,c are oriented clock-wise.
    """
    return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y) >= 0


def isFuture():
    """Return true if this object represents a date/time later
        than the time of the call"""


def get_base_input(test=False):
    """
    Return DateTimeBaseInput class from django.forms.widgets module

    Return _compatibility.DateTimeBaseInput class for older django versions.
    """
    from django.forms.widgets import DateTimeBaseInput
    if 'get_context' in dir(DateTimeBaseInput) and not test:
        base_input = DateTimeBaseInput
    else:
        from bootstrap_datepicker_plus._compatibility import CompatibleDateTimeBaseInput
        base_input = CompatibleDateTimeBaseInput
    return base_input


@staticmethod
def get_named_entity_dict(doc):
    """
        To get named entities from NLP processed text
        :param doc: spacy container for linguistic annotations.
        :return: dictionary containing entity_text and entity_label
        """
    entity_details_dict = {'ent_text': [], 'ent_label': []}
    for ent in doc.ents:
        entity_details_dict['ent_text'].append(ent.text)
        entity_details_dict['ent_label'].append(ent.label_)
    return entity_details_dict


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

        :param FileUnresolveCommentDetails val:
        :rtype: EventDetails
        """
    return cls('file_unresolve_comment_details', val)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a QueryEntitiesEntity object from a json dictionary."""
    args = {}
    if 'text' in _dict:
        args['text'] = _dict.get('text')
    if 'type' in _dict:
        args['type'] = _dict.get('type')
    return cls(**args)


def _get_added_removed(after, before):
    """Get lists of items removed from `before`
    and a lists of items added to `after`
    """
    added = list(set(after) - set(before))
    removed = list(set(before) - set(after))
    added.sort()
    removed.sort()
    return added, removed


@staticmethod
def _write_longtable_end(buf):
    """
        Write the end of a longtable environment.

        Parameters
        ----------
        buf : string or file handle
            File path or object. If not specified, the result is returned as
            a string.

        """
    buf.write('\\end{longtable}\n')


@classmethod
def js(class_, url):
    """Produces a chunk of XHTML for including JS file with this p_url"""
    return '<script src="%s"></script>' % url


def interval64_pack(m_d_timetup, qll_pack=qll_pack, mktime64=mktime64):
    """
	Given a triple, (month, day, (seconds, microseconds)), return the serialized
	data using a quad-word for the (seconds, microseconds) tuple.
	"""
    month, day, timetup = m_d_timetup
    return qll_pack((mktime64(timetup), day, month))


def get_recent_iex(*args, **kwargs):
    """
    Returns market volume and trade routing statistics for recent sessions.
    Also reports IEX's relative market share, lit share volume and a boolean
    halfday indicator.

    Reference: https://www.iextrading.com/developer/docs/#recent

    Returns
    -------
    DataFrame
    """
    from pandas_datareader.iex.stats import RecentReader
    return RecentReader(*args, **kwargs).read()


def cmd_check(check_input, return_type=str):
    """
	Allows user to execute commands at any point

	check_input: Input to be checked
	"""
    if check_input == 'exit':
        exit()
    return check_input


def cdata(data):
    """Wraps items in CDATA tag"""
    if not data:
        return ''
    return f'<![CDATA[\n{data}\n]]>'


def nested_get(data, lookup):
    """
    Preform a nested dict and list lookup.
    """
    for key in lookup.split(':'):
        if isinstance(data, list):
            try:
                idx = int(key)
                data = data[idx]
            except (ValueError, IndexError):
                raise KeyError
        else:
            try:
                data = data[key]
            except (KeyError, TypeError):
                raise KeyError
    return data


def _reapchildren(children):
    """
    Check all <children> Popen objects in the dictionary for returncodes.

    Yield the result if they have completed.

    :param children:
    :return:
    """
    for pid in list(children.keys()):
        ret = children[pid].poll()
        if ret is None:
            continue
        msg = 'child exited with %s' % ret
        yield children[pid].number, children[pid], msg, list(children.keys())
        del children[pid]


def ibatch(iterable, batch_size):
    """Collect data into fixed-length chunks"""
    return zip(*([iterable] * batch_size))


def setBit(value, bit, bitval):
    """Returns value with a specific bit position set to bitval."""
    if bitval:
        return value | 1 << bit
    else:
        return value & ~(1 << bit)


def icecore_sensor(time, d18O, alt_diff=0.0):
    """
    DOCSTRING: FUNCTION icecore_sensor

    DESCRIPTION:
    The ice core sensor model calculates precipitation-weighted
    del18OP (i.e. isotope ratio is weighted by the amount of precipitation that accumulates)
    and corrects for temperature and altitude bias between model and site ([Yurtsever, 1975],
    0.3/100m [Vogel et al., 1975]).

    CITATION: Yurtsever, Y., Worldwide survey of stable isotopes in precipitation., Rep. Isotope Hydrology Section, IAEA, 1975.

    INPUTS:
    time: (calendar year)
    d18O: d18O of precipitation (permil)
    alt_diff: Actual Altitude-Model Altitude (meters)

    RETURNS: 'icecore'

    EXAMPLE USE:
    Apply icecore_sensor to extract precipitation-weighted d18o record for each core
    and compute altitude, temperature corrections. (Please see docstring icecore_sensor).

    d18O     = ice      # your dataset loaded here

    Enter your altitude correction in meters: (+ if too low. e.g. 500 m too low, alt_diff = 500).
    alt_diff = 500      # alt_diff at location (m)

    (Example: compute altitude correction for the core)
    z1=5670-z(QUEL)

    d18Oice = icecore_sensor(time,d18O,alt_diff)

    """
    alt_eff = -0.25
    alt_corr = alt_diff / 100.0 * alt_eff
    ice = d18O + alt_corr
    return ice


def moveObjectsToBottom(ids, subset_ids=None):
    """ Move specified sub-objects to bottom of container.

        See moveObjectsByDelta for more details.

        Permission -- Manage properties

        Returns -- Number of moved sub-objects
        """


def iccorr(data, t1=None, t2=None, n=None, norm=0, method='corr', count=
    None, chunk_size=None, thread_divisor=None, auto_background=False,
    viewer=None, viewer_interval=1, mode='full', mask=None, stats=True):
    """Iterative version of :func:`ccorr`.

    Parameters
    ----------
    data : iterable
        An iterable object, iterating over dual-frame ndarray data.
    t1 : int or array-like, optional
        Array of integers defining frame times of the first data. If it is a scalar
        it defines the length of the input data
    t2 : array-like, optional
        Array of integers defining frame times of the second data. If not provided,
        regular time-spaced data is assumed.
    n : int, optional
        Determines the length of the output (max time delay - 1 by default).
    norm : int, optional
        Specifies normalization procedure 0,1,2, or 3 (default).
    method : str, optional
        Either 'fft', 'corr' or 'diff'. If not given it is chosen automatically based on
        the rest of the input parameters.
    count : int, optional
        If given, it defines how many elements of the data to process. If not given,
        count is set to len(t1) if that is not specified, it is set to len(data).
    chunk_size : int
        Length of data chunk.
    thread_divisor : int, optional
        If specified, input frame is reshaped to 2D with first axis of length
        specified with the argument. It defines how many treads are run. This
        must be a divisor of the total size of the frame. Using this may speed
        up computation in some cases because of better memory alignment and
        cache sizing.
    auto_background : bool
        Whether to use data from first chunk to calculate and subtract background.
    viewer : any, optional
        You can use :class:`.viewer.MultitauViewer` to display data.
    viewer_interval : int, optional
        A positive integer, defines how frequently are plots updated 1 for most
        frequent, higher numbers for less frequent updates.
    mode : str
        Either "full" or "partial". With mode = "full", output of this function
        is identical to the output of :func:`ccorr_multi`. With mode = "partial",
        cross correlation between neigbouring chunks is not computed.
    mask : ndarray, optional
        If specifed, computation is done only over elements specified by the mask.
        The rest of elements are not computed, np.nan values are written to output
        arrays.
    stats : bool
        Whether to return stats as well.

    Returns
    -------
    ccorr_data, bg, var : ccorr_type, ndarray, ndarray
        Ccorr data, background and variance data. See :func:`ccorr` for definition
        of accorr_type
    ccorr_data : ccorr_type
        If `stats` == False
    """
    if t1 is None and t2 is not None or t2 is None and t1 is not None:
        raise ValueError('Both `t1` and `t2` arguments must be provided')
    period = 1
    nlevel = 0
    from cddm.multitau import _compute_multi_iter, _VIEWERS
    for i, mdata in enumerate(_compute_multi_iter(data, t1, t2, period=
        period, level_size=n, chunk_size=chunk_size, method=method, count=
        count, auto_background=auto_background, nlevel=nlevel, norm=norm,
        thread_divisor=thread_divisor, mode=mode, mask=mask, stats=stats,
        cross=True)):
        if stats == True:
            (data, dummy), bg, var = mdata
        else:
            data, dummy = mdata
        if viewer is not None:
            if i == 0:
                _VIEWERS['ccorr'] = viewer
            if i % viewer_interval == 0:
                if stats == True:
                    viewer.set_data(data, background=bg, variance=var)
                    viewer.plot()
                else:
                    viewer.set_data(data)
                    viewer.plot()
    if stats == True:
        return data, bg, var
    else:
        return data


@classmethod
def get_exchange_name(cls):
    """
        Get exchange name
        :return: Exchange name string
        """
    return 'Quoine'


def start_end_query(start, end):
    """Make a catalog query out of start and end dates.
    """
    query = {}
    if start:
        query['end'] = {'query': start, 'range': 'min'}
    if end:
        query['start'] = {'query': end, 'range': 'max'}
    return query


def is_mapping(value):
    """Returns True if value is of a mapping type such as a dictionary,
    and False otherwise.
    """
    return hasattr(value, 'keys')


def merged_tagged_value_dict(iface, name):
    """
    Alternative implementation the keeps info on schema it came from
    """
    tv = {}
    for iface in reversed(iface.__iro__):
        value = iface.queryTaggedValue(name, None)
        if value is not None:
            for k, v in value.items():
                v['__schema__'] = iface
            tv.update(value)
    return tv


def getFkId(fName, infoField=False, fBase=''):
    """ Crea el id de los zooms """
    fNameId = fName + '_id'
    field = {'fkField': fNameId, 'name': fNameId, 'readOnly': True,
        'hidden': True, 'type': 'foreignid'}
    if infoField:
        field['id'] = fBase + fNameId
        field['text'] = fNameId
        field['leaf'] = True
        field['checked'] = False
    return field


def quarterly_yearly_cull(dir_to_cull: list) ->list:
    """Take a list of snapshots from a directory (already reduced to one week or quarter) and cull.

            This culling will return a list with the snapshots to remove for the week or quarter.

            For a perfect set of snapshots, (where the user has been doing one snapshot per hour and             doing the daily culling) it should leave behind (remove from list):

            - day7-1800

            .. note:: May end up combining with weekly cull as they essentially do the same thing.

            :param dir_to_cull: A list containing snapshots. Assumes another function            has already reduced this list to a list containing only one week or quarter's worth of            snapshots.
            :returns: A list containing all the subvolumes to cull.
            """
    sorted_dir_to_cull = sorted(dir_to_cull)
    if len(sorted_dir_to_cull) != 0:
        sorted_dir_to_cull.pop()
    return sorted_dir_to_cull


def get_container_view(service_instance, obj_type, container=None):
    """
    Get a vSphere Container View reference to all objects of type 'obj_type'

    It is up to the caller to take care of destroying the View when no longer
    needed.

    Args:
        obj_type (list): A list of managed object types

    Returns:
        A container view ref to the discovered managed objects

    """
    if not container:
        container = service_instance.content.rootFolder
    view_ref = service_instance.content.viewManager.CreateContainerView(
        container=container, type=obj_type, recursive=True)
    return view_ref


def are_symmetric(pair1: str, pair2: str):
    """
    >>> are_symmetric("abc dcba", "dcba abc")
    True

    >>> are_symmetric("abc dfe", "efd cba")
    False

    >>> are_symmetric("a c", "ac")
    False

    """
    if len(pair1) != len(pair2):
        return False
    split1 = pair1.split(' ')
    split2 = pair2.split(' ')
    return split1[0] == split2[1] and split1[1] == split2[0]


def decodeField(value, decode_function):
    """
    Decodes a field value using given decode_function
    :param value:
    :param decode_function:
    :return:
    """
    if value is None:
        return None
    return decode_function(value)


def random_weight(rnd):
    """Random variable X in (0, 1]."""
    return 1.0 - rnd.random()


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 try_parse(l):
    """
    Tries to TEST log messages. Returns 'pass' or 'fail' if `l` is a TEST log
    message or '' (an empty string) if it failed to parse.
    """
    try:
        test = l.split('TEST: ')[1]
        result = test.split(' ', 2)[0].lstrip('<').rstrip('>')
    except IndexError:
        result = ''
    return result


def enabled(tests, values):
    """
    Removes all tests containing the `disabled` key. This filter can be
    added by passing `disabled=False` into `active_tests`.
    """
    for test in tests:
        if 'disabled' not in test:
            yield test


def keyconfig_remove():
    """Remove key config

    """
    pass


def quantity_to_tuple(quantity, unit_str):
    """
    Splits a quantity into a tuple of (value,unit) where unit is FITS complient.

    Useful to write FITS header keywords with units in a comment.

    Parameters
    ----------
    quantity : astropy quantity
        The Astropy quantity to split.
    unit_str: str
        Unit string representation readable by astropy.units (e.g. 'm', 'TeV', ...)

    Returns
    -------
    tuple
        A tuple containing the value and the quantity.
    """
    return quantity.to(unit_str).value, quantity.to(unit_str).unit.to_string(
        format='FITS')


def quantity_value(halo, field, operator, value, units):
    """
    Filter based on a value in the halo quantities dictionary.

    Parameters
    ----------
    halo : Halo object
        The Halo object to be provided by the HaloCatalog.
    field : string
        The field used for the evaluation.
    operator : string
        The comparison operator to be used ("<", "<=", "==", ">=", ">", etc.)
    value : numneric
        The value to be compared against.
    units : string
        Units of the value to be compared.

    """
    if field not in halo.quantities:
        raise RuntimeError('Halo object does not contain %s quantity.' % field)
    h_value = halo.quantities[field].in_units(units).to_ndarray()
    return eval('%s %s %s' % (h_value, operator, value))


def _cond(*data, **kwargs):
    """Run a if-then-else using user-defined condition and computation

    From:src/operator/control_flow.cc:1212
    This function support variable length of positional input.

    Parameters
    ----------
    cond : Symbol
        Input graph for the condition.
    then_branch : Symbol
        Input graph for the then branch.
    else_branch : Symbol
        Input graph for the else branch.
    data : Symbol[]
        The input arrays that include data arrays and states.
    num_outputs : int, required
        The number of outputs of the subgraph.
    cond_input_locs : tuple of <long>, required
        The locations of cond's inputs in the given inputs.
    then_input_locs : tuple of <long>, required
        The locations of then's inputs in the given inputs.
    else_input_locs : tuple of <long>, required
        The locations of else's inputs in the given inputs.

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

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


@classmethod
def register(cls, name, public_key_type, create_verifier):
    """Register a signature key type.

        :param name: the name of the signature key type
        :param public_key_type: e.g. RSAPublicKey, DSAPublicKey, etc.
        :param create_verifier: a function to create a verifier for this type
        """
    cls.REGISTERED_TYPES[name] = cls(name, public_key_type, create_verifier)


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 inch_to_dxa(value):
    """1 inch = 72 * 20 dxa"""
    return int(value * 20 * 72)


@classmethod
def GetCurrentProfile(cls):
    """Get the name of the currently set key profile if one exists
        @param cls: Class Object
        @return: string or None

        """
    return cls.cprofile


def _add_transport_headers(headers):
    """
    Adds the transport framing headers, if needed. Naturally, this method
    cannot add a content-length header, so if there is no content-length header
    then it will add Transfer-Encoding: chunked instead. Should only be called
    if there is a body to upload.

    This should be a bit smarter: in particular, it should allow for bad or
    unexpected versions of these headers, particularly transfer-encoding.
    """
    transfer_headers = 'content-length', 'transfer-encoding'
    for header_name in headers:
        if header_name.lower() in transfer_headers:
            return
    headers['transfer-encoding'] = 'chunked'


def convex_hull_2d(points: list) ->list:
    """Returns a list of indices into the list given

    :param points: list of 2d points.
    :type points: list
    :return:  a list of indices
    """
    pass


def add_custom_attributes(UserPoolId=None, CustomAttributes=None):
    """
    Adds additional user attributes to the user pool schema.
    See also: AWS API Documentation

    :example: response = client.add_custom_attributes(
        UserPoolId='string',
        CustomAttributes=[
            {
                'Name': 'string',
                'AttributeDataType': 'String'|'Number'|'DateTime'|'Boolean',
                'DeveloperOnlyAttribute': True|False,
                'Mutable': True|False,
                'Required': True|False,
                'NumberAttributeConstraints': {
                    'MinValue': 'string',
                    'MaxValue': 'string'
                },
                'StringAttributeConstraints': {
                    'MinLength': 'string',
                    'MaxLength': 'string'
                }
            },
        ]
    )

    :type UserPoolId: string
    :param UserPoolId: [REQUIRED]
            The user pool ID for the user pool where you want to add custom attributes.

    :type CustomAttributes: list
    :param CustomAttributes: [REQUIRED]
            An array of custom attributes, such as Mutable and Name.
            (dict) --Contains information about the schema attribute.
            Name (string) --A schema attribute of the name type.
            AttributeDataType (string) --The attribute data type.
            DeveloperOnlyAttribute (boolean) --Specifies whether the attribute type is developer only.
            Mutable (boolean) --Specifies whether the attribute can be changed once it has been created.
            Required (boolean) --Specifies whether a user pool attribute is required. If the attribute is required and the user does not provide a value, registration or sign-in will fail.
            NumberAttributeConstraints (dict) --Specifies the constraints for an attribute of the number type.
            MinValue (string) --The minimum value of an attribute that is of the number data type.
            MaxValue (string) --The maximum value of an attribute that is of the number data type.
            StringAttributeConstraints (dict) --Specifies the constraints for an attribute of the string type.
            MinLength (string) --The minimum length of an attribute value of the string type.
            MaxLength (string) --The maximum length of an attribute value of the string type.

    :rtype: dict
    :return: {}

    """
    pass


def size_fmt(size: float) ->str:
    """Formats a file size in binary multiples to a human readable string.

    Parameters
    ----------
    size : float
        The file size in bytes.

    Returns
    -------
    str
        Human readable string representing size in binary multiples.
    """
    for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB']:
        if size < 1024.0:
            break
        size /= 1024.0
    return f'{size:.1f} {unit}'


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 get_prop_filter_spec(client_factory, obj_spec, prop_spec):
    """Builds the Property Filter Spec Object."""
    prop_filter_spec = client_factory.create('ns0:PropertyFilterSpec')
    prop_filter_spec.propSet = prop_spec
    prop_filter_spec.objectSet = obj_spec
    return prop_filter_spec


def remove_unwanted_files(workdir, files):
    """
    Remove files from the list that are to be ignored by the looping job algorithm.

    :param workdir: working directory (string). Needed in case the find command includes the workdir in the list of
    recently touched files.
    :param files: list of recently touched files (file names).
    :return: filtered files list.
    """
    _files = []
    for _file in files:
        if not (workdir == _file or 'pilotlog' in _file or '.lib.tgz' in
            _file or '.py' in _file or 'pandaJob' in _file):
            _files.append(_file)
    return _files


def delete_edgeloop(use_face_split: bool=True):
    """Delete an edge loop by merging the faces on each side

    :param use_face_split: Face Split, Split off face corners to maintain surrounding geometry
    :type use_face_split: bool
    """
    pass


def resolve_attribute(name, bases, default=None):
    """Find the first definition of an attribute according to MRO order."""
    for base in bases:
        if hasattr(base, name):
            return getattr(base, name)
    return default


def is_coordsys_maker(obj):
    """ Test if `obj` has the CoordSysMaker API

    Parameters
    ----------
    obj : object
        Object to test

    Returns
    -------
    tf : bool
        True if `obj` has the coordinate system API

    Examples
    --------
    >>> is_coordsys_maker(CoordSysMaker('ikj'))
    True
    >>> is_coordsys_maker(CoordinateSystem('xyz'))
    False
    """
    if not hasattr(obj, 'coord_names'):
        return False
    if not hasattr(obj, 'name'):
        return False
    if not hasattr(obj, 'coord_dtype'):
        return False
    return callable(obj)


@classmethod
def enrich_fields(cls, fields, eitem):
    """Enrich the fields property of an issue.

        Loops through al properties in issue['fields'],
        using those that are relevant to enrich eitem with new properties.
        Those properties are user defined, depending on options
        configured in Jira. For example, if SCRUM is activated,
        we have a field named "Story Points".

        :param fields: fields property of an issue
        :param eitem: enriched item, which will be modified adding more properties
        """
    for field in fields:
        if field.startswith('customfield_'):
            if type(fields[field]) is dict:
                if 'name' in fields[field]:
                    if fields[field]['name'] == 'Story Points':
                        eitem['story_points'] = fields[field]['value']
                    elif fields[field]['name'] == 'Sprint':
                        value = fields[field]['value']
                        if value:
                            sprint = value[0].partition(',name=')[2].split(','
                                )[0]
                            sprint_start = value[0].partition(',startDate=')[2
                                ].split(',')[0]
                            sprint_end = value[0].partition(',endDate=')[2
                                ].split(',')[0]
                            sprint_complete = value[0].partition(
                                ',completeDate=')[2].split(',')[0]
                            eitem['sprint'] = sprint
                            eitem['sprint_start'] = cls.fix_value_null(
                                sprint_start)
                            eitem['sprint_end'] = cls.fix_value_null(sprint_end
                                )
                            eitem['sprint_complete'] = cls.fix_value_null(
                                sprint_complete)


def minute():
    """Return the minute"""


def shape_contains(shape, pos):
    """
    Check if a tensor of the given shape contains the
    position.
    """
    assert len(shape) == len(pos)
    for val, max_val in zip(pos, shape):
        if val < 0 or val >= max_val:
            return False
    return True


def _get_index(x):
    """ retrieve the index of something if it exists """
    if hasattr(x, 'index'):
        return x.index
    else:
        return None


def fileChunkIter(file_object, file_chunk_size=65536):
    """
    Return an iterator to a file-like object that yields fixed size chunks

    :param file_object: a file-like object
    :param file_chunk_size: maximum size of chunk
    """
    while True:
        chunk = file_object.read(file_chunk_size)
        if chunk:
            yield chunk
        else:
            break


def display_init_run_notebook(output_root):
    """display function for initializing the notebooks directory"""
    print('Created output directory at %s' % output_root)


def is_transmitter(metric):
    """Is interface ``metric`` a transmitter?

    :param dict metric: The metric.
    :rtype: :py:class:`bool`

    """
    return metric.get('name', '').endswith('tx')


@staticmethod
def cost_function(records_in, records_out, distance):
    """We minimize on distance between two obs
        """
    return distance


@classmethod
def from_name(cls, name):
    """Retrieve vlan id associated to a name."""
    result = cls.list()
    vlans = {}
    for vlan in result:
        vlans[vlan['name']] = vlan['id']
    return vlans.get(name)


@classmethod
def filter_params(cls, ref):
    """Remove unspecified parameters from the dictionary.

        This function removes unspecified parameters from the dictionary.
        This method checks only root-level keys from a ref dictionary.

        :param ref: a dictionary representing deserialized response to be
                    serialized
        """
    if cls._public_parameters:
        ref_keys = set(ref.keys())
        blocked_keys = ref_keys - cls._public_parameters
        for blocked_param in blocked_keys:
            del ref[blocked_param]
    return ref


def format_datetime(dt):
    """
    Returns ISO 8601 string representation
    """
    return dt.isoformat()


def get_message(name, value):
    """Provides the message for a standard Python exception"""
    if hasattr(value, 'msg'):
        return f'{name}: {value.msg}\n'
    return f'{name}: {value}\n'


def __setitem__(key, value):
    """Store annotation under key.

        In order to avoid key collisions, users of this interface must
        use their dotted package name as part of the key name.
        """


def binary_column_as_state_type(db_column_data):
    """
        Turn *db_column_data* into something that's a valid pickle
        state.

        Valid pickle states should be acceptable to
        `io.BytesIO` and `pickle.UnPickler`.

        *db_column_dat* came from a column of data declared to be of the
        type that we store state information in (e.g., a BLOB on MySQL
        or Oracle).
        """


@classmethod
def load_from_serialized(cls, data):
    """
        Create a new instance loading the values from JSON-serialised data as a string

        :param data: The string with the JSON-serialised data to load from
        """
    from aiida.common import json
    return cls.load_from_dict(json.loads(data))


def norm3(vec3):
    """
    Quick convenient function to get the norm of a 3-element vector
    norm3: 475 ns | np.linalg.norm: 4.31 us
    """
    a, b, c = vec3
    return (a * a + b * b + c * c) ** 0.5


def version_to_sip_tag(version):
    """ Convert a version number to a SIP tag.  version is the version number.
    """
    if version > 393216:
        version = 393216
    major = version >> 16 & 255
    minor = version >> 8 & 255
    patch = version & 255
    if (major, minor) >= (5, 13):
        patch = 0
    elif (major, minor) == (5, 12):
        if patch > 4:
            patch = 4
    return 'Qt_%d_%d_%d' % (major, minor, patch)


def middle_drop(progress):
    """
    Returns a linear value with a drop near the middle to a constant value for the Scheduler

    :param progress: (float) Current progress status (in [0, 1])
    :return: (float) 1 - progress if (1 - progress) >= 0.75 else 0.075
    """
    eps = 0.75
    if 1 - progress < eps:
        return eps * 0.1
    return 1 - progress


def getobject_use_prevfield(idf, idfobject, fieldname):
    """field=object_name, prev_field=object_type. Return the object"""
    if not fieldname.endswith('Name'):
        return None
    fdnames = idfobject.fieldnames
    ifieldname = fdnames.index(fieldname)
    prevfdname = fdnames[ifieldname - 1]
    if not prevfdname.endswith('Object_Type'):
        return None
    objkey = idfobject[prevfdname].upper()
    objname = idfobject[fieldname]
    try:
        foundobj = idf.getobject(objkey, objname)
    except KeyError as e:
        return None
    return foundobj


def getIlluminaName(name):
    """
    Return sample name used by Illumina in filename.

    :param name: The name provided to Illumina process (for example in samplesheet).
    :type name: str
    :return: The sample name used by Illumina as part of filename.
    :rtype: str
    """
    return name.replace('_', '-').replace(' ', '-').replace('.', '-').replace(
        '+', '')


@classmethod
def toolkit_setter(cls, setter, translate):
    """ Get the toolkit representation of a setter.

        This method will return the cached toolkit setter, if available,
        or invoke the translator to create the cached setter. The cached
        toolkit setter will be cleared when the setter is invalidated.

        Parameters
        ----------
        setter : :class:`Setter`
            The style setter of interest.

        translate : callable
            A callable which accepts a single :class:`Setter` argument
            and returns a toolkit representation of the setter. The
            returned value is cached until the setter is invalidated.

        Returns
        -------
        result : object
            The toolkit representation of the setter.

        """
    cache = cls._toolkit_setters
    if setter in cache:
        return cache[setter]
    result = cache[setter] = translate(setter)
    return result


def to_bool(value):
    """Return boolean value. Convert string to True when "true", "yes" or "on"
    """
    if isinstance(value, str):
        value = value.lower()
        return value in ['1', 'true', 'yes', 'on'] and value != '0'
    else:
        return bool(value)


def is_namedtuple(x):
    """
    Check if x is a namedtuple.

    :rtype: Boolean.
    """
    return all((type(x).__bases__[0] is tuple, len(type(x).__bases__) == 1,
        isinstance(getattr(x, '_fields', None), tuple)))


def markdown_2_rst(lines):
    """
    Convert markdown to restructured text
    """
    out = []
    code = False
    for line in lines:
        if line.strip() == '```':
            code = not code
            space = ' ' * (len(line.rstrip()) - 3)
            if code:
                out.append('\n\n%s.. code-block:: none\n\n' % space)
            else:
                out.append('\n')
        else:
            if code and line.strip():
                line = '    ' + line
            else:
                line = line.replace('\\', '\\\\')
            out.append(line)
    return out


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


@staticmethod
def p_in_val_out_val(p):
    """in_val_out_val : number_list"""
    p[0] = p[1]


def release_local(local):
    """Releases the contents of the local for the current context.
    This makes it possible to use locals without a manager.

    Example::

        >>> loc = Local()
        >>> loc.foo = 42
        >>> release_local(loc)
        >>> hasattr(loc, 'foo')
        False

    With this function one can release :class:`Local` objects as well
    as :class:`LocalStack` objects.  However it is not possible to
    release data held by proxies that way, one always has to retain
    a reference to the underlying local object in order to be able
    to release it.

    .. versionadded:: 0.6.1
    """
    local.__release_local__()


def t_NUMBER(t):
    """[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"""
    try:
        t.value = float(t.value)
    except:
        t.lexer.log.info('[%d]: Number %s is not valid!' % (t.lineno, t.value))
        t.value = 0
    return t


def simple_parse(content):
    """Returns blocks, where each block is a 2-tuple (kind, text).

    :kind: one of 'heading', 'release', 'section', 'empty' or 'text'.
    :text: a str, including newlines.
    """
    blocks = content.split('\n\n')
    for block in blocks:
        if block.startswith('###'):
            yield 'heading', block
            continue
        last_line = block.rsplit('\n', 1)[-1]
        if last_line.startswith('###'):
            yield 'release', block
        elif last_line.startswith('***'):
            yield 'section', block
        elif block.startswith('* '):
            yield 'bullet', block
        elif block.strip() == '':
            yield 'empty', block
        else:
            yield 'text', block


@staticmethod
def _extra_attributes_from_db_object(vnf_package, db_vnf_package,
    expected_attrs=None):
    """Method to help with migration of extra attributes to objects."""
    if expected_attrs is None:
        expected_attrs = []
    if 'vnf_deployment_flavours' in expected_attrs:
        vnf_package._load_vnf_deployment_flavours(db_vnf_package.get(
            'vnf_deployment_flavours'))
    if 'vnfd' in expected_attrs:
        vnf_package._load_vnfd(db_vnf_package.get('vnfd'))


@staticmethod
def _extract_message_key(key, msg, msg_id_keys):
    """Extract and return the requested key from the message.

        Note that msg and msg_id_keys are modfied if the found key was
        node_id specific.
        """
    value = None
    if key in msg:
        value = msg[key]
    for i, (_key, _fullkey) in enumerate(msg_id_keys):
        if key == _key:
            value = msg.pop(_fullkey)
            msg_id_keys.pop(i)
            break
    return value


def prtOptions():
    """Print a list of command-line options and arguments."""
    print('The command-line arguments are:')
    print('  -h (print help)')
    print('  --help (print help)')
    print('  -r (print the full version string)')
    print('  --version (print the version number)')
    print('  -v (very verbose -- print more messages than the default)')
    print('  -q (quiet -- print almost no messages)')
    print('')
    print('Following the options, give the following:')
    print('  Name of input file, optionally including wildcards')
    print('  String with which to begin output file names')
    print("  Time at beginning of first interval, or ''")
    print("  Length (s) of each time interval, or ''")
    print("  Time at end of last interval, or ''")
    print('  Comma- or blank-separated string of times for intervals')
    print('  Verbosity (0 [low], 1 [default], or 2 [high])')


def cpp_class(package, message=None):
    """Returns the fully qualified class name for a message type"""
    if not message:
        return package.replace('.', '::')
    return '::%s::%s' % (package.replace('.', '::'), message)


def view_ghost_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin:
    int=0, ymax: int=0):
    """Set the boundaries of the border used for offset-view

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    """
    pass


@staticmethod
def get_es_id(page):
    """
        An ID built with the node path and the position of this category in the taxonomy:
            - P: parent, the category has children
            - L: leaf, the category has no children

        For example: a parent category `P_00010002` and its child `L_000100020001`.
        """
    return '{type:s}-{path:s}'.format(type='L' if page.node.is_leaf() else
        'P', path=page.node.path)


@staticmethod
def _check_params(**kwargs):
    """ Reassemble kwargs to identify additional optimizer params for default optimizers. base_params contains
        all the param names in base class Optimizer.

        Parameters
        ----------
        kwargs: dict
            Parameters for the default optimizer

        Returns
        ----------
        default_params: dict
            Optimizer parameters that are defined in base class Optimizer
        """
    optimizer_param = dict(kwargs)
    base_params = ['rescale_grad', 'param_idx2name', 'wd', 'clip_gradient',
        'learning_rate', 'lr_scheduler', 'sym', 'begin_num_update',
        'multi_precision', 'param_dict']
    default_params = {}
    for key, _ in optimizer_param.items():
        if key in base_params:
            default_params[key] = optimizer_param[key]
    return default_params


@classmethod
def get(cls, name: str):
    """Get an ``Attack`` instance of the given Brawler.

        Parameters
        --------------
        name: :class:`str`
            The full/partial name of the Brawler.

        Returns
        ----------
        :class:`Attack`
            ``Attack`` instance from given name.

        Raises
        --------
        BrawlerNotFound
            If a Brawler can't be found from the given ``name``.
        """
    data = cls._get(name)
    return cls(data)


def psi_H_MgOH_HSO4_HMW84(T, P):
    """c-c'-a: hydrogen magnesium-hydroxide bisulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def strf3(val):
    """Nicely formats a float (single precision), remove trailing zeros """
    if val == 0.0:
        return '0.0'
    if abs(val) > 1.0:
        strg = '{0:.3f}'.format(val)
    elif abs(val) > 0.01:
        strg = '{0:.6f}'.format(val)
    else:
        return '{0:.7e}'.format(val)
    if strg[-3:] == '000':
        return strg[:-3]
    if strg[-2:] == '00':
        return strg[:-2]
    return strg


def inter_point_point(p1, p2):
    """intersection function for Point and Point
    input:
    p1: Point
    p2: Point

    output:
    intersection
    """
    if p1 == p2:
        return p1
    else:
        return None


def pd_create_colmapdict_nametoint(df):
    """ 'close' ---> 5    """
    col = df.columns.values
    dict1 = {}
    for k, x in enumerate(col):
        dict1[x] = k
    return dict1


@staticmethod
def dim_ouput(output_id, percent, ramp):
    """Generate a dim command for a single output-port.

        :param    int    output_it:    Output id 0..3
        :param    int    percent:      Brightness in percent 0..100
        :param    int    ramp:         Ramp value
        :return:    The PCK command (without address header) as text
        :rtype:    str
        """
    if output_id < 0 or output_id > 3:
        raise ValueError('Invalid output_id.')
    percent_round = int(round(percent * 2))
    ramp = int(ramp)
    if percent_round % 2 == 0:
        pck = 'A{:d}DI{:03d}{:03d}'.format(output_id + 1, percent_round //
            2, ramp)
    else:
        pck = 'O{:d}DI{:03d}{:03d}'.format(output_id + 1, percent_round, ramp)
    return pck


def chunk_bounds(nsamples, chunk_size, overlap=0):
    """Returns chunks of the form:
    [ overlap/2 | chunk_size-overlap | overlap/2 ]
    s_start   keep_start           keep_end     s_end
    Except for the first and last chunks which do not have a left/right overlap

    """
    s_start = 0
    s_end = chunk_size
    keep_start = s_start
    keep_end = s_end - overlap // 2
    yield s_start, s_end, keep_start, keep_end
    while s_end - overlap + chunk_size < nsamples:
        s_start = s_end - overlap
        s_end = s_start + chunk_size
        keep_start = keep_end
        keep_end = s_end - overlap // 2
        if s_start < s_end:
            yield s_start, s_end, keep_start, keep_end
    s_start = s_end - overlap
    s_end = nsamples
    keep_start = keep_end
    keep_end = s_end
    if s_start < s_end:
        yield s_start, s_end, keep_start, keep_end


def stabilize_2d_rotation_add():
    """Add selected tracks to 2D rotation stabilization

    """
    pass


@staticmethod
def p_characteristic_type(p):
    """characteristic_type : VALUE
                               | CURVE
                               | MAP
                               | CUBOID
                               | VAL_BLK
                               | ASCII"""
    p[0] = p[1]


def cols_to_rename(df, dictionary):
    """Drop selected columns and return dataframe.

    Args:
        df: Pandas dataframe.
        dictionary: {'old_name1': 'new_name1', 'old_name2': 'new_name2'}

    Returns:
        Original dataframe without dropped columns.
    """
    df.rename(dictionary, axis=1, inplace=True)
    return df


def filter_value(func):
    """Return a function which filters the value."""
    return lambda kv: func(kv[1])


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


def get_model(project_dir, train_seq, hparams, num_GPUs, logger, args):
    """
    Initializes a tf.keras Model from MultiPlanarUNet.models as specified in
    hparams['build']. If args.continue_training, the best previous model stored
    in [project_dir]/models will be loaded.

    If hparams["build"]["biased_output_layer"] is True, sets the bias weights
    on the final conv. layer so that a zero-input gives an output of class
    probabilities equal to the class frequencies of the training set.

    If num_GPUs > 1, distribute the model on multiple GPUs

    Args:
        project_dir: A path to a MultiPlanarUNet project folder
        train_seq: A MultiPlanarUNet.sequences object for the training data
        hparams: A MultiPlanarUNet YAMLHParams object
        num_GPUs: An integer, the number of GPUs to train the model on
        logger: A MultiPlanarUNet logging object
        args: argparse arguments

    Returns:
        model: The model to fit
        org_model: The original, non-GPU-distributed model
                   (Same as model if num_GPUs==1)
    """
    from MultiPlanarUNet.models import model_initializer
    org_model = model_initializer(hparams=hparams, continue_training=args.
        continue_training, project_dir=project_dir, logger=logger)
    if not args.continue_training and hparams['build'].get(
        'biased_output_layer'):
        from MultiPlanarUNet.utils.utils import set_bias_weights_on_all_outputs
        set_bias_weights_on_all_outputs(org_model, train_seq, hparams, logger)
    if num_GPUs > 1:
        from tensorflow.keras.utils import multi_gpu_model
        model = multi_gpu_model(org_model, gpus=num_GPUs, cpu_merge=False,
            cpu_relocation=False)
        logger('Creating multi-GPU model: N=%i' % num_GPUs)
    else:
        model = org_model
    return model, org_model


def wrap_css_lines(css, line_length):
    """Wrap the lines of the given CSS to an approximate length."""
    lines = []
    line_start = 0
    for i, char in enumerate(css):
        if char == '}' and i - line_start >= line_length:
            lines.append(css[line_start:i + 1])
            line_start = i + 1
    if line_start < len(css):
        lines.append(css[line_start:])
    return '\n'.join(lines)


def _encode_mixins(tbl):
    """Encode a Table ``tbl`` that may have mixin columns to a Table with only
    astropy Columns + appropriate meta-data to allow subsequent decoding.
    """
    from astropy.table import serialize
    from astropy.table.table import has_info_class
    from astropy import units as u
    from astropy.utils.data_info import MixinInfo, serialize_context_as
    try:
        import yaml
    except ImportError:
        for col in tbl.itercols():
            if has_info_class(col, MixinInfo
                ) and col.__class__ is not u.Quantity:
                raise TypeError(
                    "cannot write type {} column '{}' to HDF5 without PyYAML installed."
                    .format(col.__class__.__name__, col.info.name))
    with serialize_context_as('hdf5'):
        encode_tbl = serialize.represent_mixins_as_columns(tbl)
    return encode_tbl


def b64pad(data):
    """
    Pad base64 data with '=' so that it's length is a multiple of 4.
    """
    missing = len(data) % 4
    if missing:
        data += b'=' * (4 - missing)
    return data


@property
@staticmethod
def addFields():
    """Returns additional fields for the subProblem systemConfigs"""
    return {}


def expires():
    """ Return the DateTime form of ExpirationDate.

        o Permission:  View
        """


def getQualifiedLanguages():
    """Return a sequence of Language IDublinCoreElementItem.
        """


@staticmethod
def _columns_index_to_name(columns, idxdict):
    """
        Substitutes column indexes with column names, return the passed list of columns
        as a list of names only.

        :param columns:
        :type columns: list
        :param idxdict:
        :type idxdict: dict
        :return:
        :rtype: list
        """
    res = []
    for col in columns:
        if type(col) is int:
            assert 0 <= col < len(idxdict
                ), "Column index '%s' out of range" % col
            res.append(idxdict[col])
        else:
            res.append(col)
    return res


@classmethod
def resolve_attr_spec(cls, spec, cb_obj, model=None):
    """
        Resolves a Callback attribute specification looking the
        corresponding attribute up on the cb_obj, which should be a
        bokeh model. If not model is supplied cb_obj is assumed to
        be the same as the model.
        """
    if not cb_obj:
        raise Exception('Bokeh plot attribute %s could not be found' % spec)
    if model is None:
        model = cb_obj
    spec = spec.split('.')
    resolved = cb_obj
    for p in spec[1:]:
        if p == 'attributes':
            continue
        if isinstance(resolved, dict):
            resolved = resolved.get(p)
        else:
            resolved = getattr(resolved, p, None)
    return {'id': model.ref['id'], 'value': resolved}


def read_renderlayers():
    """Read all render layers of all used scenes

    """
    pass


def db_to_amplitude(amplitude_db: float, reference: float=1e-06) ->float:
    """
    Convert amplitude from decibel (dB) to volts.

    Args:
        amplitude_db: Amplitude in dB
        reference: Reference amplitude. Defaults to 1 µV for dB(AE)

    Returns:
        Amplitude in volts
    """
    return reference * 10 ** (amplitude_db / 20)


@staticmethod
def getBlockedReactions(fvaMinmax):
    """ get reactions whose flux is restricted to zero based on FVA solution

        Keyword arguments:
        fvaMinmax  -- dict { reaction : flux minimum, flux maximum }

        Returns list of reactions (in arbitrary order)
        """
    blockedReactions = []
    for name in fvaMinmax:
        mini, maxi = fvaMinmax[name]
        if mini == maxi == 0.0:
            blockedReactions.append(name)
    return blockedReactions


def extract_arj(archive, compression, cmd, verbosity, interactive, outdir):
    """Extract an ARJ archive."""
    cmdlist = [cmd, 'x', '-r']
    if not interactive:
        cmdlist.append('-y')
    cmdlist.extend([archive, outdir])
    return cmdlist


@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 load_cands(path, lines_have_ids=False, cands_are_replies=False):
    """Load global fixed set of candidate labels that the teacher provides.

    Every example will include these as candidates. The true labels for a
    specific example are also added to this set, so that it's possible to get
    the right answer.
    """
    if path is None:
        return None
    cands = []
    cnt = 0
    with open(path) as read:
        for line in read:
            line = line.strip().replace('\\n', '\n')
            if len(line) > 0:
                cnt = cnt + 1
                if cnt == 1 and line[0:2] == '1 ':
                    lines_have_ids = True
                if '\t' in line and not cands_are_replies:
                    cands_are_replies = True
                    cands = []
                if lines_have_ids:
                    space_idx = line.find(' ')
                    line = line[space_idx + 1:]
                    if cands_are_replies:
                        sp = line.split('\t')
                        if len(sp) > 1 and sp[1] != '':
                            cands.append(sp[1])
                    else:
                        cands.append(line)
                else:
                    cands.append(line)
    return cands


def select(lst, fields):
    """Select fields from an iterable of dictionaries.

    Given an iterable of dictionaries and an iterable of key names, selects the
    given key names from the dictionaries and returns an iterable of
    dictionaries containing only those keys.

    For example, given the list::

        >>> lst = [
        ...     {'A': 'a1', 'B': 'b1'},
        ...     {'A': 'a2', 'B': 'b2'},
        ...     {'A': 'a3', 'B': 'b3'},
        ... ]

    We can select only the `A` keys from the dictionaries with::

        >>> list(select(lst, ['A']))
        [{'A': 'a1'}, {'A': 'a2'}, {'A': 'a3'}]

    :param iterable lst:
        An iterable of dictionaries.
    :param iterable fields:
        An iterable of key names.
    """
    fields = tuple(fields)
    for item in lst:
        dct = {}
        for name in fields:
            dct[name] = item[name]
        yield dct


def emptylists(n):
    """
    builds a list of n empty lists : [[],[],[], ...,[]]
    """
    return [[] for k in list(range(n))]


def get_viewable():
    """Get the publically viewable version (may be the object itself if
        no versioning).
        Returns None if there is no such version.
        """


def read(node):
    """Read a field from the node and return a new instance
        """


def extract_iter(txt, begin, end, pos=0):
    """Yield values that would be returned by repeated calls of extract()"""
    index = txt.index
    lbeg = len(begin)
    lend = len(end)
    try:
        while True:
            first = index(begin, pos) + lbeg
            last = index(end, first)
            pos = last + lend
            yield txt[first:last]
    except (ValueError, TypeError, AttributeError):
        return


def yellow(string):
    """foreground color to yellow"""
    return '\x1b[33m' + string + '\x1b[0m'


def ftShift2d(inputData, outputData=None):
    """
    Helper function to shift an array of 2-D FFT data

    Args:
        inputData(ndarray): array of data to be shifted. Will shift final 2 axes
        outputData(ndarray, optional): array to place data. If not given, will overwrite inputData
    """
    if not outputData:
        outputData = inputData.view()
    shape = inputData.shape
    shape_1 = int(round(shape[-2] * 0.5))
    shape_2 = int(round(shape[-1] * 0.5))
    outputData[(...), :shape_1, :shape_2] = inputData[(...), :shape_1, :shape_2
        ][(...), ::-1, ::-1]
    outputData[(...), shape_1:, :shape_2] = inputData[(...), shape_1:, :shape_2
        ][(...), ::-1, ::-1]
    outputData[(...), :shape_1, shape_2:] = inputData[(...), :shape_1, shape_2:
        ][(...), ::-1, ::-1]
    outputData[(...), shape_1:, shape_2:] = inputData[(...), shape_1:, shape_2:
        ][(...), ::-1, ::-1]
    return outputData


def raw_cmd_unit(action, ability_id, queued, unit_tags, target_unit_tag):
    """Do a raw command to another unit towards a unit."""
    action_cmd = action.action_raw.unit_command
    action_cmd.ability_id = ability_id
    action_cmd.queue_command = queued
    if not isinstance(unit_tags, (tuple, list)):
        unit_tags = [unit_tags]
    action_cmd.unit_tags.extend(unit_tags)
    action_cmd.target_unit_tag = target_unit_tag


def get_host(environ):
    """Return the real host for the given WSGI environment.  This takes care
    of the `X-Forwarded-Host` header.

    :param environ: the WSGI environment to get the host of.
    """
    scheme = environ.get('wsgi.url_scheme')
    if 'HTTP_X_FORWARDED_HOST' in environ:
        result = environ['HTTP_X_FORWARDED_HOST']
    elif 'HTTP_HOST' in environ:
        result = environ['HTTP_HOST']
    else:
        result = environ['SERVER_NAME']
        if (scheme, str(environ['SERVER_PORT'])) not in (('https', '443'),
            ('http', '80')):
            result += ':' + environ['SERVER_PORT']
    if result.endswith(':80') and scheme == 'http':
        result = result[:-3]
    elif result.endswith(':443') and scheme == 'https':
        result = result[:-4]
    return result


def getdescfromdrev(drev):
    """get description (commit message) from "Differential Revision"

    This is similar to differential.getcommitmessage API. But we only care
    about limited fields: title, summary, test plan, and URL.
    """
    title = drev[b'title']
    summary = drev[b'summary'].rstrip()
    testplan = drev[b'testPlan'].rstrip()
    if testplan:
        testplan = b'Test Plan:\n%s' % testplan
    uri = b'Differential Revision: %s' % drev[b'uri']
    return b'\n\n'.join(filter(None, [title, summary, testplan, uri]))


def find_callback(args, kw=None):
    """Return callback whether passed as a last argument or as a keyword"""
    if args and callable(args[-1]):
        return args[-1], args[:-1]
    try:
        return kw['callback'], args
    except (KeyError, TypeError):
        return None, args


def get_target_audiences():
    """Returns the list of target audiences."""


def _lmax(a, r):
    """
    Utility function giving the maximal value of the harmonic index `\\ell`
    for tabulated values of `Z^\\infty_{\\ell m}(r)`.

    INPUT:

    - ``a`` -- BH angular momentum parameter (in units of `M`, the BH mass)
    - ``r`` -- areal radius of the orbit (in units of `M`)

    OUTPUT:

    - maximal value of `\\ell` for which `Z^\\infty_{\\ell m}(r)` is tabulated

    EXAMPLES::

        sage: from kerrgeodesic_gw.zinf import _lmax
        sage: _lmax(0, 6.)
        10
        sage: _lmax(0, 40.)
        5
        sage: _lmax(0.9, 12.)
        10
        sage: _lmax(0.95, 12.)
        5

    """
    r_high_l = 20.0 if a <= 0.9 else 10.0
    l_max = 10 if r <= r_high_l else 5
    return l_max


def MIN(src_column):
    """
    Builtin minimum aggregator for groupby

    Example: Get the minimum rating of each user.

    >>> sf.groupby("user",
    ...            {'rating_min':tc.aggregate.MIN('rating')})

    """
    return '__builtin__min__', [src_column]


def eletype(iet):
    """Assigns number to degrees of freedom

    According to iet assigns number of degrees of freedom, number of
    nodes and minimum required number of integration points.

    Parameters
    ----------
    iet :  int
      Type of element. These are:
        1. 4 node bilinear quadrilateral.
        2. 6 node quadratic triangle.
        3. 3 node linear triangle.
        5. 2 node spring.
        6. 2 node truss element.
        7. 2 node beam (3 DOF per node).

    Returns
    -------
    ndof : int
      Number of degrees of freedom for the selected element.
    nnodes : int
      Number of nodes for the selected element.
    ngpts : int
      Number of Gauss points for the selected element.

    """
    if iet == 1:
        ndof = 8
        nnodes = 4
        ngpts = 4
    if iet == 2:
        ndof = 12
        nnodes = 6
        ngpts = 7
    if iet == 3:
        ndof = 6
        nnodes = 3
        ngpts = 3
    if iet == 5:
        ndof = 4
        nnodes = 2
        ngpts = 3
    if iet == 6:
        ndof = 4
        nnodes = 2
        ngpts = 3
    if iet == 7:
        ndof = 6
        nnodes = 2
        ngpts = 3
    return ndof, nnodes, ngpts


@staticmethod
def get_replace_cset(engine, csets):
    """Return the cset of what will be replaced going from old->new pkg."""
    return csets['install'].intersection(csets['old_cset'])


def add_nocolour_argument(subparser):
    """
    Oft used argument for disabling colour.

    :param subparser: an argparse instance
    """
    add = subparser.add_argument
    add('--no-colour', action='store_true', help='disable colour output')


def getQueriables():
    """Return an iterable of objects that can be queried

        The returned obects should be two-tuples with:

        - A unicode id

          The id must uniquely identify the queriable object within
          the set of queriable objects. Furthermore, in subsequent
          calls, the same id should be used for a given queriable
          object.

        - A queriable object

          This is an object for which there is a view provided for
          searching for items.

        """


@classmethod
def get_driver(cls):
    """
        returns the thread local driver
        """
    return cls.local.driver


def import_lmfit(funcname='XU'):
    """
    lazy import function for lmfit
    """
    try:
        import lmfit
        return lmfit
    except ImportError:
        raise ImportError(
            '%s: Fitting of models needs the lmfit package (https://pypi.python.org/pypi/lmfit)'
             % funcname)


def umode(event, server, view):
    """ This method is called everytime someone sets mode on a nick.
        It uses colours instead of @ and +.
    """
    nicka = event['nicka']
    nickb = event['nickb']
    mode = event['mode']
    chan = event['channel'].lower()
    win = view.get_win((server.getName(), chan))
    packet = '%s sets mode %s on %s\n' % (nicka, mode, nickb)
    win.update_screen(packet)
    if not mode in ('+o', '-o', '+v', '-v'):
        return
    group = win.box.get(0, 'end')
    ind = group.index(nickb)
    if mode == '+o':
        win.box.itemconfigure(ind, background='brown')
    elif mode == '-o':
        win.box.itemconfigure(ind, background='')
    elif mode == '+v':
        win.box.itemconfigure(ind, foreground='green')
    elif mode == '-v':
        win.box.itemconfigure(ind, foreground='')


def join_eb_ee(eb, ee, name=''):
    """
    combined 2 icCMS (one for EB, one for EE) into a single one for all Ecal
    """
    out = ee.copy()
    out.iov = ee.iov.where(eb.iov['iz'] != 0, eb.iov)
    out.name = name
    return out


def identity():
    """ Return a parser that passes state unchanged. """
    return lambda state: state._replace()


def parallel_finalize_cplist(cplist, outdir, objfits=None):
    """This is a parallel driver for `finalize_checkplot`, operating on a list
    of checkplots.

    Parameters
    ----------

    cplist : list of str
        This is a list of paths of all checkplot pickles to process and run
        through the finalization process.

    outdir : str
        The directory to where the finalized checkplot pickles will be written.

    objfits : str
        Path to the FITS file containing a WCS header and detections of all
        objects observed by the actual instrument that obtained the light
        curves. This should generally be a high quality 'reference' frame so
        that all of the objects whose checkplots we're finalizing (in `cplist`)
        can be seen on the frame.

    Returns
    -------

    dict
        Dict indicating the success/failure (as True/False) of the checkplot
        finalize operations for each checkplot pickle provided in `cplist`.

    """


def _handle_from_hex_to_string(handle):
    """Convert TC handle from hex to string

    :param handle: (int) TC handle
    :return: (string) handle formatted to string: 0xMMMMmmmm -> "M:m"
    """
    minor = format(handle & 65535, 'x')
    major = format((handle & 4294901760) >> 16, 'x')
    return ':'.join([major, minor])


@classmethod
def configure(cls, settings):
    """ Configure the storage method with app settings """
    return {}


def lambd_NH3_Sr_CB89(T, P):
    """n-c: ammonia strontium [CB89]."""
    lambd = -0.041
    valid = T == 298.15
    return lambd, valid


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 check_section(node, section, keys=None):
    """Validate keys in a section"""
    if keys:
        for key in keys:
            if key not in node:
                raise ValueError('Missing key %r inside %r node' % (key,
                    section))


def _truncate(f, n):
    """Truncates/pads a float `f` to `n` decimal places without rounding

    From https://stackoverflow.com/a/783927/1307974 (CC-BY-SA)
    """
    s = '{}'.format(f)
    if 'e' in s or 'E' in s:
        return '{0:.{1}f}'.format(f, n)
    i, p, d = s.partition('.')
    return '.'.join([i, (d + '0' * n)[:n]])


def create_from_datatype(cls, datatype, field_name, label=None):
    """
        create_from_datatype returns a FilterControl subclass, based on the datatype.  If datatype matches a registered
        datatype, then the appropriate subclass is instantiated and returned.

        :param datatype: The datatype of the field.  A string.
        :param field_name:  The name of the FilterControl subclass - passed thru to the constructor
        :param label:  The label for the FilterControl subclass - passed through to the constructor
        :return:  A FilterControl subclass.
        """
    for test, factory, dt in cls.filter_controls:
        if dt == datatype:
            return factory(field_name, label)


def format_uptime(uptime_in_seconds):
    """Format number of seconds into human-readable string.
    :param uptime_in_seconds: The server uptime in seconds.
    :returns: A human-readable string representing the uptime.
    >>> uptime = format_uptime('56892')
    >>> print(uptime)
    15 hours 48 min 12 sec
    """
    m, s = divmod(int(uptime_in_seconds), 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    uptime_values = []
    for value, unit in ((d, 'days'), (h, 'hours'), (m, 'min'), (s, 'sec')):
        if value == 0 and not uptime_values:
            continue
        elif value == 1 and unit.endswith('s'):
            unit = unit[:-1]
        uptime_values.append('{0} {1}'.format(value, unit))
    uptime = ' '.join(uptime_values)
    return uptime


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 __setitem__(key, value):
    """Set a new item on the object.

        Here we assume that the value does not require any inheritance, so
        that we do not set '__parent__' or '__name__' on the value.
        """


def load(path=None, filename=None):
    """Load network from file.

    Parameters
    ----------

    path: str
        Path to directory where to load model from.
    filename: str
        Name of file to load model from.

    Returns
    -------

    model: dict
        A dictionary of objects that constitute the input model. It must
        contain the following two keys:

        - 'model': tuple[caffe.Net, caffe.proto.caffe_pb2.NetParameter]
            Caffe model instance.
        - 'val_fn':
            Function that allows evaluating the original model.
    """
    import os
    from google.protobuf import text_format
    import caffe
    prototxt = os.path.join(path, filename + '.prototxt')
    caffemodel = os.path.join(path, filename + '.caffemodel')
    try:
        model = caffe.Net(prototxt, 1, weights=caffemodel)
    except RuntimeError:
        caffemodel += '.h5'
        model = caffe.Net(prototxt, 1, weights=caffemodel)
    model_protobuf = caffe.proto.caffe_pb2.NetParameter()
    text_format.Merge(open(prototxt).read(), model_protobuf)
    return {'model': (model, model_protobuf), 'val_fn': model.forward_all}


def convert_args_to_laid_out_tensors(xs):
    """Convert list elements to laid-out-tensors when possible.

  Args:
    xs: a list
  Returns:
    a list
  """
    ret = []
    for x in xs:
        if hasattr(x, 'to_laid_out_tensor'):
            ret.append(x.to_laid_out_tensor())
        else:
            ret.append(x)
    return ret


def detect_mode(line, default):
    """
    Detects line break for given line, if line break couldn't be found
    given default value is returned

    :param line: str line
    :param default: default
    :rtype: int
    :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
    """
    if line.endswith('\r\n'):
        return 2
    elif line.endswith('\n'):
        return 0
    elif line.endswith('\r'):
        return 1
    else:
        return default


def validate_form(request, form_cls, initial=None, instance=None, condition
    =True, **extra_kwargs):
    """
    Creates a form instance with/without data depending
    on whether page was POSTed. Returns the form instance.

    :param HttpRequest request: The request object.
    :param Form form_cls: The form class to be instantiated and validated.
    :param dict initial: Initial values for form fields.
    :param type instance: An initial model instance for ModelForms.
    :param bool condition: A boolean indicating whether this form should be validated
        from POST. Useful if there are multiple forms on the page::

            form = validate_form(request, MyForm, condition=('myformsubmit' in request.POST))

    :param extra_kwargs: Any extra kwargs passed to the form constructor.

    :returns: The validated form class instance, after calling ``full_clean()``.
    """
    kwargs = {}
    if initial is not None:
        kwargs['initial'] = initial
    if instance is not None:
        kwargs['instance'] = instance
    if extra_kwargs:
        kwargs.update(extra_kwargs)
    if request.method == 'POST' and condition:
        form = form_cls(data=request.POST, files=request.FILES if len(
            request.FILES) else None, **kwargs)
    else:
        form = form_cls(**kwargs)
    form.full_clean()
    return form


@classmethod
def list(cls, zone_id, options=None):
    """List zone records for a zone."""
    options = options if options else {}
    return cls.call('domain.zone.record.list', zone_id, 0, options)


def inside(head):
    """Return True if head inside boundaries."""
    return -200 < head.x < 190 and -200 < head.y < 190


@classmethod
def from_cartesian(cls, cart):
    """
        Converts 3D rectangular cartesian coordinates to radial coordinate.
        """
    return cls(distance=cart.norm(), copy=False)


def capitalize_sentence_series(string_series):
    """Capitalize first letter, but do not affect rest, e.g., 'the Brown Fox' -> 'The Brown Fox' """
    return string_series.str[:1].str.upper() + string_series.str[1:]


def is_bijection(dictionary):
    """Check if a dictionary is a proper one-to-one mapping."""
    return len(set(dictionary.keys())) == len(set(dictionary.values()))


def getRolesForPermission(permission_id):
    """Get the roles that have a permission.

        Return a sequence of (role id, setting) tuples for the given
        permission.

        If no roles have been granted this permission, then the empty list is
        returned.
        """


def job_cancel(context, data_dict):
    """Cancel a background job. Only sysadmins."""
    return {'success': False}


def choose_currency():
    """Gets user input on their preferred currency."""
    print('At the moment, we only support trading a single currency at a time.'
        )
    print('Here are your choices:')
    print('[1] Bitcoin')
    print('[2] Ethereum')
    print('[3] Litecoin')
    while True:
        currency = input('Which do you choose? ')
        if currency == '1':
            return 'Currency=BTC\n'
        elif currency == '2':
            return 'Currency=ETH\n'
        elif currency == '3':
            return 'Currency=LTC\n'
        else:
            print('Please enter in a valid number.')


def assert_shape_equals(array, shape):
    """Asserts that an array has the given shape."""
    assert array.shape == shape, 'Invalid shape {}; expected {}.'.format(array
        .shape, shape)


def sub_seq_split(seq, number_of_subseq):
    """
	Split the originl seq in n number of subsequences.
	:param seq: protein sequence
	:param number_of_subseq: number of subsequences to divide the original seq
	:return: list with number_of_sequences sequences.

	"""
    avg = len(seq) / float(number_of_subseq)
    out = []
    last = 0.0
    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg
    return out


def is_live(domain):
    """
    Domain is "live" if *any* endpoint is live.
    """
    http, httpwww, https, httpswww = (domain.http, domain.httpwww, domain.
        https, domain.httpswww)
    return http.live or httpwww.live or https.live or httpswww.live


def list2str(lst):
    """translate samtools returned cigar_list into cigar_string"""
    code2Char = {'0': 'M', '1': 'I', '2': 'D', '3': 'N', '4': 'S', '5': 'H',
        '6': 'P', '7': '=', '8': 'X'}
    cigar_str = ''
    for i in lst:
        cigar_str += str(i[1]) + code2Char[str(i[0])]
    return cigar_str


def set_value(dictionary, keys, value):
    """
    类似于Python内置的字典`dictionary[key] = value`，
    但是需要一个嵌套键的列表，而不是一个键。

    set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
    set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
    set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}}
    """
    if not keys:
        dictionary.update(value)
        return
    for key in keys[:-1]:
        if key not in dictionary:
            dictionary[key] = {}
        dictionary = dictionary[key]
    dictionary[keys[-1]] = value


def _get_or_default(mylist, i, default=None):
    """return list item number, or default if don't exist"""
    if i >= len(mylist):
        return default
    else:
        return mylist[i]


def __call__():
    """ Renders the table
        """


def repeat(number_of_times):
    """
    Repeat a set of commands a certain number of times.

    Equivalent to `range(1, number_of_times+1)`.

    Used like this:

    @play.repeat_forever
    async def do():
        for count in play.repeat(10):
            print(count)
    """
    return range(1, number_of_times + 1)


def octave_model_output(Q, eq):
    """
    Output an Octave-style matrix and vector assigned to 'Q' and a 'eq'.
    NOTE: It is the Q matrix, not the symmetric replacment rates as e.g. PAML
          and PhyML prefers.
    """
    q_str = '# name: Q\n# type: matrix\n# rows: 20\n# columns: 20\n'
    for row in Q:
        q_str += '  '.join(map(lambda e: str(round(e, 6)), row))
        q_str += '\n'
    eq_str = '# name: eq\n# type: matrix\n# rows: 1\n# columns: 20\n'
    eq_str += ' '.join(map(lambda e: str(round(e, 6)), eq))
    return q_str + '\n' + eq_str


def exists(dict, key):
    """ is key in dict and is dict[key] not none """
    if key in dict and dict[key] is not None:
        return True
    return False


def get_template(StackName=None, ChangeSetName=None, TemplateStage=None):
    """
    Returns the template body for a specified stack. You can get the template for running or deleted stacks.
    For deleted stacks, GetTemplate returns the template for up to 90 days after the stack has been deleted.
    See also: AWS API Documentation

    :example: response = client.get_template(
        StackName='string',
        ChangeSetName='string',
        TemplateStage='Original'|'Processed'
    )

    :type StackName: string
    :param StackName: The name or the unique stack ID that is associated with the stack, which are not always interchangeable:
            Running stacks: You can specify either the stack's name or its unique stack ID.
            Deleted stacks: You must specify the unique stack ID.
            Default: There is no default value.

    :type ChangeSetName: string
    :param ChangeSetName: The name or Amazon Resource Name (ARN) of a change set for which AWS CloudFormation returns the associated template. If you specify a name, you must also specify the StackName .

    :type TemplateStage: string
    :param TemplateStage: For templates that include transforms, the stage of the template that AWS CloudFormation returns. To get the user-submitted template, specify Original . To get the template after AWS CloudFormation has processed all transforms, specify Processed .
            If the template doesn't include transforms, Original and Processed return the same template. By default, AWS CloudFormation specifies Original .

    :rtype: dict
    :return: {
        'TemplateBody': {},
        'StagesAvailable': [
            'Original'|'Processed',
        ]
    }

    :returns:
    (string) --

    """
    pass


def seams_from_islands(mark_seams: bool=True, mark_sharp: bool=False):
    """Set mesh seams according to island setup in the UV editor

    :param mark_seams: Mark Seams, Mark boundary edges as seams
    :type mark_seams: bool
    :param mark_sharp: Mark Sharp, Mark boundary edges as sharp
    :type mark_sharp: bool
    """
    pass


def ensure_list(obj):
    """
    This function ensures that *obj* is a list.  Typically used to convert a
    string to a list, for instance ensuring the *fields* as an argument is a
    list.
    """
    if obj is None:
        return [obj]
    if not isinstance(obj, list):
        return [obj]
    return obj


@classmethod
def _java_loader_class(cls, clazz):
    """
        Returns the full class name of the Java ML instance.
        """
    return clazz.getJavaPackage()


def material_type(rec):
    """Determine material type for record (arg1).

    Returns:
    A string, one of BK (books), CF (computer files), MP
    (maps), MU (music), CR (continuing resource), VM (visual
    materials), MX (mixed materials)

    """
    l = rec[0]
    if l[2] in ('a', 't') and l[3] in ('a', 'c', 'd', 'm'):
        return 'BK'
    if l[2] == 'm':
        return 'CF'
    if l[2] in ('e', 'f'):
        return 'MP'
    if l[2] in ('c', 'd', 'i', 'j'):
        return 'MU'
    if l[2] == 'a' and l[3] in ('b', 'i', 's'):
        return 'CR'
    if l[2] in ('g', 'k', 'o', 'r'):
        return 'VM'
    if l[2] == 'p':
        return 'MX'
    raise ValueError


def normalize(a, axis=None):
    """
    Normalizes the input array so that it sums to 1.

    Parameters
    ----------
    a : array
        Non-normalized input data.

    axis : int
        Dimension along which normalization is performed.

    Notes
    -----
    Modifies the input **inplace**.
    """
    a_sum = a.sum(axis)
    if axis and a.ndim > 1:
        a_sum[a_sum == 0] = 1
        shape = list(a.shape)
        shape[axis] = 1
        a_sum.shape = shape
    a /= a_sum


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_urn(url):
    """
    convert https://blog.scrapinghub.com/page/6/ into blog.scrapinghub.com/page/6/
    :param url:
    :return:
    """
    if '://' in url:
        return url.split('://')[1]
    return url


def find(iterable, default=None, pred=None):
    """
    Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.
    """
    return next(filter(pred, iterable), default)


def strings_differ(string1: str, string2: str) ->bool:
    """Check whether two strings differ while avoiding timing attacks.

    This function returns True if the given strings differ and False
    if they are equal.  It's careful not to leak information about *where*
    they differ as a result of its running time, which can be very important
    to avoid certain timing-related crypto attacks:

        http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf

    >>> strings_differ('one', 'one')
    False
    >>> strings_differ('one', 'two')
    True

    :param string1:
    :param string2:
    """
    if len(string1) != len(string2):
        return True
    invalid_bits = 0
    for a, b in zip(string1, string2):
        invalid_bits += a != b
    return invalid_bits != 0


def min_weighted_vertex_cover(G, weight=None):
    """Returns an approximate minimum weighted vertex cover.

    The set of nodes returned by this function is guaranteed to be a
    vertex cover, and the total weight of the set is guaranteed to be at
    most twice the total weight of the minimum weight vertex cover. In
    other words,

    .. math::

       w(S) \\leq 2 * w(S^*),

    where $S$ is the vertex cover returned by this function,
    $S^*$ is the vertex cover of minimum weight out of all vertex
    covers of the graph, and $w$ is the function that computes the
    sum of the weights of each node in that given set.

    Parameters
    ----------
    G : NetworkX graph

    weight : string, optional (default = None)
        If None, every node has weight 1. If a string, use this node
        attribute as the node weight. A node without this attribute is
        assumed to have weight 1.

    Returns
    -------
    min_weighted_cover : set
        Returns a set of nodes whose weight sum is no more than twice
        the weight sum of the minimum weight vertex cover.

    Notes
    -----
    For a directed graph, a vertex cover has the same definition: a set
    of nodes such that each edge in the graph is incident to at least
    one node in the set. Whether the node is the head or tail of the
    directed edge is ignored.

    This is the local-ratio algorithm for computing an approximate
    vertex cover. The algorithm greedily reduces the costs over edges,
    iteratively building a cover. The worst-case runtime of this
    implementation is $O(m \\log n)$, where $n$ is the number
    of nodes and $m$ the number of edges in the graph.

    References
    ----------
    .. [1] Bar-Yehuda, R., and Even, S. (1985). "A local-ratio theorem for
       approximating the weighted vertex cover problem."
       *Annals of Discrete Mathematics*, 25, 27–46
       <http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf>

    """
    cost = dict(G.nodes(data=weight, default=1))
    for u, v in G.edges():
        min_cost = min(cost[u], cost[v])
        cost[u] -= min_cost
        cost[v] -= min_cost
    return {u for u, c in cost.items() if c == 0}


def elemwise_add(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Adds arguments element-wise.

    The storage type of ``elemwise_add`` output depends on storage types of inputs

       - elemwise_add(row_sparse, row_sparse) = row_sparse
       - elemwise_add(csr, csr) = csr
       - elemwise_add(default, csr) = default
       - elemwise_add(csr, default) = default
       - elemwise_add(default, rsp) = default
       - elemwise_add(rsp, default) = default
       - otherwise, ``elemwise_add`` generates output with default storage

    Parameters
    ----------
    lhs : NDArray
        first input
    rhs : NDArray
        second input

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

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


@staticmethod
def get_event_types():
    """Return a list of all event types relevant to this datasource

        Example:
        return ['compute.instance.update',
                'compute.instance.resume']

        It also supports prefixes- the event types which start
        with this prefix will be processed by this driver:
        Example:
        return ['compute.instance']

        :return: a list of event types
        :rtype: list of str
        """
    return []


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 purge_sublist(app, env, docname):
    """Clear out cached data when each document (file) is parsed.

    TODO: make this not a linear search?
    """
    if not hasattr(env, 'substitute_all_subs'):
        return
    all_subs = env.substitute_all_subs
    for id_ in list(all_subs.keys()):
        if all_subs[id_]['docname'] == docname:
            del all_subs[id_]


def is_pattern(s):
    """
    Returns *True* if the string *s* represents a pattern, i.e., if it contains characters such as
    ``"*"`` or ``"?"``.
    """
    return '*' in s or '?' in s


def to_bytes(url):
    """to_bytes(u"URL") --> 'URL'."""
    if isinstance(url, str):
        try:
            url = url.encode('ASCII').decode()
        except UnicodeError:
            raise UnicodeError('URL ' + repr(url) +
                ' contains non-ASCII characters')
    return url


def get_registry():
    """
    Return the Pyramid application registry associated to the current running
    application

    :returns: A Pyramid registry instance
    """
    from pyramid_celery import celery_app
    return celery_app.conf['PYRAMID_REGISTRY']


def find_balanced(text, start=0, start_sep='(', end_sep=')'):
    """ Finds balanced ``start_sep`` with ``end_sep`` assuming
        that ``start`` is pointing to ``start_sep`` in ``text``.
    """
    if start >= len(text) or start_sep != text[start]:
        return start
    balanced = 1
    pos = start + 1
    while pos < len(text):
        token = text[pos]
        pos += 1
        if token == end_sep:
            if balanced == 1:
                return pos
            balanced -= 1
        elif token == start_sep:
            balanced += 1
    return start


def minimize_stretch(fill_holes: bool=True, blend: float=0.0, iterations: int=0
    ):
    """Reduce UV stretching by relaxing angles

    :param fill_holes: Fill Holes, Virtual fill holes in mesh before unwrapping, to better avoid overlaps and preserve symmetry
    :type fill_holes: bool
    :param blend: Blend, Blend factor between stretch minimized and original
    :type blend: float
    :param iterations: Iterations, Number of iterations to run, 0 is unlimited when run interactively
    :type iterations: int
    """
    pass


def incr(stat, count=1, rate=1, buf=None, rate_applied=False):
    """
        Increment a counter by ``count``.

        Note that Statsd clears all counter values every time it sends
        the metrics to Graphite, which usually happens every 10
        seconds. If you need a persistent value, it may be more
        appropriate to use a gauge instead of a counter.
        """


def create_clutch_list(gear_list, clutch_duration):
    """

    Returns a list with the vehicle clutch position (1 or 0) for each simulation step

    :param gear_list: A list with the vehicle gear on each simulation step
    :param clutch_duration: The duration of the clutch, in sim steps
    :return:
    """
    l1 = len(gear_list) + clutch_duration
    clutch_list = [0] * l1
    for i, gear in enumerate(gear_list[1:]):
        if gear != gear_list[i]:
            clutch_list[i + 1:i + clutch_duration] = [1] * clutch_duration
    if clutch_duration != 0:
        clutch_list = clutch_list[:-clutch_duration]
    return clutch_list


def airspeed_energy_error(NAV_CONTROLLER_OUTPUT, VFR_HUD):
    """return airspeed energy error matching APM internals
    This is positive when we are going too slow
    """
    aspeed_cm = VFR_HUD.airspeed * 100
    target_airspeed = NAV_CONTROLLER_OUTPUT.aspd_error + aspeed_cm
    airspeed_energy_error = (target_airspeed * target_airspeed - aspeed_cm *
        aspeed_cm) * 5e-05
    return airspeed_energy_error


def xylabel_subplots(fig, y_axis_labels=None, x_axis_labels=None):
    """Set x-axis label and y-axis label for each sub plot in figure

    Note: labels are applied to axes in the order they were created, which
    is not always the way they appear in the figure.

    Parameters
    ----------
    fig : matplotlib.Figure
        Figure to apply labels to.
    y_axis_labels : sequence
        Label to place on y-axis of each subplot.  Use None to skip a subplot.
        Default y_axis_label=None
    x_axis_labels : sequence
        Label to place on x-axis of each subplot.  Use None to skip a subplot.
        Default x_axis_label=None.

    """
    if not y_axis_labels is None:
        for i, label in enumerate(y_axis_labels):
            if not label is None:
                fig.axes[i].set_ylabel(label)
    if not x_axis_labels is None:
        for i, label in enumerate(x_axis_labels):
            if not label is None:
                fig.axes[i].set_xlabel(label)
    return