def _log_removed_output(log_file, original, new, type_):
    """
    function writing the output of functions that remove datapoints to a log file.

    Parameters
    ----------
    log_file : str
        string containing the directory to the log file to be written out
    original : int
        original length of the dataset
    new : int
        length of the new dataset
    type_ : str
        'removed' or 'dropped'
    """
    log_file = open(log_file, 'a')
    log_file.write(str('\nOriginal dataset: ' + str(original) +
        ' datapoints; new dataset: ' + str(new) + ' datapoints' + str(
        original - new) + ' datapoints ', type_))
    log_file.close()


def datetime_is_naive(dateTime):
    """ Returns True if dateTime is naive."""
    return dateTime.tzinfo is None or dateTime.tzinfo.utcoffset(dateTime
        ) is None


def data_unlink():
    """Unlink active Grease Pencil data-block

    """
    pass


def is_same(e1, e2):
    """
    Elements in entity can be cloned by a simulation module or viewer module.
    In some cases, their same identity should be checked.
    """
    if e1.name == e2.name and e1.module == e2.module:
        return True
    return False


def solve_camera():
    """Solve camera motion from tracks

    """
    pass


def _get_format_control(values, option):
    """Get a format_control object."""
    return getattr(values, option.dest)


def setExtensionContext(context_id):
    """ Set extension profile that contains migrations used
            At this point look up installed instance version if its in quickinstaller
        """


def p_const_map(p):
    """const_map : '{' const_map_seq '}' """
    p[0] = dict(p[2])


def format_number(number) ->str:
    """Format a number with thousand separators and return a string"""
    try:
        return '{:,}'.format(number)
    except ValueError:
        return str(number)


def type_object_attrgetter(obj, attr, *defargs):
    """
    This implements an improved attrgetter for type objects (i.e. classes)
    that can handle class attributes that are implemented as properties on
    a metaclass.

    Normally `getattr` on a class with a `property` (say, "foo"), would return
    the `property` object itself.  However, if the class has a metaclass which
    *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find
    the "foo" property on the metaclass and resolve it.  For the purposes of
    autodoc we just want to document the "foo" property defined on the class,
    not on the metaclass.

    For example::

        >>> class Meta(type):
        ...     @property
        ...     def foo(cls):
        ...         return 'foo'
        ...
        >>> class MyClass(metaclass=Meta):
        ...     @property
        ...     def foo(self):
        ...         ""\"Docstring for MyClass.foo property.""\"
        ...         return 'myfoo'
        ...
        >>> getattr(MyClass, 'foo')
        'foo'
        >>> type_object_attrgetter(MyClass, 'foo')
        <property at 0x...>
        >>> type_object_attrgetter(MyClass, 'foo').__doc__
        'Docstring for MyClass.foo property.'

    The last line of the example shows the desired behavior for the purposes
    of autodoc.
    """
    for base in obj.__mro__:
        if attr in base.__dict__:
            if isinstance(base.__dict__[attr], property):
                return base.__dict__[attr]
            break
    return getattr(obj, attr, *defargs)


def get_status_tree(depth=-1):
    """Get tree of all active content objects. For containers,
        show the default object if available.  This is a list of
        indent, object tuples.
        """


def select(scope=None, fn=None):
    """
        Select values based on scope; returns list eqivalent
        to self.values() if scope is None, otherwise filtered.

        Return value function may be passed as self.items or
        self.keys to get items/keys instead of values.
        """


def _predict_output_python_function(model, input):
    """
    Predict output function for python functions.
    """
    output = model(input)
    return output


def delete_identity(Identity=None):
    """
    Deletes the specified identity (an email address or a domain) from the list of verified identities.
    This action is throttled at one request per second.
    See also: AWS API Documentation

    Examples
    The following example deletes an identity from the list of identities that have been submitted for verification with Amazon SES:
    Expected Output:

    :example: response = client.delete_identity(
        Identity='string'
    )

    :type Identity: string
    :param Identity: [REQUIRED]
            The identity to be removed from the list of identities for the AWS Account.

    :rtype: dict
    :return: {}

    """
    pass


def findex_main():
    """Findex main loop.
    """
    try:
        print(
            'Usage: findex [OPTION]...\n  web           runs the web interface\n        '
            )
    except KeyboardInterrupt:
        print('w00t')


def _const_compare_digest_backport(a, b):
    """
    Compare two digests of equal length in constant time.

    The digests must be of type str/bytes.
    Returns True if the digests match, and False otherwise.
    """
    result = abs(len(a) - len(b))
    for l, r in zip(bytearray(a), bytearray(b)):
        result |= l ^ r
    return result == 0


def get_formset_alive(formset_class, data, instance=None, initial=None):
    """
    https://schinckel.net/2016/04/30/%28directly%29-testing-django-formsets/
    formset = get_formset_alive(MyFormSet, [
        # Form 1
        {
          'foo': ['bar1', 'bar2'],
          'multi_val': {0: 'val1', 1: 'val2'},
          'baz': 'qux1',
        },
        # Form 2
        {
          'foo': ['cam1'],
          'multi_val': {0: 'zoo1', 1: 'zoo2'},
          'baz': 'eggs',
        },
    ])
    ============================================================================
    Many to many field is represented with a list:
        '{}-{}-{}'.format(prefix, form_number, field_name) = ['val_1', 'val_2']
    Multivalue field is represented with a dict:
    '{}-{}-{}_{}'.format(prefix, form_number, field_name, value_number=key) = value
    ============================================================================
    """
    prefix = formset_class().prefix
    formset_data = {}
    for i, form_data in enumerate(data):
        for name, value in form_data.items():
            if isinstance(value, dict):
                for k, v in value.items():
                    formset_data['{}-{}-{}_{}'.format(prefix, i, name, k)] = v
            else:
                formset_data['{}-{}-{}'.format(prefix, i, name)] = value
    formset_data['{}-TOTAL_FORMS'.format(prefix)] = len(data)
    formset_data['{}-INITIAL_FORMS'.format(prefix)] = len(initial
        ) if initial else 0
    if instance:
        return formset_class(formset_data, instance=instance, initial=initial)
    else:
        return formset_class(formset_data, initial=initial)


def distance_paris(lat1, lng1, lat2, lng2):
    """
    Distance euclidienne approchant la distance de Haversine
    (uniquement pour Paris).

    @param      lat1    lattitude
    @param      lng1    longitude
    @param      lat2    lattitude
    @param      lng2    longitude
    @return             distance
    """
    return ((lat1 - lat2) ** 2 + (lng1 - lng2) ** 2) ** 0.5 * 90


def fill_list_valueparamIR(initialparameters):
    """
    return a list of default value for index_refine board from a dict initialparameters
    """
    list_valueparamIR = [initialparameters['PeakList Folder'],
        initialparameters['PeakListCor Folder'], initialparameters[
        'IndexRefine PeakList Folder'], initialparameters[
        'PeakList Filename Prefix'], initialparameters[
        'PeakList Filename Suffix'], initialparameters['nbdigits'],
        initialparameters['startingindex'], initialparameters['finalindex'],
        initialparameters['stepindex'], initialparameters[
        'Detector Calibration File .det'], initialparameters[
        'GuessedUBMatrix'], initialparameters['MinimumMatchingRate'],
        initialparameters['IndexRefine Parameters File'], initialparameters
        ['Selected Peaks from File']]
    return list_valueparamIR


def _get_reffile(hdr, key):
    """Get ref file from given key in given FITS header."""
    ref_file = None
    if key in hdr:
        ref_file = hdr[key].strip()
        if ref_file.upper() == 'N/A':
            ref_file = None
    return ref_file


def prepareImageSignal(button, label, type_, col, row, x, y, xPixel, yPixel):
    """See Plot documentation for content of events"""
    return {'event': 'imageClicked', 'button': button, 'label': label,
        'type': type_, 'col': col, 'row': row, 'x': x, 'y': y, 'xpixel':
        xPixel, 'ypixel': yPixel}


def get_product_codes(product_codes=None):
    """
    @type product_codes: dict
    """
    if product_codes:
        out = ''
        for prodcode in product_codes:
            out += '{0}/{1}'.format(prodcode.get('ProductCodeId'), prodcode
                .get('ProductCodeType'))
        return out


@classmethod
def available(cls):
    """returns True if ALSA is available and running on the system"""
    try:
        from audiotools.output import ALSAAudio
        return True
    except ImportError:
        return False


def _is_sunder(name):
    """Returns True if a _sunder_ name, False otherwise."""
    return name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1
        ] != '_' and len(name) > 2


def replace_pattern(tokens, new_pattern):
    """ Given a RegexLexer token dictionary 'tokens', replace all patterns that
        match the token specified in 'new_pattern' with 'new_pattern'.
    """
    for state in tokens.values():
        for index, pattern in enumerate(state):
            if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]:
                state[index] = new_pattern


def area_fpa(force, pressure):
    """Usage: area_fpa(force of object, pressure)"""
    return force * pressure


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


def tstv(ts, tv):
    """
    Calculate ts/tv, and avoid division by zero error
    """
    try:
        return round(float(ts) / float(tv), 4)
    except ZeroDivisionError:
        return 0


def compute_cells(text_dict, booleans=None, floats=None, integers=None,
    strings=None):
    """
    Compute a row of values, using data types.

    Args:
        booleans:
        floats:
        integers:
        strings:

    Returns:
        A python lists of values
    """
    if strings is None:
        strings = []
    if integers is None:
        integers = []
    if floats is None:
        floats = []
    if booleans is None:
        booleans = []
    row = list()
    for name in booleans:
        row.append(bool(text_dict[name]) if name in text_dict else None)
    for name in floats:
        row.append(float(text_dict[name]) if name in text_dict else None)
    for name in integers:
        row.append(int(text_dict[name]) if name in text_dict else None)
    for name in strings:
        row.append(str(text_dict[name]) if name in text_dict else None)
    return row


@classmethod
def all(cls):
    """Return query of all buckets (excluding deleted)."""
    return cls.query.filter_by(deleted=False)


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

        :param UserSelectorArg val:
        :rtype: UserAddResult
        """
    return cls('invalid_user', val)


def zero_separation(n):
    """Zero separation in normalized r based on radial order n."""
    return 1 / n ** 2


def get_t(x, mu, s, n):
    """
    Function to get the T value correspondent of the X value in the t-student
    distribution.

    Parameters:
    --------------------------
    x : double, float
        Specific value from the random variable.

    mu : double, float
        Population average given.

    sd : double, float
        Sample standard deviation given.

    n : int, optional
        Sample size, less than 30.

    Returns:
    --------------------------
    t : float, double
        The T value correspondent of the X value in the t-student.
    """
    if n > 30:
        print('The sample size must be less than 30.')
    else:
        t = (x - mu) / (s / n ** 0.5)
        return t


def moving_average(data, xcol, ycol, width):
    """Compute the moving average of  YCOL'th column of each sample point
in  DATA. In particular, for each element  I in  DATA,
this function extracts up to  WIDTH*2+1 elements, consisting of
 I itself,  WIDTH elements before  I, and  WIDTH
elements after  I. It then computes the mean of the  YCOL'th
column of these elements, and it composes a two-element sample
consisting of  XCOL'th element and the mean.

>>> data = [[10,20], [20,30], [30,50], [40,70], [50,5]]
... chart_data.moving_average(data, 0, 1, 1)
[(10, 25.0), (20, 33.333333333333336), (30, 50.0), (40, 41.666666666666664), (50, 37.5)]

  The above value actually represents:

[(10, (20+30)/2), (20, (20+30+50)/3), (30, (30+50+70)/3),
  (40, (50+70+5)/3), (50, (70+5)/2)]

"""
    out = []
    try:
        for i in range(len(data)):
            n = 0
            total = 0
            for j in range(i - width, i + width + 1):
                if j >= 0 and j < len(data):
                    total += data[j][ycol]
                    n += 1
            out.append((data[i][xcol], float(total) / n))
    except IndexError:
        raise IndexError('bad data: %s,xcol=%d,ycol=%d,width=%d' % (data,
            xcol, ycol, width))
    return out


def setdefaulttimeout(timeout):
    """
    Set the global timeout setting to connect.

    timeout: default socket timeout time. This value is second.
    """
    global _default_timeout
    _default_timeout = timeout


def copy_python_command_button():
    """Copy the Python command matching this button

    """
    pass


@staticmethod
def is_supported_action(action):
    """ Returns True if the given action is supported. """
    return action in {'new', 'paste', 'edit', 'delete'}


def init_rulesengine_db(rulesengine_db):
    """initializes the base rules engine database"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(rulesengine_db)
    cur = conn.cursor()
    create_rules_table = (
        'CREATE TABLE "RulesEngine" (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Path TEXT, Active INTEGER) '
        )
    cur.execute(create_rules_table)
    conn.commit()
    conn.close()


def ignore(obj, ign):
    """ check if object needs to be ignored. """
    if not ign:
        return False
    return False


def _rowsize(shape, maindim, itemsize):
    """"The size of the rows in bytes in dimensions orthogonal to *maindim*."

    shape:
        Shape of the sample to fit in the row

    maindim:
        The dimension along which iterators work. Its value is 0 (i.e. the first
        dimension) when the dataset is not extendable, and self.extdim (where
        available) for extendable ones.

    itemsize:
        nbytes of each element

    The meaning of *atomic* is that individual elements of a cell can not be
    extracted directly by indexing (i.e.  __getitem__()) the dataset; e.g. if a
    dataset has shape (2, 2) and its atoms have shape (3,), to get the third
    element of the cell at (1, 0) one should use dataset[1,0][2] instead of
    dataset[1,0,2].
    """
    rowsize = itemsize
    for i, dim in enumerate(shape):
        if i != maindim:
            rowsize *= dim
    return rowsize


@classmethod
def can_translate(cls, header, filename=None):
    """Indicate whether this translation class can translate the
        supplied header.

        Checks the instrument value and compares with the supported
        instruments in the class

        Parameters
        ----------
        header : `dict`-like
            Header to convert to standardized form.
        filename : `str`, optional
            Name of file being translated.

        Returns
        -------
        can : `bool`
            `True` if the header is recognized by this class. `False`
            otherwise.
        """
    if cls.supported_instrument is None:
        return False
    try:
        translator = cls(header, filename=filename)
        instrument = translator.to_instrument()
    except KeyError:
        return False
    return instrument == cls.supported_instrument


@classmethod
def info(cls, msg):
    """
        Log provided message with level INFO.
        """
    return cls(msg, level='info')


def xsetattr(object, xname, value):
    """ Sets the value of an extended object attribute name of the form:
        name[.name2[.name3...]].
    """
    names = xname.split('.')
    for name in names[:-1]:
        object = getattr(object, name)
    setattr(object, names[-1], value)


def hmean(nums):
    """Return harmonic mean.

    The harmonic mean is defined as

        .. math::

            \\frac{|nums|}{\\sum\\limits_{i}\\frac{1}{nums_i}}

    Following the behavior of Wolfram|Alpha:
    - If one of the values in nums is 0, return 0.
    - If more than one value in nums is 0, return NaN.

    Cf. https://en.wikipedia.org/wiki/Harmonic_mean

    Parameters
    ----------
    nums : list
        A series of numbers

    Returns
    -------
    float
        The harmonic mean of nums

    Raises
    ------
    ValueError
        hmean requires at least one value

    Examples
    --------
    >>> hmean([1, 2, 3, 4])
    1.9200000000000004
    >>> hmean([1, 2])
    1.3333333333333333
    >>> hmean([0, 5, 1000])
    0

    .. versionadded:: 0.1.0

    """
    if len(nums) < 1:
        raise ValueError('hmean requires at least one value')
    elif len(nums) == 1:
        return nums[0]
    else:
        for i in range(1, len(nums)):
            if nums[0] != nums[i]:
                break
        else:
            return nums[0]
    if 0 in nums:
        if nums.count(0) > 1:
            return float('nan')
        return 0
    return len(nums) / sum(1 / i for i in nums)


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


@classmethod
def new(cls, *values):
    """ Create a new matrix from the provided `values` array. """
    M = cls()
    M[:] = values
    return M


def determine_engine(content):
    """
    Determine the engine used in the given content.

    The engine is determined by the ``@startXXX`` used at the beginning of the
    file. Possible values are:

    ::

        @startuml --> plantuml
        @startdot --> graphviz
        @startditaa --> ditaa

    :param str content: Content to analyze.
    :return: The name of the engine found, or None.
    :rtype: str
    """
    if content.startswith('@startuml'):
        return 'plantuml'
    if content.startswith('@startdot'):
        return 'graphviz'
    if content.startswith('@startditaa'):
        return 'ditaa'
    return None


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

        :param GuestAdminChangeStatusDetails val:
        :rtype: EventDetails
        """
    return cls('guest_admin_change_status_details', val)


@classmethod
def get_bit_info(cls, value):
    """Get the name of all bits set

        Returns a list of strings."""
    res = []
    for name, info in cls.desc.items():
        if value & info[0]:
            res.append(name)
    return res


@staticmethod
def mutation_probability(cell):
    """Probability to mutate if selected for it."""
    return 1


def operate(elems, units, inplace_units=False, unitdict=None, key=None,
    operation='+'):
    """
    Operate on elements considering their units

    Parameters
    -----------
    elems: list, tuple
        list of pandas.Series
    units: list, tuple
        list of pint.units ordered as the elems list
    inplace_units: bool
        sets dictionary inplace_units
    unitdict: dict
        dict to be set inplace
    key: str
        name of variables to be set inplace as dict key
    """
    import pandas as pd
    import numpy as np
    idx = elems[0].index
    if operation == '+':
        result = elems[0].values * units[0]
        for elem, unit in zip(elems[1:], units[1:]):
            if type(elem) == pd.Series:
                elem = elem.reindex(idx)
                result += elem.values * unit
            else:
                result += elem * unit
    if operation == '*':
        result = elems[0].values * units[0]
        for elem, unit in zip(elems[1:], units[1:]):
            if type(elem) == pd.Series:
                elem = elem.reindex(idx)
                result *= elem.values * unit
            else:
                result *= elem * unit
    if operation == '/':
        result = elems[0].values * units[0]
        for elem, unit in zip(elems[1:], units[1:]):
            if type(elem) == pd.Series:
                elem = elem.reindex(idx)
                result /= elem.values * unit
            else:
                result /= elem * unit
    out = pd.Series(result.magnitude, index=idx)
    funit = result.units
    if inplace_units == True:
        unitdict.update({key: funit})
        return out
    else:
        return out, funit


def track_settings_as_default():
    """Copy tracking settings from active track to default settings

    """
    pass


def get_user(email):
    """Get the user that controls the given email address, or None.

        :param email: The email address to look up.
        :type email: str
        :return: The user found or None.
        :rtype: `IUser`.
        """


def z2_n_probability(z2, n=2, ntrial=1, n_summed_spectra=1):
    """Calculate the probability of a certain folded profile, due to noise.

    Parameters
    ----------
    z2 : float
        A Z^2_n statistics value
    n : int, default 2
        The ``n`` in $Z^2_n$

    Other Parameters
    ----------------
    ntrial : int
        The number of trials executed to find this profile
    n_summed_spectra : int
        Number of Z_2^n periodograms that were averaged to obtain z2

    Returns
    -------
    p : float
        The probability that the Z^2_n value has been produced by noise
    """
    if ntrial > 1:
        import warnings
        warnings.warn(
            'Z2_n: The treatment of ntrial is very rough. Use with caution')
    from scipy import stats
    epsilon = ntrial * stats.chi2.sf(z2 * n_summed_spectra, 2 * n *
        n_summed_spectra)
    return epsilon


def hex_to_float(hexstring):
    """
    The chiller encodes floats using the following hex convevntion.

    1. convert hex to int
    2. if int val > 32767, it's a negative number, subtract 65536
    3. divide by temp resolution (100)
    """
    val = int(hexstring, 16)
    if val > 32767:
        val -= 65536
    return val / 100


def is_object(swagger_spec, object_spec, no_default_type=False):
    """
    A schema definition is of type object if its type is object or if it uses
    model composition (i.e. it has an allOf property).
    :param swagger_spec: :class:`bravado_core.spec.Spec`
    :param object_spec: specification for a swagger object
    :type object_spec: dict
    :param no_default_type: ignore bravado-core 'default_type_to_object' configuration
    :type no_default_type: bool
    :return: True if the spec describes an object, False otherwise.
    """
    deref = swagger_spec.deref
    default_type = 'object' if not no_default_type and swagger_spec.config[
        'default_type_to_object'] else None
    object_type = deref(deref(object_spec).get('type', default_type))
    return (object_type == 'object' or object_type is None and 'allOf' in
        object_spec)


def getBuild(number):
    """Attempt to return an IBuildControl object for the given build.
        Returns None if no such object is available. This will only work for
        the build that is currently in progress: once the build finishes,
        there is nothing to control anymore."""


def find_macaddr_via_iface(dev, macaddr):
    """ '* 17       0050.abcd.de17    dynamic   0          F    F  Po1' """
    cli_text = dev.execute(f'show mac address-table | inc {macaddr}')
    if not cli_text:
        return None
    return cli_text.split()[-1]


def line(num=11, char='#'):
    """
    Print line of char.

    :param num: number of character in this line
    :type num : int
    :param char: character
    :type char : str
    :return: None
    """
    print(char * num)


def as_scalar(data):
    """Returns a scalar whose value is copied from this array.

    Parameters
    ----------
    data : Tensor
        The input data

    Returns
    -------
    scalar
        The scalar value in the tensor.
    """
    pass


def preprocess_identity(*data, categorical_variables=None):
    """
    An identify function for preprocessing.

    Returns inputs without modifying them.

    :param data: array(s).
    :param categorical_variables: A list of strings representing the variables that are categorical.
    :return: array(s).
    """
    if len(data) == 1:
        output = data[0]
    elif len(data) == 2:
        output = data[0], data[1]
    else:
        raise ValueError
    return output


@staticmethod
def split_string(text_block, max_segment_len):
    """
        Splits a string into segments such that each segment fits into the
        passed maximum segment length. Splits on space only. If any segment
        of the passed string cannot be split on space, then chops that
        segment at the passed length. E.g.:

        print(Util.split_string("this is a test of stringsplitting", 10))
        Produces: '["this is a", "test of", "stringspli", "tting"]'

        In all cases, trims trailing spaces on all segments but - within a
        segment interior - does not alter spaces. Honors leading spaces at
        the start of a string (or after a newline embedded in a string) but
        left-justifies if a string was split to fit within the passed width.
        Nuances arise based on the yaml flow operator (pipe, or greater-than)
        provided in the yaml.

        :param text_block: the string the split into segments
        :param max_segment_len: the maximum length of any segment

        :return: a List of the segments created by the function. If 'None'
        is passed in 'text_block', or the empty string is passed, or a string
        of all spaces is passed, then an empty List is returned.
        """
    segments = []
    if not text_block or len(text_block.strip()) == 0:
        return segments
    lines = text_block.split('\n')
    for line in lines:
        if len(line.strip()) == 0:
            segments.append('')
            continue
        cur = 0
        while True:
            end = cur + max_segment_len
            if end >= len(line):
                if len(line[cur:].strip()) > 0:
                    segments.append(line[cur:])
                break
            for i in range(end, cur - 1, -1):
                if line[i] == ' ':
                    end = i
                    break
            segments.append(line[cur:end].rstrip())
            cur = end + len(line[end:]) - len(line[end:].lstrip())
    return segments


def lookupHostInfo(name, timeout=None):
    """
        Perform a HINFO record lookup.

        @type name: C{str}
        @param name: DNS name to resolve.

        @type timeout: Sequence of C{int}
        @param timeout: Number of seconds after which to reissue the query.
            When the last timeout expires, the query is considered failed.

        @rtype: L{Deferred}
        @return: A L{Deferred} which fires with a three-tuple of lists of
            L{twisted.names.dns.RRHeader} instances.  The first element of the
            tuple gives answers.  The second element of the tuple gives
            authorities.  The third element of the tuple gives additional
            information.  The L{Deferred} may instead fail with one of the
            exceptions defined in L{twisted.names.error} or with
            C{NotImplementedError}.
        """


@classmethod
def from_coo(cls, A, dense_index=False):
    """
        Create a Series with sparse values from a scipy.sparse.coo_matrix.

        Parameters
        ----------
        A : scipy.sparse.coo_matrix
        dense_index : bool, default False
            If False (default), the SparseSeries index consists of only the
            coords of the non-null entries of the original coo_matrix.
            If True, the SparseSeries index consists of the full sorted
            (row, col) coordinates of the coo_matrix.

        Returns
        -------
        s : Series
            A Series with sparse values.

        Examples
        --------
        >>> from scipy import sparse
        >>> A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])),
                               shape=(3, 4))
        >>> A
        <3x4 sparse matrix of type '<class 'numpy.float64'>'
                with 3 stored elements in COOrdinate format>
        >>> A.todense()
        matrix([[ 0.,  0.,  1.,  2.],
                [ 3.,  0.,  0.,  0.],
                [ 0.,  0.,  0.,  0.]])
        >>> ss = pd.Series.sparse.from_coo(A)
        >>> ss
        0  2    1
           3    2
        1  0    3
        dtype: float64
        BlockIndex
        Block locations: array([0], dtype=int32)
        Block lengths: array([3], dtype=int32)
        """
    from pandas.core.arrays.sparse.scipy_sparse import _coo_to_sparse_series
    from pandas import Series
    result = _coo_to_sparse_series(A, dense_index=dense_index)
    result = Series(result.array, index=result.index, copy=False)
    return result


def default_true(*arg):
    """
    Auxiliar function to be used if type is not provided.

    :return: True
    """
    return True


def spooler_pid():
    """Returns first spooler process ID

    :rtype: int
    """
    return -1


def load_layer1_to_cdbg(cdbg_to_catlas, domfile):
    """Load the mapping between first layer catlas and the original DBG nodes."""
    layer1_to_cdbg = {}
    fp = open(domfile, 'rt')
    for line in fp:
        dom_node, *beneath = line.strip().split(' ')
        dom_node = int(dom_node)
        beneath = map(int, beneath)
        equiv_cdbg_to_catlas = cdbg_to_catlas[dom_node]
        layer1_to_cdbg[equiv_cdbg_to_catlas] = set(beneath)
    fp.close()
    return layer1_to_cdbg


@classmethod
def request_all_data(cls, time, pressure=None, **kwargs):
    """Retrieve upper air observations from Iowa State's archive for all stations.

        Parameters
        ----------
        time : datetime
            The date and time of the desired observation.

        pressure : float, optional
            The mandatory pressure level at which to request data (in hPa). If none is given,
            all the available data in the profiles is returned.

        kwargs
            Arbitrary keyword arguments to use to initialize source

        Returns
        -------
            :class:`pandas.DataFrame` containing the data

        """
    endpoint = cls()
    df = endpoint._get_data(time, None, pressure, **kwargs)
    return df


def update_hosted_zone_comment(Id=None, Comment=None):
    """
    Updates the comment for a specified hosted zone.
    See also: AWS API Documentation

    :example: response = client.update_hosted_zone_comment(
        Id='string',
        Comment='string'
    )

    :type Id: string
    :param Id: [REQUIRED]
            The ID for the hosted zone that you want to update the comment for.

    :type Comment: string
    :param Comment: The new comment for the hosted zone. If you don't specify a value for Comment , Amazon Route 53 deletes the existing value of the Comment element, if any.

    :rtype: dict
    :return: {
        'HostedZone': {
            'Id': 'string',
            'Name': 'string',
            'CallerReference': 'string',
            'Config': {
                'Comment': 'string',
                'PrivateZone': True|False
            },
            'ResourceRecordSetCount': 123
        }
    }

    """
    pass


def abort():
    """Abort the current transaction."""


def _set_map_int(src_dict, dst_proto, attr_name):
    """ Setter for a dictionary of integers """
    if src_dict[attr_name] is None:
        return
    for key, value in src_dict[attr_name].items():
        if value is None:
            continue
        getattr(dst_proto, attr_name)[key] = int(value)


def InLineComposition(layer):
    """ Hack to use the Adachi-alfa calculator, provinding the composition as a single string

    :param layer: A layer as defined in the Device structures of the PDD solver
    :return: A mterial string
    """
    comp = layer['properties']['composition']
    if 'element' in comp.keys():
        return comp['material'].replace(comp['element'], comp['element'] +
            str(comp['fraction']))
    else:
        return comp['material']


def nested_lookup(dictionary, *entry):
    """get a nested entry from a dictionary"""
    try:
        if isinstance(entry, str):
            v = dictionary[entry]
        else:
            v = None
            for e in entry:
                v = v[e] if v is not None else dictionary[e]
    except:
        raise Exception("could not find entry '" + '/'.join(list(entry)) +
            "' in the dictionary")
    return v


def Nu_vertical_cylinder_McAdams_Weiss_Saunders(Pr, Gr, turbulent=None):
    """Calculates Nusselt number for natural convection around a vertical
    isothermal cylinder according to the results of [1]_ and [2]_ correlated by
    [3]_, as presented in [4]_, [5]_, and [6]_.

    .. math::
        Nu_H = 0.59 Ra_H^{0.25},\\; 10^{4} < Ra < 10^{9}

    .. math::
        Nu_H = 0.13 Ra_H^{1/3.},\\; 10^{9} < Ra < 10^{12}

    Parameters
    ----------
    Pr : float
        Prandtl number [-]
    Gr : float
        Grashof number [-]
    turbulent : bool or None, optional
        Whether or not to force the correlation to return the turbulent
		 result; will return the laminar regime if False; leave as None for
        automatic selection
    Returns
    -------
    Nu : float
        Nusselt number, [-]

    Notes
    -----
    Transition between ranges is not smooth. If outside of range, no warning is
    given. For ranges under 10^4, a graph is provided, not included here.

    Examples
    --------
    >>> Nu_vertical_cylinder_McAdams_Weiss_Saunders(.7, 2E10)
    313.31849434277973

    References
    ----------
    .. [1] Weise, Rudolf. "Warmeubergang durch freie Konvektion an
       quadratischen Platten." Forschung auf dem Gebiet des Ingenieurwesens
       A 6, no. 6 (November 1935): 281-92. doi:10.1007/BF02592565.
    .. [2] Saunders, O. A. "The Effect of Pressure Upon Natural Convection in
       Air." Proceedings of the Royal Society of London A: Mathematical,
       Physical and Engineering Sciences 157, no. 891 (November 2, 1936):
       278-91. doi:10.1098/rspa.1936.0194.
    .. [3] McAdams, William Henry. Heat Transmission. 3E. Malabar, Fla:
       Krieger Pub Co, 1985.
    .. [4] Morgan, V.T., The Overall Convective Heat Transfer from Smooth
       Circular Cylinders, in Advances in Heat Transfer, eds. T.F. Irvin and
       J.P. Hartnett, V 11, 199-264, 1975.
    .. [5] Popiel, Czeslaw O. "Free Convection Heat Transfer from Vertical
       Slender Cylinders: A Review." Heat Transfer Engineering 29, no. 6
       (June 1, 2008): 521-36. doi:10.1080/01457630801891557.
    .. [6] Boetcher, Sandra K. S. "Natural Convection Heat Transfer From
       Vertical Cylinders." In Natural Convection from Circular Cylinders,
       23-42. Springer, 2014.
    """
    Ra = Pr * Gr
    if turbulent or Ra > 1000000000.0 and turbulent is None:
        return 0.13 * Ra ** (1 / 3.0)
    else:
        return 0.59 * Ra ** 0.25


def clear_caches():
    """Jinja2 keeps internal caches for environments and lexers.  These are
    used so that Jinja2 doesn't have to recreate environments and lexers all
    the time.  Normally you don't have to care about that but if you are
    measuring memory consumption you may want to clean the caches.
    """
    from nunavut.jinja.jinja2.environment import _spontaneous_environments
    from nunavut.jinja.jinja2.lexer import _lexer_cache
    _spontaneous_environments.clear()
    _lexer_cache.clear()


def snap_value(input, snap_value):
    """
    Returns snap value given an input and a base snap value
    :param input: float
    :param snap_value: float
    :return: float
    """
    return round(float(input) / snap_value) * snap_value


def multi_append(table: dict, row: dict):
    """
	Utility function for collections of parallel arrays; these often have better
	storage and encoding characteristics than arrays of records do.
	:param table: A dictionary in which several keys point to lists.
	:param row: A dictionary; the values get appended to the corresponding lists in `table`.
	:return: Nothing.
	"""
    for key, value in row.items():
        table[key].append(value)


def type_object_attrgetter(obj, attr, *defargs):
    """
    This implements an improved attrgetter for type objects (i.e. classes)
    that can handle class attributes that are implemented as properties on
    a metaclass.

    Normally `getattr` on a class with a `property` (say, "foo"), would return
    the `property` object itself.  However, if the class has a metaclass which
    *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find
    the "foo" property on the metaclass and resolve it.  For the purposes of
    autodoc we just want to document the "foo" property defined on the class,
    not on the metaclass.

    For example::

        >>> class Meta(type):
        ...     @property
        ...     def foo(cls):
        ...         return 'foo'
        ...
        >>> class MyClass(metaclass=Meta):
        ...     @property
        ...     def foo(self):
        ...         ""\"Docstring for MyClass.foo property.""\"
        ...         return 'myfoo'
        ...
        >>> getattr(MyClass, 'foo')
        'foo'
        >>> type_object_attrgetter(MyClass, 'foo')
        <property at 0x...>
        >>> type_object_attrgetter(MyClass, 'foo').__doc__
        'Docstring for MyClass.foo property.'

    The last line of the example shows the desired behavior for the purposes
    of autodoc.
    """
    for base in obj.__mro__:
        if attr in base.__dict__:
            if isinstance(base.__dict__[attr], property):
                return base.__dict__[attr]
            break
    return getattr(obj, attr, *defargs)


def _safe_int(string):
    """ Simple function to convert strings into ints without dying. """
    try:
        return int(string)
    except ValueError:
        return string


def write_vec(f, vec, name, vec_type):
    """
    Write vector to file
    """
    f.write('%s %s[%d] = {\n' % (vec_type, name, len(vec)))
    for i in range(len(vec)):
        if vec_type == 'c_float':
            f.write('(c_float)%.20f,\n' % vec[i])
        else:
            f.write('%i,\n' % vec[i])
    f.write('};\n')


def format_pvalue(pval):
    """Latex compatible representations

    """
    pval = str('%.1g' % pval)
    if 'e' in pval:
        pval += '}'
        pval = pval.replace('e', '*10^{').replace('-0', '-')
    return pval


def set_show_agenda_items(flag):
    """sets whether to show agenda items"""


def mm2px(value, dpi=300):
    """Converts the given value in millimeters into dots per inch.

    Args:
        value(float): value, in millimeters.
        dpi (int): resolution, in dots per inch.

    Returns:
        (float): value, in dots per inch.
    """
    return value * dpi / 25.4


def read_file(fo):
    """Get rows from file-like"""
    import fastavro
    with fo as f:
        return list(fastavro.iter_avro(f))


@classmethod
def _after_postgeneration(cls, instance, create, results=None):
    """Save again the instance if creating and at least one hook ran."""
    if create and results:
        instance.save()


def addColumn(pageIndex=0, columnIndex=-1, retJson=True):
    """ Add a new column.

        @param pageIndex
        index of the page( default is 0, first page )

        @param columnIndex
        index of the column( default is -1, append to the end )

        @retJson
        format return value to json format or not( default True )

        @return
        a dict contains state of process, format like:
        {
            'success': True,
            'msg': 'Add column success.'
            'columnIndex': new column index(from 0)
        }

        """


def is_comment(path):
    """Does the line start with a # symbol?"""
    return path.lstrip().startswith('#')


@classmethod
def str2tags(cls, tagstr):
    """ Takes a raw string with tags and returns a list of parsed tags.

        :param tagstr: A string with tags as entered by a user on a form.

        :returns: A list of Tag objects. If you subclass Tag, set your subclass
                  in the TAGCLASS property.
        """
    if not tagstr:
        return []
    tags, keys = [], set()
    for strtag in tagstr.split(cls.SEPARATOR):
        cls._process_tag(tags, keys, strtag)
    return tags


def set_preferred_button(target_button, button_list, pref_style):
    """ Highlight a preferred button """
    for button in button_list:
        if button == target_button:
            button.configure(style=pref_style)
            button.config(state='normal')
        else:
            button.configure(style='TButton')


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 ratio_round(a, b, r_1, r_2):
    """Find the closest pair of numbers satisfying the ratio r_1:r2 to a:b.
    """
    amult = float(a) / r_1
    bmult = float(b) / r_2
    tmult = round((amult + bmult) / 2)
    return r_1 * tmult, r_2 * tmult


def payload(remote_id, group, toggle, chan, unit):
    """generate binary payload from given values"""
    return remote_id << 6 | group << 5 | toggle << 4 | chan << 2 | unit


def deleteLink(nodeA, nodeB):
    """Delete a link between two node objects.

    This function can be empty. Used for optional complex database quieries.

    Parameters:
        nodeA (MgvNode): source node.
        nodeB (MgvNode): destination node.
    """
    return


def test_fail(message: str=None):
    """
    Forced failure of the test, can be used in rare conditions instead of checking obviously wrong conditions.
    :param message: is the optional message
    :return: None
    """
    raise AssertionError(message if message else 'Test was forcibly failed!')


def object_remove():
    """Remove Rigid Body settings from Object

    """
    pass


def main(args=None):
    """Console script for paudel_test"""


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

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


def update_user(UserName=None, NewPath=None, NewUserName=None):
    """
    Updates the name and/or the path of the specified IAM user.
    See also: AWS API Documentation

    Examples
    The following command changes the name of the IAM user Bob to Robert. It does not change the user's path.
    Expected Output:

    :example: response = client.update_user(
        UserName='string',
        NewPath='string',
        NewUserName='string'
    )

    :type UserName: string
    :param UserName: [REQUIRED]
            Name of the user to update. If you're changing the name of the user, this is the original user name.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type NewPath: string
    :param NewPath: New path for the IAM user. Include this parameter only if you're changing the user's path.
            This paramater allows (per its regex pattern ) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes, containing any ASCII character from the ! (u0021) thru the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters.

    :type NewUserName: string
    :param NewUserName: New name for the user. Include this parameter only if you're changing the user's name.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :return: response = client.update_user(
        NewUserName='Robert',
        UserName='Bob',
    )

    print(response)

    """
    pass


@staticmethod
def flatten_query_tree(query_tree):
    """
        Takes a query tree and returns the elements in list form.

        Args:
            query_tree (dict): A nested dictionary that organizes queries by domain then intent.

        Returns:
            list: A list of Query objects.
        """
    flattened = []
    for _, intent_queries in query_tree.items():
        for _, queries in intent_queries.items():
            flattened.extend(queries)
    return flattened


def wcs_coord_transform(ct, x, y):
    """Computes tha WCS corrected pixel coordinates (RA and Dec
    in degrees) given a coordinate transformation and the screen
    coordinates (x and y, in pixels).

    Input:
    ct      coordinate transformation. instance of coord_tran.
    x       x coordinate in pixels.
    y       y coordinate in pixels.

    Returns:
    (RA, Dec) in degrees (as floats).
    """
    x = float(x)
    y = float(y)
    if ct.valid:
        if abs(ct.a) > 0.001:
            ra = ct.a * x + ct.c * y + ct.tx
        if abs(ct.d) > 0.001:
            dec = ct.b * x + ct.d * y + ct.ty
    else:
        ra = x
        dec = y
    return ra, dec


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

        :param WatermarkingPolicyChangedDetails val:
        :rtype: EventDetails
        """
    return cls('watermarking_policy_changed_details', val)


def pretty_print(n):
    """Pretty print function for very big integers"""
    if not isinstance(n, int):
        return n
    ret = []
    n = str(n)
    for i in range(len(n) - 1, -1, -1):
        ret.append(n[i])
        if (len(n) - i) % 3 == 0:
            ret.append(',')
    ret.reverse()
    return ''.join(ret[1:]) if ret[0] == ',' else ''.join(ret)


def getMass(generalData):
    """Computes mass of unit cell contents

    :param dict generalData: The General dictionary in Phase

    :returns: float mass: Crystal unit cell mass in AMU.

    """
    mass = 0.0
    for i, elem in enumerate(generalData['AtomTypes']):
        mass += generalData['NoAtoms'][elem] * generalData['AtomMass'][i]
    return max(mass, 1.0)


def list_rules_in_ruleset(ruleset_db):
    """returns a list of all rule names in a ruleset"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(ruleset_db)
    cur = conn.cursor()
    list_rules = 'SELECT * FROM "Rules" ORDER BY Name'
    cur.execute(list_rules)
    conn.commit()
    rules = cur.fetchall()
    conn.close()
    return rules


def _has_desired_permit(permits, acategory, astatus):
    """
    return True if permits has one whose
    category_code and status_code match with the given ones
    """
    if permits is None:
        return False
    for permit in permits:
        if permit.category_code == acategory and permit.status_code == astatus:
            return True
    return False


@classmethod
def condition(cls, previous_value, value, has_changed=False, first_save=
    False, graph_property=None):
    """ Only save this value if it is decreasing

        :rtype: bool
        """
    if previous_value is not None:
        return value < previous_value
    else:
        return True


@classmethod
def get_computation_wallclock_time(cls, calc, **kwargs):
    """Return the computation wallclock time in seconds."""
    parameters = calc.outputs.output_parameters
    if 'wall_time_seconds' not in parameters.attrs():
        return None
    return parameters.get_attr('wall_time_seconds')


def convert_quat(q, to='xyzw'):
    """
    Converts quaternion from one convention to another.
    The convention to convert TO is specified as an optional argument.
    If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa.

    Args:
        q: a 4-dim numpy array corresponding to a quaternion
        to: a string, either 'xyzw' or 'wxyz', determining
            which convention to convert to.
    """
    if to == 'xyzw':
        return q[[1, 2, 3, 0]]
    if to == 'wxyz':
        return q[[3, 0, 1, 2]]
    raise Exception('convert_quat: choose a valid `to` argument (xyzw or wxyz)'
        )


def sizeof_fmt(num, suffix='B'):
    """ Returns bytes in human readable form. Taken from below link:
    https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size

    Args:
        num: Number (bytes) to represent in human readable form.
        suffix: Suffix required for Python format string.

    Returns:
        Human readable form of bytes provided.
    """
    for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
        if abs(num) < 1024.0:
            return '%3.1f%s%s' % (num, unit, suffix)
        num /= 1024.0
    return '%.1f%s%s' % (num, 'Yi', suffix)


def _setup(app_obj):
    """
        The _setup function is called during application initialization and
        must 'setup' the handler object making it ready for the framework
        or the application to make further calls to it.

        :param app_obj: The application object.

        """


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


def load_source(file, **kwds):
    """load an object that was stored with dill.temp.dump_source

    file: filehandle
    alias: string name of stored object
    mode: mode to open the file, one of: {'r', 'rb'}

    >>> f = lambda x: x**2
    >>> pyfile = dill.temp.dump_source(f, alias='_f')
    >>> _f = dill.temp.load_source(pyfile)
    >>> _f(4)
    16
    """
    alias = kwds.pop('alias', None)
    mode = kwds.pop('mode', 'r')
    fname = getattr(file, 'name', file)
    source = open(fname, mode=mode, **kwds).read()
    if not alias:
        tag = source.strip().splitlines()[-1].split()
        if tag[0] != '#NAME:':
            stub = source.splitlines()[0]
            raise IOError('unknown name for code: %s' % stub)
        alias = tag[-1]
    local = {}
    exec(source, local)
    _ = eval('%s' % alias, local)
    return _


def performance_ratio(E, H_poa, P_ref, G_ref=1000):
    """
    Compute performance ratio defined as:

    :math:`PR=\\dfrac{Y_{f}}{Yr} = \\dfrac{\\dfrac{E}{P_{ref}}}{\\dfrac{H_{poa}}{G_{ref}}}`

    where
    :math:`Y_f` is the observed energy (AC or DC) produced by the PV system (kWh)
    divided by the DC power rating at STC conditions.
    :math:`Y_r` is the plane-of-array insolation (kWh/m2) divided
    by the reference irradiance (1000 W/m2).

    Parameters
    -----------
    E : pandas Series or float
        Energy (AC or DC)

    H_poa : pandas Series or float
         Plane of array insolation

    P_ref : float
        DC power rating at STC conditions

    G_ref : float (optional)
        Reference irradiance, default = 1000

    Returns
    -------
    pandas Series or float
        Performance ratio in a pandas Series (if E or H_poa are Series) or
        float (if E and H_poa are floats)
    """
    Yf = E / P_ref
    Yr = H_poa / G_ref
    PR = Yf / Yr
    return PR


def binom(n, r):
    """
    Returns the binomial coefficient as a long integer.
    """
    if n < 0 or r < 0 or n < r:
        raise RuntimeError('bad binom() arguments')
    c = 1
    denom = 1
    for num, denom in zip(range(n, n - r, -1), range(1, r + 1, 1)):
        c = c * num // denom
    return c


def _generate_range(num_range):
    """Generate number for range specified like 10-12:20-30."""
    for rang in num_range.split(':'):
        boundaries = rang.split('-')
        if len(boundaries) == 2:
            try:
                if boundaries[0][0] == '0':
                    fmt = '%%0%dd' % len(boundaries[0])
                else:
                    fmt = '%d'
                start = int(boundaries[0])
                stop = int(boundaries[1]) + 1
                if stop > start:
                    step = 1
                else:
                    step = -1
                    stop = stop - 2
                for res in range(start, stop, step):
                    yield fmt % res
            except ValueError:
                yield num_range
        else:
            yield num_range


@staticmethod
def _encode_bool(bool_):
    """Encode a boolean value.

        True values because ``0x01`` and false ``0x00``.
        """
    return b'\x01' if bool_ else b'\x00'


def convert_to_int(m):
    """
    Convert the string m to an int, except if m is 'all' or None
    """
    if m == 'all' or m is None:
        return m
    else:
        return int(m)


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

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


def venn_order(input_files):
    """
    Checks the order of venn plot.

    @type input_files: list[Iterable]
    @rtype int

    input
      input_files: a list of files of genomic regions or lists

    return
      len(input_files): return length of input files
    """
    return len(input_files)


@staticmethod
def deserializeObject(value):
    """Return a original value.

        :return: object.
        """
    return value


def frobenius_product(A, B):
    """
    Returns the Frobenius scalar product <A, B> = Tr(A^\\dagger B) for two matrices.
    """
    return (A.H @ B).trace().simplify()


def splitesc_quoted(string, split_char, escape_char='\\', quote_chars='\'"'):
    """split a string at split_char, but respect (and preserve) all the
    characters inside a quote_chars pair (including escaped quote_chars and
    split_chars). split_char can also be escaped when outside of a
    quote_chars pair."""
    out = []
    i = 0
    l = len(string)
    prev = 0
    while i < l:
        is_escaped = i > 0 and string[i - 1] == escape_char
        c = string[i]
        if c in quote_chars:
            j = i + 1
            closes_quotes = False
            while j < l:
                d = string[j]
                is_escaped_j = j > 0 and string[j - 1] == escape_char
                if d == c and not is_escaped_j:
                    j += 1
                    closes_quotes = True
                    break
                j += 1
            if not closes_quotes:
                i += 1
            else:
                s = string[prev:j]
                if j < l and string[j] != split_char:
                    s += string[j]
                if s:
                    if prev > 0 and string[prev - 1] == split_char:
                        prev = j + 1
                        i = prev
                        out.append(s)
                    else:
                        prev = j + 1
                        i = prev
                        if j < l and string[j] != split_char:
                            s += string[j]
                        if out:
                            out[-1] += s
                        else:
                            out.append(s)
        elif c == split_char and not is_escaped:
            if i > 0 and i < l and i > prev:
                s = string[prev:i]
                if s:
                    out.append(s)
            prev = i + 1
            i = prev
        else:
            i += 1
    if prev < l:
        s = string[prev:l]
        if s:
            out.append(s)
    return out


@staticmethod
def binance_org_websocket(stream_data_json):
    """
        unicorn_fy binance.org (incl testnet) raw_stream_data

        :param stream_data_json: The received raw stream data from the Binance websocket
        :type stream_data_json: json

        :return: dict
        """
    return stream_data_json


def truncated(text, max_length=100, msg='...'):
    """
    >>> truncated("hello world!", 5)
    'hello...'
    >>> truncated("hello world!", 25)
    'hello world!'
    >>> truncated("hello world!", 5, " [truncated]")
    'hello [truncated]'
    """
    if len(text) < max_length:
        return text
    else:
        return text[:max_length] + msg


def merge_results(x, y):
    """
    Given two dicts, x and y, merge them into a new dict as a shallow copy.

    The result only differs from `x.update(y)` in the way that it handles list
    values when both x and y have list values for the same key. In which case
    the returned dictionary, z, has a value according to:
      z[key] = x[key] + z[key]

    :param x: The first dictionary
    :type x: :py:class:`dict`
    :param y: The second dictionary
    :type y: :py:class:`dict`
    :returns: The merged dictionary
    :rtype: :py:class:`dict`
    """
    z = x.copy()
    for key, value in y.items():
        if isinstance(value, list) and isinstance(z.get(key), list):
            z[key] += value
        else:
            z[key] = value
    return z


def dt_to_struct(s):
    """
    datetime -> time_struct

    :param s:
    :return:

    .. code-block:: python

        >>> dt = datetime.datetime.now()
        >>> print dt_to_struct(dt)
    """
    return s.timetuple()


def cancel_export_task(taskId=None):
    """
    Cancels the specified export task.
    The task must be in the PENDING or RUNNING state.
    See also: AWS API Documentation

    :example: response = client.cancel_export_task(
        taskId='string'
    )

    :type taskId: string
    :param taskId: [REQUIRED]
            The ID of the export task.

    """
    pass


@classmethod
def __cnc(cls, calib, we_c):
    """
        Compute cnc from weC
        """
    if we_c is None:
        return None
    offset_v = calib.pid_elc_mv / 1000.0
    response_c = we_c - offset_v
    cnc = response_c / calib.pid_sens_mv
    return cnc


def feature(geom, properties: dict=None, options: dict=None):
    """
    Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}
    """
    if properties is None:
        properties = {}
    if options is None:
        options = {}
    feat = {'type': 'Feature'}
    if options.get('id') is not None:
        feat['id'] = options.get('id')
    if options.get('bbox'):
        feat['bbox'] = options.get('bbox')
    feat['properties'] = properties
    feat['geometry'] = geom
    return feat


def _get_index_list_of_values(d, k, def_value=None):
    """Like _index_list_of_values, but uses get to access and
    returns an empty list if the key is absent.
    Returns d[k] or [d[k]] if the value is not a list"""
    v = d.get(k, def_value)
    if v is None:
        return []
    if isinstance(v, list):
        return v
    return [v]


def leaveGroup(addr, interface=''):
    """
        Leave multicast group, return L{Deferred} of success.
        """


def describe_create_account_status(CreateAccountRequestId=None):
    """
    Retrieves the current status of an asynchronous request to create an account.
    This operation can be called only from the organization's master account.
    See also: AWS API Documentation

    :example: response = client.describe_create_account_status(
        CreateAccountRequestId='string'
    )

    :type CreateAccountRequestId: string
    :param CreateAccountRequestId: [REQUIRED]
            Specifies the operationId that uniquely identifies the request. You can get the ID from the response to an earlier CreateAccount request, or from the ListCreateAccountStatus operation.
            The regex pattern for an create account request ID string requires 'car-' followed by from 8 to 32 lower-case letters or digits.

    :rtype: dict
    :return: {
        'CreateAccountStatus': {
            'Id': 'string',
            'AccountName': 'string',
            'State': 'IN_PROGRESS'|'SUCCEEDED'|'FAILED',
            'RequestedTimestamp': datetime(2015, 1, 1),
            'CompletedTimestamp': datetime(2015, 1, 1),
            'AccountId': 'string',
            'FailureReason': 'ACCOUNT_LIMIT_EXCEEDED'|'EMAIL_ALREADY_EXISTS'|'INVALID_ADDRESS'|'INVALID_EMAIL'|'INTERNAL_FAILURE'
        }
    }

    """
    pass


def python_3000_has_key(logical_line, noqa):
    """The {}.has_key() method is removed in Python 3: use the 'in' operator.

    Okay: if "alph" in d:\\n    print d["alph"]
    W601: assert d.has_key('alph')
    """
    pos = logical_line.find('.has_key(')
    if pos > -1 and not noqa:
        yield pos, "W601 .has_key() is deprecated, use 'in'"


@classmethod
def register(cls):
    """Register this class for easier retrieval later."""
    cls._register[cls.name] = cls


def entity_from_primary_key(pkname):
    """Given the name of a primary key, return the mapped entity.

    :param pkname: the name of a primary key
    :rtype: a mapped class
    """
    from sqlalchemy.orm.mapper import _mapper_registry
    for m in list(_mapper_registry):
        if len(m.primary_key) == 1 and m.primary_key[0].name == pkname:
            return m.class_
    raise Exception('Unknown PK: %s' % pkname)


@classmethod
def from_token(cls, token):
    """Creates a CellId from a hex encoded cell id string, called a token.

        :param str token:
            A hex representation of the cell id. If the input is shorter than
            16 characters, zeros are appended on the right.
        """
    return cls(int(token.ljust(16, '0'), 16))


def send(sender, recipient, content):
    """
        Sends the content to the recipient as the sender.
        """


def flatten(iterable):
    """Flatten a list produced by an iterable.  Non-recursive."""
    iterator, sentinel, stack = iter(iterable), object(), []
    while True:
        value = next(iterator, sentinel)
        if value is sentinel:
            if not stack:
                break
            iterator = stack.pop()
        elif isinstance(value, str):
            yield value
        else:
            try:
                new_iterator = iter(value)
            except TypeError:
                yield value
            else:
                stack.append(iterator)
                iterator = new_iterator


def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
    """Truncates a pair of sequences to a maximum sequence length."""
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_num_tokens:
            break
        trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
        assert len(trunc_tokens) >= 1
        if rng.random() < 0.5:
            del trunc_tokens[0]
        else:
            trunc_tokens.pop()


def df_cols():
    """This goes to both main.py and report.py"""
    _dc_out = ['train_peak', 'val_peak', 'train_acc', 'val_acc',
        'train_loss', 'val_loss', 'train_score', 'val_score',
        'round_epochs', 'batch_size', 'epochs', 'dropout', 'hidden_layers',
        'normalized_lr', 'first_neuron', 'loss', 'optimizer', 'activation',
        'last_activation', 'embed_dims', 'weight_regul']
    return _dc_out


def KK_RC11(w, Rs, R_values, t_values):
    """
    Kramers-Kronig Function: -RC-

    Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
    """
    return Rs + R_values[0] / (1 + w * 1.0j * t_values[0]) + R_values[1] / (
        1 + w * 1.0j * t_values[1]) + R_values[2] / (1 + w * 1.0j * t_values[2]
        ) + R_values[3] / (1 + w * 1.0j * t_values[3]) + R_values[4] / (1 +
        w * 1.0j * t_values[4]) + R_values[5] / (1 + w * 1.0j * t_values[5]
        ) + R_values[6] / (1 + w * 1.0j * t_values[6]) + R_values[7] / (1 +
        w * 1.0j * t_values[7]) + R_values[8] / (1 + w * 1.0j * t_values[8]
        ) + R_values[9] / (1 + w * 1.0j * t_values[9]) + R_values[10] / (1 +
        w * 1.0j * t_values[10])


@staticmethod
def mime_from_blob(blob):
    """
        Calculates the mime type from the given blob
        :return:
        """
    import magic
    return magic.from_buffer(blob, mime=True)


def _to_list(objs):
    """Makes a list of objs"""
    if objs is None:
        return []
    elif not isinstance(objs, list):
        return [objs]
    else:
        return objs


def convert_decimal_to_degrees(decimal):
    """
    Convert decimal degrees to degree-minute-second format.

    Example:
        >>> convert_decimal_to_degrees(30.56)
        (30, 33, 36)

    Args:
        Decimal: degree in decimals
    Returns:
        Tuple of degree-minute-second.
    """
    degrees = int(decimal)
    minutes = int((decimal - degrees) * 60)
    seconds = round((decimal - degrees - minutes / 60.0) * 3600, 4)
    return degrees, minutes, seconds


@staticmethod
def p_qp_data(p):
    """qp_data : generic_parameter"""
    p[0] = p[1]


def indicates_division(token):
    """A helper function that helps the tokenizer to decide if the current
    token may be followed by a division operator.
    """
    if token.type == 'operator':
        return token.value in (')', ']', '}', '++', '--')
    return token.type in ('name', 'number', 'string', 'regexp')


def authGSSClientStep(context, challenge, **kwargs):
    """
    Processes a single GSSAPI client-side step using the supplied server data.

    @param context: the context object returned from authGSSClientInit.
    @param challenge: a string containing the base64-encoded server data (which may be empty
        for the first step).
    @param channel_bindings: Optional channel bindings to bind onto the auth request. This
        struct can be built using the channelBindings function and it not specified, this process
        will pass along GSS_C_NO_CHANNEL_BINDINGS as a default
    @return: a result code (see above).
    """


def type_object_attrgetter(obj, attr, *defargs):
    """
    This implements an improved attrgetter for type objects (i.e. classes)
    that can handle class attributes that are implemented as properties on
    a metaclass.

    Normally `getattr` on a class with a `property` (say, "foo"), would return
    the `property` object itself.  However, if the class has a metaclass which
    *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find
    the "foo" property on the metaclass and resolve it.  For the purposes of
    autodoc we just want to document the "foo" property defined on the class,
    not on the metaclass.

    For example::

        >>> class Meta(type):
        ...     @property
        ...     def foo(cls):
        ...         return 'foo'
        ...
        >>> class MyClass(metaclass=Meta):
        ...     @property
        ...     def foo(self):
        ...         ""\"Docstring for MyClass.foo property.""\"
        ...         return 'myfoo'
        ...
        >>> getattr(MyClass, 'foo')
        'foo'
        >>> type_object_attrgetter(MyClass, 'foo')
        <property at 0x...>
        >>> type_object_attrgetter(MyClass, 'foo').__doc__
        'Docstring for MyClass.foo property.'

    The last line of the example shows the desired behavior for the purposes
    of autodoc.
    """
    for base in obj.__mro__:
        if attr in base.__dict__:
            if isinstance(base.__dict__[attr], property):
                return base.__dict__[attr]
            break
    return getattr(obj, attr, *defargs)


def _trips_definitions(df):
    """
    Append GTFS definitions for trip columns to trip dataframe

    Parameters
    ----------
    df : pandas:DataFrame
        trip dataframe

    Returns
    -------
    df : pandas.DataFrame
    """
    if 'bikes_allowed' in df.columns:
        trips_bikes_allowed = {(1): 'can accommodate at least one bicycle',
            (2): 'no bicycles are allowed on this trip'}
        df['bikes_allowed_desc'] = df['bikes_allowed'].map(trips_bikes_allowed
            .get)
    if 'wheelchair_accessible' in df.columns:
        trips_wheelchair_accessible = {(1):
            'can accommodate at least one rider in a wheelchair', (2):
            'no riders in wheelchairs can be accommodated on this trip'}
        df['wheelchair_accessible_desc'] = df['wheelchair_accessible'].map(
            trips_wheelchair_accessible.get)
    return df


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


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

        :param NoPasswordLinkViewCreateReportType val:
        :rtype: EventType
        """
    return cls('no_password_link_view_create_report', val)


def _asmStopCrit(matchIndices, nSamples, window=0.1, threshold=0.95):
    """ returns true if thresh proportion of xpads are in the middle
    window proportion of pLength
    """
    n0 = nSamples / 2.0 - nSamples * window
    n1 = nSamples / 2.0 + nSamples * window
    passes = ((n0 <= matchIndices) & (matchIndices <= n1)).sum()
    passFrac = float(passes) / len(matchIndices)
    if passFrac > threshold:
        return True, passFrac
    else:
        return False, passFrac


def _convert_bool(boolean):
    """Convert to stringified boolean"""
    return str(boolean).lower()


def is_classifier(estimator):
    """Returns True if the given estimator is (probably) a classifier."""
    return getattr(estimator, '_estimator_type', None) == 'classifier'


def dlopen(ffi, *names):
    """Try various names for the same library, for different platforms."""
    for name in names:
        try:
            return ffi.dlopen(name)
        except OSError:
            pass
    return ffi.dlopen(names[0])


def dispatch_cuda(cuda_class, cpu_func, x):
    """Depending on `x.device` uses `cpu_func` or `cuda_class.apply`"""
    return cuda_class.apply if x.device.type == 'cuda' else cpu_func


def get_maxrate(ratelimits, size):
    """
    Returns number of requests allowed per second for given size.
    """
    last_func = None
    if size:
        size = int(size)
        for ratesize, rate, func in ratelimits:
            if size < ratesize:
                break
            last_func = func
        if last_func:
            return last_func(size)
    return None


def get_ident():
    """Dummy implementation of _thread.get_ident().

    Since this module should only be used when _threadmodule is not
    available, it is safe to assume that the current process is the
    only thread.  Thus a constant can be safely returned.
    """
    return 1


@classmethod
def unpack_scalar(cls, dataset, data):
    """
        Given a dataset object and data in the appropriate format for
        the interface, return a simple scalar.
        """
    if data.shape == (1, 1):
        return data[0, 0]
    return data


def get_globus_id_type(uuid):
    """**Not implemented**
    Determine the type of resource a Globus UUID identifies.
    This utility is not comprehensive.

    Arguments:
        uuid (str): A Globus UUID.

    Returns:
        str: The type of resource identified. Types this utility can identify:

                * ``identity``: A user's identity in Globus Auth
                * ``group``: A Globus Group
                * ``endpoint``: A Globus Transfer Endpoint

                This utility cannot detect other types of UUID.
                If the UUID is not one of the above types, or is invalid, the return
                value will be ``unknown``.
    """
    raise NotImplementedError('get_globus_id_type currently not functional')


def other():
    """
    Note to contributors:
        Alternative multifrequency masking methods must be named with
        the author or method name. If already published, the full citation must
        be provided.

        Please, check /DESIGN.md to adhere to our coding style.
    """


def get_short_title_editable():
    """Get the short title of the editable version if possible.
        """


def safe_str(obj, newline='\\n'):
    """This function eliminates newlines and replaces them with the explicit character newline string
    passed.  Defaults to the showing '
' explicitly"""
    return str(obj).replace('\n', newline)


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


def intent_not_recognized(method):
    """Apply this decorator to a method of class :class:`.HermesSnipsComponent`
    to register it as a callback to be triggered when the dialogue manager
    doesn't recognize an intent.
    """
    method.subscribe_method = 'subscribe_intent_not_recognized'
    return method


def class_filter(instances, **filters):
    """
    Search for class instances by their attributes
    """
    found_instances = []
    for instance in instances:
        for filter_key, filter_value in filters.items():
            if not filter_value:
                continue
            looking_for = getattr(instance, filter_key)
            if isinstance(filter_value, str):
                if looking_for != filter_value:
                    break
            elif looking_for not in filter_value:
                break
        else:
            found_instances.append(instance)
    return len(found_instances), found_instances


def to_camel_case(name):
    """
    Turn a snake_case name into camelCase.
    """
    output = name.title().replace('_', '')
    return output[0].lower() + output[1:]


def write_to_file(report):
    """
    Start a new page and save current report_info to a file.
    :param report: dictionary holding report information
    """
    report['canvas'].showPage()
    report['canvas'].save()


def CRRAutilityP_inv(uP, gam):
    """
    Evaluates the inverse of the CRRA marginal utility function (with risk aversion
    parameter gam) at a given marginal utility level uP.

    Parameters
    ----------
    uP : float
        Marginal utility value
    gam : float
        Risk aversion

    Returns
    -------
    (unnamed) : float
        Consumption corresponding to given marginal utility value.
    """
    return uP ** (-1.0 / gam)


def rl_fixorder(strings):
    """ fix implicit sorting of readline.

        if the strings are not accidentally sorted
        then fix the current 'strings' order.
    """
    num = len(strings)
    for s1, s2 in zip(strings, strings[1:]):
        if s1 >= s2:
            digits = num <= 10 and '%d ' or '%02d '
            for i in range(num):
                strings[i] = digits % i + strings[i]
            break


def pad_line(line):
    """Helper function to pad line to 80 characters in case it is shorter"""
    size_of_line = len(line)
    if size_of_line < 80:
        padding = 80 - size_of_line + 1
        line = line.strip('\n') + ' ' * padding + '\n'
    return line[:81]


def fil_parse_status(all_status):
    """return generator with {'value': status, 'path': file}"""
    for status in all_status:
        splited = status.split(' ')
        value = splited[0]
        path = splited[1:]
        yield {'value': value, 'path': path}


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

    :param pd.Dataframe dataframe: Dataframe containing twitter data

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

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


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

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


def sinh(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns the hyperbolic sine of the input array, computed element-wise.

    .. math::
       sinh(x) = 0.5\\times(exp(x) - exp(-x))

    The storage type of ``sinh`` output depends upon the input storage type:

       - sinh(default) = default
       - sinh(row_sparse) = row_sparse
       - sinh(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L313

    Parameters
    ----------
    data : Symbol
        The input array.

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

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


def _operation_to_pooling_shape(operation):
    """Takes in the operation string and returns the pooling kernel shape."""
    splitted_operation = operation.split('_')
    shape = splitted_operation[-1]
    assert 'x' in shape
    filter_height, filter_width = shape.split('x')
    assert filter_height == filter_width
    return int(filter_height)


def capitalize(string):
    """
    Capitalizes the first letter of a string.
    """
    return string[0].upper() + string[1:]


def isAudio():
    """ Is this media audio? """


def p_data_type(p):
    """data_type : type
               | type LPAREN NUMBER RPAREN
  """
    if len(p) != 2:
        data_type = p[1]
        data_type.length = p[3]
    p[0] = p[1]


@classmethod
def from_any(cls, stylespec: str):
    """Returns a configured StyleBook. First it attempts to load
        a StyleBook from stylespec interpreted as a filesystem path.
        If no file is found, the method next tries to load a StyleBook
        using stylespec is a style name (see `available_styles`).

        If both of those fail, ValueError is raised.

        :param str stylespec: path or style name
        """
    try:
        return cls.from_filename(stylespec)
    except FileNotFoundError:
        pass
    try:
        return cls.by_name(stylespec)
    except FileNotFoundError:
        pass
    raise ValueError(f"unable to find a style matching '{stylespec}'")


def generate_kml(tx, ty, tz, tileext, tile_size, tileswne, options,
    children=None, **args):
    """
    Template for the KML. Returns filled string.
    """
    if not children:
        children = []
    args['tx'], args['ty'], args['tz'] = tx, ty, tz
    args['tileformat'] = tileext
    if 'tile_size' not in args:
        args['tile_size'] = tile_size
    if 'minlodpixels' not in args:
        args['minlodpixels'] = int(args['tile_size'] / 2)
    if 'maxlodpixels' not in args:
        args['maxlodpixels'] = int(args['tile_size'] * 8)
    if children == []:
        args['maxlodpixels'] = -1
    if tx is None:
        tilekml = False
        args['title'] = options.title
    else:
        tilekml = True
        args['title'] = '%d/%d/%d.kml' % (tz, tx, ty)
        args['south'], args['west'], args['north'], args['east'] = tileswne(tx,
            ty, tz)
    if tx == 0:
        args['drawOrder'] = 2 * tz + 1
    elif tx is not None:
        args['drawOrder'] = 2 * tz
    else:
        args['drawOrder'] = 0
    url = options.url
    if not url:
        if tilekml:
            url = '../../'
        else:
            url = ''
    s = (
        """<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>%(title)s</name>
    <description></description>
    <Style>
      <ListStyle id="hideChildren">
        <listItemType>checkHideChildren</listItemType>
      </ListStyle>
    </Style>"""
         % args)
    if tilekml:
        s += (
            """
    <Region>
      <LatLonAltBox>
        <north>%(north).14f</north>
        <south>%(south).14f</south>
        <east>%(east).14f</east>
        <west>%(west).14f</west>
      </LatLonAltBox>
      <Lod>
        <minLodPixels>%(minlodpixels)d</minLodPixels>
        <maxLodPixels>%(maxlodpixels)d</maxLodPixels>
      </Lod>
    </Region>
    <GroundOverlay>
      <drawOrder>%(drawOrder)d</drawOrder>
      <Icon>
        <href>%(ty)d.%(tileformat)s</href>
      </Icon>
      <LatLonBox>
        <north>%(north).14f</north>
        <south>%(south).14f</south>
        <east>%(east).14f</east>
        <west>%(west).14f</west>
      </LatLonBox>
    </GroundOverlay>
"""
             % args)
    for cx, cy, cz in children:
        csouth, cwest, cnorth, ceast = tileswne(cx, cy, cz)
        s += (
            """
    <NetworkLink>
      <name>%d/%d/%d.%s</name>
      <Region>
        <LatLonAltBox>
          <north>%.14f</north>
          <south>%.14f</south>
          <east>%.14f</east>
          <west>%.14f</west>
        </LatLonAltBox>
        <Lod>
          <minLodPixels>%d</minLodPixels>
          <maxLodPixels>-1</maxLodPixels>
        </Lod>
      </Region>
      <Link>
        <href>%s%d/%d/%d.kml</href>
        <viewRefreshMode>onRegion</viewRefreshMode>
        <viewFormat/>
      </Link>
    </NetworkLink>
        """
             % (cz, cx, cy, args['tileformat'], cnorth, csouth, ceast,
            cwest, args['minlodpixels'], url, cz, cx, cy))
    s += '      </Document>\n</kml>\n    '
    return s


def is_integer(val):
    """Returns whether the given value is an integer.

    Args:
      val (object): value to check

    Returns:
      ``True`` if the given value is an integer, otherwise ``False``.
    """
    try:
        val += 1
    except TypeError:
        return False
    return True


def ensure_one(found):
    """
    确保列表中仅有一个项，并返回这个项，否则抛出 `ValueError` 异常

    通常可用在查找聊天对象时，确保查找结果的唯一性，并直接获取唯一项

    :param found: 列表
    :return: 唯一项
    """
    if not isinstance(found, list):
        raise TypeError('expected list, {} found'.format(type(found)))
    elif not found:
        raise ValueError('not found')
    elif len(found) > 1:
        raise ValueError('more than one found')
    else:
        return found[0]


def simple_format(num):
    """Takes a number and returns the simplest format for the number removing
    all trailing 0's and the '.' if it's the trailing character.

    >>> simple_format(123)
    '123'
    >>> simple_format(123.0)
    '123'
    >>> simple_format(123.01100)
    '123.011'
    """
    return ('%f' % num).rstrip('0').rstrip('.')


def means(vectors):
    """ Computes the means between this and the next point.

    Parameters
    ----------
    vectors : ndarray
        An array of vectors or scalars.

    Returns
    -------
    ndarray
        An array of vectors or scalars of shape (n-1,...),
        when vectors input have shape (n,...).

    Examples
    --------
    >>> from pyfac.utils import *  # doctest: +SKIP
    >>> means(np.array(list(range(5))))
    array([0.5, 1.5, 2.5, 3.5])
    >>> means(np.array([4, 3, 7, 4, 2, 92]))
    array([ 3.5,  5. ,  5.5,  3. , 47. ])
    >>> means(np.array([[1, 0, 0], [0, 1, 3], [7, -13, 4]]))
    array([[ 0.5,  0.5,  1.5],
           [ 3.5, -6. ,  3.5]])
    """
    return (vectors[1:] + vectors[:-1]) * 0.5


def grouped_impl(wrap, size, sequence):
    """
    Implementation for grouped_t
    :param wrap: wrap children values with this
    :param size: size of groups
    :param sequence: sequence to group
    :return: grouped sequence
    """
    for i in range(0, len(sequence), size):
        yield wrap(sequence[i:i + size])


def evolve(connection):
    """Execute any ALTER TABLE etc. statements needed to bring the
    database up-to-date."""
    pass


def query_utility(interface, name='', default=None, context=None):
    """Look for the utility that provides interface

        Returns the nearest utility to the context that implements
        the specified interface.  If one is not found, returns default.
        """


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 execute(need_active: bool=False):
    """Execute selected file

    :param need_active: Need Active, Only execute if there’s an active selected file in the file list
    :type need_active: bool
    """
    pass


def _get_log_time_scale(units):
    """Retrieves the ``log10()`` of the scale factor for a given time unit.

    Args:
        units (str): String specifying the units
            (one of ``'fs'``, ``'ps'``, ``'ns'``, ``'us'``, ``'ms'``, ``'sec'``).

    Returns:
        The the ``log10()`` of the scale factor for the time unit.
    """
    scale = {'fs': -15, 'ps': -12, 'ns': -9, 'us': -6, 'ms': -3, 'sec': 0}
    units_lwr = units.lower()
    if units_lwr not in scale:
        raise ValueError('Invalid unit ({0}) provided'.format(units))
    else:
        return scale[units_lwr]


def list_incoming_typed_links(DirectoryArn=None, ObjectReference=None,
    FilterAttributeRanges=None, FilterTypedLink=None, NextToken=None,
    MaxResults=None, ConsistencyLevel=None):
    """
    Returns a paginated list of all the incoming  TypedLinkSpecifier information for an object. It also supports filtering by typed link facet and identity attributes. For more information, see Typed link .
    See also: AWS API Documentation

    :example: response = client.list_incoming_typed_links(
        DirectoryArn='string',
        ObjectReference={
            'Selector': 'string'
        },
        FilterAttributeRanges=[
            {
                'AttributeName': 'string',
                'Range': {
                    'StartMode': 'FIRST'|'LAST'|'LAST_BEFORE_MISSING_VALUES'|'INCLUSIVE'|'EXCLUSIVE',
                    'StartValue': {
                        'StringValue': 'string',
                        'BinaryValue': b'bytes',
                        'BooleanValue': True|False,
                        'NumberValue': 'string',
                        'DatetimeValue': datetime(2015, 1, 1)
                    },
                    'EndMode': 'FIRST'|'LAST'|'LAST_BEFORE_MISSING_VALUES'|'INCLUSIVE'|'EXCLUSIVE',
                    'EndValue': {
                        'StringValue': 'string',
                        'BinaryValue': b'bytes',
                        'BooleanValue': True|False,
                        'NumberValue': 'string',
                        'DatetimeValue': datetime(2015, 1, 1)
                    }
                }
            },
        ],
        FilterTypedLink={
            'SchemaArn': 'string',
            'TypedLinkName': 'string'
        },
        NextToken='string',
        MaxResults=123,
        ConsistencyLevel='SERIALIZABLE'|'EVENTUAL'
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the directory where you want to list the typed links.

    :type ObjectReference: dict
    :param ObjectReference: [REQUIRED]
            Reference that identifies the object whose attributes will be listed.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

    :type FilterAttributeRanges: list
    :param FilterAttributeRanges: Provides range filters for multiple attributes. When providing ranges to typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range.
            (dict) --Identifies the range of attributes that are used by a specified filter.
            AttributeName (string) --The unique name of the typed link attribute.
            Range (dict) -- [REQUIRED]The range of attribute values that are being selected.
            StartMode (string) -- [REQUIRED]The inclusive or exclusive range start.
            StartValue (dict) --The value to start the range at.
            StringValue (string) --A string data value.
            BinaryValue (bytes) --A binary data value.
            BooleanValue (boolean) --A Boolean data value.
            NumberValue (string) --A number data value.
            DatetimeValue (datetime) --A date and time value.
            EndMode (string) -- [REQUIRED]The inclusive or exclusive range end.
            EndValue (dict) --The attribute value to terminate the range at.
            StringValue (string) --A string data value.
            BinaryValue (bytes) --A binary data value.
            BooleanValue (boolean) --A Boolean data value.
            NumberValue (string) --A number data value.
            DatetimeValue (datetime) --A date and time value.

    :type FilterTypedLink: dict
    :param FilterTypedLink: Filters are interpreted in the order of the attributes on the typed link facet, not the order in which they are supplied to any API calls.
            SchemaArn (string) -- [REQUIRED]The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns .
            TypedLinkName (string) -- [REQUIRED]The unique name of the typed link facet.

    :type NextToken: string
    :param NextToken: The pagination token.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to retrieve.

    :type ConsistencyLevel: string
    :param ConsistencyLevel: The consistency level to execute the request at.

    :rtype: dict
    :return: {
        'LinkSpecifiers': [
            {
                'TypedLinkFacet': {
                    'SchemaArn': 'string',
                    'TypedLinkName': 'string'
                },
                'SourceObjectReference': {
                    'Selector': 'string'
                },
                'TargetObjectReference': {
                    'Selector': 'string'
                },
                'IdentityAttributeValues': [
                    {
                        'AttributeName': 'string',
                        'Value': {
                            'StringValue': 'string',
                            'BinaryValue': b'bytes',
                            'BooleanValue': True|False,
                            'NumberValue': 'string',
                            'DatetimeValue': datetime(2015, 1, 1)
                        }
                    },
                ]
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An objects identifier is immutable and no two objects will ever share the same object identifier
    /some/path - Identifies the object based on path
    #SomeBatchReference - Identifies the object in a batch call

    """
    pass


def lint_repeats(tool_xml, lint_ctx):
    """Lint repeat blocks in tool inputs."""
    repeats = tool_xml.findall('./inputs//repeat')
    for repeat in repeats:
        if 'name' not in repeat.attrib:
            lint_ctx.error('Repeat does not specify name attribute.')
        if 'title' not in repeat.attrib:
            lint_ctx.error('Repeat does not specify title attribute.')


def cb_isCopyable():
    """Is object copyable? Returns 0 or 1
        """


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

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


@staticmethod
def _get_targets(*, context, previous_rcs):
    """Get targets for the tool."""
    targets_used = []
    for path, return_code in list(previous_rcs.items()):
        if return_code != 0:
            targets_used.append(path)
    if '{affected_targets}' in context['config']:
        targets_used += context['affected files']
    return list(set(targets_used))


def merge_sequentials_containing_ints(*args):
    """takes a bunch of sequential data (of the same type and structured as
    <key,value>) and merges them together by adding (not concatenating) their
    values. data should be structured homogeneously.
    WARNING: duplicate items within an argument are also merged. strings not
    allowed."""
    if not len(args):
        return ()
    if isinstance(args[0], str):
        raise ValueError("Strings are't allowed.")
    res = {}
    for arg in args:
        for key, val in arg:
            res[key] = val + res.get(key, 0)
    return tuple(res.items())


def handle_device_status_change(payload):
    """ Handles changes in device status such as battery or network """
    return


@staticmethod
def _get_displaced_neighbors(lookup_idx, nbhd, nbhd_size, max_size):
    """
		Find the indices in _lookup_table that supposedly relate to a key that
		originally mapped to the given index, but were displaced during some
		previous _free_up call

		:param lookup_idx: The index in _lookup_table to find displaced neighbors for
		:param nbhd: The neighborhood at lookup_idx
		:param nbhd_size: The size of the given neighborhood
		:param max_size: The current maximum size of the dict

		:return: (list) Indices in _lookup_table that supposedly have data that would
						be stored at lookup_idx were it empty at the time of insertion
		"""
    if lookup_idx < 0:
        raise ValueError(u'Indexes cannot be negative')
    elif lookup_idx >= max_size:
        raise ValueError(u'Index {0} outside array'.format(lookup_idx))
    result = []
    for i in range(nbhd_size):
        if nbhd & 1 << i > 0:
            result.append((lookup_idx + i) % max_size)
    return result


def dot_vectors_xy(u, v):
    """Compute the dot product of two vectors, assuming they lie in the XY-plane.

    Parameters
    ----------
    u : sequence of float
        XY(Z) coordinates of the first vector.
    v : sequence of float
        XY(Z) coordinates of the second vector.

    Returns
    -------
    float
        The dot product of the XY components of the two vectors.

    Examples
    --------
    >>> dot_vectors_xy([1.0, 0], [2.0, 0])
    2.0

    >>> dot_vectors_xy([1.0, 0, 0], [2.0, 0, 0])
    2.0

    >>> dot_vectors_xy([1.0, 0, 1], [2.0, 0, 1])
    2.0

    """
    return u[0] * v[0] + u[1] * v[1]


def _do_get_storage_connectors(featurestore_metadata):
    """
    Gets a list of all storage connectors and their type in a featurestore

    Args:
        :featurestore_metadata: metadata of the featurestore

    Returns:
        A list of names of the storage connectors in this featurestore and their type
    """
    return list(map(lambda sc: (sc.name, sc.type), featurestore_metadata.
        storage_connectors.values()))


@staticmethod
def _create_message(result=None, *args, **kwargs):
    """
        Формирует сообщение для записи в лог
        :param result: результат работы функции
        :param args: любые параметры по порядку
        :param kwargs: любые именованные параметры
        :return:
        """
    message = ''
    if args:
        message += 'args: {} '.format(args)
    if kwargs:
        message += 'kwargs: {} '.format(kwargs)
    if result:
        message += '= {}'.format(result)
    return message


def foreground_acc(input, target, void_code):
    """Computes non-background accuracy, e.g. camvid for multiclass segmentation"""
    target = target.squeeze(1)
    mask = target != void_code
    return (input.argmax(dim=1)[mask] == target[mask]).float().mean()


@staticmethod
def status(s):
    """Prints things in bold."""
    print(f'\x1b[1m{s}\x1b[0m')


def delete(message):
    """Remove the given message from the source."""


def format_mail(mail):
    """
    Format the mail address to fit gmail's rfc interpretation
    """
    return u'<{0}>'.format(mail)