@classmethod
def current(cls):
    """ Return the most recently created FileSystem

        If no instance has been created, then create one with defaults
        """
    if not len(cls._cache):
        return cls()
    else:
        return list(cls._cache.values())[-1]


def __lambda_values__(string):
    """
    Extracts the wavelength information from the string.

    :param string: A part of the HTML-code from a SVO filter web-page
    :type string: str
    :return: The float value of the string
    :rtype: float
    """
    lambda_value = string.split('<td')[2]
    lambda_value = lambda_value.split('</td>')[0]
    lambda_value = lambda_value.split('>')[-1]
    lambda_value = float(lambda_value)
    return lambda_value


def simulation_type_from_spins(dimensionless_spin_1, dimensionless_spin_2):
    """Classify simulation as non-spinning, aligned-spins, or precessing

    Classifies a simulation with dimensionless_spin_1 on the primary
    (larger) black hole and dimensionless_spin_2 on the secondary black
    hole as nonspinning (if no spin component > 0.01), aligned-spin (if
    only z components are > 0.01), or precessing (otherwise).

    """
    spin_zero_threshold = 0.01
    nonspinning_type = 'non-spinning'
    aligned_type = 'aligned-spins'
    precessing_type = 'precessing'
    simulation_type = nonspinning_type
    if abs(dimensionless_spin_1[2]) > spin_zero_threshold or abs(
        dimensionless_spin_2[2]) > spin_zero_threshold:
        simulation_type = aligned_type
    if abs(dimensionless_spin_1[0]) > spin_zero_threshold or abs(
        dimensionless_spin_2[0]) > spin_zero_threshold or abs(
        dimensionless_spin_1[1]) > spin_zero_threshold or abs(
        dimensionless_spin_2[1]) > spin_zero_threshold:
        simulation_type = precessing_type
    return simulation_type


def compact(html_tree):
    """Given an HTML tree, compact it.

    This involves:

    - finding all nodes with a single non-text child node
    - checking the pair (parent, child) in following lists,
      and it is in the list, replace the pair with the appropriate
      element of the two:

    Replace with parent:
      *, p

    Replace with child:
      hgroup, h*

    """
    for p in html_tree.xpath('//p'):
        parent = p.getparent()
        if not parent.text and parent.tag in ('li', 'dt', 'dd', 'td', 'th'):
            parent.text = p.text
            index = parent.index(p)
            for c in reversed(p):
                parent.insert(index, c)
            parent.remove(p)
    for header in html_tree.xpath('//header'):
        if len(header) == 0:
            header.getparent().remove(header)


def hex_int(hexstring):
    """converts #hexdigits to r,g,b integer colours"""
    if not hexstring:
        return 0, 0, 0
    hexstring = hexstring.strip('#')
    r = int(hexstring[0:2], base=16)
    g = int(hexstring[2:4], base=16)
    b = int(hexstring[4:6], base=16)
    return r, g, b


def patternDefCode(node):
    """ Change pattern line node value to pattern binding code:
		~ Name pattern.
		~ Flag it as recursive if ever.
		~ Special case of name patterns: must be cloned. """
    name, pattern = node
    name = node.name = name.value
    node.isRecursive = pattern.isRecursive
    format, transform = pattern.format, pattern.transform
    BIND = '**=' if node.isRecursive else '='
    if pattern.isName:
        print('name pattern format', format)
        node.value = "%s %s Clone(%s, expression='%s', name='%s')%s" % (name,
            BIND, format, format, name, transform)
    else:
        format_ = format[:-1]
        node.value = "%s %s %s, name='%s')%s" % (name, BIND, format_, name,
            transform)


def prune_frequency(population, min_frequency):
    """Delete extinct leaf nodes that did not reach a given frequency"""
    population.vs.select(lambda v: v.outdegree() == 0 and v['abundance'] ==
        0 and v['first_seen'] is not None and v['max_frequency'] <
        min_frequency).delete()
    return population


def string_to_num(s: str):
    """Converts a string to an int/float

    Returns ``None`` if it can't be converted

    >>> string_to_num('5')
    5
    >>> string_to_num('5.2')
    5.2
    >>> string_to_num(10)
    10
    >>> string_to_num(10.1)
    10.1
    >>> string_to_num('this is not a string') is None
    True
    """
    if isinstance(s, (int, float)):
        return s
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return None


@staticmethod
def get_dict_value(dictionary, path):
    """ Safely get the value of a dictionary given a key path. For
            instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at
            key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at
            key path ['a', 'b', 'c'] is None.

        :param dictionary: a dictionary.
        :param path: the key path.
        :return: The value of d at the given key path, or None if the key
                 path does not exist.
        """
    if len(path) == 0:
        return None
    temp_dictionary = dictionary
    try:
        for k in path:
            temp_dictionary = temp_dictionary[k]
        return temp_dictionary
    except (KeyError, TypeError):
        pass
    return None


def clearList(listWidget):
    """Clear a QListWidget, since the clear function is unstable."""
    while listWidget.count() > 0:
        listWidget.takeItem(0)


def clean_vbs(s):
    """
    Strip out the leading "VBS" that comes from reading string data from the scope using LeCroy VBS commands.
    This function splits the returned string and discards the first item before the space (strips "VBS")
    """
    s = s.split(' ', 1)[1]
    return s


def copy_fields(src, dest, fields=None, dest_fields=None, defaults=None):
    """Copy the k/v pairs from one dict into another"""
    if not fields:
        fields = src.keys()
    if not dest_fields:
        dest_fields = fields
    if not defaults:
        defaults = {}
    for field, dest_field in zip(fields, dest_fields):
        value = src.get(field, None)
        if value is None:
            if field in defaults:
                dest[dest_field] = defaults[field]
        else:
            dest[dest_field] = value


def describe_provisioning_parameters(AcceptLanguage=None, ProductId=None,
    ProvisioningArtifactId=None, PathId=None):
    """
    Provides information about parameters required to provision a specified product in a specified manner. Use this operation to obtain the list of ProvisioningArtifactParameters parameters available to call the  ProvisionProduct operation for the specified product.
    See also: AWS API Documentation

    :example: response = client.describe_provisioning_parameters(
        AcceptLanguage='string',
        ProductId='string',
        ProvisioningArtifactId='string',
        PathId='string'
    )

    :type AcceptLanguage: string
    :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows:
            'en' (English)
            'jp' (Japanese)
            'zh' (Chinese)
            If no code is specified, 'en' is used as the default.

    :type ProductId: string
    :param ProductId: [REQUIRED]
            The product identifier.

    :type ProvisioningArtifactId: string
    :param ProvisioningArtifactId: [REQUIRED]
            The provisioning artifact identifier for this product.

    :type PathId: string
    :param PathId: The identifier of the path for this product's provisioning. This value is optional if the product has a default path, and is required if there is more than one path for the specified product.

    :rtype: dict
    :return: {
        'ProvisioningArtifactParameters': [
            {
                'ParameterKey': 'string',
                'DefaultValue': 'string',
                'ParameterType': 'string',
                'IsNoEcho': True|False,
                'Description': 'string',
                'ParameterConstraints': {
                    'AllowedValues': [
                        'string',
                    ]
                }
            },
        ],
        'ConstraintSummaries': [
            {
                'Type': 'string',
                'Description': 'string'
            },
        ],
        'UsageInstructions': [
            {
                'Type': 'string',
                'Value': 'string'
            },
        ]
    }

    :returns:
    (string) --

    """
    pass


def partition(data, fragments):
    """Partion list into relative fractions"""
    total = sum(fragments)
    relative = len(data) // total
    i = 0
    for fragment in fragments:
        yield data[i:i + fragment * relative]


def dec(x):
    """ Subtract one from the current value """
    return x - 1


def import_string(import_name, silent=False):
    """Imports an object based on a string.  This is useful if you want to
    use import paths as endpoints or something similar.  An import path can
    be specified either in dotted notation (``xml.sax.saxutils.escape``)
    or with a colon as object delimiter (``xml.sax.saxutils:escape``).

    If `silent` is True the return value will be `None` if the import fails.

    :param import_name: the dotted name for the object to import.
    :param silent: if set to `True` import errors are ignored and
                   `None` is returned instead.
    :return: imported object
    """
    try:
        if ':' in import_name:
            module, obj = import_name.split(':', 1)
        elif '.' in import_name:
            module, obj = import_name.rsplit('.', 1)
        else:
            return __import__(import_name)
        return getattr(__import__(module, None, None, [obj]), obj)
    except (ImportError, AttributeError):
        if not silent:
            raise


def _construct_end_index(spansStartingFrom):
    """ Creates an index which stores all annotations (from spansStartingFrom)
       by their end position in text (annotation[END]).

       Each start position (in the index) is associated with a list of
       annotation objects (annotations ending at that position).
       An annotation object is also a list containing the following information:
        *) endTags -- graphic or textual formatting of the end tag,
        *) START position (of the annotation);
        *) layer name;

       Multiple annotation objects ending at the same position are sorted by
       their length: shorter annotations preceding the longer ones;
   """
    endIndex = {}
    for i in spansStartingFrom:
        for span1 in spansStartingFrom[i]:
            endSpan1 = [span1[4], span1[0], span1[2]]
            endLoc1 = span1[1]
            if endLoc1 not in endIndex:
                endIndex[endLoc1] = []
                endIndex[endLoc1].append(endSpan1)
            else:
                inserted = False
                for i in range(len(endIndex[endLoc1])):
                    endSpan2 = endIndex[endLoc1][i]
                    if endSpan2[1] < endSpan1[1]:
                        endIndex[endLoc1].insert(i, endSpan1)
                        inserted = True
                        break
                    elif endSpan2[1] == endSpan1[1] and endSpan2[2] < endSpan1[
                        2]:
                        endIndex[endLoc1].insert(i, endSpan1)
                        inserted = True
                        break
                if not inserted:
                    endIndex[endLoc1].append(endSpan1)
    return endIndex


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

    """
    pass


def ms_from_timedelta(td):
    """
    Given a timedelta object, returns a float representing milliseconds
    """
    return td.seconds * 1000 + td.microseconds / 1000.0


def xref_of_instr(instr):
    """ Return xref for branch instruction """
    return int.from_bytes(instr.operand, byteorder='little', signed=True
        ) + instr.offset_end - 2


def get_all_serverids():
    """
        @return: frozenset of serverid strings
        """


@classmethod
def _unmarshal(cls, attributes):
    """
        Create an object from the values retrieved from the database.
        """
    instance = cls.__new__(cls)
    instance.__dict__ = attributes
    return instance


@classmethod
def create_from(cls, variable):
    """Create new variable this type from existing

        Args:
            variable (Variable) : Existing variable to create from.

        Returns:
            :class:`.Variable` : new variable

        """
    v = cls(id=variable.id, name=variable.name, entity=variable.entity)
    return v


@classmethod
def export_to_hdf5(cls, h5_file, model, eids):
    """exports the elements in a vectorized way"""
    pids = []
    nodes = []
    for eid in eids:
        element = model.elements[eid]
        pids.append(element.pid)
        nodes.append(element.nodes)
    h5_file.create_dataset('eid', data=eids)
    h5_file.create_dataset('pid', data=pids)
    h5_file.create_dataset('nodes', data=nodes)


def _print_sir_params(fig_params):
    """
    Function to print parameters of plotted visualisation of SIR diffusion.

    :param fig_params: list with 4 elements (printable) - name of graph, beta coefficient, gamma coefficient and
     fraction of ill nodes on start.

    :return: formatted string which is a subtitle of gif.
    """
    return 'Graph - {}, $\\beta$ - {}, $\\gamma$ - {}, $I/N$ - {}'.format(
        fig_params[0], fig_params[1], fig_params[2], fig_params[3])


@classmethod
def discover(cls, path, depth='0'):
    """Discover a list of collections under the given ``path``.

        ``path`` is sanitized.

        If ``depth`` is "0", only the actual object under ``path`` is
        returned.

        If ``depth`` is anything but "0", it is considered as "1" and direct
        children are included in the result.

        The root collection "/" must always exist.

        """
    raise NotImplementedError


def preview():
    """Alias url(preview=True).
        """


def line_separated(value):
    """
    Return a list of values from a `value` string using line as list delimiters.
    """
    if not value:
        return []
    return list(value.splitlines(False))


def get_line_count(file):
    """
    get the line count of a file
    :param file: file path
    :return: line count of input file
    """
    with open(file=file, mode='rb') as f:
        for i, l in enumerate(f):
            pass
        return i + 1


def dG_to_flux_bounds(dG_min, dG_max, infinity=1000, abstol=1e-06):
    """ Convert standard Gibbs energy range to reaction flux bounds.

    Args:
        dG_min (float): minimum standard Gibbs energy
        dG_max (float): maximum standard Gibbs energy
        infinity (float): value to represent infinity (default: 1000)
        abstol (float): absolute tolerance to consider a value larger than zero (default: 1e-6)

    Returns:

    """
    if dG_min > abstol:
        lb, ub = -infinity, 0
    elif dG_max < -abstol:
        lb, ub = 0, infinity
    else:
        lb, ub = -infinity, infinity
    return lb, ub


def _rot(x, shift_amount, length):
    """Rotate x shift_amount bits to the left, considering the   string of bits is length bits long"""
    shift_amount = shift_amount % length
    return ((x >> length - shift_amount) + (x << shift_amount)) % (1 << length)


def _clean_dict(row):
    """
    Transform empty strings values of dict `row` to None.
    """
    row_cleaned = {}
    for key, val in row.items():
        if val is None or val == '':
            row_cleaned[key] = None
        else:
            row_cleaned[key] = val
    return row_cleaned


@staticmethod
def _build_query(tokens):
    """Build query tuple

        :param tokens:
        :rtype : tuple
        :return: tuple query data

        Return value example:
            "INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar')

        """
    sql_str_parts, values = [], ()
    for key, token in tokens.items():
        if not token.is_set:
            continue
        eval_result = token.eval()
        if isinstance(eval_result, str):
            sql_str_parts.append(eval_result)
        elif isinstance(eval_result, tuple):
            sql_str_parts.append(eval_result[0])
            values += tuple(eval_result[1])
    query = ' '.join(sql_str_parts), values
    return query


def nonzero(upper, lower):
    """Fills both values to whichever evaluates True, or leaves in place."""
    if upper and not lower:
        return upper, upper
    elif lower and not upper:
        return lower, lower
    else:
        return upper, lower


def _disposition_debug_msg(disp):
    """Make a nice debug message of what the FileDisposition is doing."""
    if disp.trace:
        msg = 'Tracing %r' % (disp.original_filename,)
        if disp.file_tracer:
            msg += ': will be traced by %r' % disp.file_tracer
    else:
        msg = 'Not tracing %r: %s' % (disp.original_filename, disp.reason)
    return msg


def __getitem__(key):
    """Return Browser request data

        Request data are retrieved from one of:

        - Environment variables

          These variables include input headers, server data, and other
          request-related data.  The variable names are as
          specified
          in the `CGI specification <https://tools.ietf.org/html/rfc3875>`_.

        - Cookies

          These are the cookie data, if present.

        - Form data

        Form data are searched before cookies, which are searched
        before environmental data.
        """


def is_sequence(arg):
    """ simple check if arg is iterable, but not a string,
    more performant than using duck typing and exception handling
    """
    return not hasattr(arg, 'strip') and (hasattr(arg, '__getitem__') or
        hasattr(arg, '__iter__'))


def is_lover(weak_order):
    """Whether a weak order represents a "lover".

    Parameters
    ----------
    weak_order : str
        A weak order, e.g. ``'a>b~c'``, ``'a~b>c'``, etc.

    Returns
    -------
    bool
        True iff the weak order is of the form ``'a>b~c'``.

    Examples
    --------
        >>> is_lover('a>b~c')
        True
    """
    return weak_order[1] == '>'


@classmethod
def find(cls, db, urlname, user=None):
    """Find a Dashboard by urlname.
        Returns None if not found.
        """
    if user is None:
        return db.query(cls).filter(cls.urlname == urlname).first()
    return db.query(cls).filter(cls.urlname == urlname, cls.user_id == user.id
        ).first()


@classmethod
def fromfile(cls, fh, memmap=True, valid=True, verify=True):
    """Read a frame from a filehandle, possible mapping the payload.

        Parameters
        ----------
        fh : filehandle
            To read header from.
        memmap : bool, optional
            If `True` (default), use `~numpy.memmap` to map the payload.
            If `False`, just read it from disk.
        valid : bool, optional
            Whether the data are valid (default: `True`). Note that this cannot
            be inferred from the header or payload itself.  If `False`, any
            data read will be set to ``cls.fill_value``.
        verify : bool, optional
            Whether to do basic verification of integrity.  Default: `True`.
        """
    header = cls._header_class.fromfile(fh, verify=verify)
    payload = cls._payload_class.fromfile(fh, header=header, memmap=memmap)
    return cls(header, payload, valid=valid, verify=verify)


@classmethod
def add_mapped_tag(cls, hdxobject, tag, log_deleted=True):
    """Add a tag to an HDX object that has tags

        Args:
            hdxobject (T <= HDXObject): HDX object such as dataset
            tag (str): Tag to add
            log_deleted (bool): Whether to log informational messages about deleted tags. Defaults to True.

        Returns:
            Tuple[List[str], List[str]]: Tuple containing list of added tags and list of deleted tags and tags not added
        """
    return cls.add_mapped_tags(hdxobject, [tag], log_deleted=log_deleted)


def get_reaction_for(model, value, add=True):
    """Get or create a reaction for a metabolite or a reaction.

    If value is a Metabolite or a Metabolite id, return any already existing demand or exchange reaction.
    If *add* is true, add a demand reaction if it does not already exist.

    Parameters
    ----------
    model : cobra.Model
        The model to for which to get / create a reaction
    value: str, Reaction or Metabolite
        A reaction identifier, a Reaction or a Metabolite for which an exchange reaction is to be created.
    add: bool
        Adds a demand reaction for a metabolite if a metabolite is found for *value*

    Returns
    -------
    Reaction

    Raises
    ------
    KeyError
        If *value* does not match any Reaction or Metabolite

    """
    try:
        reactions = model.reactions.get_by_any(value)
    except (ValueError, KeyError, TypeError):
        metabolite = model.metabolites.get_by_any(value)[0]
        reactions = model.reactions.query('^(EX|DM)_{}$'.format(metabolite.id))
        if len(reactions) == 0:
            if add:
                reactions = [model.add_boundary(metabolite, type='demand')]
            else:
                raise KeyError('Invalid target %s' % value)
    return reactions[0]


def Calc_instantaneous_ET_fraction(LE_inst, rn_inst, g_inst):
    """
    Function to calculate the evaporative fraction
    """
    EF_inst = LE_inst / (rn_inst - g_inst)
    EF_inst = EF_inst.clip(0.0, 1.8)
    EF_inst[LE_inst < 0] = 0
    return EF_inst


def ReserveRate():
    """Valuation Reserve Rate per Sum Assured"""
    return None


@staticmethod
def _is_number(s):
    """
        TODO: Add docstring

        """
    try:
        float(s)
        return True
    except ValueError:
        return False


@classmethod
def from_str(cls, elementstr):
    """Construct an instance from a string of the form 'token;key=val'."""
    ival, params = cls.parse(elementstr)
    return cls(ival, params)


def filteredvalues(interface):
    """Return filtered child nodes by interface.
        """


@staticmethod
def serializable() ->bool:
    """ Some environments may allow for the full game state to be serializable and transferable to the agents.

        Returns
        -------
        bool
            Whether or not this class supports serialization of the state."""
    return False


@staticmethod
def out_expo(progress):
    """.. image:: images/anim_out_expo.png
        """
    if progress == 1.0:
        return 1.0
    return -pow(2, -10 * progress) + 1.0


def get_input(prompt='', default=None, input=input):
    """Get user input with an optional default value."""
    if default is not None:
        ri = input('{} [{}]> '.format(prompt, default))
        if not ri:
            return default
        else:
            return ri
    else:
        return input('{}> '.format(prompt))


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 construct_surl_T0(dsn, filename):
    """
    Defines relative SURL for new replicas. This method
    contains Tier0 convention. To be used for non-deterministic sites.

    @return: relative SURL for new replica.
    @rtype: str
    """
    fields = dsn.split('.')
    nfields = len(fields)
    if nfields >= 3:
        return '/%s/%s/%s/%s/%s' % (fields[0], fields[2], fields[1], dsn,
            filename)
    elif nfields == 1:
        return '/%s/%s/%s/%s/%s' % (fields[0], 'other', 'other', dsn, filename)
    elif nfields == 2:
        return '/%s/%s/%s/%s/%s' % (fields[0], fields[2], 'other', dsn,
            filename)
    elif nfields == 0:
        return '/other/other/other/other/%s' % filename


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 _create_zip(*iterables, fillvalue=None, type_longest=False):
    """Zips supplied iterables and returns a generator.

    Aggregates `*iterables` using `zip` or `itertools.zip_longest`,
    depending on the value of the `type_longest` parameter.

    Parameters
    ----------
    *iterables : iterable
        Iterable objects passed as positional arguments. Passed on to
        `zip` or `zip_longest` depending on the `type_longest` flag.
    fillvalue : optional
        Set all missing values to this default value. Only specified
        when called by `namedzip_longest`. (default is None).
    type_longest : bool, optional
        Specifies whether to use `zip_longest` over `zip`. Used by
        `namedzip_longest`. (default is False).

    Returns
    ------
    generator object

    """
    if type_longest:
        from itertools import zip_longest
        zipped = zip_longest(*iterables, fillvalue=fillvalue)
    else:
        zipped = zip(*iterables)
    return zipped


def gap_insert(frames: int=10):
    """Insert gap at current frame to first strips at the right, independent of selection or locked state of strips

    :param frames: Frames, Frames to insert after current strip
    :type frames: int
    """
    pass


def isGoodAadapter(adapter):
    """
	Checks an adapter dictionary to ensure that it is valid. To be valid, the dictionary
	must include entries for the following keys:
		access_id - the access ID for the respective crowdsource back-end
		access_key - the secret key for the respective crowdsource back-end
		type - adapter type, determined by back-end crowdsource service

	Parameters
    ----------
    adapter : dict
    	A dictionary containing the parameters for the adapter

    Returns
    -------
    bool
    	returns True if the adapter validates (not authenticates) successfully, or
    	Raises an exception if the adapter is not created properly

    Raises
	------
	AdapterError: Indicates there was an error creating the adapter. Method will set error msg
					to indicate which required field was not found
	"""
    required_strings = ['access_id', 'access_key', 'type']
    for req in required_strings:
        if req not in adapter:
            return False
    return True


def is_tuple(value):
    """Checks if `value` is a tuple.

    Args:
        value (mixed): Value to check.

    Returns:
        bool: Whether `value` is a tuple.

    Example:

        >>> is_tuple(())
        True
        >>> is_tuple({})
        False
        >>> is_tuple([])
        False

    .. versionadded:: 3.0.0
    """
    return isinstance(value, tuple)


def test_pyblish_availability():
    """Is Pyblish available?"""
    try:
        __import__('pyblish')
        __import__('pyblish_qml')
    except Exception:
        raise Exception('Pyblish not found')


def serial(start=0, end=None, model=None):
    """A very simple serial number generator."""
    value = start
    while True:
        yield value
        value += 1
        if end is not None:
            if value >= model.get_value(end):
                value = start


def get_ids(tokens, tokenizer, max_seq_len):
    """Token ids from Tokenizer vocab"""
    token_ids = tokenizer.convert_tokens_to_ids(tokens)
    input_ids = token_ids + [0] * (max_seq_len - len(token_ids))
    return input_ids


@staticmethod
def is_game_mode() ->bool:
    """Return false since mc does not have game modes."""
    return False


def lovasz_grad(gt_sorted):
    """
    Computes gradient of the Lovasz extension w.r.t sorted errors
    See Alg. 1 in paper
    """
    p = len(gt_sorted)
    gts = gt_sorted.sum()
    intersection = gts - gt_sorted.float().cumsum(0)
    union = gts + (1 - gt_sorted).float().cumsum(0)
    jaccard = 1.0 - intersection / union
    if p > 1:
        jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
    return jaccard


def create_cone(bm: 'bmesh.types.BMesh', cap_ends: bool, cap_tris: bool,
    segments: int, diameter1: float, diameter2: float, depth: float, matrix:
    'mathutils.Matrix', calc_uvs: bool) ->dict:
    """Creates a cone with variable depth at both ends

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


def WriteASCIIFile(fname, data):
    """
	This procedure will write a list of strings to a file.

	Inputs:
		fname: name and path of output file
		data: list or array of strings to write
	"""
    f = open(fname, 'w')
    f.writelines(data)
    f.close()


@classmethod
def from_eeprom(cls, eeprom):
    """Construct description from EEPROM"""
    self = cls()
    self.describe(eeprom)
    return self


@classmethod
def find(cls, db, username):
    """Find a user info record by name.
        Returns None if not found"""
    return db.query(cls).filter(cls.username == username).first()


def __im_conform__(object):
    """Get an immutable version of the object.

        This method converts the given object into its immutable self.

        The return value will either be a core immutable object or an object
        implementing the `IImmutable` interface. If the latter is returned,
        it must be in `IM_MODE_SLAVE` mode and in the `IM_STATE_TRANSIENT`
        state.

        When having an `IImmutable` object, we must ensure that the result is
        in the transient state. Thus, if the immutable is already in the
        transient state, just return it, otherwise create a transient clone of
        it.

        This method is intended for internal use only and should only be
        called for sub-objects while adding them to the immutable. The
        resulting immutable must also be in the `IM_STATE_TRANSIENT`
        state.

        Raises a `ValueError` exception if the object cannot be converted.
        """


def layer_duplicate():
    """Make a copy of the active Grease Pencil layer

    """
    pass


def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None,
    HttpMethod=None):
    """
    Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
            ClientMethod.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
            default, the http method is whatever is used in the method's model.

    """
    pass


def _singleton_new(cls, *args, **kwargs):
    """
    An invalid new for singleton objects.
    """
    raise TypeError("'{0}' cannot be instantiated because it is a singleton"
        .format(cls.__name__))


def allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
    """
    Returns True if two tensors are element-wise equal within a tolerance.

    The tolerance values are positive, typically very small numbers.  The
    relative difference (`rtol` * abs(`b`)) and the absolute difference
    `atol` are added together to compare against the absolute difference
    between `a` and `b`.

    If either array contains one or more NaNs, False is returned.
    Infs are treated as equal if they are in the same place and of the same
    sign in both tensors.

    Parameters
    ----------
    a, b : array_like
        Input tensors to compare.
    rtol : float
        The relative tolerance parameter (see Notes).
    atol : float
        The absolute tolerance parameter (see Notes).
    equal_nan : bool
        Whether to compare NaN's as equal.  If True, NaN's in `a` will be
        considered equal to NaN's in `b` in the output tensor.

    Returns
    -------
    allclose : bool
        Returns True if the two tensors are equal within the given
        tolerance; False otherwise.

    See Also
    --------
    isclose, all, any, equal

    Notes
    -----
    If the following equation is element-wise True, then allclose returns
    True.

     absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

    The above equation is not symmetric in `a` and `b`, so that
    ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
    some rare cases.

    The comparison of `a` and `b` uses standard broadcasting, which
    means that `a` and `b` need not have the same shape in order for
    ``allclose(a, b)`` to evaluate to True.  The same is true for
    `equal` but not `array_equal`.

    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.allclose([1e10,1e-7], [1.00001e10,1e-8]).execute()
    False
    >>> mt.allclose([1e10,1e-8], [1.00001e10,1e-9]).execute()
    True
    >>> mt.allclose([1e10,1e-8], [1.0001e10,1e-9]).execute()
    False
    >>> mt.allclose([1.0, mt.nan], [1.0, mt.nan]).execute()
    False
    >>> mt.allclose([1.0, mt.nan], [1.0, mt.nan], equal_nan=True).execute()
    True

    """
    from ..arithmetic.isclose import isclose
    from .all import all
    return all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))


def _py2ri(obj):
    """ Dummy function for py2ri.

    This function will convert Python objects into rpy2.rinterface
    (ri) objects.
    """
    raise NotImplementedError(
        "Conversion 'py2ri' not defined for objects of type '%s'" % str(
        type(obj)))


@staticmethod
def calc_pressure_head(lam, h_b):
    """Calculate pressure head.

        Pressure head is set using *lambda* and *h_b*, using an
        equation after Brooks-Corey (1964), following Rawls et al., 1992.

        Parameters
        ----------
        lam : float, optional
            Pore-size distribution index. Exponent that describes the
            distribution of pore sizes in the soil, and controls
            effective hydraulic conductivity at varying water
            contents, following Brooks and Corey (1964) [-].
        h_b : float (m), optional
            Bubbling pressure. Capillary pressure of the soil,
            controlling effective hydraulic conductivity at varying
            water contents, following Brooks and Corey (1964) [m]
        """
    return (2.0 + 3.0 * lam) / (1.0 + 3.0 * lam) * h_b * 0.5


def CreateParamList(gridID, PSF, ESF, Eo, No):
    """
    Create a custom parameters list. **Be careful** of your inputs

    :param gridID: string, refer to the list at http://www.standardsforhighways.co.uk/ha/standards/ians/pdfs/ian99.pdf
    :param PSF: float - Projection Scale Factor
    :param ESF: float - Elevation Scale Factor
    :param Eo: float - delta Easting
    :param No: float - delta Northing

    :returns: Custom parameters for coordinate conversion
    """
    CSF = PSF * ESF
    return gridID, PSF, ESF, CSF, 1 / CSF, float(Eo), float(No)


def to_series(df):
    """
    For use in tests; converts DataFrame's first column to Series.
    """
    return df[df.columns[0]]


def split_datastore_path(datastore_path):
    """Split the datastore path to components.

    return the datastore name, relative folder path and the file name

    E.g. datastore_path = [datastore1] my_volume/my_volume.vmdk, returns
    (datastore1, my_volume/, my_volume.vmdk)

    :param datastore_path: Datastore path of a file
    :return: Parsed datastore name, relative folder path and file name
    """
    splits = datastore_path.split('[', 1)[1].split(']', 1)
    datastore_name = None
    folder_path = None
    file_name = None
    if len(splits) == 1:
        datastore_name = splits[0]
    else:
        datastore_name, path = splits
        splits = path.split('/')
        file_name = splits[len(splits) - 1]
        folder_path = path[:-len(file_name)]
    return datastore_name.strip(), folder_path.strip(), file_name.strip()


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

        :param TeamMergeToType val:
        :rtype: EventType
        """
    return cls('team_merge_to', val)


def get_acquisition_mode(acqu):
    """
    Retrieves the acquisition mode list from the header file.
    known values:
    REAL,
    COMPLEX,
    TPPI,
    COMPLEX_TPPI,
    PHASE_MODULATION,
    ECHO_ANTIECHO
    """
    if 'ACQUISITION_MODE' in acqu:
        return acqu['ACQUISITION_MODE'][1]
    elif 'Phase Mod' in acqu:
        return acqu['Phase Mod']
    return None


@classmethod
def factory(cls, ap, cmpid, address):
    """! @brief Common CoreSightComponent factory."""
    cmp = cls(ap, cmpid, address)
    if ap.core:
        ap.core.add_child(cmp)
    return cmp


def print_array_info(X, name='Array'):
    """Test function for verifying shapes and data ranges of input arrays"""
    Xt = X
    print('X type:', type(Xt))
    print(f'X.shape = {Xt.shape}')
    print(f'\nX[0].shape = {Xt[0].shape}')
    print(f'X[0] contains:\n\t', Xt[0])


def has_extension(ffile, extensions):
    """Check if ffile has an extension given in extensions. Extensions can be
    a string or a list of strings."""
    if isinstance(extensions, str):
        extensions = [extensions]
    if ffile.rpartition('.')[-1] in extensions:
        return True
    return False


def connect_atoms(model, data_file, model_id):
    """Takes a :py:class:`.Model` and creates :py:class:`.Bond`
    objects between atoms in it based on the ``connections`` in the provided
    :py:class:`.PdbDataFile`.

    :param Model model: the model to update.
    :param PdbDataFile data_file: The source Pdb Data File
    :param int model_id: The ID of the model in the data fileto be used for    conversion."""
    for connection in data_file.connections():
        atom = model.get_atom_by_id(connection['atom_id'])
        if atom:
            for bonded_atom_id in connection['bonded_atoms']:
                bonded_atom = model.get_atom_by_id(bonded_atom_id)
                if bonded_atom and atom is not bonded_atom:
                    atom.bond_to(bonded_atom)


def assign_weights(weights, network):
    """Assign the given parameters to the TensorLayer network.

    Parameters
    ----------
    weights : list of array
        A list of model weights (array) in order.
    network : :class:`Layer`
        The network to be assigned.

    Returns
    --------
    1) list of operations if in graph mode
            A list of tf ops in order that assign weights. Support sess.run(ops) manually.
    2) list of tf variables if in eager mode
            A list of tf variables (assigned weights) in order.

    Examples
    --------

    References
    ----------
    - `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__

    """
    ops = []
    for idx, param in enumerate(weights):
        ops.append(network.all_weights[idx].assign(param))
    return ops


def agg_catch(rec_catch):
    """
    Simple function to aggregate rec catchments.

    Parameters
    ----------
    rec_catch : GeoDataFrame
        The output from extract_catch

    Returns
    -------
    GeoDataFrame
    """
    rec_shed = rec_catch[['start', 'geometry']].dissolve('start')
    rec_shed.index = rec_shed.index.astype('int32')
    rec_shed['area'] = rec_shed.area
    rec_shed.crs = rec_catch.crs
    return rec_shed.reset_index()


@classmethod
def geom_col_name(cls):
    """
        Return the name of the metadata column used to store the feature
        geometry column.
        """
    return 'column_name'


@staticmethod
def get_time_unit(time_string: str):
    """
        Function that return the time unit from the string (Minutes/Hours)
        :param time_string: The original string with the time (ex. 50 Hours)
        :return: the unit of that time (ex. "Hours")
        """
    if '-' in time_string:
        return None
    start_pos = time_string.find(' ')
    return time_string[start_pos:].strip()


def aux_paral_f(x):
    """
    Auxiliary function needed in parallel propagate
    """
    os, rb = x
    os.ray_add(rb)
    os.propagate()
    return os


def str_slice(str1, start=None, stop=None, step=None):
    """ Perform a string slice """
    if step is None:
        step = 1
    return str1[start:stop:step]


def get_folder_path(FolderId=None, Limit=None, Fields=None, Marker=None):
    """
    Retrieves the path information (the hierarchy from the root folder) for the specified folder.
    By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested folder and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the parent folder names.
    See also: AWS API Documentation

    :example: response = client.get_folder_path(
        FolderId='string',
        Limit=123,
        Fields='string',
        Marker='string'
    )

    :type FolderId: string
    :param FolderId: [REQUIRED]
            The ID of the folder.

    :type Limit: integer
    :param Limit: The maximum number of levels in the hierarchy to return.

    :type Fields: string
    :param Fields: A comma-separated list of values. Specify 'NAME' to include the names of the parent folders.

    :type Marker: string
    :param Marker: This value is not supported.

    :rtype: dict
    :return: {
        'Path': {
            'Components': [
                {
                    'Id': 'string',
                    'Name': 'string'
                },
            ]
        }
    }

    """
    pass


def set_image_data_format(data_format):
    """Sets the value of the data format convention.

    # Arguments
        data_format: string. `'channels_first'` or `'channels_last'`.

    # Example
    ```python
        >>> from keras import backend as K
        >>> K.image_data_format()
        'channels_first'
        >>> K.set_image_data_format('channels_last')
        >>> K.image_data_format()
        'channels_last'
    ```
    """
    global _IMAGE_DATA_FORMAT
    if data_format not in {'channels_last', 'channels_first'}:
        raise ValueError('Unknown data_format:', data_format)
    _IMAGE_DATA_FORMAT = str(data_format)


@classmethod
def imageSearchEngine(cls):
    """
        Class method to get a reference to the image search engine.

        @return reference to the image finder object
        @rtype ImageSearchEngine
        """
    if cls._imageSearchEngine is None:
        from .ImageSearch.ImageSearchEngine import ImageSearchEngine
        cls._imageSearchEngine = ImageSearchEngine()
    return cls._imageSearchEngine


def transpose_dataframe(a):
    """
    Check if the input is a column-wise Pandas `DataFrame`. If `True`, return a
    transpose dataframe since stumpy assumes that each row represents data from a
    different dimension while each column represents data from the same dimension.
    If `False`, return `a` unchanged. Pandas `Series` do not need to be transposed.

    Note that this function has zero dependency on Pandas (not even a soft dependency).

    Parameters
    ----------
    a : ndarray
        First argument.

    Returns
    -------
    output : a
        If a is a Pandas `DataFrame` then return `a.T`. Otherwise, return `a`
    """
    if type(a).__name__ == 'DataFrame':
        return a.T
    return a


def validate_serializer(serializer, _type):
    """
    Validates the serializer for given type.

    :param serializer: (Serializer), the serializer to be validated.
    :param _type: (Type), type to be used for serializer validation.
    """
    if not issubclass(serializer, _type):
        raise ValueError('Serializer should be an instance of {}'.format(
            _type.__name__))


def parse_gmt_offset_timezone(tz_gmt_offset_name):
    """Parse example '(GMT-08:00) Pacific Time'
    """
    tz_parts = tz_gmt_offset_name.split(' ', 1)
    map(str.strip, tz_parts)
    tz_offset = tz_parts[0][4:-1].replace(':', '')
    tz_name = tz_parts[1]
    return tz_name, tz_offset


def CompareBigEndian(c1, c2):
    """
    Loosely matches CompareBigEndian() from eccryptoverify.cpp
    Compares two arrays of bytes, and returns a negative value if the first is
    less than the second, 0 if they're equal, and a positive value if the
    first is greater than the second.
    """
    c1 = list(c1)
    c2 = list(c2)
    while len(c1) > len(c2):
        if c1.pop(0) > 0:
            return 1
    while len(c2) > len(c1):
        if c2.pop(0) > 0:
            return -1
    while len(c1) > 0:
        diff = c1.pop(0) - c2.pop(0)
        if diff != 0:
            return diff
    return 0


def dict_remove_key(d, key, default=None):
    """
    removes a key from dict __WITH__ side effects
    Returns the found value if it was there (default=None). It also modifies the original dict.

    """
    return d.pop(key, default)


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        Different versions of Elasticsearch may need specific versions
        of the mapping, thus using es_major to potentially provide
        different mappings.

        When the mapping depends on the version of Kibiter/Kibana,
        we will use the Elasticsearch version anyway, since they should
        be paired (same major version for 5 and larger, ES major version 2
        for Kibiter/Kibana major version 4).

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = '{}'
    return {'items': mapping}


def obt_vals_paso(símismo):
    """
        Obtener los valores del variable a todos los pasos del ciclo actual.

        Returns
        -------
        np.ndarray

        """
    return símismo._matr_paso


def listToCigar(array):
    """
	Converts a list to a cigar string

	I'm calling it an array, even though I know it's a list

	Args:
		array: A list coresponding to the cigar of interest
	Returns:
		cigar: A string representing the cigar sequence
	"""
    if array is None or len(array) == 0:
        return None
    cigar = ''
    previousChar = array[0]
    previousCount = 0
    for character in array:
        if previousChar != character:
            cigar += str(previousCount) + previousChar
            previousChar = character
            previousCount = 1
        else:
            previousCount += 1
    cigar += str(previousCount) + previousChar
    return cigar


def contains_linebreaks(s):
    """True if there is any vertical whitespace in s."""
    for ch in '\x0c\n\r':
        if ch in s:
            return True
    else:
        return False


def _determine_match_unittest(module, klass, docstring):
    """
    Implements the match check for Python Unittests
    """
    return module.is_matching_klass(klass)


def unsubscribe(observer):
    """Unregister the callable that was registered with subscribe()."""


def can_paginate(operation_name=None):
    """
    Check if an operation can be paginated.

    :type operation_name: string
    :param operation_name: The operation name. This is the same name
            as the method name on the client. For example, if the
            method name is create_foo, and you'd normally invoke the
            operation as client.create_foo(**kwargs), if the
            create_foo operation can be paginated, you can use the
            call client.get_paginator('create_foo').

    """
    pass


def log2(n):
    """
    log2(n : int) -> int

    Find the binary integer logarithm to n, so that 2^s = n.
    """
    return n.bit_length() - 1


def find_between(line: str, char1: str, char2: str, nth_time=1):
    """
    Goes through the given line, looking for what's between char1 and char2.
    Returns substring found. If char1...char2 is present more than once in
    line, the nth_time parameter can be used to specify which occurrence should
    be returned. The char1 and char2 are NOT returned along with the substring.

    Parameter
    ---------
    line : str
        Line where substring shall be looked for.
    char1 : str
        Char (single char!) at the beginning of the desired substring.
    char2 : str
        Char (single char!) at the end of the desired substring.
    nth_time : int, optional
        Which occurrence of the char1...char2 pattern must be returned.
        if no number is given, nth_time is set to 1.

    Returns
    -------
    between : str
        Substring found between char1 and char2.
        Does NOT include char1 and char2.

    """
    if line.count(char1) < nth_time or line.count(char2) < nth_time:
        raise ValueError('bad arguments given to find_between()')
    between = ''
    this_time = 1
    line = iter(line)
    char = next(line)
    while True:
        while char != char1:
            char = next(line)
        char = next(line)
        while char != char2:
            between += char
            char = next(line)
        if this_time == nth_time:
            return between
        else:
            this_time += 1
            between = ''


def fill_empties(abstract):
    """Fill empty cells in the abstraction

    The way the row patterns are constructed assumes that empty cells are
    marked by the letter `C` as well. This function fill those in. The function
    also removes duplicate occurrances of ``CC`` and replaces these  with
    ``C``.

    Parameters
    ----------
    abstract : str
        The abstract representation of the file.

    Returns
    -------
    abstraction : str
        The abstract representation with empties filled.

    """
    while 'DD' in abstract:
        abstract = abstract.replace('DD', 'DCD')
    while 'DR' in abstract:
        abstract = abstract.replace('DR', 'DCR')
    while 'RD' in abstract:
        abstract = abstract.replace('RD', 'RCD')
    while 'CC' in abstract:
        abstract = abstract.replace('CC', 'C')
    if abstract.startswith('D'):
        abstract = 'C' + abstract
    if abstract.endswith('D'):
        abstract += 'C'
    return abstract


def initialize(wiki):
    """
    Initialize global datastructures.

    Parameters
    ----------
    wiki : list of dicts
        Each dict represents a langauge
    """
    globals()['iso2wiki'] = {}
    globals()['wiki2iso'] = {}
    globals()['wiki2label'] = {}
    for el in wiki:
        globals()['iso2wiki'][el['ISO 369-3']] = el['Wiki Code']
        globals()['wiki2iso'][el['Wiki Code']] = el['ISO 369-3']
        globals()['wiki2label'][el['Wiki Code']] = el['Label']


@classmethod
def connect_factory_kwargs(cls, instance):
    """
        Return keyword arguments for the connect_factory.

        Method should be derived and modified, A dictionary may be substituted.
        The default return value is an empty dictionary.

        :rtype dict
        """
    return dict()


def create_drop_parser(subparsers, parent_parser):
    """Adds sub-parser for 'drop'."""
    subparsers.add_parser('drop', parents=[parent_parser])


def getprop_other(getter):
    """getprop(property_or_getter)

    Used on getters that have the same name as a corresponding
    property.  For Qt bindings other than PythonQt, this version will
    return the result of calling the argument, which is assumed to be
    a Qt getter function.  (With PythonQt, properties override getters
    and no calling must be done.)"""
    return getter()


def _add_dry_run(arg_parser, help_text):
    """
    Adds optional --dry-run parameter to a parser. Stored as 'dry_run'.
    :param arg_parser: ArgumentParser parser to add this argument to.
    :param help_text: str label displayed in usage
    """
    arg_parser.add_argument('--dry-run', help=help_text, action=
        'store_true', dest='dry_run')


def is_valid_fai_entry(fai_entry):
    """Check if the given fai entry is valid.

    Arguments:
        fai_entry (collection): Collection that will be checked for fulfillment of
            all prerequisites of a fai-entry.

    Returns:
        bool: True if the entry is valid, False if not.

    Note:
        A valid fai entry has the following structure:

            1. name of the chromosome
            2. length of the chromosome in bytes
            3. starting position of the chromosomes in the FASTA file (in bytes)
            4. length of a line in the FASTA file (in characters)
            5. length of a line in the FASTA file (in bytes) this includes trailing

    """
    try:
        name, length, start, line_len_chars, line_len_bytes = fai_entry
    except ValueError:
        return False
    except TypeError:
        return False
    if (isinstance(name, str) or isinstance(name, bytes)) and isinstance(length
        , int) and isinstance(start, int) and isinstance(line_len_chars, int
        ) and isinstance(line_len_bytes, int):
        return True
    else:
        return False


def get_ambig_dna_values():
    """
    Dict of IUPAC alphabets ambigious base calls
    """
    ambiguous_dna_values = {'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', 'M':
        'AC', 'R': 'AG', 'W': 'AT', 'S': 'CG', 'Y': 'CT', 'K': 'GT', 'V':
        'ACG', 'H': 'ACT', 'D': 'AGT', 'B': 'CGT', 'X': 'GATC', 'N': 'GATC'}
    return ambiguous_dna_values


def vertex_group_select():
    """Select all the vertices assigned to the active vertex group

    """
    pass


def set_rules(rules):
    """Set the rules in use for policy checks."""
    global _rules
    _rules = rules


@classmethod
def from_characteristic_rate(cls, min_mag, b_val, char_mag, char_rate,
    bin_width):
    """
        Define Youngs and Coppersmith 1985 MFD by constraing cumulative a
        value from characteristic rate.
        The cumulative a value is obtained by making use of the property that
        the rate of events at m' - 1 must be equal to the rate at the
        characteristic magnitude, and therefore by first computing the
        incremental a value, using the following equation::

            10 ** (a_incr - b_val * (m_prime - 1)) == char_rate / 0.5

        where ``m' - 1 = char_mag - 1.25``.
        The cumulative a value is then obtained as ::

            a_val = a_incr - log10(b_val * ln(10))

        :param min_mag:
            The lowest magnitude for the MFD. The first bin in the
            :meth:`result histogram <get_annual_occurrence_rates>` is aligned
            to make its left border match this value.
        :param b_val:
            The Gutenberg-Richter ``b`` value -- the gradient of the loglinear
            G-R relationship.
        :param char_mag:
            The characteristic magnitude defining the middle point of
            characteristic distribution. That is the boxcar function
            representing the characteristic distribution is defined in the
            range [char_mag - 0.25, char_mag + 0.25].
        :param char_rate:
            The characteristic rate associated to the characteristic magnitude,
            to be distributed over the domain of the boxcar function
            representing the characteristic distribution (that is λ_char =
            char_rate / 0.5)
        :param bin_width:
            A positive float value -- the width of a single histogram bin.
        :returns:
            An instance of :class:`YoungsCoppersmith1985MFD`.

        Values for ``min_mag`` and the maximum magnitude (char_mag + 0.25)
        don't have to be aligned with respect to ``bin_width``. They get
        rounded accordingly anyway so that both are divisible by ``bin_width``
        just before converting a function to a histogram.
        See :meth:`_get_min_mag_and_num_bins`.
        """
    return cls(min_mag, b_val, char_mag, char_rate, bin_width)


def dict_from_file(filename, key_type=str):
    """Load a text file and parse the content as a dict.

    Each line of the text file will be two or more columns splited by
    whitespaces or tabs. The first column will be parsed as dict keys, and
    the following columns will be parsed as dict values.

    Args:
        filename(str): Filename.
        key_type(type): Type of the dict's keys. str is user by default and
            type conversion will be performed if specified.

    Returns:
        dict: The parsed contents.
    """
    mapping = {}
    with open(filename, 'r') as f:
        for line in f:
            items = line.rstrip('\n').split()
            assert len(items) >= 2
            key = key_type(items[0])
            val = items[1:] if len(items) > 2 else items[1]
            mapping[key] = val
    return mapping


def _hide_key(param, value):
    """Used to hide keys in the logging."""
    if not param.endswith('_key'):
        return value
    if len(value) > 16:
        return value[:3] + '...' + value[-3:]
    else:
        return '********'


def sparse_matrix_indices(spmat):
    """Return the indices of the given sparse matrix.

    Parameters
    ----------
    spmat : SparseMatrix
        The framework-specific sparse matrix.

    Returns
    -------
    index : tuple
        This is used to support different sparse formats.
        For COO format:
          index=('coo', coord), where coord is of shape (2, nnz).
          coord[0,:] should be the row index and coord[1,:] should be
          the column index.
        For CSR format:
          index=('csr', indices, indptr), where indices is of shape (nnz,)
          and indptr is of shape (nrows+1,). See ``scipy.sparse.csr_matrix``
          for more documents on what each array means.
    """
    pass


def dmstodec(x):
    """ Utility Function to convert CDDMMSS.sssss
    to floating point decimal degrees

    where C is the Cardinal Direction (N/W/S/E) indicator for sign
    """
    c = 1.0 if x[0] in 'NW' else -1.0
    d = float(x[1:3])
    m = float(x[3:5])
    s = float(x[5:])
    return c * (d + m / 60.0 + s / 3600.0)


@staticmethod
def _conditions_column_index_to_name(conditions, idxdict, typesdict,
    allow_casting):
    """
        Changes the conditions contained in the list in the following way:
        column indexes will be substituted by names, while column names (strings) will
        be untouched. If casting is allowed conditions which requires casting will
        have a new field 'casted_to' added, mapped to 'numeric'.

        :param conditions:
        :type conditions: list
        :param idxdict: Dict mapping column indexes to names
        :type idxdict: dict
        :param typesdict: Dict mapping column names to a type
        :type typesdict: dict
        :param allow_casting: If casting a column to a type matching the 'value' field in condition is allowed
        :type allow_casting: bool
        """
    for cond in conditions:
        col = cond['column']
        if type(col) is int:
            assert 0 <= col < len(idxdict
                ), "column index '%s' out of range" % col
            cond['column'] = idxdict[col]
        if cond['column'] != '*' and typesdict[cond['column']] == str and type(
            cond['value']) != str:
            assert allow_casting, "Type of column '%s' is string, but 'value' %s is of numeric type, and casting is not allowed" % (
                col, cond['value'])
            cond['casted_to'] = 'numeric'


def check_asset(res, asset_data, errors):
    """Check single asset."""
    try:
        obj = res.data.get(asset_data['slug'])
    except LookupError:
        errors.append('Object with slug {} does not exist.'.format(
            asset_data['slug']))
        return
    if obj.name != asset_data['name']:
        errors.append('Object with slug {} has wrong name: "{}" != "{}".'.
            format(obj.slug, obj.name, asset_data['name']))


def find_node(prev: bool=False):
    """Search for named node and allow to select and activate it

    :param prev: Previous
    :type prev: bool
    """
    pass


def format_warnings(message, category, filename, lineno, file=None, line=None):
    """Sets STDOUT warnings

    Args:
        message: the unformatted warning message being reported
        category (str): the level of warning (handled by `warnings` module)
        filename (str): filename for logging purposes (defaults to STDOUT)
        lineno (int): where the error occurred.

    Returns:
        formatted warning string
    """
    return ' {}:{}: {}:{}'.format(filename, lineno, category.__name__, message)


def _assert_real_val(msg, name, expected):
    """Verify that attr name of msg equals expected.

    protobuf messages are subject to precision loss for floats if the
    C backend is used. This function raises an assertion error if the
    message attr value isn't equal to the expected value).
    """
    actual = getattr(msg, name)
    if actual != expected:
        raise AssertionError(
            """bad protobuf value for '%s': expected %s but got %s
Try setting env PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python"""
             % (name, expected, actual))


def t_DHCPV6_SET_TEE_TIMES(t):
    """dhcpv6-set-tee-times"""
    return t


def flatten(iterable):
    """
    Flatten a sequence, returning a sequence of all its items' items.

    For example, `flatten([[1, 2], [3], [4, 'meow']]) == [1, 2, 3, 4, 'meow']`.
    """
    iterator = iter(iterable)
    try:
        return sum(iterator, next(iterator))
    except StopIteration:
        return []


def real(x):
    """Get only the real part of x."""
    return x.real if isinstance(x, complex) else x


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


def pixels_to_EMU(value):
    """1 pixel = 9525 EMUs"""
    return int(value * 9525)


def _skip_initial_italics_off_nodes(collection):
    """Return a collection like the one given, but without the
    initial <Italics OFF> nodes

    :type collection: list[_InstructionNode]
    :rtype: list[_InstructionNode]
    """
    new_collection = []
    can_add_italics_off_nodes = False
    for node in collection:
        if node.is_italics_node():
            if node.sets_italics_on():
                can_add_italics_off_nodes = True
                new_collection.append(node)
            elif can_add_italics_off_nodes:
                new_collection.append(node)
        else:
            new_collection.append(node)
    return new_collection


def zerocopy_to_dgl_ndarray(input):
    """Zerocopy a framework-specific Tensor to dgl.ndarray.NDArray

    Parameters
    ----------
    input : Tensor

    Returns
    -------
    dgl.ndarray.NDArray
    """
    pass


@staticmethod
def evaluate_fitness(individual, fn):
    """
        Sets the fitness of the individual passed in.

        Parameters
        ----------
        individual : Individual
            Individual for which to assess the fitness.
        fn : function
            Fitness function used to evaluate the fitness.
        """
    individual.fitness = fn(individual.position)


@classmethod
def construct_event(cls, validation_data: dict, **kwargs):
    """
        Construct event from given dictionary and kwargs
        :param validation_data: usually it is a response data from Policy
        :param kwargs:
        :return: constructed event data dict
        """
    event_data = dict()
    event_data['result'] = cls._known_results[validation_data['access']]
    event_data['client_id'] = kwargs['client_id']
    event_data['action'] = cls._known_actions[kwargs['action']]
    event_data['application'] = kwargs['application']
    event_data['resource_id'] = kwargs['resource_id']
    event_data['asset_name'] = kwargs['asset_name']
    event_data['severity'] = kwargs['severity'] if kwargs.get('severity', None
        ) else 50
    event_data['reason'] = validation_data['cause'] if validation_data['access'
        ] == 'denied' and validation_data.get('cause', None) else None
    return event_data


def get_permissions_for_principal(principal_id):
    """Get the permissions granted to a principal.

        Return the list of (permission, setting) tuples that describe
        security assertions for this principal.

        If no permissions have been set for this principal, then the empty
        list is returned.
        """


def dns_lookup(dns_name):
    """
    Simple DNS lookup
    """
    import socket
    try:
        return socket.gethostbyname(dns_name)
    except socket.gaierror:
        return None


def read_xds_correct_lp(correct_lp_file):
    """Read the XDS CORRECT.LP file and get out the spacegroup and
    unit cell constants it decided on."""
    unit_cell = None
    space_group_number = None
    with open(correct_lp_file, 'r') as fh:
        for record in fh.readlines():
            if 'SPACE_GROUP_NUMBER=' in record:
                try:
                    space_group_number = int(record.split()[-1])
                except Exception:
                    space_group_number = 0
            if 'UNIT_CELL_CONSTANTS=' in record and 'used' not in record:
                unit_cell = tuple(map(float, record.split()[-6:]))
    return unit_cell, space_group_number


def strip_seq_log(filename):
    """
    Clean up filename by removing trailing .seq or .log

    Args:
        filename (str): filename with possible file type

    Returns:
        filename (str): filename with .seq or .log stripped
    """
    if filename[-3:] == 'seq' or filename[-3:] == 'log':
        filename = filename[:-4]
    return filename


def swap(upper, lower):
    """Swaps the two values."""
    return lower, upper


def get_contents():
    """Return an iterator on content to be exported.
        """


def vertex_group_assign_new():
    """Assign the selected vertices to a new vertex group

    """
    pass


def now(ctx):
    """
    Returns the current date and time
    """
    return ctx.now.astimezone(ctx.timezone)


def vekt(n, base):
    """Funksjon som gir en repeterende serie med siffer fra ``base``, som
       har lengde ``n``.

       For kontroll_10 er vekttall-serien: 2,1,2,1,2,1...
       for kontroll_11 er vekttall-serien: 2,3,4,5,6,7,2,3,4,5,...
    """
    for i in range(n):
        yield base[i % len(base)]


def quaternions_flip():
    """Flip quaternion values to achieve desired rotations, while maintaining the same orientations

    """
    pass


def copy_reduce(reducer, graph, target, in_data, out_size, in_map, out_map):
    """Copy target data and perform reduce based on graph structure.

    Parameters
    ----------
    reducer : str
        Type of reduction: be 'sum', 'max', 'min', 'mean', 'prod', 'none' (no
        reduction)
    graph : GraphIndex
        The graph
    target : int
        The input target (src, dst, edge)
    in_data : Tensor
        The input data
    out_size : int
        Size of first dimension of output data
    in_map : tuple
        Two input id mapping arrays, one for forward, the other for backward
    out_map : tuple
        Two output id mapping arrays, one for forward, the other for backward

    Returns
    -------
    Tensor
        The result.
    """
    pass


@staticmethod
def derivative_at(sub_expr1, var, val_dict, order=1):
    """
        calculate 1st derivative of var using forward mode

        INPUTS
        =======
        sub_expr1: expression whose components include var(or itself be to var)
        val_dict: a dictionary containing variable name and values.
        var: variable of interest
        order: default set to 1, set to 2 if 2nd derivative is desired

        RETURNS
        ========
        derivative of var with respect to sub_expr1
        """
    return -sub_expr1.derivative_at(var, val_dict, order)


def get_current_tomb_name(ctx):
    """Retrieves the name of the current tomb.

    Returns:
        The name of the current tomb as a `string`.
    """
    return ctx.obj.open_tomb_name


def makeresponsecacher(repo, proto, command, args, objencoderfn,
    redirecttargets, redirecthashes):
    """Construct a cacher for a cacheable command.

    Returns an ``iwireprotocolcommandcacher`` instance.

    Extensions can monkeypatch this function to provide custom caching
    backends.
    """
    return None


@staticmethod
def _is_end_regex(word):
    """Returns `True` if `word` is the end of a regex."""
    return word.endswith('/') or word.endswith('/g') or word.endswith('/i'
        ) or word.endswith('/ig') or word.endswith('/gi')


@staticmethod
def __getSetBrightnessCmd(brightness):
    """Give 'Set brightness' command

    Keyword arguments:
      brightness -- (int) Brightness percentage between 0 and 100

    return: (bytearray) 'Set brightness' command
    """
    brightness = int(brightness)
    if brightness < 0:
        brightness = 0
    elif brightness > 100:
        brightness = 100
    brightness &= 255
    return bytearray([49, 0, 0, 8, 3, brightness, 0, 0, 0])


def get_bts_for_msg_compression(tl_packet):
    """return -- header bytes of DNS or b"" """
    if tl_packet._triggelistpacket_parent is not None:
        return tl_packet._triggelistpacket_parent.header_bytes
    return b''


def quantile(data, column, q):
    """ Returns number of users responsible for a specific

    :param data: an input pd.Dataframe, e.g. commit_user_stats.reset_index()
        note that without index reset commit_user_stats is a Series
    :param column: a column to aggregate on, e.g. username
    :param q: quantile, e.g. 0.9
    :return: pd.Dataframe aggregated on the specified column
    >>> df = pd.DataFrame({'foo': 1, 'bar': [1,1,1,1,1,1,1,1,1,1]})
    >>> quantile(df, 'foo', 0.5).loc[1, 'bar']
    5
    >>> quantile(df, 'foo', 0.9).loc[1, 'bar']
    9
    """
    return data.groupby(column).aggregate(lambda x: sum(x.sort_values(
        ascending=False).cumsum() / x.sum() <= q))


def extract_model(model_param):
    """Extract model from a given model param [model]"""
    return model_param.split('-', 1)[1:][0]


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 near(a, b, significance=0.0001):
    """ Returns True iff the difference between the values is within the factor 'significance' of
    one of the original values.  Default is to within 4 decimal places. """
    return abs(a - b) <= significance * max(abs(a), abs(b))


def _operation_to_pooling_type(operation):
    """Takes in the operation string and returns the pooling type."""
    splitted_operation = operation.split('_')
    return splitted_operation[0]


def fie_to_di(d):
    """Converts dimensions from feet-inches-eigths to decimal inches"""
    if isinstance(d, str):
        fie = d.split('-')
    else:
        return d
    if len(fie) == 3:
        return 12 * float(fie[0]) + float(fie[1]) + float(fie[2]) / 8.0
    else:
        return d


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 t_DO_FORWARD_UPDATES(t):
    """do-forward-updates"""
    return t


def execute_change_set(ChangeSetName=None, StackName=None,
    ClientRequestToken=None):
    """
    Updates a stack using the input information that was provided when the specified change set was created. After the call successfully completes, AWS CloudFormation starts updating the stack. Use the  DescribeStacks action to view the status of the update.
    When you execute a change set, AWS CloudFormation deletes all other change sets associated with the stack because they aren't valid for the updated stack.
    If a stack policy is associated with the stack, AWS CloudFormation enforces the policy during the update. You can't specify a temporary stack policy that overrides the current policy.
    See also: AWS API Documentation

    :example: response = client.execute_change_set(
        ChangeSetName='string',
        StackName='string',
        ClientRequestToken='string'
    )

    :type ChangeSetName: string
    :param ChangeSetName: [REQUIRED]
            The name or ARN of the change set that you want use to update the specified stack.

    :type StackName: string
    :param StackName: If you specified the name of a change set, specify the stack name or ID (ARN) that is associated with the change set you want to execute.

    :type ClientRequestToken: string
    :param ClientRequestToken: A unique identifier for this ExecuteChangeSet request. Specify this token if you plan to retry requests so that AWS CloudFormation knows that you're not attempting to execute a change set to update a stack with the same name. You might retry ExecuteChangeSet requests to ensure that AWS CloudFormation successfully received them.

    :rtype: dict
    :return: {}

    """
    pass


@classmethod
def subs_dict(cls, value):
    """Dictionary of substitutions to evaluate with a given value."""
    name = getattr(cls, 'name', None) or cls.__name__
    return {cls: value}


def unbox(data, c_type=None, ffi=ffi):
    """
    Try to return something to pass to low-level ffi calls.
    For a cffi type, return data.
    For a Struct, return the wrapper's cdata.
    Else try to use data as a ffi initializer for c_type.
    """
    if not isinstance(data, ffi.CData):
        try:
            return data.cdata
        except AttributeError:
            if c_type:
                return ffi.new(c_type, data)
    return data


def bench2(x):
    """A benchmark function for test purposes.

        f(x) = x ** 2           if x < 0
               (x-5) ** 2 - 5   otherwise.

    It has a global minima with f(x*) = -5 at x* = 5.
    """
    if x[0] < 0:
        return x[0] ** 2
    else:
        return (x[0] - 5) ** 2 - 5


def filename_or_id(string):
    """
    Determine based on suffix is something is a file or an ide.
    """
    for ending in ['.gz', '.bz2', '.json', '.parquet']:
        if string.endswith(ending):
            return 'filename'
    if '.' in string[:6]:
        return 'id'
    raise NameError(
        "Can't determine if {} is supposed to be a filename or an id.".
        format(string) +
        "Please explicitly name your first argument to Volume 'id' or 'path'.")


def process_ttl(data, template):
    """
    Replace {$ttl} in template with a serialized $TTL record
    """
    record = ''
    if data is not None:
        record += '$TTL %s' % data
    return template.replace('{$ttl}', record)


def ubytes_to_int(bytes_arr, endianness):
    """
     This method is used for turning up to 4 unsigned bytes into signed integers.
    :param list bytes_arr: one to four Bytes which are interpreted as an unsigned Integer
    :param int endianness: determines the order of the bytes: 0 = bigendian, 1 = little endian
    :return: integer
    """
    retval = 0
    length = len(bytes_arr)
    for i in range(0, length):
        if endianness == 0:
            tmpb = bytes_arr[length - i - 1]
        else:
            tmpb = bytes_arr[i]
        if tmpb < 0:
            tmpi = 256 + tmpb
        else:
            tmpi = tmpb
        tmpi <<= i * 8
        retval += tmpi
    return retval


def faultratio(I, Ipickup, CTR=1):
    """
    Fault Multiple of Pickup (Ratio) Calculator

    Evaluates the CTR-scaled pickup measured to
    pickup current ratio.

    M = meas / pickup

    Parameters
    ----------
    I:          float
                Measured Current in Amps
    Ipickup:    float
                Fault Current Pickup Setting (in Amps)
    CTR:        float, optional
                Current Transformer Ratio for relay,
                default=1

    Returns
    -------
    M:          float
                The measured-to-pickup ratio
    """
    M = I / (CTR * Ipickup)
    return M


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


def is_numeric(value):
    """
    Check if a var is a single element
    :param value:
    :return:
    """
    return isinstance(value, (int, float))


def quote_text(text, markup, username=''):
    """
    Quote message using selected markup.
    """
    if markup == 'markdown':
        return '>' + text.replace('\n', '\n>').replace('\r', '\n>') + '\n'
    elif markup == 'bbcode':
        if username is not '':
            username = '="%s"' % username
        return '[quote%s]%s[/quote]\n' % (username, text)
    else:
        return text


def norm_dlldy(y):
    """derivative of log pdf of standard normal with respect to y
    """
    return -y


def get_all(isamAppliance, check_mode=False, force=False):
    """
    Retrieving a list of all JDBC server connections
    """
    return isamAppliance.invoke_get(
        'Retrieving a list of all JDBC server connections',
        '/mga/server_connections/jdbc/v1')


@classmethod
def configurable_default(cls):
    """Returns the implementation class to be used if none is configured."""
    raise NotImplementedError()


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


def get_prefix_repr(prefix, activities):
    """
    Gets the numeric representation (as vector) of a prefix

    Parameters
    -------------
    prefix
        Prefix
    activities
        Activities

    Returns
    -------------
    prefix_repr
        Representation of a prefix
    """
    this_pref_repr = [0] * len(activities)
    for act in prefix:
        i = activities.index(act)
        this_pref_repr[i] = this_pref_repr[i] + 1
    return tuple(this_pref_repr)


def get_size():
    """
        Returns a Deferred that fires with the size of the content held
        by the uploadable.
        """


def _recover_type(v):
    """
    recover "17" to 17.
    recover "[]" to [].
    recover "datetime(2020,1,1)" to datetime(2020,1,1).
    keep "abc" as str.

    :param v: str.
    :return: Any.
    """
    try:
        nv = eval(v)
    except (NameError, SyntaxError):
        nv = v
    if callable(nv):
        nv = v
    return nv


def getCRS(path):
    """ gets the coordinate reference systems from the shapefile

    input "path": type string, file path to shapefile
    """
    return 'None'


def html_wrap(content, color='white', elm='span'):
    """
    custom html wrapping, set custom color or html element
    :param str content: the message string
    :param str elm: the html element
    :param str color: the color
    :return:
    """
    return "<{elm} style='color: {color}'>{content}</{elm}>".format(content
        =content, elm=elm, color=color)


def infusion(ratio, curr_temp, new_temp, water_temp, grain):
    """
    Calculate the amount of hot water required to raise the mash
    temperature to a specific temperature.

    From: http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions

    Wa = (T2 - T1)(.2G + Wm)/(Tw - T2)

    :arg ratio: Grist ratio in quarts/lbs
    :arg curr_temp: Current mash temperature in fahrenheit
    :arg new_temp: The target temperature of the mash in fahrenheit
    :arg water_temp: The temperature of the water to be added in fahrenheit
    :arg grain: The dry weight of the grain in the mash in pounds
    :returns: The amount of water at given temperature to add to achieve
        requested change in mash temperature
    """
    mash_water = grain * ratio
    return (new_temp - curr_temp) * (0.2 * grain + mash_water) / (water_temp -
        new_temp)


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

        :param NoteAclTeamLinkType val:
        :rtype: EventType
        """
    return cls('note_acl_team_link', val)


def __init__(A):
    """RegulatoryReportingCodes - a model defined in Swagger"""
    A.discriminator = None


def nw_align(seq_a, seq_b, args):
    """
    Perform pairwise alignment with the `nw` method.
    """
    raise ValueError('Not implemented.')


def datetime_to_str(dt):
    """Coverts a datetime into a timezone aware string.
    """
    r = dt.isoformat()
    if dt.microsecond:
        r = r[:23] + r[26:]
    if r.endswith('+00:00'):
        r = r[:-6] + 'Z'
    return r


def hide_socket_toggle():
    """Toggle unused node socket display

    """
    pass


def enable_resampling():
    """
    Enable resampling in case of gantry tilted data (disabled by default)
    """
    global resample
    resample = True


def check_wanted(zelf, *args, **kwargs):
    """ whether an object is desired. """
    want = args[0]
    for key, value in want.items():
        if key == 'format':
            continue
        if key not in zelf:
            continue
        if value.startswith('-'):
            continue
        if value not in str(zelf[key]):
            return False
    return True


def wrappush(orig, repo, remote, *args, **kwargs):
    """interpret the --publish flag and pass it to the push operation"""
    newargs = kwargs.copy()
    if kwargs.pop('publish', False):
        opargs = kwargs.get('opargs')
        if opargs is None:
            opargs = {}
        newargs['opargs'] = opargs.copy()
        newargs['opargs'][b'publish'] = True
    return orig(repo, remote, *args, **newargs)


@classmethod
def map_multi_join_model(cls, model_list, join_model_list,
    relation_prop_name, join_on, refer_to):
    """
        Map model list with list of relational model list with respect of join_on & refer_to property

        :type model_list: list
        :param model_list:

        :type join_model_list: list
        :param join_model_list:

        :type relation_prop_name: str
        :param relation_prop_name: relation property name

        :type join_on: str
        :param join_on:

        :type refer_to: str
        :param refer_to:
        """
    for model in model_list:
        join_data = []
        join_on_prop_value = getattr(model, join_on)
        for join_model in join_model_list:
            refer_to_prop_value = getattr(join_model, refer_to)
            if refer_to_prop_value == join_on_prop_value:
                join_data.append(join_model)
        model._model_state().add_with_relation(relation_prop_name)
        setattr(model, relation_prop_name, join_data)


@staticmethod
def _define_module_argument_spec():
    """
        Define the argument spec for the ansible module
        :return: argument spec dictionary
        """
    argument_spec = dict(server_ids=dict(type='list', required=True), state
        =dict(default='present', choices=['present', 'absent']), location=
        dict(), cpu=dict(type='int'), memory=dict(type='int'),
        anti_affinity_policy_id=dict(), anti_affinity_policy_name=dict(),
        alert_policy_id=dict(), alert_policy_name=dict(), wait=dict(type=
        'bool', default=True), additional_network=dict())
    mutually_exclusive = [['anti_affinity_policy_id',
        'anti_affinity_policy_name'], ['alert_policy_id', 'alert_policy_name']]
    return {'argument_spec': argument_spec, 'mutually_exclusive':
        mutually_exclusive}


@staticmethod
def _reward_while_pending():
    """Defines the reward value which is assigned to config, while it is pending."""
    return float('-inf')


@classmethod
def _object_compiled_hook(cls, ll_module, buf):
    """
        `ll_module` was compiled into object code `buf`.
        """
    try:
        self = ll_module.__library
    except AttributeError:
        return
    if self._object_caching_enabled:
        self._compiled = True
        self._compiled_object = buf


@classmethod
def load(cls, uuid):
    """
            Return an instance of the paste object with the content of the
            file matching this uuid. Use load_from_file() and get_path()
        """
    return cls.load_from_file(cls.get_path(uuid))


def is_unibipartite(graph):
    """Internal function that returns whether the given graph is a uni-directional
    bipartite graph.

    Parameters
    ----------
    graph : GraphIndex
        Input graph

    Returns
    -------
    bool
        True if the graph is a uni-bipartite.
    """
    src, dst, _ = graph.edges()
    return set(src.tonumpy()).isdisjoint(set(dst.tonumpy()))


def create_package(project, name, sourcefolder=None):
    """Creates a package and returns a `rope.base.resources.Folder`"""
    if sourcefolder is None:
        sourcefolder = project.root
    packages = name.split('.')
    parent = sourcefolder
    for package in packages[:-1]:
        parent = parent.get_child(package)
    made_packages = parent.create_folder(packages[-1])
    made_packages.create_file('__init__.py')
    return made_packages


def _copy_ancestor_docstring(mro, fn):
    """Decorator to set docstring for *fn* from *mro*"""
    if fn.__doc__ is not None:
        raise RuntimeError('Function already has docstring')
    for cls in mro:
        super_fn = getattr(cls, fn.__name__, None)
        if super_fn is None:
            continue
        fn.__doc__ = super_fn.__doc__
        break
    else:
        raise RuntimeError(
            "Can't inherit docstring for %s: method does not exist in superclass"
             % fn.__name__)
    return fn


def names(zelf, *args, **kwargs):
    """ skip the unwanted keys e.g those that start with a "_". """
    for key in zelf.keys():
        k = str(key)
        if k.startswith('_'):
            continue
        yield key


def bytes_2_str(bytes_str):
    """
    用于将bytes 类型转换为 str 类型
    :param bytes_str:
    :return:
    """
    return str(bytes_str, encoding='GBK')


def versioned_name(unversioned_name, version):
    """Joins an unversioned name with the specified version.

       Returns a versioned path.
    """
    return unversioned_name + '@' + str(version)


def rsa_crt_dmp1(private_exponent, p):
    """
    Compute the CRT private_exponent % (p - 1) value from the RSA
    private_exponent (d) and p.
    """
    return private_exponent % (p - 1)


def count(coll):
    """
    Returns the number of items in the collection. Also works on strings.
    """
    if hasattr(coll, '__len__'):
        return len(coll)
    n = 0
    for _ in coll:
        n += 1
    return n


def sanitize(text):
    """
    We're using a very simple approach to writing a CSV (which is actually
    tab-separated, but a lot of software considers that a kind of CSV). Our
    CSV output will be formatted correctly and understood by psql as long
    as we avoid certain characters that would conflict:

    - Newlines (which of course separate CSV entries)
    - Tabs (which separate our columns)
    - Null codepoints (which are not allowed in psql)

    We also need to escape every literal backslash, as backslashes are
    interpreted by psql.

    It's a good question whether this step should be necessary -- names
    of concepts shouldn't include control characters, and the few
    instances of backslashes in ConceptNet appear to be mistakes.
    """
    return text.replace('\n', '').replace('\t', '').replace('\x00', ''
        ).replace('\\', '\\\\')


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Nest binary sensors.

    No longer used.
    """


def p_nonempty_lists(t):
    """case_spec_list      : case_spec case_spec_list
                           | case_spec
       case_statement_list : case_statement case_statement_list
                           | case_statement"""
    if len(t) == 2:
        t[0] = t[1]
    else:
        t[0] = t[1] + t[2]


def bget(jdb, s):
    """Better get. Check for nonetype"""
    try:
        return jdb.get(s)
    except:
        pass
    return None


def __iter__():
    """ Return an iterator over the keys of this dictionary """


def get_names(infos):
    """Get names of all parameters.

    Parameters
    ----------
    infos : list
        Content of the config header file.

    Returns
    -------
    names : list
        Names of all parameters.
    """
    names = []
    for x in infos:
        for y in x:
            names.append(y['name'][0])
    return names


def col_normalization(data):
    """
    Perform z-normalization on all columns
    """
    data_mu = data.mean(axis=0, keepdims=True)
    data_sigma = data.std(axis=0, keepdims=True)
    data_sigma[data_sigma == 0] = 1.0
    return (data - data_mu) / data_sigma


@staticmethod
def _draw_hline(**kwargs):
    """Draw a grid of horizontal lines."""
    for y in range(0, kwargs['im_height'], kwargs['grid_size']):
        kwargs['grid'].line([(max(0, kwargs['padding_left']), min(max(y,
            kwargs['padding_top']), kwargs['im_height'] - kwargs[
            'padding_bottom'])), (kwargs['im_width'] - kwargs[
            'padding_right'], min(max(y, kwargs['padding_top']), kwargs[
            'im_height'] - kwargs['padding_bottom']))], fill=kwargs[
            'grid_colour'], width=kwargs['line_width'])


def convert_to_http_field(field):
    """Convert a field from Title-Case to HTTP_UPPER_CASE.
    """
    field = field.upper().replace('-', '_')
    if not field.startswith('HTTP_'):
        field = 'HTTP_' + field
    return field


@staticmethod
def _search_for_network_config_by_name(orgvdc_network_name,
    network_configuration_section):
    """Search for the NetworkConfig element by org vdc network name.

        :param str orgvdc_network_name: name of the org vdc network to be
            searched.
        :param lxml.objectify.ObjectifiedElement network_configuration_section:
            NetworkConfigSection of the vApp.

        :return: an object containing NetworkConfig XML element which
            represents the configuration of the named org vdc network.

        :rtype: lxml.objectify.ObjectifiedElement
        """
    if hasattr(network_configuration_section, 'NetworkConfig'):
        for network_config in network_configuration_section.NetworkConfig:
            if network_config.get('networkName') == orgvdc_network_name:
                return network_config
    return None


def _set_content_type(kwargs):
    """If the 'content-type' header is unset, set it to 'applcation/json'.

    The 'content-type' will not be set if doing a file upload as requests will
    automatically set it.

    :param kwargs: A ``dict``. The keyword args supplied to :func:`request` or
        one of the convenience functions like it.
    :return: Nothing. ``kwargs`` is modified in-place.

    """
    if 'files' in kwargs:
        return
    headers = kwargs.pop('headers', {})
    headers.setdefault('content-type', 'application/json')
    kwargs['headers'] = headers


@staticmethod
def disable():
    """Set a logging level to one above INFO to disable logs emitting"""
    pass


def format_time(t):
    """Format seconds into a human readable form.

    >>> format_time(10.4)
    '10.4s'
    >>> format_time(1000.4)
    '16min 40.4s'
    """
    m, s = divmod(t, 60)
    h, m = divmod(m, 60)
    if h:
        return '{0:2.0f}hr {1:2.0f}min {2:4.1f}s'.format(h, m, s)
    elif m:
        return '{0:2.0f}min {1:4.1f}s'.format(m, s)
    else:
        return '{0:4.1f}s'.format(s)


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

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

    Examples:
        # priority queue iterator
        iter_except(functools.partial(heappop, h), IndexError)

        # non-blocking dict iterator
        iter_except(d.popitem, KeyError)

        # non-blocking deque iterator
        iter_except(d.popleft, IndexError)

        # loop over a producer Queue
        iter_except(q.get_nowait, Queue.Empty)

        # non-blocking set iterator
        iter_except(s.pop, KeyError)

    http://docs.python.org/3.4/library/itertools.html#itertools-recipes
    """
    try:
        if first_ is not None:
            yield first_()
        while 1:
            yield func()
    except exception:
        pass


@staticmethod
def get_connection():
    """Get the SQLA database connection

        :return: the SQLA database connection
        """
    from aiida.backends import sqlalchemy as sa
    return sa.ENGINE.raw_connection()


def compute_degrees(edges):
    """
    Compute the degree of vertices.

    @param      edges       list of tuple
    @return                 dictionary {key: degree}
    """
    res = {}
    for a, b in edges:
        res[a] = res.get(a, 0) + 1
        res[b] = res.get(b, 0) + 1
    return res


def r_in(td, r_0):
    """Calculate incident countrate given dead time and detected countrate."""
    tau = 1 / r_0
    return 1.0 / (tau - td)


def strain_sort(data_dict):
    """
    Sorts a dictionary by strain

    The input dictionary should consist of plasmid keys and data for values
    The sorted dictionary with have strains for the keys and plasmid/data
    dictionaries as the values.
    """
    strain_dict = {}
    for plasmid, data in data_dict.items():
        strain = plasmid.split('_')[0]
        if strain not in strain_dict.keys():
            strain_dict[strain] = {}
        strain_dict[strain][plasmid] = data
    return strain_dict


def p_program_d(p):
    """program_d : declaracion program_d
                 | program_f
    """


def workaround_single_value_for_in_clause(build_ids):
    """Workaround for using MySQL-python 1.2.4

    This workaround is not necessary after upgrading MySQL-python to 1.2.5
    """
    return build_ids * 2 if len(build_ids) == 1 else build_ids


def extrude(forked: bool=False):
    """Create new bones from the selected joints

    :param forked: Forked
    :type forked: bool
    """
    pass


def get_root():
    """Get root of site.
        """


def _add_subjectAnimals_defaults(row, out_col_ndx_map):
    """
    Makes default values as necessary for the following required columns:
    * `Age Unit` - `Days`
    * `Age Event` - `Age at infection`
    """
    age_unit_ndx = out_col_ndx_map['Age Unit']
    age_unit = row[age_unit_ndx]
    if not age_unit:
        row[age_unit_ndx] = 'Days'
    age_event_ndx = out_col_ndx_map['Age Event']
    age_event = row[age_event_ndx]
    if not age_event:
        row[age_event_ndx] = 'Age at infection'


@classmethod
def init_by_id(cls, _id):
    """Load task by its ID"""


def index(elem):
    """
    Return the index position of an element in the children of a parent.
    """
    parent = elem.getparent()
    for x in range(0, len(parent.getchildren())):
        if parent.getchildren()[x] == elem:
            return x
    return -1


@classmethod
def run(cls, cf_profiles, rev_table, gid_col='gen_gids', profiles_dset=
    'cf_profile', rep_method='meanoid', err_method='rmse', weight=
    'gid_counts', n_profiles=1, resource_classes=None, region_map=
    'reeds_region', cap_bins=5, sort_bins_by='trans_cap_cost', pre_filter=
    None, trg_by_region=False, reg_cols=('region', 'class'), fout=None,
    hourly=True, hour_ending=True, max_workers=None):
    """Run representative profiles.

        Parameters
        ----------
        cf_profiles : str
            Filepath to reV gen output file to extract "cf_profile" from.
        rev_table : str | pd.DataFrame
            Aggregated supply curve summary table or file containing table
        gid_col : str
            Column label in rev_summary that contains the generation gids
            (data index in gen_fpath).
        profiles_dset : str
            Dataset name to pull generation profiles from.
        rep_method : str
            Method identifier for calculation of the representative profile.
        err_method : str
            Method identifier for calculation of error from the representative
            profile.
        weight : str | None
            Column in rev_summary used to apply weighted mean to profiles.
            The supply curve table data in the weight column should have
            weight values corresponding to the gid_col in the same row.
        n_profiles : int
            Number of representative profiles to save to fout.
        resource_classes : str | pandas.DataFrame | pandas.Series | dict
            Resource classes, either provided in a .csv, .json
            as a DataFrame or Series, or in a dictionary.
            If None, assumes rev_table has come from ReedsClassifier
        region_map : str | pandas.DataFrame
            Mapping of supply curve points to region to create classes for
         cap_bins : int
            Number of equal capacity bins to create for each
            region-class
        sort_bins_by : str | list, optional
            Column(s) to sort by before capacity binning,
            by default 'trans_cap_cost'
        pre_filter : dict | NoneType
            Column value pair(s) to filter on. If None don't filter
        trg_by_region : bool
            Groupby on region when computing TRGs
        reg_cols : tuple
            Label(s) for a categorical region column(s) to extract profiles
            for.
        fout : str, optional
            filepath to output h5 file, by default None
        hourly : bool, optional
            Flag to get hourly data (top of hour) instead of native resolution,
            by default True
        hour_ending : bool, optional
            Flag to shift instantaneous profiles and time index to hour ending,
            by default True
        max_workers : int, optional
            Number of parallel workers. 1 will run serial, None will use all
            available., by default None

        Returns
        -------
        profiles : dict
            dict of n_profile-keyed arrays with shape (time, n) for the
            representative profiles for each region.
        meta : pd.DataFrame
            Meta dataframes recording the regions and the selected rep profile
            gid.
        time_index : pd.DatatimeIndex
            Datetime Index for represntative profiles
        """
    rp = cls(cf_profiles, rev_table, gid_col=gid_col, profiles_dset=
        profiles_dset, rep_method=rep_method, err_method=err_method, weight
        =weight, n_profiles=n_profiles, resource_classes=resource_classes,
        region_map=region_map, cap_bins=cap_bins, sort_bins_by=sort_bins_by,
        pre_filter=pre_filter, trg_by_region=trg_by_region, reg_cols=reg_cols)
    rp._run(fout=fout, hourly=hourly, hour_ending=hour_ending, max_workers=
        max_workers)
    return rp.profiles, rp.meta, rp.time_index