def search_game_sessions(FleetId=None, AliasId=None, FilterExpression=None,
    SortExpression=None, Limit=None, NextToken=None):
    """
    Retrieves a set of game sessions that match a set of search criteria and sorts them in a specified order. Currently a game session search is limited to a single fleet. Search results include only game sessions that are in ACTIVE status. If you need to retrieve game sessions with a status other than active, use  DescribeGameSessions . If you need to retrieve the protection policy for each game session, use  DescribeGameSessionDetails .
    You can search or sort by the following game session attributes:
    To search or sort, specify either a fleet ID or an alias ID, and provide a search filter expression, a sort expression, or both. Use the pagination parameters to retrieve results as a set of sequential pages. If successful, a collection of  GameSession objects matching the request is returned.
    See also: AWS API Documentation

    :example: response = client.search_game_sessions(
        FleetId='string',
        AliasId='string',
        FilterExpression='string',
        SortExpression='string',
        Limit=123,
        NextToken='string'
    )

    :type FleetId: string
    :param FleetId: Unique identifier for a fleet to search for active game sessions. Each request must reference either a fleet ID or alias ID, but not both.

    :type AliasId: string
    :param AliasId: Unique identifier for an alias associated with the fleet to search for active game sessions. Each request must reference either a fleet ID or alias ID, but not both.

    :type FilterExpression: string
    :param FilterExpression: String containing the search criteria for the session search. If no filter expression is included, the request returns results for all game sessions in the fleet that are in ACTIVE status.
            A filter expression can contain one or multiple conditions. Each condition consists of the following:
            Operand -- Name of a game session attribute. Valid values are gameSessionName , gameSessionId , creationTimeMillis , playerSessionCount , maximumSessions , hasAvailablePlayerSessions .
            Comparator -- Valid comparators are: = , ```` , ```` , ```` , = , = .
            Value -- Value to be searched for. Values can be numbers, boolean values (true/false) or strings. String values are case sensitive, enclosed in single quotes. Special characters must be escaped. Boolean and string values can only be used with the comparators = and ```` . For example, the following filter expression searches on gameSessionName : 'FilterExpression': 'gameSessionName = 'Matt\\'s Awesome Game 1'' .
            To chain multiple conditions in a single expression, use the logical keywords AND , OR , and NOT and parentheses as needed. For example: x AND y AND NOT z , NOT (x OR y) .
            Session search evaluates conditions from left to right using the following precedence rules:
            = , ```` , ```` , ```` , = , =
            Parentheses
            NOT
            AND
            OR
            For example, this filter expression retrieves game sessions hosting at least ten players that have an open player slot: 'maximumSessions=10 AND hasAvailablePlayerSessions=true' .

    :type SortExpression: string
    :param SortExpression: Instructions on how to sort the search results. If no sort expression is included, the request returns results in random order. A sort expression consists of the following elements:
            Operand -- Name of a game session attribute. Valid values are gameSessionName , gameSessionId , creationTimeMillis , playerSessionCount , maximumSessions , hasAvailablePlayerSessions .
            Order -- Valid sort orders are ASC (ascending) and DESC (descending).
            For example, this sort expression returns the oldest active sessions first: 'SortExpression': 'creationTimeMillis ASC' . Results with a null value for the sort operand are returned at the end of the list.

    :type Limit: integer
    :param Limit: Maximum number of results to return. Use this parameter with NextToken to get results as a set of sequential pages. The maximum number of results returned is 20, even if this value is not set or is set higher than 20.

    :type NextToken: string
    :param NextToken: Token that indicates the start of the next sequential page of results. Use the token that is returned with a previous call to this action. To specify the start of the result set, do not specify a value.

    :rtype: dict
    :return: {
        'GameSessions': [
            {
                'GameSessionId': 'string',
                'Name': 'string',
                'FleetId': 'string',
                'CreationTime': datetime(2015, 1, 1),
                'TerminationTime': datetime(2015, 1, 1),
                'CurrentPlayerSessionCount': 123,
                'MaximumPlayerSessionCount': 123,
                'Status': 'ACTIVE'|'ACTIVATING'|'TERMINATED'|'TERMINATING'|'ERROR',
                'GameProperties': [
                    {
                        'Key': 'string',
                        'Value': 'string'
                    },
                ],
                'IpAddress': 'string',
                'Port': 123,
                'PlayerSessionCreationPolicy': 'ACCEPT_ALL'|'DENY_ALL',
                'CreatorId': 'string'
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    FleetId (string) -- Unique identifier for a fleet to search for active game sessions. Each request must reference either a fleet ID or alias ID, but not both.
    AliasId (string) -- Unique identifier for an alias associated with the fleet to search for active game sessions. Each request must reference either a fleet ID or alias ID, but not both.
    FilterExpression (string) -- String containing the search criteria for the session search. If no filter expression is included, the request returns results for all game sessions in the fleet that are in ACTIVE status.
    A filter expression can contain one or multiple conditions. Each condition consists of the following:

    Operand -- Name of a game session attribute. Valid values are gameSessionName , gameSessionId , creationTimeMillis , playerSessionCount , maximumSessions , hasAvailablePlayerSessions .
    Comparator -- Valid comparators are: = , ```` , ```` , ```` , = , = .
    Value -- Value to be searched for. Values can be numbers, boolean values (true/false) or strings. String values are case sensitive, enclosed in single quotes. Special characters must be escaped. Boolean and string values can only be used with the comparators = and ```` . For example, the following filter expression searches on gameSessionName : "FilterExpression": "gameSessionName = 'Matt\\'s Awesome Game 1'" .

    To chain multiple conditions in a single expression, use the logical keywords AND , OR , and NOT and parentheses as needed. For example: x AND y AND NOT z , NOT (x OR y) .
    Session search evaluates conditions from left to right using the following precedence rules:

    = , ```` , ```` , ```` , = , =
    Parentheses
    NOT
    AND
    OR

    For example, this filter expression retrieves game sessions hosting at least ten players that have an open player slot: "maximumSessions=10 AND hasAvailablePlayerSessions=true" .

    SortExpression (string) -- Instructions on how to sort the search results. If no sort expression is included, the request returns results in random order. A sort expression consists of the following elements:

    Operand -- Name of a game session attribute. Valid values are gameSessionName , gameSessionId , creationTimeMillis , playerSessionCount , maximumSessions , hasAvailablePlayerSessions .
    Order -- Valid sort orders are ASC (ascending) and DESC (descending).

    For example, this sort expression returns the oldest active sessions first: "SortExpression": "creationTimeMillis ASC" . Results with a null value for the sort operand are returned at the end of the list.

    Limit (integer) -- Maximum number of results to return. Use this parameter with NextToken to get results as a set of sequential pages. The maximum number of results returned is 20, even if this value is not set or is set higher than 20.
    NextToken (string) -- Token that indicates the start of the next sequential page of results. Use the token that is returned with a previous call to this action. To specify the start of the result set, do not specify a value.

    """
    pass


@classmethod
def _camel_case(cls, text, first_upper=False):
    """
        Transform text to camelCase or CamelCase

        :param text:
        :param first_upper: first symbol must be upper?
        :return:
        """
    result = ''
    need_upper = False
    for pos, symbol in enumerate(text):
        if symbol == '_' and pos > 0:
            need_upper = True
        else:
            if need_upper:
                result += symbol.upper()
            else:
                result += symbol.lower()
            need_upper = False
    if first_upper:
        result = result[0].upper() + result[1:]
    return result


@classmethod
def cleanup_all(cls):
    """
        Delete all temporary directories associated with all
        :class:`TempDirectory` objects.
        """
    for i in tuple(cls.instances):
        i.cleanup()


def ignore_args(function_args, args2ignore, ignore_value=None):
    """ Remove argument values to be ignored.

    Args:
        function_args: list of function arguments.
        args2ignore: list of integers representing index in argument list.
        ignore_value: value to substitute in ignored arguments.
    """
    function_args = list(function_args)
    for i in args2ignore:
        function_args[i] = ignore_value
    return function_args


@staticmethod
def is_tensor(obj):
    """Returns if `obj` is a tensor for the current backend"""
    raise NotImplementedError


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

        :param MemberChangeEmailType val:
        :rtype: EventType
        """
    return cls('member_change_email', val)


def extract_request_details(request_object, session_object=None):
    """
        a method for extracting request details from request and session objects

        NOTE:   method is also a placeholder funnel for future validation
                processes, request logging, request context building and
                counter-measures for the nasty web

    :param request_object: request object generated by flask from request route
    :param session_object: session object generated by flask from client cookie
    :return: dictionary with request details
    """
    request_details = {'error': '', 'status': 'ok', 'code': 200, 'method':
        request_object.method, 'session': {}, 'root': request_object.
        url_root, 'route': request_object.path, 'headers': {}, 'form': {},
        'params': {}, 'json': {}, 'data': ''}
    request_details['headers'].update(**request_object.headers)
    for key in request_object.args.keys():
        request_details['params'][key] = request_object.args.get(key)
    if session_object:
        request_details['session'].update(**session_object)
    if request_object.is_json:
        try:
            json_details = request_object.get_json(silent=True)
            if isinstance(json_details, dict):
                request_details['json'] = json_details
        except:
            pass
    else:
        try:
            from base64 import b64encode
            request_details['data'] = b64encode(request_object.data).decode()
        except:
            pass
        try:
            for key, value in request_object.form.items():
                request_details['form'][key] = value
        except:
            pass
    return request_details


def get_binary_target_scale_label_id(score, display_names, proba=None):
    """
    Return (target_name, scale, label_id) tuple for a binary classifier.

    >>> get_binary_target_scale_label_id(+5.0, get_target_display_names([False, True]))
    (True, 1, 1)
    >>> get_binary_target_scale_label_id(-5.0, get_target_display_names([False, True]))
    (False, -1, 0)
    >>> get_binary_target_scale_label_id(-5.0, get_target_display_names([False, True], targets=[True]))
    (True, 1, 1)
    >>> get_binary_target_scale_label_id(-5.0, get_target_display_names([False, True], targets=[False]))
    (False, -1, 0)
    """
    if score is not None:
        label_id = 1 if score >= 0 else 0
        scale = -1 if label_id == 0 else 1
    else:
        label_id = 1 if proba[1] >= 0.5 else 0
        scale = 1
    if len(display_names) == 1:
        predicted_label_id = label_id
        label_id, target = display_names[0]
        scale *= -1 if label_id != predicted_label_id else 1
    else:
        target = display_names[label_id][1]
    return target, scale, label_id


def estimate_aic(log_likelihood, degrees_of_freedom):
    """Akaike information criterion.

    Parameters
    ----------
    log_likelihood : float
    degrees_of_freedom : float

    Returns
    -------
    Akaike_information_criterion : float

    """
    return -2 * log_likelihood + 2 * degrees_of_freedom


def _dictiter(q):
    """Get query result as an iterator of dictionaries."""
    fields = q.listfields()
    for r in q:
        yield dict(zip(fields, r))


def DeleteBackup():
    """
    Request to delete whole backup or list of backups from remote machine.
    """
    return 'DeleteBackup'


def R_to_r(R):
    """
        Description: A function to scale down the autocorrelation function to a correlation function

        Input:
            :param R: Autocorrelation function of the signal
        Output:
            :return r: correlation function of the signal
            :rtype: ndarray

    """
    r = R / R[0]
    return r


@classmethod
def storage_key(cls, pk):
    """Key within the document store for a particular pk."""
    return '{storage_name}/{pk}'.format(storage_name=cls.storage_name, pk=pk)


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.featurize.text.MultiNGram'


def delete_all_errors():
    """ flush the logbook storage
        """


def _frange(start, stop, step):
    """range for floats"""
    while start < stop:
        yield start
        start += step


def SetParallelMode(mode):
    """Set the mode of data parallelism.

    Parameters
    ----------
    mode : str
        The mode, ``MPI``, ``NCCL`` or ``MIXED``.

    Returns
    -------
    None

    Notes
    -----
    The default mode is ``MPI``.

    """
    assert mode == 'MPI' or mode == 'NCCL' or mode == 'MIXED'
    global _parallel_mode
    _parallel_mode = mode


def _calculate_meta(meta, bases):
    """Calculate the most derived metaclass."""
    winner = meta
    for base in bases:
        base_meta = type(base)
        if issubclass(winner, base_meta):
            continue
        if issubclass(base_meta, winner):
            winner = base_meta
            continue
        raise TypeError(
            'metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases'
            )
    return winner


def _calcClassDefDeletionAndRemap(before, after):
    """
        >>> _calcClassDefDeletionAndRemap(set([1, 2, 3]), set([1, 2, 3]))
        ([], {0: 0, 1: 1, 2: 2, 3: 3})
        >>> _calcClassDefDeletionAndRemap(set([1, 2, 3]), set([1, 3]))
        ([2], {0: 0, 1: 1, 3: 2})
        >>> _calcClassDefDeletionAndRemap(set([1, 2, 3, 4, 5, 6]), set([1, 3, 4, 6]))
        ([5, 2], {0: 0, 1: 1, 3: 2, 4: 3, 6: 4})
        >>> _calcClassDefDeletionAndRemap(set([1, 2, 3, 4, 5, 6]), set([]))
        ([6, 5, 4, 3, 2, 1], {0: 0})
        >>> _calcClassDefDeletionAndRemap(set([0, 1, 2, 3]), set([1, 2]))
        ([3, 0], {1: 0, 2: 1})
        >>> _calcClassDefDeletionAndRemap(set([0, 1, 2, 3]), set([]))
        ([3, 2, 1, 0], {})
        >>> _calcClassDefDeletionAndRemap(set([]), set([]))
        ([], {})
    """
    assert not after - before
    if not before:
        return [], {}
    delete = sorted(before - after, reverse=True)
    rng = list(range(max(before) + 1))
    for i in delete:
        del rng[i]
    if not rng:
        return delete, {}
    if after:
        assert max(rng) == max(after)
    else:
        assert max(rng) == 0
    remap = dict(zip(rng, range(max(rng) + 1)))
    return delete, remap


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 acceleration_aug(friction_coefficient, gravity):
    """Usage: Find acceleration using friction coefficient and gravitational constant"""
    return friction_coefficient * gravity


def get(mail_host, default=None):
    """Return the named domain.

        :param mail_host: The email host name of the domain to remove.
        :type mail_host: string
        :param default: What to return if the named domain does not exist.
        :type default: object
        :return: The domain object or None if the named domain does not exist.
        :rtype: `IDomain`
        """


@classmethod
def load(cls, **namespaces):
    """
        Initialize config from a list of params.
        """
    for namespace, value in namespaces.items():
        setattr(cls, namespace, value)


def compute_utm_zone(lon, lat):
    """
    Compute the UTM zone which contains
    the point with given longitude and latitude

    Args:
        lon (float): longitude of the point
        lat (float): latitude of the point

    Returns:
        str: UTM zone number + hemisphere (eg: '30N')
    """
    zone = int((lon + 180) // 6 + 1)
    hemisphere = 'N' if lat >= 0 else 'S'
    utm_zone = '{}{}'.format(zone, hemisphere)
    return utm_zone


@classmethod
def get_by_role_id(cls, role_id=100):
    """Given a `role_id`, return the corresponding `Role` instance."""
    for code, role in cls.roles.items():
        if code == role_id:
            return role
    raise IndexError(f'Unknown role id: {role_id}')


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


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


def _format_trace(trace):
    """
    Convert the (stripped) stack-trace to a nice readable format. The stack
    trace `trace` is a list of frame records as returned by
    **inspect.stack** but without the frame objects.
    Returns a string.
    """
    lines = []
    for fname, lineno, func, src, _ in trace:
        if src:
            for line in src:
                lines.append('    ' + line.strip() + '\n')
        lines.append('  %s:%4d in %s\n' % (fname, lineno, func))
    return ''.join(lines)


def get_text_lines(text):
    """
    Get all lines from a text storing each lines as a different item in a list
    :param text: str, text to get lines from
    :return: list<str>
    """
    text = text.replace('\r', '')
    lines = text.split('\n')
    return lines


def Implements(Interface):
    """
    Returns the assert_implemented method of the given interface (used for
    decorator syntax)

    :param Interface: the interface to be implemented

    :return: the assert_implemented method of the given interface
    """
    return Interface.assert_implemented


def _is_leaf(elt):
    """Return True if elt if not an iterable."""
    if isinstance(elt, dict):
        return False
    elif isinstance(elt, list):
        return False
    elif isinstance(elt, tuple):
        return False
    else:
        return True


def psi_H_Li_ClO4_PK74(T, P):
    """c-c'-a: hydrogen lithium perchlorate [PK74]."""
    psi = -0.0017
    valid = T == 298.15
    return psi, valid


def refresh_cache(FileShareARN=None):
    """
    Refreshes the cache for the specified file share. This operation finds objects in the Amazon S3 bucket that were added or removed since the gateway last listed the bucket's contents and cached the results.
    See also: AWS API Documentation

    :example: response = client.refresh_cache(
        FileShareARN='string'
    )

    :type FileShareARN: string
    :param FileShareARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the file share.

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

    """
    pass


@classmethod
def get(cls):
    """
        Return the currently active TaskContext. This can be called inside of
        user functions to access contextual information about running tasks.

        .. note:: Must be called on the worker, not the driver. Returns None if not initialized.
        """
    return cls._taskContext


def _profile_callable_none(call, args, kwargs, is_profile_logged,
    profile_filename) ->object:
    """
    Call the passed callable with the passed positional and keyword arguments
    *without* profiling this call, returning the value returned by this call.

    See Also
    ----------
    :func:`profile_callable`
        Further details on function signature.
    """
    return call(*args, **kwargs)


def list_sql_injection_match_sets(NextMarker=None, Limit=None):
    """
    Returns an array of  SqlInjectionMatchSet objects.
    See also: AWS API Documentation

    Examples
    The following example returns an array of up to 100 SQL injection match sets.
    Expected Output:

    :example: response = client.list_sql_injection_match_sets(
        NextMarker='string',
        Limit=123
    )

    :type NextMarker: string
    :param NextMarker: If you specify a value for Limit and you have more SqlInjectionMatchSet objects than the value of Limit , AWS WAF returns a NextMarker value in the response that allows you to list another group of SqlInjectionMatchSets . For the second and subsequent ListSqlInjectionMatchSets requests, specify the value of NextMarker from the previous response to get information about another batch of SqlInjectionMatchSets .

    :type Limit: integer
    :param Limit: Specifies the number of SqlInjectionMatchSet objects that you want AWS WAF to return for this request. If you have more SqlInjectionMatchSet objects than the number you specify for Limit , the response includes a NextMarker value that you can use to get another batch of Rules .

    :rtype: dict
    :return: {
        'NextMarker': 'string',
        'SqlInjectionMatchSets': [
            {
                'SqlInjectionMatchSetId': 'string',
                'Name': 'string'
            },
        ]
    }

    """
    pass


def _const_compare_digest_backport(a, b):
    """
    Compare two digests of equal length in constant time.

    The digests must be of type str/bytes.
    Returns True if the digests match, and False otherwise.
    """
    result = abs(len(a) - len(b))
    for l, r in zip(bytearray(a), bytearray(b)):
        result |= l ^ r
    return result == 0


def database_reset():
    """
    reset database to the original state
    convert package database directory to its original state
    """
    pass


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a Bugzilla item."""
    return item['bug_id'][0]['__text__']


def _create_phpass_policy(**kwds):
    """helper to choose default alg based on bcrypt availability"""
    kwds['default'] = 'bcrypt' if hash.bcrypt.has_backend() else 'phpass'
    return kwds


def p_NULL(p):
    """opt_column_def_options : NULL"""
    p[0] = {'nullable': True}


def format_pfrule(pfrule):
    """Render port forwarding option."""
    format_str = '-{0.pf_type} {binding}'.format
    return pfrule and format_str(pfrule, binding=pfrule.binding) or ''


def msgparse(msg):
    """
    .. deprecated:: 0.0.12

    This function returns the NMEA message variables shared by both RMC and GGA.

    :param pynmea2.nmea.NMEASentence msg: A pynmea2 sentence object.
    :rtype: :py:class:`datetime.datetime`, :py:class:`float`, :py:class:`float`
    """
    return msg.timestamp, msg.latitude, msg.longitude


def deserialize_datetime(string):
    """Deserializes string to datetime.

    The string should be in iso8601 datetime format.

    :param string: str.
    :type string: str
    :return: datetime.
    :rtype: datetime
    """
    try:
        from dateutil.parser import parse
        return parse(string)
    except ImportError:
        return string


def is_hidden(post):
    """returns True/False based on `hidden` metadata in post"""
    return post and 'hidden' in post.meta and post.meta['hidden'] is True


def format_seconds(seconds: int) ->str:
    """Given a number of seconds format as X hours, X minutes, X seconds"""
    minutes, rseconds = divmod(seconds, 60)
    hours, rminutes = divmod(minutes, 60)
    strings = []
    if hours > 0:
        strings.append('{} hours'.format(hours))
    if rminutes > 0:
        strings.append('{} minutes'.format(rminutes))
    if rseconds > 0:
        strings.append('{} seconds'.format(rseconds))
    return ', '.join(strings)


def invert(series):
    """
    Swap index with values of series

    Parameters
    ----------
    series
        Series to swap on, must have a name

    Returns
    -------
    pandas.Series
        Series after swap

    See also
    --------
    pandas.Series.map
        Joins series ``a -> b`` and ``b -> c`` into ``a -> c``.
    """
    df = series.reset_index()
    df.set_index(series.name, inplace=True)
    return df[df.columns[0]]


def select_all_toggle():
    """Select or deselect all reports

    """
    pass


@classmethod
def has_archiving(cls):
    """Returns whether it supports archiving entries on the fetch process.

        :returns: this backend supports entries archive
        """
    return True


def convert_to_sql_wildcards(pattern, sql_escape='|'):
    """Converts wildcards '*' and '?' to SQL versions '%' and '_'.
       A state machine is used to allow for using the backslash to
       escape this characters:
            t\\e\\s\\t -> test
            test -> test
            test* -> test%
            test\\* -> test*
            test\\\\* -> test\\%
            test\\\\\\* -> test\\*
            test\\\\\\\\* -> test\\\\%
            test\\\\\\\\\\* -> test\\\\*
            % -> \\%
            _ -> \\_
            test_test% -> test\\_test\\%
            test__test% -> test\\_\\_test\\%
            test\\_test\\% -> test\\_test\\%
            test\\\\_test\\\\% -> test\\\\_test\\\\%
            test\\\\\\_test\\\\\\% -> test\\\\_test\\\\%
            test\\\\\\\\_test\\\\\\% -> test\\\\\\_test\\\\%
    """
    pat = ''
    esc = False
    for p in pattern:
        if p not in '*?\\':
            esc = False
            if p in '%_':
                pat += sql_escape
            pat += p
        elif esc:
            esc = False
            pat += p
        elif p == '\\':
            esc = True
        elif p == '*':
            pat += '%'
        elif p == '?':
            pat += '_'
    return pat


@classmethod
def src2type(cls, source):
    """ Convert string :source: to ES document _type name. """
    return source


def getOutgoingInterface():
    """
        Return interface of outgoing multicast packets.
        """


@classmethod
def serialize(cls, obj, skip_primary_key=False, skip_foreign_keys=False,
    relations_level=1, relations_ignore=None, relations_include=None):
    """
        Converts the object to a serializable dictionary.
        :param obj: the object to serialize

        :param skip_primary_key: should primary keys be skipped
        :type skip_primary_key: bool

        :param skip_foreign_keys: should foreign keys be skipped
        :type skip_foreign_keys: bool

        :param relations_level: how many levels of relations to serialize
        :type relations_level: int

        :param relations_ignore: relationship names to ignore
        :type relations_ignore: list

        :param relations_include: relationship names to include
        :type relations_include: list

        :return: a serializable dictionary
        :rtype: dict
        """
    data = {}
    data = cls.serialize_columns(obj, data, skip_primary_key, skip_foreign_keys
        )
    if relations_level > 0:
        if relations_ignore is None:
            relations_ignore = []
        data = cls.serialize_relations(obj, data, relations_level,
            relations_ignore, relations_include)
    return data


@classmethod
def supports_passthru_args(cls):
    """Subclasses may override to indicate that they can use passthru args.

        :API: public
        """
    return False


def test_for_blank_lines_separating_reference_lines(ref_sect):
    """Test to see if reference lines are separated by blank lines so that
       these can be used to rebuild reference lines.
       @param ref_sect: (list) of strings - the reference section.
       @return: (int) 0 if blank lines do not separate reference lines; 1 if
        they do.
    """
    num_blanks = 0
    num_lines = 0
    blank_line_separators = 0
    multi_nonblanks_found = 0
    x = 0
    max_line = len(ref_sect)
    while x < max_line:
        if not ref_sect[x].isspace():
            num_lines += 1
            x += 1
            while x < len(ref_sect) and not ref_sect[x].isspace():
                multi_nonblanks_found = 1
                x += 1
            x -= 1
        else:
            num_blanks += 1
            x += 1
            while x < len(ref_sect) and ref_sect[x].isspace():
                x += 1
            if x == len(ref_sect):
                num_blanks -= 1
            x -= 1
        x += 1
    if num_lines > 3 and (num_blanks == num_lines or num_blanks ==
        num_lines - 1) and multi_nonblanks_found:
        blank_line_separators = 1
    return blank_line_separators


def bond_is_in_ring(bond):
    """Get whether the bond is in a ring of any size.
    Parameters
    ----------
    bond : rdkit.Chem.rdchem.Bond
        RDKit bond instance.
    Returns
    -------
    list
        List containing one bool only.
    """
    return [bond.IsInRing()]


def __pyexpander_helper2(**kwargs):
    """a helper function needed at runtime.

    This evaluates named arguments.
    """
    return kwargs


def trans_array(data, _axes):
    """Calculates indices for an array transpose use by anFFT.

    :param data: The data, used for dimension purposes (rank)
    :type data: numpy array
    :param _axes: axes to FFT over, and hence transpose to the end
    :type _axes: list
    :return: tuple of axes values
    :rtype: tuple of integers

    """
    ind = list(range(data.ndim))
    try:
        axes = list(_axes)
    except:
        axes = [_axes]
    axes.sort()
    axes.reverse()
    for a in axes:
        ind.pop(a)
    ind.extend(axes)
    return ind


def header2(string):
    """Print a formatted subheading."""
    print('\n'.join(['', string, '-' * len(string), '']))


def _computeforwardmissing(a, b, match=None):
    """Computes which files are in b but not a.
    This is its own function so extensions can easily wrap this call to see what
    files _forwardcopies is about to process.
    """
    ma = a.manifest()
    mb = b.manifest()
    return mb.filesnotin(ma, match=match)


def monkeypatch_django():
    """
    Monkeypatches support for us into parts of Django.
    """
    from django.contrib.staticfiles.management.commands.runserver import Command as StaticRunserverCommand
    from .management.commands.runserver import Command as RunserverCommand
    StaticRunserverCommand.__bases__ = RunserverCommand,


def unauthenticated(func):
    """Adds 'unauthenticated' attribute to decorated function.

    Usage:

    >>> @unauthenticated
    ... def mymethod(f):
    ...     pass
    """
    func.unauthenticated = True
    return func


def add_to_run_context(settings, key, value):
    """
    Add key and value carefully to the settings
    :param key: the key to be added
    :param value: the value belonging to the key
    :param settings: the loaded settings
    :return:
    """
    if 'run_context' not in settings:
        settings['run_context'] = {}
    settings['run_context'][key] = value
    return settings


def set_user_field(model_bwp, instance, user, save=False):
    """ Устанавливает пользователя, изменившего объект """
    if model_bwp.user_field:
        setattr(instance, model_bwp.user_field, user)
    if save:
        instance.save()
    return instance


@classmethod
def get_json_schema(cls):
    """
        Get a json schema of this document with datatypes and required
        status
        """
    if cls.__schema__:
        return cls.__schema__


def unconstrained_check(state, ast):
    """
    Attempts to check if an ast is completely unconstrained
    :param state: the state to use
    :param ast: the ast to check
    :return: True if the ast is probably completely unconstrained
    """
    size = ast.size()
    test_val_0 = 0
    test_val_1 = (1 << size) - 1
    test_val_2 = int('1010' * 16, 2) % (1 << size)
    test_val_3 = int('0101' * 16, 2) % (1 << size)
    test_val_4 = int('1001' * 2 + '1010' * 2 + '1011' * 2 + '1100' * 2 +
        '1101' * 2 + '1110' * 2 + '1110' * 2 + '0001' * 2, 2) % (1 << size)
    if not state.solver.satisfiable(extra_constraints=(ast == test_val_0,)):
        return False
    if not state.solver.satisfiable(extra_constraints=(ast == test_val_1,)):
        return False
    if not state.solver.satisfiable(extra_constraints=(ast == test_val_2,)):
        return False
    if not state.solver.satisfiable(extra_constraints=(ast == test_val_3,)):
        return False
    if not state.solver.satisfiable(extra_constraints=(ast == test_val_4,)):
        return False
    return True


def display_onnx(model_onnx, max_length=1000):
    """
    Returns a shortened string of the model.

    @param      model_onnx      onnx model
    @param      max_length      maximal string length
    @return                     string
    """
    res = str(model_onnx)
    if max_length is None or len(res) <= max_length:
        return res
    begin = res[:max_length // 2]
    end = res[-max_length // 2:]
    return '\n'.join([begin, '[...]', end])


def context(match, urls):
    """A helper that provides a way of giving a common
    prefix to a set of routes.

    :return: The anillo url spec for url nesting.
    :rtype: dict
    """
    return {'context': match, 'routes': urls}


@staticmethod
def writeFile(filename, data):
    """
		Writes data to a file
		"""
    with open(filename, 'wb') as f:
        f.write(data.encode('utf-8'))


@classmethod
def nova(cls, *args):
    """
        executes nova with the given arguments
        :param args:
        :return:
        """
    return cls.execute('nova', args)


def steady_state_potential(xdata, HistBins=100):
    """
    Calculates the steady state potential. Used in
    fit_radius_from_potentials.

    Parameters
    ----------
    xdata : ndarray
        Position data for a degree of freedom
    HistBins : int
        Number of bins to use for histogram
        of xdata. Number of position points
        at which the potential is calculated.

    Returns
    -------
    position : ndarray
        positions at which potential has been
        calculated
    potential : ndarray
        value of potential at the positions above

    """
    import numpy as _np
    pops = _np.histogram(xdata, HistBins)[0]
    bins = _np.histogram(xdata, HistBins)[1]
    bins = bins[0:-1]
    bins = bins + _np.mean(_np.diff(bins))
    pops = pops / float(_np.sum(pops))
    return bins, -_np.log(pops)


@classmethod
def create_from_genomesize(cls, gsize):
    """Creates a GenomicIndexer object.

        This method constructs a GenomicIndexer from
        a given BED or GFF file.

        Parameters
        ----------
        gsize : dict
            Dictionary with keys and values representing chromosome names
            and lengths, respectively.
        """
    gind = cls(None, None, 0, zero_padding=False, collapse=False)
    for chrom in gsize:
        gind.add_interval(chrom, 0, gsize[chrom], '.')
    return gind


@classmethod
def integer(cls, integer, bits=None):
    """
        @type  integer: int
        @param integer: Integer.

        @type  bits: int
        @param bits:
            (Optional) Number of bits of the target architecture.
            The default is platform dependent. See: L{HexOutput.integer_size}

        @rtype:  str
        @return: Text output.
        """
    if bits is None:
        integer_size = cls.integer_size
    else:
        integer_size = bits / 4 + 2
    if integer >= 0:
        return '0x%%.%dx' % (integer_size - 2) % integer
    return '-0x%%.%dx' % (integer_size - 2) % -integer


@staticmethod
def get_value_from_nested_dict(data_dict, map_str, separator='.'):
    """
            Get value from nested dict
        :param data_dict:
        :param map_str: key1.key2.key3
        :param separator: for split map string of path. Default: '.'
        :return:
        Ex: list_dict={{'id1': {'value':'1'}},
                       {'id2': {'value':'2'}},
                       {'id3': {'value':'3'}}
             map_str='id1.value'
          => return '1'
        """
    map_list = str(map_str).split(separator)
    pointer = data_dict
    value = None
    try:
        for ind in range(len(map_list)):
            key = map_list[ind]
            if isinstance(pointer, list):
                if ind == len(map_list) - 1:
                    value = pointer[int(key[1:-1])]
                    return value
                pointer = pointer[int(key[1:-1])]
            elif ind == len(map_list) - 1:
                value = pointer[key]
                return value
            elif key in pointer:
                pointer = pointer[key]
        return value
    except (KeyError, TypeError, IndexError):
        return None


def check_arg_types(funcname, *args):
    """Raise TypeError if not all items of `args` are same string type."""
    hasstr = hasbytes = False
    for arg in args:
        if isinstance(arg, str):
            hasstr = True
        elif isinstance(arg, bytes):
            hasbytes = True
        else:
            raise TypeError('{0}() argument must be str or bytes, not {1}'.
                format(funcname, arg.__class__.__name__))
    if hasstr and hasbytes:
        raise TypeError("Can't mix strings and bytes in path components")


def FormatDescription(description):
    """
    Formats a wxWidgets C++ description in a more wxPython-based way.

    **Parameters:**

    * `description`: the string description to be formatted.
    """
    description = description.replace('wx', 'wx.')
    description = description.replace('EVT_COMMAND', 'wxEVT_COMMAND')
    description = description.replace('wx.Widgets', 'wxWidgets')
    return description


def is_ascii(text):
    """Returns whether the given string is ASCII."""
    try:
        text.encode('ascii', 'strict')
    except UnicodeError:
        return False
    else:
        return True


def _compute_zero_padding(kernel_size: int) ->int:
    """Computes zero padding."""
    return (kernel_size - 1) // 2


def encode_set(obj, typecode, packb, ext_type):
    """Encode a Python 'set' object into a MessagePack ExtType."""
    return ext_type(typecode, packb(tuple(obj)))


def forward_diff(p):
    """Forward difference scheme

    Parameters
    ----------
    p : ~numpy.ndarray
        The array to be processed.

    Returns
    -------
    p_x, p_y : tuple[~numpy.ndarray]
        The horizontal and vertical gradient components.

    """
    p_x = p.copy()
    p_x[:, 1:] -= p[:, :-1]
    p_x[:, (0)] = 0
    p_x[:, (-1)] = 0
    p_y = p.copy()
    p_y[1:, :] -= p[:-1, :]
    p_y[(0), :] = 0
    p_y[(-1), :] = 0
    return p_x, p_y


def find_row_by_galaxy_name(table, galaxy_name, fieldname='rootname69_u'):
    """
    Searches for galaxy name in table

    Args:
        table: list of dictionaries
        fieldname="rootname69_u": field to be considered the galaxy name
        galaxy_name: string

    Returns:
        table row (dictionary), or None if not found
    """
    ret = None
    for row in table:
        if row[fieldname] == galaxy_name:
            ret = row
            break
    return ret


@classmethod
def from_dict(cls, d):
    """Create RPCRequest object from dictionary"""
    return cls(d['code'], d['message'], d.get('data'))


@staticmethod
def define_argument_spec():
    """
        Define the argument spec for the ansible module
        :return: argument spec dictionary
        """
    argument_spec = dict(name=dict(required=True), description=dict(default
        =None), location=dict(required=True), alias=dict(required=True),
        port=dict(choices=[80, 443]), method=dict(choices=[
        'leastConnection', 'roundRobin']), persistence=dict(choices=[
        'standard', 'sticky']), nodes=dict(type='list', default=[]), status
        =dict(default='enabled', choices=['enabled', 'disabled']), state=
        dict(default='present', choices=['present', 'absent', 'port_absent',
        'nodes_present', 'nodes_absent']))
    return argument_spec


def renderForValue(value):
    """Render a single radio button element for a given value.

        Here the word ``value`` is used in the HTML sense, in other
        words it is a term token.
        """


def padded_list(candidate, reference_list):
    """
    Method creates a `list` where the first element is `candidate` and the rest
    `len(reference_list) - 1` elements are empty strings (''s).

    This is operation is useful when trying to construct tables where empty
    strings can represent empty cells.

    :param candidate: a list of strings
    :param reference_list: another list such that `candidate` should match it in
                           terms of number of elements
    :return: [text] + [''] * (len(reference_list) - 1)]
    """
    if not reference_list:
        raise AttributeError('The reference_list argument must be non-empty.'
            .format(reference_list))
    pad_length = len(reference_list) - len(candidate)
    return candidate + [''] * pad_length


def vertex_paint_toggle():
    """Toggle the vertex paint mode in 3D view

    """
    pass


@classmethod
def cookieJar(cls):
    """
        Class method to get a reference to the cookie jar.

        @return reference to the cookie jar (CookieJar)
        """
    if cls._cookieJar is None:
        from .CookieJar.CookieJar import CookieJar
        cls._cookieJar = CookieJar()
    return cls._cookieJar


def value2Tuple4(v):
    """Answers a tuple of 4 values. Can be used for colors and rectangles.

    >>> value2Tuple4(123)
    (123, 123, 123, 123)
    >>> value2Tuple4((2,3))
    (2, 3, 2, 3)
    >>> value2Tuple4((2,3,4,5))
    (2, 3, 4, 5)
    """
    if not isinstance(v, (list, tuple)):
        v = [v]
    if len(v) == 1:
        return v[0], v[0], v[0], v[0]
    if len(v) == 2:
        return v[0], v[1], v[0], v[1]
    if len(v) == 4:
        return v
    raise ValueError


def iter_dataset(dset):
    """
    Necessary because native pytorch implementation of __iter__ on Dataset is problematic
    :param dset:
    :return:
    """
    for i in range(len(dset)):
        yield dset[i]


@classmethod
def via_serial(cls, port, name=None, **kwargs):
    """Return a Driver with an underlying ASRL (Serial) Instrument resource.

        Parameters
        ----------
        port :
            The serial port to which the instrument is connected.
        name :
            Unique name given within Lantz to the instrument for logging purposes.
            Defaults to one generated based on the class name if not provided.
        kwargs :
            keyword arguments passed to the Resource constructor on initialize.
        **kwargs :

        Returns
        -------

        """
    resource_name = 'ASRL%s::INSTR' % port
    return cls(resource_name, name, **kwargs)


def _decorate_axes(ax, freq, kwargs):
    """Initialize axes for time-series plotting"""
    if not hasattr(ax, '_plot_data'):
        ax._plot_data = []
    ax.freq = freq
    xaxis = ax.get_xaxis()
    xaxis.freq = freq
    if not hasattr(ax, 'legendlabels'):
        ax.legendlabels = [kwargs.get('label', None)]
    else:
        ax.legendlabels.append(kwargs.get('label', None))
    ax.view_interval = None
    ax.date_axis_info = None


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

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


def update_maintenance_start_time(GatewayARN=None, HourOfDay=None,
    MinuteOfHour=None, DayOfWeek=None):
    """
    Updates a gateway's weekly maintenance start time information, including day and time of the week. The maintenance time is the time in your gateway's time zone.
    See also: AWS API Documentation

    Examples
    Updates a gateway's weekly maintenance start time information, including day and time of the week. The maintenance time is in your gateway's time zone.
    Expected Output:

    :example: response = client.update_maintenance_start_time(
        GatewayARN='string',
        HourOfDay=123,
        MinuteOfHour=123,
        DayOfWeek=123
    )

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation to return a list of gateways for your account and region.

    :type HourOfDay: integer
    :param HourOfDay: [REQUIRED]
            The hour component of the maintenance start time represented as hh , where hh is the hour (00 to 23). The hour of the day is in the time zone of the gateway.

    :type MinuteOfHour: integer
    :param MinuteOfHour: [REQUIRED]
            The minute component of the maintenance start time represented as mm , where mm is the minute (00 to 59). The minute of the hour is in the time zone of the gateway.

    :type DayOfWeek: integer
    :param DayOfWeek: [REQUIRED]
            The maintenance start time day of the week represented as an ordinal number from 0 to 6, where 0 represents Sunday and 6 Saturday.

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

    """
    pass


def apply(X, mu, sigma):
    """Apply normalization to the specified features."""
    sigma[sigma == 0] = 1
    return (X - mu) / sigma


def find_basal_edge(monolayer, apical_edge):
    """Returns the basal edge parallel to the apical edge passed
    in argument.

    Parameters
    ----------
    monolayer: a :class:`Monolayer` instance

    """
    srce, trgt, cell = monolayer.edge_df.loc[apical_edge, ['srce', 'trgt',
        'cell']]
    cell_edges = monolayer.edge_df[monolayer.edge_df['cell'] == cell]
    srce_segment = monolayer.vert_df.loc[cell_edges['srce'].values, 'segment']
    srce_segment.index = cell_edges.index
    trgt_segment = monolayer.vert_df.loc[cell_edges['trgt'].values, 'segment']
    trgt_segment.index = cell_edges.index
    b_trgt, = cell_edges[(srce_segment == 'apical') & (trgt_segment ==
        'basal') & (cell_edges['srce'] == srce)]['trgt']
    b_srce, = cell_edges[(srce_segment == 'basal') & (trgt_segment ==
        'apical') & (cell_edges['trgt'] == trgt)]['srce']
    b_edge, = cell_edges[(cell_edges['srce'] == b_srce) & (cell_edges[
        'trgt'] == b_trgt)].index
    return b_edge


@staticmethod
def _make_single_dict_for_game(team1, team2):
    """
        MATCHUP is vistor team @ home team for visitor
        MATCHUP is home team vs visitor team for home
        """
    item = {'GAME_ID': team1['GAME_ID'], 'GAME_DATE_EST': team1['GAME_DATE'
        ], 'GAME_STATUS_TEXT': 'Final', 'HOME_TEAM_ID': team1['TEAM_ID'] if
        '@' not in team1['MATCHUP'] else team2['TEAM_ID'],
        'VISITOR_TEAM_ID': team1['TEAM_ID'] if '@' in team1['MATCHUP'] else
        team2['TEAM_ID']}
    return item


def get_termsize():
    """Return terminal size as a tuple (height, width)."""
    try:
        import struct, fcntl, termios
        height, width = struct.unpack('hhhh', fcntl.ioctl(0, termios.
            TIOCGWINSZ, '\x00' * 8))[0:2]
        if not (height and width):
            height, width = 24, 79
    except (ImportError, IOError) as e:
        height, width = 24, 79
    return height, width


def edges_select_sharp(sharpness: float=0.523599):
    """Select all sharp-enough edges

    :param sharpness: Sharpness
    :type sharpness: float
    """
    pass


@staticmethod
def _map_multiple_inputs(inputs: dict, reduce_dim: bool) ->tuple:
    """Creates mapping between multiple input variables and a single output variable.

        Parameters
        ----------
        inputs
            Input variables.
        reduce_dim
            If true, input variables will be summed up, if false, they will be concatenated.
        kwargs
            Additional keyword arguments for the backend.

        Returns
        -------
        tuple
            Summed up or concatenated input variables and the mapping to the respective input variables

        """
    inputs_unique = []
    input_mapping = {}
    for key, var in inputs.items():
        node, in_op, in_var = key.split('/')
        i = 0
        inp = in_var
        while inp in inputs_unique:
            i += 1
            if inp[-2:] == f'_{i - 1}':
                inp[:-2] = f'_{i}'
            else:
                inp = f'{inp}_{i}'
        inputs_unique.append(inp)
        input_mapping[inp] = key
    if reduce_dim:
        inputs_unique = f"sum(({','.join(inputs_unique)}), 0)"
    else:
        idx = 0
        var = inputs[input_mapping[inputs_unique[idx]]]
        while not hasattr(var, 'shape'):
            idx += 1
            var = inputs[input_mapping[inputs_unique[idx]]]
        shape = var['shape']
        if len(shape) > 0:
            inputs_unique = (
                f"reshape(({','.join(inputs_unique)}), ({len(inputs_unique) * shape[0],}))"
                )
        else:
            inputs_unique = f"stack({','.join(inputs_unique)})"
    return inputs_unique, input_mapping


@classmethod
def generate_toy_data(cls, reco_vector, size=None):
    """Generate toy data according to the expectation values.

        The reco vector can have a shape ``([c,d,]n_reco_bins,)``. Assuming the
        data is of shape ``([a,b,...,]n_reco_bins,)``, the output will be of
        shape ``([a,b,...,][c,d,...,])``.

        """
    raise NotImplementedError('Must be implemented in a subclass!')


@staticmethod
def set_fold_lvl(block, val):
    """
        Sets the block fold level.

        :param block: block to modify
        :param val: The new fold level [0-7]
        """
    if block is None:
        return
    state = block.userState()
    if state == -1:
        state = 0
    if val >= 1023:
        val = 1023
    state &= 2080440319
    state |= val << 16
    block.setUserState(state)


@classmethod
def from_polynomial(cls, polynomial):
    """Create a frozen copy of the polynomial."""
    return cls(polynomial)


def get_pattern_package_name(pattern):
    """
    Returns the package name of the url pattern being analyzed
    """
    app_name = None
    if hasattr(pattern, 'app_name'):
        app_name = pattern.app_name
        if not app_name:
            app_name = pattern.urlconf_name.__package__
    return app_name


def access_debug_info():
    """Return debug info.
        """


def default_serialize_error(req, resp, exception):
    """Serialize the given instance of HTTPError.

    This function determines which of the supported media types, if
    any, are acceptable by the client, and serializes the error
    to the preferred type.

    Currently, JSON and XML are the only supported media types. If the
    client accepts both JSON and XML with equal weight, JSON will be
    chosen.

    Other media types can be supported by using a custom error serializer.

    Note:
        If a custom media type is used and the type includes a
        "+json" or "+xml" suffix, the error will be serialized
        to JSON or XML, respectively. If this behavior is not
        desirable, a custom error serializer may be used to
        override this one.

    Args:
        req: Instance of ``falcon.Request``
        resp: Instance of ``falcon.Response``
        exception: Instance of ``falcon.HTTPError``
    """
    if not exception.has_representation:
        return
    representation = None
    preferred = req.client_prefers(('application/xml', 'text/xml',
        'application/json'))
    if preferred is None:
        accept = req.accept.lower()
        if '+json' in accept:
            preferred = 'application/json'
        elif '+xml' in accept:
            preferred = 'application/xml'
    if preferred is not None:
        if preferred == 'application/json':
            representation = exception.to_json()
        else:
            representation = exception.to_xml()
        resp.body = representation
        resp.content_type = preferred
    resp.append_header('Vary', 'Accept')


def trans_filter(text: str, pattern: dict) ->str:
    """trans_filter filtering text by pattern key to value
    only len(key) == 1
    faster than replace_filter
    just use text_filter
    """
    return text.translate(str.maketrans(pattern))


@classmethod
def get_cap(cls, endpoint):
    """
        Retrieve the query cap for the given endpoint.

        Args:
            endpoint (str): Endpoint

        Returns:
            int: Max queries per 15 minutes

        """
    limit = cls.get(endpoint)
    if not limit:
        return
    return limit.cap


def hass_brightness(device):
    """Home Assistant logic for determining brightness"""
    if 'level' in device:
        level = int(int(device['level']) / 100 * 255)
        return level
    else:
        return 0


@classmethod
def empty_stats(cls):
    """Returns empty statistics object."""
    return cls(pages=0, percentage=0)


def hex_to_dec(x):
    """
    Convert hex to decimal
    """
    return int(x, 16)


def identity(game):
    """
    Leaves move preferences unchanged.

    :param Game game: game to play
    :return: None
    """
    return


def get_parsed_throttler_mode(throttler_mode):
    """ Parse the conveyor-throttler mode string. """
    direction = None
    all_activities = None
    if throttler_mode == 'DEST_PER_ACT':
        direction = 'destination'
        all_activities = False
    elif throttler_mode == 'DEST_PER_ALL_ACT':
        direction = 'destination'
        all_activities = True
    elif throttler_mode == 'SRC_PER_ACT':
        direction = 'source'
        all_activities = False
    elif throttler_mode == 'SRC_PER_ALL_ACT':
        direction = 'source'
        all_activities = True
    return direction, all_activities


def showfig(fig, aspect='auto'):
    """
    Shows a figure with a typical orientation so that x and y axes are set up as expected.
    """
    ax = fig.gca()
    alim = list(ax.axis())
    if alim[3] < alim[2]:
        temp = alim[2]
        alim[2] = alim[3]
        alim[3] = temp
        ax.axis(alim)
    ax.set_aspect(aspect)
    fig.show()


def signe(a):
    """ return 0 if a<0 , 1 else"""
    if a < 0:
        return 0
    else:
        return 1


def bake():
    """Bake fluid simulation

    """
    pass


@classmethod
def has_config(cls) ->bool:
    """
        Return ``True`` if this ``ConfigType`` has configuration that should be loaded.
        """
    return cls.path is not None


def write_read_list(readset, bipartition, sample_components,
    numeric_sample_ids, output_file):
    """
	Write a list of reads that has been used for phasing to given file object.
	readset -- core.ReadSet object with reads to be written
	bipartition -- bipartition of reads, i.e. iterable with one entry from {0,1} for each read in readset
	sample_components -- a dictionary that maps each sample to its connected components

			Each component in turn is a dict that maps each variant position to a
			component, where a component is identified by the position of its
			left-most variant

	numeric_sample_ids -- core.NumericSampleIds object mapping sample names to numeric ids as stored in each read
	output_file -- file object to write to
	"""
    assert len(readset) == len(bipartition)
    numeric_id_to_name = numeric_sample_ids.inverse_mapping()
    for read, haplotype in zip(readset, bipartition):
        sample = numeric_id_to_name[read.sample_id]
        components = sample_components[sample]
        phaseset = components[read[0].position] + 1
        print(read.name, read.source_id, sample, phaseset, haplotype, len(
            read), read[0].position + 1, read[-1].position + 1, file=
            output_file)


@staticmethod
def t_NUMBER(t):
    """
        \\b\\d+(\\.?\\d+)?\\b
        """
    if '.' in t.value:
        t.value = float(t.value)
    else:
        t.value = int(t.value)
    return t


def _shift(x, y, z, A, B, C, d):
    """
    Shift point p=(x, y, z) along n=(A, B, C) to distance d.

    It is assumed that |n| = 1. In many cases I define coordinates of n manually
    and thus know in advance that they are normalized. Do not computing
    normalization here helps to save this computation for these case.
    """
    xx = x + A * d
    yy = y + B * d
    zz = z + C * d
    return xx, yy, zz


def repeats_to_start_end(repeats, first, last):
    """Return pairs of (start, end) TimePoints corresponding to the start and
    end times of each Repeat object. If any of the start or end attributes
    are None, replace it with the end/start of the preceding/succeeding
    Repeat, respectively, or `first` or `last`.

    Parameters
    ----------
    repeats : list
        list of Repeat instances, possibly with None-valued start/end
        attributes
    first : TimePoint
        The first TimePoint in the timeline
    last : TimePoint
        The last TimePoint in the timeline

    Returns
    -------
    list
        list of (start, end) TimePoints corresponding to each Repeat in
        `repeats`

    """
    t = first
    starts = []
    ends = []
    for repeat in repeats:
        starts.append(t if repeat.start is None else repeat.start)
        if repeat.end is not None:
            t = repeat.end
    t = last
    for repeat in reversed(repeats):
        ends.append(t if repeat.end is None else repeat.end)
        if repeat.start is not None:
            t = repeat.start
    ends.reverse()
    return list(zip(starts, ends))


@classmethod
def get_one(cls, strategy):
    """Retrieve a single item from DynamoDB according to strategy.

        See :ref:`doc_get_one`

        :return: Instance of ``cls`` - The fetched item
        """
    cls._schema()
    keys = cls._parse_one_strategy(strategy, False)
    response = cls.table().get_item(Key=keys)
    if not response or 'Item' not in response:
        return None
    return cls._from_db_dict(response['Item'])


@classmethod
def add_parser(cls, parser):
    """ Add model specific arguments to command line arguments.
        @param parser: argparse.ArgumentParser. The argument parser.

        This function is used by `tfignite.parser.ArgumentParser`. It frees
        users from adding model-specific arguments to `argparse.ArgumentParser`
        in training/evaluation script.

        """
    pass


def state_str(state):
    """Return a string describing an instance via its InstanceState."""
    if state is None:
        return 'None'
    else:
        return '<%s at 0x%x>' % (state.class_.__name__, id(state.obj()))


def validate_roles(roles):
    """Return true if all given roles are valid.
        """


def conv_16upto32(val, nb):
    """ converts val (16bits) to 16+n bits (n must be comprised between 0 & 16 bits)
    :warning: conversion output shall not exceed 32bits (input shall strictly be unsigned 16bits)
    :warning: nb shall be in range 0-16 (note that using 0 doesn't change val)
    :param val: 16bit var to convert
    :param nb: nb of bit pseudo shifts to add
    :return: 16+n bit conversion result """
    return (val << nb) + (val & 65535 >> 16 - nb) & 4294967295


def get_ver():
    """
    Gather the version number from git
    """
    import subprocess
    proc = subprocess.Popen(['git', 'describe'], stdout=subprocess.PIPE)
    if proc.wait():
        return
    v = proc.stdout.read().decode().strip()
    if '-' not in v:
        ret = v
    else:
        csum = v[v.rindex('-') + 1:]
        base = v[:v.rindex('-')]
        count = base[base.rindex('-') + 1:]
        tag = base[:base.rindex('-')]
        ret = f'{tag}.post{count}+{csum}'
    return ret


@classmethod
def rebuild_index_by_source_model(cls, source_model, **kwargs):
    """
        元モデルを1つ指定してインデックスを再生成
        :param source_model:
        :return:
        """
    cls.update(cls.get_id_of_source_model(source_model), cls.
        data_dict_for_index(source_model), **kwargs)


def is_valid_hour(hour):
    """
    Check if hour value is valid
    :param hour: int|string
    :return: boolean
    """
    return hour == '*' or 23 >= hour >= 0


def relative_script(lines):
    """Return a script that'll work in a relocatable environment."""
    activate = (
        "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); execfile(activate_this, dict(__file__=activate_this)); del os, activate_this"
        )
    activate_at = None
    for idx, line in reversed(list(enumerate(lines))):
        if line.split()[:3] == ['from', '__future__', 'import']:
            activate_at = idx + 1
            break
    if activate_at is None:
        activate_at = 1
    return lines[:activate_at] + ['', activate, ''] + lines[activate_at:]


def add_marker_slide(CLIP_OT_add_marker=None, TRANSFORM_OT_translate=None):
    """Add new marker and slide it with mouse until mouse button release

    :param CLIP_OT_add_marker: Add Marker, Place new marker at specified location
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def effective_lang():
    """Returns language of member's choice."""


@classmethod
def _file_for_module(cls, module):
    """Return the relevant file for the module."""
    return cls._archive_for_zip_module(module) or cls._file_for_file_module(
        module)


def status(message, verbose=True):
    """Print a status update if a flag is true."""
    if verbose:
        print(message)
    return


@classmethod
def _fill_salary(cls, workbook, report, user):
    """Fill salary to exel."""
    worksheet = workbook.active
    brigadiers_path = super().get_root_path() / 'data' / 'brigadiers'
    brigadiers = super().load_data(data_path=brigadiers_path, user=user)
    worksheet['G28'] = report.totall
    ktu = report.workers_showing['бух.']['КТУ']
    hours = report.workers_showing['бух.']['часы']
    salary = report.workers_showing['бух.']['зарплата']
    for worker_number, worker in enumerate(ktu, start=1):
        row_number = 30 + worker_number
        worksheet['B' + str(row_number)] = worker_number
        worksheet['C' + str(row_number)] = super().make_name_short(worker)
        worksheet['D' + str(row_number)] = hours[worker]
        worksheet['G' + str(row_number)] = ktu[worker]
        addition = 0
        if worker in brigadiers:
            addition = 0.15
        worksheet['M' + str(row_number)] = addition
        worksheet['P' + str(row_number)] = salary[worker]
        worksheet['J' + str(row_number)] = salary[worker] / (addition + 1)


def distance(ad1, ad2, method=None):
    """ Alias for distance between AutoData.
    """
    return ad1.distance(ad2, method=method)


def addrowzip(prob, bo, side, sign, rhs, ind, coef):
    """
    Eliminate zero coefficients from coef and corresponding indices,
    then add row to branching object
    """
    ind2 = []
    coe2 = []
    for i in range(len(coef)):
        if coef[i] != 0:
            coe2.append(coef[i])
            ind2.append(ind[i])
    ind3, coe3 = [], []
    rhs3, status = prob.presolverow(sign, ind2, coe2, rhs, 100, ind3, coe3)
    if len(ind3) == 1:
        if sign == 'G':
            sign = 'L'
        else:
            sign = 'U'
            if coe3[0] < 0:
                if sign == 'L':
                    sign = 'U'
                else:
                    sign = 'L'
        bo.addbounds(side, [sign], [ind3[0]], [rhs3 / coe3[0]])
    elif len(ind3) > 1:
        bo.addrows(side, [sign], [rhs3], [0, len(ind3)], ind3, coe3)


@classmethod
def from_config(cls, config):
    """Return workflow object for the workflow specified by `config`.

        See :func:`Workflow.from_path` for further information.
        """
    return cls.from_path(config['file'])


def dP_demister_wet_ElDessouky(vs, voidage, d_wire, L=1):
    """Calculates wet pressure drop across a demister, using the
    correlation in [1]_. Uses only their own experimental data.

    .. math::
        \\frac{\\Delta P}{L} = 0.002357(1-\\epsilon)^{0.375798}(V)^{0.81317}
        (d_w)^{-1.56114147}

    Parameters
    ----------
    vs : float
        Superficial velocity of fluid, Q/A [m/s]
    voidage : float
        Voidage of bed of the demister material, normally ~0.98 []
    d_wire : float
        Diameter of mesh wire,[m]
    L : float, optional
        Length of the demister [m]

    Returns
    -------
    dP : float
        Pressure drop across a dry demister [Pa]

    Notes
    -----
    No dependency on the liquid properties is included here. Because of the
    exponential nature of the correlation, the limiting pressure drop as V
    is lowered is 0 Pa. A dry pressure drop correlation should be compared with
    results from this at low velocities, and the larger of the
    two pressure drops used.

    The correlation in [1]_ was presented as follows, with wire diameter in
    units of mm, density in kg/m^3, V in m/s, and dP in Pa/m.

    .. math::
        \\Delta P = 3.88178(\\rho_{mesh})^{0.375798}(V)^{0.81317}
        (d_w)^{-1.56114147}

    Here, the correlation is converted to base SI units and to use voidage;
    not all demisters are stainless steel as in [1]_. A density of 7999 kg/m^3
    was used in the conversion.

    In [1]_, V ranged from 0.98-7.5 m/s, rho from 80.317-208.16 kg/m^3, depth
    from 100 to 200 mm, wire diameter of 0.2mm to 0.32 mm, and particle
    diameter from 1 to 5 mm.

    Examples
    --------
    >>> dP_demister_wet_ElDessouky(6, 0.978, 0.00032)
    688.9216420105029

    References
    ----------
    .. [1] El-Dessouky, Hisham T, Imad M Alatiqi, Hisham M Ettouney, and Noura
       S Al-Deffeeri. "Performance of Wire Mesh Mist Eliminator." Chemical
       Engineering and Processing: Process Intensification 39, no. 2 (March
       2000): 129-39. doi:10.1016/S0255-2701(99)00033-1.
    """
    return L * 0.002356999643727531 * (1 - voidage
        ) ** 0.375798 * vs ** 0.81317 * d_wire ** -1.56114147


def Breakpoints(ID, cadence='lc', **kwargs):
    """

  Returns the location of the breakpoints for a given target.

  :param int ID: The target ID number
  :param str cadence: The light curve cadence. Default `lc`

  .. note :: The number corresponding to a given breakpoint is the number             of cadences *since the beginning of the campaign*.

  """
    raise NotImplementedError('This mission is not yet supported.')


def _shorten_file_path(line):
    """Shorten file path in error lines for more readable tracebacks."""
    start = line.lower().find('file')
    if start < 0:
        return line
    first_quote = line.find('"', start)
    if first_quote < 0:
        return line
    second_quote = line.find('"', first_quote + 1)
    if second_quote < 0:
        return line
    path = line[first_quote + 1:second_quote]
    new_path = '/'.join(path.split('/')[-3:])
    return line[:first_quote] + '[...]/' + new_path + line[second_quote + 1:]


def get_thumbnail_image(img, width, height, **options):
    """get thumbnail image

    Attribute:
        img -- PIL image instance
        width -- width of thumbnail
        height -- height of thumbnail
        kwargs -- Options used in PIL thumbnail method

    Usage::
        >>> from thumbnailfield.compatibility import Image
        >>> img = Image.new('RGBA', (1000, 800))
        >>> thumb = get_thumbnail_image(img, 100, 100)
        >>> assert thumb.size[0] == 100
        >>> assert thumb.size[1] == 80
    """
    thumbs = img.copy()
    thumbs.thumbnail(size=(width, height), **options)
    return thumbs


def get_channel_block(peer_ex, ord_name, ord_namespace, channel, cmd_suffix):
    """Get channel block from Peer.

    Args:
        peer_ex (Executor): A Pod Executor representing a Peer.
        ord_name (str): Name of the orderer we wish to communicate with.
        ord_namespace (str): Namespace where the orderer resides.
        channel (str): Name of the channel we with to retrieve.
        cmd_suffix (str): Suffix to the "peer channel fetch" command.

    Returns:
        bool: Were we able to fetch the channel?
    """
    channel_file = f'/var/hyperledger/{channel}.block'
    channel_block, _ = peer_ex.execute(f'ls {channel_file}')
    if not channel_block:
        res, err = peer_ex.execute(
            f"bash -c 'peer channel fetch 0 {channel_file} " +
            f'-c {channel} ' +
            f"-o {ord_name}-hlf-ord.{ord_namespace}.svc.cluster.local:7050 {cmd_suffix}'"
            )
        if err:
            return False
    return True


def reverse(d):
    """
    Reverse a `dict`, creating a new `dict` where keys and values are switched.

    Example:

        >>> reverse({'one': 1, 'two': 2, 'three': 3})
        {1: 'one', 2: 'two', 3: 'three'})

    This function requires that:

      1. The values will be distinct, i.e. no value will appear more than once.
      2. All the values be hashable.

    """
    new_d = {}
    for key, value in d.items():
        if value in new_d:
            raise Exception(
                f'Value {value} appeared twice! Once with a key of {key} and then again with a key of {new_d[value]}. This function is intended only for dicts with distinct values.'
                )
        new_d[value] = key
    return new_d


@staticmethod
def cmyk_to_rgb(cmyk_value):
    """
        Converts a color value of DeviceCMYK to DeviceRGB (returns a tuple).
        """
    cyan, magenta, yellow, black = cmyk_value
    return 1.0 - min(1, cyan + black), 1.0 - min(1, magenta + black
        ), 1.0 - min(1, yellow + black)


def asciify(label):
    """To be safe, we will use only ascii for strings inside HDF5"""
    return label.replace(u'→', '-').encode('ascii')


def provider_parser(subparser):
    """Generate a subparser for Google Cloud DNS"""
    subparser.description = """
        The Google Cloud DNS provider requires the JSON file which contains the service account info to connect to the API.
        This service account must own the project role DNS > DNS administrator for the project associated to the DNS zone.
        You can create a new service account, associate a private key, and download its info through this url:
        https://console.cloud.google.com/iam-admin/serviceaccounts?authuser=2"""
    subparser.add_argument('--auth-service-account-info', help=
        """
        specify the service account info in the Google JSON format:
        can be either the path of a file prefixed by 'file::' (eg. file::/tmp/service_account_info.json)
        or the base64 encoded content of this file prefixed by 'base64::'
        (eg. base64::eyJhbGciOyJ...)"""
        )


def tornado_start():
    """Just start tornado ioloop

    :return: None
    """
    from tornado.ioloop import IOLoop
    IOLoop.instance().start()


def identity(x):
    """The identity function."""
    return x


def vertex_weight_normalize_active_vertex():
    """Normalize active vertex’s weights

    """
    pass


def _reversal(current, prior):
    """
    do we observe a reversal
    :param current:
    :param prior:
    :return:
         1 if red to green
         0 if none
        -1 if green to red
    """
    if current == 1 and prior == -1:
        return 1
    elif current == -1 and prior == 1:
        return -1
    else:
        return 0


def retry(times, func, *args, **kwargs):
    """Try to execute multiple times function mitigating exceptions.

    :param times: Amount of attempts to execute function
    :param func: Function that should be executed
    :param args: *args that are passed to func
    :param kwargs: **kwargs that are passed to func

    :raises Exception: Raise any exception that can raise func
    :returns: Result of func(*args, **kwargs)
    """
    for i in range(times):
        try:
            return func(*args, **kwargs)
        except Exception:
            if i == times - 1:
                raise


def select_more():
    """Select keyframes beside already selected ones

    """
    pass


def log10(img):
    """
        Element-wise base 10 log of an `Image`.

        If the `Image` is empty, returns the empty `Image`.

        Example
        -------
        >>> import descarteslabs.workflows as wf
        >>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
        >>> img.log10().compute(geoctx) # doctest: +SKIP
        ImageResult:
        ...
        """
    from ..math import arithmetic
    return arithmetic.log10(img)


def _css_select(soup, css_selector):
    """ Returns the content of the element pointed by the CSS selector,
    or an empty string if not found """
    selection = soup.select(css_selector)
    retour = ''
    if len(selection) > 0:
        if hasattr(selection[0], 'text'):
            retour = selection[0].text.strip()
    return retour


def merge_paths(base_uri, relative_path):
    """Merge a base URI's path with a relative URI's path."""
    if base_uri.path is None and base_uri.authority is not None:
        return '/' + relative_path
    else:
        path = base_uri.path or ''
        index = path.rfind('/')
        return path[:index] + '/' + relative_path


def _insert_extensions(c):
    """Insert the ``extensions`` variable into the configuration state.
    """
    c['extensions'] = ['sphinx.ext.autodoc', 'sphinx.ext.doctest',
        'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage',
        'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinxcontrib.jinja',
        'sphinx-prompt', 'sphinxcontrib.autoprogram', 'numpydoc',
        'sphinx_automodapi.automodapi', 'sphinx_automodapi.smart_resolver',
        'breathe', 'sphinx_click.ext', 'documenteer.sphinxext',
        'documenteer.sphinxext.lssttasks']
    return c


def split_unescape(s, delim, escape='\\', unescape=True):
    """
        >>> split_unescape('foo,bar', ',')
        ['foo', 'bar']
        >>> split_unescape('foo$,bar', ',', '$')
        ['foo,bar']
        >>> split_unescape('foo$$,bar', ',', '$', unescape=True)
        ['foo$', 'bar']
        >>> split_unescape('foo$$,bar', ',', '$', unescape=False)
        ['foo$$', 'bar']
        >>> split_unescape('foo$', ',', '$', unescape=True)
        ['foo$']
        """
    ret = []
    current = []
    itr = iter(s)
    for ch in itr:
        if ch == escape:
            try:
                if not unescape:
                    current.append(escape)
                current.append(next(itr))
            except StopIteration:
                if unescape:
                    current.append(escape)
        elif ch == delim:
            ret.append(''.join(current))
            current = []
        else:
            current.append(ch)
    ret.append(''.join(current))
    return ret


def download_version(servermap, version):
    """Download a specific version of the file, using the servermap
        as a guide to where the shares are located.

        I return a Deferred that fires with the requested contents, or
        errbacks with UnrecoverableFileError. Note that a servermap that was
        updated with MODE_ANYTHING or MODE_READ may not know about shares for
        all versions (those modes stop querying servers as soon as they can
        fulfil their goals), so you may want to use MODE_CHECK (which checks
        everything) to get increased visibility.
        """


def get_servermap():
    """Return dict mapping IServer instance to a set of share numbers."""


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

        :param SmartSyncCreateAdminPrivilegeReportType val:
        :rtype: EventType
        """
    return cls('smart_sync_create_admin_privilege_report', val)


def replace_set_selected():
    """Replace text with specified text and set as selected

    """
    pass


def _truncate_seq_pair(tokens_a, tokens_b, max_length):
    """Truncates a sequence pair in place to the maximum length."""
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_length:
            break
        if len(tokens_a) > len(tokens_b):
            tokens_a.pop()
        else:
            tokens_b.pop()


def get_molecules(reactions):
    """
    Get a list of all molecules used by reactions

    Args:
           reaction (dict): all reactions that will be used by transport
    Returns:
           self.molecule_ids (list): all molecules used by these reactions
    """
    molecule_ids = []
    for reaction_id, specs in reactions.iteritems():
        stoichiometry = specs['stoichiometry']
        substrates = stoichiometry.keys()
        enzymes = specs['catalyzed by']
        molecule_ids.extend(substrates)
        molecule_ids.extend(enzymes)
    return list(set(molecule_ids))


def getSteps():
    """Return a list of dictionary objects. For invariant builds
        (those which always use the same set of Steps), this should always
        return the complete list, however some of the steps may not have
        started yet (step.getTimes()[0] will be None). For variant builds,
        this may not be complete (asking again later may give you more of
        them)."""


def file_to_dataset(file):
    """Example function to derive datasets from file names"""
    if 'ZJet' in file:
        return 'Z'
    elif 'WJet' in file:
        return 'W'
    elif 'HToInvisible' in file:
        return 'Hinv'


def inherited_branches(bases):
    """Returns a dictionary of combined branches for all the given bases.

    Bases are evaluated in reverse order (right to left), mimicking Python's
    method resolution order. This means that branches defined on multiple
    bases will take the value from the leftmost base.
    """
    branches = {}
    for base in reversed(bases):
        branches.update(getattr(base, '_BRANCHES', {}))
    return branches


def snap_selected_to_grid():
    """Snap selected item(s) to nearest grid division

    """
    pass


def get_resource_string(manager, resource_name):
    """Return a string containing the contents of `resource_name`

        `manager` must be an ``IResourceManager``"""


def strain_static(p, pu, yc):
    """
    Static strain using p-y model developed by Matlock

    Parameters
    ----------------
    p -- stress
    pu -- ultimate stress
    yc -- ultimate displacement

    Output
    ----------------
    y -- soil strain
    """
    if p <= pu:
        y = (p / (0.5 * pu)) ** 3 * yc
    else:
        raise ValueError('The applied stress is LARGER than ultimate strength')
    return y


@staticmethod
def argv_to_cmdline(argv):
    """
        Convert a list of arguments to a single command line string.

        @type  argv: list( str )
        @param argv: List of argument strings.
            The first element is the program to execute.

        @rtype:  str
        @return: Command line string.
        """
    cmdline = list()
    for token in argv:
        if not token:
            token = '""'
        else:
            if '"' in token:
                token = token.replace('"', '\\"')
            if ' ' in token or '\t' in token or '\n' in token or '\r' in token:
                token = '"%s"' % token
        cmdline.append(token)
    return ' '.join(cmdline)


def app_template_install(overwrite: bool=True, filepath: str='',
    filter_folder: bool=True, filter_glob: str='*.zip'):
    """Install an application-template

    :param overwrite: Overwrite, Remove existing template with the same ID
    :type overwrite: bool
    :param filepath: filepath
    :type filepath: str
    :param filter_folder: Filter folders
    :type filter_folder: bool
    :param filter_glob: filter_glob
    :type filter_glob: str
    """
    pass


def get_default_axes_id(axes):
    """Get the default axes_id."""
    for axes_id, ax in axes.items():
        if ax['xaxis']['position'] == 'bottom' and ax['yaxis']['position'
            ] == 'left':
            return axes_id
    return None


@classmethod
def update(cls, id, xml):
    """
        Updates a single record on the server

        :param id: ID of the record to be updated
        :param xml: Details to be updated in XML
        """
    raise Exception('Not Implemented Yet')


def register_handler(handler):
    """
    Install application-specific WMF image handler.

    :param handler: Handler object.
    """
    global _handler
    _handler = handler


@classmethod
def from_file(cls, path):
    """Make a Nowrc instance from given file.
        """
    instance = cls()
    instance.read(path)
    return instance


@classmethod
def all(cls):
    """
        Returns multiple Union objects
        """
    client = cls._new_api_client()
    return client.make_request(cls, 'get')


@classmethod
def has_archiving(cls):
    """Returns whether it supports archiving items on the fetch process.

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


def get_all_app(isdsAppliance, check_mode=False, force=False):
    """
    Retrieving all application interfaces
    :rtype: (str, dict)
    """
    return isdsAppliance.invoke_get('Retrieving all application interfaces',
        '/application_interfaces')


def create_raw_request(data):
    """Converts the raw request into a POST string.

    Parameters:
        data (dict): The POST request data dictionary.

    Returns:
        str: The POST request data as a formatted string.
    """
    if data:
        raw_strings = []
        for key, item in data.items():
            raw_strings.append('{}={}'.format(key, item))
        return '&'.join(raw_strings)
    return data


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

        :param str val:
        :rtype: GetAccountBatchError
        """
    return cls('no_account', val)


def _classify(srna_type, attr, samples):
    """
    Parse the line and return one
    line for each category and sample.
    """
    lines = []
    counts = dict(zip(samples, attr['Expression'].split(',')))
    for s in counts:
        if int(counts[s]) > 0:
            lines.append([srna_type, s, counts[s]])
        if attr['Variant'].find('iso') == -1:
            continue
        for v in attr['Variant'].split(','):
            if int(counts[s]) > 0:
                lines.append([v.split(':')[0], s, counts[s]])
    return lines


def get_slope_inter(writer):
    """ Return slope, intercept from array writer object

    Parameters
    ----------
    writer : ArrayWriter instance

    Returns
    -------
    slope : scalar
        slope in `writer` or 1.0 if not present
    inter : scalar
        intercept in `writer` or 0.0 if not present

    Examples
    --------
    >>> arr = np.arange(10)
    >>> get_slope_inter(ArrayWriter(arr))
    (1.0, 0.0)
    >>> get_slope_inter(SlopeArrayWriter(arr))
    (1.0, 0.0)
    >>> get_slope_inter(SlopeInterArrayWriter(arr))
    (1.0, 0.0)
    """
    try:
        slope = writer.slope
    except AttributeError:
        slope = 1.0
    try:
        inter = writer.inter
    except AttributeError:
        inter = 0.0
    return slope, inter


def enabled():
    """
        checks if issuu is enabled
        """


def exclusive_dict_merge(a, b):
    """
    Merges two dictionaries confirming that their are no
    keys present in both dictionaries.
    """
    assert not set(a.keys()) & set(b.keys())
    c = a.copy()
    c.update(b)
    return c


def p_expression_seq(p):
    """expression_seq : expression COMMA expression_seq
                      | expression"""
    if len(p) == 4:
        p[0] = [p[1]] + p[3]
    else:
        p[0] = [p[1]]


def startpoint(xyz):
    """ First point of the track

    Parameters
    -------------
    xyz : array, shape(N,3)
        Track.

    Returns
    ---------
    sp : array, shape(3,)
        First track point.

    Examples
    ----------
    >>> from dipy.tracking.metrics import startpoint
    >>> import numpy as np
    >>> theta=np.pi*np.linspace(0,1,100)
    >>> x=np.cos(theta)
    >>> y=np.sin(theta)
    >>> z=0*x
    >>> xyz=np.vstack((x,y,z)).T
    >>> sp=startpoint(xyz)
    >>> sp.any()==xyz[0].any()
    True

    """
    return xyz[0]


def allocate_public_virtual_interface(connectionId=None, ownerAccount=None,
    newPublicVirtualInterfaceAllocation=None):
    """
    Provisions a public virtual interface to be owned by a different customer.
    The owner of a connection calls this function to provision a public virtual interface which will be owned by another AWS customer.
    Virtual interfaces created using this function must be confirmed by the virtual interface owner by calling ConfirmPublicVirtualInterface. Until this step has been completed, the virtual interface will be in 'Confirming' state, and will not be available for handling traffic.
    When creating an IPv6 public virtual interface (addressFamily is 'ipv6'), the customer and amazon address fields should be left blank to use auto-assigned IPv6 space. Custom IPv6 Addresses are currently not supported.
    See also: AWS API Documentation

    :example: response = client.allocate_public_virtual_interface(
        connectionId='string',
        ownerAccount='string',
        newPublicVirtualInterfaceAllocation={
            'virtualInterfaceName': 'string',
            'vlan': 123,
            'asn': 123,
            'authKey': 'string',
            'amazonAddress': 'string',
            'customerAddress': 'string',
            'addressFamily': 'ipv4'|'ipv6',
            'routeFilterPrefixes': [
                {
                    'cidr': 'string'
                },
            ]
        }
    )

    :type connectionId: string
    :param connectionId: [REQUIRED]
            The connection ID on which the public virtual interface is provisioned.
            Default: None

    :type ownerAccount: string
    :param ownerAccount: [REQUIRED]
            The AWS account that will own the new public virtual interface.
            Default: None

    :type newPublicVirtualInterfaceAllocation: dict
    :param newPublicVirtualInterfaceAllocation: [REQUIRED]
            Detailed information for the public virtual interface to be provisioned.
            Default: None
            virtualInterfaceName (string) -- [REQUIRED]The name of the virtual interface assigned by the customer.
            Example: 'My VPC'
            vlan (integer) -- [REQUIRED]The VLAN ID.
            Example: 101
            asn (integer) -- [REQUIRED]The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.
            Example: 65000
            authKey (string) --The authentication key for BGP configuration.
            Example: asdf34example
            amazonAddress (string) --IP address assigned to the Amazon interface.
            Example: 192.168.1.1/30 or 2001:db8::1/125
            customerAddress (string) --IP address assigned to the customer interface.
            Example: 192.168.1.2/30 or 2001:db8::2/125
            addressFamily (string) --Indicates the address family for the BGP peer.
            ipv4 : IPv4 address family
            ipv6 : IPv6 address family
            routeFilterPrefixes (list) --A list of routes to be advertised to the AWS network in this region (public virtual interface).
            (dict) --A route filter prefix that the customer can advertise through Border Gateway Protocol (BGP) over a public virtual interface.
            cidr (string) --CIDR notation for the advertised route. Multiple routes are separated by commas.
            IPv6 CIDRs must be at least a /64 or shorter
            Example: 10.10.10.0/24,10.10.11.0/24,2001:db8::/64

    :rtype: dict
    :return: {
        'ownerAccount': 'string',
        'virtualInterfaceId': 'string',
        'location': 'string',
        'connectionId': 'string',
        'virtualInterfaceType': 'string',
        'virtualInterfaceName': 'string',
        'vlan': 123,
        'asn': 123,
        'authKey': 'string',
        'amazonAddress': 'string',
        'customerAddress': 'string',
        'addressFamily': 'ipv4'|'ipv6',
        'virtualInterfaceState': 'confirming'|'verifying'|'pending'|'available'|'down'|'deleting'|'deleted'|'rejected',
        'customerRouterConfig': 'string',
        'virtualGatewayId': 'string',
        'routeFilterPrefixes': [
            {
                'cidr': 'string'
            },
        ],
        'bgpPeers': [
            {
                'asn': 123,
                'authKey': 'string',
                'addressFamily': 'ipv4'|'ipv6',
                'amazonAddress': 'string',
                'customerAddress': 'string',
                'bgpPeerState': 'verifying'|'pending'|'available'|'deleting'|'deleted',
                'bgpStatus': 'up'|'down'
            },
        ]
    }

    :returns:
    ipv4 : IPv4 address family
    ipv6 : IPv6 address family

    """
    pass


def forward_checking(csp, var, value, assignment, removals):
    """Prune neighbor values inconsistent with var=value."""
    for B in csp.neighbors[var]:
        if B not in assignment:
            for b in csp.curr_domains[B][:]:
                if not csp.constraints(var, value, B, b):
                    csp.prune(B, b, removals)
            if not csp.curr_domains[B]:
                return False
    return True


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_str()
    return parameters


@staticmethod
def workbench_scenarios():
    """A canned scenario for display in the workbench."""
    return [('HTML5XBlock', '<html5/>\n             '), (
        'HTML5XBlock with sanitized content',
        """<html5 data="My custom html"/>
             """
        ), ('HTML5XBlock with JavaScript',
        """<html5
                    data="My custom html"
                    allow_javascript="true"
                />
             """
        ), ('HTML5XBlock with JavaScript not allowed',
        """<html5
                    data="My custom html"
                    allow_javascript="false"
                />
             """
        ), ('Multiple HTML5XBlock',
        """<vertical_demo>
                <html5/>
                <html5/>
                <html5/>
                </vertical_demo>
             """
        )]


def modify_cluster_parameter_group(ParameterGroupName=None, Parameters=None):
    """
    Modifies the parameters of a parameter group.
    For more information about parameters and parameter groups, go to Amazon Redshift Parameter Groups in the Amazon Redshift Cluster Management Guide .
    See also: AWS API Documentation

    :example: response = client.modify_cluster_parameter_group(
        ParameterGroupName='string',
        Parameters=[
            {
                'ParameterName': 'string',
                'ParameterValue': 'string',
                'Description': 'string',
                'Source': 'string',
                'DataType': 'string',
                'AllowedValues': 'string',
                'ApplyType': 'static'|'dynamic',
                'IsModifiable': True|False,
                'MinimumEngineVersion': 'string'
            },
        ]
    )

    :type ParameterGroupName: string
    :param ParameterGroupName: [REQUIRED]
            The name of the parameter group to be modified.

    :type Parameters: list
    :param Parameters: [REQUIRED]
            An array of parameters to be modified. A maximum of 20 parameters can be modified in a single request.
            For each parameter to be modified, you must supply at least the parameter name and parameter value; other name-value pairs of the parameter are optional.
            For the workload management (WLM) configuration, you must supply all the name-value pairs in the wlm_json_configuration parameter.
            (dict) --Describes a parameter in a cluster parameter group.
            ParameterName (string) --The name of the parameter.
            ParameterValue (string) --The value of the parameter.
            Description (string) --A description of the parameter.
            Source (string) --The source of the parameter value, such as 'engine-default' or 'user'.
            DataType (string) --The data type of the parameter.
            AllowedValues (string) --The valid range of values for the parameter.
            ApplyType (string) --Specifies how to apply the WLM configuration parameter. Some properties can be applied dynamically, while other properties require that any associated clusters be rebooted for the configuration changes to be applied. For more information about parameters and parameter groups, go to Amazon Redshift Parameter Groups in the Amazon Redshift Cluster Management Guide .
            IsModifiable (boolean) --If true , the parameter can be modified. Some parameters have security or operational implications that prevent them from being changed.
            MinimumEngineVersion (string) --The earliest engine version to which the parameter can apply.

    :rtype: dict
    :return: {
        'ParameterGroupName': 'string',
        'ParameterGroupStatus': 'string'
    }

    """
    pass


def localview():
    """Toggle display of selected object(s) separately and centered in view

    """
    pass


def size_to_kb_mb_string(data_size: int, as_additional_info: bool=False) ->str:
    """Returns human-readable string with kilobytes or megabytes depending on the data_size range.

		:param data_size: data size in bytes to convert
		:param as_additional_info:
		if True, the dynamic data appear in round bracket after the number in bytes. e.g. '12345678 bytes (11.7 MB)'
		if False, only the dynamic data is returned e.g. '11.7 MB' """
    if data_size < 1024:
        as_additional_info = False
        dynamic = f'{data_size} bytes'
    elif data_size < 1048576:
        dynamic = f'{data_size / 1024:0.1f} kB'
    else:
        dynamic = f'{data_size / 1048576:0.1f} MB'
    if as_additional_info:
        return f'{data_size} bytes ({dynamic})'
    else:
        return dynamic


def exp_str(dictionary, key):
    """Return exponent string. An empty string if exponent is 1.
    """
    if dictionary[key] == 1:
        return ''
    else:
        return '**' + str(dictionary[key])


@classmethod
def area_diff(cls, x, y, z, base=0, tol=0.001):
    """ area diff = area up - area down
        """
    return cls.area_up(x, y, z, base, tol) - cls.area_down(x, y, z, tol, base)


def degrees(d, m, s):
    """Return the decimal value of an angle expressed in degrees, minutes
    and seconds.
    """
    return d + m / 60.0 + s / 3600.0


def get_default_translations_dict(default_lang, additional_languages):
    """Generate a TRANSLATIONS dict matching the config from 'format_default_translations_config'."""
    tr = {default_lang: ''}
    for l in additional_languages:
        tr[l] = './' + l
    return tr


def xyz2zyx(dic, data):
    """
    3D Matrix transpose
    """
    raise NotImplementedError


def tpc_abort(transaction):
    """Abort the transaction.

        The argument is the same object passed to tpc_begin.

        Any changes made by the transaction are discarded.

        This call is ignored is the storage is not participating in
        two-phase commit or if the given transaction is not the same
        as the transaction the storage is commiting.
        """


def _subset(subset, superset):
    """True if subset is a subset of superset.

    :param dict subset: subset to compare.
    :param dict superset: superset to compare.
    :return: True iif all pairs (key, value) of subset are in superset.
    :rtype: bool
    """
    result = True
    for k in subset:
        result = k in superset and subset[k] == superset[k]
        if not result:
            break
    return result


def mangle_name(u, du, c, name):
    """Mangle a name from a triplet (used in check_fortran_mangling)"""
    return getattr(name, c)() + u + (name.find('_') != -1 and du or '')


def get_completions(prefix):
    """Return a list of all suffixes that could complete the given
        prefix."""


def calculate_reff(fit):
    """
    Calculate number of effective samples divided by
    the number of actual samples.
    """
    df_summary = fit.summary()
    neff = float(df_summary[['N_Eff']].astype(int).mean())
    return neff / (fit.chains * fit.draws)


@classmethod
def from_config(cls, config):
    """Instantiates an initializer from a configuration dictionary.

        Parameters
        ----------
        config : A python dictionary.
            It will typically be the output of `get_config`.

        Returns
        -------
            An Initializer instance.
        """
    if 'dtype' in config:
        config.pop('dtype')
    return cls(**config)


def _fullname(o):
    """Return the fully-qualified name of a function."""
    return o.__module__ + '.' + o.__name__ if o.__module__ else o.__name__


def moment_ult(L, D, gamma):
    """
    Ultimate static moment

    Parameters
    ----------------
    L -- Pile length
    D -- Pile diameter
    gamma -- Submerged unit weight

    Output
    ----------------
    m_ult -- Ultimate static moment
    """
    m_ult = L ** 3 * D * gamma * 0.6
    return m_ult


@staticmethod
def match_args(value, args):
    """check whether the value match the pattern args."""
    return value in args


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