def sub_dfs_by_num(df, num):
    """Get a generator yielding num consecutive sub-dataframes of the given df.

    Arguments
    ---------
    df : pandas.DataFrame
        The dataframe for which to get sub-dataframes.
    num : int
        The number of sub-dataframe to divide the given dataframe into.

    Returns
    -------
    generator
        A generator yielding n consecutive sub-dataframes of the given df.

    Example
    -------
    >>> import pandas as pd; import pdutil;
    >>> data = [[23, "Jen"], [42, "Ray"], [15, "Fin"]]
    >>> df = pd.DataFrame(data, columns=['age', 'name'])
    >>> for subdf in pdutil.iter.sub_dfs_by_num(df, 2): print(subdf)
       age name
    0   23  Jen
    1   42  Ray
       age name
    2   15  Fin
    """
    size = len(df) / float(num)
    for i in range(num):
        yield df.iloc[int(round(size * i)):int(round(size * (i + 1)))]


def clear(scope, filename):
    """
    Clear the contents of the given file. The file is created if it does
    not exist.

    :type  filename: string
    :param filename: A filename.
    """
    with open(filename[0], 'w'):
        pass
    return True


@classmethod
def get_users_by_email(cls, email):
    """Return users instances for given email address"""
    raise NotImplementedError('Implement in subclass')


def basename(p):
    """Returns the final component of a pathname"""
    i = p.rfind('/') + 1
    return p[i:]


def revert(isamAppliance, resource_id, check_mode=False, force=False):
    """
    Reverting a previously updated runtime configuration file
    """
    if check_mode is True:
        return isamAppliance.create_return_object(changed=True)
    else:
        return isamAppliance.invoke_put(
            'Reverting a previously updated runtime configuration file',
            '/isam/advanced_configuration/{0}'.format(resource_id), {
            'operation': 'revert'})


def sieve_of_eratosthenes(p_min=2, p_max=None):
    """ Generator of prime numbers using the sieve of Eratosthenes.

    Note:
        Adapted from http://code.activestate.com/recipes/117119/

    Args:
        p_min (int): prime numbers lower than p_min will not be in the resulting primes
        p_max (int): the generator will stop when this value is reached, it means that there
            will be no prime bigger than this number in the resulting primes. If p_max
            is None, there will not be any upper limit

    Returns:
        A generator of all the consecutive primes between p_min and p_max

    Raises:
        TypeError: if p_min or p_max is not an integer

    """
    if not isinstance(p_min, int):
        raise TypeError('Expecting an integer')
    if p_max is not None and not isinstance(p_max, int):
        raise TypeError('Expecting an integer')
    sieve = {}
    q = 2
    while p_max is None or q <= p_max:
        if q not in sieve:
            if q >= p_min:
                yield q
            sieve[q * q] = [q]
        else:
            for p in sieve[q]:
                sieve.setdefault(p + q, []).append(p)
            del sieve[q]
        q += 1


def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'srx_cluster':
        'A boolean indicating if the device is part of an SRX cluster.',
        'srx_cluster_id': 'A string containing the configured cluster id',
        'srx_cluster_redundancy_group':
        "A multi-level dictionary of information about the SRX cluster redundancy groups on the device. The first-level key is the redundancy group id. The second-level keys are: cluster_id, failover_count, node0, and node1. The node0 and node1 keys have third-level keys of priority, preempt, status, and failover_mode. The values for this fact correspond to the values of the 'show chassis cluster status' CLI command."
        }


def get_event():
    """
    It returns a new event signal.

    from untwisted.network import *
    X = get_event()
    Y = get_event()
    print X
    print Y

    Whenever we call get_event it increases the integer
    corresponding to the signal. That avoids events getting
    messed through modules.
    """
    global event_count
    event_count = event_count + 1
    return event_count


def StrIsDigit(input_string):
    """
    Determine whether `input_string` is entirely numeric.

    :param input_string:            the string we want to check

    :return:                        True if the string is entirely numeric otherwise False
    """
    return input_string.value.isdigit()


def COUNT(*args):
    """
  Builtin count aggregator for groupby

  Example: Get the number of occurrences of each user.

  >>> sf.groupby("user",
  ...            {'count':gl.aggregate.COUNT()})

  """
    return '__builtin__count__', ['']


def bezier_subdivide(cp, t):
    """
    Subdivide a cubic bezier curve defined by the control points `cp`.

    Parameters
    ----------
    cp : List[QPointF]
        The control points for a cubic bezier curve.
    t : float
        The cut point; a value between 0 and 1.

    Returns
    -------
    cp : Tuple[List[QPointF], List[QPointF]]
        Two lists of new control points for the new left and right part
        respectively.
    """
    c00, c01, c02, c03 = cp
    c10 = c00 * (1 - t) + c01 * t
    c11 = c01 * (1 - t) + c02 * t
    c12 = c02 * (1 - t) + c03 * t
    c20 = c10 * (1 - t) + c11 * t
    c21 = c11 * (1 - t) + c12 * t
    c30 = c20 * (1 - t) + c21 * t
    first = [c00, c10, c20, c30]
    second = [c30, c21, c12, c03]
    return first, second


@classmethod
def copy_valid_options(cls, other_options):
    """
        Produce a new options featuring only the valid settings from
        *other_options*.
        """
    option_dict = {}
    for key in cls.valid_option_names():
        value = getattr(other_options, key, None)
        if value is not None:
            option_dict[key] = value
    return cls(**option_dict)


def to_value(unit_system: str, unit_category: str, str_input: str,
    str_ref_unit: str=None) ->float:
    """Convert a given input string into a float value.

    :param unit_system: The unit system, from bpy.utils.units.systems.
    :type unit_system: str
    :param unit_category: The category of data we are converting (length, area, rotation, etc.), from bpy.utils.units.categories.
    :type unit_category: str
    :param str_input: The string to convert to a float value.
    :type str_input: str
    :param str_ref_unit: A reference string from which to extract a default unit, if none is found in str_input.
    :type str_ref_unit: str
    :return:  The converted/interpreted value.
    """
    pass


def psi_Na_Znjj_Br_PK74(T, P):
    """c-c'-a: sodium zinc(II) bromide [PK74]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def _use_crc_table_gen(opt):
    """
    Return True if the table generator function is to be generated.
    """
    if opt.algorithm == opt.algo_table_driven:
        return opt.width is None or opt.poly is None or opt.reflect_in is None
    else:
        return False


def cancel():
    """Cancel loading of selected file

    """
    pass


def setPrefix(prefix):
    """Update the subpage prefix
        """


def df_groupby_params(data, metric, dims=4, gram_type='ngram',
    group_by_func='sum'):
    """Takes in a dataframe where each column contains
    parameter labels, and then creates combinations of the
    parameters based on ngram, skipgram, or flexgram approach.

    data | DataFrame | contains the columns with parameters
    dims | int | number of parameter dimensions in the output
    gram_type | str | 'ngram', 'skipgram', 'flexgram', 'none'
    group_by_func | str | one of the supported groupby functions

    """
    import pandas as pd
    import signs
    from .df_restructure_values import df_restructure_values
    docs = df_restructure_values(data.drop(metric, 1), 'tuple').values
    out = []
    for i in range(len(docs)):
        model = signs.Grams(docs[i])
        if gram_type == 'flexgram':
            grams = model.flexgrams(dims + 1)
        elif gram_type == 'skipgram':
            grams = model.skipgrams(dims)
        elif gram_type == 'ngram':
            grams = model.ngrams(dims)
        elif gram_type == 'none':
            grams = docs[i]
        for ii in range(len(grams)):
            out.append([grams[ii], data[metric].values[i]])
    final = pd.DataFrame(out)
    final[0] = final[0].map(tuple)
    from .df_to_groupby import df_to_groupby
    return df_to_groupby(final, 0, group_by_func).sort_values(1, ascending=
        False)


def timedelta_to_seconds(td):
    """Equivalent to td.total_seconds() (introduced in python 2.7)."""
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6
        ) / float(10 ** 6)


def skip_rule(start_line, rules_skip):
    """
    Determines if the rule started by the provided line should be skipped.

    :type start_line: String
    :param start_line: The line which starts the rule.
    :type rules_skip: List
    :param rules_skip: The list of rules to skip.
    """
    skip_rule = None
    for rule_skip in rules_skip:
        skip_rule = rule_skip in start_line
        if skip_rule:
            break
    return skip_rule


def list_steps(ClusterId=None, StepStates=None, StepIds=None, Marker=None):
    """
    Provides a list of steps for the cluster in reverse order unless you specify stepIds with the request.
    See also: AWS API Documentation

    :example: response = client.list_steps(
        ClusterId='string',
        StepStates=[
            'PENDING'|'CANCEL_PENDING'|'RUNNING'|'COMPLETED'|'CANCELLED'|'FAILED'|'INTERRUPTED',
        ],
        StepIds=[
            'string',
        ],
        Marker='string'
    )

    :type ClusterId: string
    :param ClusterId: [REQUIRED]
            The identifier of the cluster for which to list the steps.

    :type StepStates: list
    :param StepStates: The filter to limit the step list based on certain states.
            (string) --

    :type StepIds: list
    :param StepIds: The filter to limit the step list based on the identifier of the steps.
            (string) --

    :type Marker: string
    :param Marker: The pagination token that indicates the next set of results to retrieve.

    :rtype: dict
    :return: {
        'Steps': [
            {
                'Id': 'string',
                'Name': 'string',
                'Config': {
                    'Jar': 'string',
                    'Properties': {
                        'string': 'string'
                    },
                    'MainClass': 'string',
                    'Args': [
                        'string',
                    ]
                },
                'ActionOnFailure': 'TERMINATE_JOB_FLOW'|'TERMINATE_CLUSTER'|'CANCEL_AND_WAIT'|'CONTINUE',
                'Status': {
                    'State': 'PENDING'|'CANCEL_PENDING'|'RUNNING'|'COMPLETED'|'CANCELLED'|'FAILED'|'INTERRUPTED',
                    'StateChangeReason': {
                        'Code': 'NONE',
                        'Message': 'string'
                    },
                    'FailureDetails': {
                        'Reason': 'string',
                        'Message': 'string',
                        'LogFile': 'string'
                    },
                    'Timeline': {
                        'CreationDateTime': datetime(2015, 1, 1),
                        'StartDateTime': datetime(2015, 1, 1),
                        'EndDateTime': datetime(2015, 1, 1)
                    }
                }
            },
        ],
        'Marker': 'string'
    }

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

    """
    pass


def SizeBenefitSickHosp(t):
    """Sickness hospitalization benefit per policy"""
    return 0


def read_qasm_file(filename, max_depth=None):
    """
    Read circuit file in the QASM format and return
    quantum circuit in the form of a list of lists

    Parameters
    ----------
    filename : str
             circuit file in the QASM format
    max_depth : int
             maximal depth of gates to read

    Returns
    -------
    qubit_count : int
            number of qubits in the circuit
    circuit : list of lists
            quantum circuit as a list of layers of gates
    """
    pass


def parent_path(path, level):
    """ for level 3 and path /a/b/c/d/e/f this returns /a/b/c """
    return '/'.join(path.split('/')[0:level + 1])


def update_lag(lagId=None, lagName=None, minimumLinks=None):
    """
    Updates the attributes of a link aggregation group (LAG).
    You can update the following attributes:
    When you create a LAG, the default value for the minimum number of operational connections is zero (0). If you update this value, and the number of operational connections falls below the specified value, the LAG will automatically go down to avoid overutilization of the remaining connections. Adjusting this value should be done with care as it could force the LAG down if the value is set higher than the current number of operational connections.
    See also: AWS API Documentation

    :example: response = client.update_lag(
        lagId='string',
        lagName='string',
        minimumLinks=123
    )

    :type lagId: string
    :param lagId: [REQUIRED]
            The ID of the LAG to update.
            Example: dxlag-abc123
            Default: None

    :type lagName: string
    :param lagName: The name for the LAG.
            Example: '3x10G LAG to AWS '
            Default: None

    :type minimumLinks: integer
    :param minimumLinks: The minimum number of physical connections that must be operational for the LAG itself to be operational.
            Default: None

    :rtype: dict
    :return: {
        'connectionsBandwidth': 'string',
        'numberOfConnections': 123,
        'lagId': 'string',
        'ownerAccount': 'string',
        'lagName': 'string',
        'lagState': 'requested'|'pending'|'available'|'down'|'deleting'|'deleted',
        'location': 'string',
        'region': 'string',
        'minimumLinks': 123,
        'awsDevice': 'string',
        'connections': [
            {
                'ownerAccount': 'string',
                'connectionId': 'string',
                'connectionName': 'string',
                'connectionState': 'ordering'|'requested'|'pending'|'available'|'down'|'deleting'|'deleted'|'rejected',
                'region': 'string',
                'location': 'string',
                'bandwidth': 'string',
                'vlan': 123,
                'partnerName': 'string',
                'loaIssueTime': datetime(2015, 1, 1),
                'lagId': 'string',
                'awsDevice': 'string'
            },
        ],
        'allowsHostedConnections': True|False
    }

    :returns:
    lagId (string) -- [REQUIRED]
    The ID of the LAG to update.
    Example: dxlag-abc123
    Default: None

    lagName (string) -- The name for the LAG.
    Example: "3x10G LAG to AWS "
    Default: None

    minimumLinks (integer) -- The minimum number of physical connections that must be operational for the LAG itself to be operational.
    Default: None

    """
    pass


def query(datatype, project, past_days, group_pks, all_users):
    """
    Perform the query
    """
    import datetime
    from aiida import orm
    from aiida.common import timezone
    qbl = orm.QueryBuilder()
    if all_users is False:
        user = orm.User.objects.get_default()
        qbl.append(orm.User, tag='creator', filters={'email': user.email})
    else:
        qbl.append(orm.User, tag='creator')
    data_filters = {}
    if past_days is not None:
        now = timezone.now()
        n_days_ago = now - datetime.timedelta(days=past_days)
        data_filters.update({'ctime': {'>=': n_days_ago}})
    qbl.append(datatype, tag='data', with_user='creator', filters=
        data_filters, project=project)
    if group_pks is not None:
        group_filters = dict()
        group_filters.update({'id': {'in': group_pks}})
        qbl.append(orm.Group, tag='group', filters=group_filters, with_node
            ='data')
    qbl.order_by({datatype: {'ctime': 'asc'}})
    object_list = qbl.distinct()
    return object_list.all()


@classmethod
def from_yaml_file(cls, filepath: str) ->'ParameterGroup':
    """Creates a :class:`ParameterGroup` from a YAML file.

        Parameters
        ----------
        filepath :
            The path to the YAML file.
        """
    with open(filepath) as f:
        cls = cls.from_yaml(f)
    return cls


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

        :param SfTeamGrantAccessType val:
        :rtype: EventType
        """
    return cls('sf_team_grant_access', val)


def find_peaks(array, baseline=0.1, return_subarrays=False):
    """
    This will try to identify the indices of the peaks in array, returning a list of indices in ascending order.

    Runs along the data set until it jumps above baseline. Then it considers all the subsequent data above the baseline
    as part of the peak, and records the maximum of this data as one peak value.
    """
    peaks = []
    if return_subarrays:
        subarray_values = []
        subarray_indices = []
    n = 0
    while n < len(array):
        if array[n] > baseline:
            if return_subarrays:
                subarray_values.append([])
                subarray_indices.append(n)
            ymax = baseline
            nmax = n
            while n < len(array) and array[n] > baseline:
                if return_subarrays:
                    subarray_values[-1].append(array[n])
                if array[n] > ymax:
                    ymax = array[n]
                    nmax = n
                n = n + 1
            peaks.append(nmax)
        else:
            n = n + 1
    if return_subarrays:
        return peaks, subarray_values, subarray_indices
    else:
        return peaks


@classmethod
def markUndoableState(cls):
    """Marks last undoable state.
        """
    return cls.build_send_payload('markUndoableState', {}), None


@classmethod
def get_from_string(cls, string_condition):
    """
        Convert string value obtained from k8s API to PodCondition enum value
        :param string_condition: str, condition value from Kubernetes API
        :return: PodCondition
        """
    if string_condition == 'PodScheduled':
        return cls.SCHEDULED
    elif string_condition == 'Ready':
        return cls.READY
    elif string_condition == 'Initialized':
        return cls.INITIALIZED
    elif string_condition == 'Unschedulable':
        return cls.UNSCHEDULABLE
    elif string_condition == 'ContainersReady':
        return cls.CONTAINERS_READY
    return cls.UNKNOWN


@classmethod
def by_name(cls, name: str):
    """Get service type by its name."""
    if name is None:
        return cls.GITHUB
    name = name.lower()
    if name == 'github':
        return cls.GITHUB
    elif name == 'gitlab':
        return cls.GITLAB
    else:
        raise NotImplementedError(
            f"Unsupported service {name!r}, available ones are 'github' and 'gitlab'"
            )


@classmethod
def _from_dict(cls, _dict):
    """Initialize a AnalyticsEngineCustomizationRunDetails object from a json dictionary."""
    return cls.from_dict(_dict)


def _validate_workflow_var_format(value: str):
    """Validate workflow vars."""
    add_info = ''
    parts = value.split('.')
    if len(parts) == 2:
        typ, attr = parts
        if attr not in ('name', 'id'):
            add_info = (
                'The only valid workflow variables with two segments are workflow.name and workflow.id.'
                )
    elif len(parts) == 4:
        typ, attr, prop, _ = parts
        if attr in ('inputs', 'outputs'):
            if prop not in ('parameters', 'artifacts'):
                add_info = (
                    'Workflow inputs and outputs variables must be "parameters" or "artifacts".'
                    )
        elif attr == 'operators':
            if parts[-1] != 'image':
                add_info = (
                    'Workflow operator variable can only access the image name.'
                    )
        else:
            add_info = (
                'Workflow variables must reference to "inputs", "outputs" or "operators".'
                )
    else:
        add_info = 'Workflow variables are either 2 or 4 segments.'
    return add_info


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


@staticmethod
def fileIndexFields():
    """
        Default behavior is that no additional file fields need to be indexed
        within the database.
        """
    return []


@staticmethod
def p_user_rights_optional_list(p):
    """user_rights_optional_list : user_rights_optional
                                     | user_rights_optional user_rights_optional_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


def standard_mask(detector):
    """Return a list of standard mask commands for the given detector."""
    assert len(detector) == 1
    size_fast, size_slow = detector[0].get_pixel_size()
    exclude = []
    for f0, s0, f1, s1 in detector[0].get_mask():
        exclude.append('LIMITS EXCLUDE %s %s %s %s' % (size_fast * f0,
            size_fast * f1, size_slow * s0, size_slow * s1))
    return exclude


def _mp3VersionKey(version):
    """Map mp3 version float to a data structure index.
    1 -> 0, 2 -> 1, 2.5 -> 2
    """
    key = None
    if version == 2.5:
        key = 2
    else:
        key = int(version - 1)
    assert 0 <= key <= 2
    return key


def _np_trace(a, offset=0, axis1=0, axis2=1, out=None):
    """
    Return the sum along diagonals of the array.
    If `a` is 2-D, the sum along its diagonal with the given offset
    is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
    If `a` has more than two dimensions, then the axes specified by axis1 and
    axis2 are used to determine the 2-D sub-arrays whose traces are returned.
    The shape of the resulting array is the same as that of `a` with `axis1`
    and `axis2` removed.

    Parameters
    ----------
    a : ndarray
        Input array, from which the diagonals are taken.
    offset : int, optional
        Offset of the diagonal from the main diagonal. Can be both positive
        and negative. Defaults to 0.
    axis1, axis2 : int, optional
        Axes to be used as the first and second axis of the 2-D sub-arrays
        from which the diagonals should be taken. Defaults are the first two
        axes of `a`.
    out : ndarray, optional
        Array into which the output is placed. It must be of the right shape
        and right type to hold the output.

    Returns
    -------
    sum_along_diagonals : ndarray
        If `a` is 2-D, the sum along the diagonal is returned.  If `a` has
        larger dimensions, then an array of sums along diagonals is returned.

    Examples
    --------
    >>> a = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    >>> np.trace(a)
    array(3.)
    >>> a = np.arange(8).reshape((2, 2, 2))
    >>> np.trace(a)
    array([6., 8.])
    >>> a = np.arange(24).reshape((2, 2, 2, 3))
    >>> np.trace(a).shape
    (2, 3)
    """
    pass


@classmethod
def from_str(cls, value):
    """Convert string to enum element.

        :param str value:
            String with value to convert.
        :returns:
            Enum class object.
        :raises:
            NotImplementedError
        """
    int_value = int(value)
    for item in cls:
        if item.value == int_value:
            return item
    raise NotImplementedError("'{}' is no element of '{}'".format(value,
        cls.__name__))


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

    """
    pass


def p_whencase(p):
    """whencase : case whencase
                 | empty
    """


def delete_elements(fhandle, element_set):
    """Removes specific atoms matching the given element(s).
    """
    records = 'ATOM', 'HETATM', 'ANISOU'
    for line in fhandle:
        if line.startswith(records):
            if line[76:78].strip() not in element_set:
                continue
        yield line


def rotate(cam_file, angle):
    """ Rotate a Cam file a specified amount about the origin.

    Parameters
    ----------
    cam_file : :class:`gerber.cam.CamFile` subclass
        Gerber or Excellon file to rotate

    angle : float
        Angle to rotate the file in degrees.

    Returns
    -------
    cam_file : :class:`gerber.cam.CamFile` subclass
        An rotated deep copy of the source file.
    """
    pass


def mean_photon(state, wires, params):
    """Computes the expectation value of the ``qml.NumberOperator``
    observable in Strawberry Fields.

    Args:
        state (strawberryfields.backends.states.BaseState): the quantum state
        wires (Sequence[int]): the measured mode
        params (Sequence): sequence of parameters (not used)

    Returns:
        float, float: mean photon number and its variance
    """
    return state.mean_photon(wires[0])


@classmethod
def stringToValue(cls, string, dtype):
    """
        Returns a representation of ``string`` as value of given ``dtype``.
        If ``string`` represents a list of values in curly brackets (e.g. ``{1, 2, 3}``),
        a list of values is returned.
        """
    string.strip()
    if string.startswith('{') and string.endswith('}'):
        value = cls._stringToList(string, dtype)
    else:
        value = dtype(string)
    return value


def get_edit_distance(s1, s2):
    """Calculate the Levenshtein distance between two normalised strings
    Adopted from example in https://stackoverflow.com/questions/2460177/edit-distance-in-python
    See https://en.wikipedia.org/wiki/Edit_distance
    @param s1: the first string to compare
    @param s2: the second string to compare
    @returns: an integer giving the edit distance
    """
    if len(s1) > len(s2):
        s1, s2 = s2, s1
    distances = range(len(s1) + 1)
    for i2, c2 in enumerate(s2):
        distances_ = [i2 + 1]
        for i1, c1 in enumerate(s1):
            if c1 == c2:
                distances_.append(distances[i1])
            else:
                distances_.append(1 + min((distances[i1], distances[i1 + 1],
                    distances_[-1])))
        distances = distances_
    return distances[-1]


@classmethod
def validate_rbac_policy_update(cls, resource, event, trigger, payload=None):
    """Callback to handle RBAC_POLICY, BEFORE_UPDATE callback.

        :raises: RbacPolicyInUse -- in case the update is forbidden.
        """
    policy = payload.latest_state
    prev_tenant = policy['target_tenant']
    new_tenant = payload.request_body['target_tenant']
    if prev_tenant == new_tenant:
        return
    if new_tenant != '*':
        return cls.validate_rbac_policy_delete(resource, event, trigger,
            payload=payload)


def sanitize(run_time):
    """Sanitizes the 'run_time' parameter by replacing ':' and '-' with '.'
       to make sure input data is consistent"""
    if '-' in run_time:
        token = '-'
    elif ':' in run_time:
        token = ':'
    else:
        return run_time
    mins, secs = run_time.split(token)
    return mins + '.' + secs


def get(tree, name):
    """ Return a float value attribute NAME from TREE.
    """
    if name in tree:
        value = tree[name]
    else:
        return float('nan')
    try:
        a = float(value)
    except ValueError:
        a = float('nan')
    return a


def to_rgb_string(rgb):
    """Convert to rgb string."""
    return ('%02x%02x%02x' % rgb).lower()


def display_bloch_sphere_qutrit(**kwargs):
    """
    Prints an error message.
    """
    print('display_bloch_sphere_qutrit not available on this version.')


@classmethod
def rollback_to(cls, **filters) ->int:
    """
        All records matching the query and valid at specified validity will be considered as valid.
        :return Number of records updated.
        """
    return 0


def _apply_odf_properties(df, headers, model):
    """
    Attach properties to the Dataframe to carry along ODF metadata

    :param df: The dataframe to be modified
    :param headers: The ODF header lines
    :param model: The ODF model type
    """
    df.headers = headers
    df.model = model


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 flatten(seq):
    """Concatenates the elements of seq.

    Given a list of lists, returns a new list that concatentes
    the elements of (seq).  This just does one level of flattening;
    it is not recursive.
    """
    return sum(seq, [])


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


def botGotPostAddAction(bot, groupId, creatorId, user, text, dbAction,
    handledByExtension, event):
    """
  bot got group chat message: text
  bot could send some response
  """
    if handledByExtension:
        return
    if f'![:Person]({bot.id})' in text:
        bot.sendMessage(groupId, {'text':
            f'![:Person]({creatorId}), Hello, you just posted "{text}"'})


@classmethod
def spawn(cls, *args, **kwargs):
    """
        spawn(function, *args, **kwargs) -> Greenlet

        Create a new :class:`Greenlet` object and schedule it to run ``function(*args, **kwargs)``.
        This can be used as ``gevent.spawn`` or ``Greenlet.spawn``.

        The arguments are passed to :meth:`Greenlet.__init__`.

        .. versionchanged:: 1.1b1
            If a *function* is given that is not callable, immediately raise a :exc:`TypeError`
            instead of spawning a greenlet that will raise an uncaught TypeError.
        """
    g = cls(*args, **kwargs)
    g.start()
    return g


def unpack(seq):
    """ Unpack sequence of length one

    >>> unpack([1, 2, 3])
    [1, 2, 3]

    >>> unpack([1])
    1
    """
    seq = list(seq)
    if len(seq) == 1:
        seq = seq[0]
    return seq


def all_in_dict(nameL, D):
    """If all members of nameL are keys in D, then return True, otherwise False."""
    for name in nameL:
        if name not in D:
            return False
    return True


def pystrdecode(cstr):
    """
    Decode a string to a python string.
    """
    try:
        return cstr.decode('utf-8')
    except AttributeError:
        return cstr


def describe():
    """Return a short string describing this handler, like 'tcp' or
        'tor'. If this method is not implemented, the handler's repr will be
        used."""


def build_plural_mappings(special_mappings, resource_map):
    """Create plural to singular mapping for all resources.

    Allows for special mappings to be provided, like policies -> policy.
    Otherwise, will strip off the last character for normal mappings, like
    routers -> router.
    """
    plural_mappings = {}
    for plural in resource_map:
        singular = special_mappings.get(plural)
        if not singular:
            if plural.endswith('ies'):
                singular = '%sy' % plural[:-3]
            else:
                singular = plural[:-1]
        plural_mappings[plural] = singular
    return plural_mappings


def get_kmgraph_meta(mapper_summary):
    """ Extract info from mapper summary to be displayed below the graph plot
    """
    d = mapper_summary['custom_meta']
    meta = 'N_cubes: ' + str(d['n_cubes']
        ) + ' Perc_overlap: ' + str(d['perc_overlap'])
    meta += '
Nodes: ' + str(mapper_summary['n_nodes']
        ) + ' Edges: ' + str(mapper_summary['n_edges']
        ) + ' Total samples: ' + str(mapper_summary['n_total']
        ) + ' Unique_samples: ' + str(mapper_summary['n_unique'])
    return meta


@staticmethod
def _path_esc(path: str) ->str:
    """Escape space character in the path.

        :param path: path to be escaped
        :type path: str
        :return: path with escaped spaces
        :rtype: str
        """
    return path.replace(' ', '\\ ')


def bytes_to_human_readable(memory_amount):
    """ Utility to convert a number of bytes (int) in a human readable string (with units)
    """
    for unit in ['B', 'KB', 'MB', 'GB']:
        if memory_amount > -1024.0 and memory_amount < 1024.0:
            return '{:.3f}{}'.format(memory_amount, unit)
        memory_amount /= 1024.0
    return '{:.3f}TB'.format(memory_amount)


def select_line():
    """Select text by line

    """
    pass


def shape_key_clear():
    """Clear weights for all shape keys

    """
    pass


def get_codon(seq, codon_no, start_offset):
    """
    This function takes a sequece and a codon number and returns the codon
    found in the sequence at that position
    """
    seq = seq.replace('-', '')
    codon_start_pos = int(codon_no - 1) * 3 - start_offset
    codon = seq[codon_start_pos:codon_start_pos + 3]
    return codon


def create_part_xml(part_msg_list=None):
    """
    get information from part_msg_list and covert it to xml.
    part_msg_list has special format.
    """
    if not part_msg_list:
        part_msg_list = []
    xml_string = '<CompleteMultipartUpload>'
    for part in part_msg_list:
        if len(part) >= 3:
            xml_string += '<Part>'
            xml_string += '<PartNumber>' + str(part[0]) + '</PartNumber>'
            xml_string += '<ETag>"' + str(part[2]) + '"</ETag>'
            xml_string += '</Part>'
        else:
            print('the ', part, ' in part_msg_list is not as expected!')
            return ''
    xml_string += '</CompleteMultipartUpload>'
    return xml_string


def quaternion_real(quaternion):
    """Return real part of quaternion.

    >>> quaternion_real([3, 0, 1, 2])
    3.0

    """
    return float(quaternion[0])


def overlap(a, b):
    """Returns overlap of a and b (symmetric)

        Cases:
        * overlap  < 0 when a and b do not overlap
        * overlap == 0 when a and b abut or at least one is zero width
        * overlap  > 0 when a and b overlap

        """
    return min(a.end, b.end) - max(a.start, b.start)


def reachedLimit(parameter, analyzer):
    """Checks if the set limit has been reached

  :rtype: bool
  """
    if analyzer.query_size() == analyzer.size():
        return True
    if not parameter.retmax:
        return False
    if analyzer.size() == parameter.retmax:
        return True
    return False


def merge_two_dicts(x, y):
    """
    Returns two combined dictionaries
    """
    return {**x, **y}


def linalg_det(A=None, out=None, name=None, **kwargs):
    """Compute the determinant of a matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* is a square matrix. We compute:

      *out* = *det(A)*

    If *n>2*, *det* is performed separately on the trailing two dimensions
    for all inputs (batch mode).

    .. note:: The operator supports float32 and float64 data types only.
    .. note:: There is no gradient backwarded when A is non-invertible (which is
              equivalent to det(A) = 0) because zero is rarely hit upon in float
              point computation and the Jacobi's formula on determinant gradient
              is not computationally efficient when A is non-invertible.

    Examples::

       Single matrix determinant
       A = [[1., 4.], [2., 3.]]
       det(A) = [-5.]

       Batch matrix determinant
       A = [[[1., 4.], [2., 3.]],
            [[2., 3.], [1., 4.]]]
       det(A) = [-5., 5.]

    Defined in src/operator/tensor/la_op.cc:L973

    Parameters
    ----------
    A : NDArray
        Tensor of square matrix

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

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


@classmethod
def register(cls, config={}):
    """
        This function is basically a shortcut of boot for accessors
        that have only the config dict argument.

        Args
        ----
          config (dict): the configuration dictionary
        """
    if cls.accessor is not None:
        if cls.instance is None:
            cls.instance = cls.accessor(config)


def pose_add(frame: int=1, name: str='Pose'):
    """Add the current Pose to the active Pose Library

    :param frame: Frame, Frame to store pose on
    :type frame: int
    :param name: Pose Name, Name of newly added Pose
    :type name: str
    """
    pass


def pytest_bdd_after_scenario(request, feature, scenario):
    """Called after scenario is executed."""


def proximity(lfam1, lfam2, geneProximityD, proximityThreshold, strain):
    """Return True if any of the genes at strain from lfam1 are within
proximityThreshold of genes at that strain for lfam2. proximityThreshold
is measured in genes, e.g. 1 means the adjacent gene.
    """
    for gn1 in lfam1.iterGenesByStrain(strain):
        for gn2 in lfam2.iterGenesByStrain(strain):
            if gn1 < gn2:
                key = gn1, gn2
            else:
                key = gn2, gn1
            if key in geneProximityD and geneProximityD[key
                ] <= proximityThreshold:
                return True
    return False


def clean_spaces(m):
    """Replace unencoded spaces in string.

    :param str m: a match object
    :return: the cleaned string
    """
    return m.group(0).replace(' ', '=20')


def get_wid(word):
    """Return the wird id for the given word.

        Return 0 of the word is not in the lexicon.
        """


def view_all():
    """Resize view so you can see all nodes

    """
    pass


def setattrdefault(obj, attribute, default=None):
    """Setdefault for attribute.

    Returns 'attribute' value if defined or set it to default and return it.
    """
    try:
        return getattr(obj, attribute)
    except AttributeError:
        setattr(obj, attribute, default)
        return default


def to_best_int_float(val):
    """Get best type for value between int and float

    :param val: value
    :type val:
    :return: int(float(val)) if int(float(val)) == float(val), else float(val)
    :rtype: int | float

    >>> to_best_int_float("20.1")
    20.1

    >>> to_best_int_float("20.0")
    20

    >>> to_best_int_float("20")
    20
    """
    integer = int(float(val))
    flt = float(val)
    if integer == flt:
        return integer
    return flt


@classmethod
def get_styles(cls):
    """
        A class method which returns a dictionary of available styles.
        """
    return cls._style_list


def get_pipeline_execute_url(environment: str, enterprise_id: str,
    pipeline_id: str, execute_id: str=None, action: str=None) ->str:
    """
    Build and return pipeline Execute url for scapi endpoint
    :param environment:
    :param enterprise_id:
    :param pipeline_id:
    :param execute_id:
    :param action:
    :return: Url
    """
    url = (
        f'https://{environment}-api.esper.cloud/api/v1/enterprise/{enterprise_id}/pipeline/{pipeline_id}/execute/'
        )
    if execute_id:
        url = f'{url}{execute_id}/'
        if action:
            url = f'{url}{action}/'
    return url


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


def eval_surface_exposed_loop(sequence_length, n_transmembrane_region,
    outer_loops, terminal_exposed_loop_min, internal_exposed_loop_min):
    """
    This is the key algorithm in SurfG+ to identify Potentially Surface
    Exposed proteins. It evaluates all loops that poke out of the periplasmic
    side of the Gram+ bacterial membrane and tests if the loops are long
    enough to stick out of the peptidoglycan layer to be cleaved by proteases
    in a cell-shaving experiment.

    Returns True if any outer loop, or the N- or C-terminii are
    longer than the given thresholds.
    """
    outer_loops = outer_loops[:]
    if n_transmembrane_region == 0:
        return sequence_length >= terminal_exposed_loop_min
    if not outer_loops:
        return False
    loop_len = lambda loop: abs(loop[1] - loop[0]) + 1
    if outer_loops[0][0] == 1:
        nterminal_loop = outer_loops[0]
        del outer_loops[0]
        if loop_len(nterminal_loop) >= terminal_exposed_loop_min:
            return True
    if outer_loops:
        if outer_loops[-1][-1] == sequence_length:
            cterminal_loop = outer_loops[-1]
            del outer_loops[-1]
            if loop_len(cterminal_loop) >= terminal_exposed_loop_min:
                return True
    for loop in outer_loops:
        if loop_len(loop) >= internal_exposed_loop_min:
            return True
    return False


def dict_to_sequence(d):
    """Returns an internal sequence dictionary update."""
    if hasattr(d, 'items'):
        d = d.items()
    return d


def perform_metadata_inspection(container):
    """
    Prints the metadata of the container to the terminal.

    :param container: the container
    :type container: :class:`surround.data.container.DataContainer`
    """
    metadata = container.metadata
    print('Metadata format version: %s' % metadata['version'])
    print('Summary Metadata:')
    print('  Title:          %s' % metadata['summary']['title'])
    print('  Description:    %s' % metadata['summary']['description'])
    print('  Creator:        %s' % metadata['summary']['creator'])
    print('  Date:           %s' % metadata['summary']['date'])
    print('  Publisher:      %s' % metadata['summary']['publisher'])
    print('  Contributor:    %s' % metadata['summary']['contributor'])
    print('  Subject:        %s' % metadata['summary']['subject'])
    print('  Formats:        %s' % metadata['summary']['formats'])
    print('  Types:          %s' % metadata['summary']['types'])
    print('  Identifier:     %s' % metadata['summary']['identifier'])
    print('  Rights:         %s' % metadata['summary']['rights'])
    print('  Under Ethics:   %s' % metadata['summary']['under-ethics'])
    print('  Language:       %s\n' % metadata['summary']['language'])
    if metadata.get_property('manifests'):
        for manifest in metadata['manifests']:
            print("'%s' Group Metadata:" % manifest['path'])
            print('  Description:   %s' % manifest['description'])
            print('  Language:      %s' % manifest['language'])
            print('  Formats:       %s' % manifest['formats'])
            print('  Types:         %s\n' % manifest['types'])


def xml_subelement_attr_list(xml_elem, subelement, convert=None, attribute=
    'value', default=None, quiet=False):
    """
    Search for sub-elements and return a list of the specified attribute.

    .. code-block:: xml

        <xml_elem>
            <subelement value="THIS" />
            <subelement value="THIS2" />
            ...
        </xml_elem>

    For the above document, ["THIS", "THIS2"] will be returned

    :param xml_elem: search the children nodes of this element
    :param subelement: name of the sub-element to search for
    :param convert: if not None, a callable used to perform the conversion of this attribute to a certain object type
    :param attribute: name of the attribute to get
    :param default: default value to use if an attribute is missing
    :param quiet: if True, don't raise exceptions from conversions, instead use the default value
    :return: list containing the values of the attributes or ``None`` in error cases
    """
    if xml_elem is None or not subelement:
        return None
    subel = xml_elem.findall(subelement)
    res = []
    for e in subel:
        value = e.attrib.get(attribute)
        if value is None:
            value = default
        elif convert:
            try:
                value = convert(value)
            except:
                if quiet:
                    value = default
                else:
                    raise
        res.append(value)
    return res


@staticmethod
def p_available_event_list_optional_list(p):
    """available_event_list_optional_list : available_event_list_optional
                                              | available_event_list_optional available_event_list_optional_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


def return_response(response):
    """Parses and prints the Analytics Reporting API V4 response
       Returns a dictionary of all the values"""
    for report in response.get('reports', []):
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get(
            'metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])
        for row in rows:
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])
            for i, values in enumerate(dateRangeValues):
                return values.get('values')
        return


def store_sort_key(item):
    """Sorting function for STORE_DATA items.
    For the regex to work correctly, we want the longest store names to
    appear first.
    """
    store, _ = item
    return -len(store), store


def select_all():
    """Select all text

    """
    pass


def edge_rotate(use_ccw: bool=False):
    """Rotate selected edge or adjoining faces

    :param use_ccw: Counter Clockwise
    :type use_ccw: bool
    """
    pass


@staticmethod
def translate(value, left_min, left_max, right_min, right_max):
    """Map a value from left span to right span."""
    left_span = left_max - left_min
    right_span = right_max - right_min
    value_scaled = float(value - left_min) / float(left_span)
    return int(right_min + value_scaled * right_span)


def extract_all_ss_dssp(in_dssp, path=True):
    """Uses DSSP to extract secondary structure information on every residue.

    Parameters
    ----------
    in_dssp : str
        Path to DSSP file.
    path : bool, optional
        Indicates if pdb is a path or a string.

    Returns
    -------
    dssp_residues : [tuple]
        Each internal list contains:
            [0] int Residue number
            [1] str Secondary structure type
            [2] str Chain identifier
            [3] str Residue type
            [4] float Phi torsion angle
            [5] float Psi torsion angle
            [6] int dssp solvent accessibility
    """
    if path:
        with open(in_dssp, 'r') as inf:
            dssp_out = inf.read()
    else:
        dssp_out = in_dssp[:]
    dssp_residues = []
    active = False
    for line in dssp_out.splitlines():
        if active:
            try:
                res_num = int(line[5:10].strip())
                chain = line[10:12].strip()
                residue = line[13]
                ss_type = line[16]
                phi = float(line[103:109].strip())
                psi = float(line[109:116].strip())
                acc = int(line[35:38].strip())
                dssp_residues.append((res_num, ss_type, chain, residue, phi,
                    psi, acc))
            except ValueError:
                pass
        elif line[2] == '#':
            active = True
    return dssp_residues


def lrelu(features, leak=0.2):
    """Leaky rectifier.

    Parameters
    ----------
    features : tf.Tensor
        Input to apply leaky rectifier to.
    leak : float, optional
        Percentage of leak.

    Returns
    -------
    op : tf.Tensor
        Resulting output of applying leaky rectifier activation.
    """
    f1 = 0.5 * (1 + leak)
    f2 = 0.5 * (1 - leak)
    return f1 * features + f2 * abs(features)


def Archimedes(L, rhof, rhop, mu, g=g):
    """Calculates Archimedes number, `Ar`, for a fluid and particle with the
    given densities, characteristic length, viscosity, and gravity
    (usually diameter of particle).

    .. math::
        Ar = \\frac{L^3 \\rho_f(\\rho_p-\\rho_f)g}{\\mu^2}

    Parameters
    ----------
    L : float
        Characteristic length, typically particle diameter [m]
    rhof : float
        Density of fluid, [kg/m^3]
    rhop : float
        Density of particle, [kg/m^3]
    mu : float
        Viscosity of fluid, [N/m]
    g : float, optional
        Acceleration due to gravity, [m/s^2]

    Returns
    -------
    Ar : float
        Archimedes number []

    Notes
    -----
    Used in fluid-particle interaction calculations.

    .. math::
        Ar = \\frac{\\text{Gravitational force}}{\\text{Viscous force}}

    Examples
    --------
    >>> Archimedes(0.002, 2., 3000, 1E-3)
    470.4053872

    References
    ----------
    .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
       Eighth Edition. McGraw-Hill Professional, 2007.
    .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    """
    return L ** 3 * rhof * (rhop - rhof) * g / mu ** 2


def create_route(app, engineio_server, engineio_endpoint):
    """This function sets up the engine.io endpoint as a route for the
    application.

    Note that both GET and POST requests must be hooked up on the engine.io
    endpoint.
    """
    app.router.add_get(engineio_endpoint, engineio_server.handle_request)
    app.router.add_post(engineio_endpoint, engineio_server.handle_request)
    app.router.add_route('OPTIONS', engineio_endpoint, engineio_server.
        handle_request)


def input_string(message):
    """Handle inputs if they are supposed to be strings"""
    while True:
        answer = input(message)
        if isinstance(answer, str):
            if answer.casefold() == 'none':
                return None
            else:
                return answer
        else:
            print('Please enter an integer')


def remove():
    """Routine to be run by the win32 installer with the -remove switch."""
    pass


def calc_source_params(source_df):
    """
    Calculate source parameters

    The source params that are calculated are:
        1. Moment Magnitude
        2. Energy
    """


@classmethod
def plot_options(cls, obj, percent_size):
    """
        Given an object and a percentage size (as supplied by the
        %output magic) return all the appropriate plot options that
        would be used to instantiate a plot class for that element.

        Default plot sizes at the plotting class level should be taken
        into account.
        """
    raise NotImplementedError


def predict_cluster_by_precomputed_distances(precomputed_distances):
    """
    Predict a cluster for each object with precomputed distances.

    Parameters
    ----------
    precomputed_distances : np.array
        array of shape (n_topics, n_objects) - distances from clusters to objects

    Returns
    -------
    np.array
        array of length X.shape[0], each element is cluster of ith object

    """
    return precomputed_distances.T.argmin(axis=1).ravel()


def _resolve_name(name, package, level):
    """Return the absolute name of the module to be imported."""
    if not hasattr(package, 'rindex'):
        raise ValueError("'package' not set to a string")
    dot = len(package)
    for x in range(level, 1, -1):
        try:
            dot = package.rindex('.', 0, dot)
        except ValueError:
            raise ValueError(
                'attempted relative import beyond top-level package')
    return '%s.%s' % (package[:dot], name)


def get_global_option(checker, option, default=None):
    """ Retrieve an option defined by the given *checker* or
    by all known option providers.

    It will look in the list of all options providers
    until the given *option* will be found.
    If the option wasn't found, the *default* value will be returned.
    """
    try:
        return getattr(checker.config, option.replace('-', '_'))
    except AttributeError:
        pass
    for provider in checker.linter.options_providers:
        for options in provider.options:
            if options[0] == option:
                return getattr(provider.config, option.replace('-', '_'))
    return default


def flags(path):
    """Return the flags value for a path (default: empty bytestring)."""


def _cost_so_far(node):
    """ also referred to as `g' in the class notation """
    prev_cost = 0 if node.is_root() else node.parent.incremental_cost
    node.incremental_cost = prev_cost + node.cost
    return node.incremental_cost


def dctDecode(stream, parameters):
    """
        Method to decode streams using a DCT technique based on the JPEG standard (NOT IMPLEMENTED YET)

        @param stream: A PDF stream
        @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1
    """
    decodedStream = ''
    try:
        from PIL import Image
        import io
    except:
        return -1, 'Python Imaging Library (PIL) not installed'
    try:
        im = Image.open(io.StringIO(stream))
        decodedStream = im.tostring()
        return 0, decodedStream
    except:
        return -1, 'Error decompresing image data'


def __contains__(item):
    """ `x.__contains__(item)` <==> `item in x` """


def drop_color(color: float=(0.0, 0.0, 0.0), gamma: bool=False):
    """Drop colors to buttons

    :param color: Color, Source color
    :type color: float
    :param gamma: Gamma Corrected, The source color is gamma corrected
    :type gamma: bool
    """
    pass


def _get_caching_device(job_name, task_id):
    """ Returns the local caching device for a given job name / task id """
    if job_name != 'learner':
        return None
    return '/job:%s/task:%d' % (job_name, task_id)


def inject_mutations_1(phi, dt, x, dx, y2, theta1):
    """
    new mutations injected along phi[1,:] against a background given by y2
    phi - numerical density function
    dt - given time step
    x, dx - one dimensional grid and grid spacing
    y2 - the biallelic density function
    theta1 - population scaled mutation rate for mutation 1
    """
    phi[(1), 1:-1] += y2[1:-1] / dx[1] * 1.0 / x[1] * dt * theta1 / 2
    return phi


def list_files(client, dataset, total=None, limit=None):
    """List dataset files.

	Args:
	    :client: the pyAMI client [ pyAMI.client.Client ]
	    :dataset: the logical dataset name [ str ]
	    :total: produce a grand total [ bool | None]
	    :limit: limit number of results [ int | tuple<int,int> | None ]

	Returns:
	    an array of python dictionnaries.
	"""
    command = ['AMIListFiles', '-logicalDatasetName="%s"' % dataset]
    if total:
        command.append('-total=yes')
    else:
        command.append('-total=no')
    if limit:
        if isinstance(limit, (list, tuple)):
            command.append('-limit=%i,%i' % (limit[0], limit[1]))
        else:
            command.append('-limit=0,%i' % limit)
    return client.execute(command, format='dom_object').get_rows()


def _thread_done(gt, *args, **kwargs):
    """Callback function to be passed to GreenThread.link() when we spawn()
    Calls the :class:`ThreadGroup` to notify if.

    """
    kwargs['group'].thread_done(kwargs['thread'])


def masterpid():
    """Return the process identifier (PID) of the uWSGI master process.

    :rtype: int
    """
    return -1


def IvyGetApplicationHost(client):
    """
    Equivalent to ``client.fqdn``. IP address is stored under ``client.ip``,
    and port number under ``client.port``

    :param client: an :py:class:`ivy.ivy.IvyClient` object,  as returned by
      :py:func:`IvyGetApplication()`
    """
    return client.fqdn


def broadcast_hypot(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """ Returns the hypotenuse of a right angled triangle, given its "legs"
    with broadcasting.

    It is equivalent to doing :math:`sqrt(x_1^2 + x_2^2)`.

    Example::

       x = [[ 3.,  3.,  3.]]

       y = [[ 4.],
            [ 4.]]

       broadcast_hypot(x, y) = [[ 5.,  5.,  5.],
                                [ 5.,  5.,  5.]]

       z = [[ 0.],
            [ 4.]]

       broadcast_hypot(x, z) = [[ 3.,  3.,  3.],
                                [ 5.,  5.,  5.]]

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L158

    Parameters
    ----------
    lhs : NDArray
        First input to the function
    rhs : NDArray
        Second input to the function

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

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


def split_nonsyllabic_maxonset(string, onsets):
    """
    Finds split between onset and coda in list with no found syllabic segments

    Parameters
    ----------
    string : iterable
        the phones to search through
    onsets : iterable
        an iterable of possible onsets

    Returns
    -------
    int
        the index in the string where the onset ends and coda begins
    """
    if len(string) == 0:
        return None
    for i in range(len(string), -1, -1):
        ons = tuple(string[:i])
        cod = tuple(string[i:])
        if ons not in onsets:
            continue
        else:
            return i
    return None


def sparse_matrix(data, index, shape, force_format=False):
    """Create a sparse matrix.

    NOTE: Please make sure that the data and index tensors are not
    copied. This is critical to the performance.

    Parameters
    ----------
    data : Tensor
        Data tensor. It should be of shape (nnz,).
    index : tuple
        This is used to support different sparse formats.
        For COO format:
          index=('coo', coord), where coord is of shape (2, nnz).
          coord[0,:] should be the row index and coord[1,:] should be
          the column index.
        For CSR format:
          index=('csr', indices, indptr), where indices is of shape (nnz,)
          and indptr is of shape (nrows+1,). See ``scipy.sparse.csr_matrix``
          for more documents on what each array means.
    shape : tuple of int
        The shape.
    force_format : bool
        If true, the returned sparse matrix must be stored in the same
        format as the given index.

    Returns
    -------
    SparseMatrix
        The framework-specific sparse matrix. It can be stored in any format
        unless force_format is True.
    Tensor
        The data convert index due to sparse format change.
        None if no conversion is needed.
    """
    pass


@staticmethod
def _broadcast(destination, message, **kwargs):
    """Broadcast a message.
        :param destination: Topic name to send to
        :param message: A string to be broadcast
        :param **kwargs: Further parameters for the transport layer. For example
               headers: Optional dictionary of header entries
               expiration: Optional expiration time, relative to sending time
               transaction: Transaction ID if message should be part of a
                            transaction
        """
    raise NotImplementedError('Transport interface not implemented')


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 _map(value, istart, istop, ostart, ostop):
    """
    Helper function that implements the Processing function map(). For more
    details see https://processing.org/reference/map_.html
    http://stackoverflow.com/questions/17134839/how-does-the-map-function-in-processing-work
    """
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))


def equals(v1, v2, epsilon=1e-06):
    """
    Returns True if difference between given values is less then tolerance.

    Args:
        v1: float
            Value one.

        v2: float
            Value two

        epsilon: float
            Max allowed difference.

    Returns:
        bool
            True if values equal, False otherwise.
    """
    return abs(v1 - v2) <= epsilon


def _ctypes_regular(parameter):
    """Returns the code lines to define a *local* variable with the fortran types
    that has a matching signature to the wrapped executable.
    """
    if ('pointer' in parameter.modifiers or 'allocatable' in parameter.
        modifiers or 'target' in parameter.modifiers or parameter.dtype ==
        'logical'):
        return parameter.definition(local=True), False


def generate_key(action, path_or_id, settings=None, default=' (default)'):
    """ generate_key: generate key used for caching
        Args:
            action (str): how video is being processed (e.g. COMPRESSED or DOWNLOADED)
            path_or_id (str): path to video or youtube_id
            settings (dict): settings for compression or downloading passed in by user
            default (str): if settings are None, default to this extension (avoid overwriting keys)
        Returns: filename
    """
    settings = ' {}'.format(str(sorted(settings.items()))
        ) if settings else default
    return '{}: {}{}'.format(action.upper(), path_or_id, settings)


def take(n, it, stop_short=False):
    """
	>>> list(take(3, iter([1,2,3,4,5])))
	[1, 2, 3]
	>>> list(take(0, iter([1,2,3,4,5])))
	[]
	>>> list(take(3, iter([1]), True))
	[1]
	"""
    results = []
    try:
        while n > 0:
            results.append(next(it))
            n -= 1
        return results
    except StopIteration:
        if stop_short:
            return results
        raise


def update_configuration_set_event_destination(ConfigurationSetName=None,
    EventDestination=None):
    """
    Updates the event destination of a configuration set.
    Event destinations are associated with configuration sets, which enable you to publish email sending events to Amazon CloudWatch or Amazon Kinesis Firehose. For information about using configuration sets, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

    :example: response = client.update_configuration_set_event_destination(
        ConfigurationSetName='string',
        EventDestination={
            'Name': 'string',
            'Enabled': True|False,
            'MatchingEventTypes': [
                'send'|'reject'|'bounce'|'complaint'|'delivery',
            ],
            'KinesisFirehoseDestination': {
                'IAMRoleARN': 'string',
                'DeliveryStreamARN': 'string'
            },
            'CloudWatchDestination': {
                'DimensionConfigurations': [
                    {
                        'DimensionName': 'string',
                        'DimensionValueSource': 'messageTag'|'emailHeader',
                        'DefaultDimensionValue': 'string'
                    },
                ]
            }
        }
    )

    :type ConfigurationSetName: string
    :param ConfigurationSetName: [REQUIRED]
            The name of the configuration set that you want to update.

    :type EventDestination: dict
    :param EventDestination: [REQUIRED]
            The event destination object that you want to apply to the specified configuration set.
            Name (string) -- [REQUIRED]The name of the event destination. The name must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
            Contain less than 64 characters.
            Enabled (boolean) --Sets whether Amazon SES publishes events to this destination when you send an email with the associated configuration set. Set to true to enable publishing to this destination; set to false to prevent publishing to this destination. The default value is false .
            MatchingEventTypes (list) -- [REQUIRED]The type of email sending events to publish to the event destination.
            (string) --
            KinesisFirehoseDestination (dict) --An object that contains the delivery stream ARN and the IAM role ARN associated with an Amazon Kinesis Firehose event destination.
            IAMRoleARN (string) -- [REQUIRED]The ARN of the IAM role under which Amazon SES publishes email sending events to the Amazon Kinesis Firehose stream.
            DeliveryStreamARN (string) -- [REQUIRED]The ARN of the Amazon Kinesis Firehose stream to which to publish email sending events.
            CloudWatchDestination (dict) --An object that contains the names, default values, and sources of the dimensions associated with an Amazon CloudWatch event destination.
            DimensionConfigurations (list) -- [REQUIRED]A list of dimensions upon which to categorize your emails when you publish email sending events to Amazon CloudWatch.
            (dict) --Contains the dimension configuration to use when you publish email sending events to Amazon CloudWatch.
            For information about publishing email sending events to Amazon CloudWatch, see the Amazon SES Developer Guide .
            DimensionName (string) -- [REQUIRED]The name of an Amazon CloudWatch dimension associated with an email sending metric. The name must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
            Contain less than 256 characters.
            DimensionValueSource (string) -- [REQUIRED]The place where Amazon SES finds the value of a dimension to publish to Amazon CloudWatch. If you want Amazon SES to use the message tags that you specify using an X-SES-MESSAGE-TAGS header or a parameter to the SendEmail /SendRawEmail API, choose messageTag . If you want Amazon SES to use your own email headers, choose emailHeader .
            DefaultDimensionValue (string) -- [REQUIRED]The default value of the dimension that is published to Amazon CloudWatch if you do not provide the value of the dimension when you send an email. The default value must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
            Contain less than 256 characters.

    :rtype: dict
    :return: {}

    """
    pass


def psi_Ca_OH_SO4_HMW84(T, P):
    """c-a-a': calcium hydroxide sulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


@staticmethod
def merge_dicts(d1, *args):
    """Merge dictionaries

        :param d1: dict 1
        :param *args: one or more dicts
        :returns: merged dict
        """
    d2 = {}
    for d in args:
        d2 = d.copy()
        d2.update(d1)
        d1 = d2
    return d2


def type2color(context, t):
    """
    Return a color to render the given UpdateType with.

    Args:
        context (mako.runtime.Context): The current template rendering context.
        t (bodhi.server.models.UpdateType): The UpdateType you wish to choose a color for.
    Returns:
        str: A string in the format rgba(RED, GREEN, BLUE, ALPHA), where RED, GREEN, BLUE,
            and ALPHA are replaced with numerical values to represent a color.
    """
    t = str(t)
    cls = {'bugfix': 'rgba(150,180,205,0.5)', 'security':
        'rgba(205,150,180,0.5)', 'newpackage': 'rgba(150,205,180,0.5)',
        'enhancement': 'rgba(205,205,150,0.5)', 'default':
        'rgba(200,200,200,0.5)'}
    return cls[t] if t in cls.keys() else cls['default']


def display_line(ligne, screen, pygame):
    """
    Affiche une ligne à l'écran.
    """
    color = 0, 0, 0
    for p in ligne:
        pygame.draw.line(screen, color, p, p)
    pygame.display.flip()


def ask_order_array(market, p, q, reference_price):
    """ make array of orders from array of percents, quantities and reference price """
    i = 0
    orders = list()
    for px in p:
        submit_price = reference_price * (1 + px)
        orders.append([market, 'SELL', submit_price, q[i]])
        i += 1
    return orders


def _to_abstime(messages):
    """Convert messages to absolute time."""
    now = 0
    for msg in messages:
        now += msg.time
        yield msg.copy(time=now)


def renderHeaders():
    """Render the individual HTML headers from the columns.

        Uses renderHeader."""


@classmethod
def get_unpack_filter(cls, unpackable_target):
    """Calculate a filter function from the include/exclude patterns of a Target.

        :param ImportRemoteSourcesMixin unpackable_target: A target with include_patterns and
                                                           exclude_patterns attributes.
        """
    return cls._calculate_unpack_filter(includes=unpackable_target.payload.
        include_patterns, excludes=unpackable_target.payload.
        exclude_patterns, spec=unpackable_target.address.spec)


def predict(model, module, sess=None, compute_pars=None, data_pars=None,
    out_pars=None, **kwarg):
    """
       predict  using a pre-trained model and some data
    :param model:
    :param module:
    :param sess:
    :param data_pars:
    :param out_pars:
    :param kwarg:
    :return:
    """
    return module.predict(model, sess, data_pars, **kwarg)


def get_class_from_string(path, default=None):
    """
    Return the class specified by the string.

    IE: django.contrib.auth.models.User
    Will return the user class or cause an ImportError
    """
    try:
        from importlib import import_module
    except ImportError:
        from django.utils.importlib import import_module
    i = path.rfind('.')
    module, attr = path[:i], path[i + 1:]
    mod = import_module(module)
    try:
        return getattr(mod, attr)
    except AttributeError:
        if default:
            return default
        else:
            raise ImportError('Cannot import name {} (from {})'.format(attr,
                mod))


@classmethod
def parse_service_table(cls, tablename):
    """Given tablename returns (service, name)."""
    pieces = tablename.split(':')
    if len(pieces) == 1:
        table = pieces[0]
        service = None
    else:
        service = pieces[0]
        table = ':'.join(pieces[1:])
    return service, table


def do_OP_PICK(vm):
    """
    >>> s = [b'a', b'b', b'c', b'd', b'']
    >>> do_OP_PICK(s, require_minimal=True)
    >>> print(s)
    [b'a', b'b', b'c', b'd', b'b']
    """
    v = vm.pop_nonnegative()
    vm.append(vm[-v - 1])


@staticmethod
def sniff_video_properties(file_path):
    """
        A utility method to find a video's resolution, frame rate, codec, etc
        in case this isn't passed to us and we need to populate it here.

        """
    pass


def return_list_matching_keys(dicto, list_keys):
    """Return a list of values matching keys in a dictionary
    from a list of keys. Returns Values in the Same order as the List Keys.
    """
    results = []
    for each in list_keys:
        results.append(dicto[each])
    return results


def klassCode(node):
    """ Change klass node value to Klass() expr. """
    expr = repr(node.snippet)
    charset = repr(node.value)
    node.value = 'Klass(u%s, expression=%s)' % (charset, expr)


def do_OP_3DUP(stack):
    """
    >>> s = [1, 2, 3]
    >>> do_OP_3DUP(s)
    >>> print(s)
    [1, 2, 3, 1, 2, 3]
    """
    stack.append(stack[-3])
    stack.append(stack[-3])
    stack.append(stack[-3])


def unsubscribe():
    """Unsubscribe (and delete) this member from the mailing list."""


def p_identifier_escaped(p):
    """identifier : '`' STRING '`'"""
    p[0] = p[2]


@classmethod
def get_name(cls):
    """Return plugin's name."""
    return cls._meta_get('name')


def search_value(d, key, default=None):
    """Return a value corresponding to the specified key in the (possibly
    nested) dictionary d. If there is no item with that key, return
    default."""
    stack = [iter(d.items())]
    while stack:
        for k, v in stack[-1]:
            if isinstance(v, dict):
                stack.append(iter(v.items()))
                break
            elif k == key:
                return v
        else:
            stack.pop()
    return default


def _is_compliant_shape(a, b):
    """Compares the shapes of two arguments.

    If size of a dimensions is None, this dimension size is ignored.

    Example:

    >>> assert _is_compliant_shape((1, 2, 3), (1, 2, 3))
    >>> assert _is_compliant_shape((1, 2, 3), (1, None, 3))
    >>> assert not _is_compliant_shape((1, 2, 3), (1, 10, 3))
    >>> assert not _is_compliant_shape((1, 2), (1,))

    :return: True, if the shapes are compliant
    """
    if len(a) != len(b):
        return False
    for i in range(len(a)):
        if a[i] and b[i]:
            if a[i] != b[i]:
                return False
    return True


def get_channel(connection, queue_name):
    """ Init method to return a prepared channel for consuming
    """
    channel = connection.channel()
    channel.queue_declare(queue=queue_name, durable=True)
    channel.confirm_delivery()
    return channel


def __to_float(val, digits):
    """Convert val into float with digits decimal."""
    try:
        return round(float(val), digits)
    except (ValueError, TypeError):
        return float(0)


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


def _atomic_hotspot_ins(jobname, probename, settings):
    """
    template for atomic hotspot input file (SuperStar ins)
    :param str jobname: general format (<probe_type>.ins)
    :param str probename: probe identifier
    :param `hotspots.atomic_hotspot_calculation.AtomicHotspot.Settings`settings:
    :return: str, atomic hotspot calculation input str
    """
    ss_str = (
        """
JOBNAME {0}
PROBENAME {1}
GRID_SPACING 0.5
CALC_CONTOUR_SURFACE 0
SAVE_SUPER_SCATTERPLOT 0
RUN_TYPE SUPERSTAR
DATA_SOURCE CSD
SHELL_VALUES 0.5 0
SIGCHECK_METHOD POISSON SHELL
PROPENSITY_CORRECTION LOGP DEFAULT DEFAULT
MIN_CAVITY_VOLUME 10
CAVITY_RADIUS 10
PEAK_FITTING 0
PEAK_FITTING_NCYCLES 1
MIN_PEAK_HEIGHT 0
PEAK_FITTING_REFINE 0
MOLECULE_FILE protein.pdb
CAVITY_DETECTION 1
MIN_PSP 5
SAVE_CAVITY MESH
USE_TORSIONS 1
RMS_ACCEPT 0.1
NO_MAP_WHEN_INCOMPLETE 0
MAP_FORMAT SYBYL_ASCII_CONTOUR
FIELD_TYPE PROPENSITY
MAP_DISTRIBUTE_POINTS GAUSSIAN_SMEARING
MAX_PENETRATION 0.3
BOX_BORDER {3}
SUPERSTAR_MAP_BACKGROUND {2}
MULTIPLY_POLAR_ONLY 0
INVERSE_MAP 0
AVOID_CLOSE_GRIDPOINTS 0
MAX_NOISE_LEVEL 1
SIGNIFICANCE_LEVEL 0.001
MIN_PROPENSITY {4}
SAVE_SUPERSTAR_MAP 1
SAVE_CENTRAL_GROUPS 0
SAVE_EXCLUDED_VOLUME_MAP 0
SAVE_ACCESSIBLE_VOLUME_MAP 0
FLEXIBILITY_EXHAUSTIVE 0
FLEXIBILITY_FLAG FLAG_ENSEMBLE
SMEARING_SIGMA {5}
SMEARING_NSIGMAS 2
POLAR_POLAR_CORRECTION 1
POLAR_APOLAR_CORRECTION 1
APOLAR_APOLAR_CORRECTION 9
REMOVE_BACKBONE_CONTACTS 1
REMOVE_SUSPICIOUS_CONTACTS 0
MAX_HBOND_DISTANCE 3.1
MIN_HBOND_ANGLE 100
PROPER_HBOND_DISTANCE 2.9
PROPER_HBOND_ANGLE 140
SAVE_LIGSITE_MAP 1
MIN_PEAK_DISTANCE 1
SAVE_PEAKS 1
SAVE_PEAK_MAP 0
CALC_METAL_BONDS 1
SAVE_GOLD_FITTING_POINTS 0
GOLD_MIN_PROPENSITY 5
MAX_SCATTER_ATOMS 5000
MIN_SCATTER_DENS 1.01
SURFACE_FORMAT SYBYL_MOL2
CALC_CONNOLLY_SURFACE 0
CONTOUR_LIST 2 CYAN 4 PURPLE 8 ORANGE
COVALENT_TOLERANCE 0.4
SCORE_PACKING_SHELL 0
ATOM_SCORING SINGLE_POINT"""
        .format(jobname, probename, settings.mapbackgroundvalue, settings.
        boxborder, settings.minpropensity, settings.superstar_sigma))
    return ss_str


def parse_map(filterfun, parser):
    """Creates a new parser that passes the result of the given parser through
	the given filterfun.

	>>> list(parse_map(int, (None, "42")))
	[None, 42]

	@type filterfun: obj -> obj
	@param parser: parser
	@returns: parser
	"""
    for element in parser:
        if element is None:
            yield None
        else:
            yield filterfun(element)
            break


def objects():
    """ Iterator over the contained objects
        """


def filenum(increment: int=1):
    """Increment number in filename

    :param increment: Increment
    :type increment: int
    """
    pass


def eva_partition_at_level(dendrogram, level):
    """Return the partition of the nodes at the given level

    A dendrogram is a tree and each level is a partition of the graph nodes.
    Level 0 is the first partition, which contains the smallest communities,
    and the best is len(dendrogram) - 1.
    The higher the level is, the bigger are the communities

    Parameters
    ----------
    dendrogram : list of dict
       a list of partitions, ie dictionnaries where keys of the i+1 are the
       values of the i.
    level : int
       the level which belongs to [0..len(dendrogram)-1]

    Returns
    -------
    partition : dictionnary
       A dictionary where keys are the nodes and the values are the set it
       belongs to

    Raises
    ------
    KeyError
       If the dendrogram is not well formed or the level is too high

    See Also
    --------
    best_partition which directly combines partition_at_level and
    generate_dendrogram to obtain the partition of highest modularity

    Examples
    --------
    >>> G=nx.erdos_renyi_graph(100, 0.01)
    >>> dendrogram = generate_dendrogram(G)
    >>> for level in range(len(dendrogram) - 1) :
    >>>     print("partition at level", level, "is", eva_partition_at_level(dendrogram, level))  # NOQA
    """
    partition = dendrogram[0].copy()
    for index in range(1, level + 1):
        for node, community in partition.items():
            partition[node] = dendrogram[index][community]
    return partition


def translate(words, tab=None):
    """Enumerates a collection of words.

    Each word will be translated into a integer.
    """
    tab = tab if isinstance(tab, dict) else {}
    i = 0
    for word in words:
        if word not in tab:
            tab[word] = i
            i += 1
        yield tab[word]


@staticmethod
def ipv4_filter(value, bogon=None, **_):
    """
        IPv4 address filter:
        - check if string length is >7 (e.g. not just 4 digits and 3 dots)
        - check if not in list of bogon IP addresses
        return True if OK, False otherwise.
        """
    ip = value
    if ip.startswith(b'0'):
        return False
    for x in ip.split(b'.'):
        if int(x) > 255:
            return False
    if ip.endswith(b'.0') or ip.endswith(b'.255'):
        return False
    if bogon is not None:
        ip_bytes = ip.split(b'.')
        byte1 = int(ip_bytes[0])
        byte2 = int(ip_bytes[1])
        if ip.startswith(b'10.'):
            return False
        if ip.startswith(b'100.') and byte2 & 192 == 64:
            return False
        if ip.startswith(b'127.'):
            return False
        if ip.startswith(b'169.254.'):
            return False
        if ip.startswith(b'172.') and byte2 & 240 == 16:
            return False
        if ip.startswith(b'192.0.0.'):
            return False
        if ip.startswith(b'192.0.2.'):
            return False
        if ip.startswith(b'192.168.'):
            return False
        if ip.startswith(b'198.') and byte2 & 254 == 18:
            return False
        if ip.startswith(b'198.51.100.'):
            return False
        if ip.startswith(b'203.0.113.'):
            return False
        if byte1 & 240 == 224:
            return False
        if byte1 & 240 == 240:
            return False
    return True


def p_instelem(p):
    """instelem : INSTELEM IDENTIFIER attribute_values ENDINSTELEM"""
    attribute_dict = dict(p[3])
    p[0] = {'instelem': {p[2]: {attribute_dict['Id']: attribute_dict}}}


def t_php_VARIABLE(t):
    """\\$[A-Za-z_][\\w_]*"""
    return t


@classmethod
def from_string(cls, in_str):
    """ Initialize from string `in_str`, return as FSF object
        """
    return cls(in_str)


def bytefmt(num, fmt='{:.2f}'):
    """
        format a value of bytes to a more human readable pattern
        example: 15 * 1024 becomes 15KiB

        Args:

            num (int): bytes

            fmt (string): format

        Return: string
    """
    for unit in ['', 'Ki', 'Mi', 'Gi']:
        if num < 1024.0:
            return '{}{}B'.format(fmt, unit).format(num)
        num /= 1024.0
    return '{}GiB'.format(fmt).format(num * 1024.0)


def on_whitespace(s):
    """
        Returns tokens taking whitespace as word boundaries

        >>> on_whitespace('This is not a test.')
        ['This', 'is', 'not', 'a', 'test.']

        Args:
            s: a string

        Returns:
            list: a list of strings
    """
    return s.split()


def _load_dist_subclass(cls, *args, **kwargs):
    """
    Used for derivative implementations
    """
    subclass = None
    distro = kwargs['module'].params['distro']
    if distro is not None:
        for sc in cls.__subclasses__():
            if sc.distro is not None and sc.distro == distro:
                subclass = sc
    if subclass is None:
        subclass = cls
    return super(cls, subclass).__new__(subclass)


def _reproject(xy, crs1, crs2):
    """ Reproject a coordinate (or 2-tuple of x and y vectors) from *crs1* to
    *crs2*. """
    return crs1.transform(crs2, *xy)


@classmethod
def escape_sql(cls, sql):
    """Escapes the raw SQL"""
    return sql


def remove(label_id):
    """Removes the label with ID ``label_id``.
        If the label was successfully removed, ``True`` is returned.
        If there is no such label, ``False`` is returned.
        """


@staticmethod
def repr_key(key):
    """
        Return string representation for key/index

        """
    return key.__repr__()


def describe_import_snapshot_tasks(DryRun=None, ImportTaskIds=None,
    NextToken=None, MaxResults=None, Filters=None):
    """
    Describes your import snapshot tasks.
    See also: AWS API Documentation

    :example: response = client.describe_import_snapshot_tasks(
        DryRun=True|False,
        ImportTaskIds=[
            'string',
        ],
        NextToken='string',
        MaxResults=123,
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ]
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type ImportTaskIds: list
    :param ImportTaskIds: A list of import snapshot task IDs.
            (string) --

    :type NextToken: string
    :param NextToken: A token that indicates the next page of results.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value.

    :type Filters: list
    :param Filters: One or more filters.
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :rtype: dict
    :return: {
        'ImportSnapshotTasks': [
            {
                'ImportTaskId': 'string',
                'SnapshotTaskDetail': {
                    'DiskImageSize': 123.0,
                    'Description': 'string',
                    'Format': 'string',
                    'Url': 'string',
                    'UserBucket': {
                        'S3Bucket': 'string',
                        'S3Key': 'string'
                    },
                    'SnapshotId': 'string',
                    'Progress': 'string',
                    'StatusMessage': 'string',
                    'Status': 'string'
                },
                'Description': 'string'
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


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


def gamma_correction(arr, gamma):
    """Perform gamma correction *g* to an array *arr*, which is assumed
    to be in the range [0.0,1.0], and return the resulting array (same
    range).
    """
    return arr ** (1.0 / gamma)


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


def clear():
    """Clear the entire cache of files."""


@staticmethod
def _extract_command(slack_data, bot_id):
    """

        The Slack Real Time Messaging API is an events firehose. this parsing function
        returns None unless a message is directed at the Bot, based on its ID.

        Extracts the channel, user and command from the slack data. If the data does
        not contain a command for the bot, then "None, None, None" is returned.

        :param slack_data: The data to check
        :type slack_data: dict
        :param bot_id: ID of the bot, looks like "<@AABB1122CC>"
        :type bot_id: str
        :return: user, channel, and command
        """
    if slack_data and len(slack_data) > 0:
        if 'text' in slack_data:
            if bot_id in slack_data['text']:
                return slack_data['user'], slack_data['channel'], slack_data[
                    'text'].split(bot_id)[1].strip()
    return None, None, None


def arr_sum(array):
    """
    definition: name( array[] ) {...}
    objective : returns the sum of all elements in the given array
    """
    sum = 0
    for element in array:
        sum += element
    return sum


def _is_valid_branch_name(work_dir, version):
    """
    Returns True if the ``version`` is the name of a branch in a Git project.
    ``work_dir`` must be the working directory in a git repo.
    """
    if version is not None:
        from git import Repo
        from git.exc import GitCommandError
        repo = Repo(work_dir, search_parent_directories=True)
        try:
            return repo.git.rev_parse('--verify', 'refs/heads/%s' % version
                ) != ''
        except GitCommandError:
            return False
    return False


def int_or_str(text):
    """Helper function for argument parsing."""
    try:
        return int(text)
    except ValueError:
        return text


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 library_source(lines):
    """
    Return source code for a VisionCpp library.

    The generated code will compile a callable library method
    "natvie_expression_tree()".

    Arguments:
        lines (str[]): Program implementation.

    Returns:
        str: Source code
    """
    program_lines = ['#include <opencv2/opencv.hpp>',
        '#include <visioncpp.hpp>', '', 'extern "C" {', '',
        'int native_expression_tree() {'] + lines + ['}', '',
        '}  // extern "C"']
    return '\n'.join(program_lines) + '\n'


def boundary_line(cx, cy, co):
    """
    Check *boundary_line*.
    :raises TypeError: Parameter cx must be a real number.
    :raises TypeError: Parameter cy must be a real number.
    :raises TypeError: Parameter co must be a real number.
    """
    if not isinstance(cx, (int, float)):
        raise TypeError('\n\nParameter cx must be a real number.\n')
    if not isinstance(cy, (int, float)):
        raise TypeError('\n\nParameter cy must be a real number.\n')
    if not isinstance(co, (int, float)):
        raise TypeError('\n\nParameter co must be a real number.\n')


def critical(msg):
    """log critical message"""


def is_iterable(obj):
    """ Check if the object is iterable. """
    has_iter = hasattr(obj, '__iter__')
    has_get_item = hasattr(obj, '__getitem__')
    return has_iter or has_get_item


def createNode(node, text):
    """ Create a child text node """
    root = node
    while root.nodeType != root.DOCUMENT_NODE:
        root = root.parentNode
    node.appendChild(root.createTextNode(text))
    return node


@staticmethod
def _make_title(title, title_format):
    """Create a title/subtitle/section in the reST-format and return it as
        a string.

        Parameters
        ----------
        title : str
            The title in words
        title_format : (str, str)
            | The surrounding lines. The titel will be:
            |
            | title_format[0] * len(title)
            | title
            | title_format[1] * len(title)
        """
    out_str = ''
    if title is not None:
        title = str(title)
        out_str += '\n' + title_format[0] * len(title)
        out_str += '\n' + title
        out_str += '\n' + title_format[1] * len(title) + '\n'
    return out_str


def assigned_order_items():
    """the collection of assigned order items."""


def add(state, transition_id, newstate, transition_fn, **kw):
    """Add a transition to the FSM."""


def hrz_to_nswe(pos):
    """
    Get cardinal/ordinal azimuth direction.

    Param: pos - Object of type hrz_posn giving local position.

    Returns string giving direction.
    """
    az = pos.az % 360.0
    if az < 45 or az >= 315:
        return 'N'
    elif az >= 45 and az < 135:
        return 'E'
    elif az >= 135 and az < 225:
        return 'S'
    else:
        return 'W'


def _justify_and_indent(text, level, munge=0, width=72):
    """ indent and justify text, rejustify (munge) if specified """
    indent = ' ' * level
    if munge:
        lines = []
        line = indent
        text = text.split()
        for word in text:
            line = ' '.join([line, word])
            if len(line) > width:
                lines.append(line)
                line = indent
        else:
            lines.append(line)
        return '\n'.join(lines)
    else:
        return indent + text.strip().replace('\r\n', '\n').replace('\n',
            '\n' + indent)


def _make_dictionary(x):
    """Convert an event _dictionary to a dict"""
    d = {}
    if x:
        d.update({x[0]: x[1]})
        for t in x[2]:
            d.update({t[0]: t[1]})
    return d


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Mfgpreviewcolor` from a :code:`mfgpreviewcolor` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Mfgpreviewcolor`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


def trapezoid_midsegment(b1, b2):
    """
    definition: func(b1, b2) {...}
    objective : returns you the midsegment of a trapezoid on its two bases
                1/2 (base 1 + base 2)
    """
    midsegment = 1 / 2 * (b1 + b2)
    return midsegment


def compact(coll):
    """Returns a new list with all falsy values removed"""
    return list(filter(None, coll))


def clip_scalar(value, vmin, vmax):
    """A faster numpy.clip ON SCALARS ONLY.

    See https://github.com/numpy/numpy/issues/14281
    """
    return vmin if value < vmin else vmax if value > vmax else value


def get_consecutive_sublists_of_length(parent_list, length):
    """
    Returns all consecutive sublists of a lists of a given length.

    For example, let parent_list = [1,2,3,4,5] and length=2.
    Then the method will return

    [1,2], [2,3], [3,4], [4,5]

    :param parent_list:
    :param length:
    :return:
    """
    sublists = []
    for i in range(len(parent_list) - length + 1):
        sublists.append(parent_list[i:i + length])
    return sublists


@classmethod
def power(cls):
    """
        Return the power @f$ k @f$ of the characteristic that yields the field
        size: @f$ q = p^k @f$, where @f$ p @f$ is the field characteristic.

        @note  In the current implementation, @f$ k @f$ is always 1.
        """
    return 1


def interpolate(x, y, x1):
    """
	Returns y1 that is the interpolated y value for x1, given two lists of
	x and y values.

    Example:

    if the x values are:
	x = [13000, 13500]
    and the corresponding y values are:

	y = [2000, 25O0]
	and we want to know the interpolated y value for x = 13100:
    >>> x = [13000, 13500]
    >>> y = [2000, 2500]
    >>> x1 = 13100
    >>> interpolate(x, y, x1)
    2100.0
	"""
    for item in x:
        item = float(item)
    for item in y:
        item = float(item)
    x1 = float(x1)
    y1 = y[0] + (x1 - x[0]) / (x[1] - x[0]) * (y[1] - y[0])
    return y1


def is_fp_closed(obj):
    """
    Checks whether a given file-like object is closed.

    :param obj:
        The file-like object to check.
    """
    try:
        return obj.isclosed()
    except AttributeError:
        pass
    try:
        return obj.closed
    except AttributeError:
        pass
    try:
        return obj.fp is None
    except AttributeError:
        pass
    raise ValueError('Unable to determine whether fp is closed.')


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

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


@staticmethod
def gen_email_token_key(email_token):
    """
        生成email_token的key
        """
    raise NotImplementedError