def _is_leaf_node(merge_node):
    """
    Returns True for dicts like {'a': {}}.

    """
    return len(merge_node) == 1 and not next(iter(merge_node.values()))


def adjust_phase(data, zero_phase, first_phase=0, fixed_frequency=0):
    """
    Adjust the phase of an MRSBase object

    Parameters
    ----------
    data : MRSSpectrum
        The MRSSpectrum object to be phased
    zero_phase : scalar
        The change to the zero order phase, in radians
    first_phase : scalar, optional
        The change to the first order phase, in radians per Hz
    fixed_frequency : scalar, optional
        The frequency, in Hz, which is unchanged by the first order
        phase shift

    Returns
    -------
    out : MRSSpectrum
        A new MRSSpectrum object with adjusted phase.
    """
    return data.adjust_phase(zero_phase, first_phase, fixed_frequency)


def generate_perm_name(func):
    """Generate permission name from callback function."""
    return '.'.join((func and func.__module__ or '', func and func.__name__ or
        ''))


def find_first(ol, test_func, *args):
    """
        from elist.elist import *
        def test_func(ele,x):
            cond = (ele > x)
            return(cond)

        ol = [1,2,3,4]
        first = find_first(ol,test_func,3)
        first
        #####
        ol = [10,20,30,40]
        first = find_first(ol,test_func,3)
        first
        ####find is the same as find_first
    """
    length = ol.__len__()
    for i in range(0, length):
        cond = test_func(ol[i], *args)
        if cond:
            return {'index': i, 'value': ol[i]}
        else:
            pass
    return {'index': None, 'value': None}


def pfxlen2mask_int(pfxlen):
    """
    Converts the given prefix length to an IP mask value.

    :type  pfxlen: int
    :param pfxlen: A prefix length.
    :rtype:  long
    :return: The mask, as a long value.
    """
    return 4294967295 << 32 - int(pfxlen)


def statevector(circuit):
    """ Get the qubit statevector.

    Args:
        circuit (renom_q.QuantumCircuit):
            A class of QuantumCircuit.

    Returns:
        (array):
            A array of the qubit statevector.

    Example:
        >>> import renom_q
        >>> q = renom_q.QuantumRegister(1)
        >>> c = renom_q.ClassicalRegister(1)
        >>> qc = renom_q.QuantumCircuit(q, c)
        >>> qc.x(q[0])
        >>> renom_q.statevector(qc)
        array([0.+0.j, 1.+0.j])
    """
    return circuit.Qr.qubit


def modify_instance_fleet(ClusterId=None, InstanceFleet=None):
    """
    Modifies the target On-Demand and target Spot capacities for the instance fleet with the specified InstanceFleetID within the cluster specified using ClusterID. The call either succeeds or fails atomically.
    See also: AWS API Documentation

    :example: response = client.modify_instance_fleet(
        ClusterId='string',
        InstanceFleet={
            'InstanceFleetId': 'string',
            'TargetOnDemandCapacity': 123,
            'TargetSpotCapacity': 123
        }
    )

    :type ClusterId: string
    :param ClusterId: [REQUIRED]
            The unique identifier of the cluster.

    :type InstanceFleet: dict
    :param InstanceFleet: [REQUIRED]
            The unique identifier of the instance fleet.
            InstanceFleetId (string) -- [REQUIRED]A unique identifier for the instance fleet.
            TargetOnDemandCapacity (integer) --The target capacity of On-Demand units for the instance fleet. For more information see InstanceFleetConfig$TargetOnDemandCapacity .
            TargetSpotCapacity (integer) --The target capacity of Spot units for the instance fleet. For more information, see InstanceFleetConfig$TargetSpotCapacity .

    """
    pass


def phase_folding(t, y, yerr, period):
    """
    phase_folding() allows the phase folding (duh...) of a given data
    accordingly to a given period

    Parameters
    ----------
    t: array
        Time array
    y: array
        Measurements array
    yerr: array
        Measurement errors arrays
    period: float
        Period to fold the data

    Returns
    -------
    phase: array
        Phase
    folded_y: array
        Sorted measurments according to the phase
    folded_yerr: array
        Sorted errors according to the phase
    """
    foldtimes = t / period
    foldtimes = foldtimes % 1
    if yerr is None:
        yerr = 0 * y
    phase, folded_y, folded_yerr = zip(*sorted(zip(foldtimes, y, yerr)))
    return phase, folded_y, folded_yerr


def collection_link():
    """Link selected collections to active scene

    """
    pass


def build_option(value, label=None):
    """
    Returns value/label inputs in a dictionary for use in
    :dash:`dash_core_components.Dropdown <dash-core-components/Dropdown>`
    """
    return {'label': label or value, 'value': value}


@classmethod
def setup_file_filter(cls):
    """
            Creates a file filter based on a list of extensions set in the
            'extensions' attribute of the class using the 'description' attribute
            as the name for the filter. If the 'mimetypes' attribute is also set,
            it will also set these. If additional properties are needed, this function
            should be overriden by subclasses.
        """
    if cls.file_filter == None and cls.description != '' and cls.extensions:
        try:
            import gi
            gi.require_version('Gtk', '3.0')
            from gi.repository import Gtk
        except ImportError:
            pass
        else:
            cls.file_filter = Gtk.FileFilter()
            cls.file_filter.set_name(cls.description)
            for mtpe in cls.mimetypes:
                pass
            for expr in cls.extensions:
                cls.file_filter.add_pattern(expr)
            setattr(cls.file_filter, 'parser', cls)


def splitting(df, target):
    """ Split data into train and test date sets.
	"""
    from sklearn.model_selection import train_test_split
    return train_test_split(df, test_size=0.2, stratify=df[target],
        random_state=2019)


def cmp(a, b):
    """Compare two numbers A and B, and return 1, 0, and -1 when A > B, A = B,
    and A < B, respectively."""
    if a > b:
        return 1
    elif a < b:
        return -1
    else:
        return 0


def ask_if_route_display_wanted():
    """Return whether user wants to view each route and its stops."""
    user_says = input('Would you like to see each route that is calculated?\n')
    return user_says.lower().strip() in ('y', 'yes')


def remove_crud(string):
    """Return string without useless information.

     Return string with trailing zeros after a decimal place, trailing
     decimal points, and leading and trailing spaces removed.
     """
    if '.' in string:
        string = string.rstrip('0')
    string = string.lstrip('0 ')
    string = string.rstrip(' .')
    return string


def get_a_node(base, node_id, show_details=False):
    """Utility function that gets a Senlin node."""
    params = None
    if show_details:
        params = {'show_details': True}
    res = base.client.get_obj('nodes', node_id, params)
    return res['body']


def convert_softmax(builder, layer, input_names, output_names, keras_layer):
    """Convert a softmax layer from keras to coreml.

    Parameters
    keras_layer: layer
    ----------
        A keras layer object.

    builder: NeuralNetworkBuilder
        A neural network builder object.
    """
    input_name, output_name = input_names[0], output_names[0]
    builder.add_softmax(name=layer, input_name=input_name, output_name=
        output_name)


@classmethod
def from_image(klass, img):
    """ Class method to create new instance of own class from `img`

        Parameters
        ----------
        img : ``spatialimage`` instance
           In fact, an object with the API of ``spatialimage`` -
           specifically ``dataobj``, ``affine``, ``header`` and ``extra``.

        Returns
        -------
        cimg : ``spatialimage`` instance
           Image, of our own class
        """
    return klass(img.dataobj, img.affine, klass.header_class.from_header(
        img.header), extra=img.extra.copy())


@classmethod
def getbroker(cls, *args, **kwargs):
    """Returns broker with *args, **kwargs from registered `BrokerCls`"""
    return cls.BrokerCls(*args, **kwargs)


def render_plugins(plugins, context, placeholder, processors=None):
    """
    Renders a collection of plugins with the given context, using the appropriate processors
    for a given placeholder name, and returns a list containing a "rendered content" string
    for each plugin.

    This is the main plugin rendering utility function, use this function rather than
    Plugin.render_plugin().
    """
    out = []
    total = len(plugins)
    for index, plugin in enumerate(plugins):
        plugin._render_meta.total = total
        plugin._render_meta.index = index
        context.push()
        out.append(plugin.render_plugin(context, placeholder, processors=
            processors))
        context.pop()
    return out


def PolsAnnuity(t):
    """Number of policies: Annuity"""
    return 0


def redis_stream_id_add_one(message_id):
    """Add one to the message ID

    This is useful when we need to xrange() events exclusive of the given ID,
    rather than inclusive of the given ID (which is the sensible default).
    There is no chance of missing events with this method.
    """
    milliseconds, n = map(int, message_id.split('-'))
    return f'{milliseconds:013d}-{n + 1}'


def __remove(node, com, weight, status):
    """ Remove node from community com and modify status"""
    status.degrees[com] = status.degrees.get(com, 0.0) - status.gdegrees.get(
        node, 0.0)
    status.internals[com] = float(status.internals.get(com, 0.0) - weight -
        status.loops.get(node, 0.0))
    status.node2com[node] = -1
    if status.directed:
        status.inoutdegrees[com] = status.inoutdegrees.get(com, 0.0
            ) - status.gindegrees.get(node, 0.0) * status.goutdegrees.get(node,
            0.0)


def seconds_to_text(seconds):
    """
    convert `seconds` to a text-representation

    :param seconds: seconds to convert
    :type seconds: int

    :return: `seconds` as text-representation
    :rtype: str
    """
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    hours = str(hours) + 'h ' if hours > 0 else ''
    minutes = str(minutes) + 'm ' if minutes > 0 else ''
    seconds = str(seconds) + 's' if seconds > 0 else ''
    return hours + minutes + seconds


def readIDENT(stream):
    """
    Read a Variable-Length Identifier from given stream. Note: some of DLIS file vendor doesn't follow the standard,
    for example whitespace is included also some not of non ASCII char are included, so in case it failed to decode with
    ASCII, we will also try with CP1252.

    :type stream: FileIO or BytesIO
    :param stream: Where to read from

    :return: result
    :rtype: str
    """
    l = stream.read(1)[0]
    payload = stream.read(l)
    try:
        return payload.decode('ascii')
    except UnicodeDecodeError:
        return payload.decode('cp1252')


def _module_internal_namespace_or_emtpy_string(cls):
    """
    Best-effort method for getting the module-internal namespace in which a
    class is defined -- i.e. the namespace _inside_ the module.
    """
    try:
        qualname = cls.__qualname__
    except AttributeError:
        return ''
    return '.'.join(qualname.split('.')[:-1])


def superclass_name(instance):
    """
    Given an instance return the lowerclass name of the penultimate
    class in the hierarchy (the last is object). This is used to do
    dynamic method lookups in adaptor classes via serializer.py and
    store.py while still allowing model entities to be subclassed.
    Those subclasses must insure that their __mro__ results in
    Bag, User, Recipe or Tiddler in the penultimate slot.
    """
    return instance.__class__.mro()[-2].__name__.lower()


@staticmethod
def squash_results(responses):
    """ combines results from multiple responses into one list of results """
    results = []
    for r in responses:
        r_json = r.json()
        if 'results' in r_json.keys():
            results += r.json()['results']
    return results


def _as_view_item(obj):
    """Return None or a suitable iterable to build a _StepsView."""
    try:
        iter(obj)
        return obj
    except TypeError:
        pass
    if isinstance(obj, slice):
        return obj,


def validate_inner_strings(line_part):
    """
    Checking the line_part to be of structure "a param", 'another param', ...

    Returns the found params or None if wrong line_part
    """
    PARAMS_START = 1
    STRING_INNER = 2
    STRING_AFTER = 4
    STRING_BETWEEN = 8
    quots = '\'"'
    params = []
    wrong = None
    line_part = line_part.strip()
    if not line_part:
        return params
    check_position = 0
    state = PARAMS_START
    taken_string = ''
    string_opened = ''
    line_part_len = len(line_part)
    while True:
        if check_position == line_part_len:
            if state not in [PARAMS_START, STRING_AFTER]:
                return wrong
            return params
        check_char = usage_char = line_part[check_position]
        check_position += 1
        if (STRING_INNER == state and check_char == '\\' and check_position <
            line_part_len):
            usage_char += line_part[check_position]
            check_char = '_'
            check_position += 1
        if PARAMS_START == state:
            if check_char not in quots:
                return wrong
            string_opened = check_char
            state = STRING_INNER
            continue
        if STRING_INNER == state:
            if check_char == string_opened:
                state = STRING_AFTER
                params.append(taken_string)
                taken_string = ''
                continue
            taken_string += usage_char
            continue
        if STRING_AFTER == state:
            if check_char in ' \t':
                continue
            if check_char == ',':
                state = STRING_BETWEEN
                continue
            return wrong
        if STRING_BETWEEN == state:
            if check_char in ' \t':
                continue
            if check_char in quots:
                string_opened = check_char
                state = STRING_INNER
                continue
            return wrong


def join_title(namespace, title):
    """
    prefix a namespace to a page title
    """
    if namespace:
        return '%s:%s' % (namespace, title)
    return title


@staticmethod
def write(fileobject, content, mode='a'):
    """Write the content (str, bytes) to the given file object."""
    with open(fileobject._path, mode=mode) as f:
        f.write(content)


def register_interface(interface, omit=(), prefix=None):
    """Create a set of records based on the given interface. For each
        schema field in the interface, a record will be inserted with a
        name like `${interface.__identifier__}.${field.__name__}`, and a
        value equal to default value of that field. Any field with a name
        listed in `omit`, or with the `readonly` property set to True, will
        be ignored. Supply an alternative identifier with `prefix`.
        """


def ordinal(n):
    """
    Black magic that turns numbers into ordinal representation (1 -> 1st)
    :param n: number to be converted
    :return: string with ordinal number
    """
    return '%d%s' % (n, 'tsnrhtdd'[(n // 10 % 10 != 1) * (n % 10 < 4) * n %
        10::4])


def getnamedargs(*args, **kwargs):
    """allows you to pass a dict and named args
    so you can pass ({'a':5, 'b':3}, c=8) and get
    dict(a=5, b=3, c=8)"""
    adict = {}
    for arg in args:
        if isinstance(arg, dict):
            adict.update(arg)
    adict.update(kwargs)
    return adict


def gelqf(A=None, name=None, attr=None, out=None, **kwargs):
    """LQ factorization for general matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, we compute the LQ factorization (LAPACK *gelqf*, followed by *orglq*). *A*
    must have shape *(x, y)* with *x <= y*, and must have full rank *=x*. The LQ
    factorization consists of *L* with shape *(x, x)* and *Q* with shape *(x, y)*, so
    that:

       *A* = *L* \\* *Q*

    Here, *L* is lower triangular (upper triangle equal to zero) with nonzero diagonal,
    and *Q* is row-orthonormal, meaning that

       *Q* \\* *Q*\\ :sup:`T`

    is equal to the identity matrix of shape *(x, x)*.

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

    .. note:: The operator supports float32 and float64 data types only.

    Examples::

       Single LQ factorization
       A = [[1., 2., 3.], [4., 5., 6.]]
       Q, L = gelqf(A)
       Q = [[-0.26726124, -0.53452248, -0.80178373],
            [0.87287156, 0.21821789, -0.43643578]]
       L = [[-3.74165739, 0.],
            [-8.55235974, 1.96396101]]

       Batch LQ factorization
       A = [[[1., 2., 3.], [4., 5., 6.]],
            [[7., 8., 9.], [10., 11., 12.]]]
       Q, L = gelqf(A)
       Q = [[[-0.26726124, -0.53452248, -0.80178373],
             [0.87287156, 0.21821789, -0.43643578]],
            [[-0.50257071, -0.57436653, -0.64616234],
             [0.7620735, 0.05862104, -0.64483142]]]
       L = [[[-3.74165739, 0.],
             [-8.55235974, 1.96396101]],
            [[-13.92838828, 0.],
             [-19.09768702, 0.52758934]]]

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

    Parameters
    ----------
    A : Symbol
        Tensor of input matrices to be factorized

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

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


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

        :param SsoChangeLoginUrlDetails val:
        :rtype: EventDetails
        """
    return cls('sso_change_login_url_details', val)


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

    The ".dev0" means dirty.

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


@classmethod
def _check_compatible(cls, metadata):
    """
        check if version is compatible

        if check pass nothing happen, otherwise raise a exception
        """
    pass


def restore_attrs(wrapper):
    """
    Restore all attributes for a wrapped module to their original values
    (removing any which weren't originally set).

    """
    for key, value in wrapper._attrs_to_restore.iteritems():
        setattr(wrapper._wrapped_module, key, value)
    for setting in wrapper._delete_settings:
        try:
            delattr(wrapper._wrapped_module, setting)
        except AttributeError:
            pass


def get_file_or_default(metric_file):
    """ Returns the module name from which to extract metrics. Defaults to cohorts.metrics

    :param str metric_file:  The name of the module to extract metrics from
    :return: The name of the module where metric functions reside
    """
    return metric_file if metric_file is not None else 'cohorts.metrics'


@classmethod
def _create_pass_name(cls, passport) ->str:
    """Create passport name."""
    pass_name = '{}-{}-{} {}'.format(passport.params.year, passport.params.
        month, passport.params.day, int(passport.params.number))
    return pass_name


def PolsLiving(t):
    """Number of policies: Living benefits"""
    return 0


def check_bar_match(old_bar, new_bar):
    """Check if two bars belong in the same collection (bar chart).

    Positional arguments:
    old_bar -- a previously sorted bar dictionary.
    new_bar -- a new bar dictionary that needs to be sorted.

    """
    tests = []
    tests += new_bar['bardir'] == old_bar['bardir'],
    tests += new_bar['facecolor'] == old_bar['facecolor'],
    if new_bar['bardir'] == 'v':
        new_width = new_bar['x1'] - new_bar['x0']
        old_width = old_bar['x1'] - old_bar['x0']
        tests += new_width - old_width < 1e-06,
        tests += new_bar['y0'] == old_bar['y0'],
    elif new_bar['bardir'] == 'h':
        new_height = new_bar['y1'] - new_bar['y0']
        old_height = old_bar['y1'] - old_bar['y0']
        tests += new_height - old_height < 1e-06,
        tests += new_bar['x0'] == old_bar['x0'],
    if all(tests):
        return True
    else:
        return False


@classmethod
def all_files(cls):
    """Returns all the loaded resources without any particular order"""
    return cls._assets.all_files()


def count_to_half(array):
    """Determination of half-initial value index

    Return first index at which array values decrease below 1/2 of
    the initial initial value `array[0]`.
    """
    num = 0
    for item in array[1:]:
        if item < array[0] / 2:
            break
        else:
            num += 1
    return num


def _falling_factorial(x, n):
    """
    Return the factorial of `x` to the `n` falling.

    This is defined as:

    .. math::   x^\\underline n = (x)_n = x (x-1) \\cdots (x-n+1)

    This can more efficiently calculate ratios of factorials, since:

    n!/m! == falling_factorial(n, n-m)

    where n >= m

    skipping the factors that cancel out

    the usual factorial n! == ff(n, n)
    """
    val = 1
    for k in range(x - n + 1, x + 1):
        val *= k
    return val


def description(filename):
    """Provide a short description."""
    with open(filename) as fp:
        for lineno, line in enumerate(fp):
            if lineno < 3:
                continue
            line = line.strip()
            if len(line) > 0:
                return line


def __call__(name=None, data=None, content_type=None):
    """Look up a charset.

        If a charset cannot be determined based on the input,
        this returns `None`.

        """


@staticmethod
def get_opt(opt_name, args):
    """Return option name and value.

        :param opt_name: name of the option, e.g., "username"
        :param args: parsed arguments
        """
    return opt_name, getattr(args, 'os_%s' % opt_name, None)


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

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

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


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


def describe_elasticsearch_instance_type_limits(DomainName=None,
    InstanceType=None, ElasticsearchVersion=None):
    """
    Describe Elasticsearch Limits for a given InstanceType and ElasticsearchVersion. When modifying existing Domain, specify the ``  DomainName `` to know what Limits are supported for modifying.
    See also: AWS API Documentation

    :example: response = client.describe_elasticsearch_instance_type_limits(
        DomainName='string',
        InstanceType='m3.medium.elasticsearch'|'m3.large.elasticsearch'|'m3.xlarge.elasticsearch'|'m3.2xlarge.elasticsearch'|'m4.large.elasticsearch'|'m4.xlarge.elasticsearch'|'m4.2xlarge.elasticsearch'|'m4.4xlarge.elasticsearch'|'m4.10xlarge.elasticsearch'|'t2.micro.elasticsearch'|'t2.small.elasticsearch'|'t2.medium.elasticsearch'|'r3.large.elasticsearch'|'r3.xlarge.elasticsearch'|'r3.2xlarge.elasticsearch'|'r3.4xlarge.elasticsearch'|'r3.8xlarge.elasticsearch'|'i2.xlarge.elasticsearch'|'i2.2xlarge.elasticsearch'|'d2.xlarge.elasticsearch'|'d2.2xlarge.elasticsearch'|'d2.4xlarge.elasticsearch'|'d2.8xlarge.elasticsearch'|'c4.large.elasticsearch'|'c4.xlarge.elasticsearch'|'c4.2xlarge.elasticsearch'|'c4.4xlarge.elasticsearch'|'c4.8xlarge.elasticsearch'|'r4.large.elasticsearch'|'r4.xlarge.elasticsearch'|'r4.2xlarge.elasticsearch'|'r4.4xlarge.elasticsearch'|'r4.8xlarge.elasticsearch'|'r4.16xlarge.elasticsearch',
        ElasticsearchVersion='string'
    )

    :type DomainName: string
    :param DomainName: DomainName represents the name of the Domain that we are trying to modify. This should be present only if we are querying for Elasticsearch `` Limits `` for existing domain.

    :type InstanceType: string
    :param InstanceType: [REQUIRED]
            The instance type for an Elasticsearch cluster for which Elasticsearch `` Limits `` are needed.

    :type ElasticsearchVersion: string
    :param ElasticsearchVersion: [REQUIRED]
            Version of Elasticsearch for which `` Limits `` are needed.

    :rtype: dict
    :return: {
        'LimitsByRole': {
            'string': {
                'StorageTypes': [
                    {
                        'StorageTypeName': 'string',
                        'StorageSubTypeName': 'string',
                        'StorageTypeLimits': [
                            {
                                'LimitName': 'string',
                                'LimitValues': [
                                    'string',
                                ]
                            },
                        ]
                    },
                ],
                'InstanceLimits': {
                    'InstanceCountLimits': {
                        'MinimumInstanceCount': 123,
                        'MaximumInstanceCount': 123
                    }
                },
                'AdditionalLimits': [
                    {
                        'LimitName': 'string',
                        'LimitValues': [
                            'string',
                        ]
                    },
                ]
            }
        }
    }

    :returns:
    Data: If the given InstanceType is used as Data node
    Master: If the given InstanceType is used as Master node

    """
    pass


@staticmethod
def _from_db_object(volume, db_volume):
    """Converts a database entity to a formal object."""
    for field in volume.fields:
        setattr(volume, field, db_volume[field])
    volume.obj_reset_changes()
    return volume


@classmethod
def _to_str(cls, value):
    """Represents values either as string or None values as empty string.

        Args:
            value: a value

        """
    if value is None:
        return ''
    else:
        return str(value)


def get_errid(errobj):
    """
    fetch the YYYY:NNNN part from an errata dict object
    basically strips off the CLA/RHSA etc prefix

    parameters:
        errobj(dict): dict representing an erratum in RHN

    returns:
        string: YYYY:NNNN from an erratum
    """
    return errobj.get('advisory').split('-')[1]


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 check_str_arg(result, func, cargs):
    """
    This is for the OSRGet[Angular|Linear]Units functions, which
    require that the returned string pointer not be freed.  This
    returns both the double and string values.
    """
    dbl = result
    ptr = cargs[-1]._obj
    return dbl, ptr.value.decode()


def get_payload_command(job):
    """
    Return the full command for execuring the payload, including the sourcing of all setup files and setting of
    environment variables.

    :param job: job object
    :return: command (string)
    """
    return ''


def onlywhite(line):
    """Return true if the line does only consist of whitespace characters."""
    for c in line:
        if c is not ' ' and c is not '  ':
            return c is ' '
    return line


def isinteger(x):
    """Check if `x` is platform native integer"""
    try:
        return int(x) == x
    except (TypeError, ValueError):
        return False


def height_of_beam_after_dx(d1, d2, L12, distance):
    """
    Calculate the total widths of beam a given distance away from a collimation
    slit.

    if distance >= 0, then it's taken to be the distance after d2.
    if distance < 0, then it's taken to be the distance before d1.

    Parameters
    ----------
    d1: float
        opening of first collimation slit
    d2: float
        opening of second collimation slit
    L12: float
        distance between first and second collimation slits
    distance: float
        distance from first or last slit to a given position

    Notes
    -----
    Units - equivalent distances (inches, mm, light years)

    Returns
    -------
    (umbra, penumbra): float, float
        full width of umbra and penumbra

    """
    alpha = (d1 + d2) / 2.0 / L12
    beta = abs(d1 - d2) / 2.0 / L12
    if distance >= 0:
        return beta * distance * 2 + d2, alpha * distance * 2 + d2
    else:
        return beta * abs(distance) * 2 + d1, alpha * abs(distance) * 2 + d1


def movetopmostbookmarks(repo, oldtopmost, newtopmost):
    """Move bookmark from oldtopmost to newly created topmost

    This is arguably a feature and we may only want that for the active
    bookmark. But the behavior is kept compatible with the old version for now.
    """
    if not oldtopmost or not newtopmost:
        return
    oldbmarks = repo.nodebookmarks(oldtopmost)
    if oldbmarks:
        with repo.lock(), repo.transaction(b'histedit') as tr:
            marks = repo._bookmarks
            changes = []
            for name in oldbmarks:
                changes.append((name, newtopmost))
            marks.applychanges(repo, tr, changes)


def psi_K_Na_SO4_HMW84(T, P):
    """c-c'-a: potassium sodium sulfate [HMW84]."""
    psi = -0.01
    valid = T == 298.15
    return psi, valid


def format_commit_lines(web_url: str, repo: repo, base: int, tip: int) ->str:
    """
    Format the per-commit information for the message, including the one-line
    commit summary and a link to the diff if a web URL has been configured:
    """
    if web_url:
        rev_base_url = web_url.rstrip('/') + '/rev/'
    commit_summaries = []
    for rev in range(base, tip):
        rev_node = repo.changelog.node(rev)
        rev_ctx = repo[rev_node]
        one_liner = rev_ctx.description().split('\n')[0]
        if web_url:
            summary_url = rev_base_url + str(rev_ctx)
            summary = '* [{summary}]({url})'.format(summary=one_liner, url=
                summary_url)
        else:
            summary = '* {summary}'.format(summary=one_liner)
        commit_summaries.append(summary)
    return '\n'.join(summary for summary in commit_summaries)


def enabled():
    """Returns ``True`` if LazyImports are globally enabled"""
    import nitime.lazyimports as l
    return not l.disable_lazy_imports


@staticmethod
def item_not_in(items):
    """
        Single item is not in item sets.

        Example::

            {"item_type": "Seafood"}, "Fruit" not in ["Fruit", "Meat"]
        """
    return {'$nin': items}


def ps(data, p0=0.0, p1=0.0, inv=False):
    """
    Linear phase correction
    Parameters
    ----------
    data : ndarray
        Array of NMR data.
    p0 : float
        Zero order phase in degrees.
    p1 : float
        First order phase in degrees.
    inv : bool, optional
        True for inverse phase correction
    Returns
    -------
    ndata : ndarray
        Phased NMR data.
    """
    import numpy as np
    p0 = p0 * np.pi / 180.0
    p1 = p1 * np.pi / 180.0
    size = data.shape[-1]
    apod = np.exp(1.0j * (p0 + p1 * np.arange(size) / size)).astype(data.dtype)
    if inv:
        apod = 1 / apod
    return apod * data


def read_path_dict(dict_like, path):
    """
    Resolves an non-recursive jsonpath like string over a given dictionary

    # Arguments
    dict_like: Mapping, Lookup dictionary
    path: String, lookup path, e.g. path.to[key].foo

    # Examples
    ```python
    read_path_dict({'foo': {'bar': 42}}, 'foo.bar')
    >>> 42
    ```

    # Raises
    KeyError
    """
    path = path.replace('][', '].[')
    segments = path.split('.')
    current = dict_like
    for segment in segments:
        if segment.find('[') >= 0:
            key = segment[segment.find('[') + 1:-1]
            if key.isdigit():
                key = int(key)
            if not segment.startswith('['):
                current = current[segment[:segment.find('[')]]
            current = current[key]
        else:
            current = current[segment]
    return current


@staticmethod
def split_prefix(key, prefixs):
    """
        split key string into prefix and remainder
        for first matching prefix from a list
        """
    key_upper = key.upper()
    for prefix in prefixs:
        if key_upper.startswith(prefix):
            plen = len(prefix)
            return key_upper[:plen], key[plen:]


def e1(x):
    """
    0 = x[0] + x[1]*t
    """
    if x[1] == 0:
        raise ZeroDivisionError('No Solution')
    else:
        return -x[0] / x[1]


def supports(codec):
    """
    Return a list of strings indicating supported operations.
    """
    if hasattr(codec, 'encode') and hasattr(codec, 'decode'):
        return ['encoding', 'decoding']
    elif hasattr(codec, 'encode'):
        return ['encoding']
    elif hasattr(codec, 'decode'):
        return ['decoding']
    return codec.supports


def _format_name(address):
    """Retrieve the e-mail and optionally the name from an address.

    :arg vCalAddress address: An address object.

    :returns str: The name and optionally the e-mail address.
    """
    if not address:
        return ''
    email = address.title().split(':')[1]
    if 'cn' in address.params:
        return '{} <{}>'.format(address.params['cn'], email)
    return email


@classmethod
def dump(cls, level, action, **kwargs):
    """A method for sub-class to override.

        :param level: An integer as defined by python logging module.
        :param action: The action that triggered this dump.
        :param dict kwargs: Additional parameters such as ``phase``,
                            ``timestamp`` or ``extra``.
        :returns: None
        """
    raise NotImplementedError


def string_between(first: str, second: str, string: str):
    """
    https://stackoverflow.com/a/16835195
    """
    return string[string.find(first) + 1:string.find(second)]


def _search_doc(search_str, doc_dict):
    """Search the documentation.

    Parameters
    ----------
    search_str : string
        string to search for (str)
    doc_dict : dict
        documentation dict to search in(dict

    """
    rtn = []
    for k in list(doc_dict.keys()):
        if k.lower().find(search_str.lower()) > -1 or doc_dict[k].lower().find(
            search_str.lower()) > -1:
            rtn.append(k)
    return rtn


def reset() ->None:
    """Reset all wdom objects.

    This function clear all connections, elements, and resistered custom
    elements. This function also makes new document/application and set them.
    """
    from wdom.document import get_new_document, set_document
    from wdom.element import Element
    from wdom.server import _tornado
    from wdom.window import customElements
    set_document(get_new_document())
    _tornado.connections.clear()
    _tornado.set_application(_tornado.Application())
    Element._elements_with_id.clear()
    Element._element_buffer.clear()
    customElements.reset()


def get_nfs_domain(session, return_type=None, **kwargs):
    """
    Retrieves the NFS domain for the VPSA.

    :type session: zadarapy.session.Session
    :param session: A valid zadarapy.session.Session object.  Required.

    :type return_type: str
    :param return_type: If this is set to the string 'json', this function
        will return a JSON string.  Otherwise, it will return a Python
        dictionary.  Optional (will return a Python dictionary by default).

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    path = '/api/settings/nfs_domain.json'
    return session.get_api(path=path, return_type=return_type, **kwargs)


def setup_smtp_object(smtp, user, passwd):
    """
    Helper function.  Set up an `smtplib.SMTP` object for use with CAT-SOOP,
    enabling TLS if possible and logging in a user if information is specified.

    **Parameters**:

    * `smtp`: the `smtplib.SMTP` object to configure
    * `user`: the username to use when logging in
    * `password`: the password to use when logging in

    **Returns:** the same `smtplib.SMTP` object that was passed in, after
    configuring it.
    """
    smtp.set_debuglevel(False)
    smtp.ehlo()
    if user is not None and passwd is not None:
        if smtp.has_extn('STARTTLS'):
            smtp.starttls()
            smtp.ehlo()
        smtp.login(user, passwd)
    return smtp


@classmethod
def get_format_string(cls):
    """See RepositoryFormat.get_format_string()."""
    return b'Bazaar-NG Repository format 7'


def create_training_data(algorithm_env, n=5):
    """Samples from algorithm env and creates 4 variants per sample.

    - executable code sample (Estimator class)
    - executable code sample (Estimator instance)
    - non-executable partially randomized code
    - non-executable fully randomized code
    """
    training_data = []
    for i in range(n):
        sample_data = algorithm_env.sample_algorithm_code()
        training_data.extend([sample_data, algorithm_env.
            algorithm_obj_to_instance(sample_data)])
    return training_data


def p_track_index(t):
    """track_flag : INDEX TIMESTAMP"""
    from audiotools.toc import TOCFlag_INDEX
    from fractions import Fraction
    t[0] = TOCFlag_INDEX(Fraction(t[2], 75))


def _removeUltrashortIntervals(tier, minLength, minTimestamp):
    """
    Remove intervals that are very tiny

    Doing many small manipulations on intervals can lead to the creation
    of ultrashort intervals (e.g. 1*10^-15 seconds long).  This function
    removes such intervals.
    """
    newEntryList = []
    j = 0
    for start, stop, label in tier.entryList:
        if stop - start < minLength:
            if len(newEntryList) > 0:
                lastStart, _, lastLabel = newEntryList[j - 1]
                newEntryList[j - 1] = lastStart, stop, lastLabel
        else:
            if len(newEntryList) == 0 and start != minTimestamp:
                newEntryList.append((minTimestamp, stop, label))
            else:
                newEntryList.append((start, stop, label))
            j += 1
    j = 0
    while j < len(newEntryList) - 1:
        diff = abs(newEntryList[j][1] - newEntryList[j + 1][0])
        if diff > 0 and diff < minLength:
            newEntryList[j] = newEntryList[j][0], newEntryList[j + 1][0
                ], newEntryList[j][2]
        j += 1
    return tier.new(entryList=newEntryList)


def getCountryListing():
    """
        Return a sequence of unicode country code and country name tuples.
        """


def rnd(float, places=None):
    """Round a float to decimal places.

    float : float
        Value to round.
    places : int, default=None
        Number of decimal places to round to. None defaults to 1 decimal place if float < 100, otherwise defaults to 0 places.
    """
    if places is None:
        if float < 1:
            places = 2
        elif float < 100:
            places = 1
        else:
            places = 0
    rounded = round(float, places)
    if rounded != int(rounded):
        return rounded
    else:
        return int(rounded)


def imap_log(log_iter, action_map):
    """Create an iterator that will invoke a callback per action for each item in a
    iterable containing structured log entries

    :param log_iter: Iterator returning structured log entries
    :param action_map: Dictionary mapping action name to callback function. Log items
                       with actions not in this dictionary will be skipped.
    """
    for item in log_iter:
        if item['action'] in action_map:
            yield action_map[item['action']](item)


def yggtime_lang():
    """Plot timing statistics comparing the different languages."""
    from yggdrasil import timing
    timing.plot_scalings(compare='language')


def list_ar(archive, compression, cmd, verbosity, interactive):
    """List a AR archive."""
    opts = 't'
    if verbosity > 1:
        opts += 'v'
    return [cmd, opts, archive]


def table_of_model(cr, model):
    """Return the table for the provided model name."""
    return {'ir.actions.actions': 'ir_actions', 'ir.actions.act_url':
        'ir_act_url', 'ir.actions.act_window': 'ir_act_window',
        'ir.actions.act_window_close': 'ir_actions',
        'ir.actions.act_window.view': 'ir_act_window_view',
        'ir.actions.client': 'ir_act_client', 'ir.actions.report.xml':
        'ir_act_report_xml', 'ir.actions.report': 'ir_act_report_xml',
        'ir.actions.server': 'ir_act_server', 'ir.actions.wizard':
        'ir_act_wizard'}.get(model, model.replace('.', '_'))


def delete(project, version=None):
    """Delete the egg stored for the given project and version. If should
        also delete the project if no versions are left"""


def grant_db_access(conn, schema, table, role):
    """Gives access to database users/ groups

    Parameters
    ----------
    conn : sqlalchemy connection object
        A valid connection to a database
    schema : str
        The database schema
    table : str
        The database table
    role : str
        database role that access is granted to

    """
    grant_str = (
        """GRANT ALL ON TABLE {schema}.{table}
    TO {role} WITH GRANT OPTION;"""
        .format(schema=schema, table=table, role=role))
    conn.execute(grant_str)


def asyncreq(proxy, handler, *args):
    """Performs an asynchronous request on the given proxy object.
    Not intended to be invoked directly.

    :param proxy: the proxy on which to issue the request
    :param handler: the request handler (one of the ``HANDLE_XXX`` members of
                    ``rpyc.protocol.consts``)
    :param args: arguments to the handler

    :returns: an :class:`~rpyc.core.async_.AsyncResult` representing
              the operation
    """
    conn = object.__getattribute__(proxy, '____conn__')
    return conn.async_request(handler, proxy, *args)


def _remove_spaces_from_column_names(original):
    """Remove spaces from column names to ensure compatibility with parquet

    Parameters
    ----------
    original : dataset
       the original dataset

    Returns
    -------
    dataset
       dataset with columns renamed
    """
    for existingName in original.columns:
        newName = existingName.replace(' ', '')
        original = original.withColumnRenamed(existingName, newName)
    return original


def _unlock_imports():
    """
    Internal function, called when gevent needs to perform imports
    lazily, but does not know the state of the system. It may be impossible
    to take the import lock because there are no other running greenlets, for
    example. This causes a monkey-patched __import__ to avoid taking any locks.
    until the corresponding call to lock_imports. This should only be done for limited
    amounts of time and when the set of imports is statically known to be "safe".
    """
    global __lock_imports
    __lock_imports = False


def workflow_state():
    """The workflow state of the current object
        """


def get_downscale_phases(class_data):
    """
    Returns downscale phases [s].

    :param class_data:
        WLTP class data.
    :type class_data: dict

    :return:
        Downscale phases [s].
    :rtype: list
    """
    return class_data['downscale']['phases']


def get_full_version(main_version, post_version=None):
    """Generate a PEP440 compliant version with an optional post-release."""
    if post_version is None:
        return main_version
    else:
        return '%s.post%s' % (main_version, post_version)


def p_small_stmt(p):
    """small_stmt :   expr_stmt
                    | print_stmt
                    | break_stmt
                    | next_stmt"""
    p[0] = p[1]


@classmethod
def from_json(Edge, e):
    """
        Returns a deserialized object from a json string

        :arg t: The json string consisting of a serialized object of type "Edge"
        """
    edge = Edge(id=e.get('id'), cdate=e.get('cdate'), tcdate=e.get('tcdate'
        ), tmdate=e.get('tmdate'), ddate=e.get('ddate'), tddate=e.get(
        'tddate'), invitation=e.get('invitation'), readers=e.get('readers'),
        nonreaders=e.get('nonreaders'), writers=e.get('writers'),
        signatures=e.get('signatures'), head=e.get('head'), tail=e.get(
        'tail'), weight=e.get('weight'), label=e.get('label'))
    return edge


def update_repository_description(repositoryName=None,
    repositoryDescription=None):
    """
    Sets or changes the comment or description for a repository.
    See also: AWS API Documentation

    :example: response = client.update_repository_description(
        repositoryName='string',
        repositoryDescription='string'
    )

    :type repositoryName: string
    :param repositoryName: [REQUIRED]
            The name of the repository to set or change the comment or description for.

    :type repositoryDescription: string
    :param repositoryDescription: The new comment or description for the specified repository. Repository descriptions are limited to 1,000 characters.

    """
    pass


def chart_maker(Int, Top, start=100, outfile='chart.txt'):
    """
    Makes a chart for performing IZZI experiments. Print out the file and
    tape it to the oven.  This chart will help keep track of the different
    steps.
    Z : performed in zero field - enter the temperature XXX.0 in the sio
        formatted measurement file created by the LabView program
    I : performed in the lab field written at the top of the form
    P : a pTRM step - performed at the temperature and in the lab field.

    Parameters
    __________
    Int : list of intervals [e.g., 50,10,5]
    Top : list of upper bounds for each interval [e.g., 500, 550, 600]
    start : first temperature step, default is 100
    outfile : name of output file, default is 'chart.txt'

    Output
    _________
    creates a file with:
         file:  write down the name of the measurement file
         field:  write down the lab field for the infield steps (in uT)
         the type of step (Z: zerofield, I: infield, P: pTRM step
         temperature of the step and code for SIO-like treatment steps
             XXX.0   [zero field]
             XXX.1   [in field]
             XXX.2   [pTRM check] - done in a lab field
         date : date the step was performed
         run # : an optional run number
         zones I-III : field in the zones in the oven
         start : time the run was started
         sp :  time the setpoint was reached
         cool : time cooling started

    """
    low, k, iz = start, 0, 0
    Tzero = []
    f = open('chart.txt', 'w')
    vline = ('\t%s\n' %
        '   |      |        |         |          |       |    |      |')
    hline = (
        '______________________________________________________________________________\n'
        )
    f.write('file:_________________    field:___________uT\n\n\n')
    f.write('%s\n' %
        '               date | run# | zone I | zone II | zone III | start | sp | cool|'
        )
    f.write(hline)
    f.write('\t%s' % '   0.0')
    f.write(vline)
    f.write(hline)
    for k in range(len(Top)):
        for t in range(low, Top[k] + Int[k], Int[k]):
            if iz == 0:
                Tzero.append(t)
                f.write('%s \t %s' % ('Z', str(t) + '.' + str(iz)))
                f.write(vline)
                f.write(hline)
                if len(Tzero) > 1:
                    f.write('%s \t %s' % ('P', str(Tzero[-2]) + '.' + str(2)))
                    f.write(vline)
                    f.write(hline)
                iz = 1
                f.write('%s \t %s' % ('I', str(t) + '.' + str(iz)))
                f.write(vline)
                f.write(hline)
            elif iz == 1:
                f.write('%s \t %s' % ('I', str(t) + '.' + str(iz)))
                f.write(vline)
                f.write(hline)
                iz = 0
                f.write('%s \t %s' % ('Z', str(t) + '.' + str(iz)))
                f.write(vline)
                f.write(hline)
        try:
            low = Top[k] + Int[k + 1]
        except:
            f.close()
    print('output stored in: chart.txt')


def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None,
    HttpMethod=None):
    """
    Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
            ClientMethod.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
            default, the http method is whatever is used in the method's model.

    """
    pass


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

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

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


@staticmethod
def get_qmake_configuration(target_configuration):
    """ Return a dict of qmake configuration values for CONFIG, DEFINES,
        INCLUDEPATH, LIBS and QT.  If value names (i.e. dict keys) have either
        'Qt4' or 'Qt5' prefixes then they are specific to the corresponding
        version of Qt.  target_configuration is the target configuration.
        """
    return {'QT': 'purchasing'}


@classmethod
def from_hex(cls, hex_str):
    """Construct a PublicKey from a hexadecimal string."""
    return cls.from_bytes(bytes.fromhex(hex_str))


def parse_bool(text):
    """Parse a string to a boolean, ignoring case. "true"/"1" is True,
    "false"/"0" is False. Anything else throws an exception."""
    if text.lower() in ('true', '1'):
        return True
    elif text.lower() in ('false', '0'):
        return False
    raise Exception('Invalid boolean: %s' % text)


def setTracebackClearing(clear=True):
    """
    Enable or disable traceback clearing.
    By default, clearing is disabled and Python will indefinitely store unhandled exception stack traces.
    This function is provided since Python's default behavior can cause unexpected retention of
    large memory-consuming objects.
    """
    global clear_tracebacks
    clear_tracebacks = clear


def strip(minlink, transaction):
    """Remove storage of items starting at a linkrev.

        See the documentation in ``ifilemutation`` for more.
        """


def FindC(line):
    """ Internal function. """
    if line.slope is None:
        c = line.y
    else:
        c = line.y - line.slope * line.x
    return c


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

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


def open_exchanges(model):
    """
    Open all exchange reactions.

    Parameters
    ----------
    model : cobra.Model
        The metabolic model under investigation.

    """
    for rxn in model.exchanges:
        rxn.bounds = -1000, 1000


def get_excluded_params(schema):
    """
    Get all params excluded in this schema,
    if "only" is provided in schema instance,
    consider all not included params as excluded.
    :param schema: instance or cls schema
    :return: set of excluded params
    """
    if isinstance(schema, type):
        return set()
    exclude = set()
    only = set()
    if getattr(schema, 'exclude', ()):
        exclude = set(getattr(schema, 'exclude', ()))
    if getattr(schema, 'only', ()):
        only = set(getattr(schema, 'only', ()))
    if only:
        for field in schema._declared_fields:
            if field not in only:
                exclude.add(str(field))
    return exclude


def hastopicext(repo):
    """True if the repo use the topic extension"""
    return getattr(repo, 'hastopicext', False)


def column_fullname(column, prefix=None):
    """Get a fully qualified name for a column

    Parameters
    ----------
    column : SQLAlchemy column
        A SQLAlchemy column object to get the full name for
    prefix : str, optional
        If specified, a manual prefix to prepend to the output string. This
        will automatically be separted with a ".".

    Returns
    -------
    str
        A fully qualified column name. The exact format will vary depending on
        your SQLAlchemy metadata, but an example would be: schema.table.column

    """
    name = '%s.%s' % (column.table.fullname, column.name)
    if prefix:
        name = prefix + '.' + name
    return name


def p_expression_parentheses(p):
    """expression : LPAREN expression RPAREN"""
    p[0] = p[2]


@classmethod
def from_files(cls, filepaths):
    """
        Build object from a list of `filenames`.
        """
    new = cls()
    for filepath in filepaths:
        new.add_file(filepath)
    return new


@classmethod
def all(cls, node=None, **kwargs):
    """Retrieve all trans records (limited by pagination) as Transactions.

        Args:
            node (BaseNode): the node from which to send funds
            per_page (int, str): (opt) number of records to retrieve
            page (int, str): (opt) page number to retrieve

        Returns:
            list: containing 0 or more Transaction instances
        """
    response = node.user.client.trans.get(node.user.id, node.id, **kwargs)
    return cls.multiple_from_response(node, response['trans'])


def print_header():
    """Print pretty header of list content

    The head contains 5 columns, each column has a differnt string length.
    """
    headers = ['TASK#', 'SUMMARY', 'LIST TYPE', 'DUE TIME', 'PRIORITY']
    print()
    print('{0:<5}  {1:<60}  {2:<9}  {3:<8}  {4:<8}'.format(*headers))
    print('{0:=<5}  {1:=<60}  {2:=<9}  {3:=<8}  {4:=<8}'.format(*['', '',
        '', '', '']))


def update_failed():
    """Return if the last update failed or not."""


def fill_defaults(args, defaults_per_task):
    """
    This function fills arguments not explicitly set (left as None)
    with default values according to the chosen task.

    We can't rely on argparse to it because using subparsers with
    set_defaults and a parent parser overwrites the defaults.
    """
    task = args.task
    defaults = defaults_per_task[task]
    for arg in args.__dict__:
        if getattr(args, arg) is None and arg in defaults:
            setattr(args, arg, defaults[arg])


@staticmethod
def reg_score_function(X, y, mean, scale, shape, skewness):
    """ GAS Normal Regression Update term using gradient only - native Python function

        Parameters
        ----------
        X : float
            datapoint for the right hand side variable

        y : float
            datapoint for the time series

        mean : float
            location parameter for the Normal distribution

        scale : float
            scale parameter for the Normal distribution

        shape : float
            tail thickness parameter for the Normal distribution

        skewness : float
            skewness parameter for the Normal distribution

        Returns
        ----------
        - Score of the Normal family
        """
    return X * (y - mean)


def cross_predict_model(fitter, X, Y, plan):
    """train a model Y~X using the cross validation plan and return predictions"""
    preds = [None] * X.shape[0]
    for g in range(len(plan)):
        pi = plan[g]
        model = fitter.fit(X.iloc[pi['train']], Y.iloc[pi['train']])
        predg = model.predict(X.iloc[pi['test']])
        for i in range(len(pi['test'])):
            preds[pi['test'][i]] = predg[i]
    return preds


def identifier(frame):
    """ A string identifier from a frame

    Strings are cheaper to use as indexes into dicts than tuples or dicts
    """
    if frame is None:
        return 'None'
    else:
        return ';'.join((frame.f_code.co_name, frame.f_code.co_filename,
            str(frame.f_code.co_firstlineno)))


@classmethod
def export_to_hdf5(cls, h5_file, model, mids):
    """exports the materials in a vectorized way"""
    comments = []
    e11 = []
    e22 = []
    nu12 = []
    g12 = []
    g1z = []
    g2z = []
    rho = []
    a1 = []
    a2 = []
    tref = []
    Xt = []
    Xc = []
    Yt = []
    Yc = []
    S = []
    ge = []
    F12 = []
    strn = []
    for mid in mids:
        material = model.materials[mid]
        e11.append(material.e11)
        e22.append(material.e22)
        nu12.append(material.nu12)
        g12.append(material.g12)
        g1z.append(material.g1z)
        g2z.append(material.g2z)
        rho.append(material.rho)
        a1.append(material.a1)
        a2.append(material.a2)
        tref.append(material.tref)
        ge.append(material.ge)
        Xt.append(material.Xt)
        Xc.append(material.Xc)
        Yt.append(material.Yt)
        Yc.append(material.Yc)
        S.append(material.S)
        F12.append(material.F12)
        strn.append(material.strn)
    h5_file.create_dataset('mid', data=mids)
    h5_file.create_dataset('E11', data=e11)
    h5_file.create_dataset('E22', data=e22)
    h5_file.create_dataset('Nu12', data=nu12)
    h5_file.create_dataset('G12', data=g12)
    h5_file.create_dataset('G1z', data=g1z)
    h5_file.create_dataset('G2z', data=g2z)
    h5_file.create_dataset('A1', data=a1)
    h5_file.create_dataset('A2', data=a2)
    h5_file.create_dataset('rho', data=rho)
    h5_file.create_dataset('tref', data=tref)
    h5_file.create_dataset('ge', data=ge)
    h5_file.create_dataset('Xt', data=Xt)
    h5_file.create_dataset('Xc', data=Xc)
    h5_file.create_dataset('Yt', data=Yt)
    h5_file.create_dataset('Yc', data=Yc)
    h5_file.create_dataset('S', data=S)
    h5_file.create_dataset('F12', data=F12)
    h5_file.create_dataset('strn', data=strn)


@staticmethod
def _format_timedelta(value1, value2):
    """ Method for formatting time delta into report
        """
    return str(value2 - value1)


@classmethod
def get_parent_scope(cls):
    """
        Returns reference to parent component that contains this type definition.
        """
    return getattr(cls, '_parent_scope', None)


def get_image_field(fieldname):
    """Returns the image field"""


def embeddings2ranks(embeddings):
    """ Converts embeddings to ranks"""
    microbes = embeddings.loc[embeddings.embed_type == 'microbe']
    metabolites = embeddings.loc[embeddings.embed_type == 'metabolite']
    U = microbes.pivot(index='feature_id', columns='axis', values='values')
    V = metabolites.pivot(index='feature_id', columns='axis', values='values')
    pc_ids = sorted(list(set(U.columns) - {'bias'}))
    U['ones'] = 1
    V['ones'] = 1
    ranks = U[pc_ids + ['ones', 'bias']] @ V[pc_ids + ['bias', 'ones']].T
    ranks = ranks - ranks.mean(axis=1).values.reshape(-1, 1)
    return ranks


def message(html=False):
    """ Returns the notification message to be sent
        """


def isNan(x: float) ->bool:
    """Not a number test."""
    return x != x


@classmethod
def from_dict(cls, data):
    """Converts this from a dictionary to a object."""
    data = dict(data)
    cause = data.get('cause')
    if cause is not None:
        data['cause'] = cls.from_dict(cause)
    return cls(**data)


def avg_ttm(df, years):
    """
    Calculate multi-year averages from TTM financial data, which has 4
    data-points per year, that each covers the Trailing Twelve Months.

    This is different from using a rolling average on TTM data, which
    over-weighs the most recent quarters in the average.

    This function should only be used on DataFrames for a single stock.
    Use :obj:`~simfin.utils.apply` with this function on DataFrames for
    multiple stocks.

    :param df:
        Pandas DataFrame with TTM financial data sorted ascendingly by date.

    :param years:
        Integer for the number of years.

    :return:
        Pandas DataFrame with the averages.
    """
    df_result = df.copy()
    for i in range(1, years):
        df_result += df.shift(4 * i)
    df_result /= years
    return df_result


def get_objects():
    """
        Return objects providing data for the xml export
        """


def update_open_id_connect_provider_thumbprint(OpenIDConnectProviderArn=
    None, ThumbprintList=None):
    """
    Replaces the existing list of server certificate thumbprints associated with an OpenID Connect (OIDC) provider resource object with a new list of thumbprints.
    The list that you pass with this action completely replaces the existing list of thumbprints. (The lists are not merged.)
    Typically, you need to update a thumbprint only when the identity provider's certificate changes, which occurs rarely. However, if the provider's certificate does change, any attempt to assume an IAM role that specifies the OIDC provider as a principal fails until the certificate thumbprint is updated.
    See also: AWS API Documentation

    :example: response = client.update_open_id_connect_provider_thumbprint(
        OpenIDConnectProviderArn='string',
        ThumbprintList=[
            'string',
        ]
    )

    :type OpenIDConnectProviderArn: string
    :param OpenIDConnectProviderArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the IAM OIDC provider resource object for which you want to update the thumbprint. You can get a list of OIDC provider ARNs by using the ListOpenIDConnectProviders action.
            For more information about ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference .

    :type ThumbprintList: list
    :param ThumbprintList: [REQUIRED]
            A list of certificate thumbprints that are associated with the specified IAM OpenID Connect provider. For more information, see CreateOpenIDConnectProvider .
            (string) --Contains a thumbprint for an identity provider's server certificate.
            The identity provider's server certificate thumbprint is the hex-encoded SHA-1 hash value of the self-signed X.509 certificate used by the domain where the OpenID Connect provider makes its keys available. It is always a 40-character string.

    """
    pass


def messpy_example_path():
    """
    Returns the path to the messpy example data shipped with skultrafast.

    Returns
    -------
    str
        The full path
    """
    import skultrafast
    return skultrafast.__path__[0] + '/examples/data/messpyv1_data.npz'


def sunset_float(solar_noon_float, hour_angle_sunrise):
    """Returns Sunset as float with Solar Noon Float, solar_noon_float
    and Hour Angle Deg, hour_angle_deg"""
    sunset_float = (solar_noon_float * 1440 + hour_angle_sunrise * 4) / 1440
    return sunset_float


@staticmethod
def mm_to_pt(measure):
    """Convert millimeters to points."""
    return measure * 2.83465


@staticmethod
def _merge_addr(host1: dict, host2: dict):
    """
        Merge host1 and host2 by preferring host2
        :param host1: {
                        'mac': <mac_addr>,
                        'mac_manufacturer': tuple,
                        'ip': <ip_addr>,
                        'ip_host': list
                      }
        :param host2: //
        :return: The host1 merged with host2
        """
    if host1 is None:
        return host2
    if host2 is None:
        return host1
    host = host2.copy()
    for key, val in host2.items():
        if val is not None:
            continue
        host[key] = host1.get(key)
    ip = host.get('ip')
    ip_host = host.get('ip_host')
    mac = host.get('mac')
    mac_manufacturer = host.get('mac_manufacturer')
    if ip is not None:
        host['label'] = ip
        host['title'] = ip_host
    elif mac_manufacturer is None:
        host['label'] = mac
    else:
        host['label'] = mac_manufacturer
        host['title'] = mac
    return host


def Nu_cylinder_Fand(Re, Pr):
    """Calculates Nusselt number for crossflow across a single tube
    at a specified `Re` and `Pr`, both evaluated at the film temperature. No
    other wall correction is necessary for this formulation. Also shown in
    [2]_.

    .. math::
        Nu = (0.35 + 0.34Re^{0.5} + 0.15Re^{0.58})Pr^{0.3}

    Parameters
    ----------
    Re : float
        Reynolds number with respect to cylinder diameter, [-]
    Pr : float
        Prandtl number at film temperature, [-]

    Returns
    -------
    Nu : float
        Nusselt number with respect to cylinder diameter, [-]

    Notes
    -----
    Developed with test results for water, and Re from 1E4 to 1E5, but also
    compared with other data in the literature. Claimed validity of Re from
    1E-1 to 1E5.

    This method applies to both the laminar and turbulent regimes.

    Examples
    --------
    >>> Nu_cylinder_Fand(6071, 0.7)
    45.19984325481126

    References
    ----------
    .. [1] Fand, R. M. "Heat Transfer by Forced Convection from a Cylinder to
       Water in Crossflow." International Journal of Heat and Mass Transfer 8,
       no. 7 (July 1, 1965): 995-1010. doi:10.1016/0017-9310(65)90084-0.
    .. [2] Sanitjai, S., and R. J. Goldstein. "Forced Convection Heat Transfer
       from a Circular Cylinder in Crossflow to Air and Liquids." International
       Journal of Heat and Mass Transfer 47, no. 22 (October 2004): 4795-4805.
       doi:10.1016/j.ijheatmasstransfer.2004.05.012.
    """
    return (0.35 + 0.34 * Re ** 0.5 + 0.15 * Re ** 0.58) * Pr ** 0.3


@staticmethod
def _display_frames_error():
    """
        Display an informative error when user attempts to set frames on a
        FigureWidget

        Raises
        ------
        ValueError
            always
        """
    msg = """
Frames are not supported by the plotly.graph_objs.FigureWidget class.
Note: Frames are supported by the plotly.graph_objs.Figure class"""
    raise ValueError(msg)


@staticmethod
def default_parameters():
    """
        The default parameters

        References
        ----------
        These parameters are from:

        file: ``mcmc_fit_kmin-0.005_kmax-1.0.npz``
        directory: ``$RSD_DIR/SimCalibrations/P11HaloZeldovich/results``
        git hash: 8e1304e6
        """
    d = {}
    d['_A0_amp'] = 658.9
    d['_A0_alpha'] = 3.91
    d['_A0_beta'] = 1.917
    d['_R_amp'] = 18.95
    d['_R_alpha'] = -0.3657
    d['_R_beta'] = -0.2585
    d['_R1h_amp'] = 0.8473
    d['_R1h_alpha'] = -0.1524
    d['_R1h_beta'] = 0.7769
    return d


def f1(labels, predictions):
    """
    weighted average presicion and recall
    """
    from sklearn.metrics import f1_score
    return f1_score(labels, predictions, average='macro', pos_label=None)


def indent(block, num_spaces):
    """Indent each row of the given string block with n spaces."""
    indentation = ' ' * num_spaces
    return indentation + ('\n' + indentation).join(block.split('\n'))


def detect_trailing_columns(file, sep, heading_columns):
    """ Tests first 10 lines to see if there are empty trailing columns"""
    file.seek(0)
    return_int = float('Inf')
    for i in range(10):
        line = file.readline()
        return_int = min(return_int, len(line.replace('\n', '')) - len(line
            .replace('\n', '').strip(sep)) - heading_columns)
        if return_int == 0:
            return 0
    return return_int


def _is_legacy_ip_per_task(app):
    """
    Return whether the application is using IP-per-task on Marathon < 1.5.
    :param app: The application to check.
    :return: True if using IP per task, False otherwise.
    """
    return app.get('ipAddress') is not None


def admin_disable_user(UserPoolId=None, Username=None):
    """
    Disables the specified user as an administrator. Works on any user.
    Requires developer credentials.
    See also: AWS API Documentation

    :example: response = client.admin_disable_user(
        UserPoolId='string',
        Username='string'
    )

    :type UserPoolId: string
    :param UserPoolId: [REQUIRED]
            The user pool ID for the user pool where you want to disable the user.

    :type Username: string
    :param Username: [REQUIRED]
            The user name of the user you wish to disable.

    :rtype: dict
    :return: {}

    """
    pass


def is_state_by_state(tpm):
    """Return ``True`` if ``tpm`` is in state-by-state form, otherwise
    ``False``.
    """
    return tpm.ndim == 2 and tpm.shape[0] == tpm.shape[1]


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
        {
            "properties": {
                "text_analyzed": {
                  "type": "text",
                  "fielddata": true,
                  "index": true
                }
           }
        } """
    return {'items': mapping}


@staticmethod
def long_name_type():
    """
        Returns the long name type for this port.

        :returns: string
        """
    return 'GigabitEthernet'


def var_view(ch_trend, var, num_bar):
    """ Retorna view com a variação percentual de duas barras."""
    return '%s %s %s' % (num_bar, ch_trend, var)


def corner_list(polygon, width, height):
    """Takes a boundingBox value from Google vision's JSON output and returns
    a condensed version, in the form [x y x y x y x y], with the first x, y
    pair representing the upper left corner."""
    corners = []
    for index in [0, 1, 2, 3]:
        if 'X' in polygon[index] and 'Y' in polygon[index]:
            corners.append(int(round(polygon[index]['X'] * width)))
            corners.append(int(round(polygon[index]['Y'] * height)))
        else:
            return []
    return corners


def unescape(s):
    """ unescape html tokens.
        <p>{{ unescape(content) }}</p>
    """
    return s.replace('&', '&').replace('<', '<').replace('>', '>'
        ).replace('"', '"').replace(''', "'")


def get_plot_title(main, model, prefix=''):
    """
    Constructs a sensible plot title from the ``model``.
    """
    if main is not None:
        main = prefix
        title = model.get_title()
        if title:
            main += f': {title}'
    return main


def PolsAccHosp(t):
    """Number of policies: Accidental Hospitalization"""
    return 0


def summary_table(params, proteins):
    """
    Returns a string representing a simple summary table of
    protein classifcations.
    """
    out = ''
    counts = {}
    for seqid in proteins:
        category = proteins[seqid]['category']
        if category not in counts:
            counts[category] = 1
        else:
            counts[category] += 1
    out += '\n\n# Number of proteins in each class:\n'
    for c in counts:
        out += '# %-15s %i\n' % (c, counts[c])
    return out


def GetScaledEventPosition(event, dc, scaling):
    """
    Function that calculates the nearest point of the grid defined by scaling for the given point
    """
    pos = event.GetLogicalPosition(dc)
    if scaling:
        pos.x = round(pos.x / scaling[0]) * scaling[0]
        pos.y = round(pos.y / scaling[1]) * scaling[1]
    return pos


def in_line(xmin_line, xmax_line, ymin_line, xmin_new, xmax_new, ymax_new):
    """Heuristic for determining whether a character is in a line.

    Note:
        Currently dependent on the order in which characters are
        added. For example, a character may vertically overlap with a
        line, but adding it to the line would be out of reading order.
        This should be fixed in a future version.

    Args:
        xmin_line (:obj:`list` of :obj:`int`): Minimum x-coordinate of
            characters in the line the new character is tested against.
        xmax_line (:obj:`list` of :obj:`int`): Maximum x-coordinate of
            characters in the line the new character is tested against.
        ymin_line (int): Minimum y-coordinate of line the new character
            is tested against.
        xmin_new (int): Minimum x-coordinate of new character.
        xmax_new (int): Maximum x-coordinate of new character.
        ymax_new (int): Maximum y-coordinate of new character.

    Returns:
        bool:
            The new character vertically overlaps with the
            "average" character in the line.
    """
    xmin_avg = sum(xmin_line) / len(xmin_line)
    xmax_avg = sum(xmax_line) / len(xmax_line)
    return (xmin_avg <= xmax_new and xmax_avg >= xmin_new and ymax_new >=
        ymin_line)


def strip_blank_lines(l):
    """Remove leading and trailing blank lines from a list of lines"""
    while l and not l[0].strip():
        del l[0]
    while l and not l[-1].strip():
        del l[-1]
    return l


@classmethod
def _parameters(cls, tokens):
    """
        Extract all of the parameters from the tokens.

        :param tokens: The tokens to extract the parameters from
        :type tokens: list

        :rtype: dict
        """
    arguments = []
    options = []
    for token in tokens:
        if not token.startswith('--'):
            arguments.append(cls._parse_argument(token))
        else:
            options.append(cls._parse_option(token))
    return {'arguments': arguments, 'options': options}


def synchronized_order(img, target_img, axes=True, reference=True):
    """ Reorder reference and axes of `img` to match target_img.

    Parameters
    ----------
    img : Image
    target_img : Image
    axes : bool, optional
        If True, synchronize the order of the axes.
    reference : bool, optional
        If True, synchronize the order of the reference coordinates.

    Returns
    -------
    newimg : Image
        An Image satisfying newimg.axes == target.axes (if axes == True),
        newimg.reference == target.reference (if reference == True).

    Examples
    --------
    >>> data = np.random.standard_normal((3,4,7,5))
    >>> im = Image(data, AffineTransform.from_params('ijkl', 'xyzt', np.diag([1,2,3,4,1])))
    >>> im_scrambled = im.reordered_axes('iljk').reordered_reference('txyz')
    >>> im == im_scrambled
    False
    >>> im_unscrambled = synchronized_order(im_scrambled, im)
    >>> im == im_unscrambled
    True

    The images don't have to be the same shape

    >>> data2 = np.random.standard_normal((3,11,9,4))
    >>> im2 = Image(data, AffineTransform.from_params('ijkl', 'xyzt', np.diag([1,2,3,4,1])))
    >>> im_scrambled2 = im2.reordered_axes('iljk').reordered_reference('xtyz')
    >>> im_unscrambled2 = synchronized_order(im_scrambled2, im)
    >>> im_unscrambled2.coordmap == im.coordmap
    True

    or have the same coordmap

    >>> data3 = np.random.standard_normal((3,11,9,4))
    >>> im3 = Image(data3, AffineTransform.from_params('ijkl', 'xyzt', np.diag([1,9,3,-2,1])))
    >>> im_scrambled3 = im3.reordered_axes('iljk').reordered_reference('xtyz')
    >>> im_unscrambled3 = synchronized_order(im_scrambled3, im)
    >>> im_unscrambled3.axes == im.axes
    True
    >>> im_unscrambled3.reference == im.reference
    True
    >>> im_unscrambled4 = synchronized_order(im_scrambled3, im, axes=False)
    >>> im_unscrambled4.axes == im.axes
    False
    >>> im_unscrambled4.axes == im_scrambled3.axes
    True
    >>> im_unscrambled4.reference == im.reference
    True
    """
    target_axes = target_img.axes
    target_reference = target_img.coordmap.function_range
    if axes:
        img = img.reordered_axes(target_axes.coord_names)
    if reference:
        img = img.reordered_reference(target_reference.coord_names)
    return img


def is_deposit(url):
    """Check if it's a deposit or a record."""
    try:
        return 'deposit' in url
    except TypeError:
        return False


def dn_attribute(dn, attr):
    """Given a full DN return the value of the attribute given"""
    for rdn in dn.split(','):
        if rdn.startswith('%s=' % attr):
            return rdn.split('=', 1)[1]


def __call__(cls, *args, **kwargs):
    """
        The constructor/initializer require at least one argument since
        the first argument is the singleton key.

        If an instance was already created with the requested key, it is
        returned without being re-allocated or re-initialized.
        """
    if not args:
        raise ValueError('Instance key must be first argument in constructor')
    key = args[0]
    if key in cls._instances:
        instance = cls._instances[key]
    else:
        instance = super().__call__(*args, **kwargs)
        cls._instances[key] = instance
    return instance


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

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

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


def make_string(x):
    """
    Force object into string and raises a TypeError if object is not of a
    compatible type.
    """
    if isinstance(x, str):
        return str
    elif isinstance(x, bytes):
        return x.decode('utf8')
    else:
        cls_name = type(x).__name__
        raise TypeError(f'expect string type, got {cls_name}')


@classmethod
def handler(cls, func):
    """
        A decorator to indicate a function is usable as a handler.

        The wrapped function must return a `webob.Response` object.
        """
    func._is_xblock_handler = True
    return func


@staticmethod
def getConfig(conf, section, key):
    """
        获取指定section下面的key
        :param conf:
        :param section:
        :param key:
        :return:
        """
    return conf.get(section, key)


def request_available():
    """No-op placeholder for easy hookage"""
    pass


def select_more():
    """Select those bones connected to the initial selection

    """
    pass


@classmethod
def load(cls, file_path, unflatten=True):
    """Load the data all at once (classmethod).

        # Arguments
            file_path: Zarr file path
            unflatten: see `load_all`
        """
    with cls(file_path) as f:
        return f.load_all(unflatten=unflatten)


def get_dic(f, dataset='spectrum'):
    """
    Get a dictionary from dataset in a HDF5 File
    """
    dset = f[dataset]
    dic = {}
    for key, value in dset.attrs.items():
        if '_' in key:
            axis, subkey = key.split('_', 1)
            axis = int(axis)
            if axis not in dic:
                dic[axis] = {}
            dic[axis][subkey] = value
        else:
            dic[key] = value
    return dic


def select_linked():
    """Select all curve points linked to already selected ones

    """
    pass


def describe_source_regions(RegionName=None, MaxRecords=None, Marker=None,
    Filters=None):
    """
    Returns a list of the source AWS regions where the current AWS region can create a Read Replica or copy a DB snapshot from. This API action supports pagination.
    See also: AWS API Documentation

    Examples
    To list the AWS regions where a Read Replica can be created.
    Expected Output:

    :example: response = client.describe_source_regions(
        RegionName='string',
        MaxRecords=123,
        Marker='string',
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ]
    )

    :type RegionName: string
    :param RegionName: The source region name. For example, us-east-1 .
            Constraints:
            Must specify a valid AWS Region name.

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a pagination token called a marker is included in the response so that the remaining results can be retrieved.
            Default: 100
            Constraints: Minimum 20, maximum 100.

    :type Marker: string
    :param Marker: An optional pagination token provided by a previous DescribeSourceRegions request. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .

    :type Filters: list
    :param Filters: This parameter is not currently supported.
            (dict) --This type is not currently supported.
            Name (string) -- [REQUIRED]This parameter is not currently supported.
            Values (list) -- [REQUIRED]This parameter is not currently supported.
            (string) --

    :rtype: dict
    :return: {
        'Marker': 'string',
        'SourceRegions': [
            {
                'RegionName': 'string',
                'Endpoint': 'string',
                'Status': 'string'
            },
        ]
    }

    """
    pass


def findPolygon(in_data, in_point):
    """
    Find the polygon that a point resides in

    @param in_data: Input data containing polygons as read in by parseBasemapShape
    @param in_point: Shapely point

    @return: Index of shape in in_data that contains in_point
    """
    result_num = None
    for index, data in enumerate(in_data):
        if data['polygon'].contains(in_point):
            if result_num == None:
                result_num = index
            else:
                raise RuntimeError('Multiple polygons contains point')
    if result_num == None:
        return -1
    return result_num


@staticmethod
def __print_url_name(elem):
    """
        Print infromation from dictionary

        @param elem: url information
        @type elem: L{dict}
        @return: formated name of url
        @rtype: str
        """
    name = ''
    try:
        name = '{} ({})'.format(elem['name'], elem['code'])
    except ValueError:
        name = elem['code']
    return name


def _one_contains_other(s1, s2):
    """
    Whether one set contains the other
    """
    return min(len(s1), len(s2)) == len(s1 & s2)


@classmethod
def get(cls, method):
    """Get RPC implementation stub by `method` name.

        :param str method:
        :rtype: Local
        """
    return cls._stubs.get(method)


def convert_to_raw(string, exceptions=''):
    """
    Converts a string to its raw form, converting all backslash to double
    backslash except when the backslash escapes a character given in
    exceptions.

    :param string:     The given string that needs to be converted
    :param exceptions: A list of characters that if escaped with backslash
                       should not be converted to double backslash.
    :return:           Returns the corresponding raw string.
    """
    i = 0
    length = len(string)
    output = ''
    while i < length:
        if string[i] == '\\' and i + 1 < length and string[i + 1
            ] not in exceptions:
            output += '\\'
            if string[i + 1] == '\\':
                i += 1
        output += string[i]
        i += 1
    return output


def get_hero_name(hero_page):
    """Method that parses hero name from its responses page.
    Pages for heroes are in the form of `Hero name/Responses`. We need only the `Hero name` part for heroes.

    :param hero_page: hero's responses page as string.
    :return: Hero name as parsed
    """
    return hero_page.split('/')[0]


@staticmethod
def maximum(df):
    """Returns the maximum similarity value between to term lists"""
    return df.values.max()


def cov(m, y=None, rowvar=1, bias=0, ddof=None, weights=None, repeat_weights=0
    ):
    """
    Estimate a covariance matrix, given data.

    Covariance indicates the level to which two variables vary together.
    If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
    then the covariance matrix element :math:`C_{ij}` is the covariance of
    :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
    of :math:`x_i`.

    Parameters
    ----------
    m : array_like
        A 1-D or 2-D array containing multiple variables and observations.
        Each row of `m` represents a variable, and each column a single
        observation of all those variables. Also see `rowvar` below.
    y : array_like, optional
        An additional set of variables and observations. `y` has the same
        form as that of `m`.
    rowvar : int, optional
        If `rowvar` is non-zero (default), then each row represents a
        variable, with observations in the columns. Otherwise, the relationship
        is transposed: each column represents a variable, while the rows
        contain observations.
    bias : int, optional
        Default normalization is by ``(N - 1)``, where ``N`` is the number of
        observations given (unbiased estimate). If `bias` is 1, then
        normalization is by ``N``. These values can be overridden by using
        the keyword ``ddof`` in numpy versions >= 1.5.
    ddof : int, optional
        .. versionadded:: 1.5
        If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
        the number of observations; this overrides the value implied by
        ``bias``. The default value is ``None``.
    weights : array-like, optional
        A 1-D array of weights with a length equal to the number of
        observations.
    repeat_weights : int, optional
        The default treatment of weights in the weighted covariance is to first
        normalize them to unit sum and use the biased weighted covariance
        equation. If `repeat_weights` is 1 then the weights must represent an
        integer number of occurrences of each observation and both a biased and
        unbiased weighted covariance is defined because the total sample size
        can be determined.

    Returns
    -------
    out : ndarray
        The covariance matrix of the variables.

    See Also
    --------
    corrcoef : Normalized covariance matrix

    Examples
    --------
    Consider two variables, :math:`x_0` and :math:`x_1`, which
    correlate perfectly, but in opposite directions:

    >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
    >>> x
    array([[0, 1, 2],
           [2, 1, 0]])

    Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
    matrix shows this clearly:

    >>> np.cov(x)
    array([[ 1., -1.],
           [-1.,  1.]])

    Note that element :math:`C_{0,1}`, which shows the correlation between
    :math:`x_0` and :math:`x_1`, is negative.

    Further, note how `x` and `y` are combined:

    >>> x = [-2.1, -1,  4.3]
    >>> y = [3,  1.1,  0.12]
    >>> X = np.vstack((x,y))
    >>> print np.cov(X)
    [[ 11.71        -4.286     ]
     [ -4.286        2.14413333]]
    >>> print np.cov(x, y)
    [[ 11.71        -4.286     ]
     [ -4.286        2.14413333]]
    >>> print np.cov(x)
    11.71

    """
    import numpy as np
    if ddof is not None and ddof != int(ddof):
        raise ValueError('ddof must be integer')
    X = np.array(m, ndmin=2, dtype=float)
    if X.size == 0:
        return np.array(m)
    if X.shape[0] == 1:
        rowvar = 1
    if rowvar:
        axis = 0
        tup = slice(None), np.newaxis
    else:
        axis = 1
        tup = np.newaxis, slice(None)
    if y is not None:
        y = np.array(y, copy=False, ndmin=2, dtype=float)
        X = np.concatenate((X, y), axis)
    if ddof is None:
        if bias == 0:
            ddof = 1
        else:
            ddof = 0
    if weights is not None:
        weights = np.array(weights, dtype=float)
        weights_sum = weights.sum()
        if weights_sum <= 0:
            raise ValueError('sum of weights is non-positive')
        X -= np.average(X, axis=1 - axis, weights=weights)[tup]
        if repeat_weights:
            fact = weights_sum - ddof
        else:
            weights /= weights_sum
            fact = 1.0 - np.power(weights, 2).sum()
    else:
        weights = 1
        X -= X.mean(axis=1 - axis)[tup]
        if rowvar:
            N = X.shape[1]
        else:
            N = X.shape[0]
        fact = float(N - ddof)
    if not rowvar:
        return (np.dot(weights * X.T, X.conj()) / fact).squeeze()
    else:
        return (np.dot(weights * X, X.T.conj()) / fact).squeeze()


@staticmethod
def base_field_type():
    """Returns the class that all fields in the schema will inherit from"""
    raise NotImplementedError('Child class must implement base_field_type')


def def_archetypes():
    """
    Produces the default niche-archetype links for a rickshaw simspec.

    Returns
    ----------
    spec : dict
        Dictionary representation of the niche-archetype links.
    """
    arches = {'mine': {':cycamore:Source'}, 'conversion': {
        ':cycamore:Storage'}, 'enrichment': {':cycamore:Enrichment'},
        'fuel_fab': {':cycamore:FuelFab'}, 'fuel_fab:uo2': {
        ':cycamore:FuelFab'}, 'fuel_fab:triso': {':cycamore:FuelFab'},
        'fuel_fab:mox': {':cycamore:FuelFab'}, 'reactor': {
        ':cycamore:Reactor'}, 'reactor:fr': {':cycamore:Reactor'},
        'reactor:lwr': {':cycamore:Reactor'}, 'reactor:hwr': {
        ':cycamore:Reactor'}, 'reactor:htgr': {':cycamore:Reactor'},
        'reactor:rbmk': {':cycamore:Reactor'}, 'reactor:pb': {
        ':cycamore:Reactor'}, 'storage': {':cycamore:Storage'},
        'storage:wet': {':cycamore:Storage'}, 'storage:dry': {
        ':cycamore:Storage'}, 'storage:interim': {':cycamore:Storage'},
        'separations': {':cycamore:Separations'}, 'repository': {
        ':cycamore:Sink'}}
    return arches


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

        :param TfaAddBackupPhoneType val:
        :rtype: EventType
        """
    return cls('tfa_add_backup_phone', val)


def _demean(in_file, in_mask=None, usemode=True):
    """
    Subtract the median (since it is robuster than the mean) from a map.

    Parameters
    ----------
    usemode : bool
        Use the mode instead of the median (should be even more robust
        against outliers).

    """
    from os import getcwd
    import numpy as np
    import nibabel as nb
    from nipype.utils.filemanip import fname_presuffix
    nii = nb.load(in_file)
    data = nii.get_fdata(dtype='float32')
    msk = np.ones_like(data, dtype=bool)
    if in_mask is not None:
        msk[nb.load(in_mask).get_fdata(dtype='float32') < 0.0001] = False
    if usemode:
        from scipy.stats import mode
        data[msk] -= mode(data[msk], axis=None)[0][0]
    else:
        data[msk] -= np.median(data[msk], axis=None)
    out_file = fname_presuffix(in_file, suffix='_demean', newpath=getcwd())
    nb.Nifti1Image(data, nii.affine, nii.header).to_filename(out_file)
    return out_file


def is_network(network):
    """Validate that the argument is a |Network|."""
    from . import Network
    if not isinstance(network, Network):
        raise ValueError(
            'Input must be a Network (perhaps you passed a Subsystem instead?')


def TT(val):
    """TransliteratedTitle"""
    return val


def get_request_validators(restApiId=None, position=None, limit=None):
    """
    Gets the  RequestValidators collection of a given  RestApi .
    See also: AWS API Documentation

    :example: response = client.get_request_validators(
        restApiId='string',
        position='string',
        limit=123
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            [Required] The identifier of a RestApi to which the RequestValidators collection belongs.

    :type position: string
    :param position: The current pagination position in the paged result set.

    :type limit: integer
    :param limit: The maximum number of returned results per page.

    :rtype: dict
    :return: {
        'position': 'string',
        'items': [
            {
                'id': 'string',
                'name': 'string',
                'validateRequestBody': True|False,
                'validateRequestParameters': True|False
            },
        ]
    }

    """
    pass


def remove_duplicates(lis):
    """
    Remove duplicate entries from a given list, preserving ordering.
    """
    out_list = []
    for el in lis:
        if el not in out_list:
            out_list.append(el)
    return out_list


def posemode_toggle():
    """Enable or disable posing/selecting bones

    """
    pass


def first(nodes):
    """
    Return the first node in the given list, or None, if the list is empty.
    """
    if len(nodes) >= 1:
        return nodes[0]
    else:
        return None


def delete_login_profile(UserName=None):
    """
    Deletes the password for the specified IAM user, which terminates the user's ability to access AWS services through the AWS Management Console.
    See also: AWS API Documentation

    Examples
    The following command deletes the password for the IAM user named Bob.
    Expected Output:

    :example: response = client.delete_login_profile(
        UserName='string'
    )

    :type UserName: string
    :param UserName: [REQUIRED]
            The name of the user whose password you want to delete.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :return: response = client.delete_login_profile(
        UserName='Bob',
    )

    print(response)

    """
    pass


def trace(*args):
    """A function used instead of "print" for debugging output.
	"""
    for arg in args:
        print(arg, end=' ')
    print()


def set_center_principal():
    """Set optical center to center of footage

    """
    pass


@staticmethod
def get_table(aci_object, title=''):
    """
        Abstract method that should be replaced by a version that is specific to
        the object

        :param aci_object:
        :param title: String containing the table title
        :return: list of Table objects
        """
    return [None]


def _get_sentences_with_word_count(sentences, word_count):
    """Get list of sentences. Total number of returned words close to specified `word_count`.

    Parameters
    ----------
    sentences : list of :class:`~gensim.summarization.syntactic_unit.SyntacticUnit`
        Given sentences.
    word_count : int or None
        Number of returned words. If None full most important sentences will be returned.

    Returns
    -------
    list of :class:`~gensim.summarization.syntactic_unit.SyntacticUnit`
        Most important sentences.

    """
    length = 0
    selected_sentences = []
    for sentence in sentences:
        words_in_sentence = len(sentence.text.split())
        if abs(word_count - length - words_in_sentence) > abs(word_count -
            length):
            return selected_sentences
        selected_sentences.append(sentence)
        length += words_in_sentence
    return selected_sentences


def factor_autocorrelation(factor_data, period=1, rank=True):
    """
    计算指定时间跨度内平均因子排名/因子值的自相关性.
    该指标对于衡量因子的换手率非常有用.
    如果每个因子值在一个周期内随机变化，我们预计自相关为 0.

    参数
    ----------
    factor_data : pd.DataFrame - MultiIndex
        一个 DataFrame, index 为日期 (level 0) 和资产(level 1) 的 MultiIndex,
        values 包括因子的值, 各期因子远期收益, 因子分位数,
        因子分组(可选), 因子权重(可选)
    period: int, optional
        对应的因子远期收益时间跨度
    Returns
    -------
    autocorr : pd.Series
        滞后一期的因子自相关性
    """
    grouper = [factor_data.index.get_level_values('date')]
    if rank:
        ranks = factor_data.groupby(grouper)[['factor']].rank()
    else:
        ranks = factor_data[['factor']]
    asset_factor_rank = ranks.reset_index().pivot(index='date', columns=
        'asset', values='factor')
    autocorr = asset_factor_rank.corrwith(asset_factor_rank.shift(period),
        axis=1)
    autocorr.name = period
    return autocorr


def get_message_id(message):
    """Sanitizes the 'reply_to' parameter a user may send"""
    if message is None:
        return None
    if isinstance(message, int):
        return message
    if hasattr(message, 'original_message'):
        return message.original_message.id
    try:
        if message.SUBCLASS_OF_ID == 2030045667:
            return message.id
    except AttributeError:
        pass
    raise TypeError('Invalid message type: {}'.format(type(message)))


@staticmethod
def _filter_parameters_to_hash(parameters):
    """Produce a filtered version of `parameters` that does not include values that should be
        ignored during hashing

        Parameters
        ----------
        parameters: Dict
            The full dictionary of initial parameters to be filtered

        Returns
        -------
        parameters: Dict
            The filtered version of the given `parameters`"""
    return parameters


def is_finalized_submission(submission_data):
    """
    Helper function to determine whether or not a Submission was finalized by the student
    """
    if submission_data and submission_data.get('answer') is not None:
        return submission_data['answer'].get('finalized', True)
    return False


@staticmethod
def height_to_supply(height):
    """Gives total supply at a given block height"""
    R0 = 11680000.4
    delta = 2e-06
    pos = 0.8
    pow = 12.6
    N = height - 800000.0
    dev_rew = 1.1
    R = dev_rew * R0 + N * (pos + dev_rew * (pow - N / 2 * delta))
    return R


def xyz_rgb(xyz):
    """
	Convert tuple from the CIE XYZ color space to the sRGB color space.

	Conversion is based on that the XYZ input uses an the D65 illuminate with a 2° observer angle.
	https://en.wikipedia.org/wiki/Illuminant_D65

	sRGB (standard Red Green Blue): https://en.wikipedia.org/wiki/SRGB
	CIE XYZ: https://en.wikipedia.org/wiki/CIE_1931_color_space
	"""
    x = xyz[0] / 100.0
    y = xyz[1] / 100.0
    z = xyz[2] / 100.0
    r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314
    g = x * -0.969266 + y * 1.8760108 + z * 0.041556
    b = x * 0.0556434 + y * -0.2040259 + z * 1.0572252
    r = r * 255.0
    g = g * 255.0
    b = b * 255.0
    return round(r), round(g), round(b)


@classmethod
def _description_validator(cls, description):
    """
        Validates the description.
        """