def create_configuration_set_event_destination(ConfigurationSetName=None,
    EventDestination=None):
    """
    Creates a configuration set event destination.
    An event destination is the AWS service to which Amazon SES publishes the email sending events associated with a configuration set. For information about using configuration sets, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

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

    :type ConfigurationSetName: string
    :param ConfigurationSetName: [REQUIRED]
            The name of the configuration set to which to apply the event destination.

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

    :rtype: dict
    :return: {}

    """
    pass


def eopreg(calc, val):
    """https://www.quantum-espresso.org/Doc/INPUT_PW.html#eopreg
    """
    assert isinstance(val, float)
    assert val >= 0 and val <= 1


def forecast(dd, f, Tnow):
    """
    call the model to calculate update and return result
    fnew = f(Tnow+Twindow)
    """
    import diff1d
    fnew = diff1d.diff_LL(dd, f, Tnow)
    return fnew


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


def org_kwd(name):
    """Remove the underscore suffix if name starts with a Python keyword."""
    from keyword import iskeyword
    if name.endswith('_'):
        res = name[:-1]
        return res if iskeyword(res) else name
    else:
        return name


@classmethod
def get_by_short_name(cls, short_name):
    """
        Return :class:`.Measure` instance with given short name by registry
        lookup.

        Parameters
        ----------
        short_name : str
            Short name, identifier in :attr:`measure_dict`.

        Returns
        -------
        measure : :class:`.Measure`
            The instance.
        """
    return cls.measure_dict.get(short_name)


def _strip_magic_tail(path):
    """    some.path___with_.__magics__ --> some.path """
    pa_th = path.split('.')
    while pa_th[-1].startswith('__'):
        del pa_th[-1]
        if not pa_th:
            return []
    path = '.'.join(pa_th)
    return path[:-2] if path.endswith('()') else path


def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text('Hola! This is Incubot for the CLAN lab.')
    update.message.reply_text(
        'Before changing volumes make sure your ID is registered.')
    update.message.reply_text('Send /help for help. Enjoy!')


def det3(ar):
    """Returns the determinants of an array of 3 x 3 matrices.

    Parameters
    ----------
    ar : array_like, shape(n, 3, 3)
        A array of 3 x 3 arrays.

    Returns
    -------
    tot : ndarray, shape(n, )
        An array of determinants.

    Notes
    -----

    This is extremely faster than calling numpy.linalg.det for 3 x 3
    matrices and is adopted from:

    http://mail.scipy.org/pipermail/numpy-discussion/2008-August/036928.html

    """
    a = ar[..., 0, 0]
    b = ar[..., 0, 1]
    c = ar[..., 0, 2]
    d = ar[..., 1, 0]
    e = ar[..., 1, 1]
    f = ar[..., 1, 2]
    g = ar[..., 2, 0]
    h = ar[..., 2, 1]
    i = ar[..., 2, 2]
    t = a.copy()
    t *= e
    t *= i
    tot = t
    t = b.copy()
    t *= f
    t *= g
    tot += t
    t = c.copy()
    t *= d
    t *= h
    tot += t
    t = g.copy()
    t *= e
    t *= c
    tot -= t
    t = h.copy()
    t *= f
    t *= a
    tot -= t
    t = i.copy()
    t *= d
    t *= b
    tot -= t
    return tot


def is_number(s):
    """ Decide if 's' is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False


def injectB(x, dx, dt, yA, phi, thetaB):
    """
    Injection new derived mutations B onto background of A/a
    x - 1D grid
    dx - 1D grid spacing
    dt - integration time step
    yB - biallelic frequency spectrum integrated by dadi
    phi - density function
    thetaB - scaled mutation rate
    """
    phi[(0), 1:-1, (1)] += dt / dx[1] / x[1] ** 2 * yA[1:-1] * (1 - x[1:-1]
        ) * thetaB / 2.0
    phi[(1), 1:-1, (0)] += dt / dx[1] / x[1] ** 2 * yA[1:-1] * x[1:-1
        ] * thetaB / 2.0
    phi[1, 0, 0] += dt / dx[1] * 2 / x[1] ** 2 * yA[1] * x[1] * thetaB / 2.0
    return phi


def get_std_bound(mean, std, std_ratio):
    """ bound from mean and std values from measurements """
    b = [mean - std_ratio * std, mean + std_ratio * std]
    if b[0] > b[1]:
        raise ValueError('Error on std bound: %s' % b)
    return b


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

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

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


@classmethod
def default(cls):
    """A factory method that returns a :class:`Colour` with a value of 0."""
    return cls(0)


def listify(to_select):
    """Utitlity function to handle both single and
    list inputs
    """
    if not isinstance(to_select, list):
        to_select = [to_select]
    return to_select


def refresh_pyconstraints():
    """Refresh all pyconstraints

    """
    pass


@classmethod
def _lovelace_function(cls, r):
    """The L(r) function as defined by (Lovelace et al 1999) & (Li et al 2000).

        Rossby Wave Instability (RWI) is characterized by the presence
        of a local extremum in this function.
        """
    return cls._entropy(r) ** (2 / cls.gamma) / (2 * cls._vortensity(r))


@classmethod
def query(cls, name, use_kerberos=None, debug=False):
    """Query the LIGO Channel Information System a `ChannelList`.

        Parameters
        ----------
        name : `str`
            name of channel, or part of it.

        use_kerberos : `bool`, optional
            use an existing Kerberos ticket as the authentication credential,
            default behaviour will check for credentials and request username
            and password if none are found (`None`)

        debug : `bool`, optional
            print verbose HTTP connection status for debugging,
            default: `False`

        Returns
        -------
        channels : `ChannelList`
            a new list containing all `Channels <Channel>` found.
        """
    from .io import cis
    return cis.query(name, use_kerberos=use_kerberos, debug=debug)


def getHierarchies():
    """Returns a list of IHierarchy related to the cube."""


def _numeric_selector(features, useful_cols):
    """
    Function skips numeric encoding and just selects the numeric features as specified in useful_cols

    Returns
    -------
    numeric_features_transformed : pandas.DataFrame
        Dataframe of transformed features

    """
    numeric_cols = useful_cols.loc[useful_cols.dtype == 'numeric', 'feature'
        ].values
    numeric_features = features[numeric_cols]
    return numeric_features


@classmethod
def from_filename(cls, filename):
    """Read the struct from a file given its path."""
    with open(str(filename)) as f:
        string = f.read()
    return cls.from_string(string)


def lookupRenderMethod(name):
    """
        Look up and return the render method associated with the given name.

        @type name: C{str}
        @param name: The value of a render directive encountered in the
            document returned by a call to L{IRenderable.render}.

        @return: A two-argument callable which will be invoked with the request
            being responded to and the tag object on which the render directive
            was encountered.
        """


@classmethod
def utc(class_):
    """Returns a time-zone representing UTC.

        Same as TimeZoneInfo('GMT Standard Time', True) but caches the result
        for performance.

        >>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo)
        True
        """
    if not '_tzutc' in class_.__dict__:
        setattr(class_, '_tzutc', class_('GMT Standard Time', True))
    return class_._tzutc


def t_heredocvar_ENCAPSED_AND_WHITESPACE(t):
    """( [^\\n\\\\${] | \\\\. | \\$(?![A-Za-z_{]) | \\{(?!\\$) )+\\n? | \\\\?\\n"""
    t.lexer.lineno += t.value.count('\n')
    t.lexer.pop_state()
    return t


@classmethod
def size(cls, pid):
    """Return the number of connections in the pool

        :param str pid: The pool id
        :rtype int

        """
    with cls._lock:
        cls._ensure_pool_exists(pid)
        return len(cls._pools[pid])


def get_type_and_data(h_node):
    """ Helper function to return the py_type and data block for a HDF node """
    py_type = h_node.attrs['type'][0]
    data = h_node[()]
    return py_type, data


def isConstructionAllowed(container):
    """ Return True if the current user is allowed to construct an
            instance of this type in 'container, else False.
        """


def _describe_source(d):
    """return either '<path>' or 'line N of <path>' or 'lines M-N of <path>'.
    """
    path = d.get('path') or ''
    if 'num_lines' in d and 'start_line' in d:
        if d['num_lines'] == 1:
            return 'line %d of %s' % (d['start_line'] + 1, path)
        else:
            return 'lines %d-%d of %s' % (d['start_line'] + 1, d[
                'start_line'] + d['num_lines'], path)
    else:
        return path


def content_categorized():
    """Returns start up directory path of content_categorized."""


def log_whodid(obj, user):
    """
    Stores the given user as creator or editor of the given object
    """
    if hasattr(obj, 'created_by') and obj.created_by is None:
        obj.created_by = user
    if hasattr(obj, 'lastmodified_by'):
        obj.lastmodified_by = user


def copier():
    """Copy content into this container.

        The coroutine takes as argument a Silva content, that is copied
        in the current container, and return the copy, or a
        ``ContentError`` is case of failure.
        """


@staticmethod
def _create_state(new_class, name, value) ->None:
    """Create a state hidden in new class."""
    if new_class._states is None:
        new_class._states = {}
    states = new_class._states
    if name in states:
        raise RuntimeError('Duplicated states are not allowed {!r} {!r}'.
            format(new_class, name))
    states[name] = value


def select_more():
    """Grow sets of selected Grease Pencil points

    """
    pass


def midpoint(pt1, pt2):
    """ Return midpoint between points. """
    return 0.5 * (pt1[0] + pt2[0]), 0.5 * (pt1[1] + pt2[1])


def seconds2walltime(seconds):
    """convert a time in seconds to [[HHH:[MM:]SS

    >>> seconds2walltime(12)
    '00:00:12'
    >>> seconds2walltime(123)
    '00:02:03'
    >>> seconds2walltime(1234)
    '00:20:34'
    >>> seconds2walltime(12345)
    '03:25:45'
    """
    seconds = int(seconds)
    secs = seconds % 60
    seconds = seconds // 60
    mins = seconds % 60
    hours = seconds // 60
    return '{h:02d}:{m:02d}:{s:02d}'.format(h=hours, m=mins, s=secs)


def get_queue_attributes(QueueUrl=None, AttributeNames=None):
    """
    Gets attributes for the specified queue.
    See also: AWS API Documentation

    :example: response = client.get_queue_attributes(
        QueueUrl='string',
        AttributeNames=[
            'All'|'Policy'|'VisibilityTimeout'|'MaximumMessageSize'|'MessageRetentionPeriod'|'ApproximateNumberOfMessages'|'ApproximateNumberOfMessagesNotVisible'|'CreatedTimestamp'|'LastModifiedTimestamp'|'QueueArn'|'ApproximateNumberOfMessagesDelayed'|'DelaySeconds'|'ReceiveMessageWaitTimeSeconds'|'RedrivePolicy'|'FifoQueue'|'ContentBasedDeduplication'|'KmsMasterKeyId'|'KmsDataKeyReusePeriodSeconds',
        ]
    )

    :type QueueUrl: string
    :param QueueUrl: [REQUIRED]
            The URL of the Amazon SQS queue whose attribute information is retrieved.
            Queue URLs are case-sensitive.

    :type AttributeNames: list
    :param AttributeNames: A list of attributes for which to retrieve information.
            Note
            In the future, new attributes might be added. If you write code that calls this action, we recommend that you structure your code so that it can handle new attributes gracefully.
            The following attributes are supported:
            All - Returns all values.
            ApproximateNumberOfMessages - Returns the approximate number of visible messages in a queue. For more information, see Resources Required to Process Messages in the Amazon SQS Developer Guide .
            ApproximateNumberOfMessagesDelayed - Returns the approximate number of messages that are waiting to be added to the queue.
            ApproximateNumberOfMessagesNotVisible - Returns the approximate number of messages that have not timed-out and aren't deleted. For more information, see Resources Required to Process Messages in the Amazon SQS Developer Guide .
            CreatedTimestamp - Returns the time when the queue was created in seconds (epoch time ).
            DelaySeconds - Returns the default delay on the queue in seconds.
            LastModifiedTimestamp - Returns the time when the queue was last changed in seconds (epoch time ).
            MaximumMessageSize - Returns the limit of how many bytes a message can contain before Amazon SQS rejects it.
            MessageRetentionPeriod - Returns the length of time, in seconds, for which Amazon SQS retains a message.
            Policy - Returns the policy of the queue.
            QueueArn - Returns the Amazon resource name (ARN) of the queue.
            ReceiveMessageWaitTimeSeconds - Returns the length of time, in seconds, for which the ReceiveMessage action waits for a message to arrive.
            RedrivePolicy - Returns the parameters for dead letter queue functionality of the source queue. For more information about the redrive policy and dead letter queues, see Using Amazon SQS Dead Letter Queues in the Amazon SQS Developer Guide .
            VisibilityTimeout - Returns the visibility timeout for the queue. For more information about the visibility timeout, see Visibility Timeout in the Amazon SQS Developer Guide .
            The following attributes apply only to server-side-encryption :
            KmsMasterKeyId - Returns the ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom CMK. For more information, see Key Terms .
            KmsDataKeyReusePeriodSeconds - Returns the length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again.
            The following attributes apply only to FIFO (first-in-first-out) queues :
            FifoQueue - Returns whether the queue is FIFO. For more information, see FIFO Queue Logic in the Amazon SQS Developer Guide .
            Note
            To determine whether a queue is FIFO , you can check whether QueueName ends with the .fifo suffix.
            ContentBasedDeduplication - Returns whether content-based deduplication is enabled for the queue. For more information, see Exactly-Once Processing in the Amazon SQS Developer Guide .
            (string) --

    :rtype: dict
    :return: {
        'Attributes': {
            'string': 'string'
        }
    }

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

    """
    pass


def mongodb_int_filter(base_field, base_field_type):
    """Prepare filters (kwargs{}) for django queryset
    where fields contain digits are checked like = | > | >= | < | <=

    >>> mongodb_int_filter(10, '1')
    10.0
    >>> mongodb_int_filter(10, '2')
    {'$gt': 10.0}
    >>> mongodb_int_filter(10, '3')
    {'$gte': 10.0}
    >>> mongodb_int_filter(10, '4')
    {'$lt': 10.0}
    """
    q = ''
    if base_field != '':
        if base_field_type == '1':
            q = float(base_field)
        if base_field_type == '2':
            q = {'$gt': float(base_field)}
        if base_field_type == '3':
            q = {'$gte': float(base_field)}
        if base_field_type == '4':
            q = {'$lt': float(base_field)}
        if base_field_type == '5':
            q = {'$lte': float(base_field)}
    return q


def output_text(account, all_data, show_hourly=False):
    """Format data to get a readable output."""
    print(
        """
#################################
# Hydro Quebec data for account #
# {}
#################################"""
        .format(account))
    for contract, data in all_data.items():
        data['contract'] = contract
        if data['period_total_bill'] is None:
            data['period_total_bill'] = 0.0
        if data['period_projection'] is None:
            data['period_projection'] = 0.0
        if data['period_mean_daily_bill'] is None:
            data['period_mean_daily_bill'] = 0.0
        output = """
----------------------------------------------------------------

Contract: {d[contract]}
===================

Balance: {d[balance]:.2f} $

Period Info
===========
Period day number:      {d[period_length]:d}
Period total days:      {d[period_total_days]:d} days

Period current bill
===================
Total Bill:             {d[period_total_bill]:.2f} $
Projection bill:        {d[period_projection]:.2f} $
Mean Daily Bill:        {d[period_mean_daily_bill]:.2f} $

Total period consumption
========================
Lower price:            {d[period_lower_price_consumption]:.2f} kWh
Higher price:           {d[period_higher_price_consumption]:.2f} kWh
Total:                  {d[period_total_consumption]:.2f} kWh
Mean daily:             {d[period_mean_daily_consumption]:.2f} kWh"""
        print(output.format(d=data))
        if data.get('period_average_temperature') is not None:
            output2 = (
                'Temperature:            {d[period_average_temperature]:d} °C')
            print(output2.format(d=data))
        if data.get('yesterday_average_temperature') is not None:
            output3 = """
Yesterday consumption
=====================
Temperature:            {d[yesterday_average_temperature]:d} °C
Lower price:            {d[yesterday_lower_price_consumption]:.2f} kWh
Higher price:           {d[yesterday_higher_price_consumption]:.2f} kWh
Total:                  {d[yesterday_total_consumption]:.2f} kWh"""
            print(output3.format(d=data))
        if show_hourly:
            msg = """
Yesterday consumption details
-----------------------------
   Hour  | Temperature | Lower price consumption | Higher price consumption | total comsumption
"""
            for hdata in data['yesterday_hourly_consumption']:
                msg += (
                    """{d[hour]} | {d[temp]:8d} °C | {d[lower]:19.2f} kWh | {d[high]:20.2f} kWh | {d[total]:.2f} kWh
"""
                    .format(d=hdata))
            print(msg)
        if data['annual_total_bill']:
            output3 = """
    Annual Total
    ============

    Start date:             {d[annual_date_start]}
    End date:               {d[annual_date_end]}
    Total bill:             {d[annual_total_bill]} $
    Mean daily bill:        {d[annual_mean_daily_bill]} $
    Total consumption:      {d[annual_total_consumption]} kWh
    Mean dailyconsumption:  {d[annual_mean_daily_consumption]} kWh
    kWh price:              {d[annual_kwh_price_cent]} ¢
    """
            print(output3.format(d=data))


def extract_args(line):
    """Parse argument strings from all outer parentheses in a line of code.

    Parameters
    ----------
    line : str
        A line of code

    Returns
    -------
    list of strings
        Contents of the outer parentheses

    Example
    -------
    >>> line = 'foo(bar, baz), "a", my(func)'
    >>> extract_args(line)
    ['bar, baz', 'func']

    """
    stack = 0
    startIndex = None
    results = []
    for i, c in enumerate(line):
        if c == '(':
            if stack == 0:
                startIndex = i + 1
            stack += 1
        elif c == ')':
            stack -= 1
            if stack == 0:
                results.append(line[startIndex:i])
    return results


def add_output(summary_output, long_output, helper):
    """
    if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report
    """
    if summary_output != '':
        helper.add_summary(summary_output)
    helper.add_long_output(long_output)


def marginal_zero(repertoire, node_index):
    """Return the marginal probability that the node is OFF."""
    index = [slice(None)] * repertoire.ndim
    index[node_index] = 0
    return repertoire[tuple(index)].sum()


def isFirstNumSmall(num1, num2):
    """첫 번째 수가 두 번째 수보다 작은 수임을 확인합니다"""
    ck = False
    if num1 < num2:
        ck = True
    return ck


def save(name, content, metadata=None):
    """Save `content` in a file named `name`.

        :parameters:
          - `name`: The name of the file.
          - `content`: A file-like object, string, or bytes.
          - `metadata`: Metadata dictionary to be saved with the file.

        :returns: The id of the saved file.

        """
    raise NotImplementedError


@staticmethod
def normalize_one(xi, learner_param, idf):
    """
        The maximum index of xi should be less
        or equal to the weight vector size.
        """
    norm = 0
    word_count = 0
    i = 0
    while xi[i].index != -1:
        idx = xi[i].index - 1
        if learner_param.binary_feature:
            xi[i].value = xi[i].value != 0
        word_count += abs(xi[i].value)
        if learner_param.inverse_document_frequency and idx < len(idf):
            xi[i].value *= idf[idx]
        norm += xi[i].value * xi[i].value
        i += 1
    norm **= 0.5
    if learner_param.term_frequency:
        i = 0
        while xi[i].index != -1:
            xi[i].value /= word_count
            i += 1
    if learner_param.inst_normalization:
        i = 0
        while xi[i].index != -1:
            xi[i].value /= norm
            i += 1


def tabulate_endpoints_sparse(walks):
    """
    Compute the endpoint of each walk that is provided and return a dictionary
    that maps to each possible endpoint the number of walks (1 or more) that
    end in this endpoint. This implementation uses a Python `dict`.
    """
    endpoints = {}
    for walk in walks:
        x, y = 0, 0
        i = 0
        quarter_plane = True
        for step in walk:
            x += step.x
            y += step.y
            i += 1
            if x < 0 or y < 0:
                quarter_plane = False
                break
        if quarter_plane:
            if not (x, y) in endpoints:
                endpoints[x, y] = 0
            endpoints[x, y] += 1
    return endpoints


def itemsReceived(event):
    """
        Called when an items notification has been received for a node.

        An item can be an element named C{item} or C{retract}. Respectively,
        they signal an item being published or retracted, optionally
        accompanied with an item identifier in the C{id} attribute.

        @param event: The items event.
        @type event: L{ItemsEvent<wokkel.pubsub.ItemsEvent>}
        """


@classmethod
def namespace_exists(cls, path, target):
    """Return whether the given namespace exists."""
    path_, namespaces = cls.__get_helper(target, path)
    return path_ in namespaces


def _buckets_resolver(obj, path):
    """Resolve bucket paths."""
    bucket = obj[int(path)]
    return bucket, lambda obj, path: (obj.files[int(path)], None)


def remove_invalid_char(text):
    """去除字符串中的无效字符，一般用于保存文件时保证文件名的有效性.

    :param str text: 待处理的字符串
    :return: 处理后的字符串
    :rtype: str
    """
    invalid_char_list = ['/', '\\', ':', '*', '?', '"', '<', '>', '|', '\n']
    res = ''
    for char in text:
        if char not in invalid_char_list:
            res += char
    return res


def get_params():
    """Parse and analyse command line parameters."""
    cnt = 0.9
    sensList = []
    for i in range(1, 9):
        sensList.append(float(i))
        for j in range(1, 10):
            fval = float(i + float(j / 10.0))
            if fval <= 8.5:
                sensList.append(fval)
    import argparse
    sonicparanoid_usage = """
Define --input-directory if you want to find orthologs for (at least 3) species in the input directory.
"""
    parser = argparse.ArgumentParser(description='SonicParanoid 1.0', usage
        ='%(prog)s -i <INPUT_DIRECTORY> -o <OUTPUT_DIRECTORY>[options]',
        prog='sonicparanoid.py')
    parser.add_argument('-i', '--input-directory', type=str, required=True,
        help=
        "Directory containing the proteomes (in FASTA format) of the species to be compared. NOTE: The file names MUST NOT contain the '-' nor '.' characters"
        , default=None)
    parser.add_argument('-o', '--output-directory', type=str, required=True,
        help='The directory in which the results will be stored.', default=None
        )
    parser.add_argument('-d', '--debug', required=False, help=
        'Output debug information.', default=False, action='store_true')
    args = parser.parse_args()
    return args, parser


def define(hub):
    """
    Define how the onfail requisite should behave
    """
    return {'result': False}


@classmethod
def _parse_task_item(cls, item):
    """Parse point/name:state or name.point:state syntax."""
    if ':' in item:
        head, state_str = item.rsplit(':', 1)
    else:
        head, state_str = item, None
    if '/' in head:
        point_str, name_str = head.split('/', 1)
    elif '.' in head:
        name_str, point_str = head.split('.', 1)
    else:
        name_str, point_str = head, None
    return point_str, name_str, state_str


def tag_resource(ResourceArn=None, Tags=None):
    """
    An API operation for adding tags to a resource.
    See also: AWS API Documentation

    :example: response = client.tag_resource(
        ResourceArn='string',
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type ResourceArn: string
    :param ResourceArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the resource. Tagging is only supported for directories.

    :type Tags: list
    :param Tags: [REQUIRED]
            A list of tag key-value pairs.
            (dict) --The tag structure that contains a tag key and value.
            Key (string) --The key that is associated with the tag.
            Value (string) --The value that is associated with the tag.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def replace_in_file(filename, old_text, new_text):
    """"replace a string in the file with another string"""
    lines = []
    try:
        with open(filename, 'r') as f:
            lines = list(f)
    except IOError:
        print('File %s does not exist.' % filename)
    if lines:
        with open(filename, 'w') as f:
            for line in lines:
                f.write(line.replace(old_text, new_text))


@classmethod
def decode_ssh_public(cls, packet):
    """Decode an SSH format U2F Ed25519 public key"""
    public_value = packet.get_string()
    application = packet.get_string()
    return public_value, application


def _xds_version(xds_output_list):
    """Return the version of XDS which has been run."""
    for line in xds_output_list:
        if 'XDS VERSION' in line:
            return line.split('XDS VERSION')[1].split(')')[0].strip()
        if 'XDS' in line and 'VERSION' in line:
            return line.split('(VERSION')[1].split(')')[0].strip()
    raise RuntimeError('XDS version not found')


@classmethod
def create(cls):
    """Create new user database entry"""
    return cls(None)


def plural(n):
    """Utility function to optionally pluralize words based on the value of n.
    """
    if n == 1:
        return ''
    else:
        return 's'


def replace_base_url_in_base_tag(index, base_url):
    """Replace base URL at base tag if present.

    Keyword arguments:
        index (string): An index for requested revision.
        base_url (string): A base URL to replace.

    Returns:
        An index with replaced `href` attribute at `base` tag`.

    """
    base = '<base href="'
    start = index.find(base)
    if start is -1:
        return index
    start += len(base)
    end = index.index('"', start)
    return index[:start] + base_url + index[end:]


def load(obj, cls, default_factory):
    """Create or load an object if necessary.

    Parameters
    ----------
    obj : `object` or `dict` or `None`
    cls : `type`
    default_factory : `function`

    Returns
    -------
    `object`
    """
    if obj is None:
        return default_factory()
    if isinstance(obj, dict):
        return cls.load(obj)
    return obj


def add_common_parser_args(parser):
    """Parse CLI common login and repo arguments."""
    parser.add_argument('repository', help=
        'Repository name to generate the Changelog for, in the form user/repo or org/repo (e.g. spyder-ide/spyder)'
        )
    parser.add_argument('-u', '--username', action='store', dest='username',
        default='', help='Github user name')
    parser.add_argument('-p', '--password', action='store', dest='password',
        default='', help='Github user password')
    parser.add_argument('-t', '--token', action='store', dest='token',
        default='', help='Github access token')
    parser.add_argument('-zt', '--zenhub-token', action='store', dest=
        'zenhub_token', default='', help='Zenhub access token')
    return parser


def _convert_gather(builder, node, graph, err):
    """
    convert to CoreML Gather Along Axis Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4296
    """
    axis = node.attrs.get('axis', 0)
    if len(node.inputs) != 2:
        err.unsupported_op_configuration(builder, node, graph,
            'Error in ONNX model: Gather expects two inputs')
    if node.inputs[0] in node.input_tensors and node.inputs[0
        ] not in graph.constants_loaded:
        value = node.input_tensors[node.inputs[0]]
        builder.add_load_constant_nd(name=node.name + '_load_data',
            output_name=node.inputs[0], constant_value=value, shape=[1] if
            value.shape == () else value.shape)
        graph.constants_loaded.add(node.inputs[0])
    if node.inputs[1] in node.input_tensors and node.inputs[1
        ] not in graph.constants_loaded:
        value = node.input_tensors[node.inputs[1]]
        builder.add_load_constant_nd(name=node.name + '_load_indices',
            output_name=node.inputs[1], constant_value=value, shape=[1] if
            value.shape == () else value.shape)
        graph.constants_loaded.add(node.inputs[1])
    builder.add_gather(name=node.name, input_names=[node.inputs[0], node.
        inputs[1]], output_name=node.outputs[0], axis=axis)


def port_for_scheme(scheme):
    """Calculate port based on ``scheme`` name. If scheme and port matches,
    port is left empty. Otherwise `port` is explicitly set to port number and
    returned as a string.

    ``scheme``, byte-string.
    """
    if scheme == b'http':
        return 80
    elif scheme == b'https':
        return 443
    else:
        return None


def die(why):
    """Describe what happened and bomb out."""
    msg = str(why).replace('\n', '')
    print('status {0}'.format(msg))
    exit(1)


@staticmethod
def _import_type(line):
    """If the current line is an import line it will return its type (from or straight)"""
    if 'isort:skip' in line:
        return
    elif line.startswith('import '):
        return 'straight'
    elif line.startswith('from '):
        return 'from'


def broadcast_sub(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Returns element-wise difference of the input arrays with broadcasting.

    `broadcast_minus` is an alias to the function `broadcast_sub`.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_sub(x, y) = [[ 1.,  1.,  1.],
                              [ 0.,  0.,  0.]]

       broadcast_minus(x, y) = [[ 1.,  1.,  1.],
                                [ 0.,  0.,  0.]]

    Supported sparse operations:

       broadcast_sub/minus(csr, dense(1D)) = dense
       broadcast_sub/minus(dense(1D), csr) = dense

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L106

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

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

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


def get_record_names(form, field):
    """Return names of all the authority records already existing"""
    return form._cw.execute('Any P WHERE NE parts P, NE is NameEntry').rows


def assembleLyrics(streamIn, lineNumber=1):
    """
    Concatenate text from a stream. The Stream is automatically flattened.

    The `lineNumber` parameter determines which line of text is assembled.

    >>> s = stream.Stream()
    >>> n1 = note.Note()
    >>> n1.lyric = 'Hi'
    >>> n2 = note.Note()
    >>> n2.lyric = 'there'
    >>> s.append(n1)
    >>> s.append(n2)
    >>> text.assembleLyrics(s)
    'Hi there'
    """
    word = []
    words = []
    noteStream = streamIn.flat.notesAndRests
    for n in noteStream:
        try:
            lyricObj = n.lyrics[lineNumber - 1]
        except IndexError:
            continue
        if lyricObj.text != '_':
            if lyricObj.syllabic in ['begin', 'middle']:
                if lyricObj.text is not None:
                    word.append(lyricObj.text)
            elif lyricObj.syllabic in ['end', 'single', None]:
                if lyricObj.text is not None:
                    word.append(lyricObj.text)
                words.append(''.join(word))
                word = []
            else:
                raise Exception('no known Text syllabic setting: %s' %
                    lyricObj.syllabic)
    return ' '.join(words)


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

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

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


@staticmethod
def _checkMemberName(name):
    """
        See if a member name indicates that it should be private.

        Private variables in Python (starting with a double underscore but
        not ending in a double underscore) and bed lumps (variables that
        are not really private but are by common convention treated as
        protected because they begin with a single underscore) get Doxygen
        tags labeling them appropriately.
        """
    assert isinstance(name, str)
    restrictionLevel = None
    if not name.endswith('__'):
        if name.startswith('__'):
            restrictionLevel = 'private'
        elif name.startswith('_'):
            restrictionLevel = 'protected'
    return restrictionLevel


@classmethod
def search_patient_code(cls, name, clause):
    """Retrieve the Patient Identification Code"""
    res = []
    value = clause[2]
    res.append(('patient.puid', clause[1], value))
    return res


def group_comments_by_round(comments, ranking=0):
    """
    Group comments by the round to which they belong
    """
    comment_rounds = {}
    ordered_comment_round_names = []
    for comment in comments:
        comment_round_name = ranking and comment[11] or comment[7]
        if comment_round_name not in comment_rounds:
            comment_rounds[comment_round_name] = []
            ordered_comment_round_names.append(comment_round_name)
        comment_rounds[comment_round_name].append(comment)
    return [(comment_round_name, comment_rounds[comment_round_name]) for
        comment_round_name in ordered_comment_round_names]


def is_a_mapping(var, allow_none=False):
    """ Returns True if var is a dictionary # TODO: ordered dict
    """
    return isinstance(var, dict) or var is None and allow_none


def nl2br(s):
    """Related to string operation

    >>> nl2br('abc
xyz')
    'abc
xyz'
    """
    return '
'.join(s.split('\n'))


def pres2alt(pressure):
    """
    Determine altitude from site pressure.

    Parameters
    ----------
    pressure : numeric
        Atmospheric pressure (Pascals)

    Returns
    -------
    altitude : numeric
        Altitude in meters above sea level

    Notes
    ------
    The following assumptions are made

    ============================   ================
    Parameter                      Value
    ============================   ================
    Base pressure                  101325 Pa
    Temperature at zero altitude   288.15 K
    Gravitational acceleration     9.80665 m/s^2
    Lapse rate                     -6.5E-3 K/m
    Gas constant for air           287.053 J/(kgK)
    Relative Humidity              0%
    ============================   ================

    References
    -----------
    .. [1] "A Quick Derivation relating altitude to air pressure" from
       Portland State Aerospace Society, Version 1.03, 12/22/2004.
    """
    alt = 44331.5 - 4946.62 * pressure ** 0.190263
    return alt


@classmethod
def convert(cls, other, **kwargs):
    """Create from other class."""
    self = cls(len(other))
    self.update(other, **kwargs)
    return self


def parseCommandLine(parser):
    """Parse command line"""
    parser.add_argument('--remove', '-r', action='store_true', dest=
        'removeFlag', default=False, help=
        'remove all diskimgr configuration files')
    args = parser.parse_args()
    return args


def call(f, *args):
    """Returns the result of calling its first argument with the remaining
arguments. This is occasionally useful as a converging function for
R.converge: the first branch can produce a function while the
remaining branches produce values to be passed to that function as its
arguments"""
    if len(args) > 1:
        return f(*args)
    return lambda *args: f(*args)


def get_file_upload_url(AssignmentId=None, QuestionIdentifier=None):
    """
    The GetFileUploadURL operation generates and returns a temporary URL. You use the temporary URL to retrieve a file uploaded by a Worker as an answer to a FileUploadAnswer question for a HIT. The temporary URL is generated the instant the GetFileUploadURL operation is called, and is valid for 60 seconds. You can get a temporary file upload URL any time until the HIT is disposed. After the HIT is disposed, any uploaded files are deleted, and cannot be retrieved.
    See also: AWS API Documentation

    :example: response = client.get_file_upload_url(
        AssignmentId='string',
        QuestionIdentifier='string'
    )

    :type AssignmentId: string
    :param AssignmentId: [REQUIRED]
            The ID of the assignment that contains the question with a FileUploadAnswer.

    :type QuestionIdentifier: string
    :param QuestionIdentifier: [REQUIRED]
            The identifier of the question with a FileUploadAnswer, as specified in the QuestionForm of the HIT.

    :rtype: dict
    :return: {
        'FileUploadURL': 'string'
    }

    """
    pass


def __getattr__(version_id):
    """Returns the version of an object corresponding to the version id.

        The object returned is of 'IVersionData'.
        """


def create_deployment(StackId=None, AppId=None, InstanceIds=None, LayerIds=
    None, Command=None, Comment=None, CustomJson=None):
    """
    Runs deployment or stack commands. For more information, see Deploying Apps and Run Stack Commands .
    See also: AWS API Documentation

    :example: response = client.create_deployment(
        StackId='string',
        AppId='string',
        InstanceIds=[
            'string',
        ],
        LayerIds=[
            'string',
        ],
        Command={
            'Name': 'install_dependencies'|'update_dependencies'|'update_custom_cookbooks'|'execute_recipes'|'configure'|'setup'|'deploy'|'rollback'|'start'|'stop'|'restart'|'undeploy',
            'Args': {
                'string': [
                    'string',
                ]
            }
        },
        Comment='string',
        CustomJson='string'
    )

    :type StackId: string
    :param StackId: [REQUIRED]
            The stack ID.

    :type AppId: string
    :param AppId: The app ID. This parameter is required for app deployments, but not for other deployment commands.

    :type InstanceIds: list
    :param InstanceIds: The instance IDs for the deployment targets.
            (string) --

    :type LayerIds: list
    :param LayerIds: The layer IDs for the deployment targets.
            (string) --

    :type Command: dict
    :param Command: [REQUIRED]
            A DeploymentCommand object that specifies the deployment command and any associated arguments.
            Name (string) -- [REQUIRED]Specifies the operation. You can specify only one command.
            For stacks, the following commands are available:
            execute_recipes : Execute one or more recipes. To specify the recipes, set an Args parameter named recipes to the list of recipes to be executed. For example, to execute phpapp::appsetup , set Args to {'recipes':['phpapp::appsetup']} .
            install_dependencies : Install the stack's dependencies.
            update_custom_cookbooks : Update the stack's custom cookbooks.
            update_dependencies : Update the stack's dependencies.
            Note
            The update_dependencies and install_dependencies commands are supported only for Linux instances. You can run the commands successfully on Windows instances, but they do nothing.
            For apps, the following commands are available:
            deploy : Deploy an app. Ruby on Rails apps have an optional Args parameter named migrate . Set Args to {'migrate':['true']} to migrate the database. The default setting is {'migrate':['false']}.
            rollback Roll the app back to the previous version. When you update an app, AWS OpsWorks Stacks stores the previous version, up to a maximum of five versions. You can use this command to roll an app back as many as four versions.
            start : Start the app's web or application server.
            stop : Stop the app's web or application server.
            restart : Restart the app's web or application server.
            undeploy : Undeploy the app.
            Args (dict) --The arguments of those commands that take arguments. It should be set to a JSON object with the following format:
            {'arg_name1' : ['value1', 'value2', ...], 'arg_name2' : ['value1', 'value2', ...], ...}
            The update_dependencies command takes two arguments:
            upgrade_os_to - Specifies the desired Amazon Linux version for instances whose OS you want to upgrade, such as Amazon Linux 2014.09 . You must also set the allow_reboot argument to true.
            allow_reboot - Specifies whether to allow AWS OpsWorks Stacks to reboot the instances if necessary, after installing the updates. This argument can be set to either true or false . The default value is false .
            For example, to upgrade an instance to Amazon Linux 2014.09, set Args to the following.
            { 'upgrade_os_to':['Amazon Linux 2014.09'], 'allow_reboot':['true'] }
            (string) --
            (list) --
            (string) --

    :type Comment: string
    :param Comment: A user-defined comment.

    :type CustomJson: string
    :param CustomJson: A string that contains user-defined, custom JSON. It is used to override the corresponding default stack configuration JSON values. The string should be in the following format:
            '{'key1': 'value1', 'key2': 'value2',...}'
            For more information on custom JSON, see Use Custom JSON to Modify the Stack Configuration Attributes .

    :rtype: dict
    :return: {
        'DeploymentId': 'string'
    }

    """
    pass


def demo_appraise():
    """
    Run demonstration and plot results

    Arguments:
    """
    raise NotImplementedError


def getAnnotation(key, default):
    """Given a key, get annotation object from module.

        The annotation key is a dotted name. All dots are replaced
        with underscores and the result is pre and post-fixed by
        double underscore. For instance 'grok.name' will be translated
        to '__grok_name__'.

        Uses default if no such annotation found.
        """


def check_node_attributes(pattern, node, *attributes):
    """
    Searches match in attributes against given pattern and if
    finds the match against any of them returns True.
    """
    for attribute_name in attributes:
        attribute = node.get(attribute_name)
        if attribute is not None and pattern.search(attribute):
            return True
    return False


@classmethod
def desc_sum(cls, desc):
    """Minimal length that will be sufficient to store the given description"""
    raise NotImplementedError()


@staticmethod
def grant_privileges_commands(rolename: str, schema: str, read_write: bool
    ) ->list:
    """Creates commands for granting privileges for accessing database objects to a role/user"""
    x_role = '"' + rolename + '"'
    x_schema = '"' + schema + '"'
    statements = list()
    statements.append(' '.join(['GRANT USAGE ON SCHEMA', x_schema, 'TO',
        x_role]))
    statements.append(' '.join(['GRANT SELECT ON ALL SEQUENCES IN SCHEMA',
        x_schema, 'TO', x_role]))
    statements.append(' '.join(['GRANT SELECT ON ALL TABLES IN SCHEMA',
        x_schema, 'TO', x_role]))
    if read_write:
        statements.append(' '.join([
            'GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA', x_schema, 'TO',
            x_role]))
        statements.append(' '.join([
            'GRANT USAGE ON ALL SEQUENCES IN SCHEMA', x_schema, 'TO', x_role]))
        statements.append(' '.join(['GRANT INSERT ON ALL TABLES IN SCHEMA',
            x_schema, 'TO', x_role]))
        if not schema.startswith('audit'):
            statements.append(' '.join([
                'GRANT UPDATE ON ALL TABLES IN SCHEMA', x_schema, 'TO',
                x_role]))
            statements.append(' '.join([
                'GRANT DELETE ON ALL TABLES IN SCHEMA', x_schema, 'TO',
                x_role]))
    return statements


def delete_application(ApplicationName=None, TerminateEnvByForce=None):
    """
    Deletes the specified application along with all associated versions and configurations. The application versions will not be deleted from your Amazon S3 bucket.
    See also: AWS API Documentation

    Examples
    The following operation deletes an application named my-app:
    Expected Output:

    :example: response = client.delete_application(
        ApplicationName='string',
        TerminateEnvByForce=True|False
    )

    :type ApplicationName: string
    :param ApplicationName: [REQUIRED]
            The name of the application to delete.

    :type TerminateEnvByForce: boolean
    :param TerminateEnvByForce: When set to true, running environments will be terminated before deleting the application.

    :return: response = client.delete_application(
        ApplicationName='my-app',
    )

    print(response)

    """
    pass


@classmethod
def insert_batch(cls, batch):
    """
        Inserts batch into database
        :param batch: Batch of tuples to insert
        :return:
        """
    if batch:
        cls.get_database(for_write=True).insert_tuples(cls, batch,
            formatted=cls.sync_formatted_tuples)


def convert_bool(string):
    """Check whether string is boolean.
    """
    if string == 'True':
        return True, True
    elif string == 'False':
        return True, False
    else:
        return False, False


@staticmethod
def format_filter(proprty, operator, value):
    """Creates a filter expression """
    return '{} {} {}'.format(proprty.name, operator, proprty.typ.traits.
        to_literal(value))


@classmethod
def can_create_at(cls, parent):
    """
        Checks if this page type can be created as a subpage under a parent
        page instance.
        """
    can_create = cls.is_creatable and cls.can_exist_under(parent)
    if cls.max_count is not None:
        can_create = can_create and cls.objects.count() < cls.max_count
    if cls.max_count_per_parent is not None:
        can_create = can_create and parent.get_children().type(cls).count(
            ) < cls.max_count_per_parent
    return can_create


def calculate_k(R, N):
    """
    Calculates the the Fisher concentration parameter (k) based on the number of
    vectors and the resultant vector length. This calculation occurs within the
    fisher_mean() function. Use of this function can be helpful when R and N
    are available, but the vectors themselves are not.

    Parameters
    ----------
    R : the resultant vector length
    N : number of vectors

    Returns
    -------
    k : the Fisher concentration parameter
    """
    if N != R:
        k = (N - 1.0) / (N - R)
    else:
        k = 'inf'
    return k


def is_empty(G):
    """Returns ``True`` if ``G`` has no edges.

        Parameters
        ----------

        G : graph
            A DyNetx graph.

        Returns
        -------

        bool
            ``True`` if ``G`` has no edges, and ``False`` otherwise.

        Notes
        -----
        An empty graph can have nodes but not edges. The empty graph with zero
        nodes is known as the null graph. This is an O(n) operation where n is the
        number of nodes in the graph.
        """
    return not any(G.adj.values())


def option_name(path, delimiter='--'):
    """returns a cli option name from attribute path"""
    return '--{}'.format(delimiter.join(path).replace('_', '-'))


def is_related(field):
    """
    Test if a given field is a related field.

    :param DjangoField field: A reference to the given field.
    :rtype: boolean
    :returns: A boolean value that is true only if the given field is related.
    """
    return 'django.db.models.fields.related' in field.__module__


@classmethod
def from_index(cls, *args, **kwargs):
    """Create index from another index. """
    return cls(*args, **kwargs)


@staticmethod
def defaultSymbol():
    """
        Returns the default symbol path for this node.

        :returns: symbol path (or resource).
        """
    return ':/symbols/qemu_guest.svg'


def pad_rectangle(rect):
    """
    Decrease rectangle dimensions to show whitespace in treemap

    :param rect: Dictionary of rectangle dimensions to be decreased to enable
        whitespace padding in treemap visualization
    :return: Dictionary of updated rectangle dimensions
    """
    if rect['dx'] > 2:
        rect['x'] += 1
        rect['dx'] -= 2
    if rect['dy'] > 2:
        rect['y'] += 1
        rect['dy'] -= 2


def compute_exception_message(default_message, extra_message=None):
    """Returns an error message with an extra error message if provided.

    Otherwise returns the default error message.
    """
    message = default_message
    if extra_message:
        message = '{0} -- {1}'.format(default_message, extra_message)
    return message


def straceback():
    """Returns a string with the traceback."""
    import traceback
    return traceback.format_exc()


def get_field(d, field_list):
    """get the subfield associated to a list of elastic fields
        E.g. ['file', 'filename'] to d['file']['filename']
    """
    if isinstance(field_list, str):
        return d[field_list]
    else:
        idx = d.copy()
        for field in field_list:
            idx = idx[field]
        return idx


def _cc(recipient):
    """
    Returns a query item matching messages that have certain recipients in
    the cc field.

    Args:
        recipient (str): The recipient in the cc field to match.

    Returns:
        The query string.

    """
    return f'cc:{recipient}'


def studyItemPixmapNOk():
    """
    Get the reference pixmap for items of this module.
    """
    return 'ADAO_small_rouge.png'


def add_rect_filled(pic, x, y, w, h, col):
    """Draw a filled rectangle of Color col, width w, and height h
    on Picture pic. The upper left corner of the rectangle is at (x, y)."""
    pic.add_rect_filled(col, x, y, w, h)


def schedule(project, spider_name, **spider_args):
    """Schedule a spider for the given project"""


def crop(img, crop_box):
    """Returns a cropped image for crop_box = (minRow, maxRow, minCol, maxCol)"""
    minRow, minCol, maxRow, maxCol = crop_box
    return img[minRow:maxRow, minCol:maxCol]


def convert_to_bool(text):
    """ Convert a few common variations of "true" and "false" to boolean

    :param text: string to test
    :return: boolean
    :raises: ValueError
    """
    try:
        return bool(int(text))
    except:
        pass
    text = str(text).lower()
    if text == 'true':
        return True
    if text == 'yes':
        return True
    if text == 'false':
        return False
    if text == 'no':
        return False
    raise ValueError


def includes_excludes(patterns, message):
    """
    Return a dict of included patterns and a dict of excluded patterns from a
    sequence of `patterns` strings and a `message` setting the message as
    value in the returned mappings. Ignore pattern as comments if prefixed
    with #. Use an empty string is message is None.
    """
    message = message or ''
    BANG = '!'
    POUND = '#'
    included = {}
    excluded = {}
    if not patterns:
        return included, excluded
    for pat in patterns:
        pat = pat.strip()
        if not pat or pat.startswith(POUND):
            continue
        if pat.startswith(BANG):
            cpat = pat.lstrip(BANG)
            if cpat:
                excluded[cpat] = message
            continue
        else:
            included.add[pat] = message
    return included, excluded


def _flush_pipe(c):
    """Flush the content of a pipe."""
    try:
        while c.poll():
            c.recv_bytes()
    except EOFError:
        pass


@classmethod
def from_file(cls, filepath, logger=None):
    """Read config from a file."""
    with open(filepath, 'r') as file_stream:
        return cls(file_stream.read(), logger)


def calc_sigma_general(wfh, wfe, N_state, N_statec, model, Ntotal2d, j,
    Well_boundary):
    """This function calculates `net' areal charge density
    n-type dopants lead to -ve charge representing electrons, and additionally
    +ve ionised donors."""
    sigma = model.dop[Well_boundary[j - 1, 1]:Well_boundary[j + 1, 0]
        ] * model.dx
    if Ntotal2d > 0:
        for j in range(0, model.subnumber_e, 1):
            sigma -= N_statec[j] * wfe[j] ** 2
    else:
        for i in range(0, model.subnumber_h, 1):
            sigma += N_state[i] * wfh[i] ** 2
    return sigma


@classmethod
def equalsMask(cls, obis, ic):
    """Check OBIS codes."""
    ret = False
    number = True
    if obis.find(',') != -1:
        tmp = obis.split(',')
        for it in tmp:
            if it.find('-') != -1:
                if cls.equalsMask(it, ic):
                    return True
            elif int(it) == ic:
                return True
        ret = False
    elif obis.find('-') != -1:
        number = False
        tmp = obis.split('-')
        ret = int(ic) >= int(tmp[0]) and ic <= int(tmp[1])
    elif number:
        if obis == '&':
            return ic in (0, 1, 7)
        ret = int(obis) == ic
    return ret


def model_params(model_name):
    """ Map Generator and Discriminator model name to parameter coefficients.

      Args:
        model_name (string): The name of the model corresponding to the dataset.

      Returns:
        A binary tuple value.
      """
    params_dict = {'g-mnist': (1, 28), 'g-fmnist': (1, 28), 'd-mnist': (1,
        28), 'd-fmnist': (1, 28)}
    return params_dict[model_name]


@classmethod
def _get_sensors_drive(cls, system):
    """Get storage drive sensors reading.

        :param chassis: Redfish `system` object
        :returns: returns a dict of sensor data.
        """
    sensors = {}
    for storage in system.simple_storage.get_members():
        for drive in storage.devices:
            sensor = cls._sensor2dict(drive, 'name', 'model', 'capacity_bytes')
            sensor.update(cls._sensor2dict(drive.status, 'state', 'health'))
            unique_name = '%s:%s@%s' % (drive.name, storage.identity,
                system.identity)
            sensors[unique_name] = sensor
    return sensors


def sprint(s):
    """ Print without newline and immediately update the display

        Parameters
        ----------
        s: string
            The string to print
    """
    print(s, end='', flush=True)


def multires_higher_levels_delete(modifier: str=''):
    """Deletes the higher resolution mesh, potential loss of detail

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    """
    pass


def kaccke(value):
    """
    获得value对应的keccak的hash值
    :param value:
    :return: bytes数据
    """
    from eth_utils import keccak
    return keccak(value)


def from_url(url, db=None, **kwargs):
    """
    Returns an active Redis client generated from the given database URL.

    Will attempt to extract the database id from the path url fragment, if
    none is provided.
    """
    from redis.client import Redis
    return Redis.from_url(url, db, **kwargs)


def deactivate_pipeline(pipelineId=None, cancelActive=None):
    """
    Deactivates the specified running pipeline. The pipeline is set to the DEACTIVATING state until the deactivation process completes.
    To resume a deactivated pipeline, use  ActivatePipeline . By default, the pipeline resumes from the last completed execution. Optionally, you can specify the date and time to resume the pipeline.
    See also: AWS API Documentation

    :example: response = client.deactivate_pipeline(
        pipelineId='string',
        cancelActive=True|False
    )

    :type pipelineId: string
    :param pipelineId: [REQUIRED]
            The ID of the pipeline.

    :type cancelActive: boolean
    :param cancelActive: Indicates whether to cancel any running objects. The default is true, which sets the state of any running objects to CANCELED . If this value is false, the pipeline is deactivated after all running objects finish.

    :rtype: dict
    :return: {}

    """
    pass


@staticmethod
def load(data_path):
    """
        Extract data from provided file and return it as a string.
        """
    with open(data_path, 'r') as data_file:
        raw_data = data_file.read()
    data_file.close()
    return raw_data


def retransmit_timeout(group_state: 'GroupState'):
    """
    retransmit timer associated with group GroupState object has expired
    """
    group_state.group_state_logger.debug(
        'NonQuerier CheckingMembership: retransmit_timeout')
    return


@staticmethod
def fan_out(framework: 'Framework') ->int:
    """
        Fan-Out: outgoing dependencies. (number of classes inside this component that depend on classes outside it)
        :param framework: The framework to analyze
        :return: The Fan-Out value (int)
        """
    fan_out = 0
    for _, value in framework.imports.items():
        fan_out += value
    return fan_out


def _pick_counters(log_interpretation):
    """Pick counters from a dictionary possibly containing
    step and history interpretations."""
    for log_type in ('step', 'history'):
        counters = log_interpretation.get(log_type, {}).get('counters')
        if counters:
            return counters
    else:
        return {}


def str_replace_multi(str_, chars):
    """
    replaces many chars in a string.
    :param str_: string to apply replacements
    :param chars: dict in the form {old char: new char, ...}
    """
    for old, new in chars.items():
        str_ = str_.replace(old, new)
    return str_


def create(obj):
    """
        Create a new object in the given namespace.

        :param IObject obj: A description of the object to create.

        :return Deferred(IObject): A description of the created object.
        """


def moveWidget(pageIndex, columnIndex, widgetIndex, toPage, toColumn,
    toWidget, retJson=True):
    """ Move a widget to specific position.

        @param pageIndex
        index of page the widget lies on( start from 0 )

        @param columnIndex
        index of column the widget lies on( start from 0 )

        @param widgetIndex
        index of the widget, count from top to bottom( start from 0 )

        @param toPage
        index of new page

        @param toColumn
        index of new column

        @param toWidget
        index of new widget position

        @retJson
        format return value to json format or not( default True )

        @return
        a dict contains state of process, format like:
        {
            'success': True,
            'msg': 'Move widget success.'
        }

        """


def _untranslate_snapshot_summary_view(context, snapshot):
    """Maps keys for snapshots summary view."""
    d = {}
    d['id'] = snapshot.id
    d['status'] = snapshot.status
    d['progress'] = snapshot.progress
    d['size'] = snapshot.size
    d['created_at'] = snapshot.created_at
    d['display_name'] = snapshot.name
    d['display_description'] = snapshot.description
    d['volume_id'] = snapshot.volume_id
    d['project_id'] = snapshot.project_id
    d['volume_size'] = snapshot.size
    return d


def aefetch(t_start, t_stop):
    """
    A function to fetch Kyoto AE directly from the Kyoto WDC website.
    Returns raw ascii lines obtained from the website representing the data
    in IAGA 2002 format.

    Note that, because of the higher density of the data, full date times
    are required for the start and stop time.  This is in contrast to
    other fetch functions, where hourly or three-hourly resolution allows
    for only the start and stop years and months are required as integers.

    Parameters
    ----------
    t_start : datetime.datetime
       Start time for range of requested data as a datetime object.
    t_stop : datetime.datetime
       Stop time for range of requested data as a datetime object.

    """
    try:
        import urllib.parse, urllib.request
    except ImportError:
        import urllib
        urllib.parse = urllib
        urllib.request = urllib
    deltaT = t_stop - t_start
    forminfo = {}
    forminfo['Tens'] = int(t_start.year / 10)
    forminfo['Year'] = int(t_start.year - 10 * forminfo['Tens'])
    forminfo['Month'] = t_start.month
    forminfo['Day_Tens'] = int(t_start.day / 10)
    forminfo['Days'] = int(t_start.day - 10 * forminfo['Day_Tens'])
    forminfo['Hour'] = t_start.hour
    forminfo['min'] = t_start.minute
    forminfo['Dur_Day_Tens'] = int(deltaT.days / 10)
    forminfo['Dur_Day'] = int(deltaT.days - 10 * forminfo['Dur_Day_Tens'])
    forminfo['Dur_Hour'] = int(deltaT.seconds / 3600.0)
    forminfo['Dur_Min'] = int(deltaT.seconds / 60.0 - forminfo['Dur_Hour'] *
        60.0)
    forminfo['Output'] = 'AE'
    forminfo['Out+format'] = 'IAGA2002'
    forminfo['Email'] = urllib.parse.quote('spacepy@lanl.gov')
    target = 'http://wdc.kugi.kyoto-u.ac.jp/cgi-bin/aeasy-cgi'
    data = 'Tens={0[Tens]:03d}&Year={0[Year]:d}&'.format(forminfo)
    data += 'Month={0[Month]:02d}&Day_Tens={0[Day_Tens]:d}&'.format(forminfo)
    data += 'Days={0[Days]:d}&Hour={0[Hour]:02d}&min={0[min]:02d}'.format(
        forminfo)
    data += '&Dur_Day_Tens={0[Dur_Day_Tens]:02d}&'.format(forminfo)
    data += 'Dur_Day={0[Dur_Day]:d}&Dur_Hour={0[Dur_Hour]:02d}&'.format(
        forminfo)
    data += 'Dur_Min={0[Dur_Min]:02d}&Image+Type=GIF&COLOR='.format(forminfo)
    data += 'COLOR&AE+Sensitivity=0&ASY%2FSYM++Sensitivity=0&'
    data += 'Output=AE&Out+format='.format(forminfo)
    data += 'IAGA2002&Email={0[Email]}'.format(forminfo)
    f = urllib.request.urlopen(target + '?' + data)
    lines = f.readlines()
    return lines


def variable_is_int(in_string):
    """
    Test if a variable can be cast as an integer

    :param in_string: Inbound value
    :type in_string: str
    :return: Boolean reflecting that it can or cant be cast as an integer
    :rtype: bool
    """
    try:
        int(in_string)
        return True
    except ValueError:
        return False


def hexDump(bytes):
    """ Useful utility; prints the string in hexadecimal.
	"""
    print('byte   0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F')
    num = len(bytes)
    for i in range(num):
        if i % 16 == 0:
            line = '%02X0 : ' % (i / 16)
        line += '%02X ' % ord(bytes[i])
        if (i + 1) % 16 == 0:
            print('%s: %s' % (line, repr(bytes[i - 15:i + 1])))
            line = ''
    bytes_left = num % 16
    if bytes_left:
        print('%s: %s' % (line.ljust(54), repr(bytes[-bytes_left:])))


def regression_types():
    """all the regression classes that follow the sklearn format"""
    sklearn_types = ["<class 'sklearn.linear_model.base.LinearRegression'>",
        "<class 'sklearn.linear_model.ridge.Ridge'>",
        "<class 'sklearn.kernel_ridge.KernelRidge'>",
        "<class 'sklearn.linear_model.coordinate_descent.Lasso'>",
        "<class 'sklearn.linear_model.coordinate_descent.MultiTaskLasso'>",
        "<class 'sklearn.linear_model.coordinate_descent.ElasticNet'>",
        "<class 'sklearn.linear_model.coordinate_descent.MultiTaskElasticNet'>"
        , "<class 'sklearn.linear_model.least_angle.Lars'>",
        "<class 'sklearn.linear_model.least_angle.LassoLars'>",
        "<class 'sklearn.linear_model.bayes.BayesianRidge'>",
        "<class 'sklearn.linear_model.bayes.ARDRegression'>",
        "<class 'sklearn.linear_model.logistic.LogisticRegression'>",
        "<class 'sklearn.linear_model.stochastic_gradient.SGDRegressor'>",
        "<class 'sklearn.svm.classes.SVR'>",
        "<class 'sklearn.svm.classes.NuSVR'>",
        "<class 'sklearn.svm.classes.LinearSVR'>",
        "<class 'sklearn.neural_network.multilayer_perceptron.MLPRegressor'>"]
    cheml_types = ["<class 'cheml.nn.keras.mlp.MLP_sklearn'>"]
    all_types = tuple(sklearn_types + cheml_types)
    return all_types


@classmethod
def build_from_edge_label_tuples(cls, tuples, additional_labels=None
    ) ->'Graph':
    """
        Build a graph from a iterator of edge label tuples.
        """
    graph = cls()
    graph._init_label_to_node(tuples, additional_labels)
    return graph


def vertex_weight_paste(weight_group: int=-1):
    """Copy this group’s weight to other selected verts (disabled if vertex group is locked)

    :param weight_group: Weight Index, Index of source weight in active vertex group
    :type weight_group: int
    """
    pass


def is_last_page(response):
    """
    Determine if we are at the last page of a Paged result flow
    :param response: server response
    :return: boolean indicating if we are at the last page or not
    """
    return not 'next' in response.links


def reveal():
    """Reveal all hidden UV vertices

    """
    pass


def compare_versions(x, y):
    """it will compare 2 version numbers and return the higher value
    example compare_versions('2020.10.6', '2020.3.7') will return '2020.10.6'
    return None if 2 versions are equal
    """
    try:
        a = [int(x) for x in x.split('.')[:3]]
        b = [int(x) for x in y.split('.')[:3]]
        for i in range(3):
            if a[i] > b[i]:
                return x
            elif a[i] < b[i]:
                return y
    except:
        pass
    return None


def elem_C(w, C):
    """
    Simulation Function: -C-

    Inputs
    ----------
    w = Angular frequency [1/s]
    C = Capacitance [F]
    """
    return 1 / (C * (w * 1.0j))


def teardown_paste_factories():
    """Reverse the effect of setup_paste_factories()."""
    global app_factory, filter_factory
    del app_factory
    del filter_factory


def bobby_droptables(msg):
    """ Return true if `msg` might be Bobby's cousin. """
    dangerous_characters = [';', '<', '>', '&', '|']
    for danger in dangerous_characters:
        if danger in msg:
            return True
    return False


def find_eggs_for_plat_repo(brood_client, plat_repo):
    """ Find the unique eggs for a given platform repository. Some eggs are
    listed in multiple indexed python tags, so we want to ensure that each
    egg is only referenced once to prevent duplication.

    Parameters
    ----------

    brood_client: BroodClient
        hatcher.core.brood_client.BroodClient instance

    plat_repo: SinglePlatformRepository
        hatcher.core.v*.repository.SinglePlatformRepository instance

    Returns
    -------
    dict: Containing egg metadata indexed by sha256

    """
    eggs_dict = {}
    for python_tag in sorted(brood_client.list_python_tags()):
        egg_index = plat_repo.egg_index(python_tag)
        for _, index_entry in egg_index.items():
            metadata = plat_repo.egg_metadata(python_tag, index_entry[
                'name'], '-'.join([str(index_entry['version']), str(
                index_entry['build'])]))
            sha256_key = metadata['sha256']
            if sha256_key not in eggs_dict:
                eggs_dict[sha256_key] = metadata.copy()
                eggs_dict[sha256_key]['indexed_tag'] = python_tag
    return eggs_dict


def check_valid(choices, selection):
    """Checks if {choice} is a valid selection from a menu, given {selections}

	returns -> bool:is_valid"""
    try:
        selection = int(selection)
    except:
        return False
    if selection == 99:
        return True
    if not selection in list(range(1, len(choices) + 1)):
        return False
    return True


def invoke(iterable, iteratee_name, arguments=None, keyword_args=None):
    """
     Calls the callable named by iteratee_name on each value in the iterable. Any extra arguments passed to invoke will be forwarded on to the method invocation.

     Difference with _.each, _.map: each takes in the callable object instead of callable objects' name as string. Also _.invoke returns the new iterable from values returned by the callable. In this sense this is much closer to _.map.

     params: iterable, iteratee_name, arguments [optional]
        iterable -> list, sequenece, set, dictionary, generator etc
        iteratee_name -> name of the function which is available in the score while executing the code
        arguments -> optional arguments that will be passed on to the iteratee function

    Examples
    >>> list(_.invoke([[5, 1, 7], [3, 2, 1]], 'sorted'))
    >>> [[1, 5, 7], [1, 2, 3]]
    >>> list(_.invoke([[5, 1, 7], [3, 2, 1]], 'sorted', keyword_args={"reverse":False, "key": lambda x: x if x %2 == 0 else 0}))
    >>>  [[1, 5, 7] [3, 1, 2]]
    """
    if arguments is None:
        arguments = []
    if keyword_args is None:
        keyword_args = {}
    func = eval(iteratee_name)
    for item in iterable:
        yield func(item, *arguments, **keyword_args)


def ISO8601():
    """Return the object in ISO 8601-compatible format containing
        the date, time with seconds-precision and the time zone
        identifier - see http://www.w3.org/TR/NOTE-datetime

        Dates are output as: YYYY-MM-DDTHH:MM:SSTZD
            T is a literal character.
            TZD is Time Zone Designator, format +HH:MM or -HH:MM

        The HTML4 method below offers the same formatting, but
        converts to UTC before returning the value and sets the TZD"Z"
        """


def ns_cleanup(qn):
    """ Get the tag from string like:
    {http://linux.duke.edu/metadata/repo}revision
    """
    if qn.find('}') == -1:
        return qn
    return qn.split('}')[1]


@classmethod
def get_dperp_apar(cls, x, apar, r=1):
    """
        calculate inplane lattice parameter and the out of plane lattice plane
        spacing (of the atomic planes!) from composition and relaxation

        Parameters
        ----------
        x :     float
            chemical composition parameter
        apar :  float
            inplane lattice parameter of the material below the current layer
            (onto which the present layer is strained to). This value also
            served as a reference for the relaxation parameter.
        r :     float
            relaxation parameter. 1=relaxed, 0=pseudomorphic

        Returns
        -------
        dperp : float
            perpendicular d-spacing
        apar :  float
            inplane lattice parameter
        """
    abulk = cls.abulk(x)
    aparl = apar + (abulk - apar) * r
    dperp = abulk * (1 + cls.poisson_ratio(x) * (1 - aparl / abulk)) / 4.0
    return dperp, aparl


@classmethod
def registry_exists(cls, base_klass):
    """
        Return True if the item is in the registry, False otherwise.

        :param base_klass: class for which registry will be created
        :return: boolean
        """
    is_registered = base_klass.__name__ in cls.__registry
    return is_registered


def get_association_options(defaults=None):
    """Adding arguments for the association subcommand

    """
    if defaults is None:
        defaults = {}
    options = {'--association-fields': {'action': 'store', 'dest':
        'association_fields', 'default': defaults.get('association_fields',
        None), 'help':
        'Comma-separated list of input fields (predictors) to create the association.'
        }, '--association': {'action': 'store', 'dest': 'association',
        'default': defaults.get('association', None), 'help':
        'BigML association Id.'}, '--associations': {'action': 'store',
        'dest': 'associations', 'default': defaults.get('associations',
        None), 'help':
        'Path to a file containing association/ids. One association per line (e.g., association/50a206a8035d0706dc000376).'
        }, '--association-file': {'action': 'store', 'dest':
        'association_file', 'default': defaults.get('association_file',
        None), 'help': 'BigML association JSON structure file.'}, '--max-k':
        {'action': 'store', 'type': int, 'dest': 'association_k', 'default':
        defaults.get('association_k', None), 'help':
        'Maximum number of rules to be included in the  association.'},
        '--search-strategy': {'action': 'store', 'dest': 'search_strategy',
        'choices': ['confidence', 'coverage', 'leverage', 'lift', 'support'
        ], 'default': defaults.get('search_strategy', None), 'help':
        'The strategy for prioritizing the rules in the search.'},
        '--no-association': {'action': 'store_true', 'dest':
        'no_association', 'default': defaults.get('no_association', False),
        'help': 'Do not create an association.'},
        '--association-attributes': {'action': 'store', 'dest':
        'association_attributes', 'default': defaults.get(
        'association_attributes', None), 'help':
        'Path to a json file describing association attributes.'},
        '--no-no-association': {'action': 'store_false', 'dest':
        'no_association', 'default': defaults.get('no_association', False),
        'help': 'Create an association.'}}
    return options


def generate_arn(partition='', service='', region='', account_id='',
    resource=''):
    """Generate an ARN value.

    Args:
        partition (str): The partition that the resource is in. For standard
            AWS regions, the partition is aws. If you have resources in other
            partitions, the partition is aws-partitionname. For example, the
            partition for resources in the China (Beijing) region is aws-cn

        service (str): The service namespace that identifies the AWS product
            (for example, Amazon S3, IAM, or Amazon RDS)

        region (str): The region the resource resides in. Note that the ARNs
            for some resources do not require a region, so this component might
            be omitted

        account_id (str): The ID of the AWS account that owns the resource,
            without the hyphens. For example, 123456789012

        resource (str): The content of this part of the ARN varies by service.
            It often includes an indicator of the type of resource for example,
            an IAM user or Amazon RDS database followed by a slash (/) or a
            colon (:), followed by the resource name itself.

    Returns:
        str: The generated ARN

    """
    return 'arn:{}:{}:{}:{}:{}'.format(partition, service, region,
        account_id, resource)


def clean_lines(lines):
    """removes blank lines and commented lines"""
    lines2 = []
    for line in lines:
        line2 = line.split('#')[0].strip()
        if line2:
            lines2.append(line2)
    return lines2


def slice_dim(slc, axis):
    """Return slice object that indexes along an arbitrary axis.
    Args:
        slc: the object used for slicing e.g. a slice object, an int or a sequence
        axis: the axis to slice
    """
    if axis < 0:
        return (Ellipsis, slc) + (slice(None),) * (-axis - 1)
    else:
        return (slice(None),) * axis + (slc, Ellipsis)


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

        :param TeamFolderMetadata val:
        :rtype: TeamFolderGetInfoItem
        """
    return cls('team_folder_metadata', val)


def find_sentence_starts(data):
    """Finds the positions inside a memory-mapped file, where the sentences
    (lines) start.

    TextIOWrapper disables tell() when readline() is called, so search for
    sentence starts in memory-mapped data.

    :type data: mmap.mmap
    :param data: memory-mapped data of the input file

    :rtype: list of ints
    :returns: a list of file offsets pointing to the next character from a
              newline (including file start and excluding file end)
    """
    result = [0]
    pos = 0
    while True:
        pos = data.find(b'\n', pos)
        if pos == -1:
            break
        pos += 1
        if pos < len(data):
            result.append(pos)
    return result


def get_terminal_size():
    """Get (width, height) of the current terminal."""
    try:
        import fcntl, termios, struct
        return struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234'))
    except:
        return 40, 80


def areaBetween(requestContext, *seriesLists):
    """
    Draws the vertical area in between the two series in seriesList. Useful for
    visualizing a range such as the minimum and maximum latency for a service.

    areaBetween expects **exactly one argument** that results in exactly two
    series (see example below). The order of the lower and higher values
    series does not matter. The visualization only works when used in
    conjunction with ``areaMode=stacked``.

    Most likely use case is to provide a band within which another metric
    should move. In such case applying an ``alpha()``, as in the second
    example, gives best visual results.

    Example::

      &target=areaBetween(service.latency.{min,max})&areaMode=stacked

      &target=alpha(areaBetween(service.latency.{min,max}),0.3)&areaMode=stacked

    If for instance, you need to build a seriesList, you should use the
    ``group`` function, like so::

      &target=areaBetween(group(minSeries(a.*.min),maxSeries(a.*.max)))
    """
    if len(seriesLists) == 1:
        [seriesLists] = seriesLists
    assert len(seriesLists
        ) == 2, 'areaBetween series argument must reference *exactly* 2 series'
    lower, upper = seriesLists
    if len(lower) == 1:
        [lower] = lower
    if len(upper) == 1:
        [upper] = upper
    lower.options['stacked'] = True
    lower.options['invisible'] = True
    upper.options['stacked'] = True
    lower.name = upper.name = 'areaBetween(%s)' % upper.pathExpression
    return [lower, upper]


def lookup(code, _cache={}):
    """Lookup an error code or class code and return its symbolic name.

    Raise `KeyError` if the code is not found.
    """
    if _cache:
        return _cache[code]
    tmp = {}
    for k, v in globals().items():
        if isinstance(v, str) and len(v) in (2, 5):
            tmp[v] = k
    assert tmp
    _cache.update(tmp)
    return _cache[code]


@classmethod
def validate(cls, value: str) ->None:
    """Value validation method.

    Valid values are ``UP`` and ``DOWN``.

    Args:
      value (str): The value to validate.

    Raises:
      ValueError: Raises ValueError if an invalid value has been specified.
    """
    super().validate(value)
    if value not in ['UP', 'DOWN']:
        raise ValueError()


def paths_clear(only_selected: bool=False):
    """Clear path caches for all bones, hold Shift key for selected bones only

    :param only_selected: Only Selected, Only clear paths from selected bones
    :type only_selected: bool
    """
    pass


def wlabel_from_units(units):
    """
    Return latex string for phonon frequencies in ``units``.
    """
    d = {'ev': 'Energy (eV)', 'mev': 'Energy (meV)', 'ha': 'Energy (Ha)',
        'cm-1': 'Frequency (cm$^{-1}$)', 'cm^-1': 'Frequency (cm$^{-1}$)',
        'thz': 'Frequency (Thz)'}
    try:
        return d[units.lower().strip()]
    except KeyError:
        raise KeyError(
            'Value for units `{}` unknown\nPossible values are:\n {}'.
            format(units, list(d.keys())))


def __ne__(A, other):
    """Returns true if both objects are not equal"""
    return not A == other


def register(history_id, object, referenced_data={}, metadata={}):
    """Sets up a new history for the object and does the first save.

        The 'object' and the 'referenced_data' together contain the whole
        data to be added to the history.

        'object' is already a clone and needn't be cloned anymore before
        beeing added to the history. Data in 'referenced_data' are direct
        references to the original object and must be cloned before being
        added to the history.

        'referenced_data' is a list or tuple of python references or
        'IStreamableReference' objects.

        'metadata' must be a (nested) dictionary. If a 'comment' key exists
        the implementation may assume it is a human readable string.

        May veto the registering proces by raising a 'StorageError'
        exception. No action is performed on repeated registering.

        Returns the value of the newest version(selector).
        """


def escape_like(string, escape_char='*'):
    """
    Escape the string paremeter used in SQL LIKE expressions.

    ::

        from sqlalchemy_utils import escape_like

        query = session.query(User).filter(
            User.name.ilike(escape_like('John'))
        )

    :param string: a string to escape
    :param escape_char: escape character
    """
    return string.replace(escape_char, escape_char * 2).replace('%',
        escape_char + '%').replace('_', escape_char + '_')


def deserialize(data):
    """
        Deserialize the endpoint template from a dictionary.

        :param dict data: a dictionary of values to import the template data
            from.
        """


def force_bytes(bytes_or_unicode, encoding='utf-8', errors='backslashreplace'):
    """Convert passed string type to bytes, if necessary."""
    if isinstance(bytes_or_unicode, bytes):
        return bytes_or_unicode
    return bytes_or_unicode.encode(encoding, errors)


def _make_version(major, minor, micro, releaselevel, serial):
    """Create a readable version string from version_info tuple components."""
    assert releaselevel in ['alpha', 'beta', 'candidate', 'final']
    version = '%d.%d' % (major, minor)
    if micro:
        version += '.%d' % (micro,)
    if releaselevel != 'final':
        short = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc'}[releaselevel]
        version += '%s%d' % (short, serial)
    return version


def _get_decorator_names(fun):
    """Get decorator names from the function.

    Args:
        fun: The function whose decorators we are getting.

    Returns:
        The names of the decorators. Does not include setters and
        getters.

    """
    ret = list()
    for decorator in fun.decorator_list:
        if hasattr(decorator, 'id'):
            ret.append(getattr(decorator, 'id'))
    return ret


@staticmethod
def _get_digest(key_iterator):
    """
        Extracts parameters for :py:meth:`address_from_digest`.

        Split into a separate method so that it can be mocked during
        unit tests.
        """
    private_key = next(key_iterator)
    return private_key.get_digest()


def setsvnProxy(host, port):
    """Sets the svn commands needed to use a proxy
    """
    global proxycmds
    proxycmds = []
    host = host.strip()
    port = port.strip()
    if not host:
        return
    proxycmds.append('--config-option')
    proxycmds.append('servers:global:http-proxy-host=' + host)
    if port:
        proxycmds.append('--config-option')
        proxycmds.append('servers:global:http-proxy-port=' + port)


def write_with_colors_win_py3(stream, outfile, flush):
    """Like `write`, but colorized chunks are written as text
    directly to `outfile` to ensure it gets processed by colorama.
    Applies only to Windows with Python 3 and colorized terminal output.

    """
    color = b'\x1b['
    encoding = outfile.encoding
    for chunk in stream:
        if color in chunk:
            outfile.write(chunk.decode(encoding))
        else:
            outfile.buffer.write(chunk)
        if flush:
            outfile.flush()


def is_independent_set(G, indep_nodes):
    """Determines whether the given nodes form an independent set.

    An independent set is a set of nodes such that the subgraph
    of G induced by these nodes contains no edges.

    Parameters
    ----------
    G : NetworkX graph
       The graph on which to check the independent set.

    indep_nodes : list
       List of nodes that form a maximum independent set, as
       determined by the given sampler.

    Returns
    -------
    is_independent : bool
        True if indep_nodes form an independent set.

    Example
    -------
    This example checks two sets of nodes, both derived from a
    single Chimera unit cell, for an independent set. The first set is
    the horizontal tile's nodes; the second has nodes from the horizontal and
    verical tiles.

    >>> import dwave_networkx as dnx
    >>> G = dnx.chimera_graph(1, 1, 4)
    >>> dnx.is_independent_set(G, [0, 1, 2, 3])
    True
    >>> dnx.is_independent_set(G, [0, 4])
    False

    """
    return len(G.subgraph(indep_nodes).edges) == 0


@classmethod
def deserialize_json(cls, json_data):
    """ Deserialize JSON data into a model.

        :param dict|list json_data: JSON list or dictionary to be deserialized.
        :return: An instance of the same class as the receiver of the call, or a list of instances.
        :rtype: Any|list[Any]
        :raises TypeError: Raised if the data cannot be deserialized.
        """
    objects, error = cls._schema.load(json_data, many=isinstance(json_data,
        list))
    if error:
        raise TypeError(
            """Invalid structure for initialization of `{type}`.
Error: {error}.
JSON data: {data}"""
            .format(type=cls.__name__, error=error, data=json_data))
    return objects


def build_clause(components, name='', join=','):
    """ Build a string from a list of components.
        This is to simplify building where clauses in particular that
        may optionally have zero, one or more parts
    """
    if not components:
        return ''
    return ' ' + name + ' ' + (' ' + join + ' ').join(components) + ' '


def get_all_headers(message, key):
    """
    Given an HTTPMessage, return all headers matching a given key.
    """
    return message.get_all(key)


def flops_relu(module, input, output):
    """FLOPs estimation for `torch.nn.ReLU`"""
    return input.numel()


def _check_square(matrix):
    """Raise a ValueError if the input matrix is square.

    Parameters
    ----------
    matrix : numpy.ndarray
        Input array.
    """
    if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[-1]:
        raise ValueError('Expected a square matrix, got array of shape {0}.'
            .format(matrix.shape))


def scale_probability(p):
    """ Levenshtein similarity is only good when it's high, when it's low, the score should go down """
    return p ** 2


def absorb(preferences):
    """Merge our preferences with the given preferences.

        Only those preferences which are unset in us but set in the given
        preferences are absorbed.

        :param preferences: The preferences to merge into ourself.
        :type preferences: IPreferences
        :raises TypeError: if `preferences` isn't a preference.
        """


def p_kw_parameter_type(p):
    """
    kw_parameter_type : KEYWORD pos_parameter_types
    kw_parameter_type : OPT_KEYWORD pos_parameter_types
    """
    p[0] = p[1], p[2]


def sensor_id(webhook_id, unique_id):
    """Return a unique sensor ID."""
    return f'{webhook_id}_{unique_id}'


@classmethod
def set(cls, key):
    """Set the Subscription Key."""
    cls.key = key


def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start] + match.string[end:]


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

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


def F1(state, qubit):
    """
    Applies a rotation (F1) about a stabilizer octahedron face to stabilizers  and destabilizers

    X -> iW = Y
    Z -> X
    W -> -iZ
    Y -> Z
    """
    stabs = state.stabs
    stabs.signs_minus ^= stabs.col_x[qubit] & stabs.col_z[qubit]
    gens_common = stabs.signs_i & stabs.col_x[qubit]
    gens_only_x = stabs.col_x[qubit] - stabs.signs_i
    stabs.signs_minus ^= gens_common
    stabs.signs_i -= gens_common
    stabs.signs_i |= gens_only_x
    for gens in state.gen_list:
        xonly = gens.col_x[qubit] - gens.col_z[qubit]
        zonly = gens.col_z[qubit] - gens.col_x[qubit]
        xzshared = gens.col_x[qubit] & gens.col_z[qubit]
        for i in xzshared:
            gens.row_x[i].discard(qubit)
        for i in xonly:
            gens.row_z[i].add(qubit)
        for i in zonly:
            gens.row_z[i].discard(qubit)
            gens.row_x[i].add(qubit)
        gens.col_x[qubit], gens.col_z[qubit] = gens.col_z[qubit], gens.col_x[
            qubit]
        gens.col_x[qubit] ^= gens.col_z[qubit]


@classmethod
def get_fields(cls):
    """Additional fields needed by algorithm. like radius of dilation"""
    return []


def p_instructions_instruction(p):
    """instructions : instruction"""
    p[0] = [p[1]]


def viz_b(body):
    """Create HTML b for graphviz"""
    return '<B>{}</B>'.format(body)


def merge_polygon(rel):
    """
    takes a relation that might possibly be a bunch of ways that HAPPEN to be a polygon, and transforms
    the MultiLineString object into a polygon object
    """
    return rel


def get_visit_footprints(visits):
    """
    Add `~shapely.geometry.Polygon` 'footprint' attributes to visit dict.

    Parameters
    ----------
    visits : list
        List of visit dictionaries.

    """
    import os
    import astropy.io.fits as pyfits
    import astropy.wcs as pywcs
    from shapely.geometry import Polygon
    N = len(visits)
    for i in range(N):
        for j in range(len(visits[i]['files'])):
            flt_file = visits[i]['files'][j]
            if (not os.path.exists(flt_file)) & os.path.exists('../RAW/' +
                flt_file):
                flt_file = '../RAW/' + flt_file
            flt_j = pyfits.open(flt_file)
            h = flt_j[0].header
            if (h['INSTRUME'] == 'WFC3') & (h['DETECTOR'] == 'IR'):
                wcs_j = pywcs.WCS(flt_j['SCI', 1])
            else:
                wcs_j = pywcs.WCS(flt_j['SCI', 1], fobj=flt_j)
            fp_j = Polygon(wcs_j.calc_footprint())
            if j == 0:
                fp_i = fp_j
            else:
                fp_i = fp_i.union(fp_j)
        visits[i]['footprint'] = fp_i
    return visits


def split_line(line):
    """splits a comma or space separated line"""
    if ',' in line:
        line2 = line.replace(',', ' ')
        sline = line2.split()
    else:
        sline = line.split()
    return sline


@staticmethod
def get_heating_status(root):
    """Get the active heating status (OpenTherm control)."""
    log_type = 'central_heating_state'
    locator = ("appliance[type='heater_central']/logs/point_log[type='" +
        log_type + "']/period/measurement")
    if root.find(locator) is not None:
        return root.find(locator).text == 'on'
    return None


def provider_parser(subparser):
    """Configure provider parser for DNSPark"""
    subparser.add_argument('--auth-username', help=
        'specify api key for authentication')
    subparser.add_argument('--auth-token', help=
        'specify token for authentication')


@classmethod
def __parse_host_scripts(cls, scripts_data):
    """
            Private method parsing the data from scripts affecting
            the target host.
            Contents of <hostscript> is returned as a list of dict.

            :param scripts_data: portion of XML describing the results of the
            scripts data
            :type scripts_data: xml.ElementTree.Element or a string

            :return: python list holding scripts output in a dict
        """
    _host_scripts = []
    for xscript in scripts_data:
        if xscript.tag == 'script':
            _script_dict = cls.__parse_script(xscript)
        _host_scripts.append(_script_dict)
    return _host_scripts


def size_GB(xr_object):
    """
    How many GB (or GiB) is your xarray object?

    // Requires an xarray object

    // Returns:
    * equivalent GB (GBytes) - 10^9 conversion
    * equivalent GiB (GiBytes) - 2^ 30 conversion

    < Thomas Moore - thomas.moore@csiro.au - 10102018 >
    """
    bytes = xr_object.nbytes
    Ten2the9 = 10 ** 9
    Two2the30 = 2 ** 30
    GBytes = bytes / Ten2the9
    GiBytes = bytes / Two2the30
    print(xr_object.name, 'is', GBytes, 'GB', 'which is', GiBytes, 'GiB')
    return GBytes, GiBytes


@staticmethod
def _is_redirection_result(response):
    """
        Return True if response is that of a redirection else False
        Redirection results have no information of use.
        """
    imdb_id = response['data'].get('tconst')
    if imdb_id and imdb_id != response['data'].get('news', {}).get('channel'):
        return True
    return False