@classmethod
def _find_coeff_for_title_hight(cls, title):
    """Find title hight.

        Count coefficient for annotations coordinate depend on scale.
        """
    if title.split(' ')[1] in ['добыча,', 'масса']:
        coef = 5
    else:
        coef = 0.1
    return coef


def _test3():
    """
    >>> vtor.check('string(default="")', '', missing=True)
    ''
    >>> vtor.check('string(default="\\n")', '', missing=True)
    '\\n'
    >>> print(vtor.check('string(default="\\n")', '', missing=True))
    <BLANKLINE>
    <BLANKLINE>
    >>> vtor.check('string()', '\\n')
    '\\n'
    >>> vtor.check('string(default="\\n\\n\\n")', '', missing=True)
    '\\n\\n\\n'
    >>> vtor.check('string()', 'random \\n text goes here\\n\\n')
    'random \\n text goes here\\n\\n'
    >>> vtor.check('string(default=" \\nrandom text\\ngoes \\n here\\n\\n ")',
    ... '', missing=True)
    ' \\nrandom text\\ngoes \\n here\\n\\n '
    >>> vtor.check("string(default='\\n\\n\\n')", '', missing=True)
    '\\n\\n\\n'
    >>> vtor.check("option('\\n','a','b',default='\\n')", '', missing=True)
    '\\n'
    >>> vtor.check("string_list()", ['foo', '\\n', 'bar'])
    ['foo', '\\n', 'bar']
    >>> vtor.check("string_list(default=list('\\n'))", '', missing=True)
    ['\\n']
    """


def hide_fields_in_newer_versions(obj):
    """This method hides fields that were added in newer API versions.

    Certain node fields were introduced at certain API versions.
    These fields are only made available when the request's API version
    matches or exceeds the versions when these fields were introduced.
    """
    pass


def parse_quantity(q):
    """
    Parse an Onshape units definition
    Args:
        q:an Onshape units definition... for instance:
            {
              'typeTag': '',
              'unitToPower': [
                {
                  'key': 'METER',
                  'value': 1
                }
              ],
              'value': 0.0868175271040671
            }

    Returns:
        a string that can be converted to any other unit engine.

    >>> from onshape_client.utility import parse_quantity
    >>> d = {'value': 0.1414213562373095, 'unitToPower': [{'value': 1, 'key': 'METER'}], 'typeTag': ''}
    >>> parse_quantity(d)
    '0.1414213562373095*meter'

    >>> d = {'value': 0.1414213562373095, 'unitToPower': [{'value': 3, 'key': 'MILLIMETER'}], 'typeTag': ''}
    >>> parse_quantity(d)
    '0.1414213562373095*millimeter**3'
    """
    units_s = str(q['value'])
    for u in q['unitToPower']:
        units_s = units_s + '*' + u['key'].lower()
        power = u['value']
        if not power == 1:
            units_s = units_s + '**' + str(power)
    return units_s


def leq(first=None, second=None):
    """ Checks if first element is less than or equals the second """
    if first is None or second is None:
        return True
    return first <= second


def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'personality':
        'A string which is generally based on the platform and indicates the behavior of the device.'
        , 'virtual': 'A boolean indicating if the device is virtual.'}


def list_repositories(nextToken=None, sortBy=None, order=None):
    """
    Gets information about one or more repositories.
    See also: AWS API Documentation

    :example: response = client.list_repositories(
        nextToken='string',
        sortBy='repositoryName'|'lastModifiedDate',
        order='ascending'|'descending'
    )

    :type nextToken: string
    :param nextToken: An enumeration token that allows the operation to batch the results of the operation. Batch sizes are 1,000 for list repository operations. When the client sends the token back to AWS CodeCommit, another page of 1,000 records is retrieved.

    :type sortBy: string
    :param sortBy: The criteria used to sort the results of a list repositories operation.

    :type order: string
    :param order: The order in which to sort the results of a list repositories operation.

    :rtype: dict
    :return: {
        'repositories': [
            {
                'repositoryName': 'string',
                'repositoryId': 'string'
            },
        ],
        'nextToken': 'string'
    }

    """
    pass


@staticmethod
def _reduce_datetimes(row):
    """Receives a row, converts datetimes to strings."""
    row = list(row)
    for i, val in enumerate(row):
        if hasattr(val, 'strftime'):
            row[i] = val.strftime('%Y-%m-%d %H:%M:%S')
        elif hasattr(val, 'isoformat'):
            row[i] = val.isoformat()
    return row


def crossing_orientations(strands):
    """
    Given the strands, compute the orientations (+1 or -1) for each crossing
    in the tangle
    """
    orientations = {}
    over_or_under = {}
    css_seen = []
    for strand in strands:
        for cs in strand:
            for seen_cs in css_seen:
                if cs[0] == seen_cs[0]:
                    orientation = (cs[1] - seen_cs[1]) % 4
                    if orientation == 3:
                        orientation = -1
                    orientations[cs[0]] = orientation
                    over_or_under[cs[0]] = cs[1] % 2
                    break
            css_seen.append(cs)
    return orientations, over_or_under


@classmethod
def _build_hash(cls):
    """Clear hash and rebuild hash by rules"""
    raise NotImplementedError()


def vertex_parent_set():
    """Parent selected objects to the selected vertices

    """
    pass


def pairwise(iterable):
    """ Return a generator which generate a pair wise list from an iterable.
    s -> (s[0],s[1]), (s[1],s[2]), ... (s[N-1],s[N])
    """
    prev = iterable[0]
    for x in iterable[1:]:
        yield prev, x
        prev = x


def toCurrent(remote):
    """Tranform an URL to a compatible type, like the current ones"""


def eigenvalue_ratio_2D(eigenvalues):
    """Compute the 2D eigenvalue ratio

    Parameters
    ----------
    eigenvalues : numpy.array
        Array of eigenvalues; must be (1, 2)-shaped
    """
    return eigenvalues[1] / eigenvalues[0]


def choice_formatter(view, choice):
    """
        Return label of selected choice
        see https://sqlalchemy-utils.readthedocs.io/

        :param choice:
            sqlalchemy_utils Choice, which has a `code` and a `value`
    """
    return choice.value


@classmethod
def from_dict(cls, d):
    """
        Construct a new `Search` instance from a raw dict containing the search
        body. Useful when migrating from raw dictionaries.

        Example::

            s = Search.from_dict({
                "query": {
                    "bool": {
                        "must": [...]
                    }
                },
                "aggs": {...}
            })
            s = s.filter('term', published=True)
        """
    s = cls()
    s.update_from_dict(d)
    return s


def lower(value):
    """
    Convert value to lowercase if possible

    For example::

        >>> print(lower('HELLO'))
        hello
        >>> print(lower(5))
        5
    """
    try:
        return value.lower()
    except AttributeError:
        return value


@staticmethod
def gen_email_token_key(email_token):
    """
        生成email_token的key
        """
    return f'email:reset_password:{email_token}'


def simplify(units):
    """
    Cancel units that appear in both numerator and denominator, then attempt to replace
    groups of units with single units where possible (ie, J/s => W)
    """
    pass


def xml_station_information_wrapper(xmlnode):
    """Convert Station information xml
    to a usable dict"""
    city = ''
    postal_code = ''
    address = xmlnode.getAttribute('address')[:-1].strip()
    address_parts = xmlnode.getAttribute('fullAddress').split()
    for p in address_parts:
        if len(p) == 5 and p.isdigit():
            postal_code = p
            city = ' '.join(address_parts[address_parts.index(p) + 1:])
            break
    return {'id': int(xmlnode.getAttribute('number')), 'address': address,
        'postal_code': postal_code, 'city': city, 'lat': xmlnode.
        getAttribute('lat'), 'lng': xmlnode.getAttribute('lng'), 'opened':
        xmlnode.getAttribute('open') == '1', 'bonus': xmlnode.getAttribute(
        'bonus') == '1'}


def interspace(sep, seq):
    """
    Return an iterator that interspace items in seq with the given separator.

    >>> list(interspace(0, [1, 2, 3]))
    [1, 0, 2, 0, 3]
    """
    it = iter(seq)
    try:
        yield next(it)
    except StopIteration:
        pass
    else:
        for item in it:
            yield sep
            yield item


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 parse_integer(element):
    """parser of vRa data integer type

    Args:
        element (dict): vRa data

    Returns:
        tuple: key,value of vRa data
    """
    return element['key'], int(element['value']['value'])


def _insert_single_package_eups_version(c, eups_version):
    """Insert version information into the configuration namespace.

    Parameters
    ----------
    eups_version
        The EUPS version string (as opposed to tag). This comes from the
        ``__version__`` attribute of individual modules and is only set for
        single package documentation builds that use the
        `build_package_configs` configuration entrypoint.

    Notes
    -----
    The variables are:

    ``release_eups_tag``
        Always ``current``.
    ``version``, ``release``
        Equal to ``eups_version``.
    ``release_git_ref``
        Always ``master``.
    ``scipipe_conda_ref``
        Always ``master``.
    ``newinstall_ref``
        Always ``master``.
    ``pipelines_demo_ref``
        Always ``master``.
    """
    c['release_eups_tag'] = 'current'
    c['release_git_ref'] = 'master'
    c['version'] = eups_version
    c['release'] = eups_version
    c['scipipe_conda_ref'] = 'master'
    c['pipelines_demo_ref'] = 'master'
    c['newinstall_ref'] = 'master'
    return c


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

        :param MemberDeleteManualContactsDetails val:
        :rtype: EventDetails
        """
    return cls('member_delete_manual_contacts_details', val)


def face_select_linked_pick(deselect: bool=False):
    """Select linked faces under the cursor

    :param deselect: Deselect, Deselect rather than select items
    :type deselect: bool
    """
    pass


def delete_point():
    """Remove Paint Curve Point

    """
    pass


@classmethod
def getxsdtype(cls, data):
    """
        resolve python data type to xsd data typename
        """
    xsdt = type(data)
    if xsdt in cls.rpc_type_map:
        return cls.rpc_type_map[type(data)]
    return None, None


def allocate_emissions(total_emissions, eta_el, eta_th, method, **kwargs):
    """
    Function to allocate emissions caused in cogeneration to the products electrical energy
    and heat according to specified method.

    .. allocate_emissions-equations:

    **IEA method**

    :math:`EM_{el} = EM \\cdot \\frac{\\eta_{el}}{\\eta_{el} + \\eta_{th}}`,

    :math:`EM_{th} = EM \\cdot \\frac{\\eta_{th}}{\\eta_{el} + \\eta_{th}}`.

    **Efficiency method**

    :math:`EM_{el} = EM \\cdot \\frac{\\eta_{th}}{\\eta_{el} + \\eta_{th}}`,

    :math:`EM_{th} = EM \\cdot \\frac{\\eta_{el}}{\\eta_{el} + \\eta_{th}}`.

    **Finnish method**

    :math:`EM_{el} = EM \\cdot (1-PEE)\\frac{\\eta_{el}}{\\eta_{el,REF}}`,

    :math:`EM_{th} = EM \\cdot (1-PEE)\\frac{\\eta_{th}}{\\eta_{th,REF}}`,

    with

    :math:`PEE = 1 - \\frac{1}{\\frac{\\eta_{th}}{\\eta_{th,ref}}+\\frac{\\eta_{el}}{\\eta_{el,ref}}}`.

    Reference:
    Mauch, W., Corradini, R., Wiesmeyer, K., Schwentzek, M. (2010).
    Allokationsmethoden für spezifische CO2-Emissionen von Strom und Waerme aus KWK-Anlagen.
    Energiewirtschaftliche Tagesfragen, 55(9), 12–14.

    Parameters
    ----------
    total_emissions : numeric
        Total absolute emissions to be allocated to electricity and heat [in CO2 equivalents].

    eta_el : numeric
        Electrical efficiency of the cogeneration [-].

    eta_th : numeric
        Thermal efficiency of the cogeneration [-].

    method : str
        Specification of method to use. Choose from ['iea', finnish', 'efficiency'].

    **kwargs
        For the finnish method, `eta_el_ref` and `eta_th_ref` have to be passed.

    Returns
    -------
    allocated_emissions_electricity : numeric
        total emissions allocated to electricity according to specified `method`
        [in CO2 equivalents].

    allocated_emissions_heat : numeric
            total emissions allocated to heat according to specified `method`
            [in CO2 equivalents].

    """
    if method == 'iea':
        allocated_emissions_electricity = total_emissions * eta_el * 1 / (
            eta_el + eta_th)
        allocated_emissions_heat = total_emissions * eta_th * 1 / (eta_el +
            eta_th)
    elif method == 'efficiency':
        allocated_emissions_electricity = total_emissions * eta_th * 1 / (
            eta_el + eta_th)
        allocated_emissions_heat = total_emissions * eta_el * 1 / (eta_el +
            eta_th)
    elif method == 'finnish':
        if kwargs is not None and kwargs.keys() >= {'eta_el_ref', 'eta_th_ref'
            }:
            eta_el_ref = kwargs.get('eta_el_ref')
            eta_th_ref = kwargs.get('eta_th_ref')
        else:
            raise ValueError(
                'Must specify eta_el_ref, eta_th_ref when using finnish method.'
                )
        pee = 1 - 1 / (eta_el / eta_el_ref + eta_th / eta_th_ref)
        allocated_emissions_electricity = total_emissions * (1 - pee) * (eta_el
             / eta_el_ref)
        allocated_emissions_heat = total_emissions * (1 - pee) * (eta_th /
            eta_th_ref)
    else:
        raise ValueError(
            f"Method '{method}' is not available. Please choose from ['iea', finnish', 'efficiency']"
            )
    return allocated_emissions_electricity, allocated_emissions_heat


@classmethod
def origin(cls):
    """Returns the Point (0 | 0 | 0)"""
    return cls(0, 0, 0)


def draw_stroke(snap: bool=False):
    """Start to draw a sketch stroke

    :param snap: Snap
    :type snap: bool
    """
    pass


@staticmethod
def getsizeof(value):
    """Return the size of a cache element's value."""
    return 1


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

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

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


def categories():
    """ Return a sorted sequence of category names known by
         this introspector """


@classmethod
def header_hash(cls, header):
    """
        Given a header return the hash for DeepOnion.
        Need to download `x13_hash` module
        Source code: https://github.com/MaruCoinOfficial/x13-hash
        """
    import x13_hash
    return x13_hash.getPoWHash(header)


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

    .. code-block:: python

        out = ((image1 + image2) % MAX)

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


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


def user_can(user, item, method_name):
    """When custom methods are required"""
    if user.is_superuser:
        return True
    if user.is_anonymous:
        return False
    method = getattr(item, method_name)
    if callable(method):
        return method(user)
    return False


def read_hook_version(path):
    """Read the hook version from the file."""
    with open(path, 'r') as f:
        f.readline()
        version_line = f.readline()
        if version_line.startswith('# THERAPIST'):
            try:
                return int(version_line.split()[3][1:])
            except IndexError:
                return 1


def Reynolds(V, D, rho=None, mu=None, nu=None):
    """Calculates Reynolds number or `Re` for a fluid with the given
    properties for the specified velocity and diameter.

    .. math::
        Re = \\frac{D \\cdot V}{\\nu} = \\frac{\\rho V D}{\\mu}

    Inputs either of any of the following sets:

    * V, D, density `rho` and kinematic viscosity `mu`
    * V, D, and dynamic viscosity `nu`

    Parameters
    ----------
    V : float
        Velocity [m/s]
    D : float
        Diameter [m]
    rho : float, optional
        Density, [kg/m^3]
    mu : float, optional
        Dynamic viscosity, [Pa*s]
    nu : float, optional
        Kinematic viscosity, [m^2/s]

    Returns
    -------
    Re : float
        Reynolds number []

    Notes
    -----
    .. math::
        Re = \\frac{\\text{Momentum}}{\\text{Viscosity}}

    An error is raised if none of the required input sets are provided.

    Examples
    --------
    >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5)
    38200.65789473684
    >>> Reynolds(2.5, 0.25, nu=1.636e-05)
    38202.93398533008

    References
    ----------
    .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
       Eighth Edition. McGraw-Hill Professional, 2007.
    .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    """
    if rho and mu:
        nu = mu / rho
    elif not nu:
        raise Exception(
            'Either density and viscosity, or dynamic viscosity,         is needed'
            )
    return V * D / nu


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 utf8_decoder(s):
    """ Decode the unicode as UTF-8 """
    if s is None:
        return None
    return s.decode('utf-8')


def extract_phone_number(phone_container):
    """Function to extract phone numbers, return a dictionary with the name of the header like
    key and a list of phone numbers like value"""
    phone_info = {}
    phone_number = phone_container.find_element_by_xpath(
        '//span[@class="t-14 t-black t-normal"]').text
    phone_info['Phone number'] = phone_number
    return phone_info


@classmethod
def get_child_fields(cls):
    """
        Get a list of child fields for the current model, in a "hash" format with the name of the field as the key
        and the related child model as the value.
        """
    return cls.child_fields


def get_feature_set():
    """
    Return a list of features' names.

    Features' name that are used to train a model and predict a class.
    Sorted by the names.

    Returns
    -------
    feature_names : list
        A list of features' names.
    """
    features = ['amplitude', 'hl_amp_ratio', 'kurtosis', 'period',
        'phase_cusum', 'phase_eta', 'phi21', 'phi31', 'quartile31', 'r21',
        'r31', 'shapiro_w', 'skewness', 'slope_per10', 'slope_per90',
        'stetson_k']
    features.sort()
    return features


@staticmethod
def _get_exposed_ports(debug_options):
    """
        Return Docker container port binding information. If a debug port tuple is given, then we will ask Docker to
        bind every given port to same port both inside and outside the container ie. Runtime process is started in debug mode with
        at given port inside the container and exposed to the host machine at the same port

        :param DebugContext debug_options: Debugging options for the function (includes debug port, args, and path)
        :return dict: Dictionary containing port binding information. None, if debug_port was not given
        """
    if not debug_options:
        return None
    if not debug_options.debug_ports:
        return None
    ports_map = {}
    for port in debug_options.debug_ports:
        ports_map[port] = port
    return ports_map


@classmethod
def all(cls, *args, **kwargs):
    """
        Return a list of instances of backend type
        """
    return list(cls.iterator(*args, **kwargs))


def name2env(name):
    """
    convert a name of the for 'radical.pilot' to an env vare base named
    'RADICAL_PILOT'.
    """
    return name.replace('.', '_').upper()


def random_flip_top_bottom(data=None, out=None, name=None, **kwargs):
    """

    Defined in src/operator/image/image_random.cc:L210

    Parameters
    ----------
    data : NDArray
        The input.

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

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


def merge(a, b):
    """
    Merge all attributes and metadata from I{a} to I{b}.

    @param a: A I{source} object
    @type a: L{Object}
    @param b: A I{destination} object
    @type b: L{Object}

    """
    for item in a:
        setattr(b, item[0], item[1])
        b.__metadata__ = b.__metadata__
    return b


def dec():
    """Decrease the indentation"""
    global __count
    __count -= 1


def pvannuity(rate, npmts, amt=1.0):
    """
    Present value of `n` payments of a given size given
    an interest rate per payment interval of `rate`.

    .. versionchanged:: 0.3.0
       `amt` can be specified in function call.

    Parameters
    ----------
    rate : float
        Interest rate per payment period. Note that if
        payments are monthly and known interest rate is annual,
        `rate` must be calculated as effective *monthly* interest.
    npmts : int
        Number of payments.
    amt : float, optional
        Amount of each payment. Defaults to 1.
    """
    return amt * (1.0 - (1.0 + rate) ** -npmts) / rate


def rendaku_merge_pairs(lpair, rpair):
    """Merge lpair < rpair while applying semi-irregular rendaku rules"""
    ltext, lnum = lpair
    rtext, rnum = rpair
    if lnum > rnum:
        raise ValueError
    if rpair == ('ひゃく', 100):
        if lpair == ('さん', 3):
            rtext = 'びゃく'
        elif lpair == ('ろく', 6):
            ltext = 'ろっ'
            rtext = 'ぴゃく'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
            rtext = 'ぴゃく'
    elif rpair == ('せん', 1000):
        if lpair == ('さん', 3):
            rtext = 'ぜん'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
    elif rpair == ('ちょう', 10 ** 12):
        if lpair == ('いち', 1):
            ltext = 'いっ'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
        elif lpair == ('じゅう', 10):
            ltext = 'じゅっ'
    elif rpair == ('けい', 10 ** 16):
        if lpair == ('いち', 1):
            ltext = 'いっ'
        elif lpair == ('ろく', 6):
            ltext = 'ろっ'
        elif lpair == ('はち', 8):
            ltext = 'はっ'
        elif lpair == ('じゅう', 10):
            ltext = 'じゅっ'
        elif lpair == ('ひゃく', 100):
            ltext = 'ひゃっ'
    return '%s%s' % (ltext, rtext), lnum * rnum


def no_limits_amp(npeaks):
    """
    No amplitude limits for npeaks
    """
    return [(None, None)] * npeaks


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True):
    """Select items using border selection

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


def get_array(array, **kw):
    """
    Extract a subarray by filtering on the given keyword arguments
    """
    for name, value in kw.items():
        array = array[array[name] == value]
    return array


def get_urls(session, name, data, find_changelogs_fn, **kwargs):
    """
    Gets URLs to changelogs.
    :param session: requests Session instance
    :param name: str, package name
    :param data: dict, meta data
    :param find_changelogs_fn: function, find_changelogs
    :return: tuple, (set(changelog URLs), set(repo URLs))
    """
    if 'versions' in data:
        candidates = set()
        for version, item in data['versions'].items():
            if 'homepage' in item and item['homepage'] is not None:
                if isinstance(item['homepage'], list):
                    candidates.add(*item['homepage'])
                else:
                    candidates.add(item['homepage'])
            if 'repository' in item and item['repository'] is not None:
                if 'url' in item['repository']:
                    repo = item['repository']['url']
                elif 'path' in item['repository']:
                    repo = item['repository']['path']
                else:
                    continue
                repo = repo.replace('git://', 'https://').replace('.git', '')
                candidates.add(repo)
        return find_changelogs_fn(session=session, name=name, candidates=
            candidates)
    return set(), set()


def authenticateCredentials(credentials):
    """Authenticates credentials and return a IPrincipal object.

        If the credentials can be authenticated, return an object that provides
        IPrincipal. If the plugin cannot authenticate the credentials,
        returns None.
        """


@staticmethod
def _is_header(line):
    """Check if a line is header."""
    line = line.strip()
    if line.startswith('#') or line.startswith('track') or line.startswith(
        'browser'):
        return True
    else:
        return False


@classmethod
def from_shapely(cls, shape):
    """
        Build a spatialpandas Ring object from a shapely shape

        Args:
            shape: A shapely LinearRing shape

        Returns:
            spatialpandas Ring
        """
    return super().from_shapely(shape)


def atse_isFieldVisible(fieldname, mode='view', schema_id=None):
    """
        Returns True if the given field is visible
        in the given mode. Default is view.
        """


def __get_score(line):
    """Get the score value from an input score file line

    @param line: An input score file line
    @type line: str

    @returns: The parsed score
    @rtype: float
    """
    sline = line.strip().split(' ')
    return float(sline[-1])


def sync_batou():
    """Update version pins on batou"""
    pass


def _percentage_contribution(box):
    """Return the percentage contribution of a cell, column or column group.

    http://dbaron.org/css/intrinsic/#pct-contrib

    """
    min_width = box.style['min_width'].value if box.style['min_width'
        ] != 'auto' and box.style['min_width'].unit == '%' else 0
    max_width = box.style['max_width'].value if box.style['max_width'
        ] != 'auto' and box.style['max_width'].unit == '%' else float('inf')
    width = box.style['width'].value if box.style['width'
        ] != 'auto' and box.style['width'].unit == '%' else 0
    return max(min_width, min(width, max_width))


def _get_data(isotherm, data_name, current_branch, drange, **kwargs):
    """Get different data from an isotherm."""
    if data_name == 'pressure':
        data = isotherm.pressure(branch=current_branch, pressure_mode=
            kwargs['pressure_mode'], pressure_unit=kwargs['pressure_unit'],
            min_range=drange[0], max_range=drange[1], indexed=True)
    elif data_name == 'loading':
        data = isotherm.loading(branch=current_branch, loading_basis=kwargs
            ['loading_basis'], loading_unit=kwargs['loading_unit'],
            adsorbent_basis=kwargs['adsorbent_basis'], adsorbent_unit=
            kwargs['adsorbent_unit'], min_range=drange[0], max_range=drange
            [1], indexed=True)
    else:
        data = isotherm.other_data(data_name, branch=current_branch,
            min_range=drange[0], max_range=drange[1], indexed=True)
    return data


def min(input, dim):
    """Reduce min the input tensor along the given dim.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The reduce dim.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


def test_view(test, urlconf, user):
    """
    Run a view test. Add in *args, **kwargs if appropriate.
    """
    args = [] if 'args' not in test.func_code.co_varnames else urlconf.args
    kwargs = {
        } if 'kwargs' not in test.func_code.co_varnames else urlconf.kwargs
    return test(user, *args, **kwargs)


def make_classyfire_graphml(graphML, final):
    """Create a network file with chemical classes mapped

    :param graphml: GNPS network file
    :type graphml: networkx.classes.graph.Graph
    :param final: A dataframe containing most predominant chemical classes per node at each level of the ClassyFire chemical ontology
    :type final: pandas.core.frame.DataFrame
    :return: A network file with most predominant chemical classes per node mapped at each level of the ClassyFire chemical ontology
    :rtype: networkx.classes.graph.Graph

    """
    for v in graphML.nodes():
        graphML.node[v]['CF_componentindex'] = str(final[final[
            'cluster index'] == int(v)]['CF_componentindex'].iloc[-1])
        graphML.node[v]['CF_NrNodes'] = float(final[final['cluster index'] ==
            int(v)]['CF_NrNodes'].iloc[-1])
        graphML.node[v]['CF_kingdom'] = str(final[final['cluster index'] ==
            int(v)]['CF_kingdom'].iloc[-1])
        try:
            graphML.node[v]['CF_kingdom_score'] = float(final[final[
                'cluster index'] == int(v)]['CF_kingdom_score'].iloc[-1])
        except:
            graphML.node[v]['CF_kingdom_score'] = object()
        graphML.node[v]['CF_superclass'] = str(final[final['cluster index'] ==
            int(v)]['CF_superclass'].iloc[-1])
        try:
            graphML.node[v]['CF_superclass_score'] = float(final[final[
                'cluster index'] == int(v)]['CF_superclass_score'].iloc[-1])
        except:
            graphML.node[v]['CF_superclass_score'] = object()
        graphML.node[v]['CF_class'] = str(final[final['cluster index'] ==
            int(v)]['CF_class'].iloc[-1])
        try:
            graphML.node[v]['CF_class_score'] = float(final[final[
                'cluster index'] == int(v)]['CF_class_score'].iloc[-1])
        except:
            graphML.node[v]['CF_class_score'] = object()
        graphML.node[v]['CF_subclass'] = str(final[final['cluster index'] ==
            int(v)]['CF_subclass'].iloc[-1])
        try:
            graphML.node[v]['CF_subclass_score'] = float(final[final[
                'cluster index'] == int(v)]['CF_subclass_score'].iloc[-1])
        except:
            graphML.node[v]['CF_subclass_score'] = object()
        graphML.node[v]['CF_Dparent'] = str(final[final['cluster index'] ==
            int(v)]['CF_Dparent'].iloc[-1])
        try:
            graphML.node[v]['CF_Dparent_score'] = float(final[final[
                'cluster index'] == int(v)]['CF_Dparent_score'].iloc[-1])
        except:
            graphML.node[v]['CF_Dparent_score'] = object()
        graphML.node[v]['CF_MFramework'] = str(final[final['cluster index'] ==
            int(v)]['CF_MFramework'].iloc[-1])
        try:
            graphML.node[v]['CF_MFramework_score'] = float(final[final[
                'cluster index'] == int(v)]['CF_MFramework_score'].iloc[-1])
        except ValueError:
            graphML.node[v]['CF_MFramework_score'] = object()
    return graphML


def prior_sample(bn):
    """Randomly sample from bn's full joint distribution. The result
    is a {variable: value} dict. [Figure 14.13]"""
    event = {}
    for node in bn.nodes:
        event[node.variable] = node.sample(event)
    return event


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

    Like 'git describe --tags --dirty --always'.

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


@staticmethod
def __docstringDisplayable(docstring):
    """True if docstring is displayable"""
    if docstring is None:
        return False
    if isinstance(docstring, dict):
        if docstring['docstring'].strip() == '':
            return False
        return True
    if docstring.strip() == '':
        return False
    return True


def segmented_date_range(start_date, end_date, segment='A'):
    """
    Split a date range into smaller segments.

    Parameters
    ----------

    start_date : str (YYYY-MM-DD), required
        start date, inclusive

    end_date : str (YYYY-MM-DD), required
        end date, inclusive

    segment : str, required
        split date range into segments of this size (use Pandas
        frequency string, e.g. 'A' for annual segments or 'Q' for quarterly
        segments; default 'A')

    Returns
    -------
    list
        list of tuples of (start_date, end_date)

    Examples
    --------
    >>> segmented_date_range("2013-06-01", "2015-12-15")
    [('2013-06-01', '2013-12-30'),
    ('2013-12-31', '2014-12-30'),
    ('2014-12-31', '2015-12-15')]
    """
    try:
        import pandas as pd
    except ImportError:
        raise ImportError('pandas must be installed to use this function')
    date_segments = []
    period_boundaries = list(pd.date_range(start_date, end_date, freq=segment))
    start_date = pd.Timestamp(start_date)
    end_date = pd.Timestamp(end_date)
    if start_date not in period_boundaries:
        period_boundaries.insert(0, start_date)
    if end_date not in period_boundaries:
        period_boundaries.append(end_date)
    for i in range(len(period_boundaries) - 1):
        period_start_date = period_boundaries[i].date()
        period_end_date = period_boundaries[i + 1].date()
        if period_end_date < end_date.date():
            period_end_date -= pd.Timedelta(days=1)
        period_start_date = period_start_date.isoformat()
        period_end_date = period_end_date.isoformat()
        date_segments.append((period_start_date, period_end_date))
    return date_segments


def _fast_smooth_array(arr):
    """Simple smoothing which is less computationally expensive than
    applying a gaussian filter.

    Only the first three dimensions of the array will be smoothed. The
    filter uses [0.2, 1, 0.2] weights in each direction and use a
    normalisation to preserve the local average value.

    Parameters
    ----------
    arr: numpy.ndarray
        4D array, with image number as last dimension. 3D arrays are
        also accepted.

    Returns
    -------
    smoothed_arr: numpy.ndarray
        Smoothed array.

    Notes
    -----
    Rather than calling this function directly, users are encouraged
    to call the high-level function :func:`smooth_img` with
    fwhm='fast'.

    """
    neighbor_weight = 0.2
    nb_neighbors = 6
    scale = 1 + nb_neighbors * neighbor_weight
    smoothed_arr = arr.copy()
    weighted_arr = neighbor_weight * arr
    smoothed_arr[:-1] += weighted_arr[1:]
    smoothed_arr[1:] += weighted_arr[:-1]
    smoothed_arr[:, :-1] += weighted_arr[:, 1:]
    smoothed_arr[:, 1:] += weighted_arr[:, :-1]
    smoothed_arr[:, :, :-1] += weighted_arr[:, :, 1:]
    smoothed_arr[:, :, 1:] += weighted_arr[:, :, :-1]
    smoothed_arr /= scale
    return smoothed_arr


def call_menu_pie(name: str=''):
    """Call (draw) a pre-defined pie menu

    :param name: Name, Name of the pie menu
    :type name: str
    """
    pass


def get_xy_range(bbox):
    """Return x and y ranges in meters based on bounding box.

    bbox: dictionary
        dictionary containing coordinates for corners of study area

    Returns
    -------
    x_range: float
        Range in meters in x dimension.
    y_range: float
        Range in meters in y dimension.

    """
    x_range = bbox['east'] - bbox['west']
    y_range = bbox['north'] - bbox['south']
    return x_range, y_range


@classmethod
def get(cls, obj, *default):
    """
        Returns the value contained in the class dictoinary.

        Parameters
        ----------
        obj : object
            The object to acquire values for.
        default
            The default value to return if the object is not found.
        """
    odict = cls.CLASS_DICT
    if obj in odict:
        return odict[obj]
    elif default:
        return default[0]
    else:
        raise KeyError('Key {!r} does not exist.'.format(obj))


def bytearray_to_bytes(byte_array):
    """
  Converts a byte array into a string.

  :param byte_array:
      The byte array.
  :returns:
      String.
  """
    return byte_array.tostring()


def inverseDict(d):
    """
	Returns a dictionay indexed by values {value_k:key_k}
	Parameters:
	-----------
		d : dictionary
	"""
    dt = {}
    for k, v in list(d.items()):
        if type(v) in (list, tuple):
            for i in v:
                dt[i] = k
        else:
            dt[v] = k
    return dt


def update_dist(state, updates, dist):
    """yields outcomes updates and their probability"""
    if not isinstance(dist, list):
        dist = dist(state)
    mass = sum(dist)
    if mass < 1:
        updates.append({})
        dist.append(1 - mass)
    for u, p in zip(updates, dist):
        yield u, p


def levenshtein(a, b):
    """Calculates the Levenshtein distance between a and b."""
    n, m = len(a), len(b)
    if n > m:
        a, b = b, a
        n, m = m, n
    current = list(range(n + 1))
    for i in range(1, m + 1):
        previous, current = current, [i] + [0] * n
        for j in range(1, n + 1):
            add, delete = previous[j] + 1, current[j - 1] + 1
            change = previous[j - 1]
            if a[j - 1] != b[i - 1]:
                change = change + 1
            current[j] = min(add, delete, change)
    return current[n]


def get_reader_time_step_values(extensions, reader_description):
    """Get the XML content for reader time step values the Python path when
    making a ParaView plugin.
    """
    return (
        """<DoubleVectorProperty
      name="TimestepValues"
      repeatable="1"
      information_only="1">
      <TimeStepsInformationHelper/>
          <Documentation>
          Available timestep values.
          </Documentation>
      </DoubleVectorProperty>
      <Hints>
          <ReaderFactory extensions="%s"
                  file_description="%s" />
      </Hints>
      """
         % (extensions, reader_description))


@classmethod
def GetMountPoint(cls, mount_point):
    """Retrieves the path specification of a mount point.

    Args:
      mount_point (str): mount point identifier.

    Returns:
      PathSpec: path specification of the mount point or None if the mount
          point does not exists.
    """
    return cls._mount_points.get(mount_point, None)


@staticmethod
def _get_eth_port_value(metric, data):
    """
        function that returns the data from the managed object
        :param metric:
        :param data:
        :return:
        """
    if metric == 'network.eth.tx.rate':
        return float(float(data.EtherTxStats.total_bytes_delta) / 60 * 8 /
            1000000000)
    elif metric == 'network.eth.rx.rate':
        return float(float(data.EtherRxStats.total_bytes_delta) / 60 * 8 /
            1000000000)
    elif metric == 'network.eth.pause.recv':
        return float(data.EtherPauseStats.recv_pause_delta)
    elif metric == 'network.eth.pause.resets':
        return float(data.EtherPauseStats.resets_delta)
    elif metric == 'network.eth.pause.xmit':
        return float(data.EtherPauseStats.xmit_pause_delta)
    elif metric == 'network.eth.err.xmit':
        return float(data.EtherErrStats.xmit_delta)
    elif metric == 'network.eth.err.recv':
        return float(data.EtherErrStats.xmit_delta)
    elif metric == 'network.eth.link.speed':
        return float(data.oper_speed.replace('gbps', ''))
    else:
        return None


@classmethod
def create_text(cls, position, *chars):
    """Create a node interpretable as text

        :type position: tuple[int]
        :param position: a tuple (row, col) to mark the positioning

        :type chars: tuple[unicode]
        :param chars: characters to add to the text

        :rtype: _InstructionNode
        """
    return cls(u''.join(chars), position=position)


def theta_H_K_MarChemSpec25(T, P):
    """c-c': hydrogen potassium [MarChemSpec]."""
    theta = 0.005
    valid = T == 298.15
    return theta, valid


def is_gpxfile(value):
    """Return True or False without looking at the type, so we do not need to import GpxFile."""
    return hasattr(value, 'id_in_backend')


def _which_unix_compiler(compiler):
    """
    Find which Unix compiler is "cc", "c++".

    Default to GCC if no other found.

    Parameters
    ----------
    compiler : str
        Compiler Name

    Returns
    -------
    str:
        Detected compiler Name
    """
    from subprocess import Popen, PIPE
    try:
        version_str = Popen([compiler if compiler != 'unix' else 'cc',
            '--version'], stdout=PIPE, universal_newlines=True).stdout.read(
            ).lower()
    except OSError:
        return 'gcc'
    if 'clang' in version_str:
        return 'llvm'
    return 'gcc'


def find_local_boundary(tri, triangles):
    """Find and return the outside edges of a collection of natural neighbor triangles.

    There is no guarantee that this boundary is convex, so ConvexHull is not
    sufficient in some situations.

    Parameters
    ----------
    tri: `scipy.spatial.Delaunay`
        A Delaunay Triangulation
    triangles: (N, ) array
        List of natural neighbor triangles.

    Returns
    -------
    edges: list
        List of vertex codes that form outer edges of
        a group of natural neighbor triangles.

    """
    edges = []
    for triangle in triangles:
        for i in range(3):
            pt1 = tri.simplices[triangle][i]
            pt2 = tri.simplices[triangle][(i + 1) % 3]
            if (pt1, pt2) in edges:
                edges.remove((pt1, pt2))
            elif (pt2, pt1) in edges:
                edges.remove((pt2, pt1))
            else:
                edges.append((pt1, pt2))
    return edges


def render():
    """We use the content provider update/render couple.
        """


def get_coherent_next_tag(prev_label: str, cur_label: str) ->str:
    """
    Generate a coherent tag, given previous tag and current label.
    """
    if cur_label == 'O':
        return 'O'
    if prev_label == cur_label:
        return f'I-{cur_label}'
    else:
        return f'B-{cur_label}'


def psi_H_Na_SO4_HMW84(T, P):
    """c-c'-a: hydrogen sodium sulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def get_weight(stats):
    """
    Return a data point weight for the result.
    """
    if stats is None or 'ci_99' not in stats:
        return None
    try:
        return 2 / abs(stats['ci_99'][1] - stats['ci_99'][0])
    except ZeroDivisionError:
        return None


def p_var_decls(p):
    """ statement : var_decl
    """
    p[0] = p[1]


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

        :param AddMemberSelectorError val:
        :rtype: AddFolderMemberError
        """
    return cls('bad_member', val)


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


def order_streams(in_a, in_b, out_a, out_b):
    """
    Return cold and hot inlet and outlet streams.

    Parameters
    ----------
    in_a : Stream
        Inlet a.
    in_b : Stream
        Inlet b.
    out_a : Stream
        Outlet a.
    out_b : Stream
        Outlet b.

    Returns
    -------
    ci : Stream
        Cold inlet.
    hi : Stream
        Hot inlet.
    co : Stream
        Cold outlet.
    ho : Stream
        Hot outlet.

    """
    if in_a.T < in_b.T:
        return in_a, in_b, out_a, out_b
    else:
        return in_b, in_a, out_b, out_a


def join_uvs():
    """Transfer UV Maps from active to selected objects (needs matching geometry)

    """
    pass


def atomic_number(atom):
    """Get the atomic number for an atom.

    Parameters
    ----------
    atom : rdkit.Chem.rdchem.Atom
        RDKit atom instance.

    Returns
    -------
    list
       List containing one int only.
    """
    return [atom.GetAtomicNum()]


def feet2m(length_feet):
    """Converts length value from feet to meters"""
    return length_feet * 0.3048


def last_word(value: str):
    """
    Splits out the word after the last slash in a string.  K8
    objects are expressed in a path style name

    Example
    -------

    >>> last_word('pods/my-pod')
    'my-pod'
    """
    return value.split('/')[-1:][0]


def afw_completion(afw):
    """ Side effect on input! Complete the afw adding not
    present transitions and marking them as False.

    :param dict afw: input AFW.
    """
    for state in afw['states']:
        for a in afw['alphabet']:
            if (state, a) not in afw['transitions']:
                afw['transitions'][state, a] = 'False'
    return afw


def merkle_pair(hashes, hash_f):
    """Take a list of hashes, and return the parent row in the tree of merkle hashes."""
    if len(hashes) % 2 == 1:
        hashes = list(hashes)
        hashes.append(hashes[-1])
    l = []
    for i in range(0, len(hashes), 2):
        l.append(hash_f(hashes[i] + hashes[i + 1]))
    return l


def lambd_NH3_Cl_CB89(T, P):
    """n-a: ammonia chloride [CB89]."""
    lambd = 0
    valid = T == 298.15
    return lambd, valid


@classmethod
def spatial_dim(cls, tensor):
    """ Return spatial dim of the input tensor (without channels and batch dimension)

        Parameters
        ----------
        tensor : tf.Tensor

        Returns
        -------
        dim : int
        """
    return len(tensor.get_shape().as_list()) - 2


def compat_explain(cur):
    """
    Simulate MongoDB 3.0 explain result on prior versions.
    http://docs.mongodb.org/v3.0/reference/explain-results/
    """
    res = cur.explain()
    if 'nscannedObjects' in res:
        res['executionStats'] = dict(nReturned=res.pop('n'),
            totalKeysExamined=res.pop('nscanned'), totalDocsExamined=res.
            pop('nscannedObjects'), executionTimeMillis=res.pop('millis'))
    return res


@classmethod
def get_product_images(cls, products, name=None):
    """
        Getter for `images` function field
        """
    res = {}
    for product in products:
        product_images = []
        for media in product.media:
            if not media.static_file.mimetype:
                continue
            if 'image' in media.static_file.mimetype:
                product_images.append(media.static_file.id)
        res[product.id] = product_images
    return res


@staticmethod
def _subscribe_broadcast(sub_id, channel, callback, **kwargs):
    """Listen to a broadcast topic, notify via callback function.
        :param sub_id: ID for this subscription in the transport layer
        :param channel: Topic name to subscribe to
        :param callback: Function to be called when messages are received
        :param **kwargs: Further parameters for the transport layer. For example
               retroactive: Ask broker to send old messages if possible
        """
    raise NotImplementedError('Transport interface not implemented')


def merge_status(main, other):
    """
    Merge two status tuples.
    """
    new_code = main[0] | other[0]
    new_out = '%s%s' % (main[1], other[1])
    new_err = '%s%s' % (main[2], other[2])
    return new_code, new_out, new_err


def remove_role_from_principal(role_id, principal_id):
    """Remove a role from the principal."""


def setPreviousResponse(response):
    """
        Set the reference to the previous L{IResponse}.

        The value of the previous response can be read via
        L{IResponse.previousResponse}.
        """


def upgrade():
    """A no-op migration for marking the Kilo release."""
    pass


def iteritems():
    """
        Get the iterator for this storage, should yield tuple of (key, value)
        """


def validate_str(obj):
    """
    Check that obj is a string and then convert it to unicode.

    Parameters
    ----------
    obj: Any
        Object that should be a string

    Returns
    -------
    str
        `obj` as a string.

    Raises
    -------
    ValueError
        If `obj` is not a string.

    """
    if not isinstance(obj, str):
        raise TypeError('Expected a string but got {} instead'.format(type(
            obj)))
    try:
        return obj.decode('utf-8')
    except AttributeError:
        return obj


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 heavsineFunction(dim=1024, normalize=True, heavs=0):
    """
    Generate the Heavsine function in a range of 0 to 1, with dim points.

    Parameters
    ----------
    dim: int
        Dimension of the signal.

    normalize: bool, optional
        It is True by default. This parameter normalize the data values
        in a range of 0 to 1 with a function present in
        ``statsWaveletFilt.miscellaneous``.

    heavs: int or float, optional
        It is 0 by default. This parameter, called * heavs * is the number of
        discontinuities in the heavens characteristic signal shown by
        Donoho [1] with 0 the signal will be the original, used in [1].

    Returns
    -------
    tuple:
        [0] 1-D array-like, coordinates in X axis and [1] 1-D array-like,
        coordinates in Y axis

    References
    ----------
    .. [1] DONOHO, D. L.; JOHNSTONE, I. M. Ideal spatial adaptation via
           wavelet shrinkage. Biometrika, v. 81, p. 425–455, 1994.
    """
    import numpy as np
    import statsWaveletFilt.miscellaneous as misc
    linspace = np.linspace
    sin = np.sin
    signal = np.sign
    pi = np.pi
    x = linspace(0, 1, dim)
    if heavs == 0:
        y = 4 * sin(4 * pi * x) - signal(x - 0.3) - signal(0.72 - x)
    else:
        y = 4 * sin(4 * pi * x)
        for i in range(heavs):
            if i % 2:
                y -= signal(x - np.random.random())
            else:
                y += signal(x - np.random.random())
    if normalize:
        y_nor = misc.normalizeData(y)
    else:
        y_nor = y
    return x, y_nor


def apply_schema(PublishedSchemaArn=None, DirectoryArn=None):
    """
    Copies the input published schema into the  Directory with the same name and version as that of the published schema .
    See also: AWS API Documentation

    :example: response = client.apply_schema(
        PublishedSchemaArn='string',
        DirectoryArn='string'
    )

    :type PublishedSchemaArn: string
    :param PublishedSchemaArn: [REQUIRED]
            Published schema Amazon Resource Name (ARN) that needs to be copied. For more information, see arns .

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The Amazon Resource Name (ARN) that is associated with the Directory into which the schema is copied. For more information, see arns .

    :rtype: dict
    :return: {
        'AppliedSchemaArn': 'string',
        'DirectoryArn': 'string'
    }

    """
    pass


@classmethod
def get_api_sub_resources(cls):
    """Define the API sub-resources this object will appear under.

        This should return a list of API sub-resources that the object
        will be exposed under.

        This is used by the standard attr extensions to discover which
        sub-resources need to be extended with the standard attr fields
        (e.g. created_at/updated_at/etc).
        """
    try:
        return cls.api_sub_resources
    except AttributeError:
        return []


def item_rename():
    """Rename item under cursor

    """
    pass


@classmethod
def home(cls):
    """Return a new path pointing to the user's home directory (as
        returned by os.path.expanduser('~')).
        """
    return cls(cls()._flavour.gethomedir(None))


def NMB(obs, mod, axis=None):
    """ Normalized Mean Bias (%)"""
    return (mod - obs).sum(axis=axis) / obs.sum(axis=axis) * 100.0


def uquote(value):
    """Quote a unicode string value."""
    res = ['"']
    for char in value:
        if char == u'"':
            res.append(u'\\')
        res.append(char)
    res.append(u'"')
    return u''.join(res)


def get(isamAppliance, id, check_mode=False, force=False):
    """
    Retrieve a Client Certificate Mapping
    """
    return isamAppliance.invoke_get('Retrieve a Client Certificate Mapping',
        '/wga/client_cert_cdas/{0}'.format(id))


def __init__(**kw):
    """Everything contained in kw is available through __getitem__
        """


def get_model_name(model):
    """
    Returns the name of the model
    """
    return model._meta.model_name


def boolean_convert(value):
    """Converts a string like '1' or '0' to a boolean value"""
    try:
        return bool(int(value))
    except ValueError:
        return value


def map_value_or(f, value, default):
    """Return Value or Default if Value is None."""
    return f(value) if value is not None else default


def write_file(filename, data):
    """
    Write data to a file.

    :param filename: Path to the file.
    :type filename: str
    :param line: Line to be written.
    :type line: str
    """
    with open(filename, 'w') as file_obj:
        file_obj.write(data)


@conf
def find_solstudio(conf):
    """Find the Solaris Studio compiler (will look in the environment variable 'FC')"""
    fc = conf.find_program(['sunf95', 'f95', 'sunf90', 'f90'], var='FC')
    conf.get_solstudio_version(fc)
    conf.env.FC_NAME = 'SOL'


def calculate_onedimensional_distance(x, y, horizontal=True):
    """
    x and y are 2D positions.

    horizontal checks whether we measure horizontal or vertical distance.
    """
    x = list(x)
    y = list(y)
    x[0] = float(x[0])
    x[1] = float(x[1])
    y[0] = float(y[0])
    y[1] = float(y[1])
    if horizontal:
        return abs(x[0] - y[0])
    else:
        return abs(x[1] - y[1])


def key_to_idx(key):
    """convert a binary LMDB key to an integer index"""
    return int(key)


@classmethod
def make_instance(cls, data):
    """Validate the data and create a model instance from the data.

        Args:
            data (dict): The unserialized data to insert into the new model
                instance through it's constructor.

        Returns:
            peewee.Model|sqlalchemy.Model: The model instance with it's data
                inserted into it.

        Raises:
            AttributeError: This is raised if ``Meta.model`` isn't set on the
                schema's definition.
        """
    schema = cls()
    if not hasattr(schema.Meta, 'model'):
        raise AttributeError(
            'In order to make an instance, a model for the schema must be defined in the Meta class.'
            )
    serialized_data = schema.load(data).data
    return cls.Meta.model(**serialized_data)


def _bits_to_bytes_not_aligned(n_bits):
    """ Converts number of bits into number of not aligned bytes

    Parameters
    -------------
    n_bits : int
        number of bits

    Returns
    ----------
    number of equivalent not aligned bytes
    """
    n_bytes = n_bits // 8
    if not n_bits % 8 == 0:
        n_bytes += 1
    return n_bytes


def _lookup_enum_in_ns(namespace, value):
    """Return the attribute of namespace corresponding to value."""
    for attribute in dir(namespace):
        if getattr(namespace, attribute) == value:
            return attribute


@staticmethod
def getSkimArguments():
    """
        _getSkimArguments_

        Skim arguments can be many of the same, it depends on the number
        of defined skims. However we need to keep the same definition of its arguments
        in a generic form. This method follows the same definition of getWorkloadCreateArgs in StdBase.
        """
    skimArgs = {'SkimName#N': {'default': None, 'type': str, 'optional':
        False, 'validate': None, 'null': False}, 'SkimInput#N': {'default':
        None, 'type': str, 'optional': False, 'validate': None, 'null':
        False}, 'Skim#NConfigCacheID': {'default': None, 'type': str,
        'optional': False, 'validate': None, 'null': False},
        'SkimTimePerEvent#N': {'default': None, 'type': float, 'optional':
        True, 'validate': lambda x: x > 0, 'null': False},
        'SkimSizePerEvent#N': {'default': None, 'type': float, 'optional':
        True, 'validate': lambda x: x > 0, 'null': False}, 'SkimMemory#N':
        {'default': None, 'type': float, 'optional': True, 'validate': lambda
        x: x > 0, 'null': False}, 'SkimSplittingAlgo#N': {'default': None,
        'type': str, 'optional': True, 'validate': None, 'null': False},
        'SkimEventsPerJob#N': {'default': None, 'type': int, 'optional':
        True, 'validate': lambda x: x > 0, 'null': False},
        'SkimLumisPerJob#N': {'default': 8, 'type': int, 'optional': True,
        'validate': lambda x: x > 0, 'null': False}, 'SkimFilesPerJob#N': {
        'default': 1, 'type': int, 'optional': True, 'validate': lambda x:
        x > 0, 'null': False}}
    return skimArgs


def getParent():
    """Return this member's parent member unique or None if this is the root
        already."""


@classmethod
def to_yaml(cls, representer, node):
    """A YAML representation of this Transformation, including all its
        arguments (which must again be YAML-representable). In essence, this
        returns a YAML mapping that has the ``!dag_trf`` YAML tag prefixed,
        such that *reading* it in will lead to the ``from_yaml`` method being
        invoked.

        .. note::

            The YAML representation does *not* include the ``file_cache``
            parameters.

        .. warning::

            The YAML representation is used in computing the hashstr that
            identifies this transformation.
            Changing the argument order here or adding further keys to the
            dict will lead to hash changes and thus to cache misses.

        """
    d = dict(operation=node._operation, args=node._args, kwargs=dict(node.
        _kwargs))
    if node._salt is not None:
        d['salt'] = node._salt
    return representer.represent_mapping(cls.yaml_tag, d)


def SFFloat_vrmlstr(value, lineariser=None):
    """Convert floats to (compact) VRML97 representation"""
    rpr = str(value)
    if rpr == '0.0':
        return '0'
    elif rpr[:2] == '0.':
        return rpr[1:]
    elif rpr[:3] == '-0.':
        return '-' + rpr[2:]
    elif rpr[-2:] == '.0':
        return rpr[:-2]
    else:
        return rpr


def flatlist(inlist):
    """Convert list of tuples into a list expanded by concatenating tuples"""
    outlist = []
    for r in inlist:
        for x in r:
            outlist.append(x)
    return outlist


def GetMassGivenPPM(t, p):
    """
    calculate theoretical mass (t) given a ppm tolerance (p)
    """
    return t - p * t / 1000000.0


def comp_delta(x):
    """ Computes delta values as in the objective function of SFA.
    The feature vectors are not normalized to unit variance or zero mean.
    """
    xderiv = x[1:, :] - x[:-1, :]
    return (xderiv ** 2).mean(axis=0)


def usage_hint(command, shell):
    """
    Returns the usage hint and comment, for the given shell.
    """
    if shell == 'fish':
        return 'eval ({command})'.format(command=command), '#'
    elif shell == 'powershell':
        return (
            '{command} | ForEach-Object {{If (-Not[string]::IsNullOrEmpty($_)) {{ $_ | Invoke-Expression }}}}'
            .format(command=command), '#')
    elif shell == 'cmd':
        return '\t@FOR /f "tokens=*" %i IN ({command}) DO @%i'.format(command
            =command), 'REM'
    elif shell == 'emacs':
        return (
            '(with-temp-buffer (shell-command {command} (current-buffer))(eval-buffer))'
            .format(command=command), ';;')
    elif shell == 'tcsh':
        return 'eval `{command}`'.format(command=command), ':'
    else:
        return 'eval $({command})'.format(command=command), '#'


def scan(function, accumulator, list):
    """Scan is similar to reduce, but returns a list of successively
reduced values from the left"""
    result = [accumulator]
    for x in list:
        accumulator = function(accumulator, x)
        result.append(accumulator)
    return result


@staticmethod
def get_creation_arguments_model():
    """
        This is needed so the BaseState can validate the provided
        creation arguments as well as for auto documentation.
        return = {
            'required_creation_arguments': {
                'required_creation_arg_1': type,
                'required_creation_arg_2': type,
            },
            'optional_creation_arguments': {
                'optional_creation_arg_1': type,
                'optional_creation_arg_2': type,
            },
        }
        """
    return {'required_creation_arguments': {},
        'optional_creation_arguments': {'topic': str, 'is_x_pub': bool,
        'wait_after_creation_s': float}}


def validate_format(*_arg):
    """
    This method can be overridden with format validation logic.
    """
    return True


def remove_prep_table(tt):
    """Removes prep table from a fontTools.ttLib.TTFont object"""
    try:
        del tt['prep']
    except KeyError:
        pass


def wid_to_gid(wid):
    """Calculate gid of a worksheet from its wid."""
    widval = wid[1:] if len(wid) > 3 else wid
    xorval = 474 if len(wid) > 3 else 31578
    return str(int(widval, 36) ^ xorval)


def setUpRow(item):
    """Setup table row."""


def describe_targets(best_targets):
    """Return a list of lines describing the results of `target`, if any."""
    if not best_targets:
        return []
    elif len(best_targets) == 1:
        label, score = next(iter(best_targets.items()))
        return ['Highest target score: {:g}  (label={!r})'.format(score, label)
            ]
    else:
        lines = ['Highest target scores:']
        for label, score in sorted(best_targets.items(), key=lambda x: x[::-1]
            ):
            lines.append('{:>16g}  (label={!r})'.format(score, label))
        return lines


def filter_params(params, plugin, ith=-1):
    """
    Get the values within params that apply to a plugin.
    More specific names override more general names, in this order:

    <index_order>.parameter > <plugin.name>.parameter > parameter

    Example:

    >>> filter_params({'0.hello': True, 'hello': False}, Plugin(), 0)
    { '0.hello': True, 'hello': True}

    """
    thisparams = {}
    if ith >= 0:
        ith = '{}.'.format(ith)
    else:
        ith = ''
    for k, v in params.items():
        if ith and k.startswith(str(ith)):
            thisparams[k[len(ith):]] = v
        elif k.startswith(plugin.name):
            thisparams[k[len(plugin.name) + 1:]] = v
        elif k not in thisparams:
            thisparams[k] = v
    return thisparams


def resizeAllSections(header, sectionSize):
    """ Sets all sections (columns or rows) of a header to the same section size.

        :param header: a QHeaderView
        :param sectionSize: the new size of the header section in pixels
    """
    for idx in range(header.length()):
        header.resizeSection(idx, sectionSize)


@classmethod
def _build_signal(cls, key, value):
    """
        Builds the signal structure.  A signal should be a dict in the format
        {<key>: <bool>}
        """
    return {key: value}


def optmatch(pattern, match):
    """
    Easier argument specs than argparse

    >>> optmatch("l?ist|ls", "lis")
    True
    >>> optmatch("l?ist|ls", "ls")
    True
    >>> optmatch("l?ist|ls", "l")
    True
    >>> optmatch("l?ist|ls", "loo")
    False
    """
    match = str(match).lower().split('=', 1)[0]
    for variant in pattern.split('|'):
        req, opt = (variant + '?').split('?')[0:2]
        if req == match:
            return True
        for char in opt:
            req = req + char
            if req == match:
                return True
    return False


@classmethod
def get_name(cls):
    """Name of the representation or differential.

        In lower case, with any trailing 'representation' or 'differential'
        removed. (E.g., 'spherical' for
        `~astropy.coordinates.SphericalRepresentation` or
        `~astropy.coordinates.SphericalDifferential`.)
        """
    name = cls.__name__.lower()
    if name.endswith('representation'):
        name = name[:-14]
    elif name.endswith('differential'):
        name = name[:-12]
    return name


def track_markers(backwards: bool=False, sequence: bool=False):
    """Track selected markers

    :param backwards: Backwards, Do backwards tracking
    :type backwards: bool
    :param sequence: Track Sequence, Track marker during image sequence rather than single image
    :type sequence: bool
    """
    pass


def set_format(fmt):
    """
    Set the log format

    :param string fmt: "json" or "text"
    """


def intersect(r1, z1, r2, z2, closed1=True, closed2=True):
    """Test if two polynomials intersect. The polynomials consist of
    (r1, z1) and (r2, z2) line segments. All inputs are expected to be lists.

    Returns True or False.
    """
    assert len(r1) == len(z1)
    assert len(r2) == len(z2)
    n1 = len(r1) if closed1 else len(r1) - 1
    n2 = len(r2) if closed2 else len(r2) - 1
    for i in range(n1):
        for j in range(n2):
            ip = (i + 1) % n1
            jp = (j + 1) % n2
            a = r1[ip] - r1[i]
            b = r2[jp] - r2[j]
            c = z1[ip] - z1[i]
            d = z2[jp] - z2[j]
            dr = r2[jp] - r1[i]
            dz = z2[jp] - z1[i]
            det = a * d - b * c
            if abs(det) < 1e-06:
                continue
            alpha = (d * dr - b * dz) / det
            beta = (a * dz - c * dr) / det
            if (alpha > 0.0) & (alpha < 1.0) & (beta > 0.0) & (beta < 1.0):
                return True
    return False


def get_http_status_code_value(status_code):
    """Py2/3 status code."""
    if hasattr(status_code, 'value'):
        return status_code.value
    else:
        return status_code


def make_range(x, set_zero_index=False):
    """Making a range from a string of comma-delimited and hyphenated number strings.
    If x = 'all', None returned
    x : string
    set_zero_index : change from 1-index to 0-index
    Example: 1,2,3,4
    Example: 1,2,5-6
    """
    x = str(x)
    if x.lower() == 'all':
        return None
    y = str(x).split(',')
    z = []
    for i in y:
        j = [int(x) for x in i.split('-')]
        if len(j) > 1:
            z = z + list(range(j[0], j[1] + 1))
        else:
            z = z + j
    if set_zero_index:
        z = [(x - 1) for x in z]
        if min(z) < 0:
            raise ValueError('Negative values from setting zero index')
    return z


def normalize_word(w: str) ->str:
    """Normalize word by uppering cases."""
    return w.upper()


def selectCiphers(availableCiphers):
    """
        Choose which ciphers to allow to be negotiated on a TLS connection.

        @param availableCiphers: A L{list} of L{ICipher} which gives the names
            of all ciphers supported by the TLS implementation in use.

        @return: A L{list} of L{ICipher} which represents the ciphers
            which may be negotiated on the TLS connection.  The result is
            ordered by preference with more preferred ciphers appearing
            earlier.
        """


def addGroup(segments, group, permissions):
    """
        Add `group` to file/folder at `segments` using `permissions`.

        On Unix it will replace the current group and
        is equivalent to setGroup.
        """


@classmethod
def get(cls, session, parent=None):
    """Gets all of the Clusters from the APIC.

        :returns: Instance of Cluster class.
        """
    infra_query_url = '/api/node/class/infraCont.json'
    ret = session.get(infra_query_url)
    cluster_info = ret.json()['imdata']
    infra_cluster_url = '/api/node/class/infraClusterPol.json'
    ret = session.get(infra_cluster_url)
    ret_cluster = ret.json()['imdata']
    cluster = cls('apic-cluster', parent=parent)
    cluster.config_size = ret_cluster[0]['infraClusterPol']['attributes'][
        'size']
    for apic in cluster_info:
        cluster.apics.append(apic['infraCont']['attributes']['dn'])
    cluster._populate_from_attributes(cluster_info[0]['infraCont'][
        'attributes'])
    return cluster


def discrete_binary_search(tab, lo, hi):
    """Binary search in a table

    :param tab: boolean monotone table with tab[hi] = True
    :param int lo:
    :param int hi: with hi >= lo
    :returns: first index i in [lo,hi] such that tab[i]
    :complexity: `O(log(hi-lo))`
    """
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if tab[mid]:
            hi = mid
        else:
            lo = mid + 1
    return lo


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['action']
    if type == 'ADD_HTTP_REQUEST_HEADER':
        return 'AddHttpRequestHeaderRule'
    if type == 'REDIRECT':
        return 'RedirectRule'
    if type == 'REMOVE_HTTP_REQUEST_HEADER':
        return 'RemoveHttpRequestHeaderRule'
    if type == 'EXTEND_HTTP_REQUEST_HEADER_VALUE':
        return 'ExtendHttpRequestHeaderValueRule'
    if type == 'REMOVE_HTTP_RESPONSE_HEADER':
        return 'RemoveHttpResponseHeaderRule'
    if type == 'CONTROL_ACCESS_USING_HTTP_METHODS':
        return 'ControlAccessUsingHttpMethodsRule'
    if type == 'ALLOW':
        return 'AllowRule'
    if type == 'ADD_HTTP_RESPONSE_HEADER':
        return 'AddHttpResponseHeaderRule'
    if type == 'EXTEND_HTTP_RESPONSE_HEADER_VALUE':
        return 'ExtendHttpResponseHeaderValueRule'
    else:
        return 'Rule'


def _parse_osl(root, parser):
    """Assemble Python dictionaries of groups from XML document"""
    if root.findtext('Succeeded') == 'false':
        error_reason = root.findtext('Reason', default='unknown reason')
        raise Exception('Lookup failed: ' + error_reason)
    return parser(root)


@classmethod
def get_payable(cls) ->list:
    """
        Returns list of statuses from which an order is eligible for payment.
        """
    return []


def origins(distribution):
    """
    Return all origins for a distribution.
    """
    return distribution['Origins']['Items']


def truncate(string, chars_number):
    """
    Truncates a string to the 'chars_number' character.
    """
    return string[:chars_number] + '..' if len(string
        ) > chars_number else string


def rzpad(value, total_length):
    " Right zero pad value `x` at least to length `l`.\n\n    >>> zpad('', 1)\n    '\x00'\n    >>> zpad('Êþ', 4)\n    'Êþ\x00\x00'\n    >>> zpad('ÿ', 1)\n    'ÿ'\n    >>> zpad('Êþ', 2)\n    'Êþ'\n    "
    return value + b'\x00' * max(0, total_length - len(value))


@classmethod
def get(cls, project_id, model_id):
    """
        Retrieve the prediction explanations initialization for a model.

        Prediction explanations initializations are a prerequisite for computing prediction
        explanations, and include a sample what the computed prediction explanations for a
        prediction dataset would look like.

        Parameters
        ----------
        project_id : str
            id of the project the model belongs to
        model_id : str
            id of the model the prediction explanations initialization is for

        Returns
        -------
        prediction_explanations_initialization : PredictionExplanationsInitialization
            The queried instance.

        Raises
        ------
        ClientError (404)
            If the project or model does not exist or the initialization has not been computed.
        """
    path = cls._path_template.format(project_id, model_id)
    return cls.from_location(path)


def setReplyTo(reply_to):
    """ Make this object a response to the passed object.

        o 'reply_to' is an IDiscussable, or a path (as a string) to one.

        o Raise ValueError if 'reply_to' is not an IDiscussable (or doesn't
          resolve to one as a path).

        o XXX This does not seem like the right exception.

        o Permission: None assigned
        """


def EscapeDelimiters(s):
    """
    Changes ``;`` into ``\\`` and ``|`` into ``\\|`` in the input string.

    :param string `s`: the string to be analyzed.

    :note: This is an internal functions which is used for saving perspectives.
    """
    result = s.replace(';', '\\')
    result = result.replace('|', '|\\')
    return result


@classmethod
def deserialize(cls, serialized):
    """Deserializes the layer from the Protobuf format.
        """
    raise NotImplementedError


def _is_method_shortcut(key):
    """Is this test key indicating a request method.

    It is a request method if it is all upper case.
    """
    return key.isupper()


@classmethod
def run(cls, *arguments):
    """Reference implementation of the function."""
    raise NotImplementedError()


def get_unique_3grams(string):
    """ Return the set of different tri-grams in a string
    """
    string = '  ' + string + '  '
    return set(zip(string, string[1:], string[2:]))


def _show(config_dictionary, msg):
    """
    Print a message on the screen
    :param config_dictionary: configuration dictionary
    :param msg: message to print
    """
    if 'quiet' not in config_dictionary or config_dictionary['quiet'].lower(
        ) != 'true':
        print(msg)


def floating_point(v):
    """ Is arg a floating point number ? """
    return isinstance(v, float)


def get_body_region(defined):
    """Return the start and end offsets of function body"""
    scope = defined.get_scope()
    pymodule = defined.get_module()
    lines = pymodule.lines
    node = defined.get_ast()
    start_line = node.lineno
    if defined.get_doc() is None:
        start_line = node.body[0].lineno
    elif len(node.body) > 1:
        start_line = node.body[1].lineno
    start = lines.get_line_start(start_line)
    scope_start = pymodule.logical_lines.logical_line_in(scope.start)
    if scope_start[1] >= start_line:
        start = pymodule.source_code.index(':', start) + 1
        while pymodule.source_code[start].isspace():
            start += 1
    end = min(lines.get_line_end(scope.end) + 1, len(pymodule.source_code))
    return start, end


def pos_ricc_lrcf_solver_options():
    """Return available positive Riccati solvers with default options for the SciPy backend.

    Returns
    -------
    A dict of available solvers with default solver options.
    """
    return {'scipy': {'type': 'scipy'}}


def get_close_edges(edges, nids_close):
    """this seems like it could be a lot faster"""
    close_edges = []
    for edge in edges:
        n1, n2 = edge
        if n1 not in nids_close and n2 not in nids_close:
            continue
        close_edges.append(edge)
    return close_edges


def unassign_volume(VolumeId=None):
    """
    Unassigns an assigned Amazon EBS volume. The volume remains registered with the stack. For more information, see Resource Management .
    See also: AWS API Documentation

    :example: response = client.unassign_volume(
        VolumeId='string'
    )

    :type VolumeId: string
    :param VolumeId: [REQUIRED]
            The volume ID.

    """
    pass


def set_workflow(ctype_or_obj, workflow):
    """Sets the workflow for passed content type or object. See the specific
    methods for more information.

    **Parameters:**

    workflow
        The workflow which should be set to the object or model.

    ctype_or_obj
        The content type or the object to which the passed workflow should be
        set. Can be either a ContentType instance or any Django model
        instance.
    """
    return workflow.set_to(ctype_or_obj)


@classmethod
def header_hash(cls, header):
    """Given a header return the hash."""
    return cls.HEADER_HASH(header)


def get_records_iex(*args, **kwargs):
    """
    Returns the record value, record date, recent value, and 30-day average for
    market volume, # of symbols traded, # of routed trades and notional value.
    This function accepts no additional parameters.

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

    :return: DataFrame
    """
    from pandas_datareader.iex.stats import RecordsReader
    return RecordsReader(*args, **kwargs).read()


def identity(val):
    """Returns the value it is given."""
    return val


def __setitem__(oid_tid, state_bytes_tid):
    """
        Store the *state_bytes_tid* (``(state_bytes, tid_int)``) for
        the ``(oid, tid)`` pair.

        Note that it does not necessarily mean that the key tid
        matches the value tid.

        Also note that if the object has been deleted, ``state_bytes``
        may be `None`.
        """


def parse(fasta):
    """Parse an open FASTA file for sequences.

    For example, given a FASTA file `fasta.faa` containing:

    ::
        >sequence
        ACGTACGTACGT

    This file can be parsed:

    >>> with open('fasta.faa') as handle:
    ...     parse_fasta(handle)
    {"sequence": "ACGTACGTACGT"}

    Parameters
    ----------
    fasta : str
        Either an open file handle of a FASTA file, or newline split string (e.g. read
        in via readlines()) that can be iterated over.

    Returns
    -------
    sequences : dict
        Sequences in the FASTA file, keyed on sequence headers.
    """
    sequences = {}
    for line in fasta:
        try:
            line = line.decode().strip()
        except AttributeError:
            line = line.strip()
        if line.startswith('>'):
            header = line[1:]
            sequences[header] = ''
        else:
            sequences[header] += line
    return sequences


@staticmethod
def clean_option_variable(option_variable, inverse=False):
    """
        Convert option variable between UI and python format
        :param option_variable: option available for edit user settings UI
        :type option_variable: str
        :param inverse: True to return python format, False to return UI format
        :type inverse: bool
        :return: formatted option variable
        :rtype: str
        """
    if inverse:
        return option_variable.upper().replace(' ', '_')
    else:
        return option_variable.replace('_', ' ').title().replace('Dvh', 'DVH'
            ).replace('Iqr', 'IQR')


def get_value(token):
    """Return a value for a given identifier token

        LookupError is raised if there isn't a value in the source.
        """


def view_selected():
    """Reset viewable area to show selected keyframes range

    """
    pass


@staticmethod
def _next(stream_obj):
    """
        从流中获取下一个对象，并将流指针指向下一个位置

        @param {object} stream_obj - _init_stream生成的流对象

        @returns {string} - 获取到的下一个位置的字符

        @throws {StopIteration} - 如果到了流结尾，抛出该异常

        """
    if stream_obj.pos + 1 > len(stream_obj.obj):
        raise StopIteration
    stream_obj.pos = stream_obj.pos + 1
    return stream_obj.obj[stream_obj.pos - 1:stream_obj.pos]


def retrieve(obj, selector=None, preserve=(), countPurged=True):
    """Returns a former version of a content without replacing the working
        copy.

        It returns an ``IVersionData`` object and doesn't modify the working
        copy in any way.

        Also counts purged versions if ``True`` is passed to ``countPurged``
        (see interface documentation for details).
        """


@staticmethod
def _check_type(term):
    """Check type of input term, and return as a list.

        Parameters
        ----------
        term : str OR list of str
            New term to add to the object.

        Returns
        -------
        list of str
            New term, set as a list.
        """
    if isinstance(term, str):
        return [term]
    elif isinstance(term, list):
        return term


@classmethod
def call_(cls, name, *args, **kwargs):
    """Call a named API function with positional and keyword arguments.

    Args:
      name: The name of the API function to call.
      *args: Positional arguments to pass to the function.
      **kwargs: Keyword arguments to pass to the function.

    Returns:
      An object representing the called function. If the signature specifies
      a recognized return type, the returned value will be cast to that type.
    """
    return cls.lookup(name).call(*args, **kwargs)


def __new__(mcs, __name__, __bases__, __dict__):
    """Add include constructer to class."""
    cls = mcs.__class__.__new__(mcs, __name__, __bases__, __dict__)
    cls.add_constructor('!include', cls.construct_include)
    return cls


def _collect_column_constraints(column, unique):
    """
    Collect constraints for a column.

    Use column information as well as unique constraint information.
    Note: for a unique constraint on a single column we set
          column / constraints / unique = True
          (and store all multicolumn uniques in the table realm)
    """
    res = {}
    if 'null' in column:
        res['required'] = column['null']
    for constr_i, constr in enumerate(unique):
        if column['column_name'] in constr['fields']:
            if len(constr['fields']) == 1:
                res['unique'] = True
    return res


@classmethod
def read(cls, five9, external_id):
    """Return a record singleton for the ID.

        Args:
            five9 (five9.Five9): The authenticated Five9 remote.
            external_id (mixed): The identified on Five9. This should be the
                value that is in the ``__uid_field__`` field on the record.

        Returns:
            BaseModel: The record, if found. Otherwise ``None``
        """
    results = cls.search(five9, {cls.__uid_field__: external_id})
    if not results:
        return None
    return results[0]


def identityfunc(arg, *args, **kwargs):
    """Single argument identity function.

    >>> identityfunc('arg')
    'arg'

    """
    return arg


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 properties():
    """Toggle the properties region visibility

    """
    pass


def get_types(path=''):
    """
        get_types returns a list of addable types for a given context.
        """


def update_gateway_information(GatewayARN=None, GatewayName=None,
    GatewayTimezone=None):
    """
    Updates a gateway's metadata, which includes the gateway's name and time zone. To specify which gateway to update, use the Amazon Resource Name (ARN) of the gateway in your request.
    See also: AWS API Documentation

    Examples
    Updates a gateway's metadata, which includes the gateway's name and time zone.
    Expected Output:

    :example: response = client.update_gateway_information(
        GatewayARN='string',
        GatewayName='string',
        GatewayTimezone='string'
    )

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation to return a list of gateways for your account and region.

    :type GatewayName: string
    :param GatewayName: The name you configured for your gateway.

    :type GatewayTimezone: string
    :param GatewayTimezone:

    :rtype: dict
    :return: {
        'GatewayARN': 'string',
        'GatewayName': 'string'
    }

    """
    pass


@staticmethod
def func_substitute(header, lines):
    """Returns modified lines and whether string changed.

        Keyword arguments:
        header -- Header object
        lines -- file contents string

        Returns modified file contents string
        """
    pos = 0
    while pos < len(lines):
        old_length = len(lines)
        match = header.func_regex.search(lines, pos)
        if not match:
            break
        pos = match.start(1) + len(header.prefix) + len(match.group(1))
        if match.group(1) in header.func_names:
            lines = lines[0:match.start(1)] + header.prefix + match.group(1
                ) + lines[match.end(1):]
    return lines


@staticmethod
def __resolve_depends_on_one_req_master(req):
    """For the master requirement there must be no depends on."""
    if 'Depends on' in req.brmo:
        print('+++ ERROR %s: initial requirement has Depends on field.' %
            req.get_id())
        return False
    req.graph_depends_on = None
    return True


def batch(iterable, n=1):
    """
    "batch" function that would take as input an iterable and return an iterable of iterables
    https://stackoverflow.com/a/8290508/6753144
    """
    len_ = len(iterable)
    for ndx in range(0, len_, n):
        yield iterable[ndx:min(ndx + n, len_)]


def get_preactivation_tensors(layers):
    """Get all valid layers for computing saturation."""
    dense_outputs = []
    for layer in layers:
        if 'dense' in layer.name:
            if '_input' in layer.name:
                continue
            if hasattr(layer, 'activation'
                ) and layer.activation.__name__ != 'linear':
                preactivation_tensor = layer.output.op.inputs[0]
            else:
                preactivation_tensor = layer.output
            dense_outputs.append(preactivation_tensor)
    return dense_outputs


def recurse_kwargs_list(parameter_name, class_name, **kwargs):
    """
    Recurses through a list of kwargs.
    """
    if parameter_name in kwargs:
        parameter_list = kwargs.get(parameter_name)
        param_list = []
        for parameter in parameter_list:
            param_list.append(class_name(**parameter))
        return param_list
    else:
        pass


def is_header(line, name):
    """only the first 4 chancters are read, but we're going to ensure all the letters are correct"""
    return line.startswith(name[:4]) and line == name[:len(line)]


@classmethod
def _inContext(cls, adaptor, tokenNames, t, context):
    """The worker for inContext.

        It's static and full of parameters for testing purposes.
        """
    if cls.dotdotPattern.match(context):
        raise ValueError('invalid syntax: ..')
    if cls.doubleEtcPattern.match(context):
        raise ValueError('invalid syntax: ... ...')
    context = context.replace('...', ' ... ')
    context = context.strip()
    nodes = context.split()
    ni = len(nodes) - 1
    t = adaptor.getParent(t)
    while ni >= 0 and t is not None:
        if nodes[ni] == '...':
            if ni == 0:
                return True
            goal = nodes[ni - 1]
            ancestor = cls._getAncestor(adaptor, tokenNames, t, goal)
            if ancestor is None:
                return False
            t = ancestor
            ni -= 1
        name = tokenNames[adaptor.getType(t)]
        if name != nodes[ni]:
            return False
        ni -= 1
        t = adaptor.getParent(t)
    if t is None and ni >= 0:
        return False
    return True


def scene_style(string):
    """
    Return given string in scene style.
    WIth spaces replaced with '.' and lowercase.
    """
    if string is None:
        return
    return '.'.join(string.split())


def _check_chn_type(channels, available_channels):
    """
    Function used for checking weather the elements in "channels" input are coincident with the
    available channels.

    ----------
    Parameters
    ----------
    channels : list [[mac_address_1_channel_1 <int>, mac_address_1_channel_2 <int>...],
                    [mac_address_2_channel_1 <int>...]...]
        From which channels will the data be loaded.

    available_channels : dict
        Dictionary with the list of all the available channels per device.

    Returns
    -------
    out : list
        It is returned a list of the selected channels in a standardized format.

    """
    chn_list_standardized = []
    devices = list(available_channels.keys())
    for dev_nbr, device in enumerate(devices):
        if channels is not None:
            sub_unit = channels[dev_nbr]
            for channel in sub_unit:
                if channel in available_channels[devices[dev_nbr]]:
                    continue
                else:
                    raise RuntimeError(
                        'At least one of the specified channels is not available in the acquisition file.'
                        )
            chn_list_standardized.append(sub_unit)
        else:
            chn_list_standardized.append(available_channels[device])
    return chn_list_standardized


def c_sum32(*args):
    """
    Add all elements of *args* within the uint32 value range.

    >>> c_sum32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)
    4294967293
    """
    return sum(args) & 4294967295


def _get_norb_nel(oe):
    """Return number of orbitals and electrons.

    Parameters
    ----------
    oe : list
         The orbital occupation numbers and energies read with
         ``_read_cp2k_occupations_energies``.
    """
    norb = 0
    nel = 0
    for row in oe:
        norb += 2 * row[0] + 1
        nel += row[2]
    return norb, nel


@classmethod
def build_batch(cls, size, **kwargs):
    """Build a batch of instances of the given class, with overriden attrs.

        Args:
            size (int): the number of instances to build

        Returns:
            object list: the built instances
        """
    return [cls.build(**kwargs) for _ in range(size)]


def read_uic3tag(fh, byteorder, dtype, planecount, offsetsize):
    """Read MetaMorph STK UIC3Tag from file and return as dict."""
    assert dtype == '2I' and byteorder == '<'
    values = fh.read_array('<u4', 2 * planecount).reshape(planecount, 2)
    return {'Wavelengths': values[:, (0)] / values[:, (1)]}


def remove_hidden(names):
    """Remove (in-place) all strings starting with a '.' in the given list."""
    i = 0
    while i < len(names):
        if names[i].startswith('.'):
            names.pop(i)
        else:
            i += 1
    return names


def nrmse(ref_im, test_ims):
    """
    Euclidean normalised mean square error.

    Parameters
    ----------
    ref_im : 2-D array
        Reference image.
    test_ims : ndarray
        Images to compare.

    """
    im1 = ref_im.astype(float)
    im2 = test_ims.astype(float)
    n = (((im1 - im2) ** 2).mean((-2, -1)) / ((im1 ** 2 + im2 ** 2).mean((-
        2, -1)) / 2)) ** 0.5
    return n


def list_tests(arn=None, nextToken=None):
    """
    Gets information about tests.
    See also: AWS API Documentation

    Examples
    The following example returns information about tests, given a specific Device Farm project.
    Expected Output:

    :example: response = client.list_tests(
        arn='string',
        nextToken='string'
    )

    :type arn: string
    :param arn: [REQUIRED]
            The tests' ARNs.

    :type nextToken: string
    :param nextToken: An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

    :rtype: dict
    :return: {
        'tests': [
            {
                'arn': 'string',
                'name': 'string',
                'type': 'BUILTIN_FUZZ'|'BUILTIN_EXPLORER'|'APPIUM_JAVA_JUNIT'|'APPIUM_JAVA_TESTNG'|'APPIUM_PYTHON'|'APPIUM_WEB_JAVA_JUNIT'|'APPIUM_WEB_JAVA_TESTNG'|'APPIUM_WEB_PYTHON'|'CALABASH'|'INSTRUMENTATION'|'UIAUTOMATION'|'UIAUTOMATOR'|'XCTEST'|'XCTEST_UI',
                'created': datetime(2015, 1, 1),
                'status': 'PENDING'|'PENDING_CONCURRENCY'|'PENDING_DEVICE'|'PROCESSING'|'SCHEDULING'|'PREPARING'|'RUNNING'|'COMPLETED'|'STOPPING',
                'result': 'PENDING'|'PASSED'|'WARNED'|'FAILED'|'SKIPPED'|'ERRORED'|'STOPPED',
                'started': datetime(2015, 1, 1),
                'stopped': datetime(2015, 1, 1),
                'counters': {
                    'total': 123,
                    'passed': 123,
                    'failed': 123,
                    'warned': 123,
                    'errored': 123,
                    'stopped': 123,
                    'skipped': 123
                },
                'message': 'string',
                'deviceMinutes': {
                    'total': 123.0,
                    'metered': 123.0,
                    'unmetered': 123.0
                }
            },
        ],
        'nextToken': 'string'
    }

    :returns:
    BUILTIN_FUZZ: The built-in fuzz type.
    BUILTIN_EXPLORER: For Android, an app explorer that will traverse an Android app, interacting with it and capturing screenshots at the same time.
    APPIUM_JAVA_JUNIT: The Appium Java JUnit type.
    APPIUM_JAVA_TESTNG: The Appium Java TestNG type.
    APPIUM_PYTHON: The Appium Python type.
    APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps.
    APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps.
    APPIUM_WEB_PYTHON: The Appium Python type for Web apps.
    CALABASH: The Calabash type.
    INSTRUMENTATION: The Instrumentation type.
    UIAUTOMATION: The uiautomation type.
    UIAUTOMATOR: The uiautomator type.
    XCTEST: The XCode test type.
    XCTEST_UI: The XCode UI test type.

    """
    pass


@classmethod
def first_or_new(cls, **attributes):
    """
        Get the first record matching the attributes or instantiate it.

        :param attributes: The instance attributes
        :type attributes: dict

        :return: The new instance
        :rtype: Model
        """
    instance = cls().new_query_without_scopes().where(attributes).first()
    if instance is not None:
        return instance
    return cls(**attributes)


def get_coordinates(lines):
    """Returns list of coordinates.
    """
    coords = []
    for l in lines:
        if l.startswith('] def'):
            break
        elif l.startswith('['):
            coords.append(map(float, l.strip('\n[]').split()))
    return coords


@staticmethod
def _filter(ftype):
    """
        Internal function to generate text string for setting up default files.
        """
    if ftype == '*':
        return 'AllFiles (*)'
    if ftype == 'dicom':
        return 'Dicom Files (*.dcm, *.ima)'
    if ftype == 'ctx':
        return 'CtxCube Files (*.ctx)'
    if ftype == 'hed':
        return 'Header Files (*.hed)'
    if ftype == 'dos':
        return 'DosCube Files (*.dos)'
    if ftype == 'let':
        return 'LETCube Files (*.dosemlet.dos)'
    return 'AllFiles (*)'


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


def FREQ_COUNT(src_column):
    """
  Builtin frequency counts for groupby. Returns a dictionary where the key is
  the `src_column` and the value is the number of times each value occurs.

  >>> sf.groupby("user",
  ...       {'rating_distinct':gl.aggregate.FREQ_COUNT('rating')})

  """
    return '__builtin__freq_count__', [src_column]


@staticmethod
def _store_map_from_type(item_type):
    """
        Return a list with the name of the workstep store corresponding to the item type give.
        :param item_type: The string type of the item. If 'all' all stores will be returned
        :return: str store name, for all item_types except 'all'. If item_type == 'all', a tuple of all the store
        names. If item_type is not recognized, returns None.
        """
    if not item_type or not isinstance(item_type, str):
        return None
    if 'Signal' in item_type:
        return 'sqTrendSeriesStore'
    if 'Condition' in item_type:
        return 'sqTrendCapsuleSetStore'
    if 'Scalar' in item_type:
        return 'sqTrendScalarStore'
    if 'Metric' in item_type:
        return 'sqTrendMetricStore'
    if 'Table' in item_type:
        return 'sqTrendTableStore'
    if item_type == 'all':
        return ('sqTrendSeriesStore', 'sqTrendCapsuleSetStore',
            'sqTrendScalarStore', 'sqTrendMetricStore', 'sqTrendTableStore')
    else:
        return None


@classmethod
def tearDownClass(cls):
    """Hook method for deconstructing the class fixture after running all tests in the class."""


def extrude_faces_indiv(mirror: bool=False):
    """Extrude individual faces only

    :param mirror: Mirror Editing
    :type mirror: bool
    """
    pass


def get_component_registry():
    """Returns the site manager contained in this object.

        If there isn't a site manager, raise a component lookup.
        """


def tupleize(obj):
    """
    Converts into or wraps in a tuple.

    If `obj` is an iterable object other than a `str`, converts it to a `tuple`.

      >>> tupleize((1, 2, 3))
      (1, 2, 3)
      >>> tupleize([1, 2, 3])
      (1, 2, 3)
      >>> tupleize(range(1, 4))
      (1, 2, 3)

    Otherwise, wraps `obj` in a one-element `tuple`.

      >>> tupleize(42)
      (42,)
      >>> tupleize(None)
      (None,)
      >>> tupleize("Hello, world!")
      ('Hello, world!',)

    @type obj
      Any.
    @rtype
      `tuple`.
    """
    if isinstance(obj, str):
        return obj,
    else:
        try:
            return tuple(obj)
        except:
            return obj,


def order_tuple(toOrder):
    """
    Given a tuple (a, b), returns (a, b) if a <= b,
    else (b, a).
    """
    if toOrder[0] <= toOrder[1]:
        return toOrder
    return toOrder[1], toOrder[0]