def architecture_name_from_target(target):
    """
    Return architecture name from given LLDB target.

    :param lldb.SBTarget target: LLDB target.
    :return: Architecture name or None if cannot find architecture.
    :rtype: str | None
    """
    triple = target.GetTriple()
    """:type : str"""
    if triple.startswith('i386'):
        return 'i386'
    elif triple.startswith('x86_64'):
        return 'x86_64'
    elif triple.startswith('armv7'):
        return 'armv7'
    elif triple.startswith('armv7s'):
        return 'armv7s'
    elif triple.startswith('arm64'):
        return 'arm64'
    return None


def _is_json_mime(mime):
    """Is a key a JSON mime-type that should be left alone?"""
    return mime == 'application/json' or mime.startswith('application/'
        ) and mime.endswith('+json')


def __new__(cls, name, value, uom=None, min=None, max=None, context=None,
    contextobj=None, resource=None):
    """Creates new Metric instance.

        :param name: short internal identifier for the value -- appears
            also in the performance data
        :param value: data point, usually has a boolen or numeric type,
            but other types are also possible
        :param uom: :term:`unit of measure`, preferrably as ISO
            abbreviation like "s"
        :param min: minimum value or None if there is no known minimum
        :param max: maximum value or None if there is no known maximum
        :param context: name of the associated context (defaults to the
            metric's name if left out)
        :param contextobj: reference to the associated context object
            (set automatically by :class:`~nagiosplugin.check.Check`)
        :param resource: reference to the originating
            :class:`~nagiosplugin.resource.Resource` (set automatically
            by :class:`~nagiosplugin.check.Check`)
        """
    return tuple.__new__(cls, (name, value, uom, min, max, context or name,
        contextobj, resource))


def output_sequences(d, connect, fn):
    """Output sequences in Joe's format."""
    f = open(fn, 'w')
    for struct in list(d.structs.values()):
        f.write('%d:%s\n' % (0, struct.name))
        gc_content = (struct.seq.count('C') + struct.seq.count('G')) / (len
            (struct.seq) - len(struct.strands))
        f.write('%s %f %f %d\n' % (struct.seq, 0, gc_content, 0))
        f.write('%s\n' % struct.struct)
        f.write('%s\n' % struct.mfe_struct)
    for seq in list(d.seqs.values()):
        f.write('%d:%s\n' % (0, seq.name))
        gc_content = (seq.seq.count('C') + seq.seq.count('G')) / seq.length
        f.write('%s %f %f %d\n' % (seq.seq, 0, gc_content, 0))
        f.write(('.' * seq.length + '\n') * 2)
        seq = seq.wc
        f.write('%d:%s\n' % (0, seq.name))
        f.write('%s %f %f %d\n' % (seq.seq, 0, gc_content, 0))
        f.write(('.' * seq.length + '\n') * 2)
    f.write('Total n(s*) = %f' % 0)
    f.close()


def modify_keepout(laminate, is_adhesive):
    """is this better than other algorithms"""
    for ii, (test, layer) in enumerate(zip(laminate, is_adhesive)):
        if test:
            l = laminate[ii]
            if ii > 0:
                l |= laminate[ii - 1]
            if ii < len(laminate) - 1:
                l |= laminate[ii + 1]
            laminate[ii] = l
    return laminate


def _dump_list_np(obj, h5f, **kwargs):
    """ Dump a list of numpy objects to file """
    np_group = h5f.create_group('data')
    h5f.create_dataset('type', data=['np_list'])
    ii = 0
    for np_item in obj:
        np_group.create_dataset('%s' % ii, data=np_item, **kwargs)
        ii += 1


def getNextInThread(message_id):
    """Returns a proxy for the next message in the thread"""


def format_RFC4180(original_value):
    """
    Transform the value from the key-value pairs of a flattened JSON in
    RFC4180-compliant. This is, remove "None" values and duplicate inner
    double quotes.
    Added removal of newlines and carriage returns, which are really
    troublesome in CSVs
    """
    new_value = str(original_value).strip().replace('"', '""')
    new_value = new_value.replace('\n', ' ')
    new_value = new_value.replace('\r', ' ')
    new_value = new_value.replace('None', '')
    new_value = '"' + new_value + '"'
    return new_value


def _log(something):
    """
    Uninspired logging utility. Overwrite at will.
    Use the `logging` module instead of print ?
    """
    print('%s' % something)


def save(df, name):
    """
    Save a dataframe as a csv and pickle file

    :param df: (pd.DataFrame) - dataframe to save
    :param name: (str) - output name
    :return name: (str) - output name
    """
    df.to_csv('{0}.csv'.format(name))
    df.to_pickle('{0}.pkl'.format(name))
    return name


def get_list_entries(*args):
    """
    Utility to return only certain values of a given list based on the indices.

    :param args: list and indices
    :type args: list and int
    :return: list with requested values at indices
    :rtype: list
    """
    assert isinstance(args[0], list), 'First argument should be a list.'
    assert len(args) > 1, 'At least two arguments are required.'
    input_list = args[0]
    return_list = []
    for arg in args[1:]:
        assert isinstance(arg, int), 'Indices should be integers.'
        return_list.append(input_list[arg])
    return return_list


def _is_method(func, cls):
    """Check if func is a method of cls.

    The previous way to do this using isinstance(types.MethodType) is not
    compatible with Python 3 (which no more has unbound methods). So one way to
    do this is to check if func is an attribute of cls, and has a __name__
    attribute.

    """
    try:
        getattr(cls, func.__name__)
    except AttributeError:
        return False
    else:
        return True


def find_section(section, lines):
    """
    Find a named section in a ``numpy``-formatted docstring.

    Parameters
    ----------
    section : string
        The name of the section to find

    lines : array of string
        The docstring, split into lines

    Returns
    -------
    int, int
        The indices of the first and last lines of the section.
    """
    first_line = None
    for i, line in enumerate(lines):
        if '----' in line and i > 0 and section in lines[i - 1]:
            first_line = i + 1
            break
    if first_line is None:
        return None, None
    last_line = None
    for i in range(first_line, len(lines)):
        if '---' in lines[i]:
            last_line = i - 2
            break
    if last_line is None:
        last_line = len(lines) - 1
    return first_line, last_line


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


def _start_upperbound(versions, version, condition):
    """Gets all versions from [start, version] that meet condition.

    :param versions: the tree of versions.
    :param version: the required version
    :param condition: condition for search
    :return: the list of found versions
    """
    result = list(versions.value_slice(None, version))
    try:
        bound = versions.ceiling_item(version)
        if condition(bound[0], version):
            result.append(bound[1])
    except KeyError:
        pass
    return result


def render_preload():
    """method for rendering the portlet in preloading state

        this usually just contains a class to which an KSS event is bound
        """


@classmethod
def getFormula(cls, rec):
    """Get the formula field string"""
    if not type(rec) is dict:
        return None
    string = rec['formula']
    return string


def Relay():
    """
    Used by proxy transport to route packets in/out via third node.
    """
    return 'Relay'


def filter_arglist(args, defaults, bound_argnames):
    """
    Filters a list of function argument nodes (``ast.arg``)
    and corresponding defaults to exclude all arguments with the names
    present in ``bound_arguments``.
    Returns a pair of new arguments and defaults.
    """
    new_args = []
    new_defaults = []
    required_args = len(args) - len(defaults)
    for i, arg in enumerate(args):
        if arg.arg not in bound_argnames:
            new_args.append(arg)
            if i >= required_args:
                new_defaults.append(defaults[i - required_args])
    return new_args, new_defaults


def dbnd_operator__get_task_retry_delay(dbnd_operator):
    """
    This method overrides the task retry delay found in airflow.
    We must override the actual task retry delay from airflow to ensure that we can control the retry delay
    per task, for example when we send pods to retry, we may want a different delay rather than another engine
    """
    import datetime
    from dbnd._core.current import try_get_databand_run
    run = try_get_databand_run()
    if not run:
        return
    task_run = run.get_task_run_by_id(dbnd_operator.dbnd_task_id)
    if task_run.task_engine.task_definition.task_family == 'kubernetes':
        return task_run.task_engine.pod_retry_delay
    else:
        return task_run.task.task_retry_delay


def fixspacing(s):
    """ Try to make the output prettier by inserting blank lines
        in random places.
    """
    result = []
    indent = -1
    for line in s.splitlines():
        line = line.rstrip()
        if not line:
            continue
        indent, previndent = len(line) - len(line.lstrip()), indent
        if indent <= previndent and indent < 8:
            if indent < previndent or not indent:
                result.append('')
        result.append(line)
    result.append('')
    return '\n'.join(result)


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 script(fpath, s):
    """
    Create a executable file include command s.
    :param fpath: file path (include name.)
    :param s: file content.
    :return: fpath.
    """
    import os
    fpath = os.path.abspath(fpath)
    with open(fpath, 'w') as f:
        f.write(s + '\n')
    os.system('chmod +x ' + fpath)
    return fpath


def consume():
    """consumes the items from the stack, and sets the __name__
        and attributes"""


def _read_genel_fields_until_char_blank(card_fields, istart):
    """somewhat loose parser helper function for GENEL"""
    new_fields = []
    i = 0
    for i, field in enumerate(card_fields[istart:]):
        if field is None:
            break
        if field.upper() in ['UD', 'K', 'S', 'Z']:
            break
        new_fields.append(field)
    return new_fields, istart + i


def dFF_martian(data, rm_window, signal='Gcamp', reference='Isosbestic',
    rm_nans='fill', lambda_=100, porder=1, itermax=15):
    """
    Calculates dF/F for a given signal and reference.
    This method is adapted from Martianova, Aronson, & Proulx Multi-Fiber Photometry
    to Record Neural activity in Freely Moving Animal. 2019 JOVE

    inputs
      args:
        data: pandas dataframe containing columns for signal and reference
        rm_window: int representing window for calculating running mean (i.e. sample freq * time window)
      kwargs:
        signal: string containing column name for signal
        reference: string containing column name for reference
        rm_nans: string indicating how NaNs should be handeled after rolling running_mean ('fill' or 'clip')
        lambda_: int for lambda_ value in airPLS (larger values results in smoother baseline estimation)
        porder: int for porder in airPLS
        itermax: int for maximum number of iterations for airPLS

    returns
        data: pandas dataframe containing original data, new columns with intermediate calculations, and dFF_signal

    """
    import numpy as np
    import pandas as pd
    from ._steps import z_score, scale_Isos, calc_dF_F
    from ._smooth import running_mean
    from ._baseline_correction import WhittakerSmooth, airPLS
    from sklearn.linear_model import Lasso
    data['rm_%s' % signal] = running_mean(data[signal], rm_window)
    data['rm_%s' % reference] = running_mean(data[reference], rm_window)
    if rm_nans != 'clip' and rm_nans != 'fill':
        rm_nans = 'fill'
        print('Invalid input for rm_nans, defaulting to "fill"')
    if rm_nans == 'clip':
        data = data[pd.notnull(data['rm_%s' % signal])].copy()
    if rm_nans == 'fill':
        data = data.fillna(method='bfill')
    data['blc_%s' % reference] = data['rm_%s' % reference] - airPLS(data[
        'rm_%s' % reference], lambda_=lambda_, porder=porder, itermax=itermax)
    data['blc_%s' % signal] = data['rm_%s' % signal] - airPLS(data['rm_%s' %
        signal], lambda_=lambda_, porder=porder, itermax=itermax)
    data['z_%s' % reference] = z_score(data['blc_%s' % reference])
    data['z_%s' % signal] = z_score(data['blc_%s' % signal])
    lin = Lasso(alpha=0.0001, precompute=True, max_iter=1000, positive=True,
        random_state=9999, selection='random')
    lin.fit(np.array(data['z_%s' % reference]).reshape(-1, 1), np.array(
        data['z_%s' % signal]).reshape(-1, 1))
    z_reference_fitted = lin.predict(np.array(data['z_%s' % reference]).
        reshape(-1, 1))
    data['scaled_%s' % reference] = list(z_reference_fitted)
    data['dFF_%s' % signal] = data['z_%s' % signal] - data['scaled_%s' %
        reference]
    return data


def p_static_expr_group(p):
    """static_expr : LPAREN static_expr RPAREN"""
    p[0] = p[2]


@classmethod
def from_file(cls, tmpl_path, *args, **kwargs):
    """ Alternative constructor -> Creates a template from a file. """
    with open(tmpl_path, 'r') as tmpl_f:
        template_string = tmpl_f.read()
    return cls(template_string, *args, **kwargs)


def get_jvm_class(cl):
    """Builds JVM class name from Python class
    """
    return 'org.apache.{}.{}'.format(cl.__module__[2:], cl.__name__)


def update_pipeline(pipeline=None):
    """
    Updates a specified pipeline with edits or changes to its structure. Use a JSON file with the pipeline structure in conjunction with UpdatePipeline to provide the full structure of the pipeline. Updating the pipeline increases the version number of the pipeline by 1.
    See also: AWS API Documentation

    :example: response = client.update_pipeline(
        pipeline={
            'name': 'string',
            'roleArn': 'string',
            'artifactStore': {
                'type': 'S3',
                'location': 'string',
                'encryptionKey': {
                    'id': 'string',
                    'type': 'KMS'
                }
            },
            'stages': [
                {
                    'name': 'string',
                    'blockers': [
                        {
                            'name': 'string',
                            'type': 'Schedule'
                        },
                    ],
                    'actions': [
                        {
                            'name': 'string',
                            'actionTypeId': {
                                'category': 'Source'|'Build'|'Deploy'|'Test'|'Invoke'|'Approval',
                                'owner': 'AWS'|'ThirdParty'|'Custom',
                                'provider': 'string',
                                'version': 'string'
                            },
                            'runOrder': 123,
                            'configuration': {
                                'string': 'string'
                            },
                            'outputArtifacts': [
                                {
                                    'name': 'string'
                                },
                            ],
                            'inputArtifacts': [
                                {
                                    'name': 'string'
                                },
                            ],
                            'roleArn': 'string'
                        },
                    ]
                },
            ],
            'version': 123
        }
    )

    :type pipeline: dict
    :param pipeline: [REQUIRED]
            The name of the pipeline to be updated.
            name (string) -- [REQUIRED]The name of the action to be performed.
            roleArn (string) -- [REQUIRED]The Amazon Resource Name (ARN) for AWS CodePipeline to use to either perform actions with no actionRoleArn, or to use to assume roles for actions with an actionRoleArn.
            artifactStore (dict) -- [REQUIRED]The Amazon S3 location where artifacts are stored for the pipeline. If this Amazon S3 bucket is created manually, it must meet the requirements for AWS CodePipeline. For more information, see the Concepts .
            type (string) -- [REQUIRED]The type of the artifact store, such as S3.
            location (string) -- [REQUIRED]The location for storing the artifacts for a pipeline, such as an S3 bucket or folder.
            encryptionKey (dict) --The encryption key used to encrypt the data in the artifact store, such as an AWS Key Management Service (AWS KMS) key. If this is undefined, the default key for Amazon S3 is used.
            id (string) -- [REQUIRED]The ID used to identify the key. For an AWS KMS key, this is the key ID or key ARN.
            type (string) -- [REQUIRED]The type of encryption key, such as an AWS Key Management Service (AWS KMS) key. When creating or updating a pipeline, the value must be set to 'KMS'.

            stages (list) -- [REQUIRED]The stage in which to perform the action.
            (dict) --Represents information about a stage and its definition.
            name (string) -- [REQUIRED]The name of the stage.
            blockers (list) --Reserved for future use.
            (dict) --Reserved for future use.
            name (string) -- [REQUIRED]Reserved for future use.
            type (string) -- [REQUIRED]Reserved for future use.

            actions (list) -- [REQUIRED]The actions included in a stage.
            (dict) --Represents information about an action declaration.
            name (string) -- [REQUIRED]The action declaration's name.
            actionTypeId (dict) -- [REQUIRED]The configuration information for the action type.
            category (string) -- [REQUIRED]A category defines what kind of action can be taken in the stage, and constrains the provider type for the action. Valid categories are limited to one of the values below.
            owner (string) -- [REQUIRED]The creator of the action being called.
            provider (string) -- [REQUIRED]The provider of the service being called by the action. Valid providers are determined by the action category. For example, an action in the Deploy category type might have a provider of AWS CodeDeploy, which would be specified as CodeDeploy.
            version (string) -- [REQUIRED]A string that identifies the action type.
            runOrder (integer) --The order in which actions are run.
            configuration (dict) --The action declaration's configuration.
            (string) --
            (string) --

            outputArtifacts (list) --The name or ID of the result of the action declaration, such as a test or build artifact.
            (dict) --Represents information about the output of an action.
            name (string) -- [REQUIRED]The name of the output of an artifact, such as 'My App'.
            The input artifact of an action must exactly match the output artifact declared in a preceding action, but the input artifact does not have to be the next action in strict sequence from the action that provided the output artifact. Actions in parallel can declare different output artifacts, which are in turn consumed by different following actions.
            Output artifact names must be unique within a pipeline.

            inputArtifacts (list) --The name or ID of the artifact consumed by the action, such as a test or build artifact.
            (dict) --Represents information about an artifact to be worked on, such as a test or build artifact.
            name (string) -- [REQUIRED]The name of the artifact to be worked on, for example, 'My App'.
            The input artifact of an action must exactly match the output artifact declared in a preceding action, but the input artifact does not have to be the next action in strict sequence from the action that provided the output artifact. Actions in parallel can declare different output artifacts, which are in turn consumed by different following actions.

            roleArn (string) --The ARN of the IAM service role that will perform the declared action. This is assumed through the roleArn for the pipeline.

            version (integer) --The version number of the pipeline. A new pipeline always has a version number of 1. This number is automatically incremented when a pipeline is updated.

    :rtype: dict
    :return: {
        'pipeline': {
            'name': 'string',
            'roleArn': 'string',
            'artifactStore': {
                'type': 'S3',
                'location': 'string',
                'encryptionKey': {
                    'id': 'string',
                    'type': 'KMS'
                }
            },
            'stages': [
                {
                    'name': 'string',
                    'blockers': [
                        {
                            'name': 'string',
                            'type': 'Schedule'
                        },
                    ],
                    'actions': [
                        {
                            'name': 'string',
                            'actionTypeId': {
                                'category': 'Source'|'Build'|'Deploy'|'Test'|'Invoke'|'Approval',
                                'owner': 'AWS'|'ThirdParty'|'Custom',
                                'provider': 'string',
                                'version': 'string'
                            },
                            'runOrder': 123,
                            'configuration': {
                                'string': 'string'
                            },
                            'outputArtifacts': [
                                {
                                    'name': 'string'
                                },
                            ],
                            'inputArtifacts': [
                                {
                                    'name': 'string'
                                },
                            ],
                            'roleArn': 'string'
                        },
                    ]
                },
            ],
            'version': 123
        }
    }

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

    """
    pass


def user_confirm(prompt, default=False):
    """Yes/No question dialog with user.

    :param prompt: question/statement to present to user (string)
    :param default: boolean value to return if empty string
                    is received as response to prompt

    """
    if default:
        prompt_default = '[Y/n]'
    else:
        prompt_default = '[y/N]'
    answer = input('%s %s ' % (prompt, prompt_default))
    if answer == '':
        return default
    else:
        return answer.lower() in ('yes', 'y')


def outdated_images(images, cutoff=10):
    """
    Returns the oldest images to a cutoff (by default 10)

    Returns
        * A list of image names.

    """
    outdated = []
    sorted_images = sorted(images, key=lambda i: i['Created'])
    for image in sorted_images:
        for repo in image['RepoTags']:
            if repo not in outdated:
                outdated.append(repo)
                if len(outdated) >= cutoff:
                    return outdated
    return outdated


def count_lines(text):
    """Return the number of lines in text."""
    return text.count('\n')


def circuit_failed(circuit, **kw):
    """
        A circuit has been closed because something went wrong.

        The circuit won't be in the TorState's list anymore.

        :param kw:
            A dict of additional args. REASON is alsways included, and
            often REMOTE_REASON also. See the control-spec
            documentation.  As of this writing, REASON is one of the
            following strings: MISC, RESOLVEFAILED, CONNECTREFUSED,
            EXITPOLICY, DESTROY, DONE, TIMEOUT, NOROUTE, HIBERNATING,
            INTERNAL,RESOURCELIMIT, CONNRESET, TORPROTOCOL,
            NOTDIRECTORY, END, PRIVATE_ADDR. However, don't depend on
            that: it could be anything.

            To facilitate declaring args you want in the method
            (e.g. ``circuit_failed(self, circuit, reason=None,
            remote_reason=None, **kw)``) lower-case versions of all the
            keys are also provided (pointing to the same -- usually
            UPPERCASE -- strings as the upper-case keys).
        """


@classmethod
def _get_android_keystore_prefix(cls):
    """
        Returns the Android keystore path prefix.
        The location differs based on the persistency user settings.
        """
    if cls.is_persistent_keystore():
        keystore_dir_prefix = cls.get_persistent_keystore_path()
    else:
        keystore_dir_prefix = cls.get_non_persistent_keystore_path()
    return keystore_dir_prefix


@staticmethod
def _generate_data(phg: str=None, rng: str=None, dfs: str=None, course: int
    =None, speed: int=None, altitude: int=None, comment: str=None) ->str:
    """
        Generate additional information for the information field.

        :param str phg: a PHG value
        :param str rng: an RNG value
        :param str dfs: a DFS value
        :param int course: course, in degrees
        :param int speed: speed, in knots
        :param int altitude: altitude, in feet
        :param str comment: a comment

        Position packets can have additional information in them, such as station power, antenna
        height, antenna gain, etc. These are described in APRS 1.01 C7. This will generate an
        information field based on these values.

        Note that PHG, RNG, DFS and course/speed are mutually exclusive. Altitude is specified as
        part of the comment and so can coexist with any of the other values.
        """
    data = ''
    if phg:
        data += phg
    elif rng:
        data += rng
    elif dfs:
        data += dfs
    elif course and speed:
        data += '{}/{}'.format(str(course).zfill(3), str(speed).zfill(3))
    if altitude:
        data += '/A={}'.format(str(altitude).zfill(6))
    if comment:
        data += comment
    return data


def get_wsgi_header(header):
    """Returns a WSGI compliant HTTP header.
    See https://www.python.org/dev/peps/pep-3333/#environ-variables for
    information from the spec.
    """
    return 'HTTP_{}'.format(header.upper().replace('-', '_'))


def select_previous():
    """Select control points preceding already selected ones along the curves

    """
    pass


def contour(z, x=None, y=None, filled=None, xlim=None, ylim=None, xinvert=
    False, yinvert=False, xlog=False, ylog=False, title=None, xlabel=None,
    ylabel=None, lab_loc=0, ax=None, grid=None, plot_kw={}, **kwargs):
    """Level contour plotting function.

	This is a wrapper for pyplot.contour() and pyplot.contourf().

	Parameters
	----------
	z : array-like
		The height values to draw the contours.
	x : array-like, optional
		Position of data points in the x axis.
	y : array-like, optional
		Position of data points in the y axis.
	filled: boolean, optional
		If True, draws filled contours. If not given defaults to the value defined in splotch.Params.
	xlim : tuple-like, optional
		Defines the limits of the x-axis, it must contain two elements (lower and higer limits).
	ylim : tuple-like, optional
		Defines the limits of the y-axis, it must contain two elements (lower and higer limits).
	xinvert : bool, optional
		If True, inverts the x-axis.
	yinvert : bool, optional
		If True, inverts the y-axis.
	xlog : bool, optional
		If True, the scale of the x-axis is logarithmic. If not given defaults to the value defined in splotch.Params.
	ylog : bool, optional
		If True, the scale of the x-axis is logarithmic. If not given defaults to the value defined in splotch.Params.
	title : str, optional
		Sets the title of the plot
	xlabel : str, optional
		Sets the label of the x-axis.
	ylabel : str, optional
		Sets the label of the y-axis.
	lab_loc : int, optional
		Defines the position of the legend
	ax : pyplot.Axes, optional
		Use the given axes to make the plot, defaults to the current axes.
	grid : boolean, optional
		If not given defaults to the value defined in splotch.Params.
	output : boolean, optional
		If True, returns the edges and values of the underlying histogram plus the levels of the contours.
	plot_kw : dict, optional
		Passes the given dictionary as a kwarg to the plotting function. Valid kwargs are QuadContourSet properties.
	**kwargs: QuadContourSet properties, optional
		kwargs are used to specify matplotlib specific properties such as cmap, linewidths, hatches, etc.
		The list of available properties can be found here:
		https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contour.html

	Returns
	-------
	bin_edges_x : array
		The bin edges for the x axis.
	bin_edges_y : array
		The bin edges for the y axis.
	n : array
		The values of the underlying histogram.
	l : array
		The levels for the contours.
	"""
    from numpy import shape, linspace
    from matplotlib.pyplot import contour, contourf, legend
    from .base_func import axes_handler, dict_splicer, plot_finalizer
    if ax is not None:
        old_axes = axes_handler(ax)
    if filled is None:
        from .defaults import Params
        filled = Params.cont_filled
    if x is None:
        x = linspace(0, 1, z.shape[0])
    if y is None:
        y = linspace(0, 1, z.shape[1])
    plot_par = plot_kw.copy()
    plot_par.update(kwargs)
    plotf = {(False): contour, (True): contourf}
    plotf[filled](x, y, z, **plot_par)
    plot_finalizer(xlog, ylog, xlim, ylim, title, xlabel, ylabel, xinvert,
        yinvert, grid)
    if ax is not None:
        old_axes = axes_handler(old_axes)


def mathrm2mathsf(texstr):
    """Convert math roman LaTeX string to math sans-serif LaTeX string.

    Parameters
    ----------
    txtstr : str

    Returns
    -------
    str

    """
    return texstr.replace('mathrm', 'mathsf')


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


def line_is_heading(line):
    """Check whether a line of output generated by :func:`report_metrics()` should be highlighted as a heading."""
    return line.endswith(':')


def list_endpoints_by_platform_application(PlatformApplicationArn=None,
    NextToken=None):
    """
    Lists the endpoints and endpoint attributes for devices in a supported push notification service, such as GCM and APNS. The results for ListEndpointsByPlatformApplication are paginated and return a limited list of endpoints, up to 100. If additional records are available after the first page results, then a NextToken string will be returned. To receive the next page, you call ListEndpointsByPlatformApplication again using the NextToken string received from the previous call. When there are no more records to return, NextToken will be null. For more information, see Using Amazon SNS Mobile Push Notifications .
    See also: AWS API Documentation

    :example: response = client.list_endpoints_by_platform_application(
        PlatformApplicationArn='string',
        NextToken='string'
    )

    :type PlatformApplicationArn: string
    :param PlatformApplicationArn: [REQUIRED]
            PlatformApplicationArn for ListEndpointsByPlatformApplicationInput action.

    :type NextToken: string
    :param NextToken: NextToken string is used when calling ListEndpointsByPlatformApplication action to retrieve additional records that are available after the first page results.

    :rtype: dict
    :return: {
        'Endpoints': [
            {
                'EndpointArn': 'string',
                'Attributes': {
                    'string': 'string'
                }
            },
        ],
        'NextToken': 'string'
    }

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

    """
    pass


def bookmark_toggle():
    """Toggle bookmarks display

    """
    pass


@classmethod
def __parse_service(cls, xserv):
    """
            Parse <service> tag to manage CPE object
        """
    _service = cls.__format_attributes(xserv)
    _cpelist = []
    for _servnode in xserv:
        if _servnode.tag == 'cpe':
            _cpe_string = _servnode.text
            _cpelist.append(_cpe_string)
    _service['cpelist'] = _cpelist
    return _service


def find_edges(mesh, key):
    """ Temp replacement for mesh.findEdges().
        This is painfully slow.
    """
    for edge in mesh.edges:
        v = edge.vertices
        if key[0] == v[0] and key[1] == v[1]:
            return edge.index


def time_correction(EoT, longitude, GMTOffset):
    """Return the time correction (minutes) where EoT is the equation of time,
    and given location longitude (degrees) and the GMT offset (hours)"""
    LSTM = 15.0 * GMTOffset
    TimeCorrection = 4.0 * (longitude - LSTM) + EoT
    return TimeCorrection


@classmethod
def get_type(cls):
    """
        This function is called when the unmounted type (Scalar instance)
        is mounted (as a Field, InputField or Argument)
        """
    return cls


def _encode_uvarint(data, n):
    """ Encodes integer into variable-length format into data."""
    if n < 0:
        raise ValueError('only support positive integer')
    while True:
        this_byte = n & 127
        n >>= 7
        if n == 0:
            data.append(this_byte)
            break
        data.append(this_byte | 128)


def parse_unified_diff_output(lines):
    """
    Parses the unified diff output of two files.

    :param lines: diff lines
    :type lines: [str]
    :returns: pair of adds and removes, where each is a list of trimmed lines
    :rtype: ([str], [str])
    """
    adds = []
    removes = []
    for line in lines:
        if len(line) > 2 and (line[:3] == '+++' or line[:3] == '---'):
            continue
        elif len(line) > 1 and line[:2] == '@@':
            continue
        elif len(line) > 0 and line[0] == '+':
            added_line = line[1:].lstrip().rstrip()
            if len(added_line) == 0:
                continue
            adds = adds + [added_line]
        elif len(line) > 0 and line[0] == '-':
            removed_line = line[1:].lstrip().rstrip()
            if len(removed_line) == 0:
                continue
            removes = removes + [removed_line]
    return adds, removes


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

        :param files.SyncSettingsError val:
        :rtype: TeamFolderCreateError
        """
    return cls('sync_settings_error', val)


@staticmethod
def from_excel(path, worksheet=0):
    """Return a reader object which will iterate over lines in the
        given Excel worksheet. *path* must specify to an XLSX or XLS
        file and *worksheet* should specify the index or name of the
        worksheet to load (defaults to the first worksheet).

        Load first worksheet::

            reader = get_reader.from_excel('mydata.xlsx')

        Specific worksheets can be loaded by name (a string) or
        index (an integer)::

            reader = get_reader.from_excel('mydata.xlsx', 'Sheet 2')

        .. note::

            This constructor requires the optional, third-party
            library xlrd.
        """
    try:
        import xlrd
    except ImportError:
        raise ImportError(
            """No module named 'xlrd'

This is an optional constructor that requires the third-party library 'xlrd'."""
            )
    book = xlrd.open_workbook(path, on_demand=True)
    try:
        if isinstance(worksheet, int):
            sheet = book.sheet_by_index(worksheet)
        else:
            sheet = book.sheet_by_name(worksheet)
        for index in range(sheet.nrows):
            yield sheet.row_values(index)
    finally:
        book.release_resources()


@classmethod
def from_schema(cls, schema, schema_registry=None):
    """Construct a ComponentSchema from a schema.

        Args:
            schema (dict): Schema.

        Returns:
            ComponentSchema: Schema with information from schema.

        """
    schema_type = schema['title']
    out = cls(schema_type, schema_registry=schema_registry)
    out._base_schema = schema['allOf'][0]
    subt_schema = schema['allOf'][1]['anyOf']
    for v in subt_schema:
        out._storage[v['title']] = v
        subtypes = v['properties'][out.subtype_keys[0]]['enum']
        out.schema_subtypes[v['title']] = subtypes
    return out


def pre_hook():
    """A plugin hook called in the first initialization step.

        This is called before the database is initialized.
        """


def extend(hub, name, state, sls_ref):
    """
    Resolve the extend statement
    """
    if 'extend' in state:
        ext = state.pop('extend')
        if not isinstance(ext, dict):
            hub.idem.RUNS[name]['errors'].append(
                f'Extension value in SLS "{sls_ref}" is not a dictionary')
            return
        for id_ in ext:
            if not isinstance(ext[id_], dict):
                hub.idem.RUNS[name]['errors'].append(
                    f'Extension ID "{id_}" in SLS "{sls_ref}" is not a dictionary'
                    )
                continue
            if '__sls__' not in ext[id_]:
                ext[id_]['__sls__'] = sls_ref
            for key in list(ext[id_]):
                if key.startswith('_'):
                    continue
                if not isinstance(ext[id_][key], list):
                    continue
                if '.' in key:
                    comps = key.split('.')
                    ext[id_][comps[0]] = ext[id_].pop(key)
                    ext[id_][comps[0]].append(comps[1])
        state.setdefault('__extend__', []).append(ext)


@classmethod
def is_produced(kls, obj):
    """ Provide a hook for customizing ways to check produced output
        """
    return isinstance(obj, kls.__swagger_ref_object__)


def delete_repo(repo):
    """Delete given repository."""
    repo.delete()
    print('{} was deleted.\n'.format(repo.full_name))


def kth_to_last(head, k):
    """
    This is an optimal method using iteration.
    We move p1 k steps ahead into the list.
    Then we move p1 and p2 together until p1 hits the end.
    """
    if not (head or k > -1):
        return False
    p1 = head
    p2 = head
    for i in range(1, k + 1):
        if p1 is None:
            raise IndexError
        p1 = p1.next
    while p1:
        p1 = p1.next
        p2 = p2.next
    return p2


def __load_default_wordlists():
    """ Populates the lists with default content.
    """
    wordlists = {'nouns': [], 'adjectives': []}
    wordlists['nouns'].extend(['axel', 'babbage', 'baby', 'ballmer', 'bay',
        'bishop', 'bulbasaur', 'charles', 'charlie', 'charmander',
        'clarice', 'doctor', 'doge', 'drone', 'einstein', 'failfishfeynman',
        'fish', 'gates', 'grump', 'horton', 'jessica', 'jobs', 'johnson',
        'king', 'metcalfe', 'mew', 'michael', 'nicholas', 'pimp', 'priest',
        'roadrunner', 'tacocat', 'transformers', 'voltorb', 'wayne',
        'worker', 'zuckerberg'])
    wordlists['adjectives'].extend(['adorable', 'bigoted', 'bouncy',
        'charming', 'chipper', 'comical', 'crass', 'creepy', 'cross',
        'dangerous', 'despressed', 'diminished', 'disfigured', 'disturbed',
        'ecstatic', 'electric', 'enlightened', 'excited', 'failing',
        'faithful', 'fastidious', 'fervent', 'firey', 'flying', 'frazzled',
        'freaky', 'friendly', 'frustrated', 'gloomy', 'glum', 'gnarled',
        'gross', 'hurtful', 'immune', 'intense', 'jealous', 'likable',
        'livid', 'massive', 'nasty', 'naughty', 'nosey', 'offended',
        'overzealous', 'peculiar', 'perfunctory', 'pleasant', 'pokey',
        'pontiferous', 'ravishing', 'resourceful', 'ridiculous', 'riveting',
        'rowdy', 'sad', 'smashed', 'smelly', 'spectacular', 'terrified',
        'voltaic'])
    return wordlists


def unlink():
    """Unlink active font data-block

    """
    pass


def evaluate_expression(expression, vars):
    """evaluation an expression"""
    try:
        v = eval(expression, globals(), vars)
    except NameError:
        return None
    except ZeroDivisionError:
        return None
    except IndexError:
        return None
    return v


def _check_is_max_context(doc_spans, cur_span_index, position):
    """Check if this is the 'max context' doc span for the token."""
    best_score = None
    best_span_index = None
    for span_index, doc_span in enumerate(doc_spans):
        end = doc_span.start + doc_span.length - 1
        if position < doc_span.start:
            continue
        if position > end:
            continue
        num_left_context = position - doc_span.start
        num_right_context = end - position
        score = min(num_left_context, num_right_context
            ) + 0.01 * doc_span.length
        if best_score is None or score > best_score:
            best_score = score
            best_span_index = span_index
    return cur_span_index == best_span_index


def _check_argument_units(args, defaults, dimensionality):
    """Yield arguments with improper dimensionality."""
    for arg, val in args.items():
        try:
            need, parsed = dimensionality[arg]
        except KeyError:
            continue
        if arg in defaults:
            check = val == defaults[arg]
            if check:
                continue
        try:
            if val.dimensionality != parsed:
                yield arg, val.units, need
        except AttributeError:
            if parsed != '':
                yield arg, 'none', need


@classmethod
def Extsearch(cls, _ext_, _path_='C:'):
    """
        Return a list with all the files with the specified extension in the specified path.
        """
    import os
    _result = []
    _path_ = _path_ + '\\'
    for RootDir, _Fldrs_, Ext_Srch in os.walk(_path_):
        for __files__ in Ext_Srch:
            if __files__.endswith(_ext_):
                __pth = RootDir + '\\' + __files__
                _result.append(__pth)
    return _result


def is_among(value, *possibilities):
    """Ensure that the method that has been used for the request is one of the expected ones (e.g., GET or POST)."""
    for possibility in possibilities:
        if value == possibility:
            return True
    raise Exception(
        'A different request value was encountered than expected: %s' % value)


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


@classmethod
def set_items(cls, s2m):
    """
        This class method allows setting of some class variables
        :param s2m:
        :return:
        """
    cls.s2m = s2m


def likelihood_from_chi_squared_and_noise_normalization(chi_squared,
    noise_normalization):
    """Compute the log likelihood of each model data point's fit to the dataset, where:

    Log Likelihood = -0.5*[Chi_Squared_Term + Noise_Term] (see functions above for these definitions)

    Parameters
    ----------
    chi_squared : float
        The chi-squared term for the model-simulator fit to the dataset.
    noise_normalization : float
        The normalization noise_map-term for the dataset's noise map.
    """
    return -0.5 * (chi_squared + noise_normalization)


def abs_contact_2_coo_file(abs_contact_file, coo_file):
    """Convert contact maps between old-style and new-style formats.

    A legacy function that converts contact maps from the older GRAAL format to
    the simpler instaGRAAL format. This is useful with datasets generated by
    Hi-C box.

    Parameters
    ----------
    abs_contact_file : str, file or pathlib.Path
        The input old-style contact map.
    coo_file : str, file, or pathlib.Path
        The output path to the generated contact map; must be writable.
    """
    sparse_dict = dict()
    h = open(abs_contact_file, 'r')
    all_lines = h.readlines()
    n_lines = len(all_lines)
    for i in range(1, n_lines):
        line = all_lines[i]
        dat = line.split()
        mates = [int(dat[0]), int(dat[1])]
        mates.sort()
        f1 = mates[0] - 1
        f2 = mates[1] - 1
        if f1 in sparse_dict:
            if f2 in sparse_dict[f1]:
                sparse_dict[f1][f2] += 1
            else:
                sparse_dict[f1][f2] = 1
        else:
            sparse_dict[f1] = dict()
            sparse_dict[f1][f2] = 1
    keys = list(sparse_dict.keys())
    keys.sort()
    h.close()
    h_coo = open(coo_file, 'w')
    h_coo.write('%s\t%s\t%s\n' % ('id_frag_a', 'id_frag_b', 'n_contact'))
    for fa in keys:
        d_fb = sparse_dict[fa]
        keys_b = list(d_fb.keys())
        keys_b.sort()
        for fb in keys_b:
            nc = d_fb[fb]
            h_coo.write('%s\t%s\t%s\n' % (str(fa), str(fb), str(nc)))
    h_coo.close()
    h.close()


def attributes_dict_to_string(attribues):
    """
    Converts the attributes dictionary to a string
    example output: rel='stylesheet' href=''
    """
    output = ''
    for key in attribues.keys():
        output += f"{key}='{str(attribues[key])}' "
    return output


def get_assembly_size(assembly_file):
    """Returns the number of nucleotides and the size per contig for the
    provided assembly file path

    Parameters
    ----------
    assembly_file : str
        Path to assembly file.

    Returns
    -------
    assembly_size : int
        Size of the assembly in nucleotides
    contig_size : dict
        Length of each contig (contig name as key and length as value)

    """
    assembly_size = 0
    contig_size = {}
    header = ''
    with open(assembly_file) as fh:
        for line in fh:
            if line.strip() == '':
                continue
            if line.startswith('>'):
                header = line.strip()[1:]
                contig_size[header] = 0
            else:
                line_len = len(line.strip())
                assembly_size += line_len
                contig_size[header] += line_len
    return assembly_size, contig_size


def rr_or(x, y, nx, ny):
    """Dimensionless production rate for a gene regulated by two
    repressors with OR logic in the absence of leakage.

    Parameters
    ----------
    x : float or NumPy array
        Concentration of first repressor.
    y : float or NumPy array
        Concentration of second repressor.
    nx : float
        Hill coefficient for first repressor.
    ny : float
        Hill coefficient for second repressor.

    Returns
    -------
    output : NumPy array or float
        (1 + x**nx + y**ny) / (1 + x**nx) / (1 + y**ny)
    """
    return (1 + x ** nx + y ** ny) / (1 + x ** nx) / (1 + y ** ny)


def p_or_terms2(p):
    """or_terms : or_term"""
    p[0] = p[1]


def __iter__():
    """Return an interator in the actions, in order
        """


def contains(small_list, big_list):
    """Checks if a list is contained in another list

    :param small_list: The smaller list
    :param big_list: The bigger list in which to find the smaller list
    :return: True if the small list is found inside the big list
    """
    if len(small_list) == 0:
        return False
    for i in iter(range(len(big_list) - len(small_list) + 1)):
        for j in iter(range(len(small_list))):
            if big_list[i + j] != small_list[j]:
                break
        else:
            return i, i + len(small_list)
    return False


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

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

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


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

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

    """
    pass


def view_ndof():
    """Use a 3D mouse device to pan/zoom the view

    """
    pass


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

        :param ShowcaseRemoveMemberDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_remove_member_details', val)


def _print_pgfplot_libs_message(data):
    """Prints message to screen indicating the use of PGFPlots and its
    libraries."""
    pgfplotslibs = ','.join(list(data['pgfplots libs']))
    tikzlibs = ','.join(list(data['tikz libs']))
    print(70 * '=')
    print('Please add the following lines to your LaTeX preamble:\n')
    print('\\usepackage[utf8]{inputenc}')
    print('\\usepackage{fontspec}  % This line only for XeLaTeX and LuaLaTeX')
    print('\\usepackage{pgfplots}')
    if tikzlibs:
        print('\\usetikzlibrary{' + tikzlibs + '}')
    if pgfplotslibs:
        print('\\usepgfplotslibrary{' + pgfplotslibs + '}')
    print(70 * '=')
    return


def parse_key_val_list(input_list):
    """
     Takes list of keyword value strings (seperated by =) and returns a dictionary with those keys and values
     **NOTE** if a key has no value, the key is stored and given the value True

    :param input_list: A list of strings which are keyword value pairs separated by =
    :return: A dictionary of the keywords and values
    """
    key_val_dict = {}
    for element in input_list:
        key_value = element.split('=')
        key = key_value[0]
        value = key_value[1] if len(key_value) > 1 else True
        key_val_dict[key] = value
    return key_val_dict


def logStarted(build, step, log):
    """A new Log has been started, probably because a step has just
        started running a shell command. 'log' is the IStatusLog object
        which can be queried for more information.

        This method may return an IStatusReceiver (such as 'self'), in which
        case the target's logChunk method will be invoked as text is added to
        the logfile. This receiver will automatically be unsubsribed when the
        log finishes."""


def is_java_source(s):
    """
    Return True if s looks like a Java source path.
    Example: this.java
    FIXME: should get actual algo from contenttype.
    """
    return s.endswith(('.java', '.jsp', '.aj'))


def set_fd_inheritable(fd, inheritable):
    """
    disable the "inheritability" of a file descriptor

    See Also:
        https://docs.python.org/3/library/os.html#inheritance-of-file-descriptors
        https://github.com/python/cpython/blob/65e6c1eff3/Python/fileutils.c#L846-L857
    """
    from fcntl import ioctl
    if inheritable:
        from termios import FIONCLEX
        return ioctl(fd, FIONCLEX)
    else:
        from termios import FIOCLEX
        return ioctl(fd, FIOCLEX)


def extractor(data, cell_type, conditions, cell_type_key='cell_type',
    condition_key='condition'):
    """
        Returns a list of `data` files while filtering for a specific `cell_type`.

        # Parameters
        data: `~anndata.AnnData`
            Annotated data matrix
        cell_type: basestring
            specific cell type to be extracted from `data`.
        conditions: dict
            dictionary of stimulated/control of `data`.

        # Returns
            list of `data` files while filtering for a specific `cell_type`.

        # Example
        ```python
        import scgen
        import anndata
        train_data = anndata.read("./data/train.h5ad")
        test_data = anndata.read("./data/test.h5ad")
        train_data_extracted_list = extractor(train_data, "CD4T", conditions={"ctrl": "control", "stim": "stimulated"})
        ```

    """
    cell_with_both_condition = data[data.obs[cell_type_key] == cell_type]
    condtion_1 = data[(data.obs[cell_type_key] == cell_type) & (data.obs[
        condition_key] == conditions['ctrl'])]
    condtion_2 = data[(data.obs[cell_type_key] == cell_type) & (data.obs[
        condition_key] == conditions['stim'])]
    training = data[~((data.obs[cell_type_key] == cell_type) & (data.obs[
        condition_key] == conditions['stim']))]
    return [training, condtion_1, condtion_2, cell_with_both_condition]


def normalize_state(state):
    """Convert state into standardized (slurm style) state."""
    state = state.lower()
    if state == 'queued':
        state = 'pending'
    return state


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


def noop(*args, **kwargs):
    """ This function does absolutely nothing. Other functions can be
        disabled by assigning this to their name.
        Example:
            debugv = noop
    """
    return None


def get_extend_cbar(metric):
    """
    Find out whether the colorbar should extend, based on globals._metric_value_ranges[metric]

    Parameters
    ----------
    metric : str
        metric used in plot

    Returns
    -------
    str
        one of ['neither', 'min', 'max', 'both'].
    """
    vrange = globals._metric_value_ranges[metric]
    if vrange[0] is None:
        if vrange[1] is None:
            return 'both'
        else:
            return 'min'
    elif vrange[1] is None:
        return 'max'
    else:
        return 'neither'


def fw_romaji_lt(full, regular):
    """
    Generates a lookup table with the fullwidth rōmaji characters
    on the left side, and the regular rōmaji characters as the values.
    """
    lt = {}
    for n in range(len(full)):
        fw = full[n]
        reg = regular[n]
        lt[fw] = reg
    return lt


@classmethod
def delete(cls, id_):
    """ Remove a cert from the hosted cert store. """
    return cls.call('cert.hosted.delete', id_)


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


def makename(package, module):
    """Join package and module with a dot."""
    if package:
        name = package
        if module:
            name += '.' + module
    else:
        name = module
    return name


def table_from_primary_key(pkname):
    """Given the name of a primary key, return the related table.

    :param pkname: the name of a primary key
    :rtype: a SQLAlchemy table
    """
    from . import Base
    for t in Base.metadata.sorted_tables:
        if len(t.primary_key.columns) == 1 and pkname in t.primary_key.columns:
            return t
    raise Exception('Unknown PK: %s' % pkname)


@staticmethod
def get_state_arguments_model():
    """
        This is needed so the BaseState can validate the provided
        model has the required or optional arguments for the state
        to function.
        return = {
            'required_state_arguments': {
                'required_state_arg_1': type,
                'required_state_arg_2': type,
            },
            'optional_state_arguments': {
                'optional_state_arg_1': type,
                'optional_state_arg_2': type,
            },
        }
        """
    return {'required_state_arguments': {}, 'required_State_arguments': {}}


def _draw_single_ncf(values, ax, xlim, ls):
    """Draw a plotted line of values."""
    ax.plot(values, marker='o', linestyle=ls)
    ax.set_xlim(right=xlim, left=-1)


def initialize(molecule):
    """Initialize atom labeling algorithm by setting ``IDname`` and ``IDdone`` attributes for all atoms in *molecule*."""
    for at in molecule:
        at.IDname = at.symbol
        at.IDdone = False


def scroll_forward(event, half=False):
    """
    Scroll window down.
    """
    w = event.app.layout.current_window
    b = event.app.current_buffer
    if w and w.render_info:
        info = w.render_info
        ui_content = info.ui_content
        scroll_height = info.window_height
        if half:
            scroll_height //= 2
        y = b.document.cursor_position_row + 1
        height = 0
        while y < ui_content.line_count:
            line_height = info.get_height_for_line(y)
            if height + line_height < scroll_height:
                height += line_height
                y += 1
            else:
                break
        b.cursor_position = b.document.translate_row_col_to_index(y, 0)


def _query_include_self(X, include_self, mode):
    """Return the query based on include_self param"""
    if include_self == 'auto':
        include_self = mode == 'connectivity'
    if not include_self:
        X = None
    return X


@staticmethod
def __replace_base_variables(text, req_len, idx):
    """
        Replace i and n in text with index+1 and req_len.

        :param text: base text to modify
        :param req_len: amount of required resources
        :param idx: index of resource we are working on
        :return: modified string
        """
    return text.replace('{i}', str(idx + 1)).replace('{n}', str(req_len))


def set_verbosity(level):
    """Sets the modules message verbosity level for *all* messages printed.

    :arg level: a positive integer (>0); higher levels including more detail.
    """
    global verbosity
    verbosity = level


def chunks_known_length(iterable, size, length=None):
    """
    Yield successive `size`-sized chunks from `iterable`,
    if the length of `iterable is already known or easy to compute.

    https://stackoverflow.com/a/312464/3423324

    :param iterable: The object you want to split into pieces.

    :param size: The size each of the resulting pieces should have.
    :type  size: int

    :param length: Optional. Length of the `iterable`.
                   If set to `None` (default), the length get calculated automatically.
    :type  length: None | int
    """
    if length is None:
        len(iterable)
    for i in range(0, length, size):
        yield iterable[i:i + size]


def get_edges(tree):
    """
    Get edges of the tree in the form of (node_start,node_end)
    :param tree: ETE tree
    :return: List of edges of a tree of a list of tuples (node_start,node_end)
    """
    edges = []
    for node in tree.traverse('postorder'):
        if not node.is_leaf():
            edges.append((node, node.children[0]))
            edges.append((node, node.children[1]))
    return edges


def numeric_menu(options):
    """
    Asks the user for numeric input based on an input dictionary of options.

    :param options: (dict) a numerical selection menu.
                    E.g.: {1: 'Do this',
                           2: 'Do that'}
    """
    if type(options) != dict:
        raise TypeError('numeric_menu requires a dictionary as input')
    while True:
        print('Please select one of the options below:')
        for _, value in options.items():
            print(value)
        user_selection = input()
        user_selection = int(user_selection)
        if user_selection in options.keys():
            return user_selection


@classmethod
def remove_domain(cls, options=None):
    """Removes a domain from an org"""
    cls.command_sub = 'remove-domain'
    return cls.execute(cls._construct_command(options))


def interleave(*iteratives):
    """
    Return an iterator that interleave elements from given `iteratives`.

    >>> list(interleave([1, 2, 3], itertools.repeat(None)))
    [1, None, 2, None, 3, None]

    """
    iters = list(map(iter, iteratives))
    while True:
        for it in iters:
            yield next(it)


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

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


def reboot_workspaces(RebootWorkspaceRequests=None):
    """
    Reboots the specified WorkSpaces.
    To be able to reboot a WorkSpace, the WorkSpace must have a State of AVAILABLE , IMPAIRED , or INOPERABLE .
    See also: AWS API Documentation

    :example: response = client.reboot_workspaces(
        RebootWorkspaceRequests=[
            {
                'WorkspaceId': 'string'
            },
        ]
    )

    :type RebootWorkspaceRequests: list
    :param RebootWorkspaceRequests: [REQUIRED]
            An array of structures that specify the WorkSpaces to reboot.
            (dict) --Contains information used with the RebootWorkspaces operation to reboot a WorkSpace.
            WorkspaceId (string) -- [REQUIRED]The identifier of the WorkSpace to reboot.

    :rtype: dict
    :return: {
        'FailedRequests': [
            {
                'WorkspaceId': 'string',
                'ErrorCode': 'string',
                'ErrorMessage': 'string'
            },
        ]
    }

    """
    pass


def _fd(f):
    """Get a filedescriptor from something which could be a file or an fd."""
    return f.fileno() if hasattr(f, 'fileno') else f


def glIsTexture(texture: int):
    """Determine if a name corresponds to a texture

    :param texture: Specifies a value that may be the name of a texture.
    :type texture: int
    """
    pass


def is_instant_time_axis(ctx):
    """
    Deduces from MIP frequency, variable and realm, if the file requires an instantaneous time axis.

    :param dict ctx: The processing context (as a :func:`ProcessingContext` class instance)
    :returns: True if the file requires an instantaneous time axis
    :rtype: *boolean*

    """
    need_instant_time = eval(ctx.cfg.get(ctx.project, 'need_instant_time'))
    if (ctx.attributes['variable'], ctx.attributes['frequency'], ctx.
        attributes['realm']) in need_instant_time:
        return True
    else:
        return False


@staticmethod
def isatty():
    """
        Convince module we're in a terminal.
        """
    return True


def is_usb_serial(device, vid=None, pid=None, vendor=None, serial=None, *
    args, **kwargs):
    """Checks device to see if its a USB Serial device.
    The caller already filters on the subsystem being 'tty'.
    If serial_num or vendor is provided, then it will further check to
    see if the serial number and vendor of the device also matches.
    """
    if 'ID_VENDOR' not in device:
        return False
    if vid is not None:
        if device['ID_VENDOR_ID'] != vid:
            return False
    if pid is not None:
        if device['ID_MODEL_ID'] != pid:
            return False
    if vendor is not None:
        if 'ID_VENDOR' not in device:
            return False
        if not device['ID_VENDOR'].startswith(vendor):
            return False
    if serial is not None:
        if 'ID_SERIAL_SHORT' not in device:
            return False
        if not device['ID_SERIAL_SHORT'].startswith(serial):
            return False
    return True


def str_to_list(s):
    """
    Converts a string into a sequence of bytes.

    This will also handle unicode strings, so sanitise all input.

    :param str s: The string to be converted.
    :return list: A sequence of bytes.
    """
    return list(s.encode('utf-8'))


def _normalize_handler_method(method):
    """Transforms an HTTP method into a valid Python identifier."""
    return method.lower().replace('-', '_')


def format_speed(speed):
    """Return a bytes/s measurement as a human readable string."""
    kb_spd = float(speed) / 1024
    return round(kb_spd, 2 if kb_spd < 0.1 else 1)


def viewer_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True):
    """Set the boundaries for viewer operations

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


def initColumns():
    """Initialize columns definitions used by the table"""


def validate_rating(value):
    """
    Ensures value is an int between 1 and 5
    :param value:
        Hopefully something that can be turned into an int
        hopefully between 1 and 5
    :throws ValueError if the conditions are not met
    """
    int_value = int(value)
    if int_value < 1 or int_value > 5:
        raise ValueError('ratings must be between 1 and 5')


def _compute_refill_amount(current_tokens, time_since_refill, limit, token_ms):
    """
    Compute the number of tokens accumulated since the last refill.

    Args:
      current_tokens (int): The number of tokens currently in the bucket.
      time_since_refill (int): Timestamp, in milliseconds, since the last time the bucket was refilled.
      limit (int): Time, in milliseconds, when the token retrieval started.
      token_ms (int): The rate of token accumulation per millisecond.

    Returns:
        int: The number of tokens accumulated since the last refill.
    """
    tokens = max(0, current_tokens)
    return min(limit - 1, tokens + int(token_ms * time_since_refill))


def pendingparentchange():
    """Returns true if the dirstate is in the middle of a set of changes
        that modify the dirstate parent.
        """


def _default_key_normalizer(key_class, request_context):
    """
    Create a pool key out of a request context dictionary.

    According to RFC 3986, both the scheme and host are case-insensitive.
    Therefore, this function normalizes both before constructing the pool
    key for an HTTPS request. If you wish to change this behaviour, provide
    alternate callables to ``key_fn_by_scheme``.

    :param key_class:
        The class to use when constructing the key. This should be a namedtuple
        with the ``scheme`` and ``host`` keys at a minimum.
    :type  key_class: namedtuple
    :param request_context:
        A dictionary-like object that contain the context for a request.
    :type  request_context: dict

    :return: A namedtuple that can be used as a connection pool key.
    :rtype:  PoolKey
    """
    context = request_context.copy()
    context['scheme'] = context['scheme'].lower()
    context['host'] = context['host'].lower()
    for key in ('headers', '_proxy_headers', '_socks_options'):
        if key in context and context[key] is not None:
            context[key] = frozenset(context[key].items())
    socket_opts = context.get('socket_options')
    if socket_opts is not None:
        context['socket_options'] = tuple(socket_opts)
    for key in list(context.keys()):
        context['key_' + key] = context.pop(key)
    for field in key_class._fields:
        if field not in context:
            context[field] = None
    return key_class(**context)


def ceil_shift(n, b):
    """Return ceil(n / 2**b) without performing any floating-point or division operations.

    This is done by right-shifting n by b bits and incrementing the result by 1
    if any '1' bits were shifted out.
    """
    if not isinstance(n, int) or not isinstance(b, int):
        raise TypeError('unsupported operand type(s): %r and %r' % (type(n)
            .__name__, type(b).__name__))
    assert n >= 0 and b >= 0
    mask = (1 << b) - 1
    if n & mask:
        return (n >> b) + 1
    else:
        return n >> b


def writeFile(path, data):
    """Write a file at the specified path.

        Parent directories will be added if necessary. The final path component
        gives the filename. If the file already exists, it will be overwritten.

        ``data`` may be a string or file-like object.
        """


def format_cert(cert):
    """
    Return human readable representation of certificate for error messages.
    """
    return str(cert.cert)


@classmethod
def from_table(cls, table):
    """
        Create a `StarList` from a :class:`astropy.table.Table` instance

        Parameters
        ----------
        table : :class:`astropy.table.Table`
            The astropy :class:`astropy.table.Table` instance
        Returns
        -------
        sl : `StarList`
            A `StarList`instance
        """
    from .file_helpers import as_starlist
    return as_starlist(table)


def rot_clear():
    """Reset rotations of selected bones to their default values

    """
    pass


def load_rate_constants(filein='rates.dat'):
    """Load and return dissociation rate constants for forward reaction only.

    Parameters
    ----------
    filein: str
        Name of the file created with method *save_rate_constants* of
        class *Dissociation*.

    Returns
    -------
    rates: list of floats
        Rate constants.
    forces: list of floats
        External forces.

    """
    rates = []
    forces = []
    fd = open(filein)
    first = True
    for line in fd:
        if first:
            first = False
            continue
        line_arr = line.rstrip().split()
        forces.append(float(line_arr[0]))
        rates.append(float(line_arr[1]))
    fd.close()
    return rates, forces


def TargetDirectory(ID, season, relative=False, **kwargs):
    """
  Returns the location of the :py:mod:`everest` data on disk
  for a given target.

  :param ID: The target ID
  :param int season: The target season number
  :param bool relative: Relative path? Default :py:obj:`False`

  """
    raise NotImplementedError('This mission is not yet supported.')


def _clear(subs, shared):
    """Configure the `doorstop clear` subparser."""
    info = 'absolve items of their suspect link status'
    sub = subs.add_parser('clear', description=info.capitalize() + '.',
        help=info, **shared)
    sub.add_argument('label', help="item UID, document prefix, or 'all'")
    group = sub.add_mutually_exclusive_group()
    group.add_argument('-i', '--item', action='store_true', help=
        "indicates the 'label' is an item UID")
    group.add_argument('-d', '--document', action='store_true', help=
        "indicates the 'label' is a document prefix")
    sub.add_argument('parents', nargs='*', help=
        'only clear links with these parent item UIDs')


def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

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

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


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

        :param DeviceLinkFailType val:
        :rtype: EventType
        """
    return cls('device_link_fail', val)


def proc_sat(gpu, nproc):
    """ Return true if the number of processes on gpu is at most nproc"""
    return len(gpu.entry['processes']) <= nproc


def notmain():
    """Run some local code"""
    pass


@staticmethod
def get_session():
    """Return a database session that can be used by the `QueryBuilder` to perform its query.

        :return: an instance of :class:`sqlalchemy.orm.session.Session`
        """
    from aiida.backends.sqlalchemy import get_scoped_session
    return get_scoped_session()


@staticmethod
def is_unique(field):
    """ Return True is field's value should be a unique.

        :return bool:

        """
    return field.scheme.unique


def nfa_determinization(nfa: dict) ->dict:
    """ Returns a DFA that reads the same language of the input NFA.

    Let A be an NFA, then there exists a DFA :math:`A_d` such
    that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d`
    collapses all possible runs of A on a given input word into
    one run over a larger state set.
    :math:`A_d` is defined as:

    :math:`A_d = (Σ, 2^S , s_0 , ρ_d , F_d )`

    where:

    • :math:`2^S` , i.e., the state set of :math:`A_d` , consists
      of all sets of states S in A;
    • :math:`s_0 = S^0` , i.e., the single initial state of
      :math:`A_d` is the set :math:`S_0` of initial states of A;
    • :math:`F_d = \\{Q | Q ∩ F ≠ ∅\\}`, i.e., the collection of
      sets of states that intersect F nontrivially;
    • :math:`ρ_d(Q, a) = \\{s' | (s,a, s' ) ∈ ρ\\ for\\ some\\ s ∈ Q\\}`.

    :param dict nfa: input NFA.
    :return: *(dict)* representing a DFA
    """
    dfa = {'alphabet': nfa['alphabet'].copy(), 'initial_state': None,
        'states': set(), 'accepting_states': set(), 'transitions': dict()}
    if len(nfa['initial_states']) > 0:
        dfa['initial_state'] = str(nfa['initial_states'])
        dfa['states'].add(str(nfa['initial_states']))
    sets_states = list()
    sets_queue = list()
    sets_queue.append(nfa['initial_states'])
    sets_states.append(nfa['initial_states'])
    if len(sets_states[0].intersection(nfa['accepting_states'])) > 0:
        dfa['accepting_states'].add(str(sets_states[0]))
    while sets_queue:
        current_set = sets_queue.pop(0)
        for a in dfa['alphabet']:
            next_set = set()
            for state in current_set:
                if (state, a) in nfa['transitions']:
                    for next_state in nfa['transitions'][state, a]:
                        next_set.add(next_state)
            if len(next_set) == 0:
                continue
            if next_set not in sets_states:
                sets_states.append(next_set)
                sets_queue.append(next_set)
                dfa['states'].add(str(next_set))
                if next_set.intersection(nfa['accepting_states']):
                    dfa['accepting_states'].add(str(next_set))
            dfa['transitions'][str(current_set), a] = str(next_set)
    return dfa


def read_in_chunks(file_object, chunk_size=1024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data


@classmethod
def get_name(cls):
    """ Returns the name of the supplier.

			# Return value

			A lower-case string unique to this supplier.
		"""
    return cls.__name__.lower()


def cv_classes():
    """all objects to be used as a cross-validation generator"""
    all_types = ("<class 'sklearn.model_selection._split.KFold'>",
        "<class 'sklearn.model_selection._split.ShuffleSplit'>",
        "<class 'sklearn.model_selection._split.StratifiedShuffleSplit'>",
        "<class 'sklearn.model_selection._split.LeaveOneOut'>")
    return all_types


def pred_diff(y_pred, y):
    """
    Returns the difference between the test target and the predicted one, for a future mse calculation.
    :param y_pred: the vector of predictions
    :param y: the target
    :return: the vector difference between y and y_pred
    """
    return y - y_pred


def SetCorrespondentsChangedCallback(cb):
    """
    Set callback to fire when correspondents is changed.
    """
    global _CorrespondentsChangedCallback
    _CorrespondentsChangedCallback = cb


def _find_database_key(results):
    """
    The same data from different plugins are connected together in results
    under the same key. This key is just a tuple (e.q. (database, puppet)).
    This function returns tuple which contains "database" element.
    """
    for sources in results.iterkeys():
        if 'database' in sources:
            return sources


def _generate_overlap_table(prefix):
    """
    Generate an overlap table for the following prefix.
    An overlap table is a table of the same size as the prefix which
    informs about the potential self-overlap for each index in the prefix:
    - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...]
    - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with
      prefix[0:k]
    """
    table = [0] * len(prefix)
    for i in range(1, len(prefix)):
        idx = table[i - 1]
        while prefix[i] != prefix[idx]:
            if idx == 0:
                table[i] = 0
                break
            idx = table[idx - 1]
        else:
            table[i] = idx + 1
    return table


@classmethod
def _create_bits_by_thousand_rocks(cls, figure, data_by_year, shifts, bits):
    """Bits by thousand rock mass."""
    bit_by_rock = figure.add_subplot(224)
    bits_by_thousand_rocks1 = bits[0] / (data_by_year[shifts[0]].rock_mass /
        1000)
    bits_by_thousand_rocks2 = bits[1] / (data_by_year[shifts[1]].rock_mass /
        1000)
    bit_by_rock.plot(data_by_year[shifts[0]].month, bits_by_thousand_rocks1,
        marker='D', markersize=4)
    bit_by_rock.plot(data_by_year[shifts[1]].month, bits_by_thousand_rocks2,
        marker='D', markersize=4)
    bit_by_rock.legend(['Смена 1', 'Смена 2'])
    bit_by_rock.set_ylabel('коронок / 1000м³ горной массы')
    bit_by_rock.set_xlabel('месяцы')
    bit_by_rock.grid(b=True, linestyle='--', linewidth=0.5)
    bit_by_rock.set_title('Коронок на тысячу кубов горной массы.')


def max_int(width):
    """ Returns Max signed Int of desired width """
    return 2 ** (width * 8 - 1) - 1


def minimals(A, le=lambda x, y: x <= y):
    """ Find the minimal element(s) of a sequence of partially ordered elements"""
    r = []
    for x in A:
        for a in A:
            if le(a, x) and not le(x, a):
                break
        else:
            for a in r:
                if le(a, x):
                    break
            else:
                r.append(x)
    return r


def delete_metadata(receipt, price=None, retailer=None, note=None):
    """Delete XMP metadata."""
    if not price and not retailer and not note:
        del receipt.price
        del receipt.retailer
        del receipt.note
    if price:
        del receipt.price
    if retailer:
        del receipt.retailer
    if note:
        del receipt.note


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def get_resource_string(manager, resource_name):
    """Return a string containing the contents of `resource_name`

        `manager` must be an ``IResourceManager``"""


@classmethod
def check(cls) ->None:
    """
        Calls various checks to validate the model.

        :raises ConfigurationError: If the model has not been configured correctly.
        """
    cls._check_together('unique_together')
    cls._check_together('indexes')


def getNearestSite():
    """Return the site the object is contained in

        If the object is a site, the object itself is returned.

        """


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

        :param TfaAddExceptionDetails val:
        :rtype: EventDetails
        """
    return cls('tfa_add_exception_details', val)


def history_cycle(reverse: bool=False):
    """Cycle through history

    :param reverse: Reverse, Reverse cycle history
    :type reverse: bool
    """
    pass


@classmethod
def configure_arggroup(cls, parser):
    """Configure argument parser."""
    pass


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

        :param ShowcaseCreatedDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_created_details', val)


def local_incid_press(p_inc, rho_cont, h_l, h_ref, gamma_inc=1.1, g=9.81
    ) ->'p_li':
    """Calculate local incidental pressure. Also applicable for
    local system test pressure.

    :param p_d: $p_d$ design pressure at ref elevation
    :param rho_cont: $\\rho_{cont}$ density of pipeline contents
    :param h_l: $h_l$ elevation of the local pressure point
    :param h_ref: $h_{ref}$ elevation of the reference point
    :param gamma_inc: $\\gamma_{inc}$ incidental to design pressure ratio
    :param g: $g$ gravitational acceleration
    :returns: p_li: $h_{ref}$ local incidental pressure

    .. math::
        p_{li} = p_{inc} - \\rho_{cont} \\cdot g \\cdot \\left( h_l - h_{ref} \\right)

    Reference:
    DNVGL-ST-F101 (2017-12)
        sec:4.2.2.2 eq:4.1 page:67 p_{li}
        sec:4.2.2.2 eq:4.2 page:67 $p_{lt}$

    Example:
    >>> local_incid_press(100.e-5, 1025, -125, 30)
    1558563.751
    """
    p_li = p_inc - rho_cont * g * (h_l - h_ref)
    return p_li


@staticmethod
def interfaces_roles_change_and_tree_was_unsure_and_transitions_to_active(
    interface: 'TreeInterfaceUpstream'):
    """
        Interfaces roles change (NonRoot->Root) AND
        Tree was Unsure and transitions to Active state
        """
    interface.logger.debug(
        'interfaces_roles_change_and_tree_was_unsure_and_transitions_to_active'
        )
    interface.send_my_interest()


def intersection(lists):
    """
        lists must contain lists of elements or a lists of strings then strings.
    """
    if lists is None or len(lists) == 0 or lists[0] is None:
        return []
    elif len(lists) == 1:
        return lists[0]
    else:
        theIntersection = list(lists[0])
        for current in lists[1:]:
            if current is None:
                theIntersection = []
                break
            elif isinstance(current, str):
                currentInter = []
                for el in theIntersection:
                    if el in current:
                        currentInter.append(el)
                theIntersection = currentInter
                theIntersection = list(set(theIntersection))
            else:
                theIntersection = list(set(current).intersection(
                    theIntersection))
        return theIntersection


@classmethod
def from_node_meta(cls, meta_description):
    """
        Create an `NodeItem` instance from a node meta description.
        """
    self = cls()
    self.setWidgetDescription(meta_description)
    return self


def frequency_to_channel(freq):
    """ Convert frequency in GHz to ITU DWDM channel in C-band

    >>> frequency_to_channel(193100)
    0
    >>> frequency_to_channel(192750)
    -7
    >>> frequency_to_channel(193550)
    9
    """
    itu_channel = (freq - 193100) / 50
    assert itu_channel == int(itu_channel)
    return int(itu_channel)


def make_table_header(table_label, table_width, junction_char='+',
    horizontal_char='-', vertical_char='|'):
    """Generalized way make a table header string.

    :param table_label: label to print on header
    :param table_width: total width of table
    :param junction_char: character used where vertical and
        horizontal lines meet.
    :param horizontal_char: character used for horizontal lines.
    :param vertical_char: character used for vertical lines.

    :returns: string
    """
    if len(table_label) >= table_width - 2:
        raise ValueError(
            'Table header %s is longer than total width of the table.')
    label_and_space_width = table_width - len(table_label) - 2
    padding = 0 if label_and_space_width % 2 == 0 else 1
    half_table_width = label_and_space_width // 2
    left_spacing = ' ' * half_table_width
    right_spacing = ' ' * (half_table_width + padding)
    border_line = ''.join((junction_char, horizontal_char * (table_width -
        2), junction_char))
    label_line = ''.join((vertical_char, left_spacing, table_label,
        right_spacing, vertical_char))
    return '\n'.join((border_line, label_line))


@staticmethod
def decode_version_nr(version_nr):
    """ Decode an encoded version number to a 3-tuple. """
    major = version_nr >> 16
    minor = version_nr >> 8 & 255
    patch = version_nr & 255
    return major, minor, patch


def parseCmdline():
    """Load command line arguments"""
    from argparse import ArgumentParser
    parser = ArgumentParser(description=
        'Automates tax forms and provides an API for new tax form interfaces')
    parser.add_argument('-P', '--postgres', help=
        'use postgres database [default=sqlite]', action='store_true')
    return parser.parse_args()


def theta_H_Mg_MP98(T, P):
    """c-c': hydrogen magnesium [MP98]."""
    theta = 0.062 + 0.0003275 * (T - 298.15)
    valid = T == 298.15
    return theta, valid


def to_bytes(something, encoding='utf8') ->bytes:
    """
    cast string to bytes() like object, but for python2 support it's bytearray copy
    """
    if isinstance(something, bytes):
        return something
    if isinstance(something, str):
        return something.encode(encoding)
    elif isinstance(something, bytearray):
        return bytes(something)
    else:
        raise TypeError('Not a string or bytes like object')


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


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


@staticmethod
def construct_condition_name(failure_node, idx):
    """Construct condition name that will be used in case of conditional fallbacks.

        :param failure_node: failure node for which the condition name should be constructed
        :param idx: index of condition that should be printed (could be multiple fallbacks with same source and dst)
        :return: string representation of constructed condition name as stated in the generated python code
        """
    return '_{flow}_{src}_f_{dest}_{idx}'.format(flow=failure_node.flow.
        name, src='_'.join(failure_node.traversed), dest='_'.join(
        failure_node.fallbacks[idx]), idx=idx)


def _get_floppy_image_name(node):
    """Returns the floppy image name for a given node.

    :param node: the node for which image name is to be provided.
    """
    return 'image-%s.img' % node.uuid


def dictitems(d):
    """ A pickleable version of dict.items

    >>> dictitems({'x': 1})
    [('x', 1)]
    """
    return list(d.items())


def view_template_id():
    """View or template id for this context."""


def computePrecisionCurve(predicted_edge_list, true_digraph, max_k=-1):
    """Function to calculate the precision curve

           Attributes:
               predicted_edge_list (list): List of predicted edges.
               true_digraph (object): original graph
               max_k(int): precision@k

            Returns:
                ndarray: precision_scores, delta_factors
    """
    if max_k == -1:
        max_k = len(predicted_edge_list)
    else:
        max_k = min(max_k, len(predicted_edge_list))
    sorted_edges = sorted(predicted_edge_list, key=lambda x: x[2], reverse=True
        )
    precision_scores = []
    delta_factors = []
    correct_edge = 0
    for i in range(max_k):
        if true_digraph.has_edge(sorted_edges[i][0], sorted_edges[i][1]):
            correct_edge += 1
            delta_factors.append(1.0)
        else:
            delta_factors.append(0.0)
        precision_scores.append(1.0 * correct_edge / (i + 1))
    return precision_scores, delta_factors


@classmethod
def put_settings(cls, my_data):
    """Merge/Set the given settings.

    ex:
    # to update the max result window
    put_settings({'max_result_window': 100000})
    # to add an analyzer
    put_settings({
      "analysis": {
        "analyzer": {
          "no_punctuation_analyzer": {
            "tokenizer": "kuromoji_no_punctuation_dict",
            "filter": ["kuromoji_st", "kuromoji_syn", "cjk_width"]
          }
        },
        "tokenizer": {
          "kuromoji_no_punctuation_dict": {
             "type": "kuromoji_tokenizer",
             "mode": "search",
             "discard_punctuation": "true",
             "user_dictionary": "luxeysdict_ja.txt"
          }
        }
      }
    })
    """
    conn = cls.get_connection()
    return conn.indices.put_settings(body=my_data, index=cls.get_index_name())


@classmethod
def from_storage(cls, storage, indexname='THES'):
    """Creates a Thesaurus object from the given storage object,
        which should contain an index created by Thesaurus.to_storage().

        >>> from whoosh.filedb.filestore import FileStorage
        >>> fs = FileStorage("index")
        >>> t = Thesaurus.from_storage(fs)
        >>> t.synonyms("hail")
        ['acclaim', 'come', 'herald']

        :param storage: A :class:`whoosh.store.Storage` object from
            which to load the index.
        :param indexname: A name for the index. This allows you to
            store multiple indexes in the same storage object.
        """
    thes = cls()
    index = storage.open_index(indexname=indexname)
    thes.searcher = index.searcher()
    return thes


def user_prompt_yes_no(**kwargs):
    """
    This function takes in a prompt string and asks the user to select "0" or "1" for No and Yes, respectively. User
    choice is returned as integer 0 or 1.

    :param kwargs: message: User prompt that is displayed in console.
    :return: selection: User selection (integer 0 or 1)
    """
    message = ''
    if 'message' in kwargs:
        message = kwargs['message']
    while True:
        prompt = '\n{}\n[0] No\n[1] Yes\n'.format(message)
        try:
            selection = int(input(prompt))
        except ValueError:
            print('\nOnly a single integer value allowed as input.')
            continue
        if selection not in [0, 1]:
            print(
                "Selection invalid. Please choose [0] for 'No' or [1] for 'Yes'."
                )
            continue
        else:
            break
    return selection


def snap_to_grid():
    """Snap selected points to the nearest grid points

    """
    pass


def figshow():
    """`pyplot.show` to make a plotted figure show up"""
    from matplotlib import pyplot
    pyplot.ion()
    pyplot.show()


def comma_delimited(s):
    """Split a comma-delimited string."""
    for part in s.split(','):
        stripped = part.strip()
        if stripped:
            yield stripped


@classmethod
def yaml_tag(cls, class_):
    """Return YAML tag for object.

        Constructed from module and class name."""
    return '!{}.{}'.format(class_.__module__, class_.__qualname__)


def telemetry(func):
    """Automagica Activity Telemetry

    This allows us to collect information on the usage of
    certain Automagica functionalities in order for us to keep improving
    the software. If you would like to disable telemetry, make sure the
    environment variable 'AUTOMAGICA_NO_TELEMETRY' is set. That way no
    information is being shared with us.
    """
    import requests
    from uuid import getnode
    import os
    import platform
    if not os.environ.get('AUTOMAGICA_NO_TELEMETRY') and not os.environ.get(
        'AUTOMAGICA_URL'):
        if func.__doc__:
            name = func.__doc__.split('\n')[0]
        else:
            name = func.__name__
        data = {'activity': name, 'machine_id': getnode(), 'os': {'name':
            os.name, 'platform': platform.system(), 'release': platform.
            release()}}
        try:
            r = requests.post('https://telemetry.automagica.com/', json=
                data, timeout=1)
        except:
            pass


def _file_iter_range(fp, offset, bytes, maxread=1024 * 1024):
    """ Yield chunks from a range in a file. No chunk is bigger than maxread."""
    fp.seek(offset)
    while bytes > 0:
        part = fp.read(min(bytes, maxread))
        if not part:
            break
        bytes -= len(part)
        yield part


def timeago(secs, precision=0):
    """
    Return human-readable string of seconds elapsed.

    :param int secs: number of seconds "ago".
    :param int precision: optional decimal precision of returned seconds.

    Pass a duration of time and return human readable shorthand, fe::

        >>> asctime(126.32)
        ' 2m 6s',
        >>> asctime(70.9999, 2)
        ' 1m 10.99s'
    """
    years = weeks = days = mins = hours = 0
    mins, secs = divmod(secs, 60)
    hours, mins = divmod(mins, 60)
    days, hours = divmod(hours, 24)
    weeks, days = divmod(days, 7)
    years, weeks = divmod(weeks, 52)
    (num1, num2), (label1, label2) = ((years, weeks), (u'y', u'w')
        ) if years >= 1.0 else ((weeks, days), (u'w', u'd')
        ) if weeks >= 1.0 else ((days, hours), (u'd', u'h')
        ) if days >= 1.0 else ((hours, mins), (u'h', u'm')
        ) if hours >= 1.0 else ((mins, secs), (u'm', u's'))
    return u'%2d%s%2.*f%s' % (num1, label1, precision, num2, label2)


def mjd_to_jd(mjd):
    """
    Converts Modified Julian date to Julian Date.

    Parameters
    ----------

    mjd : float
        The Modified Julian date measured at UTC.

    Returns
    -------

    jd : float
        `jd = mjd + 2400000.5`

    """
    return mjd + 2400000.5


def p_expression_group(t):
    """expression : LPAREN expression RPAREN
    """
    t[0] = t[2]


def _mp_init_lock(lock):
    """Initialize lock for :mod:`multiprocessing`.

    Args:
        lock (multiprocessing.synchronize.Lock): the lock to be shared among tasks

    """
    global task_lock
    task_lock = lock


def boolArg(v):
    """Own boolean type for arguments, which converts a string into a bool.

    Provide it as type in add_argument.
    """
    if isinstance(v, bool):
        return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise ValueError('Boolean value expected.')


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 delete_usage_plan(usagePlanId=None):
    """
    Deletes a usage plan of a given plan Id.
    See also: AWS API Documentation

    :example: response = client.delete_usage_plan(
        usagePlanId='string'
    )

    :type usagePlanId: string
    :param usagePlanId: [REQUIRED]
            The Id of the to-be-deleted usage plan.

    """
    pass


def button_top_released(controller):
    """
    Callback function that is triggered, when the top button was released

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('ACTION:' + str(controller.number) + ':' + controller.name +
        ':Button Top released')