def parse_children_using_function(parent, parse_function, tag=None):
    """
    Find and parse children using a specified function.

    :param parent: The parent ``Element`` object.
    :param parse_function: A function which accepts an ``Element`` and returns an object.
    :param tag: The tag name of the specific type of child to parse, or None to parse all children.

    :returns: A list of objects.

    """
    children = []
    if tag == None:
        nodes = parent.getchildren()
    else:
        nodes = parent.findall(tag)
    for n in nodes:
        c = parse_function(n)
        if c != None:
            children.append(c)
    return children


def disable_platform_warning():
    """Disable the SSL warnings emitted by urllib3. This is the default
    behavior unless the caller specifically asks for these warnings.

    See https://github.com/smarter-travel-media/warthog/issues/5
    """
    import warnings
    from urllib3.exceptions import InsecurePlatformWarning, SNIMissingWarning
    warnings.filterwarnings('ignore', category=InsecurePlatformWarning)
    warnings.filterwarnings('ignore', category=SNIMissingWarning)


def ffcall(option, obj, vid):
    """
    helper function to choose between 2 function to call i.e. get_description and open_id
    """
    if option == 0:
        des = obj.get_descriptions()
        print(des[vid])
    if option == 1:
        obj.open_id(vid)


def unrelate(*pairs):
    """ Given any number of ``(category_name, discriminator)`` pairs
        passed as positional arguments, unrelate the associated introspectables
        from each other. The introspectable related to each pair must have
        already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
        will result if this is not true.  An error will not be raised if any
        pair is not already related to another.

        This method is not typically called directly, instead it's called
        indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
        """


def _fake(*args):
    """
    Stub function that does nothing
    :param args:
    :return: None
    """
    pass


def get_float_attr(node, attribute, default=None):
    """Cast an element attribute to a float or return None if not present"""
    attr = node.get(attribute)
    return default if attr is None else float(attr)


def height_from_humerus_length(segment_length):
    """
    Calculates body height based on the humerus (shoulder to elbow) length

    args:
        segment_length (float): length of humerus (shoulder to end of elbow)

    Returns:
        float: total body height
    """
    if segment_length <= 0:
        raise ValueError('segment_length must be > 0')
    return segment_length / 0.186


def distanceChangingSpeed(v0, vf, a, TPR):
    """for decelerations, a < 0"""
    return TPR * v0 - (vf ** 2 - v0 ** 2) / (2 * a)


def pytest_match_skip_run_skip_warning(request, message):
    """The warning message when running tests that should be skipped."""
    pass


def vecBetweenBoxes(obj1, obj2):
    """A distance function between two TextBoxes.

    Consider the bounding rectangle for obj1 and obj2.
    Return vector between 2 boxes boundaries if they don't overlap, otherwise returns vector betweeen boxes centers
             +------+..........+ (x1, y1)
             | obj1 |          :
             +------+www+------+
             :          | obj2 |
    (x0, y0) +..........+------+
    """
    x0, y0 = min(obj1.x0, obj2.x0), min(obj1.y0, obj2.y0)
    x1, y1 = max(obj1.x1, obj2.x1), max(obj1.y1, obj2.y1)
    ow, oh = x1 - x0, y1 - y0
    iw, ih = ow - obj1.width - obj2.width, oh - obj1.height - obj2.height
    if iw < 0 and ih < 0:
        xc1, yc1 = (obj1.x0 + obj1.x1) / 2, (obj1.y0 + obj1.y1) / 2
        xc2, yc2 = (obj2.x0 + obj2.x1) / 2, (obj2.y0 + obj2.y1) / 2
        return xc1 - xc2, yc1 - yc2
    else:
        return max(0, iw), max(0, ih)


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


def v112_feodo_tracker_ips(defaults, runtime, harmonization, dry_run):
    """
    Fix URL of feodotracker IPs feed in runtime configuration
    """
    changed = None
    for bot_id, bot in runtime.items():
        if bot['parameters'].get('http_url'
            ) == 'https://feodotracker.abuse.ch/blocklist/?download=ipblocklist':
            bot['parameters']['http_url'
                ] = 'https://feodotracker.abuse.ch/downloads/ipblocklist.csv'
            changed = True
    return changed, defaults, runtime, harmonization


@staticmethod
def only_extracts_articles():
    """
        Meta-Method, so if the heuristic "crawler_contains_only_article_alikes"
        is called, the heuristic will return True on this crawler.
        """
    return True


def cAnisoShrink():
    """
    Return the kernel source of cAnisoShrink
    """
    R = """
    KERNEL void cAnisoShrink(const  float2 threshold,
                                    GLOBAL_MEM const float2 *indata,
                                    GLOBAL_MEM  float2 *outdata)
    {
    const unsigned int gid =  get_global_id(0);
    float2 tmp; // temporay register
    tmp = indata[gid];
    //float zero = 0.0;
    //tmp.x=sign(tmp.x)*max(fabs(tmp.x)-threshold.x, zero);
    //tmp.y=sign(tmp.y)*max(fabs(tmp.y)-threshold.y, zero);
    tmp.x =  (tmp.x > threshold.x)*(tmp.x - threshold.x) ;//+ (tmp.x < - threshold.x)*(tmp.x + threshold.x);
    tmp.y =  (tmp.y > threshold.x)*(tmp.y - threshold.x) ;//+ (tmp.y < - threshold.x)*(tmp.y + threshold.x);
    outdata[gid]=tmp;
    };
    """
    return R


@staticmethod
def __definit(ensemble, fonction, oui):
    """Ajoute ou enleve une fonction d'un ensemble

        :arg set ensemble: Ensemble à manipuler
        :arg func  fonction: Fonction à manipuler
        :arg bool oui: Si `True`, ajoute la fonction; sinon, l'enlève.
        """
    if oui:
        ensemble.add(fonction)
    else:
        ensemble.discard(fonction)


def measure_var_int(number):
    """
	Returns the length of the bytearray returned by encode_var_int().
	"""
    length = 0
    shift = 1
    while True:
        length += 1
        number -= number & 127
        if number == 0:
            break
        number -= shift
        number >>= 7
        shift += 7
    return length


def put(message, when=None, tags=None):
    """
        Поместить новое сообщение в лог.

        @param when: дата/время записи в логе, UTC
        @type when: C{int}
        @param message: само сообщение
        @type message: L{IMessage} или L{ITaggedMessage}
        @param tags: тэги, привзяанные к сообщению
        @type tags: C{list(str)}
        @return: Deferred о завершении операции
        @rtype: C{twisted.internet.defer.Deferred}
        """


def Retrieve():
    """
    Used to request some data from supplier for example.
    """
    return 'Retrieve'


def project_edit():
    """Edit a snapshot of the view-port in an external image editor

    """
    pass


def userauthenticator_factory():
    """
    `userauthenticator_factory` returns a Authenticator class which verifies
    that the connections belongs to a registered user.
    """
    from .authenticators import UserAuthenticator
    return UserAuthenticator


def bake_all(bake: bool=True):
    """Bake all physics

    :param bake: Bake
    :type bake: bool
    """
    pass


def onroot_stop(*args):
    """
    Always stop after finding root
    """
    return 1


@classmethod
def add_common_opts(cls, parser):
    """Add options that are common for several plugins.
        """
    for opt in cls.common_opt_names:
        cls._parser_add_opt(parser, opt)


@classmethod
def _stripe_object_to_tax_rates(cls, target_cls, data):
    """
        Retrieves TaxRates for a SubscriptionItem or InvoiceItem
        :param target_cls:
        :param data:
        :return:
        """
    tax_rates = []
    for tax_rate_data in data.get('tax_rates', []):
        tax_rate, _ = target_cls._get_or_create_from_stripe_object(
            tax_rate_data, refetch=False)
        tax_rates.append(tax_rate)
    return tax_rates


def phi_chain(n):
    """
    For each number in 1 to n, compute the Smolyak indices for the
    corresponding basis functions. This is the :math:`n` in
    :math:`\\phi_n`

    Parameters
    ----------
    n : int
        The last Smolyak index :math:`n` for which the basis polynomial
        indices should be found

    Returns
    -------
    aphi_chain : dict (int -> list)
        A dictionary whose keys are the Smolyak index :math:`n` and
        values are lists containing all basis polynomial subscripts for
        that Smolyak index

    """
    aphi_chain = {}
    aphi_chain[1] = [1]
    aphi_chain[2] = [2, 3]
    curr_val = 4
    for i in range(3, n + 1):
        end_val = 2 ** (i - 1) + 1
        temp = range(curr_val, end_val + 1)
        aphi_chain[i] = temp
        curr_val = end_val + 1
    return aphi_chain


def write_mod2cmd(cmd_file: str, mod_file: str):
    """
    write_mod2cmd(cmd_file, mod_file)

    This function writes the model file to the cmd file

    Parameters
    ----------
    cmd_file: str
        Path to cmd file
    mod_file: str
        Path to model file

    Returns
    -------
    Modified cmd_file including path to model file

    """
    file = open(cmd_file, 'r')
    lines = file.read().splitlines()
    lines[2] = '"{}"                              Velocity model file'.format(
        mod_file)
    file.close()
    file = open(cmd_file, 'w')
    file.write('\n'.join(lines))
    file.close()


def get_query_count() ->int:
    """
        Get number of queries tranaction ran
        """


def search(pattern, sentence, *args, **kwargs):
    """ Returns a list of all matches found in the given sentence.
    """
    return compile(pattern, *args, **kwargs).search(sentence)


def error(*args):
    """
    throw error and exit the program
    """
    header = '[error]\t'
    print(header, *args)
    exit(-1)


def norat2ret(normarr, mean, sigma, yearly=256):
    """Reform array of N(0, 1) normalized RATES into array of RETURNS.
       Arguments mean and sigma should be in decimal form.
       Argument yearly expresses frequency to be obtained.
    """
    meanly = mean / yearly
    sigmaly = sigma / yearly ** 0.5
    retarr = 1 + meanly + sigmaly * normarr
    return retarr


@staticmethod
def hex_to_rgb(hex_string, digits=2):
    """
        Yield RGB values from a hexadecimal string.
        """
    for i in range(1, len(hex_string), digits):
        yield int('0x%s' % hex_string[i:i + digits], 0)


def GetGeneratedFileName(clsid, lcid, major, minor):
    """Given the clsid, lcid, major and  minor for a type lib, return
    the file name (no extension) providing this support.
    """
    return str(clsid).upper()[1:-1] + 'x%sx%sx%s' % (lcid, major, minor)


def validate_not_empty(arg):
    """
    Make sure the string is not empty
    """
    if len(arg) == 0:
        raise ValueError('String cannot be empty')


def describe_jobs(jobs=None):
    """
    Describes a list of AWS Batch jobs.
    See also: AWS API Documentation

    Examples
    This example describes a job with the specified job ID.
    Expected Output:

    :example: response = client.describe_jobs(
        jobs=[
            'string',
        ]
    )

    :type jobs: list
    :param jobs: [REQUIRED]
            A space-separated list of up to 100 job IDs.
            (string) --

    :rtype: dict
    :return: {
        'jobs': [
            {
                'jobName': 'string',
                'jobId': 'string',
                'jobQueue': 'string',
                'status': 'SUBMITTED'|'PENDING'|'RUNNABLE'|'STARTING'|'RUNNING'|'SUCCEEDED'|'FAILED',
                'attempts': [
                    {
                        'container': {
                            'containerInstanceArn': 'string',
                            'taskArn': 'string',
                            'exitCode': 123,
                            'reason': 'string'
                        },
                        'startedAt': 123,
                        'stoppedAt': 123,
                        'statusReason': 'string'
                    },
                ],
                'statusReason': 'string',
                'createdAt': 123,
                'retryStrategy': {
                    'attempts': 123
                },
                'startedAt': 123,
                'stoppedAt': 123,
                'dependsOn': [
                    {
                        'jobId': 'string'
                    },
                ],
                'jobDefinition': 'string',
                'parameters': {
                    'string': 'string'
                },
                'container': {
                    'image': 'string',
                    'vcpus': 123,
                    'memory': 123,
                    'command': [
                        'string',
                    ],
                    'jobRoleArn': 'string',
                    'volumes': [
                        {
                            'host': {
                                'sourcePath': 'string'
                            },
                            'name': 'string'
                        },
                    ],
                    'environment': [
                        {
                            'name': 'string',
                            'value': 'string'
                        },
                    ],
                    'mountPoints': [
                        {
                            'containerPath': 'string',
                            'readOnly': True|False,
                            'sourceVolume': 'string'
                        },
                    ],
                    'readonlyRootFilesystem': True|False,
                    'ulimits': [
                        {
                            'hardLimit': 123,
                            'name': 'string',
                            'softLimit': 123
                        },
                    ],
                    'privileged': True|False,
                    'user': 'string',
                    'exitCode': 123,
                    'reason': 'string',
                    'containerInstanceArn': 'string',
                    'taskArn': 'string'
                }
            },
        ]
    }

    :returns:
    (string) --
    (string) --

    """
    pass


def constraint(value):
    """Check a customized constraint on the value.

        You can implement this method with your Field to
        require a certain constraint.  This relaxes the need
        to inherit/subclass a Field you to add a simple constraint.
        Returns true if the given value is within the Field's constraint.
        """


@classmethod
def set_global(cls, name, value):
    """ Set value for a global attribute

        :param name: Name of the attribute
        :type name: str
        :param name: Value of the attribute
        :type name: str
        """
    global_attr = cls._attributes[name]
    global_attr.value = value
    return value


def gen_url_name(resource):
    """ URL name for resource class generator. """
    if resource._meta.parent:
        yield resource._meta.parent._meta.url_name
    if resource._meta.prefix:
        yield resource._meta.prefix
    for p in resource._meta.url_params:
        yield p
    yield resource._meta.name


def compute_epsg(lon, lat):
    """
    Compute the EPSG code of the UTM zone which contains
    the point with given longitude and latitude

    Args:
        lon (float): longitude of the point
        lat (float): latitude of the point

    Returns:
        int: EPSG code
    """
    zone = int((lon + 180) // 6 + 1)
    const = 32600 if lat > 0 else 32700
    return const + zone


def _check_large_sparse(X, accept_large_sparse=False):
    """Raise a ValueError if X has 64bit indices and accept_large_sparse=False
    """
    if not accept_large_sparse:
        supported_indices = ['int32']
        if X.getformat() == 'coo':
            index_keys = ['col', 'row']
        elif X.getformat() in ['csr', 'csc', 'bsr']:
            index_keys = ['indices', 'indptr']
        else:
            return
        for key in index_keys:
            indices_datatype = getattr(X, key).dtype
            if indices_datatype not in supported_indices:
                raise ValueError(
                    'Only sparse matrices with 32-bit integer indices are accepted. Got %s indices.'
                     % indices_datatype)


def get_num_length(num):
    """Returns the number of characters contained in num
    :param num: an integer number
    :return: number of characters in num
    """
    if type(num) == int:
        return len(str(num))
    else:
        print('Number is not an Int. Length will include the decimal')
        return len(str(num))


@staticmethod
def nabs_process(obs, pred):
    """
        This function performs a origin shift operation by translating
        obs and pred so that the end-point of each trajectory in the obs
        variable is at the origin. This operation has been reported
        to improve the trajectory prediction result in the SR-LSTM paper.
        Note that this function should be applied only to the trajectories
        in the test set.

        :param obs: The observed part of the trajectories. Must be an
               Ntrajectories x Nobs_time_step x 2 numpy array.
        :param pred: The predicted part of the trajectories. Must be an
               Ntrajectories x Npred_time_step x 2 numpy array.
        :return obs_data, pred_data: the new trajectories of the same
                size.
        """
    last_obs_pts = obs[:, (-1), :].reshape(-1, 1, 2)
    obs_data = obs - last_obs_pts
    pred_data = pred - last_obs_pts
    return obs_data, pred_data


def reclaimNetworkResources(chute):
    """
    Reclaim network resources for a previously running chute.

    This function only applies to the special case in which pd starts up and
    loads a list of chutes that were running.  This function marks their IP
    addresses and interface names as taken so that new chutes will not use the
    same values.
    """
    pass


def items(key=None):
    """Return an iterator over the key-value pairs in the container.

        If ``None`` is passed as `key`, this method behaves as if no argument
        were passed; exactly as required for ``IContainer.items()``.

        If `key` is in the container, the first item provided by the iterator
        will correspond to that key.  Otherwise, the first item will be for
        the key that would come next if `key` were in the container.
        """


@classmethod
def schema(cls):
    """Return a json-schema for the plugin's properties as a dictionary.
        Of importance to plugin authors is the 'properties' keyword and
        optionally the 'requires' keyword with a list of required
        'properties'.

        By default the properties will be that of a standard VCS,
        override in custom implementations if required.
        """
    return {'$schema': 'http://json-schema.org/draft-04/schema#', 'type':
        'object', 'additionalProperties': False, 'properties': {}}


def geobox_from_points(points):
    """Given a list of points, flatten them starting from y and going to x.

    This function exists because for some reason Tweepy/Twitter API likes to
    have a bounding box with flipped lat/long coordinates.

    Example:
        `flatten_points([Point(x=1,y=2), Point(x=2,y=3)])`
        -->
        `[2, 1, 3, 2]`"""
    numbers = []
    for point in points:
        numbers.append(point.y)
        numbers.append(point.x)
    return numbers


def thomassenMelodicAccent(streamIn):
    """
    adds a attribute melodicAccent to each note of a :class:`~music21.stream.Stream` object
    according to the method postulated in Joseph M. Thomassen, "Melodic accent: Experiments and
    a tentative model," ''Journal of the Acoustical Society of America'', Vol. 71, No. 6 (1982) pp.
    1598-1605; with, Erratum, ''Journal of the Acoustical Society of America'', Vol. 73,
    No. 1 (1983) p.373, and in David Huron and Matthew Royal,
    "What is melodic accent? Converging evidence
    from musical practice." ''Music Perception'', Vol. 13, No. 4 (1996) pp. 489-516.

    Similar to the humdrum melac_ tool.

    .. _melac: http://www.music-cog.ohio-state.edu/Humdrum/commands/melac.html

    Takes in a Stream of :class:`~music21.note.Note` objects (use `.flat.notes` to get it, or
    better `.flat.getElementsByClass('Note')` to filter out chords) and adds the attribute to
    each.  Note that Huron and Royal's work suggests that melodic accent has a correlation
    with metrical accent only for solo works/passages; even treble passages do not have a
    strong correlation. (Gregorian chants were found to have a strong ''negative'' correlation
    between melodic accent and syllable onsets)

    Following Huron's lead, we assign a `melodicAccent` of 1.0 to the first note in a piece
    and take the accent marker of the first interval alone to the second note and
    of the last interval alone to be the accent of the last note.

    Example from Thomassen, figure 5:

    >>> s = converter.parse('tinynotation: 7/4 c4 c c d e d d')
    >>> analysis.metrical.thomassenMelodicAccent(s.flat.notes)
    >>> for n in s.flat.notes:
    ...    (n.pitch.nameWithOctave, n.melodicAccent)
    ('C4', 1.0)
    ('C4', 0.0)
    ('C4', 0.0)
    ('D4', 0.33)
    ('E4', 0.5561)
    ('D4', 0.17)
    ('D4', 0.0)

    """
    maxNotes = len(streamIn) - 1
    p2Accent = 1.0
    for i, n in enumerate(streamIn):
        if i == 0:
            n.melodicAccent = 1.0
            continue
        elif i == maxNotes:
            n.melodicAccent = p2Accent
            continue
        lastPs = streamIn[i - 1].pitch.ps
        thisPs = n.pitch.ps
        nextPs = streamIn[i + 1].pitch.ps
        if lastPs == thisPs and thisPs == nextPs:
            thisAccent = 0.0
            nextAccent = 0.0
        elif lastPs != thisPs and thisPs == nextPs:
            thisAccent = 1.0
            nextAccent = 0.0
        elif lastPs == thisPs and thisPs != nextPs:
            thisAccent = 0.0
            nextAccent = 1.0
        elif lastPs < thisPs and thisPs > nextPs:
            thisAccent = 0.83
            nextAccent = 0.17
        elif lastPs > thisPs and thisPs < nextPs:
            thisAccent = 0.71
            nextAccent = 0.29
        elif lastPs < thisPs and thisPs < nextPs:
            thisAccent = 0.33
            nextAccent = 0.67
        elif lastPs > thisPs and thisPs > nextPs:
            thisAccent = 0.5
            nextAccent = 0.5
        n.melodicAccent = thisAccent * p2Accent
        p2Accent = nextAccent


def remove_ruleset(args, rulesengine_db):
    """remove a ruleset, deleting the associated db"""
    import os
    from src.praxxis.sqlite import sqlite_rulesengine
    from src.praxxis.rulesengine import rules
    if hasattr(args, 'name'):
        name = args.name
    else:
        name = args
    name = rules.get_ruleset_by_ordinal(name, rulesengine_db)
    path = sqlite_rulesengine.get_ruleset_path(rulesengine_db, name)
    if os.path.isfile(path):
        os.remove(path)
        sqlite_rulesengine.remove_ruleset(rulesengine_db, name)
    else:
        from src.praxxis.util import error
        raise error.RulesetNotFoundError(name)
    return name


def browse_interactive(pose_index: int=-1):
    """Interactively browse poses in 3D-View

    :param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)
    :type pose_index: int
    """
    pass


def validate_urls(urls):
    """
    Make sure each URL in a list starts with 'http://' and is not empty,
    which can happen when reading URLs from a file.

    :param list(str) urls: list of URLs
    :return list(str): list of validated URLs
    """
    validated = []
    for u in urls:
        if u.startswith('http://'):
            validated.append(u)
        elif u.startswith('www.'):
            validated.append(f'http://{u}')
        else:
            continue
    return validated


def new():
    """Create a new IExtension instance"""


def provides(interface):
    """Explicitly specify with which interface a component will be
        looked up."""


def surfaceTemp(theta_inf, theta_1, R0, Rsurf):
    """ Surface temperature

	Parameters
	----------
	theta_inf : float or (m x n) np.array
		ambient temperature [°C] or [K]

	theta_1 : float or (m x n) np.array
		first node temperature [°C] or [K]

	R0 : float or (m x n) np.array
		resistance between ambient and first node [K/W]

	Rsurf : float or (m x n) np.array
		surface resistance [K/W]

	Returns
	-------
	R : (n+1,) np.array
		heat transfer resistance [K/W]

	Comment
	-------
	- To be superseded by 2D concept
	- Different return options in code give same result; speed difference unclear

	Example use
	-----------
	>>> XXX
	"""
    return theta_inf - (theta_inf - theta_1) * Rsurf / R0


def type_formatter(type_):
    """Format the menu item types with some emoji."""
    return {'Vegetarian': ':herb:', 'Pasta': ':spaghetti:', 'Grill':
        ':meat_on_bone:', 'Pizza': ':pizza:', 'Speciality': ':ok_hand:',
        'La Saison': ':fish: / :pig: / :cow:', 'Le Marché':
        ':man_with_gua_pi_mao:'}.get(type_, '')


def get_role_id(role):
    """
    Get a role's ID.

    Args:
        role (obj): a Python object.

    Returns:
        str: the role's ID or None.
    """
    if hasattr(role, 'role_id'):
        attr = role.role_id
        if callable(attr):
            return str(attr())
        return str(attr)
    elif hasattr(role, 'id'):
        return str(role.id)
    return ''


def intersectBed(lst1, lst2):
    """
	Return intersection of two bed regions.

	Parameters
	----------
	lst1 : list
		The 1st genomic region. List of chrom, start, end.
		Example: ['chr1',10, 100]

	lst2 : list
		 The 2nd genomic region. List of chrom, start, end.
		 Example: ['chr1',50, 120]

	Examples
	--------
	>>> intersectBed(['chr1',10, 100],['chr1',50, 120])
	('chr1', 50, 100)
	>>> intersectBed(['chr1',10, 100],['chr1',20, 30])
	('chr1', 20, 30)

	"""
    chr1, st1, end1 = lst1
    chr2, st2, end2 = lst2
    if int(st1) > int(end1) or int(st2) > int(end2):
        raise Exception('Start cannot be larger than end')
    if chr1 != chr2:
        return None
    if int(st1) > int(end2) or int(end1) < int(st2):
        return None
    return chr1, max(st1, st2), min(end1, end2)


def template_to_dict_alt(tree, title):
    """
    Returns parse tree template as {<title>: <parts>}
    This is a more general parse tree infobox template parser.
    """
    box = []
    part = []
    for item in tree.iter():
        if item.tag == 'part':
            if part:
                box.append(part)
            part = []
        if item.tag == 'name' or item.tag == 'value':
            for attr in item.keys():
                part.append({attr: item.get(attr)})
            if item.text:
                part.append(item.text.strip())
            if item.tail:
                part.append(item.tail.strip())
    if part:
        box.append(part)
    return {title.strip(): box}


@staticmethod
def in_out_quint(progress):
    """.. image:: images/anim_in_out_quint.png
        """
    p = progress * 2
    if p < 1:
        return 0.5 * p * p * p * p * p
    p -= 2.0
    return 0.5 * (p * p * p * p * p + 2.0)


@classmethod
def get_map(cls) ->dict:
    """
        Returns the map between JSON string and enum values.

        Returns
        -------
        dict
            The map.
        """
    return {'classification': cls.CLASSIFICATION, 'regression': cls.
        REGRESSION, 'clustering': cls.CLUSTERING, 'linkPrediction': cls.
        LINK_PREDICTION, 'vertexNomination': cls.VERTEX_NOMINATION,
        'communityDetection': cls.COMMUNITY_DETECTION, 'graphClustering':
        cls.GRAPH_CLUSTERING, 'graphMatching': cls.GRAPH_MATCHING,
        'timeSeriesForecasting': cls.TIME_SERIES_FORECASTING,
        'collaborativeFiltering': cls.COLLABORATIVE_FILTERING}


def upload_files(file_path):
    """ Uploads multiple files to a Dropbox account.

    Keyword arguments:
    file_path -- Path to the files to upload.
    """
    pass


def _convert_to_dependency_graph(sentence):
    """
    (Helper function for the Floyd Warshall algorithm).
    Computes the adjacency matrix (graph) based on the dependency graph of a sentence of tokens.
    """
    graph = {}
    for token in sentence:
        graph[token.features['id']] = {}
    for from_token in sentence:
        graph[from_token.features['id']] = {}
        for to_token, _ in from_token.features['dependency_to']:
            graph[from_token.features['id']][to_token.features['id']] = 1
            graph[to_token.features['id']][from_token.features['id']] = 1
    return graph


def register_handler(handler):
    """
    Install application-specific GRIB image handler.

    :param handler: Handler object.
    """
    global _handler
    _handler = handler


def command_scan_file(util, args):
    """ Handler for command scan_file """
    return util.scan_file(args.filename)


def single_sort_by(queryset, params):
    """
    Orders and returns the queryset using the GET parameters of a request
    The function takes care of checking if the "sort_by" key exists in the dict
    """
    sort_by = params.get('sort_by', None)
    if sort_by:
        ascending = params.get('ascending', False)
        if ascending != 'true':
            sort_by = '-' + sort_by
        queryset = queryset.order_by(sort_by)
    return queryset


def circuit_hamiltonien(chemin):
    """
    Extrait un circuit hamiltonien depuis un circuit eulérien,
    passe par tous les sommets une et une seule fois.
    """
    nb = max(chemin) + 1
    res = []
    coche = [(False) for i in range(0, nb)]
    for c in chemin:
        if coche[c]:
            continue
        res.append(c)
        coche[c] = True
    return res


@staticmethod
def bitSizeOf():
    """
        Returns length of Zserio float32 type stored in the bit stream in bits.

        :returns: Length of Zserio float32 type in bits.
        """
    return 32


@classmethod
def fromReader(cls, arrayTraits, reader, size=None, *, isAuto=None,
    isImplicit=None, setOffsetMethod=None, checkOffsetMethod=None):
    """
        Constructs array and reads elements from the given bit stream reader.

        :param arrayTraits: Array traits which specify the array type.
        :param reader: Bit stream from which to read.
        :param size: Number of elements to read or None in case of implicit or auto arrays.
        :param rawArray: Native python list which will be hold by this abstraction.
        :param isAuto: True if mapped Zserio array is auto array.
        :param isImplicit: True if mapped Zserio array is implicit array.
        :param setOffsetMethod:  Set offset method if mapped Zserio array is indexed offset array.
        :param checkOffsetMethod: Check offset method if mapped Zserio array is indexed offset array.
        :returns: Array instance filled using given bit stream reader.
        """
    instance = cls(arrayTraits, isAuto=isAuto, isImplicit=isImplicit,
        setOffsetMethod=setOffsetMethod, checkOffsetMethod=checkOffsetMethod)
    instance.read(reader, size)
    return instance


def describe_tape_recovery_points(GatewayARN=None, Marker=None, Limit=None):
    """
    Returns a list of virtual tape recovery points that are available for the specified tape gateway.
    A recovery point is a point-in-time view of a virtual tape at which all the data on the virtual tape is consistent. If your gateway crashes, virtual tapes that have recovery points can be recovered to a new gateway. This operation is only supported in the tape gateway architecture.
    See also: AWS API Documentation

    Examples
    Returns a list of virtual tape recovery points that are available for the specified gateway-VTL.
    Expected Output:

    :example: response = client.describe_tape_recovery_points(
        GatewayARN='string',
        Marker='string',
        Limit=123
    )

    :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 Marker: string
    :param Marker: An opaque string that indicates the position at which to begin describing the virtual tape recovery points.

    :type Limit: integer
    :param Limit: Specifies that the number of virtual tape recovery points that are described be limited to the specified number.

    :rtype: dict
    :return: {
        'GatewayARN': 'string',
        'TapeRecoveryPointInfos': [
            {
                'TapeARN': 'string',
                'TapeRecoveryPointTime': datetime(2015, 1, 1),
                'TapeSizeInBytes': 123,
                'TapeStatus': 'string'
            },
        ],
        'Marker': 'string'
    }

    """
    pass


def produce_mix(tracks, outfile, format='mp3'):
    """
    Mix a list of tracks together.
    """
    mix = tracks[0]
    for track in tracks[1:]:
        mix = mix.overlay(track)
    mix.export(outfile, format=format)


def write_sentence(t, f):
    """writes a sentence in export format
        and does NOT write the #EOS"""
    for n in t.terminals:
        if n.parent:
            parent_id = n.parent.id
        else:
            parent_id = '0'
        extra = ''
        if hasattr(n, 'secedge') and n.secedge is not None:
            for secedge in n.secedge:
                tgt = secedge[1]
                if tgt.isTerminal():
                    tgt_id = tgt.start
                else:
                    tgt_id = tgt.id
                extra += '\t%s %s' % (secedge[0], tgt_id)
        if hasattr(n, 'comment') and n.comment:
            if extra:
                extra += ' '
            else:
                extra = '     '
            extra += '%% ' + n.comment
        f.write('%-23s %-7s %-15s %-7s %s%s\n' % (n.word, n.cat, n.morph, n
            .edge_label, parent_id, extra))
    all_nodes = t.node_table.values()
    all_nodes.sort(key=lambda n: n.id)
    for n in all_nodes:
        if n.parent:
            parent_id = n.parent.id
        else:
            parent_id = '0'
        extra = ''
        if hasattr(n, 'secedge') and n.secedge is not None:
            extra = '     %-7s %s' % (n.secedge[0], n.secedge[1].id)
        f.write('#%-22s %-7s %-15s %-7s %s%s\n' % (n.id, n.cat, n.attr, n.
            edge_label, parent_id, extra))


def fleur_calc_get_structure(calc_node):
    """
    Get the AiiDA data structure from a fleur calculations
    """
    fleurinp = calc_node.inp.fleurinpdata
    structure = fleurinp.get_structuredata(fleurinp)
    return structure


def _handle_continuation(line, col, form):
    """Modify column and format string to account for a continuation block.

    The PDB format specifies, that `Continuation` fields are intended by
    one char, which (in `.PDBRecordLibrary`) is marked by a trailing `c` in the
    format string. Example: ``<{10}s`` <--> ``<{10}sc``.  If the `c` is present
    and if there is a continuation number in the preceeding column, the data
    field is moved by one char to the right.  In any case, the trailing `c` is
    removed from the format string.

    """
    out_col = list(col)
    if form.endswith('c'):
        out_form = form[:-1]
        if line[col[0] - 1].strip():
            out_col[0] += 1
            out_col[1] += 1
    else:
        out_form = form
    return out_col, out_form


def all_with_version(stack_refs: list):
    """
    Checks if all stackreferences have versions
    """
    for ref in stack_refs:
        if not ref.version:
            return False
    return True


def create_monkey(bm: 'bmesh.types.BMesh', matrix: 'mathutils.Matrix') ->dict:
    """Creates a monkey (standard blender primitive).

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param matrix: matrix to multiply the new geometry with
    :type matrix: 'mathutils.Matrix'
    :return:  verts: output vertstype list of (bmesh.types.BMVert)
    """
    pass


def collapse():
    """Collapse this node.
        """


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 pybool(v_str, strict_logical=True):
    """Convert string repr of Fortran logical to Python logical."""
    assert isinstance(v_str, str)
    assert isinstance(strict_logical, bool)
    if strict_logical:
        v_bool = v_str.lower()
    else:
        try:
            if v_str.startswith('.'):
                v_bool = v_str[1].lower()
            else:
                v_bool = v_str[0].lower()
        except IndexError:
            raise ValueError('{0} is not a valid logical constant.'.format(
                v_str))
    if v_bool in ('.true.', '.t.', 'true', 't'):
        return True
    elif v_bool in ('.false.', '.f.', 'false', 'f'):
        return False
    else:
        raise ValueError('{0} is not a valid logical constant.'.format(v_str))


def __iter__():
    """
        Return an iterator over the status codes.
        """


@classmethod
def update(cls, spec, document, upsert=False):
    """
        Mimics a subset of PyMongo's Collection.update functionality. The spec
        is used to search for the document to update, document contains the
        values to be updated, and upsert specifies whether to do an insert if
        the original document is not found.
        """
    previous = cls.get(**spec)
    cls.pre_save.send(previous)
    result = cls.c.update(spec, document, upsert=upsert)
    current = cls.get(**spec)
    cls.post_save.send(current)
    return result


def scatter_row_inplace(data, row_index, value):
    """Write the value into the data tensor using the row index inplace.

    This is an inplace write so it will break the autograd.

    Parameters
    ----------
    data : Tensor
        The data tensor to be updated.
    row_index : Tensor
        A 1-D integer tensor containing which rows to be updated.
    value : Tensor
        The new value.
    """
    pass


@classmethod
def unregisterExtraObject(cls, name):
    """
        Class method to unregister extra JavaScript objects.

        @param name name of the object
        @type str
        """
    if name in cls.extraObjects:
        del cls.extraObjects[name]


def _get_values(line):
    """
    Returns the portion of an INSERT statement containing values
    """
    return line[line.find('` VALUES ') + 9:]


def delete_key_pair(keyPairName=None):
    """
    Deletes a specific SSH key pair.
    See also: AWS API Documentation

    :example: response = client.delete_key_pair(
        keyPairName='string'
    )

    :type keyPairName: string
    :param keyPairName: [REQUIRED]
            The name of the key pair to delete.

    :rtype: dict
    :return: {
        'operation': {
            'id': 'string',
            'resourceName': 'string',
            'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
            'createdAt': datetime(2015, 1, 1),
            'location': {
                'availabilityZone': 'string',
                'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
            },
            'isTerminal': True|False,
            'operationDetails': 'string',
            'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
            'status': 'NotStarted'|'Started'|'Failed'|'Completed',
            'statusChangedAt': datetime(2015, 1, 1),
            'errorCode': 'string',
            'errorDetails': 'string'
        }
    }

    """
    pass


@staticmethod
def sort_key(variable):
    """ Get a key to sort a variable

        Args:
            variable (:obj:`BiomodelVariable`): variable

        Returns:
            :obj:`str`
        """
    return variable.id


@classmethod
def to_api_dict(cls, annotation_type, annotation):
    """
        This method simply puts the annotation_type within
        the annotation dict again.

        :param annotation_type: The type of annotation
        :type annotation_type: str
        :param annotation: The annotation data
        :type annotation: dict
        :returns: the annotation with annotation_type set
        :rtype: dict
        """
    result = dict(annotation)
    if 'annotationType' in result:
        del result['annotationType']
    result['annotation_type'] = annotation_type
    return result


def size8(parent=None, new_value=None, **kwargs):
    """
    Size getter for rsa key data where the byte size
    of the integer is (parent.parent.bitlen + 7) // 8
    (the + 7 is to round up to the nearest multiple of 8)

    We dont want to have this be a setter since bitlen
    is used by more than one attribute and while it may
    work for some bigints, it may be too small for others.
    """
    if new_value is None:
        return (parent.parent.bitlen + 7) // 8


def filetypes():
    """Get supported archive filetypes for network import."""
    return {'npz': 'Numpy Zipped Archive'}


def checksum_fn(book_id):
    """
    Construct filename for checksum file.

    Args:
        book_id (int/str): ID of the book, without special characters.

    Returns:
        str: Filename in format ``MD5_BOOKID.md5``.
    """
    return 'MD5_%s.md5' % str(book_id)


def stroke_apply_thickness():
    """Apply the thickness change of the layer to its strokes

    """
    pass


def setup(settings, app, request_class):
    """Setup is perfomred early and for certain before first request is
    handled.
    """

    @app.before_first_request
    def before_first_request():
        pass

    @app.before_request
    def example_preprocessor():
        pass

    @app.after_request
    def after_request(resp):
        """If there is anything that api should do before ending request, add
        it in here for example you might have transactional backend that
        require commit or rollback at the end of each request.

        NOTE: if unhandled exception happens, this function is not going to be
        executed.
        """
        return resp
    app.debug = settings.DEBUG
    app.request_class = request_class


def to_two_bytes(integer):
    """
    Breaks an integer into two 7 bit bytes.
    """
    if integer > 32767:
        raise ValueError(
            "Can't handle values bigger than 32767 (max for 2 bits)")
    return bytearray([integer % 128, integer >> 7])


@staticmethod
def _query_clean(query):
    """Here we clean the queryset"""
    query += ';'
    return query


@classmethod
def fromEventsAndSequences(cls, events, sequences, unk02=0):
    """
        Create a new SSAR object from a list of sequence events and a
        list of sequences.
        """
    obj = cls(unk02=unk02)
    obj.events = events
    obj.sequences = sequences
    return obj


def get_bucket_analytics_configuration(Bucket=None, Id=None):
    """
    Gets an analytics configuration for the bucket (specified by the analytics configuration ID).
    See also: AWS API Documentation

    :example: response = client.get_bucket_analytics_configuration(
        Bucket='string',
        Id='string'
    )

    :type Bucket: string
    :param Bucket: [REQUIRED] The name of the bucket from which an analytics configuration is retrieved.

    :type Id: string
    :param Id: [REQUIRED] The identifier used to represent an analytics configuration.

    :rtype: dict
    :return: {
        'AnalyticsConfiguration': {
            'Id': 'string',
            'Filter': {
                'Prefix': 'string',
                'Tag': {
                    'Key': 'string',
                    'Value': 'string'
                },
                'And': {
                    'Prefix': 'string',
                    'Tags': [
                        {
                            'Key': 'string',
                            'Value': 'string'
                        },
                    ]
                }
            },
            'StorageClassAnalysis': {
                'DataExport': {
                    'OutputSchemaVersion': 'V_1',
                    'Destination': {
                        'S3BucketDestination': {
                            'Format': 'CSV',
                            'BucketAccountId': 'string',
                            'Bucket': 'string',
                            'Prefix': 'string'
                        }
                    }
                }
            }
        }
    }

    :returns:
    (dict) --
    AnalyticsConfiguration (dict) -- The configuration and any analyses for the analytics filter.
    Id (string) -- The identifier used to represent an analytics configuration.
    Filter (dict) -- The filter used to describe a set of objects for analyses. A filter must have exactly one prefix, one tag, or one conjunction (AnalyticsAndOperator). If no filter is provided, all objects will be considered in any analysis.
    Prefix (string) -- The prefix to use when evaluating an analytics filter.
    Tag (dict) -- The tag to use when evaluating an analytics filter.
    Key (string) -- Name of the tag.
    Value (string) -- Value of the tag.

    And (dict) -- A conjunction (logical AND) of predicates, which is used in evaluating an analytics filter. The operator must have at least two predicates.
    Prefix (string) -- The prefix to use when evaluating an AND predicate.
    Tags (list) -- The list of tags to use when evaluating an AND predicate.
    (dict) --
    Key (string) -- Name of the tag.
    Value (string) -- Value of the tag.

    StorageClassAnalysis (dict) -- If present, it indicates that data related to access patterns will be collected and made available to analyze the tradeoffs between different storage classes.
    DataExport (dict) -- A container used to describe how data related to the storage class analysis should be exported.
    OutputSchemaVersion (string) -- The version of the output schema to use when exporting data. Must be V_1.
    Destination (dict) -- The place to store the data for an analysis.
    S3BucketDestination (dict) -- A destination signifying output to an S3 bucket.
    Format (string) -- The file format used when exporting data to Amazon S3.
    BucketAccountId (string) -- The account ID that owns the destination bucket. If no account ID is provided, the owner will not be validated prior to exporting data.
    Bucket (string) -- The Amazon resource name (ARN) of the bucket to which data is exported.
    Prefix (string) -- The prefix to use when exporting data. The exported data begins with this prefix.

    """
    pass


@staticmethod
def read_meta_info():
    """
        The meta_info for the codetable is not implemented, output a empty
        dictionary
        """
    return dict()


@classmethod
def reset_to_defaults(cls):
    """
        Reset all settings to their default values.
        """
    for name, setting in cls._settings.items():
        setattr(cls, name, setting.default)


def lattice_to_spacegroup(lattice):
    """ Converts a lattice to the spacegroup with the lowest symmetry
    possible for that lattice"""
    l2s = {'aP': 1, 'mP': 3, 'mC': 5, 'mI': 5, 'oP': 16, 'oC': 21, 'oI': 23,
        'oF': 22, 'tP': 75, 'tI': 79, 'hP': 143, 'hR': 146, 'hH': 146, 'cP':
        195, 'cF': 196, 'cI': 197}
    return l2s[lattice]


def df_drop_nancols(data, threshold=0, destructive=False):
    """Drop columns based on a threshold of nan values. The optimal
    approach, especially for small datasets, seems to be to first
    start with df_drop_nancols, then follow with df_drop_nanrows,
    and then do one more pass with df_drop_nancols.

    data : pandas dataframe
        A pandas dataframe to be processed
    threshold : float
        A decimal value between 1 (all can be nans) and 0 (no nans allowed).
    destructive : bool
        If set to True, will make changes directly to the dataframe which
        may be useful with very large dataframes instead of making a copy.

    """
    if destructive is False:
        data = data.copy(deep=True)
    threshold = threshold * len(data)
    return data.dropna(axis=1, thresh=threshold)


def _deltaKappaCalcite_I75(TempC):
    """Delta and kappa terms for calcite solubility [I75]."""
    deltaVKCa = -48.76 + 0.5304 * TempC
    KappaKCa = (-11.76 + 0.3692 * TempC) / 1000
    return deltaVKCa, KappaKCa


def _samplingToEmx(emxObj, sampling):
    """ Write sampling rate info as expected by EMX. """
    emxObj.set('pixelSpacing__X', sampling)
    emxObj.set('pixelSpacing__Y', sampling)


def normalize_directory(directory):
    """ Normalize a directory path.

    Normalizing a directory path consists of turning it into a relative
    directory path, even if it initially was a relative directory path.

        /foo/bar/qaz -> foo/bar/qaz
        foo/bar/qaz  -> foo/bar/qaz

    A normalized directory path can be combined with the (path of the)
    root directory.
    """
    return directory.relative_to(directory.root)


def _render_groupings(fields):
    """Render the group by part of a query.

    Parameters
    ----------
    fields : list
        A list of fields to group by.

    Returns
    -------
    str
        A string that represents the "group by" part of a query.
    """
    if not fields:
        return ''
    return 'GROUP BY ' + ', '.join(fields)


def set_record_topology(record, topology):
    """Set the Biopython record's topology, possibly passing if already set.

    This actually sets the ``record.annotations['topology']``.The ``topology``
    parameter can be "circular", "linear", "default_to_circular" (will default
    to circular if ``annotations['topology']`` is not already set) or
    "default_to_linear".
    """
    valid_topologies = ['circular', 'linear', 'default_to_circular',
        'default_to_linear']
    if topology not in valid_topologies:
        raise ValueError('topology should be one of %s.' % ', '.join(
            valid_topologies))
    annotations = record.annotations
    default_prefix = 'default_to_'
    if topology.startswith(default_prefix):
        if 'topology' not in annotations:
            annotations['topology'] = topology[len(default_prefix):]
    else:
        annotations['topology'] = topology


@classmethod
def UNITS(cls):
    """ Units of this class. """
    return cls._UNITS[:]


def p_character_capture(p):
    """character : K_CAPTURE group"""
    p[0] = [('capture', (p[2], None))]


def delete():
    """
        Unshare & delete this blurb, and any descendent blurbs and previous
        versions of this blurb
        """


@staticmethod
def _variable_attributes(varname):
    """Get dict of netCDF4 variable attributes for a given NcdcRecord Data column name"""
    proxy_map = {'d13c': ('d13C', 'per mil'), 'd18o': ('d18O', 'per mil'),
        'mgca': ('Mg/Ca', 'per mil'), 'percent': ('Percent foraminifera',
        '%'), 'tex86': ('TEX86', 'index'), 'uk37': ("UK'37", 'index')}
    foraminifera_map = {'bulloides': 'Globigerina bulloides',
        'crassaformis': 'Globorotalia crassaformis', 'dutertrei':
        'Neogloboquadrina dutertrei', 'inflata': 'Globoconella inflata',
        'mabahethi': 'Cibicides mabahethi', 'marginata':
        'Bulimina marginata', 'menardii': 'Globorotalia menardii',
        'obliquiloculata': 'Pulleniatina obliquiloculata', 'pachyderma':
        'Neogloboquadrina pachyderma sinistral', 'pachysin':
        'Neogloboquadrina pachyderma sinistral', 'pachyderma_d':
        'Neogloboquadrina incompta', 'peregrina': 'Uvigerina peregrina',
        'quinqueloba': 'Turborotalita quinqueloba', 'ruber':
        'Globigerinoides ruber white', 'ruber_lato':
        'Globigerinoides ruber white', 'ruber_pink':
        'Globigerinoides ruber pink', 'ruber_stricto':
        'Globigerinoides ruber white', 'sacculifer':
        'Trilobatus sacculifer', 'truncatulinoides':
        'Globorotalia pachytheca', 'tumida': 'Globorotalia tumida',
        'acicula': 'Creseis acicula'}
    varname = varname.lower()
    try:
        if '_' not in varname:
            out = {'long_name': proxy_map[varname][0], 'units': proxy_map[
                varname][1]}
        else:
            proxy, foram = varname.split('_', 1)
            out = {'long_name': proxy_map[proxy][0], 'units': proxy_map[
                proxy][1], 'foraminifera_type': foraminifera_map[foram]}
    except KeyError:
        out = {}
    return out


def validate_signature_ser(sig):
    """Checks that the serialized signature is a valid byte string.
    Args:
        seckey  (bytes):        signature
    Returns:
        (True):                 if sig is valid, otherwise error
    """
    if not isinstance(sig, bytes):
        raise ValueError('Invalid signature. Must be bytes.')
    return True


def escape(t):
    """HTML-escape the text in `t`.

    This is only suitable for HTML text, not attributes.

    """
    return t.replace('&', '&').replace('<', '<')


@classmethod
def get_related_field_names(cls):
    """
        Get a list of the names of related fields for the current model.
        """
    return cls.related_fields


def padr(text, n, c):
    """
    padr - right pad of text with character c
    """
    text = str(text)
    return text + str(c) * (n - len(text))


def __material_mx(d):
    """ Fixed length data fields for mixed materials. """
    return d[0:5], d[6], d[7:]


def check_parameter_accepted_values(param, param_name, accepted_values):
    """Raise an error if parameter does not belong to a set of values.

    Parameters
    ----------
    param : unspecified
        Parameter to be tested.
    param_name : string
        Name of the parameter.
    accepted_values : list
        Accepted values that the parameter can take.
    """
    if param not in accepted_values:
        raise ValueError('Parameter {} needs to be in {}, got: {}'.format(
            param_name, accepted_values, param))


def LONGER(fragment):
    """Sorts longer passages first."""
    return 0 - len(fragment)


def extrude_faces_move(MESH_OT_extrude_faces_indiv=None,
    TRANSFORM_OT_shrink_fatten=None):
    """Extrude faces and move result

    :param MESH_OT_extrude_faces_indiv: Extrude Individual Faces, Extrude individual faces only
    :param TRANSFORM_OT_shrink_fatten: Shrink/Fatten, Shrink/fatten selected vertices along normals
    """
    pass


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

        :param TfaChangeStatusDetails val:
        :rtype: EventDetails
        """
    return cls('tfa_change_status_details', val)


def dfa_reachable(dfa: dict) ->dict:
    """ Side effects on input! Removes unreachable states from a
    DFA and returns the pruned DFA.

    It is possible to remove from a DFA A all unreachable states
    from the initial state without altering the language.
    The reachable DFA :math:`A_R` corresponding to A is defined as:

    :math:`A_R = (Σ, S_R , s_0 , ρ|S_R , F ∩ S_R )`

    where

    • :math:`S_R` set of reachable state from the initial one
    • :math:`ρ|S_R` is the restriction on :math:`S_R × Σ` of ρ.

    :param dict dfa: input DFA.
    :return: *(dict)* representing the pruned DFA.
    """
    reachable_states = set()
    boundary = set()
    reachable_states.add(dfa['initial_state'])
    boundary.add(dfa['initial_state'])
    while boundary:
        s = boundary.pop()
        for a in dfa['alphabet']:
            if (s, a) in dfa['transitions']:
                if dfa['transitions'][s, a] not in reachable_states:
                    reachable_states.add(dfa['transitions'][s, a])
                    boundary.add(dfa['transitions'][s, a])
    dfa['states'] = reachable_states
    dfa['accepting_states'] = dfa['accepting_states'].intersection(dfa[
        'states'])
    transitions = dfa['transitions'].copy()
    for t in transitions:
        if t[0] not in dfa['states']:
            dfa['transitions'].pop(t)
        elif dfa['transitions'][t] not in dfa['states']:
            dfa['transitions'].pop(t)
    return dfa


@classmethod
def get(cls, level):
    """
        Get the emoji that represents this logging level.
        Defaults to warning if no level can be found in the loopup
        :param str level: The log level. e.g. INFO or ERROR
        :return: The emoji for this logging level
        :rtype: str
        """
    return getattr(cls, level, ':warning:')


@classmethod
def get(cls, context, uuid):
    """Find a DB attribute and return an Obj Deployable."""
    db_attr = cls.dbapi.attribute_get(context, uuid)
    obj_attr = cls._from_db_object(cls(context), db_attr)
    return obj_attr


def load_mclust_header(filename):
    """Loads a mclust .t tetrode file.

    Parameters
    ----------
    filename: str

    Returns
    -------
    times: np.array

    """
    with open(filename, 'rb') as f:
        file_contents = f.read()
    header_begin_idx = file_contents.find(b'%%BEGINHEADER')
    header_end_idx = file_contents.find(b'%%ENDHEADER') + len(b'%%ENDHEADER\n')
    header = file_contents[header_begin_idx:header_end_idx]
    return header


def read():
    """Get the template source
        """


def positive_int(var, var_name):
    """
    Check if *var* is a positive integer.

    :raises TypeError: Parameter *var* must be an integer.
    :raises ValueError: Parameter *var* must be a positive integer.
    """
    if not isinstance(var, int):
        raise TypeError('\n\nParameter {} must be an integer.\n'.format(
            var_name))
    if var < 1:
        raise ValueError('\n\nParameter {} must be a positive integer.\n'.
            format(var_name))


@classmethod
def init_wrapper(cls, initializer, trainable, **kargs):
    """wraps the object to be used as an initializer."""
    return lambda shape: cls(initial_value=initializer(shape=shape),
        trainable=trainable, **kargs)


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_bool()
    return parameters


def divide(stack):
    """
    Divides the second number by the first number on top of the stack.
    """
    item_1 = stack.pop()
    item_2 = stack.pop()
    result = item_2 / item_1
    stack.append(result)


def read_utf8(fh, byteorder, dtype, count, offsetsize):
    """Read tag data from file and return as unicode string."""
    return fh.read(count).decode()


def update(*args, **kwds):
    """od.update(E, **F) -> None.  Update od from dict/iterable E and F.

        If E is a dict instance, does:           for k in E: od[k] = E[k]
        If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]
        Or if E is an iterable of items, does:   for k, v in E: od[k] = v
        In either case, this is followed by:     for k, v in F.items(): od[k] = v

        """
    if len(args) > 2:
        raise TypeError(
            'update() takes at most 2 positional arguments (%d given)' % (
            len(args),))
    elif not args:
        raise TypeError('update() takes at least 1 argument (0 given)')
    self = args[0]
    other = ()
    if len(args) == 2:
        other = args[1]
    if isinstance(other, dict):
        for key in other:
            self[key] = other[key]
    elif hasattr(other, 'keys'):
        for key in other.keys():
            self[key] = other[key]
    else:
        for key, value in other:
            self[key] = value
    for key, value in kwds.items():
        self[key] = value


def grouper_list(l, n):
    """Evenly divide list into fixed-length piece, no filled value if chunk
    size smaller than fixed-length.

    Example::

        >>> list(grouper(range(10), n=3)
        [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

    **中文文档**

    将一个列表按照尺寸n, 依次打包输出, 有多少输出多少, 并不强制填充包的大小到n。

    下列实现是按照性能从高到低进行排列的:

    - 方法1: 建立一个counter, 在向chunk中添加元素时, 同时将counter与n比较, 如果一致
      则yield。然后在最后将剩余的item视情况yield。
    - 方法2: 建立一个list, 每次添加一个元素, 并检查size。
    - 方法3: 调用grouper()函数, 然后对里面的None元素进行清理。
    """
    chunk = list()
    counter = 0
    for item in l:
        counter += 1
        chunk.append(item)
        if counter == n:
            yield chunk
            chunk = list()
            counter = 0
    if len(chunk) > 0:
        yield chunk


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 encode_light_rgb(brightness, red, green, blue):
    """Encode rgb value used to control the gateway light"""
    return (brightness << 24) + (red << 16) + (green << 8) + blue


def iterkeys(obj, **kwargs):
    """Use this only if compatibility with Python versions before 2.7 is
    required. Otherwise, prefer viewkeys().
    """
    func = getattr(obj, 'iterkeys', None)
    if not func:
        func = obj.keys
    return func(**kwargs)


def i_to_rgb(i, normalize=False):
    """Convert a number between 0.0 and 1.0 to an equivalent RGB tuple.

    Parameters
    ----------
    i : float
        A number between `0.0` and `1.0`.
    normalize : bool, optional
        Normalize the resulting RGB values.
        Default is to return integer values ranging from 0 to 255.

    Returns
    -------
    tuple
        The RGB values of the color corresponding to the provided number.
        If `normalize` is true, the RGB values are normalized to values between 0.0 and 1.0.
        If `normalize` is false, the RGB values are integers between 0 and 255.

    Examples
    --------
    >>> i_to_rgb(1.0)
    (255, 0, 0)
    >>> i_to_rgb(0.75)
    (255, 255, 0)
    >>> i_to_rgb(0.5)
    (0, 255, 0)
    >>> i_to_rgb(0.25)
    (0, 255, 255)
    >>> i_to_rgb(0.0)
    (0, 0, 255)

    >>> i_to_rgb(1.0, True)
    (1.0, 0.0, 0.0)
    >>> i_to_rgb(0.75, True)
    (1.0, 1.0, 0.0)
    >>> i_to_rgb(0.5, True)
    (0.0, 1.0, 0.0)
    >>> i_to_rgb(0.25, True)
    (0.0, 1.0, 1.0)
    >>> i_to_rgb(0.0, True)
    (0.0, 0.0, 1.0)
    """
    i = max(i, 0.0)
    i = min(i, 1.0)
    if i == 0.0:
        r, g, b = 0, 0, 255
    elif 0.0 < i < 0.25:
        r, g, b = 0, int(255 * (4 * i)), 255
    elif i == 0.25:
        r, g, b = 0, 255, 255
    elif 0.25 < i < 0.5:
        r, g, b = 0, 255, int(255 - 255 * 4 * (i - 0.25))
    elif i == 0.5:
        r, g, b = 0, 255, 0
    elif 0.5 < i < 0.75:
        r, g, b = int(0 + 255 * 4 * (i - 0.5)), 255, 0
    elif i == 0.75:
        r, g, b = 255, 255, 0
    elif 0.75 < i < 1.0:
        r, g, b = 255, int(255 - 255 * 4 * (i - 0.75)), 0
    elif i == 1.0:
        r, g, b = 255, 0, 0
    else:
        r, g, b = 0, 0, 0
    if not normalize:
        return r, g, b
    return r / 255.0, g / 255.0, b / 255.0


def str2numorstr(x, method=int):
    """
    This extracts numbers from strings. eg. 114 from M114R.

    :param x: string
    """
    try:
        x = method(x)
        return x
    except:
        return x


@staticmethod
def make_session_run_hook():
    """ Builds a SessionRunHook for the MonitoredTrainingSession object """


def print_arr(text, a):
    """print the contents of an array to the console"""
    n, m = a.shape
    print('%s[][] = (' % text)
    for i in range(n):
        print(' (', end='')
        for j in range(m):
            print(' %g, ' % a[i][j], end='')
        print('),')
    print(')')


def p_cuesheet_item(t):
    """cuesheet_item : catalog
                     | title
                     | performer
                     | songwriter
                     | cdtextfile"""
    t[0] = t[1]


def get_preferred_sparse_format():
    """Get the preferred sparse matrix format supported by the backend.

    Different backends have their preferred backend. This info is useful when
    constructing a sparse matrix.

    Returns
    -------
    string
        the name of the preferred sparse matrix format.
    """
    pass


def choose_start_node(e):
    """
    Choose a node of the `Expression` such that no property leading to a data
    has to be reversed (with !).
    """
    for node in e.iter_nodes():
        if list(e.iter_edges(node)):
            return node
    return node


def types_existing_measures():
    """ Returns all tool type names that use the "Measures already in
        place" feature"""


def split(fn):
    """Return the extension of the provided base file"""
    sf = fn.split('.')
    l = len(sf)
    if l == 1:
        return fn, None
    else:
        ext = sf[-1]
        bn = '.'.join(sf[0:l - 1])
    return bn, ext


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

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


def prod(iterable, ignore=False):
    """Takes the product sum of iterable. If ignore=True all elements except those that are None are multiplied.
	If ignore=False, None is returned if any element is None. """
    x = None
    for i in iterable:
        if not i is None:
            if x is None:
                x = i
            else:
                x = x * i
        elif not ignore:
            return None
    return x


def update_in(d, keys, func, default=None, factory=dict):
    """ Update value in a (potentially) nested dictionary

    inputs:
    d - dictionary on which to operate
    keys - list or tuple giving the location of the value to be changed in d
    func - function to operate on that value

    If keys == [k0,..,kX] and d[k0]..[kX] == v, update_in returns a copy of the
    original dictionary with v replaced by func(v), but does not mutate the
    original dictionary.

    If k0 is not a key in d, update_in creates nested dictionaries to the depth
    specified by the keys, with the innermost value set to func(default).

    >>> inc = lambda x: x + 1
    >>> update_in({'a': 0}, ['a'], inc)
    {'a': 1}

    >>> transaction = {'name': 'Alice',
    ...                'purchase': {'items': ['Apple', 'Orange'],
    ...                             'costs': [0.50, 1.25]},
    ...                'credit card': '5555-1234-1234-1234'}
    >>> update_in(transaction, ['purchase', 'costs'], sum) # doctest: +SKIP
    {'credit card': '5555-1234-1234-1234',
     'name': 'Alice',
     'purchase': {'costs': 1.75, 'items': ['Apple', 'Orange']}}

    >>> # updating a value when k0 is not in d
    >>> update_in({}, [1, 2, 3], str, default="bar")
    {1: {2: {3: 'bar'}}}
    >>> update_in({1: 'foo'}, [2, 3, 4], inc, 0)
    {1: 'foo', 2: {3: {4: 1}}}
    """
    ks = iter(keys)
    k = next(ks)
    rv = inner = factory()
    rv.update(d)
    for key in ks:
        if k in d:
            d = d[k]
            dtemp = factory()
            dtemp.update(d)
        else:
            d = dtemp = factory()
        inner[k] = inner = dtemp
        k = key
    if k in d:
        inner[k] = func(d[k])
    else:
        inner[k] = func(default)
    return rv


def renormalize_reward(reward, lower=0.0, amplitude=1.0, trust=1.0,
    unbiased=True, mintrust=None):
    """Renormalize the reward to `[0, 1]`:

    - divide by (`trust/mintrust`) if `unbiased` is `True`.
    - simply project to `[0, 1]` if `unbiased` is `False`,

    .. warning:: If `mintrust` is unknown, the unbiased estimator CANNOT be projected back to a bounded interval.
    """
    if unbiased:
        if mintrust is not None:
            return (reward - lower) / (amplitude * (trust / mintrust))
        else:
            return (reward - lower) / (amplitude * trust)
    else:
        return (reward - lower) / amplitude


def one_and_none(first, second):
    """
    Check if one element in a pair is None and one isn't.

    :param first: To return True, this must be None.
    :type first: str

    :param second: To return True, this mustbe false.
    :type second: str
    """
    sentinel = True if first is None and second is not None else False
    return sentinel


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 write_cf_from_gp_stream(gp_stream, cfWr):
    """Write counts file using a given GP stream with reference and CFWriter.

    Write the counts format file using all genes in the GP stream.
    The sequences are automatically reversed and complemented if this
    is needed.

    :param GPStream gp_stream: The GP stream and reference :class:`GPStream
      <cflib.gp.GPStream>`.
    :param CFWriter cfWf: The :class:`CFWriter` object that contains
      the VCF files.

    """
    nr_rc_genes_correct_start_codon = 0
    nr_genes_correct_start_codon = 0
    nr_genes_inc = 0
    nr_genes_total = 0
    while True:
        correct_frame_shift_flag = False
        if gp_stream.gene.is_rc and gp_stream.seqs[0].data[-3:].lower(
            ) == 'cat':
            nr_rc_genes_correct_start_codon += 1
            correct_frame_shift_flag = True
        elif not gp_stream.gene.is_rc and gp_stream.seqs[0].data[:3].lower(
            ) == 'atg':
            nr_genes_correct_start_codon += 1
            correct_frame_shift_flag = True
        if correct_frame_shift_flag is False and gp_stream.gene.name.find('inc'
            ) != -1:
            nr_genes_inc += 1
            correct_frame_shift_flag = True
        nr_genes_total += 1
        for s in gp_stream.seqs:
            if s.get_rc() is True:
                s.rev_comp()
        if correct_frame_shift_flag:
            for i in range(gp_stream.gene.nr_exons):
                rg = gp_stream.seqs[i].get_region()
                cfWr.set_seq(gp_stream.seqs[i])
                cfWr.write_Rn(rg)
        else:
            print('Gene has no start codon and is not flagged incomplete:')
            print(gp_stream.gene.name)
        try:
            gp_stream.read_next_gene()
        except ValueError:
            break
    print('+ genes with correct start codon ATG:',
        nr_rc_genes_correct_start_codon)
    print('- genes with correct start codon ATG:', nr_genes_correct_start_codon
        )
    print('Incomplete genes without start codon:', nr_genes_inc)
    print('Total number of processed genes:', nr_genes_total)


@classmethod
def check_handler(cls, request):
    """Determine whether the request should be handled by this table."""
    if request.method == 'POST' and 'action' in request.POST:
        table, action, obj_id = cls.parse_action(request.POST['action'])
    elif 'table' in request.GET and 'action' in request.GET:
        table = request.GET['table']
        action = request.GET['action']
        obj_id = request.GET.get('obj_id', None)
    else:
        table = action = obj_id = None
    return table, action, obj_id


def split_exons(exons):
    """
    Return a list of the s-exons in the string.

    >>> split_exons('3_0/3_1')
    ['3_0', '3_1']
    >>> split_exons('4_0')
    ['4_0']
    """
    if '/' in exons:
        return exons.split('/')
    return [exons]


def product(seq, start=1.0):
    """
    Return the product of all numbers in the sequence.
    """
    result = start
    for x in seq:
        result *= x
    return result


def qtr_to_master_url(qtr):
    """
    Build the URL for the master index of a given quarter.

    :param qtr: given qtr
    :return: string that represents the URL
    """
    assert type(qtr) == tuple
    url = 'https://www.sec.gov/Archives/edgar/full-index'
    return '{}/{}/QTR{}/master.zip'.format(url, qtr[0], qtr[1])


def linear_interpolation(left, right, alpha):
    """
    Linear interpolation between `left` and `right`.

    :param left: (float) left boundary
    :param right: (float) right boundary
    :param alpha: (float) coeff in [0, 1]
    :return: (float)
    """
    return left + alpha * (right - left)


def getimagesize(url):
    """
    Attempts to determine an image's width and height, and returns a tuple,
    (width, height), in pixels or an empty string in case of failure.
    Requires that PIL is installed.

    """
    try:
        from PIL import ImageFile
    except ImportError:
        return ''
    from urllib.request import urlopen
    try:
        p = ImageFile.Parser()
        f = urlopen(url)
        while True:
            s = f.read(1024)
            if not s:
                break
            p.feed(s)
            if p.image:
                return p.image.size
    except (IOError, ValueError):
        return ''


def safe_str_cmp(a, b):
    """Compare two strings in constant time."""
    if len(a) != len(b):
        return False
    r = 0
    for c, d in zip(a, b):
        r |= ord(c) ^ ord(d)
    return r == 0


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


@staticmethod
def _handle_stdout(stdout, queue):
    """ bytes from the stdout pipe pass through here """
    for line in iter(stdout.readline, b''):
        queue.put_nowait(line)
    stdout.close()


def _peirce_skill_score(table):
    """This function is borrowed with modification from the hagelslag repository
    MulticlassContingencyTable class. It is used here with permission of
    David John Gagne II <djgagne@ou.edu>

    Multiclass Peirce Skill Score (also Hanssen and Kuipers score, True Skill Score)
    """
    n = float(table.sum())
    nf = table.sum(axis=1)
    no = table.sum(axis=0)
    correct = float(table.trace())
    no_squared = (no * no).sum()
    if n ** 2 == no_squared:
        return correct / n
    else:
        return (n * correct - (nf * no).sum()) / (n ** 2 - no_squared)


def matrix_transpose(m):
    """ Transposes the input matrix.

    The input matrix :math:`m` is a 2-dimensional array.

    :param m: input matrix with dimensions :math:`(n \\times m)`
    :type m: list, tuple
    :return: transpose matrix with dimensions :math:`(m \\times n)`
    :rtype: list
    """
    num_cols = len(m)
    num_rows = len(m[0])
    m_t = []
    for i in range(num_rows):
        temp = []
        for j in range(num_cols):
            temp.append(m[j][i])
        m_t.append(temp)
    return m_t


def source_id(fname, method='sha1'):
    """Returns a hash-based identifier for the contents of fname using method.

    Any secure hash method supported by python's hashlib library is supported.
    Raises errors for invalid files or methods.

    """
    import hashlib
    with open(fname, 'rb') as fp:
        return hashlib.new(method, fp.read()).hexdigest()


def stop_task(cluster=None, task=None, reason=None):
    """
    Stops a running task.
    When  StopTask is called on a task, the equivalent of docker stop is issued to the containers running in the task. This results in a SIGTERM and a default 30-second timeout, after which SIGKILL is sent and the containers are forcibly stopped. If the container handles the SIGTERM gracefully and exits within 30 seconds from receiving it, no SIGKILL is sent.
    See also: AWS API Documentation

    :example: response = client.stop_task(
        cluster='string',
        task='string',
        reason='string'
    )

    :type cluster: string
    :param cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task to stop. If you do not specify a cluster, the default cluster is assumed.

    :type task: string
    :param task: [REQUIRED]
            The task ID or full Amazon Resource Name (ARN) entry of the task to stop.

    :type reason: string
    :param reason: An optional message specified when a task is stopped. For example, if you are using a custom scheduler, you can use this parameter to specify the reason for stopping the task here, and the message will appear in subsequent DescribeTasks API operations on this task. Up to 255 characters are allowed in this message.

    :rtype: dict
    :return: {
        'task': {
            'taskArn': 'string',
            'clusterArn': 'string',
            'taskDefinitionArn': 'string',
            'containerInstanceArn': 'string',
            'overrides': {
                'containerOverrides': [
                    {
                        'name': 'string',
                        'command': [
                            'string',
                        ],
                        'environment': [
                            {
                                'name': 'string',
                                'value': 'string'
                            },
                        ]
                    },
                ],
                'taskRoleArn': 'string'
            },
            'lastStatus': 'string',
            'desiredStatus': 'string',
            'containers': [
                {
                    'containerArn': 'string',
                    'taskArn': 'string',
                    'name': 'string',
                    'lastStatus': 'string',
                    'exitCode': 123,
                    'reason': 'string',
                    'networkBindings': [
                        {
                            'bindIP': 'string',
                            'containerPort': 123,
                            'hostPort': 123,
                            'protocol': 'tcp'|'udp'
                        },
                    ]
                },
            ],
            'startedBy': 'string',
            'version': 123,
            'stoppedReason': 'string',
            'createdAt': datetime(2015, 1, 1),
            'startedAt': datetime(2015, 1, 1),
            'stoppedAt': datetime(2015, 1, 1),
            'group': 'string'
        }
    }

    :returns:
    (string) --

    """
    pass


def KMeans(V, **kwargs):
    """Performs k-means clustering on *V*. The function uses :func:`sklearn.cluster.KMeans`. See sklearn documents
    for details.

    :arg V: row-normalized eigenvectors for the purpose of clustering.
    :type V: :class:`numpy.ndarray`

    :arg n_clusters: specifies the number of clusters.
    :type n_clusters: int
    """
    try:
        from sklearn.cluster import KMeans
    except ImportError:
        raise ImportError(
            'Use of this function (KMeans) requires the installation of sklearn.'
            )
    n_clusters = kwargs.get('n_clusters', None)
    if n_clusters is None:
        raise ValueError(
            'KMeans requires to desiginate the number of clusters.')
    n_init = kwargs.pop('n_init', 100)
    kmeans = KMeans(n_init=n_init, **kwargs).fit(V)
    return kmeans.labels_


def ceil(attrs, inputs, proto_obj):
    """ Calculate ceil value for input """
    return 'ceil', attrs, inputs


@classmethod
def iterates(cls, *base_args, **base_kwargs):
    """Get the Kaczmarz iterates.

        Note
        ----
        This method takes the same parameters as :class:`kaczmarz.Base`
        or the subclass from which it is called.
        For example, :meth:`kaczmarz.Cyclic.iterates`
        takes the same arguments as :class:`kaczmarz.Cyclic`.

        Parameters
        ----------
        base_args : tuple
            Positional arguments for :class:`kaczmarz.Base` constructor
            or the subclass in use.
        base_kwargs : dict
            Keyword arguments for :class:`kaczmarz.Base` constructor
            or the subclass in use.

        Returns
        -------
        iterates : iterable((n,) or (n, 1) array)
            An iterable of the Kaczmarz iterates.
            The shapes will match that of ``x0`` if provided,
            or ``b`` otherwise.
        """
    return cls(*base_args, **base_kwargs)


taqdir-2.1.3//تقدیر/کوائف.pyclass:کوائف/لاپتہ

def لاپتہ(خود, سارے=False):
    """
        نا معلوم دنوں کے کوائف واپس دیگا۔

        Parameters
        ----------
        سارے: bool
             صرف ان دنوں  کے کوائف دے گا جینکے سارےعمودی ستون کے کوائف نا معلوم ہیں۔

        Returns
        -------
        pd.PeriodIndex
        """
    if سارے:
        return خود.اعداد[خود.اعداد.isnull().all(axis=1)].index
    return خود.اعداد[خود.اعداد.isnull().any(axis=1)].index


def closer(x):
    """Helper to call close on x"""
    x.close()


@classmethod
def engine_created(cls, engine):
    """A convenience hook called before returning the final :class:`.Engine`.

        If the dialect returned a different class from the
        :meth:`.get_dialect_cls`
        method, then the hook is called on both classes, first on
        the dialect class returned by the :meth:`.get_dialect_cls` method and
        then on the class on which the method was called.

        The hook should be used by dialects and/or wrappers to apply special
        events to the engine or its components.   In particular, it allows
        a dialect-wrapping class to apply dialect-level events.

        .. versionadded:: 1.0.3

        """
    pass


def newMediaObject(blogid, username, password, struct):
    """The blogid, username and password params are as in the Blogger API.

        The struct must contain at least three elements, name, type and bits.

            - name is a string, it may be used to determine the name of the file
              that stores the object, or to display it in a list of objects. It
              determines how the weblog refers to the object. If the name is the
              same as an existing object stored in the weblog, it may replace
              the existing object.

            - type is a string, it indicates the type of the object, it's a
              standard MIME type, like audio/mpeg or image/jpeg or
              video/quicktime.

            - bits is a base64-encoded binary value containing the content of
              the object.

        The struct may contain other elements, which may or may not be stored by
        the content management system.

        If newMediaObject fails, it throws an error. If it succeeds, it returns
        a struct, which must contain at least one element, url, which is the url
        through which the object can be accessed. It must be either an FTP or
        HTTP url.
        """


def import_corpus(corpusfilename, vocabfilename, context_type='document'):
    """
    Converts an lda-c compatible data file into a VSM Corpus object.

    :param corpusfilename: path to corpus file, as defined in lda-c
    documentation.
    :type string:

    :param vocabfilename: path to vocabulary file, one word per line
    :type string:
    """
    pass


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

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


def json_get_value(json, path):
    """
    Get the value from specified json path

    json: json document
    path: a list of keys
    """
    crt = json
    for name in path:
        if name in crt:
            crt = crt[name]
        else:
            return None
    return crt


def get_dataobj(img):
    """ Return data object for nibabel image

    Parameters
    ----------
    img : ``SpatialImage`` instance
        Instance of nibabel ``SpatialImage`` class

    Returns
    -------
    dataobj : object
        ``ArrayProxy`` or ndarray object containing data for `img`
    """
    try:
        return img.dataobj
    except AttributeError:
        return img._data


@classmethod
def from_dict(cls, d: dict) ->'Machine':
    """
        Get an instance from a dict taken from :func:`~Machine.to_dict`
        """
    return cls(**d)


def _to_int(x):
    """Converts a completion and error code as it is listed in 32-bit notation
    in the VPP-4.3.2 specification to the actual integer value.
    """
    if x > 2147483647:
        return int(x - 4294967296)
    else:
        return int(x)


@property
def description(cls):
    """Return stripped class documentation string."""
    return cls.__doc__.strip()


@staticmethod
def _parse_mode(data):
    """Parses the measurement mode.

        :param data: Measurement output.

        :type data: `str`

        :return: A Mode string.
        :rtype: `str`

        """
    return data[8:10]


def get_db_func(dictdb, cmd):
    """
    Return callable function of method on ``dictdb``.

    :raises AssertionError: not a valid method or not callable.
    """
    assert hasattr(dictdb, cmd
        ), '{cmd!r} not a valid method of {db_type!r}'.format(cmd=cmd,
        db_type=type(dictdb))
    func = getattr(dictdb, cmd)
    assert callable(func
        ), '{cmd!r} not a callable method of {db_type!r}'.format(cmd=cmd,
        db_type=type(dictdb))
    return func


def gammaln(data=None, out=None, name=None, **kwargs):
    """Returns element-wise log of the absolute value of the gamma function \\
    of the input.

    The storage type of ``gammaln`` output is always dense

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

    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 from_none(exc):
    """raise from_none(ValueError('a')) == raise ValueError('a') from None"""
    exc.__cause__ = None
    exc.__suppress_context__ = True
    return exc


def apply_solution_scale(distance: float=0.0):
    """Apply scale on solution itself to make distance between selected tracks equals to desired

    :param distance: Distance, Distance between selected tracks
    :type distance: float
    """
    pass


def verify_job(job):
    """
    Verify job parameters for specific errors.
    Note:
      in case of problem, the function should set the corresponding pilot error code using
      job.piloterrorcodes, job.piloterrordiags = errors.add_error_code(error.get_error_code())

    :param job: job object
    :return: Boolean.
    """
    return True


def split_comma_seperated_option(option):
    """
    >>> split_comma_seperated_option(['foo,bar', 'baz'])
    ['foo', 'bar', 'baz']
    """
    result = []
    if option:
        for args in option:
            result.extend(args.split(','))
    return result


@staticmethod
def on_parsing(options, args):
    """Plugin hook to manipulate the command line parsing results.
        A tuple of values can be returned, which will replace (options, args).
        """


def GetComNode(APCG):
    """
	Find and return the communication node of APCG.
	"""
    ComNode = None
    for Node in APCG.nodes():
        if Node.GetType() == 'Communication':
            ComNode = Node
            break
    return ComNode


def nccopyAtt(ncin, ncout, excl=[]):
    """Function to copy attributes from an open netcdf file to another"""
    for attnm in ncin.ncattrs():
        if attnm in excl:
            continue
        ncout.setncattr(attnm, ncin.getncattr(attnm))


def _hash_wordlist(wordlist, hashing_algorithm):
    """Hashes each of the words in the wordlist and yields the digests for each
  word.

  Parameters:
    - wordlist: The wordlist which we'll be hashing.
    - hashing_obj: The hashlib hashing algorithm which we'll be passing to the
      appropriate function to actually hash the word.

  Yields:
    - Hexadecimal digest of the given word.

  """
    for word in wordlist:
        hashing_obj = hashing_algorithm.copy()
        hashing_obj.update(word.encode())
        return_string = hashing_obj.hexdigest() + ':' + word
        yield return_string


def p_typeA(p):
    """typeA : TYPE_BOOL
            | TYPE_FLOAT
            | TYPE_INT
            | TYPE_STRING
    """
    p[0] = p[1]


def s3_bucket(path):
    """ Get the bucket name """
    return path.replace('s3://', '').split('/')[0]


def insert_data(apps, schema_editor):
    """
    Inserts initial data for repetition and weight units

    Needed so that the migrations can go through without having to load any
    fixtures or perform any intermediate steps.
    """
    WeightUnit = apps.get_model('core', 'WeightUnit')
    WeightUnit(name='kg', pk=1).save()
    WeightUnit(name='lb', pk=2).save()
    WeightUnit(name='Body Weight', pk=3).save()
    WeightUnit(name='Plates', pk=4).save()
    WeightUnit(name='Kilometers Per Hour', pk=5).save()
    WeightUnit(name='Miles Per Hour', pk=6).save()
    RepetitionUnit = apps.get_model('core', 'RepetitionUnit')
    RepetitionUnit(name='Repetitions', pk=1).save()
    RepetitionUnit(name='Until Failure', pk=2).save()
    RepetitionUnit(name='Seconds', pk=3).save()
    RepetitionUnit(name='Minutes', pk=4).save()
    RepetitionUnit(name='Miles', pk=5).save()
    RepetitionUnit(name='Kilometers', pk=6).save()


@classmethod
def import_classes(cls, options=None):
    """Import puppet classes from puppet proxy."""
    cls.command_sub = 'import-classes'
    return cls.execute(cls._construct_command(options))


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


def add_empty_vol(in_file, out_file=None):
    """
    Adds an empty vol to the phase difference image
    """
    import nibabel as nb
    import os.path as op
    import numpy as np
    import math
    if out_file is None:
        fname, fext = op.splitext(op.basename(in_file))
        if fext == '.gz':
            fname, _ = op.splitext(fname)
        out_file = op.abspath('./%s_4D.nii.gz' % fname)
    im = nb.load(in_file)
    zim = nb.Nifti1Image(np.zeros_like(im.get_data()), im.affine, im.header)
    nb.funcs.concat_images([im, zim]).to_filename(out_file)
    return out_file


def _single_prefix_path(root):
    """ Return (single-prefix path, rest of tree with new root) """
    path = []
    tree = root
    node_links = root.node_links
    while len(tree) == 1:
        tree = next(iter(tree.values()))
        path.append((tree.item, tree.count))
        node_links.pop()
    tree.parent, tree.item, tree.node_links = None, None, node_links
    return path, tree


def threshold(data, delta=1e-07):
    """
    给定一组成双峰分布的数据 data 计算双峰之间的分界值

    Args:
        data : numpy.array
        delta: 精确度，默认 delta = 1e-7
    """
    threshold = m1 = m2 = data.mean()
    while True:
        g1 = data[data < threshold]
        g2 = data[data > threshold]
        m1 = g1.mean()
        m2 = g2.mean()
        t = (m1 + m2) / 2
        if abs(threshold - t) < delta:
            break
        threshold = t
    return threshold


@staticmethod
def _get_firstname(optional, k2v):
    """Get first name to be used as the display name."""
    if 'inn' in optional:
        return optional['inn']
    return k2v['name'][0]


def tokenize_spec(spec):
    """Tokenize a GitHub-style spec into parts, error if spec invalid."""
    spec_parts = spec.split('/', 2)
    if len(spec_parts) != 3:
        msg = ('Spec is not of the form "user/repo/ref", provided: "{spec}".'
            .format(spec=spec))
        if len(spec_parts) == 2 and spec_parts[-1] != 'master':
            msg += ' Did you mean "{spec}/master"?'.format(spec=spec)
        raise ValueError(msg)
    return spec_parts


def _move_active_host_to_head(hosts, active_host):
    """
    to improve efficiency move active host to head
    """
    hosts.remove(active_host)
    hosts.insert(0, active_host)


def different_of_cubes(a, b):
    """
    definition: func(a, b) {...}
    objective : gives you the result of the formula different of cubes
                (a-b)^3 = (a-b)(a^2 + ab + b^2)
    """
    result = (a - b) * (a * a + a * b + b * b)
    return result


@classmethod
def execute(cls, *args):
    """ Process the command-line arguments and run the relevant Command """
    parser = cls._configure()
    parsed = parser.parse_args(*args)
    Command = parsed.data['command']
    Command(**vars(parsed)).run()


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def pointInPolygon(pXY, xy):
    """Needs a doc string"""
    Inside = False
    N = len(pXY)
    p1x, p1y = pXY[0]
    for i in range(N + 1):
        p2x, p2y = pXY[i % N]
        if max(p1y, p2y) >= xy[1] > min(p1y, p2y) and xy[0] <= max(p1x, p2x):
            if p1y != p2y:
                xinters = (xy[1] - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
            if p1x == p2x or xy[0] <= xinters:
                Inside = not Inside
        p1x, p1y = p2x, p2y
    return Inside


def one(iterable, too_short=None, too_long=None):
    """Return the first item from *iterable*, which is expected to contain only
    that item. Raise an exception if *iterable* is empty or has more than one
    item.

    :func:`one` is useful for ensuring that an iterable contains only one item.
    For example, it can be used to retrieve the result of a database query
    that is expected to return a single row.

    If *iterable* is empty, ``ValueError`` will be raised. You may specify a
    different exception with the *too_short* keyword:

        >>> it = []
        >>> one(it)  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        ValueError: too many items in iterable (expected 1)'
        >>> too_short = IndexError('too few items')
        >>> one(it, too_short=too_short)  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        IndexError: too few items

    Similarly, if *iterable* contains more than one item, ``ValueError`` will
    be raised. You may specify a different exception with the *too_long*
    keyword:

        >>> it = ['too', 'many']
        >>> one(it)  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        ValueError: Expected exactly one item in iterable, but got 'too',
        'many', and perhaps more.
        >>> too_long = RuntimeError
        >>> one(it, too_long=too_long)  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        RuntimeError

    Note that :func:`one` attempts to advance *iterable* twice to ensure there
    is only one item. See :func:`spy` or :func:`peekable` to check iterable
    contents less destructively.

    """
    it = iter(iterable)
    try:
        first_value = next(it)
    except StopIteration:
        raise (too_short or ValueError(
            'too few items in iterable (expected 1)'))
    try:
        second_value = next(it)
    except StopIteration:
        pass
    else:
        msg = (
            'Expected exactly one item in iterable, but got {!r}, {!r}, and perhaps more.'
            .format(first_value, second_value))
        raise (too_long or ValueError(msg))
    return first_value


def get_complete_version(version):
    """
    Returns a tuple of the version. If version argument is non-empty,
    then checks for correctness of the tuple provided.
    """
    if not version:
        return 0, 0, 1, 'alpha', 0
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')
    return version


def get_possible_sgrp_suf(sgrp_nr):
    """
    determine possible space group suffix. Multiple suffixes might be possible
    for one space group due to different origin choice, unique axis, or choice
    of the unit cell shape.

    Parameters
    ----------
    sgrp_nr :   int
        space group number

    Returns
    -------
    str or list
        either an empty string or a list of possible valid suffix strings
    """
    sgrp_suf = ''
    if sgrp_nr in [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]:
        sgrp_suf = [':b', ':c']
    elif sgrp_nr in [48, 50, 59, 68, 70, 85, 86, 88, 125, 126, 129, 130,
        133, 134, 137, 138, 141, 142, 201, 203, 222, 224, 227, 228]:
        sgrp_suf = [':1', ':2']
    elif sgrp_nr in [146, 148, 155, 160, 161, 166, 167]:
        sgrp_suf = [':H', ':R']
    return sgrp_suf


def mask_hash(hash, show=6, char='*'):
    """
    Returns the given hash, with only the first ``show`` number shown. The
    rest are masked with ``char`` for security reasons.
    """
    masked = hash[:show]
    masked += char * len(hash[show:])
    return masked


def items():
    """ Return all cached keys and values

        Returns a sequence of (key, value) tuples.
        """


def do(task):
    """
        Perform the given task.

        As an interface, this method makes no specific claims about concurrent
        execution.  An L{IWorker}'s C{do} implementation may defer execution
        for later on the same thread, immediately on a different thread, or
        some combination of the two.  It is valid for a C{do} method to
        schedule C{task} in such a way that it may never be executed.

        It is important for some implementations to provide specific properties
        with respect to where C{task} is executed, of course, and client code
        may rely on a more specific implementation of C{do} than L{IWorker}.

        @param task: a task to call in a thread or other concurrent context.
        @type task: 0-argument callable

        @raise AlreadyQuit: if C{quit} has been called.
        """