def put_scaling_policy(Name=None, FleetId=None, ScalingAdjustment=None,
    ScalingAdjustmentType=None, Threshold=None, ComparisonOperator=None,
    EvaluationPeriods=None, MetricName=None):
    """
    Creates or updates a scaling policy for a fleet. An active scaling policy prompts Amazon GameLift to track a certain metric for a fleet and automatically change the fleet's capacity in specific circumstances. Each scaling policy contains one rule statement. Fleets can have multiple scaling policies in force simultaneously.
    A scaling policy rule statement has the following structure:
    If [MetricName] is [ComparisonOperator] [Threshold] for [EvaluationPeriods] minutes, then [ScalingAdjustmentType] to/by [ScalingAdjustment] .
    For example, this policy: "If the number of idle instances exceeds 20 for more than 15 minutes, then reduce the fleet capacity by 10 instances" could be implemented as the following rule statement:
    If [IdleInstances] is [GreaterThanOrEqualToThreshold] [20] for [15] minutes, then [ChangeInCapacity] by [-10].
    To create or update a scaling policy, specify a unique combination of name and fleet ID, and set the rule values. All parameters for this action are required. If successful, the policy name is returned. Scaling policies cannot be suspended or made inactive. To stop enforcing a scaling policy, call  DeleteScalingPolicy .
    See also: AWS API Documentation

    :example: response = client.put_scaling_policy(
        Name='string',
        FleetId='string',
        ScalingAdjustment=123,
        ScalingAdjustmentType='ChangeInCapacity'|'ExactCapacity'|'PercentChangeInCapacity',
        Threshold=123.0,
        ComparisonOperator='GreaterThanOrEqualToThreshold'|'GreaterThanThreshold'|'LessThanThreshold'|'LessThanOrEqualToThreshold',
        EvaluationPeriods=123,
        MetricName='ActivatingGameSessions'|'ActiveGameSessions'|'ActiveInstances'|'AvailableGameSessions'|'AvailablePlayerSessions'|'CurrentPlayerSessions'|'IdleInstances'|'PercentAvailableGameSessions'|'PercentIdleInstances'|'QueueDepth'|'WaitTime'
    )

    :type Name: string
    :param Name: [REQUIRED]
            Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. A fleet can have only one scaling policy with the same name.

    :type FleetId: string
    :param FleetId: [REQUIRED]
            Unique identifier for a fleet to apply this policy to.

    :type ScalingAdjustment: integer
    :param ScalingAdjustment: [REQUIRED]
            Amount of adjustment to make, based on the scaling adjustment type.

    :type ScalingAdjustmentType: string
    :param ScalingAdjustmentType: [REQUIRED]
            Type of adjustment to make to a fleet's instance count (see FleetCapacity ):
            ChangeInCapacity   add (or subtract) the scaling adjustment value from the current instance count. Positive values scale up while negative values scale down.
            ExactCapacity   set the instance count to the scaling adjustment value.
            PercentChangeInCapacity   increase or reduce the current instance count by the scaling adjustment, read as a percentage. Positive values scale up while negative values scale down; for example, a value of '-10' scales the fleet down by 10%.

    :type Threshold: float
    :param Threshold: [REQUIRED]
            Metric value used to trigger a scaling event.

    :type ComparisonOperator: string
    :param ComparisonOperator: [REQUIRED]
            Comparison operator to use when measuring the metric against the threshold value.

    :type EvaluationPeriods: integer
    :param EvaluationPeriods: [REQUIRED]
            Length of time (in minutes) the metric must be at or beyond the threshold before a scaling event is triggered.

    :type MetricName: string
    :param MetricName: [REQUIRED]
            Name of the Amazon GameLift-defined metric that is used to trigger an adjustment.
            ActivatingGameSessions   number of game sessions in the process of being created (game session status = ACTIVATING ).
            ActiveGameSessions   number of game sessions currently running (game session status = ACTIVE ).
            CurrentPlayerSessions   number of active or reserved player sessions (player session status = ACTIVE or RESERVED ).
            AvailablePlayerSessions   number of player session slots currently available in active game sessions across the fleet, calculated by subtracting a game session's current player session count from its maximum player session count. This number includes game sessions that are not currently accepting players (game session PlayerSessionCreationPolicy = DENY_ALL ).
            ActiveInstances   number of instances currently running a game session.
            IdleInstances   number of instances not currently running a game session.

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

    """
    pass


def shrink_to_hint(s: str):
    """
    Shrink a string to hint.

    :param str s: Source string
    :return: str
    """
    length = len(s)
    if length < 4:
        return '*' * length
    return '{}**{}'.format(s[0], s[length - 1])


def swap(t):
    """
    swap :: (a, b) -> (b, a)
    Swap the components of a pair.
    """
    a, b = t
    return b, a


@classmethod
def get_last_failed_access_attempt(cls, **kwargs):
    """
        Return Failed access attempt of Client
        :param ip_adress: String
        :return:
        """
    try:
        lockout = cls.objects.get(**kwargs)
    except cls.DoesNotExist:
        lockout = None
    if lockout:
        time_remaining = lockout.expiration_time
        if time_remaining and time_remaining <= 0:
            lockout.is_expired = True
            lockout.save()
            return None
    return lockout


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming
        """
    return True


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

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

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


def findCompleteFragments(fragments, max_dist, current_position,
    max_collapse_dist=20):
    """Find complete fragments that are >max_dist bp away from
    the current BAM file position

    Parameters
    ----------
    fragments : dict
        A dictionary containing ATAC fragment information
    max_dist : int
        The maximum allowed distance between fragment start and
        end positions
    current_position : int
        The current position being looked at in the position-sorted
        BAM file
    max_collapse_dist : int
        Maximum allowed distance for fragments from the same cell
        barcode that share one Tn5 integration site (fragment
        start or end coordinate) to be collapsed into a single
        fragment.

    Moves completed fragments to a new dictionary
    Completed fragments will be deleted from the original dictionary
    """
    allkey = list(fragments.keys())
    completed = dict()
    d = max_dist + max_collapse_dist
    for key in allkey:
        if fragments[key][4]:
            if fragments[key][2] + d < current_position:
                completed[key] = fragments[key][:-1]
                del fragments[key]
        elif fragments[key][1] is None:
            if fragments[key][2] + d < current_position:
                del fragments[key]
        elif fragments[key][2] is None:
            if fragments[key][1] + d < current_position:
                del fragments[key]
        else:
            del fragments[key]
    return completed


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


def standardize(instance, keys, is_singular=False, suffixes=None, altkeys=None
    ):
    """Standardize a component such that each key contains a list of dictionaries.

    Args:
        instance (dict): Component to standardize.
        keys (list): Keys to standardize in the instance.
        is_singular (bool, optional): If False, the keys are assumed to be plural
            and singular alternatives are also checked. If True, the keys are
            assumed to be singular and plural alternatives are also checked.
            Defaults to False.
        suffixes (list, optional): Suffixes to add to the keys to get a set of
            alternate keys that should also be checked. Defaults to None as is
            ignored.
        altkeys (list, optional): List of lists of alternate keys. Defaults to None.

    """
    for k in keys:
        if k not in instance:
            instance[k] = []
        if not isinstance(instance[k], list):
            instance[k] = [instance[k]]
    if altkeys is None:
        altkeys = []
    if suffixes is not None:
        for s in suffixes:
            altkeys.append([('%s%s' % (k, s)) for k in keys])
            if is_singular:
                altkeys.append([('%ss%s' % (k, s)) for k in keys])
                altkeys.append([('%s%ss' % (k, s)) for k in keys])
            else:
                altkeys.append([('%s%s' % (k[:-1], s)) for k in keys])
                altkeys.append([('%s%ss' % (k[:-1], s)) for k in keys])
    if is_singular:
        altkeys.append([('%ss' % k) for k in keys])
    else:
        altkeys.append([k[:-1] for k in keys])
    for ialtkeys in altkeys:
        for k, kalt in zip(keys, ialtkeys):
            if kalt in instance:
                if isinstance(instance[kalt], list):
                    instance[k] += instance.pop(kalt)
                else:
                    instance[k].append(instance.pop(kalt))
    for k in keys:
        for i in range(len(instance[k])):
            if isinstance(instance[k][i], str):
                instance[k][i] = {'name': instance[k][i]}


def unlink(force_delete: bool=False):
    """Unlink this action from the active action slot (and/or exit Tweak Mode)

    :param force_delete: Force Delete, Clear Fake User and remove copy stashed in this data-block’s NLA stack
    :type force_delete: bool
    """
    pass


def _no_tests_collected(suite):
    """
    Report for empty results
    """
    return 'No test cases found to run (ran in {0}).'.format(suite.timetxt)


def _needs_to_implement(that, func_name):
    """Helper to raise NotImplementedError in interface stubs."""
    if hasattr(that, '_coverage_plugin_name'):
        thing = 'Plugin'
        name = that._coverage_plugin_name
    else:
        thing = 'Class'
        klass = that.__class__
        name = '{klass.__module__}.{klass.__name__}'.format(klass=klass)
    raise NotImplementedError(
        '{thing} {name!r} needs to implement {func_name}()'.format(thing=
        thing, name=name, func_name=func_name))


@classmethod
def donate_url(cls):
    """Return media wiki donate url"""
    return cls.DONATE_URL


def translate(cls, key):
    """Get the translated message for a key."""
    return cls.instance.getmessage(key)


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


def has_organization_field(obj):
    """
    To check whether this object has a organization field
    :param obj: object to check
    :return: True if organization field exists, otherwise false
    """
    return hasattr(obj, 'organization')


def comma_separated_list(value):
    """
    Configuration-friendly list type converter.

    Supports both list-valued and string-valued inputs (which are comma-delimited lists of values, e.g. from env vars).

    """
    if isinstance(value, list):
        return value
    if value == '':
        return []
    return value.split(',')


def lzip(*args):
    """
    zip function that returns a list.
    """
    return list(zip(*args))


def set_identity_feedback_forwarding_enabled(Identity=None,
    ForwardingEnabled=None):
    """
    Given an identity (an email address or a domain), enables or disables whether Amazon SES forwards bounce and complaint notifications as email. Feedback forwarding can only be disabled when Amazon Simple Notification Service (Amazon SNS) topics are specified for both bounces and complaints.
    This action is throttled at one request per second.
    For more information about using notifications with Amazon SES, see the Amazon SES Developer Guide .
    See also: AWS API Documentation

    Examples
    The following example configures Amazon SES to forward an identity's bounces and complaints via email:
    Expected Output:

    :example: response = client.set_identity_feedback_forwarding_enabled(
        Identity='string',
        ForwardingEnabled=True|False
    )

    :type Identity: string
    :param Identity: [REQUIRED]
            The identity for which to set bounce and complaint notification forwarding. Examples: user@example.com , example.com .

    :type ForwardingEnabled: boolean
    :param ForwardingEnabled: [REQUIRED]
            Sets whether Amazon SES will forward bounce and complaint notifications as email. true specifies that Amazon SES will forward bounce and complaint notifications as email, in addition to any Amazon SNS topic publishing otherwise specified. false specifies that Amazon SES will publish bounce and complaint notifications only through Amazon SNS. This value can only be set to false when Amazon SNS topics are set for both Bounce and Complaint notification types.

    :rtype: dict
    :return: {}

    """
    pass


def init(app_id, app_key=None, master_key=None):
    """初始化 LeanCloud 的 AppId / AppKey / MasterKey

    :type app_id: string_types
    :param app_id: 应用的 Application ID
    :type app_key: None or string_types
    :param app_key: 应用的 Application Key
    :type master_key: None or string_types
    :param master_key: 应用的 Master Key
    """
    if not app_key and not master_key:
        raise RuntimeError('app_key or master_key must be specified')
    global APP_ID, APP_KEY, MASTER_KEY
    APP_ID = app_id
    APP_KEY = app_key
    MASTER_KEY = master_key


def epsilon_Bird_Stewart_Lightfoot_boiling(Tb):
    """Calculates Lennard-Jones depth of potential-energy minimum.
    Uses boiling temperature. CSP method by [1]_.

    .. math::
        \\epsilon/k = 1.15 T_b

    Parameters
    ----------
    Tb : float
        Boiling temperature [K]

    Returns
    -------
    epsilon_k : float
        Lennard-Jones depth of potential-energy minimum over k, [K]

    Notes
    -----

    Examples
    --------
    >>> epsilon_Bird_Stewart_Lightfoot_boiling(357.85)
    411.5275

    References
    ----------
    .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.
       Transport Phenomena, Revised 2nd Edition. New York:
       John Wiley & Sons, Inc., 2006
    """
    epsilon_k = 1.15 * Tb
    return epsilon_k


def lookahead(iterator):
    """
    Implements a new iterator from a given one which returns elements
    `(last, item)` where each `item` is taken from the original iterator
    and `last` is a boolean indicating whether this is the last item.
    """
    last = False
    it = iter(iterator)
    try:
        peek = next(it)
    except StopIteration:
        return
    while not last:
        item = peek
        try:
            peek = next(it)
        except StopIteration:
            last = True
        yield last, item


@staticmethod
def clone(repo_config):
    """Clones the latest version of the repo from the git server"""
    import logging
    from .process import ProcessWrapper
    import os
    import platform
    logger = logging.getLogger()
    logger.info('Cloning repository %s' % repo_config['path'])
    if 'path' not in repo_config:
        logger.info('No local repository path configured, no clone will occure'
            )
        return 0
    commands = []
    commands.append('unset GIT_DIR')
    commands.append('git clone --recursive ' + repo_config['url'] + ' -b ' +
        repo_config['branch'] + ' ' + repo_config['path'])
    for command in commands:
        res = ProcessWrapper().call(command, shell=True)
        if res != 0:
            logger.error("Command '%s' failed with exit code %s" % (command,
                res))
            break
    if res == 0 and os.path.isdir(repo_config['path']):
        logger.info('Repository %s successfully cloned' % repo_config['url'])
    else:
        logger.error('Unable to clone repository %s' % repo_config['url'])
    return int(res)


@classmethod
def get_all_connected_probes(cls):
    """! @brief Returns a list of DebugProbe instances."""
    raise NotImplementedError()


def missing_whitespace_after_import_keyword(logical_line):
    """Multiple imports in form from x import (a, b, c) should have space
    between import statement and parenthesised name list.

    Okay: from foo import (bar, baz)
    E275: from foo import(bar, baz)
    E275: from importable.module import(bar, baz)
    """
    line = logical_line
    indicator = ' import('
    if line.startswith('from '):
        found = line.find(indicator)
        if -1 < found:
            pos = found + len(indicator) - 1
            yield pos, 'E275 missing whitespace after keyword'


@classmethod
def update(cls, index_name, throughput):
    """ Update the throughput on the index """
    return cls('Update', index_name, throughput=throughput)


@staticmethod
def parse(parser):
    """parse line given parser and the current container, return a block if can be parsed,
        otherwise return None"""
    pass


def find_empty_id(used_id, desired=-1):
    """Ensure this item has a unique ID.

        Used by entities, solids and brush sides to keep their IDs valid.
        used_id must be sorted, and will be kept sorted.
        """
    if desired == -1:
        desired = 1
    else:
        desired = int(desired)
    used_id.sort()
    if len(used_id) == 0 or desired not in used_id:
        used_id.append(desired)
        return desired
    for poss_id in range(used_id[-1] + 1):
        if poss_id not in used_id:
            used_id.append(poss_id)
            return poss_id


@staticmethod
def _location(name, container, value):
    """Find location for index/column value."""
    if isinstance(value, int):
        if value in container:
            location = container.index(value)
        elif value < 0:
            location = value + len(container)
        else:
            location = value
        if location > len(container):
            raise IndexError(f'{name.title()} out of of range')
    else:
        try:
            location = container.index(str(value))
        except ValueError:
            raise ValueError(f'Unknown {name} name: {value}')
    return location


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

        Ensure data.message is string, since it can be very large

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
         {
            "dynamic":true,
            "properties": {
                "id" : {
                    "type" : "keyword"
                },
                "interval_months" : {
                    "type" : "long"
                },
                "origin" : {
                    "type" : "keyword"
                },
                "study_creation_date" : {
                    "type" : "date"
                },
                "total_blanks" : {
                    "type" : "long"
                },
                "total_blanks_per_loc" : {
                    "type" : "float"
                },
                "total_ccn" : {
                    "type" : "long"
                },
                "total_comments" : {
                    "type" : "long"
                },
                "total_comments_per_loc" : {
                    "type" : "float"
                },
                "total_files" : {
                    "type" : "long"
                },
                "total_loc" : {
                    "type" : "long"
                },
                "total_loc_per_function" : {
                    "type" : "float"
                },
                "total_num_funs" : {
                    "type" : "long"
                },
                "total_tokens" : {
                    "type" : "long"
                }
            }
        }
        """
    return {'items': mapping}


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

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

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


def oneway(method):
    """
    decorator to mark a method to be oneway (client won't wait for a response)
    """
    method._pyroOneway = True
    return method


@classmethod
def _get_mapping(cls, component):
    """Return a dict of attributes of a given component on the class"""
    mapping = {}
    for klass in cls.__mro__:
        for key, value in klass.__dict__.items():
            if isinstance(value, component):
                if key not in mapping:
                    mapping[key] = value.name
    return mapping


def nint(x):
    """Round a value to an integer.

    :param float x: original value
    :return: rounded integer
    :rtype: int
    """
    return int(x + 0.5)


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

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

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


@classmethod
def from_code(cls, code, *args, **kwargs):
    """
        Create an error object from code
        """
    if code in cls.INDEX:
        return cls(code, *args, **kwargs)
    return None


@classmethod
def sampler(cls, format_, *args, **kwargs):
    """Fetch a method to generate an initial binary sample

        Parameters
        ----------
        format : str
            the method name; Choose from 'independent' or 'multidim'

        *args
            the arguments necessary for the registered sample
            method; see help(InitialBinaryTable.sampler('independent')
            to see the arguments necessary for the independent sample
        """
    from .sampler.sampler import get_sampler
    sampler = get_sampler(format_, cls)
    return sampler(*args, **kwargs)


def getItems():
    """Returns the items to be rendered from the full set of self.items.

        Should be based on batch_start and batch_size, if set.
        """


def key_number_to_key_name(key_number):
    """Convert a key number to a key string.

    Parameters
    ----------
    key_number : int
        Uses pitch classes to represent major and minor keys.
        For minor keys, adds a 12 offset.
        For example, C major is 0 and C minor is 12.

    Returns
    -------
    key_name : str
        Key name in the format ``'(root) (mode)'``, e.g. ``'Gb minor'``.
        Gives preference for keys with flats, with the exception of F#, G# and
        C# minor.
    """
    if not isinstance(key_number, int):
        raise ValueError('`key_number` is not int!')
    if not (key_number >= 0 and key_number < 24):
        raise ValueError('`key_number` is larger than 24')
    keys = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
    key_idx = key_number % 12
    mode = key_number // 12
    if mode == 0:
        return keys[key_idx] + ' Major'
    elif mode == 1:
        if key_idx in [1, 6, 8]:
            return keys[key_idx - 1] + '# minor'
        else:
            return keys[key_idx] + ' minor'


def GetAscii(data):
    """Helper function to pretty print any ASCII chars in byte array"""
    ascii = ''
    for c in data:
        if 32 <= c <= 126:
            ascii = ascii + str(chr(c))
        else:
            ascii = ascii + '.'
    return ascii


def parse_paragraphs(soup):
    """Parse sentences and paragraphs in the section.

    Parameters
    ----------
    soup: bs4.BeautifulSoup
        The parsed XML data.

    Returns
    -------
    list of (list of str)
        List of paragraphs given as list of sentences.
    """
    paragraphs = []
    for para in soup.find_all('p'):
        sentences = []
        for sent in para.find_all('s'):
            sentence = sent.text.strip()
            if len(sentence) > 0:
                sentences.append(sentence)
        if len(sentences) > 0:
            paragraphs.append({'sentences': sentences})
    return paragraphs


def tamper(payload, **kwargs):
    """
    Replaces apostrophe character (') with its illegal double unicode counterpart (e.g. ' -> %00%27)

    >>> tamper("1 AND '1'='1")
    '1 AND %00%271%00%27=%00%271'
    """
    return payload.replace("'", '%00%27') if payload else payload


def edge_id(data=None, u=None, v=None, name=None, attr=None, out=None, **kwargs
    ):
    """This operator implements the edge_id function for a graph
    stored in a CSR matrix (the value of the CSR stores the edge Id of the graph).
    output[i] = input[u[i], v[i]] if there is an edge between u[i] and v[i]],
    otherwise output[i] will be -1. Both u and v should be 1D vectors.

    Example:

       .. code:: python

          x = [[ 1, 0, 0 ],
               [ 0, 2, 0 ],
               [ 0, 0, 3 ]]
          u = [ 0, 0, 1, 1, 2, 2 ]
          v = [ 0, 1, 1, 2, 0, 2 ]
          edge_id(x, u, v) = [ 1, -1, 2, -1, -1, 3 ]

    The storage type of ``edge_id`` output depends on storage types of inputs
      - edge_id(csr, default, default) = default
      - default and rsp inputs are not supported

    Defined in src/operator/contrib/dgl_graph.cc:L1321

    Parameters
    ----------
    data : Symbol
        Input ndarray
    u : Symbol
        u ndarray
    v : Symbol
        v ndarray

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

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


def timeoffset_tz(localdate):
    """
    returns the timezone from utc_offset in a Python datetime object

    input:
    local (official) date and time in Python datetime format with timezone

    returns:
    the timezone as float with one decimal

    the timezone is returned from the datetime object as utcoffset
    timedelta in days and seconds

    """
    try:
        offset_day = localdate.utcoffset().days
    except:
        offset_day = 0
    try:
        offset_sec = localdate.utcoffset().seconds
    except:
        offset_sec = 0
    offset_tz = round((offset_day * 86400 + offset_sec) / 3600, 1)
    return offset_tz


def cbrt(data=None, out=None, name=None, **kwargs):
    """Returns element-wise cube-root value of the input.

    .. math::
       cbrt(x) = \\sqrt[3]{x}

    Example::

       cbrt([1, 8, -125]) = [1, 2, -5]

    The storage type of ``cbrt`` output depends upon the input storage type:

       - cbrt(default) = default
       - cbrt(row_sparse) = row_sparse
       - cbrt(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L216

    Parameters
    ----------
    data : NDArray
        The input array.

    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 clean_column_name_sql_dump(i, line, hist, sep=';'):
    """
    Removes quotes in a line which looks like:

    ::

        0; "a"; 'j"'; "r;"

    @param      i       line number (unused)
    @param      line    line to process
    @param      hist    distribution of the number of columns
    @param      sep     line separator
    @return             text line, number of columns
    """
    vals = []
    beg = -1
    ending = ''
    for ii, c in enumerate(line):
        if beg == -1:
            beg = ii
            if c in ('"', "'"):
                nxt = c
            else:
                nxt = sep
        elif c == nxt:
            if c == sep:
                vals.append(line[beg:ii].strip())
                beg = -1
            else:
                nxt = sep
        elif c == '\n':
            ending = c
    if beg != -1:
        vals.append(line[beg:].strip())
    if ending:
        return sep.join(vals) + ending, len(vals)
    else:
        return sep.join(vals), len(vals)


def __iter__():
    """Iterate over revision numbers for this file."""


def upgrade():
    """A no-op migration for marking the Kilo release."""
    pass


def get_url(protocol, address, port):
    """ Returns the Url with the given parameters

    Args:
        protocol:
        address:
        port:

    Returns:

    """
    return protocol + '://' + address + ':' + str(port)


def convert_lists(varmap, listnames=('classifiers', 'requires', 'provides',
    'obsoletes')):
    """Convert long strings to lists of strings.

    Allows variable names in ``listnames`` to be specified as
    long strings instead of lists, for easier typing. The
    ``license_map`` and ``devstatus_trove`` strings below give
    examples of the kind of long strings that can be used.
    """
    listnames = varmap.get('listnames', listnames)
    for listname in listnames:
        try:
            var = varmap[listname]
        except KeyError:
            pass
        else:
            if isinstance(var, str):
                varmap[listname] = var.strip().splitlines()


def read_bytes(path):
    """
    Returns the bytes read from a local file at the given path

    :param str path: The local path to the file to read
    :return six.binary_type: bytes read from the given field_file
    """
    with open(path, 'r+b') as fh:
        result = fh.read()
    return result


def __new__(mcs, name, bases, dct):
    """Collect all ``Item`` instances and add them to the new class."""
    cls = type.__new__(mcs, name, bases, dct)
    if mcs.__node_base__ is None:
        mcs.__node_base__ = cls
    return cls


def log2(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise Base-2 logarithmic value of the input.

    ``2**log2(x) = x``

    The storage type of ``log2`` output is always dense

    Defined in src/operator/tensor/elemwise_unary_op_logexp.cc:L105

    Parameters
    ----------
    data : Symbol
        The input array.

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

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


def _while_loop(*data, **kwargs):
    """Run a while loop over with user-defined condition and computation

    From:src/operator/control_flow.cc:1151
    This function support variable length of positional input.

    Parameters
    ----------
    cond : Symbol
        Input graph for the loop condition.
    func : Symbol
        Input graph for the loop body.
    data : Symbol[]
        The input arrays that include data arrays and states.
    num_outputs : int, required
        The number of outputs of the subgraph.
    num_out_data : int, required
        The number of outputs from the function body.
    max_iterations : int, required
        Maximum number of iterations.
    cond_input_locs : tuple of <long>, required
        The locations of cond's inputs in the given inputs.
    func_input_locs : tuple of <long>, required
        The locations of func's inputs in the given inputs.
    func_var_locs : tuple of <long>, required
        The locations of loop_vars among func's inputs.

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

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


def psi_H_Na_Cl_HMW84(T, P):
    """c-c'-a: hydrogen sodium chloride [HMW84]."""
    psi = -0.004
    valid = T == 298.15
    return psi, valid


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


def funex(c):
    """
	Compiles a scriptlet expression into a Python function

	:param c: function to compile
	:type c: string
	:return: the function 'f' declared in the input string
	:rtype: function
	"""
    dc = {}
    exec(c, dc)
    return dc['f']


def base(property):
    """ Return the base part of a URI, `property` is a string denoting a URI.

    .. code-block:: python

        >>> print ns.base('http://sometest.ns/ns#symbol')
        http://sometest.ns/ns#

    """
    if '#' in property:
        return '%s#' % property.rsplit('#', 1)[0]
    return '%s/' % property.rsplit('/', 1)[0]


def _passedArgSpec(argspec, positional, keyword):
    """
    Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
    keyword arguments, and return a mapping of arguments that were actually
    passed to their passed values.

    @param argspec: The argument specification for the function to inspect.
    @type argspec: I{inspect.ArgSpec}

    @param positional: The positional arguments that were passed.
    @type positional: L{tuple}

    @param keyword: The keyword arguments that were passed.
    @type keyword: L{dict}

    @return: A dictionary mapping argument names (those declared in C{argspec})
        to values that were passed explicitly by the user.
    @rtype: L{dict} mapping L{str} to L{object}
    """
    result = {}
    unpassed = len(argspec.args) - len(positional)
    if argspec.keywords is not None:
        kwargs = result[argspec.keywords] = {}
    if unpassed < 0:
        if argspec.varargs is None:
            raise TypeError('Too many arguments.')
        else:
            result[argspec.varargs] = positional[len(argspec.args):]
    for name, value in zip(argspec.args, positional):
        result[name] = value
    for name, value in keyword.items():
        if name in argspec.args:
            if name in result:
                raise TypeError('Already passed.')
            result[name] = value
        elif argspec.keywords is not None:
            kwargs[name] = value
        else:
            raise TypeError('no such param')
    return result


def get_strng_field(k):
    """Parse arguments of the form string:field"""
    valor = k.split(':')
    if len(valor) == 1:
        ff = []
        ss = valor[0]
    elif len(valor) == 2:
        if valor[0] == '':
            ss = '*'
        else:
            ss = valor[0]
        if valor[1] == '':
            ff = []
        else:
            ff = valor[1].split(':')
    return ss, ff


def checkignore(path):
    """Check if a file is ignored by .gitignore"""
    import subprocess
    return 0 == subprocess.call(['git', 'check-ignore', path])


@classmethod
def from_file_and_offsets(cls, file, hdr_offset, data_offset, disk_length):
    """Instantiate a Rec object from the file object and the header and
    data offsets. The headers are read in, and also the record object
    is ready for calling get_data().

        """
    c = file._c_interface
    int_hdr, real_hdr = c.read_header(file.fd, hdr_offset, file.
        byte_ordering, file.word_size)
    return cls(int_hdr, real_hdr, hdr_offset, data_offset, disk_length,
        file=file)


def wordCount():
    """Return the number of unique terms in the lexicon."""


def add_container_output_args(argument_parser):
    """Define command-line arguments for output of a container (result files).
    @param argument_parser: an argparse parser instance
    """
    argument_parser.add_argument('--output-directory', metavar='DIR',
        default='output.files', help=
        "target directory for result files (default: './output.files')")
    argument_parser.add_argument('--result-files', metavar='PATTERN',
        action='append', default=[], help=
        "pattern for specifying which result files should be copied to the output directory (default: '.')"
        )


def _clean_annotation_label(label: str) ->str:
    """
		Removes extra stuff included in the annotation form breseq.
	"""
    if not isinstance(label, str):
        return ''
    if 'intergenic' in label:
        result = 'intergenic'
    elif 'del' in label:
        result = 'del'
    else:
        result = label.split('(')[0]
        if result == '':
            result = label
    return result


def getTrivialMatch(ach, bch):
    """Returns lists of matching residues (match based on residue number).

    """
    amatch = []
    bmatch = []
    match = 0.0
    for ares in ach:
        bres = bch[ares.getResnum(), ares.getIcode()]
        if bres is not None:
            if ares.getResname() == bres.getResname():
                match += 1
            amatch.append(ares.getResidue())
            bmatch.append(bres.getResidue())
    return amatch, bmatch, match


@classmethod
def list(cls, domain, options):
    """List forwards for a given domain name."""
    return cls.call('domain.forward.list', domain, options)


@classmethod
def _from_array(cls, data):
    """Constructs an UserArray object from some array data by assigining it
        to the _user_array attribute. If extra computation is necessary to
        correctly initialize the object, subclasses must define the
        _from_array_init() method, which takes no arguments."""
    new = object.__new__(cls)
    new._user_data = data
    new._from_array_init()
    return new


def print_options():
    """Displays usage information, available command line params."""
    print()
    """"""


def t_DUBCONSTANT(t):
    """-?\\d+\\.\\d*(e-?\\d+)?"""
    t.value = float(t.value)
    return t


def new_metadata_path(dataset_path):
    """
    Get the path where we should write a metadata file for this dataset.

    :type dataset_path: Path
    :rtype: Path
    """
    if dataset_path.is_dir():
        return dataset_path.joinpath('ga-metadata.yaml')
    if dataset_path.is_file():
        return dataset_path.parent.joinpath('{}.ga-md.yaml'.format(
            dataset_path.name))
    raise ValueError('Unhandled path type for %r' % dataset_path)


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


def tmpfs_list_to_dict(tmpfs_list):
    """Transform list of tmpfs parameters to dictionary

    :param tmpfs_list: List of tmpfs entry (of form 'directory:options')
    :returns: Dictionary as needed by Docker API
    """
    d = dict()
    for i in tmpfs_list:
        tmpfs_spec = i.split(':', 1)
        if len(tmpfs_spec) == 1:
            d[tmpfs_spec[0]] = ''
        else:
            d[tmpfs_spec[0]] = tmpfs_spec[1]
    return d


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 make_b2_delete_note(version, index, transferred):
    """
    Create a note message for delete action.

    :param b2sdk.v1.FileVersionInfo version: an object which contains file version info
    :param int index: file version index
    :param bool transferred: if True, file has been transferred, False otherwise
    """
    note = ''
    if version.action == 'hide':
        note = '(hide marker)'
    elif transferred or 0 < index:
        note = '(old version)'
    return note


def is_pinned_requirement(ireq):
    """
    Returns whether an InstallRequirement is a "pinned" requirement.

    An InstallRequirement is considered pinned if:

    - Is not editable
    - It has exactly one specifier
    - That specifier is "=="
    - The version does not contain a wildcard

    Examples:
        django==1.8   # pinned
        django>1.8    # NOT pinned
        django~=1.8   # NOT pinned
        django==1.*   # NOT pinned
    """
    if ireq.editable:
        return False
    if ireq.req is None or len(ireq.specifier._specs) != 1:
        return False
    op, version = next(iter(ireq.specifier._specs))._spec
    return (op == '==' or op == '===') and not version.endswith('.*')


def setup_parser(sub_parsers):
    """
    Sets up the command line parser for the *run* subprogram and adds it to *sub_parsers*.
    """
    parser = sub_parsers.add_parser('run', prog='law run', description=
        'Run a task with configurable parameters. See http://luigi.rtfd.io/en/stable/running_luigi.html for more info.'
        )
    parser.add_argument('task_family', help=
        'a task family registered in the task database file or a module and task class in the format <module>.<class>'
        )
    parser.add_argument('parameter', nargs='*', help='task parameters')


@classmethod
def create_block(cls, text: str='', lbcount: int=1) ->str:
    """
        Appends linebreaks to the given text
        :param text: The input text
        :param times: The number of linebreaks that will be appended
        """
    return text + ''.join(['\n'] * lbcount)


@classmethod
def getGcMode(cls):
    """Get AWLSIM_GCMODE.
		Returns one of the GCMODE_... constants.
		"""
    gcModeStr = cls.__getVar('GCMODE', '').lower().strip()
    if gcModeStr == cls.GCMODE_RT:
        return cls.GCMODE_RT
    if gcModeStr == cls.GCMODE_AUTO:
        return cls.GCMODE_AUTO
    if gcModeStr == cls.GCMODE_MANUAL:
        return cls.GCMODE_MANUAL
    return cls.GCMODE_RT


def str_to_file(str_val, fname, mode='w'):
    """
    Writes the string to the given file.
    @param str_val: The string to write.
    @param fname: The location of the file to write
    @param mode: default mode is to overwrite file
    @return:
    """
    with open(fname, mode) as f:
        f.write(str_val)


def distance_pivot_mfd(moment, force):
    """Usage: Calculate perpendicular distance from the pivot from force and the moment """
    return moment / force


@staticmethod
def _bwtocolor(gs, colormap, bgcolor=[0, 0, 0]):
    """
        Convert normalized [0,1] B&W image (gs) to color, applying a
        3-value list colormap (colormap)
        """
    return (1 - gs[:, :, (None)]) * bgcolor + gs[:, :, (None)] * colormap


def _get_embl_key(line):
    """Return first part of a string as a embl key (ie 'AC M14399;' -> 'AC')"""
    return line[:2]


def setDefaultIREncoding(encoding):
    """
		setDefaultIREncoding - Sets the default encoding used by IndexedRedis.
		  This will be the default encoding used for field data. You can override this on a
		  per-field basis by using an IRField (such as IRUnicodeField or IRRawField)

		@param encoding - An encoding (like utf-8)
	"""
    try:
        b''.decode(encoding)
    except:
        raise ValueError(
            'setDefaultIREncoding was provided an invalid codec. Got (encoding="%s")'
             % (str(encoding),))
    global defaultIREncoding
    defaultIREncoding = encoding


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

    Args:
        v1: float
            Value one.

        v2: float
            Value two

        epsilon: float
            Max allowed difference.

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


def extract_kw_args(args):
    """
    Extracts KW args and turns them into a dictionary
    :param args: 2d tuple of form ((TOKEN,VALUE),..)
    :return: Dictionary with key being token data and value being the value
    """
    d = {}
    for child in args:
        if len(child) == 2:
            d[child[0].value] = child[1]
    return d


def get_level_name(da):
    """
        Returns name of atmospheric level dimension in input array
        Author: Dougie Squire
        Date: 03/03/2018

        Parameters
        ----------
        da : xarray DataArray
            Array with coordinate corresponding to atmospheric level

        Returns
        -------
        name : str
            Name of dimension corresponding to atmospheric level

        Examples
        --------
        >>> A = xr.DataArray(np.random.normal(size=(2,2,2,2,2)),
        ...                  coords=[('lat', np.arange(2)), ('lon', np.arange(2)),
        ...                          ('depth', np.arange(2)), ('level', np.arange(2))])
        >>> doppyo.utils.get_level_name(A)
        'level'
    """
    if 'level' in da.dims:
        return 'level'
    else:
        raise KeyError('Unable to determine level dimension')
        pass


def merge_inner(clsdict):
    """
    Merge the inner class(es) of a class:
    e.g class A { ... } class A$foo{ ... } class A$bar{ ... }
       ==> class A { class foo{...} class bar{...} ... }
    """
    samelist = False
    done = {}
    while not samelist:
        samelist = True
        classlist = list(clsdict.keys())
        for classname in classlist:
            parts_name = classname.rsplit('$', 1)
            if len(parts_name) > 1:
                mainclass, innerclass = parts_name
                innerclass = innerclass[:-1]
                mainclass += ';'
                if mainclass in clsdict:
                    clsdict[mainclass].add_subclass(innerclass, clsdict[
                        classname])
                    clsdict[classname].name = innerclass
                    done[classname] = clsdict[classname]
                    del clsdict[classname]
                    samelist = False
                elif mainclass in done:
                    cls = done[mainclass]
                    cls.add_subclass(innerclass, clsdict[classname])
                    clsdict[classname].name = innerclass
                    done[classname] = done[mainclass]
                    del clsdict[classname]
                    samelist = False


def merge_entities(doc):
    """Merge entities into a single token.

    doc (Doc): The Doc object.
    RETURNS (Doc): The Doc object with merged entities.

    DOCS: https://spacy.io/api/pipeline-functions#merge_entities
    """
    with doc.retokenize() as retokenizer:
        for ent in doc.ents:
            attrs = {'tag': ent.root.tag, 'dep': ent.root.dep, 'ent_type':
                ent.label}
            retokenizer.merge(ent, attrs=attrs)
    return doc


def has_good_webhook(gh_api, repo):
    """Check webhook at GitHub for repo

    :param gh_api: GitHub API client for communication
    :type gh_api: ``repocribro.github.GitHubAPI``
    :param repo: Repository which webhook should be checked
    :type repo: ``repocribro.models.Repository``
    :return: If webhook is already in good shape
    :rtype: bool

    :todo: move somewhere else, check registered events
    """
    if repo.webhook_id is None:
        return False
    webhook = gh_api.webhook_get(repo.full_name, repo.webhook_id)
    return webhook is None


def Description():
    """ Return a textual description of the type

        o This descriptoin is used for display in a "constructor list".
        """


def tyn_calus(target, VA, VB, sigma_A, sigma_B, temperature=
    'pore.temperature', viscosity='pore.viscosity'):
    """
    Uses Tyn_Calus model to estimate diffusion coefficient in a dilute liquid
    solution of A in B from first principles at conditions of interest

    Parameters
    ----------
    target : OpenPNM Object
        The object for which these values are being calculated.  This
        controls the length of the calculated array, and also provides
        access to other necessary thermofluid properties.

    VA : float, array_like
        Molar volume of component A at boiling temperature (m3/mol)

    VB : float, array_like
        Molar volume of component B at boiling temperature (m3/mol)

    sigmaA:  float, array_like
        Surface tension of component A at boiling temperature (N/m)

    sigmaB:  float, array_like
        Surface tension of component B at boiling temperature (N/m)

    pressure : string
        The dictionary key containing the pressure values in Pascals (Pa)

    temperature : string
        The dictionary key containing the temperature values in Kelvin (K)

    Returns
    -------
    value : NumPy ndarray
        Array containing liquid diffusion coefficient values [m2/s].

    """
    T = target[temperature]
    mu = target[viscosity]
    A = 8.93e-08 * (VB * 1000000.0) ** 0.267 / (VA * 1000000.0) ** 0.433 * T
    B = (sigma_B / sigma_A) ** 0.15 / (mu * 1000.0)
    value = A * B
    return value


def writefilegnomon(gnomonx, gnomony, outputfilename, dataselected):
    """
    write file with gnomonic coordinates
    """
    linestowrite = []
    linestowrite.append(['gnomonx gnomony 2theta chi I #spot'])
    longueur = len(gnomonx)
    for i in list(range(longueur)):
        linestowrite.append([str(gnomonx[i]), str(gnomony[i]), str(2.0 *
            dataselected[0][i]), str(dataselected[1][i]), str(dataselected[
            2][i]), str(i)])
    naname = outputfilename + '.gno'
    outputfile = open(naname, 'w')
    for line in linestowrite:
        lineData = '\t'.join(line)
        outputfile.write(lineData)
        outputfile.write('\n')
    outputfile.close()


def render_homepage(config, env):
    """Render the homepage.jinja template."""
    template = env.get_template('homepage.jinja')
    rendered_page = template.render(config=config)
    return rendered_page


def is_unicode(obj):
    """Helper method to see if the object is a unicode string"""
    return type(obj) is str


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

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

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


def get_header2d(header3d):
    """Remove the spectral axis from a 3D FITS Header

        Args:
            header3d (astropy.io.fits.Header): Input 3D header.

        Returns:
            astropy.io.fits.Header: 2D Header object (spatial axes only)

        Example:

            If you wanted to collapse a cube to a 2D image and save it:

            >>> from astropy.io import fits
            >>> from cwitools import cubes
            >>> import numpy as np
            >>> mydata,header = fits.getdata("mydata.fits",header=True)
            >>> image_data = np.sum(mydata,axis=(0)) #Sum over wavelength
            >>> image_header = cubes.get_header2d(header)
            >>> image_fits = cubes.make_fits(image_data,image_header)
            >>> image_fits.writeto("image2D.fits")

            Note again - this example doesn't convert to surface-brightness or
            do any proper handling of units. That's up to you!

    """
    hdr2D = header3d.copy()
    for key in hdr2D.keys():
        if '3' in key:
            del hdr2D[key]
    hdr2D['NAXIS'] = 2
    hdr2D['WCSDIM'] = 2
    return hdr2D


def _show_opt(term, keys):
    """ Display characters ``key`` highlighted as keystroke """
    return u''.join((term.bold_black(u'['), term.bold_red_underline(keys),
        term.bold_black(u']')))


def getnext(iterator, default=None):
    """
    Get next item of iterable object
    :param iterator: object
    :param default: default value
    :return: next item of iterator till the end, otherwise default value
    """
    try:
        return next(iterator)
    except StopIteration:
        return default


def clr_transformed(df, masked=False):
    """ return a center log-ratio (clr)-transformed dataframe for a dataframe with raw counts """
    from skbio.stats.composition import clr
    from skbio.stats.composition import multiplicative_replacement
    import pandas as pd
    if masked:
        df2 = df[df['masked'] == False]
        df2.select_dtypes(include=int).apply(multiplicative_replacement).apply(
            clr)
        df[df.select_dtypes(include=int).columns.tolist()] = None
        df.update(df2)
    else:
        df[df.select_dtypes(include=int).columns.tolist()] = df.select_dtypes(
            include=int).apply(multiplicative_replacement).apply(clr)
    return df


@staticmethod
def internal_attrs():
    """Returns a list of internal attributes.

        Internal attributes can't be added, replaced or removed. This
        method may be overwritten by derived class.

        """
    return ['/created_at', '/id', '/links', '/updated_at', '/deleted_at',
        '/uuid']


def axis_off(ax, which='both'):
    """Turn off specific axis in an ``ax``."""
    assert which in ('x', 'y', 'both'), 'Which must be `x`, `y`, or `both`.'
    if which == 'both':
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    if which == 'x':
        ax.get_xaxis().set_visible(False)
    elif which == 'y':
        ax.get_yaxis().set_visible(False)
    return ax


@classmethod
def fromFile(cls, filePath, *args, **kwargs):
    """
        Load a STRM from a filesystem file.
        """
    with open(filePath, 'rb') as f:
        return cls(f.read(), *args, **kwargs)


def _convert_value_safe(value):
    """Convert `neo` values to a value compatible with `pandas`.

    Some types and dtypes used with neo are not safe to use with pandas in some
    or all situations.

    `quantities.Quantity` don't follow the normal python rule that values
    with that are equal should have the same hash, making it fundamentally
    incompatible with `pandas`.

    On python 3, `pandas` coerces `S` dtypes to bytes, which are not always
    safe to use.

    Parameters
    ----------

    value : any
            Value to convert (if it has any known issues).

    Returns
    -------

    any
        `value` or a version of value with potential problems fixed.

    """
    if hasattr(value, 'dimensionality'):
        return value.magnitude.tolist(), str(value.dimensionality)
    if hasattr(value, 'dtype') and value.dtype.kind == 'S':
        return value.astype('U').tolist()
    if hasattr(value, 'tolist'):
        return value.tolist()
    if hasattr(value, 'decode') and not hasattr(value, 'encode'):
        return value.decode('UTF8')
    return value


def PCA_custom(data, dims_rescaled_data=100):
    """
    returns: data transformed in 2 dims/columns + regenerated original data
    pass in: data as 2D NumPy array
    """
    import numpy as np
    from scipy import linalg as la
    data -= data.mean(axis=0)
    r = np.cov(data, rowvar=False)
    evals, evecs = la.eigh(r)
    idx = np.argsort(evals)[::-1]
    evecs = evecs[:, (idx)]
    evals = evals[idx]
    evecs = evecs[:, :dims_rescaled_data]
    return evecs, np.dot(evecs.T, data.T).T, evals


def get_import_package(modname):
    """
    Return the import package.

    Given modname is 'salt.utils', returns 'salt'
    """
    return modname.split('.')[0]


def _calc_tstop(num_bins, binsize, t_start):
    """
    Calculates the stop point from given parameters.

    Calculates the stop point `t_stop` from the three parameters
    `num_bins`, `binsize`, `t_start`.

    Parameters
    ----------
    num_bins : int
        Number of bins
    binsize : pq.Quantity
        Size of bins
    t_start : pq.Quantity
        Start time

    Returns
    -------
    t_stop : pq.Quantity
        Stopping point calculated from given parameters.
    """
    if num_bins is not None and binsize is not None and t_start is not None:
        return t_start.rescale(binsize.units) + num_bins * binsize


def neg_right(data):
    """
    Negate right half.
    """
    data[(...), int(data.shape[-1] / 2.0):] = -data[(...), int(data.shape[-
        1] / 2.0):]
    return data


def _generateKey(package, subdir):
    """Generate a key for a path inside a package.

    The key has the quality that keys for subdirectories can be derived by
    simply appending to the key.
    """
    return ':'.join((package, subdir.replace('\\', '/')))


def getitem(x, key):
    """Like :func:`operator.getitem`, but allows setting key using partial
    ``partial(chunk.getitem, key=key)
    """
    return x[key]


def create_masks(degree):
    """
    Create masks for taking bits from text bytes and
    putting them to image bytes.

    :param degree: number of bits from byte that are taken to encode text data in image
    :return: a mask for a text and a mask for an image
    """
    text_mask = 255
    img_mask = 255
    text_mask <<= 8 - degree
    text_mask %= 256
    img_mask >>= degree
    img_mask <<= degree
    return text_mask, img_mask


def min_(xs):
    """Returns min element (or None if there are no elements)"""
    if len(xs) == 0:
        return None
    else:
        return min(xs)


def delete_orphen_comm_items(session, comm_items):
    """
    deletes list of orphened comm_items identified by get_comm_items_without_parents
    """
    for ci in comm_items:
        session.delete(ci)
        print('deleted orphen invoice %s' % ci)
    session.commit()


def echo(text):
    """Echoes the text to stdout.

    :param str text:

    """
    print(text)


def AICc(N, rho, k, norm=True):
    """corrected Akaike information criterion

    .. math:: AICc(k) = log(\\rho_k) + 2 \\frac{k+1}{N-k-2}

    :validation: double checked versus octave.
    """
    from numpy import log, array
    p = k
    res = log(rho) + 2.0 * (p + 1) / (N - p - 2)
    return res


def SET_DIFFERENCE(*expressions):
    """
    Takes two sets and returns an array containing the elements that only exist in the first set.
    https://docs.mongodb.com/manual/reference/operator/aggregation/setDifference/
    for more details
    :param expressions: The arrays (expressions)
    :return: Aggregation operator
    """
    return {'$setDifference': list(expressions)}


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

        :param PaperDocRevertType val:
        :rtype: EventType
        """
    return cls('paper_doc_revert', val)


@classmethod
def quick_visitor(cls, visit_dict, node):
    """Class method to quickly define and run a custom visitor."""
    qv = type('QuickVisitor', cls, visit_dict)
    qv.visit(node)


def getTOFgammaDeriv(dsp):
    """get derivatives of TOF peak profile gamma wrt X, Y & Z

    :param float dsp: d-spacing of peak

    :returns: list getTOFgammaDeriv: d(gam)/dX & d(gam)/dY

    """
    return dsp, dsp ** 2, 1.0


@staticmethod
def _to_field(config_key):
    """Convert a config key to a field name"""
    return config_key.replace('-', '_')


def revoke_snapshot_access(SnapshotIdentifier=None,
    SnapshotClusterIdentifier=None, AccountWithRestoreAccess=None):
    """
    Removes the ability of the specified AWS customer account to restore the specified snapshot. If the account is currently restoring the snapshot, the restore will run to completion.
    For more information about working with snapshots, go to Amazon Redshift Snapshots in the Amazon Redshift Cluster Management Guide .
    See also: AWS API Documentation

    :example: response = client.revoke_snapshot_access(
        SnapshotIdentifier='string',
        SnapshotClusterIdentifier='string',
        AccountWithRestoreAccess='string'
    )

    :type SnapshotIdentifier: string
    :param SnapshotIdentifier: [REQUIRED]
            The identifier of the snapshot that the account can no longer access.

    :type SnapshotClusterIdentifier: string
    :param SnapshotClusterIdentifier: The identifier of the cluster the snapshot was created from. This parameter is required if your IAM user has a policy containing a snapshot resource element that specifies anything other than * for the cluster name.

    :type AccountWithRestoreAccess: string
    :param AccountWithRestoreAccess: [REQUIRED]
            The identifier of the AWS customer account that can no longer restore the specified snapshot.

    :rtype: dict
    :return: {
        'Snapshot': {
            'SnapshotIdentifier': 'string',
            'ClusterIdentifier': 'string',
            'SnapshotCreateTime': datetime(2015, 1, 1),
            'Status': 'string',
            'Port': 123,
            'AvailabilityZone': 'string',
            'ClusterCreateTime': datetime(2015, 1, 1),
            'MasterUsername': 'string',
            'ClusterVersion': 'string',
            'SnapshotType': 'string',
            'NodeType': 'string',
            'NumberOfNodes': 123,
            'DBName': 'string',
            'VpcId': 'string',
            'Encrypted': True|False,
            'KmsKeyId': 'string',
            'EncryptedWithHSM': True|False,
            'AccountsWithRestoreAccess': [
                {
                    'AccountId': 'string',
                    'AccountAlias': 'string'
                },
            ],
            'OwnerAccount': 'string',
            'TotalBackupSizeInMegaBytes': 123.0,
            'ActualIncrementalBackupSizeInMegaBytes': 123.0,
            'BackupProgressInMegaBytes': 123.0,
            'CurrentBackupRateInMegaBytesPerSecond': 123.0,
            'EstimatedSecondsToCompletion': 123,
            'ElapsedTimeInSeconds': 123,
            'SourceRegion': 'string',
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ],
            'RestorableNodeTypes': [
                'string',
            ],
            'EnhancedVpcRouting': True|False
        }
    }

    :returns:
    CreateClusterSnapshot and  CopyClusterSnapshot returns status as "creating".
    DescribeClusterSnapshots returns status as "creating", "available", "final snapshot", or "failed".
    DeleteClusterSnapshot returns status as "deleted".

    """
    pass


@classmethod
def all(cls, columns=None):
    """
        Get all og the models from the database.

        :param columns: The columns to retrieve
        :type columns: list

        :return: A Collection instance
        :rtype: Collection
        """
    instance = cls()
    return instance.new_query().get(columns)


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


@staticmethod
def _datatype_size(datatype, numElms):
    """
        Gets datatype size

        Parameters:
            datatype : int
                CDF variable data type
            numElms : int
                number of elements

        Returns:
            numBytes : int
                The number of bytes for the data
        """
    sizes = {(1): 1, (2): 2, (4): 4, (8): 8, (11): 1, (12): 2, (14): 4, (21
        ): 4, (22): 8, (31): 8, (32): 16, (33): 8, (41): 1, (44): 4, (45):
        8, (51): 1, (52): 1}
    try:
        if isinstance(datatype, int):
            if datatype == 51 or datatype == 52:
                return numElms
            else:
                return sizes[datatype]
        else:
            datatype = datatype.upper()
            if (datatype == 'CDF_INT1' or datatype == 'CDF_UINT1' or
                datatype == 'CDF_BYTE'):
                return 1
            elif datatype == 'CDF_INT2' or datatype == 'CDF_UINT2':
                return 2
            elif datatype == 'CDF_INT4' or datatype == 'CDF_UINT4':
                return 4
            elif datatype == 'CDF_INT8' or datatype == 'CDF_TIME_TT2000':
                return 8
            elif datatype == 'CDF_REAL4' or datatype == 'CDF_FLOAT':
                return 4
            elif datatype == 'CDF_REAL8' or datatype == 'CDF_DOUBLE' or datatype == 'CDF_EPOCH':
                return 8
            elif datatype == 'CDF_EPOCH16':
                return 16
            elif datatype == 'CDF_CHAR' or datatype == 'CDF_UCHAR':
                return numElms
            else:
                return -1
    except Exception:
        return -1


def derive_key(purpose, length):
    """
        Derive a purpose-specific key.

        This combines the master SPAKE2 key with the given purpose string and
        deterministically derives a new key of the requested length.  Any two
        connected Wormhole objects which call ``derive_key`` with the same
        purpose and length will get the same key.  This can be used to
        encrypt or sign other messages, or exchanged for verification
        purposes.  The master key will remain secret even if you reveal a
        derivative key.

        This must be called after the key has been established, so after any
        of
        ``get_unverified_key()/get_verifier()/get_versions()/get_message()``
        have fired.  ``derive_key()`` returns immediately, rather than
        returning a ``Deferred``.

        :return: a derivative key, of the requested length
        :rtype: ``bytes``
        """


def shape(input):
    """Return the shape of the tensor.

    Parameters
    ----------
    input : Tensor
        The input tensor.

    Returns
    -------
    tuple of int
        The tensor shape.
    """
    pass


def keep_scan(patients, i):
    """Discard other scans except index i. NOTE: Changes the structure."""
    for p in patients:
        p.scans = [p.scans[i]]


@classmethod
def supports(cls, name):
    """
        Check to see if a specific algorithm is supported.

        :param name: Name of the deterministic algorithm.
        :returns: True if `name` is an algorithm supported by the translator class, False otherwise.
        """
    return name in cls._LFN2PFN_ALGORITHMS


@staticmethod
def combine_dicts(*d):
    """Take any set of dictionaries and combine them."""
    dict_buffer = {}
    for dct in d:
        dict_buffer.update(dct)
    return dict_buffer


def swap_data():
    """Swap 2 sequencer strips

    """
    pass


@staticmethod
def _sort(x: tuple, allow_duplicates=False) ->tuple:
    """
        Sorts a tuple, optionally removing duplicates.

        Parameters
        ----------
        x:
            Tuple to be sorted.
        allow_duplicates:
            If True, duplicate entries are kept

        Returns
        -------
            A sorted tuple.
        """
    if allow_duplicates:
        return tuple(sorted(x))
    return tuple(sorted(set(x)))


def checkMessageMemoryAlignment(message, word_size_in_bits=8):
    """
    Examines a CANMessage object and checks that signals in the message are
    properly arranged so as to minimize padding in the struct bitfield. If a
    message cannot fit into the DLC that has been defined for it, this function
    will stop header file generation and raise an error.
    """
    pass


@classmethod
def return_or_raise(cls, response, expected_status_code):
    """Check for ``expected_status_code``."""
    try:
        if response.status_code in expected_status_code:
            return response
    except TypeError:
        if response.status_code == expected_status_code:
            return response
    raise cls(response)


def dt_dt(sdat, tstart=None, tend=None):
    """Derivative of temperature.

    Compute dT/dt as a function of time using an explicit Euler scheme.

    Args:
        sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
        tstart (float): time at which the computation should start. Use the
            beginning of the time series data if set to None.
        tend (float): time at which the computation should end. Use the
            end of the time series data if set to None.
    Returns:
        tuple of :class:`numpy.array`: derivative of temperature and time
        arrays.
    """
    tseries = sdat.tseries_between(tstart, tend)
    time = tseries['t'].values
    temp = tseries['Tmean'].values
    dtdt = (temp[1:] - temp[:-1]) / (time[1:] - time[:-1])
    return dtdt, time[:-1]


@classmethod
def create(cls, five9, data, refresh=False):
    """Create a record on Five9.

        Args:
            five9 (five9.Five9): The authenticated Five9 remote.
            data (dict): A data dictionary that can be fed to ``deserialize``.
            refresh (bool, optional): Set to ``True`` to get the record data
                from Five9 before returning the record.

        Returns:
            BaseModel: The newly created record. If ``refresh`` is ``True``,
                this will be fetched from Five9. Otherwise, it's the data
                record that was sent to the server.
        """
    raise NotImplementedError()


@staticmethod
def sort_prefixes(key):
    """
        Returns a numeric value for a named prefix mode: higher ranks have lower values
        (sorted first), and lower ranks have higher values (sorted last).

        This function essentially implements a sorted() key function for named prefix modes.
        """
    values = {'owner': 0, 'admin': 100, 'op': 200, 'halfop': 300, 'voice': 500}
    return values.get(key, 1000)


def should_skip_request(pin, request):
    """Helper to determine if the provided request should be traced"""
    if not pin or not pin.enabled():
        return True
    api = pin.tracer.writer.api
    return request.host == api.hostname and request.port == api.port


def init_tracing(tracer=None, start_span_cb=None):
    """
    Set our tracer for Redis. Tracer objects from the
    OpenTracing django/flask/pyramid libraries can be passed as well.

    :param tracer: the tracer object.
    """
    if start_span_cb is not None and not callable(start_span_cb):
        raise ValueError('start_span_cb is not callable')
    global _g_tracer, _g_start_span_cb
    if hasattr(tracer, '_tracer'):
        tracer = tracer._tracer
    _g_tracer = tracer
    _g_start_span_cb = start_span_cb


def should_build_with_cython(previous_cython_version, is_release):
    """
    Returns the previously used Cython version (or 'unknown' if not
    previously built) if Cython should be used to build extension modules from
    pyx files.
    """
    have_cython = False
    try:
        from Cython import __version__ as cython_version
        have_cython = True
    except ImportError:
        pass
    if have_cython and (not is_release or previous_cython_version == 'unknown'
        ):
        return cython_version
    else:
        return False


def onnx_get_node(graph, name):
    """
    Get ONNX node from graph by name

    Parameters
    ----------
    graph : ONNX GraphProto
        Specifies a GraphProto object.
    node : ONNX NodeProto
        Specifies a NodeProto object.

    Returns
    -------
    NodeProto

    """
    for node in graph.node:
        if node.name == name:
            return node


def format_job_command(job):
    """Truncates the job command to 47 characters + '...', if necessary"""
    return job['command'] if len(job['command']) <= 50 else '%s...' % job[
        'command'][:47]


@staticmethod
def filter_value(setting, data, *args):
    """Remove values related to setting that are invalid given args."""


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

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

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


def describe_table(TableName=None):
    """
    Returns information about the table, including the current status of the table, when it was created, the primary key schema, and any indexes on the table.
    See also: AWS API Documentation

    Examples
    This example describes the Music table.
    Expected Output:

    :example: response = client.describe_table(
        TableName='string'
    )

    :type TableName: string
    :param TableName: [REQUIRED]
            The name of the table to describe.

    :rtype: dict
    :return: {
        'Table': {
            'AttributeDefinitions': [
                {
                    'AttributeName': 'string',
                    'AttributeType': 'S'|'N'|'B'
                },
            ],
            'TableName': 'string',
            'KeySchema': [
                {
                    'AttributeName': 'string',
                    'KeyType': 'HASH'|'RANGE'
                },
            ],
            'TableStatus': 'CREATING'|'UPDATING'|'DELETING'|'ACTIVE',
            'CreationDateTime': datetime(2015, 1, 1),
            'ProvisionedThroughput': {
                'LastIncreaseDateTime': datetime(2015, 1, 1),
                'LastDecreaseDateTime': datetime(2015, 1, 1),
                'NumberOfDecreasesToday': 123,
                'ReadCapacityUnits': 123,
                'WriteCapacityUnits': 123
            },
            'TableSizeBytes': 123,
            'ItemCount': 123,
            'TableArn': 'string',
            'LocalSecondaryIndexes': [
                {
                    'IndexName': 'string',
                    'KeySchema': [
                        {
                            'AttributeName': 'string',
                            'KeyType': 'HASH'|'RANGE'
                        },
                    ],
                    'Projection': {
                        'ProjectionType': 'ALL'|'KEYS_ONLY'|'INCLUDE',
                        'NonKeyAttributes': [
                            'string',
                        ]
                    },
                    'IndexSizeBytes': 123,
                    'ItemCount': 123,
                    'IndexArn': 'string'
                },
            ],
            'GlobalSecondaryIndexes': [
                {
                    'IndexName': 'string',
                    'KeySchema': [
                        {
                            'AttributeName': 'string',
                            'KeyType': 'HASH'|'RANGE'
                        },
                    ],
                    'Projection': {
                        'ProjectionType': 'ALL'|'KEYS_ONLY'|'INCLUDE',
                        'NonKeyAttributes': [
                            'string',
                        ]
                    },
                    'IndexStatus': 'CREATING'|'UPDATING'|'DELETING'|'ACTIVE',
                    'Backfilling': True|False,
                    'ProvisionedThroughput': {
                        'LastIncreaseDateTime': datetime(2015, 1, 1),
                        'LastDecreaseDateTime': datetime(2015, 1, 1),
                        'NumberOfDecreasesToday': 123,
                        'ReadCapacityUnits': 123,
                        'WriteCapacityUnits': 123
                    },
                    'IndexSizeBytes': 123,
                    'ItemCount': 123,
                    'IndexArn': 'string'
                },
            ],
            'StreamSpecification': {
                'StreamEnabled': True|False,
                'StreamViewType': 'NEW_IMAGE'|'OLD_IMAGE'|'NEW_AND_OLD_IMAGES'|'KEYS_ONLY'
            },
            'LatestStreamLabel': 'string',
            'LatestStreamArn': 'string'
        }
    }

    :returns:
    S - the attribute is of type String
    N - the attribute is of type Number
    B - the attribute is of type Binary

    """
    pass


def create_stack(StackName=None, TemplateBody=None, TemplateURL=None,
    Parameters=None, DisableRollback=None, TimeoutInMinutes=None,
    NotificationARNs=None, Capabilities=None, ResourceTypes=None, RoleARN=
    None, OnFailure=None, StackPolicyBody=None, StackPolicyURL=None, Tags=
    None, ClientRequestToken=None):
    """
    Creates a stack as specified in the template. After the call completes successfully, the stack creation starts. You can check the status of the stack via the  DescribeStacks API.
    See also: AWS API Documentation

    :example: response = client.create_stack(
        StackName='string',
        TemplateBody='string',
        TemplateURL='string',
        Parameters=[
            {
                'ParameterKey': 'string',
                'ParameterValue': 'string',
                'UsePreviousValue': True|False
            },
        ],
        DisableRollback=True|False,
        TimeoutInMinutes=123,
        NotificationARNs=[
            'string',
        ],
        Capabilities=[
            'CAPABILITY_IAM'|'CAPABILITY_NAMED_IAM',
        ],
        ResourceTypes=[
            'string',
        ],
        RoleARN='string',
        OnFailure='DO_NOTHING'|'ROLLBACK'|'DELETE',
        StackPolicyBody='string',
        StackPolicyURL='string',
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ],
        ClientRequestToken='string'
    )

    :type StackName: string
    :param StackName: [REQUIRED]
            The name that is associated with the stack. The name must be unique in the region in which you are creating the stack.
            Note
            A stack name can contain only alphanumeric characters (case sensitive) and hyphens. It must start with an alphabetic character and cannot be longer than 128 characters.

    :type TemplateBody: string
    :param TemplateBody: Structure containing the template body with a minimum length of 1 byte and a maximum length of 51,200 bytes. For more information, go to Template Anatomy in the AWS CloudFormation User Guide.
            Conditional: You must specify either the TemplateBody or the TemplateURL parameter, but not both.

    :type TemplateURL: string
    :param TemplateURL: Location of file containing the template body. The URL must point to a template (max size: 460,800 bytes) that is located in an Amazon S3 bucket. For more information, go to the Template Anatomy in the AWS CloudFormation User Guide.
            Conditional: You must specify either the TemplateBody or the TemplateURL parameter, but not both.

    :type Parameters: list
    :param Parameters: A list of Parameter structures that specify input parameters for the stack. For more information, see the Parameter data type.
            (dict) --The Parameter data type.
            ParameterKey (string) --The key associated with the parameter. If you don't specify a key and value for a particular parameter, AWS CloudFormation uses the default value that is specified in your template.
            ParameterValue (string) --The value associated with the parameter.
            UsePreviousValue (boolean) --During a stack update, use the existing parameter value that the stack is using for a given parameter key. If you specify true , do not specify a parameter value.

    :type DisableRollback: boolean
    :param DisableRollback: Set to true to disable rollback of the stack if stack creation failed. You can specify either DisableRollback or OnFailure , but not both.
            Default: false

    :type TimeoutInMinutes: integer
    :param TimeoutInMinutes: The amount of time that can pass before the stack status becomes CREATE_FAILED; if DisableRollback is not set or is set to false , the stack will be rolled back.

    :type NotificationARNs: list
    :param NotificationARNs: The Simple Notification Service (SNS) topic ARNs to publish stack related events. You can find your SNS topic ARNs using the SNS console or your Command Line Interface (CLI).
            (string) --

    :type Capabilities: list
    :param Capabilities: A list of values that you must specify before AWS CloudFormation can create certain stacks. Some stack templates might include resources that can affect permissions in your AWS account, for example, by creating new AWS Identity and Access Management (IAM) users. For those stacks, you must explicitly acknowledge their capabilities by specifying this parameter.
            The only valid values are CAPABILITY_IAM and CAPABILITY_NAMED_IAM . The following resources require you to specify this parameter: AWS::IAM::AccessKey , AWS::IAM::Group , AWS::IAM::InstanceProfile , AWS::IAM::Policy , AWS::IAM::Role , AWS::IAM::User , and AWS::IAM::UserToGroupAddition . If your stack template contains these resources, we recommend that you review all permissions associated with them and edit their permissions if necessary.
            If you have IAM resources, you can specify either capability. If you have IAM resources with custom names, you must specify CAPABILITY_NAMED_IAM . If you don't specify this parameter, this action returns an InsufficientCapabilities error.
            For more information, see Acknowledging IAM Resources in AWS CloudFormation Templates .
            (string) --

    :type ResourceTypes: list
    :param ResourceTypes: The template resource types that you have permissions to work with for this create stack action, such as AWS::EC2::Instance , AWS::EC2::* , or Custom::MyCustomInstance . Use the following syntax to describe template resource types: AWS::* (for all AWS resource), Custom::* (for all custom resources), Custom::*logical_ID* `` (for a specific custom resource), ``AWS::*service_name* ::* (for all resources of a particular AWS service), and ``AWS::service_name ::resource_logical_ID `` (for a specific AWS resource).
            If the list of resource types doesn't include a resource that you're creating, the stack creation fails. By default, AWS CloudFormation grants permissions to all resource types. AWS Identity and Access Management (IAM) uses this parameter for AWS CloudFormation-specific condition keys in IAM policies. For more information, see Controlling Access with AWS Identity and Access Management .
            (string) --

    :type RoleARN: string
    :param RoleARN: The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that AWS CloudFormation assumes to create the stack. AWS CloudFormation uses the role's credentials to make calls on your behalf. AWS CloudFormation always uses this role for all future operations on the stack. As long as users have permission to operate on the stack, AWS CloudFormation uses this role even if the users don't have permission to pass it. Ensure that the role grants least privilege.
            If you don't specify a value, AWS CloudFormation uses the role that was previously associated with the stack. If no role is available, AWS CloudFormation uses a temporary session that is generated from your user credentials.

    :type OnFailure: string
    :param OnFailure: Determines what action will be taken if stack creation fails. This must be one of: DO_NOTHING, ROLLBACK, or DELETE. You can specify either OnFailure or DisableRollback , but not both.
            Default: ROLLBACK

    :type StackPolicyBody: string
    :param StackPolicyBody: Structure containing the stack policy body. For more information, go to Prevent Updates to Stack Resources in the AWS CloudFormation User Guide . You can specify either the StackPolicyBody or the StackPolicyURL parameter, but not both.

    :type StackPolicyURL: string
    :param StackPolicyURL: Location of a file containing the stack policy. The URL must point to a policy (maximum size: 16 KB) located in an S3 bucket in the same region as the stack. You can specify either the StackPolicyBody or the StackPolicyURL parameter, but not both.

    :type Tags: list
    :param Tags: Key-value pairs to associate with this stack. AWS CloudFormation also propagates these tags to the resources created in the stack. A maximum number of 10 tags can be specified.
            (dict) --The Tag type enables you to specify a key-value pair that can be used to store information about an AWS CloudFormation stack.
            Key (string) --
            Required . A string used to identify this tag. You can specify a maximum of 128 characters for a tag key. Tags owned by Amazon Web Services (AWS) have the reserved prefix: aws: .
            Value (string) --
            Required . A string containing the value for this tag. You can specify a maximum of 256 characters for a tag value.

    :type ClientRequestToken: string
    :param ClientRequestToken: A unique identifier for this CreateStack request. Specify this token if you plan to retry requests so that AWS CloudFormation knows that you're not attempting to create a stack with the same name. You might retry CreateStack requests to ensure that AWS CloudFormation successfully received them.

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

    """
    pass


def box_wood_frame_dictionary_init():
    """ create and initiate a box_wood_frame_dictionary with the default value
  """
    r_bwfd = {}
    r_bwfd['box_width'] = 400.0
    r_bwfd['box_depth'] = 400.0
    r_bwfd['box_height'] = 400.0
    r_bwfd['fitting_height'] = 30.0
    r_bwfd['h_plank_width'] = 50.0
    r_bwfd['v_plank_width'] = 30.0
    r_bwfd['plank_height'] = 20.0
    r_bwfd['d_plank_width'] = 30.0
    r_bwfd['d_plank_height'] = 10.0
    r_bwfd['crenel_depth'] = 5.0
    r_bwfd['wall_diagonal_size'] = 50.0
    r_bwfd['tobo_diagonal_size'] = 100.0
    r_bwfd['diagonal_lining_top_height'] = 20.0
    r_bwfd['diagonal_lining_bottom_height'] = 20.0
    r_bwfd['module_width'] = 1
    r_bwfd['router_bit_radius'] = 2.0
    r_bwfd['cutting_extra'] = 2.0
    r_bwfd['slab_thickness'] = 5.0
    r_bwfd['output_file_basename'] = ''
    r_bwfd['args_in_txt'] = ''
    r_bwfd['return_type'] = 'int_status'
    return r_bwfd


@staticmethod
def of_size(exact=None, at_least=None, at_most=None):
    """Confuse pylint so it doesn't complain about fluent-endpoints."""


@classmethod
def put(cls, item, **kwargs):
    """Put a single item into the table for this model

        The attributes on the item go through validation, so this may raise :class:`ValidationError`.

        :param dict item: The item to put into the table
        :param \\*\\*kwargs: All other kwargs are passed through to the put method on the table
        """
    return cls.Table.put(cls.Schema.dynamorm_validate(item), **kwargs)


def _parallel_compare_helper(class_obj, pairs, x, x_link=None):
    """Internal function to overcome pickling problem in python2."""
    return class_obj._compute(pairs, x, x_link)


@classmethod
def from_stream(cls, stream, parser=None):
    """
        Construct a :class:`Config` from a stream such as a :func:`file <open>`.
        If the stream does not have a ``name`` attribute from which the correct
        parser can be guessed, :doc:`parser <parsers>` must be specified.
        If ``text`` is provided as :class:`bytes`, then the ``encoding``
        specified will be used to decode it.
        """
    if parser is None:
        name = getattr(stream, 'name', None)
        if name is not None:
            try:
                _, parser = name.rsplit('.', 1)
            except ValueError:
                pass
    if not callable(parser):
        parser = cls.parsers[parser]
    return cls(parser(stream))


def p_dynamic_class_name_variable_property(p):
    """dynamic_class_name_variable_property : OBJECT_OPERATOR object_property"""
    p[0] = p[2]


def _argument_list_to_execution_argument(argument_list, cli_argument,
    batch_value):
    """
    Returns a list of strings representing the execution argument for the given cli argument.

    :param argument_list: The list of argument without prefix
    :param cli_argument: The cli argument whose prefix might be added.
    :param batch_value: The batch value corresponding to the cli argument
    """
    execution_argument = []
    if cli_argument.prefix:
        do_separate = cli_argument.separate
        if cli_argument.is_array() and not cli_argument.item_separator:
            do_separate = True
        should_add_prefix = True
        if cli_argument.is_array():
            if not batch_value:
                should_add_prefix = False
        if cli_argument.is_boolean():
            if not batch_value:
                should_add_prefix = False
        if should_add_prefix:
            if do_separate:
                execution_argument.append(cli_argument.prefix)
                execution_argument.extend(argument_list)
            elif not argument_list:
                execution_argument.append(cli_argument.prefix)
            else:
                assert len(argument_list) == 1
                joined_argument = '{}{}'.format(cli_argument.prefix,
                    argument_list[0])
                execution_argument.append(joined_argument)
    else:
        execution_argument.extend(argument_list)
    return execution_argument


def keyphrase_label(keyphrase):
    """Receive keyphrase and return label"""
    _, (keyphrase_label_, _), _ = keyphrase
    return keyphrase_label_


def keyframe_clear_button(all: bool=True):
    """Clear all keyframes on the currently active property

    :param all: All, Clear keyframes from all elements of the array
    :type all: bool
    """
    pass


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 escape(st):
    """
    Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
    the given string ``st`` and returns it.
    """
    return st.replace('\\', '\\\\').replace('\t', '\\t').replace('\r', '\\r'
        ).replace('\n', '\\n').replace('"', '\\"')


def add(a, b):
    """
    Returns the sum of two numbers
    """
    return a + b


@classmethod
def is_site_in_topic(cls) ->bool:
    """True if site id is part of topic."""
    return False


def chunks(items, size: int):
    """Break up items, an iterable, into chunks of length size."""
    if size < 1:
        raise ValueError(f'size must be positive, not {repr(size)}')
    for i in range(0, len(items), size):
        yield items[i:i + size]


def get_default_data(data, category):
    """
    Find the default value from a list of data, return the first one if no default found
    :param data: the data to search in
    :param category: the category of the data
    :return: one name contained in data
    """
    for _data in data:
        if _data.get('category').get('name') == category:
            if _data.get('extra', {}).get('action') == 'default':
                return _data.get('name')
    for _data in data:
        if _data.get('category').get('name') == category:
            return _data.get('name')


def extractFileNamefromUrl(url):
    """Extracts a file name from url.

   :param url: url
   :type url: string
   :returns: file name
   :rtype: string

   :Example:

   >>> from westpy import *
   >>> extractFileNamefromUrl("http://www.west-code.org/database/gw100/xyz/CH4.xyz")
   """
    fname = None
    my_url = url[:-1] if url.endswith('/') else url
    if my_url.find('/'):
        fname = my_url.rsplit('/', 1)[1]
    return fname


def plot_time_series(meter_data, temperature_data, **kwargs):
    """ Plot meter and temperature data in dual-axes time series.

    Parameters
    ----------
    meter_data : :any:`pandas.DataFrame`
        A :any:`pandas.DatetimeIndex`-indexed DataFrame of meter data with the column ``value``.
    temperature_data : :any:`pandas.Series`
        A :any:`pandas.DatetimeIndex`-indexed Series of temperature data.
    **kwargs
        Arbitrary keyword arguments to pass to
        :any:`plt.subplots <matplotlib.pyplot.subplots>`

    Returns
    -------
    axes : :any:`tuple` of :any:`matplotlib.axes.Axes`
        Tuple of ``(ax_meter_data, ax_temperature_data)``.
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('matplotlib is required for plotting.')
    default_kwargs = {'figsize': (16, 4)}
    default_kwargs.update(kwargs)
    fig, ax1 = plt.subplots(**default_kwargs)
    ax1.plot(meter_data.index, meter_data.value, color='C0', label=
        'Energy Use', drawstyle='steps-post')
    ax1.set_ylabel('Energy Use')
    ax2 = ax1.twinx()
    ax2.plot(temperature_data.index, temperature_data, color='C1', label=
        'Temperature', alpha=0.8)
    ax2.set_ylabel('Temperature')
    fig.legend()
    return ax1, ax2


def list_traffic_policies(TrafficPolicyIdMarker=None, MaxItems=None):
    """
    Gets information about the latest version for every traffic policy that is associated with the current AWS account. Policies are listed in the order in which they were created.
    See also: AWS API Documentation

    :example: response = client.list_traffic_policies(
        TrafficPolicyIdMarker='string',
        MaxItems='string'
    )

    :type TrafficPolicyIdMarker: string
    :param TrafficPolicyIdMarker: (Conditional) For your first request to ListTrafficPolicies , don't include the TrafficPolicyIdMarker parameter.
            If you have more traffic policies than the value of MaxItems , ListTrafficPolicies returns only the first MaxItems traffic policies. To get the next group of policies, submit another request to ListTrafficPolicies . For the value of TrafficPolicyIdMarker , specify the value of TrafficPolicyIdMarker that was returned in the previous response.

    :type MaxItems: string
    :param MaxItems: (Optional) The maximum number of traffic policies that you want Amazon Route 53 to return in response to this request. If you have more than MaxItems traffic policies, the value of IsTruncated in the response is true , and the value of TrafficPolicyIdMarker is the ID of the first traffic policy that Amazon Route 53 will return if you submit another request.

    :rtype: dict
    :return: {
        'TrafficPolicySummaries': [
            {
                'Id': 'string',
                'Name': 'string',
                'Type': 'SOA'|'A'|'TXT'|'NS'|'CNAME'|'MX'|'NAPTR'|'PTR'|'SRV'|'SPF'|'AAAA',
                'LatestVersion': 123,
                'TrafficPolicyCount': 123
            },
        ],
        'IsTruncated': True|False,
        'TrafficPolicyIdMarker': 'string',
        'MaxItems': 'string'
    }

    """
    pass


def tle_fmt_epoch(EpochDateTime):
    """ Return an Epoch string in TLE format, with a total width of 14 characters

    YYDDD.dddddddd where Midnight Jan 1 2019 is 19001.00000000
    """
    hour, minute, second, _, yday = EpochDateTime.timetuple()[3:8]
    YY = EpochDateTime.strftime('%y')
    microsecond = EpochDateTime.microsecond
    frac_days = yday + (microsecond / (3600 * 1000000.0) + second / 3600 +
        minute / 60 + hour) / 24
    return '{:2s}{:012.8f}'.format(YY, frac_days)


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

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

      *out* = *det(A)*

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

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

    Examples::

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

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

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

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

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

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


def year():
    """Return the calendar year of the object"""


@staticmethod
def score(uri: str) ->int:
    """
        Returns a score value for the give uri. E.g. 0 for unlikely/unknown, 20 for yes, probably thats the file format the reader can read.

        :param uri: str
        :return: int
        """
    return 0


def valid_view(context):
    """
    Prevent adding the global snippet in admin views and in editor view
    """
    view_class = getattr(context['view'], '__class__', None) if context.get(
        'view') else None
    if not view_class or not context.get('request'):
        return False
    request = context.get('request')
    if request:
        match = request.resolver_match
        if match and match.app_name == 'shuup_admin':
            return False
    view_name = getattr(view_class, '__name__', '')
    if view_name == 'EditorView':
        return False
    return True


def same_schema(atom1, atom2, theoryname=None):
    """Return True if ATOM1 and ATOM2 have the same schema.

    THEORYNAME is the default theory name.
    """
    if not atom1.table.same(atom2.table, theoryname):
        return False
    if len(atom1.arguments) != len(atom2.arguments):
        return False
    return True


def no_print(*args, **kwargs):
    """
    Do-nothing: useful to disable printing, while keeping its interface.
    """


def filter_by_expression_magnitude(raw_data, magnitude_threshold=1):
    """
    Remove any transcripts not expressed at at least <magnitude_threshold> in one or more samples.
    """
    data_rows = raw_data.index[:]
    print('Initial transcripts: {}'.format(raw_data.shape[1]))
    filtered_data = raw_data.loc[:, ((raw_data.loc[data_rows] >=
        magnitude_threshold).any(axis=0))]
    print('Removed {} transcripts with magnitude < {} across all samples'.
        format(raw_data.shape[1] - filtered_data.shape[1], magnitude_threshold)
        )
    print('{} transcripts remaining'.format(filtered_data.shape[1]))
    return filtered_data