def batch_get_item(RequestItems=None, ReturnConsumedCapacity=None):
    """
    The BatchGetItem operation returns the attributes of one or more items from one or more tables. You identify requested items by primary key.
    A single operation can retrieve up to 16 MB of data, which can contain as many as 100 items. BatchGetItem will return a partial result if the response size limit is exceeded, the table's provisioned throughput is exceeded, or an internal processing failure occurs. If a partial result is returned, the operation returns a value for UnprocessedKeys . You can use this value to retry the operation starting with the next item to get.
    For example, if you ask to retrieve 100 items, but each individual item is 300 KB in size, the system returns 52 items (so as not to exceed the 16 MB limit). It also returns an appropriate UnprocessedKeys value so you can get the next page of results. If desired, your application can include its own logic to assemble the pages of results into one data set.
    If none of the items can be processed due to insufficient provisioned throughput on all of the tables in the request, then BatchGetItem will return a ProvisionedThroughputExceededException . If at least one of the items is successfully processed, then BatchGetItem completes successfully, while returning the keys of the unread items in UnprocessedKeys .
    By default, BatchGetItem performs eventually consistent reads on every table in the request. If you want strongly consistent reads instead, you can set ConsistentRead to true for any or all tables.
    In order to minimize response latency, BatchGetItem retrieves items in parallel.
    When designing your application, keep in mind that DynamoDB does not return items in any particular order. To help parse the response by item, include the primary key values for the items in your request in the ProjectionExpression parameter.
    If a requested item does not exist, it is not returned in the result. Requests for nonexistent items consume the minimum read capacity units according to the type of read. For more information, see Capacity Units Calculations in the Amazon DynamoDB Developer Guide .
    See also: AWS API Documentation

    Examples
    This example reads multiple items from the Music table using a batch of three GetItem requests.  Only the AlbumTitle attribute is returned.
    Expected Output:

    :example: response = client.batch_get_item(
        RequestItems={
            'string': {
                'Keys': [
                    {
                        'string': {
                            'S': 'string',
                            'N': 'string',
                            'B': b'bytes',
                            'SS': [
                                'string',
                            ],
                            'NS': [
                                'string',
                            ],
                            'BS': [
                                b'bytes',
                            ],
                            'M': {
                                'string': {'... recursive ...'}
                            },
                            'L': [
                                {'... recursive ...'},
                            ],
                            'NULL': True|False,
                            'BOOL': True|False
                        }
                    },
                ],
                'AttributesToGet': [
                    'string',
                ],
                'ConsistentRead': True|False,
                'ProjectionExpression': 'string',
                'ExpressionAttributeNames': {
                    'string': 'string'
                }
            }
        },
        ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE'
    )

    :type RequestItems: dict
    :param RequestItems: [REQUIRED]
            A map of one or more table names and, for each table, a map that describes one or more items to retrieve from that table. Each table name can be used only once per BatchGetItem request.
            Each element in the map of items to retrieve consists of the following:
            ConsistentRead - If true , a strongly consistent read is used; if false (the default), an eventually consistent read is used.
            ExpressionAttributeNames - One or more substitution tokens for attribute names in the ProjectionExpression parameter. The following are some use cases for using ExpressionAttributeNames :
            To access an attribute whose name conflicts with a DynamoDB reserved word.
            To create a placeholder for repeating occurrences of an attribute name in an expression.
            To prevent special characters in an attribute name from being misinterpreted in an expression.
            Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:
            Percentile
            The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames :
            {'#P':'Percentile'}
            You could then use this substitution in an expression, as in this example:
            #P = :val
            Note
            Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime.
            For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
            Keys - An array of primary key attribute values that define specific items in the table. For each primary key, you must provide all of the key attributes. For example, with a simple primary key, you only need to provide the partition key value. For a composite key, you must provide both the partition key value and the sort key value.
            ProjectionExpression - A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. For more information, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
            AttributesToGet - This is a legacy parameter. Use ProjectionExpression instead. For more information, see AttributesToGet in the Amazon DynamoDB Developer Guide .
            (string) --
            (dict) --Represents a set of primary keys and, for each key, the attributes to retrieve from the table.
            For each primary key, you must provide all of the key attributes. For example, with a simple primary key, you only need to provide the partition key. For a composite primary key, you must provide both the partition key and the sort key.
            Keys (list) -- [REQUIRED]The primary key attribute values that define the items and the attributes associated with the items.
            (dict) --
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            S (string) --An attribute of type String. For example:
            'S': 'Hello'
            N (string) --An attribute of type Number. For example:
            'N': '123.45'
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            B (bytes) --An attribute of type Binary. For example:
            'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk'
            SS (list) --An attribute of type String Set. For example:
            'SS': ['Giraffe', 'Hippo' ,'Zebra']
            (string) --
            NS (list) --An attribute of type Number Set. For example:
            'NS': ['42.2', '-19', '7.5', '3.14']
            Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations.
            (string) --
            BS (list) --An attribute of type Binary Set. For example:
            'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k=']
            (bytes) --
            M (dict) --An attribute of type Map. For example:
            'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}}
            (string) --
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .

            L (list) --An attribute of type List. For example:
            'L': ['Cookies', 'Coffee', 3.14159]
            (dict) --Represents the data for an attribute.
            Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.
            For more information, see Data Types in the Amazon DynamoDB Developer Guide .
            NULL (boolean) --An attribute of type Null. For example:
            'NULL': true
            BOOL (boolean) --An attribute of type Boolean. For example:
            'BOOL': true

            AttributesToGet (list) --This is a legacy parameter. Use ProjectionExpression instead. For more information, see Legacy Conditional Parameters in the Amazon DynamoDB Developer Guide .
            (string) --
            ConsistentRead (boolean) --The consistency of a read operation. If set to true , then a strongly consistent read is used; otherwise, an eventually consistent read is used.
            ProjectionExpression (string) --A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the ProjectionExpression must be separated by commas.
            If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result.
            For more information, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
            ExpressionAttributeNames (dict) --One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames :
            To access an attribute whose name conflicts with a DynamoDB reserved word.
            To create a placeholder for repeating occurrences of an attribute name in an expression.
            To prevent special characters in an attribute name from being misinterpreted in an expression.
            Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:
            Percentile
            The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames :
            {'#P':'Percentile'}
            You could then use this substitution in an expression, as in this example:
            #P = :val
            Note
            Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime.
            For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide .
            (string) --
            (string) --

    :type ReturnConsumedCapacity: string
    :param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response:
            INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s).
            TOTAL - The response includes only the aggregate ConsumedCapacity for the operation.
            NONE - No ConsumedCapacity details are included in the response.

    :rtype: dict
    :return: {
        'Responses': {
            'string': [
                {
                    'string': {
                        'S': 'string',
                        'N': 'string',
                        'B': b'bytes',
                        'SS': [
                            'string',
                        ],
                        'NS': [
                            'string',
                        ],
                        'BS': [
                            b'bytes',
                        ],
                        'M': {
                            'string': {'... recursive ...'}
                        },
                        'L': [
                            {'... recursive ...'},
                        ],
                        'NULL': True|False,
                        'BOOL': True|False
                    }
                },
            ]
        },
        'UnprocessedKeys': {
            'string': {
                'Keys': [
                    {
                        'string': {
                            'S': 'string',
                            'N': 'string',
                            'B': b'bytes',
                            'SS': [
                                'string',
                            ],
                            'NS': [
                                'string',
                            ],
                            'BS': [
                                b'bytes',
                            ],
                            'M': {
                                'string': {'... recursive ...'}
                            },
                            'L': [
                                {'... recursive ...'},
                            ],
                            'NULL': True|False,
                            'BOOL': True|False
                        }
                    },
                ],
                'AttributesToGet': [
                    'string',
                ],
                'ConsistentRead': True|False,
                'ProjectionExpression': 'string',
                'ExpressionAttributeNames': {
                    'string': 'string'
                }
            }
        },
        'ConsumedCapacity': [
            {
                'TableName': 'string',
                'CapacityUnits': 123.0,
                'Table': {
                    'CapacityUnits': 123.0
                },
                'LocalSecondaryIndexes': {
                    'string': {
                        'CapacityUnits': 123.0
                    }
                },
                'GlobalSecondaryIndexes': {
                    'string': {
                        'CapacityUnits': 123.0
                    }
                }
            },
        ]
    }

    :returns:
    (string) --

    """
    pass


def read_in_file(in_file):
    """Read input file."""
    with open(in_file, 'r') as f:
        file_lines = f.read().rstrip('\r\n')
    return file_lines


def _check_expression(expr):
    """
    Make sure an expression is not an empty string

    Parameters
    ----------
    expr : object
        An object that can be converted to a string

    Raises
    ------
    ValueError
      * If expr is an empty string
    """
    if not expr:
        raise ValueError('expr cannot be an empty string')


def psi_Ba_H_Cl_PK74(T, P):
    """c-c'-a: barium hydrogen chloride [PK74]."""
    psi = 0.024
    valid = T == 298.15
    return psi, valid


def mk_part_uri(uri: str, idx: int) ->str:
    """ Appends fragment part to the uri recording index of the part
    """
    return '{}#part={:d}'.format(uri, idx)


def bytes_to_int(b: bytes) ->int:
    """Attempts to convert a bytes object of any length to an integer"""
    return int.from_bytes(b, 'little', signed=False)


def introduction(maxchars=1024, maxwords=None):
    """Get the introduction of this reference.
        """


def to3d(x):
    """Make sure point is 3D."""
    if len(x) == 2:
        x = x[0], x[1], 0.0
    return x


def convertToPlato(specificGravity: float) ->float:
    """
    Convert Specific Gravity to Plato.

    http://hbd.org/ensmingr/

    Parameters
    ----------
    specificGravity : float
        Specific gravity.

    Returns
    -------
    float
        Degress plato.
    """
    return -463.37 + 668.72 * specificGravity - 205.35 * pow(specificGravity, 2
        )


def output_ec2_vols(vols_datapoints=None, instance_id=None, output_type=None):
    """
    @type vols_datapoints: list
    @type instance_id: unicode
    @type output_type: unicode
    """
    try:
        import matplotlib.pyplot as plt
        import matplotlib.dates as mdates
    except ImportError:
        exit('matplotlib required to output graphs.')
    try:
        import numpy as np
    except ImportError:
        exit('install numpy.')
    if output_type in ('graph', None):
        num_plots = len(vols_datapoints)
        f, axarr = plt.subplots(num_plots, sharex=True, sharey=True)
        f.suptitle('Volumes for instance: {0}'.format(instance_id), fontsize=16
            )
        plt.ylabel('Bytes')
        if isinstance(axarr, np.ndarray):
            for index, vol_set in enumerate(vols_datapoints):
                read_dates = vol_set.get('read_dates')
                read_values = vol_set.get('read_values')
                write_dates = vol_set.get('write_dates')
                write_values = vol_set.get('write_values')
                axarr[index].set_title(vol_set.get('device_name'))
                axarr[index].grid(True)
                axarr[index].plot(write_dates, write_values, label='write')
                axarr[index].plot(read_dates, read_values, label='read')
                axarr[index].legend(loc='upper right', title=None, fancybox
                    =False)
            plt.subplots_adjust(bottom=0.2)
            plt.xticks(rotation=25)
            plt.xlabel('Time (UTC)')
        else:
            read_dates = vols_datapoints[0].get('read_dates')
            read_values = vols_datapoints[0].get('read_values')
            write_dates = vols_datapoints[0].get('write_dates')
            write_values = vols_datapoints[0].get('write_values')
            axarr.set_title(vols_datapoints[0].get('device_name'))
            axarr.plot(write_dates, write_values, label='write')
            axarr.plot(read_dates, read_values, label='read')
            axarr.legend(loc='upper right', title=None, fancybox=False)
            axarr.grid(True)
            plt.subplots_adjust(bottom=0.2)
            plt.xticks(rotation=25)
            plt.xlabel('Time (UTC)')
        ax = plt.gca()
        ax.set_ylim(bottom=0)
        handles, labels = ax.get_legend_handles_labels()
        ax.legend(handles, labels)
        xfmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')
        ax.xaxis.set_major_formatter(xfmt)
        plt.grid(True)
        plt.show()
        exit(0)


def parse_header_links(value):
    """
    Return a list of Dicts of parsed link headers proxies.
    i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",
    <http://.../back.jpeg>; rel=back;type="image/jpeg"

    :param value: HTTP Link header to parse
    :return: List of Dicts
    """
    links = []
    replace_chars = ' \'"'
    for val in value.split(','):
        try:
            url, params = val.split(';', 1)
        except ValueError:
            url, params = val, ''
        link = {'url': url.strip('<> \'"')}
        for param in params.split(';'):
            try:
                key, value = param.split('=')
            except ValueError:
                break
            link[key.strip(replace_chars)] = value.strip(replace_chars)
        links.append(link)
    return links


def _LDRB_register(cpu, reg_op, mem_op):
    """
        LDRB (register).

        :param reg_op: destination register.
        :param mem_op: memory.
        """
    cpu._ldr_str_register(reg_op, mem_op, ldr=True, size=8)


def calculate_sequence_distance(seq1, seq2, case_insensitive=True):
    """Calulate the number of nucleotide differences between two sequences.

    The sequences must be the same length.

    Args:
        seq1 : DNA string 1
        seq2 : DNA string 2
        case_insensitive : optional flag for case insensitive compare, defaults to True

    Returns:
        int number of differences
    """
    if case_insensitive:
        allowed_bases = frozenset(['A', 'C', 'G', 'T'])
        seq1 = seq1.upper()
        seq2 = seq2.upper()
    else:
        allowed_bases = frozenset(['A', 'C', 'G', 'T', 'a', 'c', 'g', 't'])
    mismatches = 0
    for pos in range(len(seq1)):
        base1 = seq1[pos]
        base2 = seq2[pos]
        if base1 not in allowed_bases:
            continue
        if base2 not in allowed_bases:
            continue
        if base1 != base2:
            mismatches += 1
    return mismatches


@classmethod
def unit_attname(cls, unit_str):
    """
        Retrieve the unit attribute name for the given unit string.
        For example, if the given unit string is 'metre', return 'm'.
        Raise an exception if an attribute cannot be found.
        """
    lower = unit_str.lower()
    if unit_str in cls.UNITS:
        return unit_str
    elif lower in cls.UNITS:
        return lower
    elif lower in cls.LALIAS:
        return cls.LALIAS[lower]
    else:
        raise Exception(
            'Could not find a unit keyword associated with "%s"' % unit_str)


@staticmethod
def _decode(frame, tab):
    """Decode a frame with the help of the table."""
    blocks = []
    while frame:
        length, endseq = tab[frame[0]]
        blocks.extend([frame[1:length], endseq])
        frame = frame[length:]
    if blocks and len(blocks[-1]) > 0:
        blocks[-1] = blocks[-1][:-1]
    return ''.join(blocks)


def field_on_space(function_space, arguments):
    """ Returns the corresponding argument if the supplied list of arguments
    contains a field that exists on the specified space. Otherwise
    returns None."""
    if function_space.mangled_name in arguments.unique_fs_names:
        for arg in arguments.args:
            if (arg.type == 'gh_field' and arg.function_space.orig_name ==
                function_space.orig_name):
                return arg
    return None


def export_net_json(net, net_type, indent='no-indent'):
    """ export json string of dat """
    import json
    from copy import deepcopy
    if net_type == 'dat':
        exp_dict = deepcopy(net.dat)
        if type(exp_dict['mat']) is not list:
            exp_dict['mat'] = exp_dict['mat'].tolist()
            if 'mat_orig' in exp_dict:
                exp_dict['mat_orig'] = exp_dict['mat_orig'].tolist()
    elif net_type == 'viz':
        exp_dict = net.viz
    elif net_type == 'sim_row':
        exp_dict = net.sim['row']
    elif net_type == 'sim_col':
        exp_dict = net.sim['col']
    if indent == 'indent':
        exp_json = json.dumps(exp_dict, indent=2)
    else:
        exp_json = json.dumps(exp_dict)
    return exp_json


def _pruneLookups(table, deadLookups):
    """Go through the lookup list and remove the lookups that are in the
    deadLookups set. Return a dictionary that maps the old lookup indices to
    the new, for remapping the lookup indices used in features and in other
    lookups."""
    lookupsToDelete = []
    indicesBefore = list(range(len(table.LookupList.Lookup)))
    for lookupIndex, lookup in enumerate(table.LookupList.Lookup):
        subTablesToDelete = []
        for subTableIndex, subTable in enumerate(lookup.SubTable):
            actualSubTable = subTable
            if subTable.__class__.__name__ in ['ExtensionSubst', 'ExtensionPos'
                ]:
                actualSubTable = subTable.ExtSubTable
            if actualSubTable in deadLookups:
                subTablesToDelete.append(subTableIndex)
        for subTableIndex in reversed(subTablesToDelete):
            del lookup.SubTable[subTableIndex]
        lookup.SubTableCount = len(lookup.SubTable)
        if not lookup.SubTable:
            lookupsToDelete.append(lookupIndex)
    for i in reversed(lookupsToDelete):
        del indicesBefore[i]
        del table.LookupList.Lookup[i]
    table.LookupList.LookupCount = len(table.LookupList.Lookup)
    indicesAfter = range(len(indicesBefore))
    lookupRemap = dict(zip(indicesBefore, indicesAfter))
    return lookupRemap


def mel_to_hertz(mel):
    """Returns frequency from mel-frequency input.
    Parameter
    ---------
    mel : scalar or ndarray
        Mel-frequency value or ndarray in Mel
    Returns
    -------
    freq : scalar or ndarray
        Frequency value or array in Hz.
    """
    return 250.0 * 9 ** (mel / 3340.0) - 250.0


def barycentric_transform(point: 'mathutils.Vector', tri_a1:
    'mathutils.Vector', tri_a2: 'mathutils.Vector', tri_a3:
    'mathutils.Vector', tri_b1, tri_b2, tri_b3):
    """Return a transformed point, the transformation is defined by 2 triangles.

    :param point: The point to transform.
    :type point: 'mathutils.Vector'
    :param tri_a1: source triangle vertex.
    :type tri_a1: 'mathutils.Vector'
    :param tri_a2: source triangle vertex.
    :type tri_a2: 'mathutils.Vector'
    :param tri_a3: source triangle vertex.
    :type tri_a3: 'mathutils.Vector'
    :param tri_a1: target triangle vertex.
    :param tri_a2: target triangle vertex.
    :param tri_a3: target triangle vertex.
    :return:  The transformed point
    """
    pass


def EventletWSGIServer(app, sock=None, host=None, port=None, max_size=None,
    **kwargs):
    """A wrapper of eventlet.wsgi.server()."""
    from eventlet import listen, wsgi
    if not sock:
        sock = listen((host, port))
    wsgi.server(sock, app, max_size=max_size, **kwargs)


def make_interaction_map(name, list, interaction):
    """ Print out an interaction map named 'name' of the groups in 'list'
    based on the function 'interaction' """
    if len(list) == 0:
        return ''
    if len(list) > 10:
        res = 'Condensed form:\n'
        for i in range(len(list)):
            for j in range(i, len(list)):
                if interaction(list[i], list[j]):
                    res += 'Coupling: %9s - %9s\n' % (list[i].label, list[j
                        ].label)
        return res
    res = '%s\n%12s' % (name, '')
    for g in list:
        res += '%9s | ' % g.label
    for g1 in list:
        res += '\n%-12s' % g1.label
        for g2 in list:
            tag = ''
            if interaction(g1, g2):
                tag = '    X     '
            res += '%10s| ' % tag
    return res


def _add(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Adds arguments element-wise.

    The storage type of ``elemwise_add`` output depends on storage types of inputs

       - elemwise_add(row_sparse, row_sparse) = row_sparse
       - elemwise_add(csr, csr) = csr
       - elemwise_add(default, csr) = default
       - elemwise_add(csr, default) = default
       - elemwise_add(default, rsp) = default
       - elemwise_add(rsp, default) = default
       - otherwise, ``elemwise_add`` generates output with default storage

    Parameters
    ----------
    lhs : NDArray
        first input
    rhs : NDArray
        second input

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

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


@staticmethod
def _get_loaded_field_cb(target, model, fields):
    """
        Callback used by get_deferred_field_names().
        """
    target[model] = fields


@classmethod
def all(cls):
    """
        Wrapper around _all() to cache and return all results of something

        >>> ec2.instances.all()
        [ ... ]
        """
    if not hasattr(cls, '_cache'):
        cls._cache = cls._all()
    return cls._cache


def to_list_name(name):
    """Return a splited name by `_`.

    :param name: name of the product.
    :type name: str.
    """
    return name.split('_')


def ft_chunk(data, i, cols, rel=0, *args, **kwargs):
    """Generates a context feature based on chunk annotation in column
    `chunktag`.

    :param data: data
    :type: np.recarray
    :param i: focus position
    :type i: int
    :param cols: column map
    :type cols: dict
    :param rel: relative position of context features
    :type rel: int
    :return: feature
    :rtype: str
    """
    if 0 <= i + rel < len(data):
        chunktag = data[i + rel][cols['chunktag']]
    else:
        chunktag = None
    return 'ch[%s]=%s' % (rel, chunktag)


@classmethod
def restore(cls, data):
    """
        cannot restore here because we don't know what type of enum it is
        """
    raise NotImplementedError


def __init__(cls, name, base, attr):
    """ Defining Your Own Rules  """
    if cls.__name__[0].isupper():
        """ Create class only if First Letter is Capital    """
        for k, v in attr.items():
            if hasattr(v, '__call__'):
                if v.__name__[0] == '_' or v.__name__[0].islower():
                    """  check name function starts with _ or lower case  """
                    if v.__doc__ is None:
                        """  Check is User has provided Documentation """
                        raise ValueError(
                            'Make sure to Provide Documentation check {}'.
                            format(v.__name__))
                    else:
                        """ if function has Doccumentation pass """
                        pass
                else:
                    """ function name starts with upper case throw error  """
                    raise ValueError(
                        'Function should start with Lower case :{}'.format(
                        v.__name__))
    else:
        raise ValueError('Class Name  should start with Capital Letter :{} '
            .format(cls.__name__[0]))


def write(field, fieldName, fieldType, elementName='field'):
    """Create and return a new node representing the given field
        """


def height_from_height_fingertip(segment_length):
    """
    Calculates body height based on the height of the fingertips from the ground

    args:
        segment_length (float): height of the fingertips

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


def set_identity_pool_configuration(IdentityPoolId=None, PushSync=None,
    CognitoStreams=None):
    """
    Sets the necessary configuration for push sync.
    This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
    See also: AWS API Documentation

    :example: response = client.set_identity_pool_configuration(
        IdentityPoolId='string',
        PushSync={
            'ApplicationArns': [
                'string',
            ],
            'RoleArn': 'string'
        },
        CognitoStreams={
            'StreamName': 'string',
            'RoleArn': 'string',
            'StreamingStatus': 'ENABLED'|'DISABLED'
        }
    )

    :type IdentityPoolId: string
    :param IdentityPoolId: [REQUIRED]
            A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. This is the ID of the pool to modify.

    :type PushSync: dict
    :param PushSync: Options to apply to this identity pool for push synchronization.
            ApplicationArns (list) --List of SNS platform application ARNs that could be used by clients.
            (string) --
            RoleArn (string) --A role configured to allow Cognito to call SNS on behalf of the developer.

    :type CognitoStreams: dict
    :param CognitoStreams: Options to apply to this identity pool for Amazon Cognito streams.
            StreamName (string) -- The name of the Cognito stream to receive updates. This stream must be in the developers account and in the same region as the identity pool.
            RoleArn (string) -- The ARN of the role Amazon Cognito can assume in order to publish to the stream. This role must grant access to Amazon Cognito (cognito-sync) to invoke PutRecord on your Cognito stream.
            StreamingStatus (string) -- Status of the Cognito streams. Valid values are:ENABLED - Streaming of updates to identity pool is enabled.
            DISABLED - Streaming of updates to identity pool is disabled. Bulk publish will also fail if StreamingStatus is DISABLED.

    :rtype: dict
    :return: {
        'IdentityPoolId': 'string',
        'PushSync': {
            'ApplicationArns': [
                'string',
            ],
            'RoleArn': 'string'
        },
        'CognitoStreams': {
            'StreamName': 'string',
            'RoleArn': 'string',
            'StreamingStatus': 'ENABLED'|'DISABLED'
        }
    }

    :returns:
    (string) --

    """
    pass


@classmethod
def _meta_set(cls, key, value):
    """Set value for key in meta."""
    cls._meta_is_inited()
    cls._meta[key] = value


@classmethod
def make_request(cls, data=None):
    """
        Generates a request for RequestTransferExit

        :param data: Additional optional data to send to the server
        :type data: bytes

        :raises ValueError: If parameters are out of range, missing or wrong type
        """
    from udsoncan import Request, MemoryLocation
    if data is not None and not isinstance(data, bytes):
        raise ValueError('data must be a bytes object')
    request = Request(service=cls, data=data)
    return request


def lastindex(lst, which):
    """Finds the last occurrence of `which` in the list.

    If `which` is not in the list, raise an ValueError.

    """
    lst.reverse()
    try:
        return len(lst) - lst.index(which) - 1
    finally:
        lst.reverse()


def _find_human_readable_labels(synsets, synset_to_human):
    """Build a list of human-readable labels.

  Args:
    synsets: list of strings; each string is a unique WordNet ID.
    synset_to_human: dict of synset to human labels, e.g.,
      'n02119022' --> 'red fox, Vulpes vulpes'

  Returns:
    List of human-readable strings corresponding to each synset.
  """
    humans = []
    for s in synsets:
        assert s in synset_to_human, 'Failed to find: %s' % s
        humans.append(synset_to_human[s])
    return humans


def fromutc(dt):
    """Return an equivalent datetime in self's local time."""


def load_config(nbapp):
    """Load the JupyterLab configuration and defaults for a given application.
    """
    from jupyterlab_server import LabConfig
    from .commands import get_app_dir, get_app_info, get_workspaces_dir, get_user_settings_dir, pjoin, AppOptions
    app_dir = getattr(nbapp, 'app_dir', get_app_dir())
    info = get_app_info(app_options=AppOptions(app_dir=app_dir))
    static_url = info['staticUrl']
    user_settings_dir = getattr(nbapp, 'user_settings_dir',
        get_user_settings_dir())
    workspaces_dir = getattr(nbapp, 'workspaces_dir', get_workspaces_dir())
    config = LabConfig()
    config.app_dir = app_dir
    config.app_name = 'JupyterLab'
    config.app_namespace = 'jupyterlab'
    config.app_settings_dir = pjoin(app_dir, 'settings')
    config.app_version = info['version']
    config.cache_files = True
    config.schemas_dir = pjoin(app_dir, 'schemas')
    config.listings_dir = pjoin(app_dir, 'listings')
    config.templates_dir = pjoin(app_dir, 'static')
    config.themes_dir = pjoin(app_dir, 'themes')
    config.user_settings_dir = user_settings_dir
    config.workspaces_dir = workspaces_dir
    if getattr(nbapp, 'override_static_url', ''):
        static_url = nbapp.override_static_url
    if getattr(nbapp, 'override_theme_url', ''):
        config.themes_url = nbapp.override_theme_url
        config.themes_dir = ''
    if static_url:
        config.static_url = static_url
    else:
        config.static_dir = pjoin(app_dir, 'static')
    return config


@classmethod
def get(cls, size=32, depth=1, clean=True):
    """Return a randomly generated expression
        @size: (optional) Operation size
        @depth: (optional) Expression depth
        @clean: (optional) Clean expression cache between two calls
        """
    if clean:
        cls.generated_elements = {}
    got = cls._gen(size=size, depth=depth)
    if clean:
        cls.generated_elements = {}
    return got


def _gen_dyn_name(pkg, base_type):
    """
    Modify pkg/base_type name so that it can safely co-exist with
    statically generated files.

    :returns: name to use for pkg/base_type for dynamically generated message class.
    @rtype: str
    """
    return '_%s__%s' % (pkg, base_type)


def timetostr(dtime):
    """
    Convert datetime into a string
    """
    return dtime.strftime('%Y-%m-%dT%H:%M:%S.%fZ')


def remove_item(item):
    """Remove from the list or database the item desired."""


def get_container_status(pod, name):
    """Get the status of container ``name`` from a pod"""
    for cs in pod['status'].get('containerStatuses', ()):
        if cs['name'] == name:
            return cs
    return None


def _create_affinity_mask(mask_or_list):
    """converts a list of cores to a mask if necessary"""
    if isinstance(mask_or_list, int):
        return mask_or_list
    cores = mask_or_list
    mask = 0
    for core in cores:
        mask |= 1 << core
    return mask


def ensure_evidence(badge_data: dict) ->dict:
    """Given badge_data, ensure 'evidence' key exists with list value"""
    if 'evidence' not in badge_data:
        badge_data['evidence'] = [{}]
    return badge_data


def _split_section_and_key(key):
    """Return a tuple with config section and key."""
    parts = key.split('.')
    if len(parts) > 1:
        return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:])
    return 'renku', key


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


@classmethod
def create(cls, name, defn, state=None):
    """
        Create a new program object
        """
    prog = cls(name, False)
    prog.raw_data.update(defn)
    prog.state.update(state or {})
    prog.mk_data()
    return prog


def search_menu():
    """Pop-up a search menu over all available operators in current context

    """
    pass


def _represent_numpy_int(dumper, npint: 'numpy.int_') ->str:
    """
    Convert the passed Numpy integer into a YAML-formatted string.

    Specifically, this function returns a stringified YAML integer equivalent
    to the passed integer.

    Parameters
    ----------
    dumper: yaml.Dumper
        Object converting arbitrary Python objects to YAML-formatted strings.
    npint: numpy.ndarray
        Numpy integer to be converted into a YAML-formatted string.

    Returns
    ----------
    str
        YAML-formatted string representing this Numpy integer.
    """
    return dumper.represent_int(int(npint))


def __call__(cls, *args, **kwds):
    """Instantiate cls after preprocessing its token definitions."""
    if '_tokens' not in cls.__dict__:
        cls._all_tokens = {}
        cls._tmpname = 0
        if hasattr(cls, 'token_variants') and cls.token_variants:
            pass
        else:
            cls._tokens = cls.process_tokendef('', cls.get_tokendefs())
    return type.__call__(cls, *args, **kwds)


def convert_by_vocab(vocab, items):
    """Converts a sequence of [tokens|ids] using the vocab."""
    output = []
    for item in items:
        output.append(vocab[item])
    return output


def gen_open_files(filepaths):
    """
    Open a sequence of filenames one at a time producing a file object.
    The file is closed immediately when proceeding to the next iteration.
    :param filenames: List of filepaths to open
    :return: Generator of opened files

    Example:
        files = gen_opener(filenames)
    """
    for filepath in filepaths:
        f = open(filepath, 'rt')
        yield f
        f.close()


def unquote(s):
    """
    Undo the effects of quote(). Based heavily on urllib.unquote().
    """
    mychr = chr
    myatoi = int
    list = s.split('_')
    res = [list[0]]
    myappend = res.append
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                myappend(mychr(myatoi(item[:2], 16)) + item[2:])
            except ValueError:
                myappend('_' + item)
        else:
            myappend('_' + item)
    return ''.join(res)


def kindAsBreatheDirective(kind):
    """
    Returns the appropriate breathe restructured text directive for the specified kind.
    The output for a given kind is as follows:

    +-------------+--------------------+
    | Input Kind  | Output Directive   |
    +=============+====================+
    | "class"     | "doxygenclass"     |
    +-------------+--------------------+
    | "define"    | "doxygendefine"    |
    +-------------+--------------------+
    | "enum"      | "doxygenenum"      |
    +-------------+--------------------+
    | "enumvalue" | "doxygenenumvalue" |
    +-------------+--------------------+
    | "file"      | "doxygenfile"      |
    +-------------+--------------------+
    | "function"  | "doxygenfunction"  |
    +-------------+--------------------+
    | "group"     | "doxygengroup"     |
    +-------------+--------------------+
    | "namespace" | "doxygennamespace" |
    +-------------+--------------------+
    | "struct"    | "doxygenstruct"    |
    +-------------+--------------------+
    | "typedef"   | "doxygentypedef"   |
    +-------------+--------------------+
    | "union"     | "doxygenunion"     |
    +-------------+--------------------+
    | "variable"  | "doxygenvariable"  |
    +-------------+--------------------+

    The following breathe kinds are ignored:

    - "autodoxygenfile"
    - "doxygenindex"
    - "autodoxygenindex"

    Note also that although a return value is generated, neither "enumvalue" nor
    "group" are actually used.

    :Parameters:
        ``kind`` (str)
            The kind of the breathe compound / ExhaleNode object (same values).

    :Return (str):
        The directive to be used for the given ``kind``.  The empty string is returned
        for both unrecognized and ignored input values.
    """
    return 'doxygen{kind}'.format(kind=kind)


def chained_get(container, path, default=None):
    """Helper function to perform a series of .get() methods on a dictionary
    and return a default object type in the end.

    Parameters
    ----------
    container : dict
        The dictionary on which the .get() methods should be performed.

    path : list or tuple
        The list of keys that should be searched for.

    default : any (optional, default=None)
        The object type that should be returned if the search yields
        no result.
    """
    for key in path:
        try:
            container = container[key]
        except (AttributeError, KeyError, TypeError):
            return default
    return container


def finalize_wrapper(finalizable):
    """
    Wrapper around the finalize method for the object
    :param finalizable: an object with the finalize method
    :return:
    """
    finalizable.finalize()
    return finalizable


@staticmethod
def _get_gc_content(sequence, length):
    """Get GC content and proportions.

        Parameters
        ----------
        sequence : str
            The complete sequence of the contig.
        length : int
            The length of the sequence contig.

        Returns
        -------
        x : dict
            Dictionary with the at/gc/n counts and proportions

        """
    at = sum(map(sequence.count, ['A', 'T']))
    gc = sum(map(sequence.count, ['G', 'C']))
    n = length - (at + gc)
    at_prop = at / length
    gc_prop = gc / length
    n_prop = n / length
    return {'at': at, 'gc': gc, 'n': n, 'at_prop': at_prop, 'gc_prop':
        gc_prop, 'n_prop': n_prop}


def setScriptname(name):
    """
    Module function to set the scriptname to be reported back to the IDE.

    @param name absolute pathname of the script (string)
    """
    global __scriptname
    __scriptname = name


def _ch_dev(arg_params, aux_params, ctx):
    """
    Changes device of given mxnet arguments
    :param arg_params: arguments
    :param aux_params: auxiliary parameters
    :param ctx: new device context
    :return: arguments and auxiliary parameters on new device
    """
    new_args = dict()
    new_auxs = dict()
    for k, v in arg_params.items():
        new_args[k] = v.as_in_context(ctx)
    for k, v in aux_params.items():
        new_auxs[k] = v.as_in_context(ctx)
    return new_args, new_auxs


@staticmethod
def exclude_paths_from_context(root, exclude, dockerfile):
    """
        * root: path of build context
        * exclude: list of `.dockerignore` patterns
        * dockerfile: path to dockerfile
        * **return:** iterator of all paths (files and directories) not excluded with patterns
                    All paths returned are relative to the root.
        """
    pass


def project_opened(project):
    """This function is called after opening the project"""


def _replace_ref_index(matched, citations):
    """citations: index => ref"""
    index = matched[2:-2]
    if index in citations:
        return '[#REF: %s #]' % citations[index]
    return matched


@classmethod
def get_visible_name_from_scope(cls, scope):
    """ Generate visible name based on host scope """
    return ('%s-%s' % (scope.uuid.hex, scope.name))[:64]


def compute_ratios(df_dict, df_str, gridclimname1, gridclimname2, prefix1,
    prefix2='meanmonth', comp_dict=None):
    """
    Compute fold-difference between monthly means (e.g,. Temp) for two different gridded datasets (e.g., Liv, WRF)
    """
    if isinstance(comp_dict, type(None)):
        comp_dict = {}
    for each1 in prefix1:
        for each2 in prefix2:
            ratios = df_dict['_'.join([each2, each1, gridclimname1])
                ] / df_dict['_'.join([each2, each1, gridclimname2])]
            comp_dict['_'.join([str(each1), df_str])] = ratios
    return comp_dict


def _contains_fallback(iterable, item):
    """Fallback to determine whether the iterable contains the value specified.

  Uses a loop instead of built-in methods.

  :param iterable:
      Iterable sequence.
  :param item:
      The value to find.
  :returns:
      ``True`` if the iterable sequence contains the value; ``False``
      otherwise.
  """
    for element in iter(iterable):
        if element == item:
            return True
    return False


def formatLevel(level: int, s: str) ->str:
    """Helper to indent a string with a number of tabs"""
    return '\t' * level + s


def sanitize(time_string):
    """a function that make the different separators same as ':'"""
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return time_string
    mins, secs = time_string.split(splitter)
    return mins + '.' + secs


def _runNAInsertion(dtable, col, navals):
    """Performs NA insertion on one column. """
    dtable[:, (col)] = dtable[:, (col)].replace(navals)


def isBroken():
    """Return True if this is a broken relation.
        """


def doc():
    """Returns a string that represents the error message."""


def init(**kwargs):
    """To get access to shell defaults dict"""
    global genders_file
    db_file = kwargs.get('defaults', {}).get('genders_file', None)
    if db_file:
        genders_file = db_file


def _worker(remote, parent_remote, env_fn_wrapper, lock=None):
    """
    @brief      Worker for each subprocess of SubprocVecEnvLock.

    @details    It enables the use of a threading.Lock. It is the only
                difference with the implementation provided with the
                class `SubprocVecEnv` of Gym OpenAI.

    @remark     `remote` and `parent_remote` are returned by the method `Pipe` of
                `multiprocessing`.  It is a pair of connection objects connected
                by a pipe which by default is duplex (two-way). See
                `multiprocessing` documentation for more information.

                This is a hidden function that is not automatically imported
                using 'from gym_jiminy import *'.

    @param[in]  remote              Child remote
    @param[in]  parent_remote       Parent remote
    @param[in]  env_fn_wrapper      Gym environment
    @param[in]  lock                threading.Lock object. Optional: None by default
    """
    parent_remote.close()
    env = env_fn_wrapper.var()
    while True:
        try:
            cmd, data = remote.recv()
            if cmd == 'step':
                observation, reward, done, info = env.step(data)
                if done:
                    info['terminal_observation'] = observation
                    observation = env.reset()
                remote.send((observation, reward, done, info))
            elif cmd == 'reset':
                observation = env.reset()
                remote.send(observation)
            elif cmd == 'render':
                remote.send(env.render(*data[0], lock=lock, **data[1]))
            elif cmd == 'close':
                remote.close()
                break
            elif cmd == 'get_spaces':
                remote.send((env.observation_space, env.action_space))
            elif cmd == 'env_method':
                method = getattr(env, data[0])
                remote.send(method(*data[1], **data[2]))
            elif cmd == 'get_attr':
                remote.send(getattr(env, data))
            elif cmd == 'set_attr':
                remote.send(setattr(env, data[0], data[1]))
            else:
                raise NotImplementedError
        except EOFError:
            break


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

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

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


def ignore_error(f):
    """a decorator that marks a callback as ok to fail

    intended to be used by plugins
    """
    setattr(f, 'failure_is_an_option', True)
    return f


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


@staticmethod
def fix_query(query):
    """
        Removes some query parameters that otherwise will lead to a cache miss.
        Eg: 'track_no' since we can't query TIDAL for a specific album's track.
        :param query: query dictionary
        :return: sanitized query dictionary
        """
    query.pop('track_no', None)
    return query


def approve_pr_arguments(parser):
    """ Approve reviewed pull request.
    """
    parser.add_argument('name', type=str, action='store', nargs=1, help=
        'pull request name')
    parser.add_argument('-s', '--serial', type=str, action='store', help=
        "pull request serial, only required if not using 'review-pr' first")
    parser.add_argument('-m', '--message', action='store', help=
        'Message to add on submit.')
    parser.add_argument('-k', '--keep-index', action='store_true', help=
        'Keep the pr index instead of deleting it after approval.')


def pop_count(inp):
    """
    Function to determine the population count in the bit-stream
    "borrowed" in gnuradio
    """
    pop_cnt = inp - (inp >> 1 & 3681400539) - (inp >> 2 & 1227133513)
    return (pop_cnt + (pop_cnt >> 3) & 3340530119) % 63


def mergeDataCodingTable(vartable, dctable):
    """Merges information from the data coding table into the variable
    table.

    Called by :func:`loadVariableTable`.

    :arg vartable: The variable table.
    :arg dctable:  The data coding table.
    """
    with_datacoding = vartable['DataCoding'].notna()
    for field in ['NAValues', 'RawLevels', 'NewLevels']:
        mask = vartable[field].isna() & with_datacoding
        newvals = vartable.loc[mask].merge(dctable, left_on='DataCoding',
            right_index=True, suffixes=('_v', '_dc'), copy=False)['{}_dc'.
            format(field)]
        vartable.loc[mask, field] = newvals


def get_project_request(rd, project_id, request_id):
    """ Get Project's Merge Request
    :param rd: Redis Object Instance
    :param project_id: Project Identifier (int)
    :param request_id: Merge Request Identifier (int)
    :return: Merge Request (Object)
    """
    return False


def sd_nzs(period, site_class, z_factor, r_factor, n_factor):
    """
    Returns the NZ sd_nzs value for a given Time and soil type

    :param period: float or array
    :param site_class: Either 'C', 'D' or 'E'
    output: sd_nzs: float or array
    """
    if period < 0:
        raise ValueError('Structural period is negative')
    elif site_class == 'C':
        if period == 0:
            c_h = 1.33 * period ** 2
        elif period < 0.1:
            c_h = (1.33 + 1.6 * (period / 0.1)) * period ** 2
        elif period < 0.3:
            c_h = 2.93 * period ** 2
        elif period < 1.5:
            c_h = 2.0 * (0.5 / period) ** 0.75 * period ** 2
        elif period < 3.0:
            c_h = 1.32 / period * period ** 2
        else:
            c_h = 3.96
    elif site_class == 'D':
        if period == 0:
            c_h = 1.12 * period ** 2
        elif period < 0.1:
            c_h = (1.12 + 1.88 * (period / 0.1)) * period ** 2
        elif period < 0.56:
            c_h = 3.0 * period ** 2
        elif period < 1.5:
            c_h = 2.4 * (0.75 / period) ** 0.75 * period ** 2
        elif period < 3.0:
            c_h = 2.14 / period * period ** 2
        else:
            c_h = 6.42
    elif site_class == 'E':
        if period == 0:
            c_h = 1.12 * period ** 2
        elif period < 0.1:
            c_h = (1.12 + 1.88 * (period / 0.1)) * period ** 2
        elif period < 1.0:
            c_h = 3.0 * period ** 2
        elif period < 1.5:
            c_h = 3.0 / period ** 0.75 * period ** 2
        elif period < 3.0:
            c_h = 3.32 / period * period ** 2
        else:
            c_h = 9.96
    else:
        raise ValueError('Soil must be type C, D or E')
    sd = c_h * z_factor * n_factor * r_factor
    return sd


def get_detail_view_name(model):
    """
    Given a model class, return the view name to use for URL relationships
    that rever to instances of the model.
    """
    return '{}-detail'.format(model.__name__.lower())


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


@staticmethod
def validate_property(element, element_selector, property_name,
    valid_property_values):
    """Goes through array to see if property is contained in the array.

		Args:
			element (dict): Element to search for in network.
			element_selector (str): Selector for element in the network.
			property_name (str): Name of the property.
			valid_property_values (List[str]): List of valid properties.

		Returns:
			None or str: None, if the property is valid or does not exist; error message if property is invalid.
		"""
    if property_name in element and element[property_name
        ] not in valid_property_values:
        return (element_selector + ' contains illegal value for property: ' +
            property_name + '.  Value given for this property was: ' +
            element[property_name] + '.  Accepted values for property: ' +
            property_name + ' are: [' + str(valid_property_values) + ']')
    return None


def compute_seismic_energy(m):
    """
    Compute seismic energy using Gutenberg-Richter equation.

    .. math::

        log E = 11.8 + 1.5M

    where :math:`M` is Richter local magnitude  and :math:`E` is energy in ergs.

    :param m: Richter local magnitude.
    :type m: float
    :return: Seismic energy in factor of :math:`10^{12}` ergs.
    :rtype: float
    """
    return 10 ** (11.8 + 1.5 * m) / 10 ** 12


def timedelta_to_days(td):
    """
    Convert a `datetime.timedelta` object to a total number of days.

    Parameters
    ----------
    td : `datetime.timedelta` instance

    Returns
    -------
    days : float
        Total number of days in the `datetime.timedelta` object.

    Examples
    --------
    >>> td = datetime.timedelta(4.5)
    >>> td
    datetime.timedelta(4, 43200)
    >>> timedelta_to_days(td)
    4.5

    """
    seconds_in_day = 24.0 * 3600.0
    days = td.days + (td.seconds + td.microseconds * 10000000.0
        ) / seconds_in_day
    return days


def keyconfig_remove():
    """Remove key config

    """
    pass


def save_csv_to_file(csv_data, abs_file_path):
    """
    Save a python object acceptable for pickle to the provided file path
    """
    with open(abs_file_path, 'w') as outfile:
        outfile.write(csv_data)


def union_overlapping(intervals):
    """Union any overlapping intervals in the given set."""
    disjoint_intervals = []
    for interval in intervals:
        if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
            disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
        else:
            disjoint_intervals.append(interval)
    return disjoint_intervals


def reboot(isamAppliance, check_mode=False, force=False):
    """
    Reboot the appliance
    """
    if check_mode is True:
        return isamAppliance.create_return_object(changed=True)
    else:
        return isamAppliance.invoke_post('Rebooting appliance',
            '/diagnostics/restart_shutdown/reboot', {})


def stream_copy(read, write, size, chunk_size):
    """
    Copy a stream up to size bytes using the provided read and write methods,
    in chunks of chunk_size

    **Note:** its much like stream_copy utility, but operates just using methods"""
    dbw = 0
    while True:
        cs = min(chunk_size, size - dbw)
        data = read(cs)
        data_len = len(data)
        dbw += data_len
        write(data)
        if data_len < cs or dbw == size:
            break
    return dbw


def is_string(value):
    """Check whether specified value is of type string (not bytes)."""
    return isinstance(value, str)


def chunked_sequence_iter(sequence, chunk_size):
    """
    Yield successive chunk_size sized chunks from sequence.
    """
    if not chunk_size > 0:
        raise ValueError('chunk_size must be > 0')
    for i in range(0, len(sequence), chunk_size):
        yield sequence[i:i + chunk_size]


def list_rules_packages(nextToken=None, maxResults=None):
    """
    Lists all available Amazon Inspector rules packages.
    See also: AWS API Documentation

    Examples
    Lists all available Amazon Inspector rules packages.
    Expected Output:

    :example: response = client.list_rules_packages(
        nextToken='string',
        maxResults=123
    )

    :type nextToken: string
    :param nextToken: You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListRulesPackages action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.

    :type maxResults: integer
    :param maxResults: You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500.

    :rtype: dict
    :return: {
        'rulesPackageArns': [
            'string',
        ],
        'nextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


@staticmethod
def _token_auth_str(token):
    """Return a Token auth string."""
    return 'Token {}'.format(token.strip())


def save():
    """Save the image with current name and settings

    """
    pass


def dgl_csr_neighbor_uniform_sample(*seed_arrays, **kwargs):
    """This operator samples sub-graphs from a csr graph via an
    uniform probability. The operator is designed for DGL.

    The operator outputs three sets of NDArrays to represent the sampled results
    (the number of NDArrays in each set is the same as the number of seed NDArrays):
    1) a set of 1D NDArrays containing the sampled vertices, 2) a set of CSRNDArrays representing
    the sampled edges, 3) a set of 1D NDArrays indicating the layer where a vertex is sampled.
    The first set of 1D NDArrays have a length of max_num_vertices+1. The last element in an NDArray
    indicate the acutal number of vertices in a subgraph. The third set of NDArrays have a length
    of max_num_vertices, and the valid number of vertices is the same as the ones in the first set.

    Example:

       .. code:: python

      shape = (5, 5)
      data_np = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], dtype=np.int64)
      indices_np = np.array([1,2,3,4,0,2,3,4,0,1,3,4,0,1,2,4,0,1,2,3], dtype=np.int64)
      indptr_np = np.array([0,4,8,12,16,20], dtype=np.int64)
      a = mx.nd.sparse.csr_matrix((data_np, indices_np, indptr_np), shape=shape)
      a.asnumpy()
      seed = mx.nd.array([0,1,2,3,4], dtype=np.int64)
      out = mx.nd.contrib.dgl_csr_neighbor_uniform_sample(a, seed, num_args=2, num_hops=1, num_neighbor=2, max_num_vertices=5)

      out[0]
      [0 1 2 3 4 5]
      <NDArray 6 @cpu(0)>

      out[1].asnumpy()
      array([[ 0,  1,  0,  3,  0],
             [ 5,  0,  0,  7,  0],
             [ 9,  0,  0, 11,  0],
             [13,  0, 15,  0,  0],
             [17,  0, 19,  0,  0]])

      out[2]
      [0 0 0 0 0]
      <NDArray 5 @cpu(0)>

    Defined in src/operator/contrib/dgl_graph.cc:L784
    This function support variable length of positional input.

    Parameters
    ----------
    csr_matrix : Symbol
        csr matrix
    seed_arrays : Symbol[]
        seed vertices
    num_hops : long, optional, default=1
        Number of hops.
    num_neighbor : long, optional, default=2
        Number of neighbor.
    max_num_vertices : long, optional, default=100
        Max number of vertices.

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

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


@classmethod
def dashboards(cls):
    """Get the current user dashboards list

        See https://app.yuleak.com/apidoc#get-dashboards for endpoint details.

        Returns:
            list of Dashboard items
        """
    from .models.dashboard import Dashboard
    results = []
    for d in cls.get_request('dashboards'):
        results.append(Dashboard(d.get('id'), d.get('name')))
    return results


def write_dframe(dframe, path, header=True, index=True):
    """ Write a dataframe to local disk. """
    dframe.to_csv(path, index=index, header=header)


def get_illust_url(illust_id: int) ->str:
    """Get illust URL from ``illust_id``.

    :param illust_id: Pixiv illust_id
    :type illust_id: :class:`int`
    :return: Pixiv Illust URL
    :rtype: :class:`str`

    """
    return ('https://www.pixiv.net/member_illust.php?mode=medium&illust_id={}'
        .format(illust_id))


def _get_new_parent(moved, target, position='first-child'):
    """
    Find out which parent the node will reside under.
    """
    if position in ('first-child', 'last-child'):
        return target
    elif position in ('left', 'right'):
        parent_attr_id = '{}_id'.format(moved._mptt_meta.parent_attr)
        if getattr(target, parent_attr_id) == getattr(moved, parent_attr_id):
            return getattr(moved, moved._mptt_meta.parent_attr)
        return getattr(target, target._mptt_meta.parent_attr)
    else:
        raise ValueError('invalid mptt position argument')


def write_simpletypes_imports(wrtmodels, simpletypes_set):
    """write simple types imports from sqlalchemy to model"""
    wrtmodels('from sqlalchemy import Table, Column, MetaData, ForeignKey, ')
    types_string = ''
    for simpletype in simpletypes_set:
        types_string = '%s%s, ' % (types_string, simpletype)
    if types_string:
        types_string = types_string[:-2]
    wrtmodels(types_string)
    wrtmodels('\n')
    return


def name_fields(cursor, records):
    """
    Take a cursor and a list of records fetched with that cursor, then return a
    list of dictionaries (one for each record) whose keys are column names and
    values are records' values.

    :param cursor: cursor used to execute the query
    :param records: list returned by fetch*()
    """
    result = []
    for record in records:
        record_dict = {}
        for i in range(len(record)):
            record_dict[cursor.description[i][0]] = record[i]
        result.append(record_dict)
    return result


def ppxv2density(data, units, notation=None, inplace_units=True, solutes=[]):
    """
    Calculates density of solutes based on their molar concentration (ppmv, ppbv and etc), not
    to be confused with mass concentration (ppm, ppb and etc).

    Uses the relation
    :math:`\\rho_x = \\frac{C p}{\\theta R_x}`

    Parameters
    ----------
    data: pandas.DataFrame
        dataset of micromet variables
    units: dict
        dict of pint units
    notation: pymicra.Notation
        notation to be used here
    inplace_units: bool
        whether or not to treat the dict units in place
    solutes: list or tuple
        solutes to consider when doing this conversion

    Returns
    -------
    pandas.DataFrame
        input data plus calculated density columns
    """
    from . import constants
    from . import algs
    if not solutes:
        raise ValueError('Should specify for which solutes')
    defs = algs.get_notation(notation)
    defsdic = vars(defs)
    data = data.copy()
    cunits = constants.units
    sol_units = {}
    convert_to = {}
    p = data[defs.pressure]
    theta = data[defs.thermodyn_temp]
    for solute in solutes:
        sol_mconc = defsdic['%s_molar_concentration' % solute]
        rho_sol = defsdic['%s_mass_density' % solute]
        data[rho_sol] = data[sol_mconc] * p / (theta * constants.R_spec[solute]
            )
        unit = units[sol_mconc] * units[defs.pressure] / (units[defs.
            thermodyn_temp] * cunits['R_spec'])
        sol_units.update({rho_sol: unit})
        convert_to.update({rho_sol: 'kg/m**3'})
    data = data.convert_cols(convert_to, sol_units, inplace_units=True)
    if inplace_units:
        units.update(sol_units)
        return data
    else:
        return data, unit


def update(observable, arg):
    """Called when the observed object is
        modified. You call an Observable object's
        notifyObservers method to notify all the
        object's observers of the change."""
    pass


@classmethod
def export_set(cls, dataset, **kwargs):
    """
        Returns reStructuredText table representation of dataset.

        Returns a simple table if the text in the first column is never
        wrapped, otherwise returns a grid table.

        >>> from tablib import Dataset
        >>> bits = ((0, 0), (1, 0), (0, 1), (1, 1))
        >>> data = Dataset()
        >>> data.headers = ['A', 'B', 'A and B']
        >>> for a, b in bits:
        ...     data.append([bool(a), bool(b), bool(a * b)])
        >>> table = data.rst
        >>> table.split('\\n') == [
        ...     '=====  =====  =====',
        ...     '  A      B    A and',
        ...     '                B  ',
        ...     '=====  =====  =====',
        ...     'False  False  False',
        ...     'True   False  False',
        ...     'False  True   False',
        ...     'True   True   True ',
        ...     '=====  =====  =====',
        ... ]
        True

        """
    if not dataset.dict:
        return ''
    force_grid = kwargs.get('force_grid', False)
    max_table_width = kwargs.get('max_table_width', cls.MAX_TABLE_WIDTH)
    column_widths = cls._get_column_widths(dataset, max_table_width)
    use_simple_table = cls._use_simple_table(dataset.headers[0] if dataset.
        headers else None, dataset.get_col(0), column_widths[0])
    if use_simple_table and not force_grid:
        return cls.export_set_as_simple_table(dataset, column_widths)
    else:
        return cls.export_set_as_grid_table(dataset, column_widths)


def sortKeyBytes(b_word):
    """
	b_word is a bytes instance
	"""
    assert isinstance(b_word, bytes)
    return b_word.lower(), b_word


def init_spark_on_yarn(hadoop_conf, conda_name, num_executor,
    executor_cores, executor_memory='2g', driver_memory='1g', driver_cores=
    4, extra_executor_memory_for_ray=None, extra_python_lib=None,
    penv_archive=None, hadoop_user_name='root', spark_yarn_archive=None,
    spark_log_level='WARN', redirect_spark_log=True, jars=None, spark_conf=None
    ):
    """
    Create a SparkContext with Zoo configuration on Yarn cluster on "Yarn-client" mode.
    You should create a conda env and install the python dependencies in that env.
    Conda env and the python dependencies only need to be installed in the driver machine.
    It's not necessary create and install those on the whole yarn cluster.

    :param hadoop_conf: path to the yarn configuration folder.
    :param conda_name: Name of the conda env.
    :param num_executor: Number of the Executors.
    :param executor_cores: Cores for each Executor.
    :param executor_memory: Memory for each Executor.
    :param driver_memory: Memory for the Driver.
    :param driver_cores: Number of cores for the Driver.
    :param extra_executor_memory_for_ray: Memory size for the Ray services.
    :param extra_python_lib:
    :param penv_archive: Ideally, program would auto-pack the conda env which is specified by
           `conda_name`, but you can also pass the path to a packed file in "tar.gz" format here.
    :param hadoop_user_name: User name for running in yarn cluster. Default value is: root
    :param spark_log_level: Log level of Spark
    :param redirect_spark_log: Direct the Spark log to local file or not.
    :param jars: Comma-separated list of jars to include on the driver and executor classpaths.
    :param spark_conf: You can append extra spark conf here in key value format.
                       i.e spark_conf={"spark.executor.extraJavaOptions": "-XX:+PrintGCDetails"}
    :return: SparkContext
    """
    from zoo.util.spark import SparkRunner
    sparkrunner = SparkRunner(spark_log_level=spark_log_level,
        redirect_spark_log=redirect_spark_log)
    sc = sparkrunner.init_spark_on_yarn(hadoop_conf=hadoop_conf, conda_name
        =conda_name, num_executor=num_executor, executor_cores=
        executor_cores, executor_memory=executor_memory, driver_memory=
        driver_memory, driver_cores=driver_cores,
        extra_executor_memory_for_ray=extra_executor_memory_for_ray,
        extra_python_lib=extra_python_lib, penv_archive=penv_archive,
        hadoop_user_name=hadoop_user_name, spark_yarn_archive=
        spark_yarn_archive, jars=jars, spark_conf=spark_conf)
    return sc


def add_register_args(parser):
    """Add the register command and arguments.

    :param argparse.Subparser parser: parser

    """
    registerp = parser.add_parser('register', help=
        'Register a service for this node')
    registerp.add_argument('name', help='The service name')
    registerp.add_argument('-a', '--address', default=None, help=
        'Specify an address')
    registerp.add_argument('-p', '--port', default=None, type=int, help=
        'Specify a port')
    registerp.add_argument('-s', '--service-id', default=None, help=
        'Specify a service ID')
    registerp.add_argument('-t', '--tags', default=[], help=
        'Specify a comma delimited list of tags')
    rsparsers = registerp.add_subparsers(dest='ctype', title=
        'Service Check Options')
    check = rsparsers.add_parser('check', help=
        'Define an external script-based check')
    check.add_argument('interval', default=10, type=int, help=
        'How often to run the check script')
    check.add_argument('path', default=None, help=
        'Path to the script invoked by Consul')
    httpcheck = rsparsers.add_parser('httpcheck', help=
        'Define an HTTP-based check')
    httpcheck.add_argument('interval', default=10, type=int, help=
        'How often to run the check script')
    httpcheck.add_argument('url', default=None, help=
        'HTTP URL to be polled by Consul')
    rsparsers.add_parser('no-check', help='Do not enable service monitoring')
    ttl = rsparsers.add_parser('ttl', help='Define a duration based TTL check')
    ttl.add_argument('duration', type=int, default=10, help=
        'TTL duration for a service with missing check data')


def get(isamAppliance, id, check_mode=False, force=False):
    """
    Retrieving the details for a particular federated directory
    """
    return isamAppliance.invoke_get(
        'Retrieving the details for a particular federated directory',
        '/isam/runtime_components/federated_directories/{0}/v1'.format(id))


def __new__(cls, name, description=None):
    """Keep a dict of PermissionSetting instances, indexed by
        name. If the name already exists in the dict, return that
        instance rather than creating a new one.
        """
    instances = cls.__dict__.get('_z_instances')
    if instances is None:
        cls._z_instances = instances = {}
    it = instances.get(name)
    if it is None:
        instances[name] = it = object.__new__(cls)
        it._init(name, description)
    return it


def __iter__():
    """
        Retrieve an iterator for the results of this query.

        The query is performed whenever this is called.
        """


def validate_schema(columns, rows):
    """Validate that the given set of rows contains exactly one value for each
    column in a dataset schema.

    Raises ValueError in case of a schema violation.
    """
    for i in range(len(rows)):
        row = rows[i]
        if len(row.values) != len(columns):
            raise ValueError("schema violation for row '" + str(i) + "'")


def properties():
    """Toggle the properties region visibility

    """
    pass


@classmethod
def registerfilter(cls, function):
    """Decorator to register a jinja2 filter"""
    cls.filters[function.__name__] = function
    return function


@classmethod
def geom_col_name(cls):
    """
        Returns the name of the metadata column used to store the
        the feature geometry column.
        """
    return 'column_name'


def _json_formatter(obj):
    """Formatter for unserialisable values."""
    return str(obj)


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


@classmethod
def add_int_kw(cls, kw):
    """Will add keyword @kw to the standard set of integer keywords."""
    cls.int_kw_set.add(kw)


@staticmethod
def gen_prefix_dict(dict_f):
    """ Reads a dict file and generates the prefix dictionary with total word counts.
        """
    word_counts = {}
    with open(dict_f, 'rb') as f:
        for line in f:
            line = line.strip().decode('utf-8')
            word, freq = line.split(',')
            word_counts[word] = int(freq)
            for i in range(len(word)):
                prefix = word[:i + 1]
                if prefix not in word_counts:
                    word_counts[prefix] = 0
    return word_counts, sum(word_counts.values())


def keyconfig_import(filepath: str='keymap.py', filter_folder: bool=True,
    filter_text: bool=True, filter_python: bool=True, keep_original: bool=True
    ):
    """Import key configuration from a python script

    :param filepath: filepath
    :type filepath: str
    :param filter_folder: Filter folders
    :type filter_folder: bool
    :param filter_text: Filter text
    :type filter_text: bool
    :param filter_python: Filter python
    :type filter_python: bool
    :param keep_original: Keep original, Keep original file after copying to configuration folder
    :type keep_original: bool
    """
    pass


def silverman_rule_of_thumb(n_samples, dimension):
    """
    Silverman's rule of thumb.

    .. math::

       \\left ( \\frac{4}{n (d+2)} \\right ) ^ {\\frac{1}{d + 4}}

    (see also scipy.stats.kde.gaussian_kde.silverman_factor)
    """
    return (4 / n_samples / (dimension + 2)) ** (1 / (dimension + 4))


def from_inclusive(a, b):
    """Returns a range from a to b, including both endpoints"""
    c = int(b > a) * 2 - 1
    return range(a, b + c, c)


def is_float(potential_float: str) ->bool:
    """
    Check if potential_float is a valid float.

    Returns
    -------
    is_float : bool

    Examples
    --------
    >>> is_float('123')
    True
    >>> is_float('1234567890123456789')
    True
    >>> is_float('0')
    True
    >>> is_float('-123')
    True
    >>> is_float('123.45')
    True
    >>> is_float('a')
    False
    >>> is_float('0x8')
    False
    """
    try:
        float(potential_float)
        return True
    except ValueError:
        return False


def getProxiedObject(obj):
    """Get the proxied Object

        If the object isn't proxied, then just return the object.
        """


@staticmethod
def check_for_calibration_data(function, path_to_results_file):
    """Check to see if there is any calibration data in the results file

        Parameters
        ----------
        function: func
            callable function that will check to see if calibration data is in
            the results file
        path_to_results_file: str
            path to the results file
        """
    return function(path_to_results_file)


def touch(ctx, fpath):
    """Creates a file or updates modified date if already exists."""
    ctx.run('touch %s' % fpath)


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

        :param DataPlacementRestrictionSatisfyPolicyDetails val:
        :rtype: EventDetails
        """
    return cls('data_placement_restriction_satisfy_policy_details', val)


def time(model):
    """
    Deprecated alias of :meth:`Model.timex()`.
    """
    import warnings
    warnings.warn(
        'The method `myokit.lib.multi.time()` is deprecated and will be removed in future versions of Myokit. Please use `Model.timex()` instead.'
        )
    return model.timex()


def list_equal(list_a, list_b):
    """Check if two lists are equal

    Parameters
    ----------
    list_a: list, tuple
    list_b: list, tuple

    Returns
    -------
    bool
    """
    return tuple(list_a) == tuple(list_b)


def delete_message(message_id):
    """Remove the given message from the store.

        If the referenced message is missing from the message store, the
        operation is ignored.

        :param message: The Message-ID of the message to delete from the store.
        """


def check_for_split(G, edge):
    """
    Given an edge in tuple form, check if it splits the
    graph into two disjoint clusters. If so, it returns
    True. Otherwise, False.
    """
    if edge[0] == edge[1]:
        return False
    return not G.edge_disjoint_paths(source=edge[0], target=edge[1])


def _string_from_cmd_list(cmd_list):
    """Takes a list of command line arguments and returns a pretty
    representation for printing."""
    cl = []
    for arg in map(str, cmd_list):
        if ' ' in arg or '\t' in arg:
            arg = '"' + arg + '"'
        cl.append(arg)
    return ' '.join(cl)


def get_example_tree():
    """ generate a quick 100 leaf tree for demo purposes """
    retval = {'name': 'parent', 'children': []}
    for i in range(10):
        retval['children'].append({'name': 'child ' + str(i)})
        retval['children'][i]['children'] = []
        for j in range(10):
            retval['children'][i]['children'].append({'name': 'grandchild ' +
                str(i) + '.' + str(j)})
    return retval


def list_max_show_all(changelist):
    """
    Returns the maximum amount of results a changelist can have for the
    "Show all" link to be displayed in a manner compatible with both Django
    1.4 and 1.3. See Django ticket #15997 for details.
    """
    try:
        from django.contrib.admin.views.main import MAX_SHOW_ALL_ALLOWED
        return MAX_SHOW_ALL_ALLOWED
    except ImportError:
        return changelist.list_max_show_all


def compact_range_dumps(li):
    """
    Accepts a list of integers and represent it as intervals
    [1,2,3,4,6,7] => '1-4,6-7'
    """
    li = sorted(li)
    low = None
    high = None
    collections = []
    for i, number in enumerate(li):
        number = li[i]
        if low is None:
            low = number
            high = number
        elif high + 1 == number:
            high = number
        else:
            collections.append('{}-{}'.format(low, high))
            low = None
            high = None
    collections.append('{}-{}'.format(low, high))
    return ','.join(collections)


def interpolate_linear_single(start, end, coefficient):
    """ Cosine interpolation """
    return start + (end - start) * coefficient


def put_bucket_notification_configuration(Bucket=None,
    NotificationConfiguration=None):
    """
    Enables notifications of specified events for a bucket.
    See also: AWS API Documentation

    :example: response = client.put_bucket_notification_configuration(
        Bucket='string',
        NotificationConfiguration={
            'TopicConfigurations': [
                {
                    'Id': 'string',
                    'TopicArn': 'string',
                    'Events': [
                        's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
                    ],
                    'Filter': {
                        'Key': {
                            'FilterRules': [
                                {
                                    'Name': 'prefix'|'suffix',
                                    'Value': 'string'
                                },
                            ]
                        }
                    }
                },
            ],
            'QueueConfigurations': [
                {
                    'Id': 'string',
                    'QueueArn': 'string',
                    'Events': [
                        's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
                    ],
                    'Filter': {
                        'Key': {
                            'FilterRules': [
                                {
                                    'Name': 'prefix'|'suffix',
                                    'Value': 'string'
                                },
                            ]
                        }
                    }
                },
            ],
            'LambdaFunctionConfigurations': [
                {
                    'Id': 'string',
                    'LambdaFunctionArn': 'string',
                    'Events': [
                        's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
                    ],
                    'Filter': {
                        'Key': {
                            'FilterRules': [
                                {
                                    'Name': 'prefix'|'suffix',
                                    'Value': 'string'
                                },
                            ]
                        }
                    }
                },
            ]
        }
    )

    :type Bucket: string
    :param Bucket: [REQUIRED]

    :type NotificationConfiguration: dict
    :param NotificationConfiguration: [REQUIRED] Container for specifying the notification configuration of the bucket. If this element is empty, notifications are turned off on the bucket.
            TopicConfigurations (list) --
            (dict) -- Container for specifying the configuration when you want Amazon S3 to publish events to an Amazon Simple Notification Service (Amazon SNS) topic.
            Id (string) -- Optional unique identifier for configurations in a notification configuration. If you don't provide one, Amazon S3 will assign an ID.
            TopicArn (string) -- [REQUIRED] Amazon SNS topic ARN to which Amazon S3 will publish a message when it detects events of specified type.
            Events (list) -- [REQUIRED]
            (string) -- Bucket event for which to send notifications.
            Filter (dict) -- Container for object key name filtering rules. For information about key name filtering, go to Configuring Event Notifications in the Amazon Simple Storage Service Developer Guide.
            Key (dict) -- Container for object key name prefix and suffix filtering rules.
            FilterRules (list) -- A list of containers for key value pair that defines the criteria for the filter rule.
            (dict) -- Container for key value pair that defines the criteria for the filter rule.
            Name (string) -- Object key name prefix or suffix identifying one or more objects to which the filtering rule applies. Maximum prefix length can be up to 1,024 characters. Overlapping prefixes and suffixes are not supported. For more information, go to Configuring Event Notifications in the Amazon Simple Storage Service Developer Guide.
            Value (string) --

            QueueConfigurations (list) --
            (dict) -- Container for specifying an configuration when you want Amazon S3 to publish events to an Amazon Simple Queue Service (Amazon SQS) queue.
            Id (string) -- Optional unique identifier for configurations in a notification configuration. If you don't provide one, Amazon S3 will assign an ID.
            QueueArn (string) -- [REQUIRED] Amazon SQS queue ARN to which Amazon S3 will publish a message when it detects events of specified type.
            Events (list) -- [REQUIRED]
            (string) -- Bucket event for which to send notifications.
            Filter (dict) -- Container for object key name filtering rules. For information about key name filtering, go to Configuring Event Notifications in the Amazon Simple Storage Service Developer Guide.
            Key (dict) -- Container for object key name prefix and suffix filtering rules.
            FilterRules (list) -- A list of containers for key value pair that defines the criteria for the filter rule.
            (dict) -- Container for key value pair that defines the criteria for the filter rule.
            Name (string) -- Object key name prefix or suffix identifying one or more objects to which the filtering rule applies. Maximum prefix length can be up to 1,024 characters. Overlapping prefixes and suffixes are not supported. For more information, go to Configuring Event Notifications in the Amazon Simple Storage Service Developer Guide.
            Value (string) --

            LambdaFunctionConfigurations (list) --
            (dict) -- Container for specifying the AWS Lambda notification configuration.
            Id (string) -- Optional unique identifier for configurations in a notification configuration. If you don't provide one, Amazon S3 will assign an ID.
            LambdaFunctionArn (string) -- [REQUIRED] Lambda cloud function ARN that Amazon S3 can invoke when it detects events of the specified type.
            Events (list) -- [REQUIRED]
            (string) -- Bucket event for which to send notifications.
            Filter (dict) -- Container for object key name filtering rules. For information about key name filtering, go to Configuring Event Notifications in the Amazon Simple Storage Service Developer Guide.
            Key (dict) -- Container for object key name prefix and suffix filtering rules.
            FilterRules (list) -- A list of containers for key value pair that defines the criteria for the filter rule.
            (dict) -- Container for key value pair that defines the criteria for the filter rule.
            Name (string) -- Object key name prefix or suffix identifying one or more objects to which the filtering rule applies. Maximum prefix length can be up to 1,024 characters. Overlapping prefixes and suffixes are not supported. For more information, go to Configuring Event Notifications in the Amazon Simple Storage Service Developer Guide.
            Value (string) --

    """
    pass


@staticmethod
def prompt(msg: str, skip: bool=False) ->bool:
    """Print a yes/no prompt message, returns True if user answered yes"""
    if skip:
        return skip
    response = input(f'{msg} [y/N] ')
    return response.lower() == 'y'


def _truncate(x):
    """ Returns the truncated value of x in the interval [0,1]
    """
    if x < 0:
        return 0
    if x > 1:
        return 1
    return x


def get_adk_step(s):
    """Gets the Step object representing the ASIC design kit.

    Returns:
      The Step object that was constructed from the currently set ADK.
    """
    return s.adk_step


@classmethod
def from_cdms2(cls, variable: 'cdms2_Variable') ->'DataArray':
    """Convert a cdms2.Variable into an xarray.DataArray
        """
    from ..convert import from_cdms2
    return from_cdms2(variable)


def p_cardinality(p):
    """
    cardinality : INTEGER COMMA INTEGER
                | INTEGER COMMA MANY
    """
    p[0] = [p[1], p[3]]


def get_single_if_any(iterable, *, exception_on_multiple=True,
    none_on_multiple=False):
    """
    Get the single item of `iterable`, if any.

    Default behavior: Get the first item from `iterable`, and ensure it doesn't
    have any more items (raise an exception if it does.)

    If you pass in `exception_on_multiple=False`: If `iterable` has more than
    one item, an exception won't be raised. The first value will be returned.

    If you pass in `none_on_multiple=True`: If `iterable` has more than one
    item, `None` will be returned regardless of the value of the first item.
    Note that passing `none_on_multiple=True` causes the
    `exception_on_multiple` argument to be ignored. (This is a bit ugly but I
    made it that way so you wouldn't have to manually pass
    `exception_on_multiple=False` in this case.)
    """
    if none_on_multiple:
        exception_on_multiple = False
    iterator = iter(iterable)
    try:
        first_item = next(iterator)
    except StopIteration:
        return None
    else:
        if exception_on_multiple or none_on_multiple:
            try:
                second_item = next(iterator)
            except StopIteration:
                return first_item
            else:
                if none_on_multiple:
                    return None
                else:
                    assert exception_on_multiple
                    raise Exception('More than one value not allowed.')
        else:
            return first_item


def check_outfile(filename, wanted_result):
    """ wanted_result: a string """
    is_ok = True
    handle = open(filename)
    for wanted_line, result_line in zip(wanted_result.splitlines(True), handle
        ):
        if wanted_line != result_line:
            print('Aaaaarg, result is not what we wanted (result:' +
                result_line + ', should be:' + wanted_line.decode() + ')')
            is_ok = False
    handle.close()
    if is_ok:
        print('check ' + filename + ': ok')
    else:
        exit(1)


@classmethod
def extract_error_message(cls, e):
    """Extract error message for queries"""
    message = str(e)
    try:
        if isinstance(e.args, tuple) and len(e.args) > 1:
            message = e.args[1]
    except Exception:
        pass
    return message


def _drop_protected_attrs(model_class, values):
    """Removed protected attributes from values dictionary using the models
    __protected_attributes__ field.
    """
    for attr in model_class.__protected_attributes__:
        if attr in values:
            del values[attr]


def _has_method(obj, method):
    """ Given an object determine if it supports the method.

  Args:
    obj: Object which needs to be inspected.
    method: Method whose presence needs to be determined.

  Returns:
    Boolean depending upon whether the method is available or not.
  """
    return getattr(obj, method, None) is not None


def check_role_trust_relationships(admin_role, idbroker_role, log_role,
    ranger_role, issues):
    """Check the trust relationships amongst the roles, reporting errors
    back in the issues collector

    """
    if not idbroker_role.trusts_ec2_service():
        issues.append("IdBroker role {} doesn't trust the EC2 service".
            format(idbroker_role.role_arn))
    if not admin_role.trusts(idbroker_role):
        issues.append("Admin Role {} doesn't trust the IDBroker role {}".
            format(admin_role.role_arn, idbroker_role.role_arn))
    if not log_role.trusts_ec2_service():
        issues.append("Log Role {} doesn't trust the EC2 service".format(
            log_role.role_arn, idbroker_role.role_arn))
    if not ranger_role.trusts(idbroker_role):
        issues.append("Ranger Role {} doesn't trust the IDBroker role {}".
            format(ranger_role.role_arn, idbroker_role.role_arn))


def endswith_lf(line):
    """Return True if line (a text or bytestring) ends with '
'."""
    return line.endswith('\n' if isinstance(line, str) else b'\n')


@classmethod
def one(cls):
    """
        Return the quotient ring's neutral element of multiplication: the
        residue class (QuotientRing element) of ring().one()
        """
    return cls(cls._ring.one())


def bone_siblings(obj, bone):
    """ Returns a list of the siblings of the given bone.
        This requires that the bones has a parent.

    """
    parent = obj.data.bones[bone].parent
    if parent is None:
        return []
    bones = []
    for b in parent.children:
        if b.name != bone:
            bones += [b.name]
    return bones


def removeAboveValue(requestContext, seriesList, n):
    """
    Removes data above the given threshold from the series or list of series
    provided. Values above this threshold are assigned a value of None.
    """
    for s in seriesList:
        s.name = 'removeAboveValue(%s, %g)' % (s.name, n)
        s.pathExpression = s.name
        for index, val in enumerate(s):
            if val is None:
                continue
            if val > n:
                s[index] = None
    return seriesList


def extract_id(line):
    """
        Extract the image id from a success line

        These lines look like:
        'Successfully built ad8402983js938'
    """
    idstr = line.split(' ')[2]
    return idstr


def formula_2017_01_01(individu, period, parameters):
    """
        Gains de levée d'option
        """
    f3vf = individu('f3vf', period)
    f3vi = individu('f3vi', period)
    f3vj = individu('f3vj', period)
    return f3vf + f3vi + f3vj


def find():
    """first incoming thing for which call is `True`"""