def get_campaign_activities(ApplicationId=None, CampaignId=None, PageSize=
    None, Token=None):
    """
    Returns information about the activity performed by a campaign.

    :example: response = client.get_campaign_activities(
        ApplicationId='string',
        CampaignId='string',
        PageSize='string',
        Token='string'
    )

    :type ApplicationId: string
    :param ApplicationId: [REQUIRED]

    :type CampaignId: string
    :param CampaignId: [REQUIRED]

    :type PageSize: string
    :param PageSize:

    :type Token: string
    :param Token:

    :rtype: dict
    :return: {
        'ActivitiesResponse': {
            'Item': [
                {
                    'ApplicationId': 'string',
                    'CampaignId': 'string',
                    'End': 'string',
                    'Id': 'string',
                    'Result': 'string',
                    'ScheduledStart': 'string',
                    'Start': 'string',
                    'State': 'string',
                    'SuccessfulEndpointCount': 123,
                    'TimezonesCompletedCount': 123,
                    'TimezonesTotalCount': 123,
                    'TotalEndpointCount': 123,
                    'TreatmentId': 'string'
                },
            ]
        }
    }

    :returns:
    (dict) -- 200 response
    ActivitiesResponse (dict) -- Activities for campaign.
    Item (list) -- List of campaign activities
    (dict) -- Activity definition
    ApplicationId (string) -- The ID of the application to which the campaign applies.
    CampaignId (string) -- The ID of the campaign to which the activity applies.
    End (string) -- The actual time the activity was marked CANCELLED or COMPLETED. Provided in ISO 8601 format.
    Id (string) -- The unique activity ID.
    Result (string) -- Indicates whether the activity succeeded. Valid values: SUCCESS, FAIL
    ScheduledStart (string) -- The scheduled start time for the activity in ISO 8601 format.
    Start (string) -- The actual start time of the activity in ISO 8601 format.
    State (string) -- The state of the activity. Valid values: PENDING, INITIALIZING, RUNNING, PAUSED, CANCELLED, COMPLETED
    SuccessfulEndpointCount (integer) -- The total number of endpoints to which the campaign successfully delivered messages.
    TimezonesCompletedCount (integer) -- The total number of timezones completed.
    TimezonesTotalCount (integer) -- The total number of unique timezones present in the segment.
    TotalEndpointCount (integer) -- The total number of endpoints to which the campaign attempts to deliver messages.
    TreatmentId (string) -- The ID of a variation of the campaign used for A/B testing.

    """
    pass


def delete_document(DocumentId=None):
    """
    Permanently deletes the specified document and its associated metadata.
    See also: AWS API Documentation

    :example: response = client.delete_document(
        DocumentId='string'
    )

    :type DocumentId: string
    :param DocumentId: [REQUIRED]
            The ID of the document.

    """
    pass


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

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

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


def Bft_sigmoid(sc, d, show=False):
    """ function [param]=fitSigmoid2Scores(posFeats, negFeats, classifier, display)
     original de A.Soto
     nPosExamples=size(posFeats,1);
     nNegExamples=size(negFeats,1);

     [predict_label, accuracy, posScores]=svmpredict31EchoOff(ones(nPosExamples,1), posFeats, classifier);
     [predict_label, accuracy, negScores]=svmpredict31EchoOff(ones(nNegExamples,1), negFeats, classifier);

     Modificado por D.Mery

     With collaboration from:
     Diego Patiño (dapatinoco@unal.edu.co) -> Translated implementation into python (2016)
    """
    """if d.size > 2:
        dneg = np.amin(d);
        dpos = np.amax(d);

        posScores = sc(d == dpos);
        negScores = sc(d == dneg);

        nPosExamples = length(posScores);
        nNegExamples = length(negScores);

        x = [negScores;
        posScores];

        y = [zeros(nNegExamples, 1);
        ones(nPosExamples, 1)];

        param = nlinfit(x, y, @ fsig, [-1 0.05]);"""
    return 0


@classmethod
def construct_scan_limit(cls, count):
    """
        Create a condition that will limit the number of items scanned

        Parameters
        ----------
        count : int

        Returns
        -------
        condition : :class:`.Condition`

        """
    c = cls()
    c.scan_limit = count
    return c


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

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


def filter_raising_callables(it, exception, *args, **kwargs):
    """
    Filters all callable items inside the given iterator that raise the
    given exceptions.

    :param it:        The iterator to filter.
    :param exception: The (tuple of) exception(s) to filter for.
    :param args:      Positional arguments to pass to the callable.
    :param kwargs:    Keyword arguments to pass to the callable.
    """
    for elem in it:
        try:
            yield elem(*args, **kwargs)
        except exception:
            pass


def unpaginate(initial_url, initial_params, client):
    """ Iterate over a paginated endpoint and get all results

    Assumes the endpoint follows the "standard" pagination interface (data stored under "data",
    "next" used to link next page, "offset" and "limit" accepted as query parameters).

    Yields
    ------
    data : dict
        a series of objects from the endpoint's data, as raw server data
    """
    resp_data = client.get(initial_url, params=initial_params).json()
    for item in resp_data['data']:
        yield item
    while resp_data['next'] is not None:
        next_url = resp_data['next']
        resp_data = client.get(next_url).json()
        for item in resp_data['data']:
            yield item


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 filter_payload(payload: str) ->str:
    """ Convert payload to text and search for not allowed symbols. """
    import re
    if not isinstance(payload, str):
        payload = str(payload)
    if re.search('[^_A-z0-9-]', payload):
        message = (
            'Wrong payload! Only A-Z, a-z, 0-9, _ and - are allowed. We recommend to encode parameters with binary and other types of content.'
            )
        raise ValueError(message)
    return payload


def to_date(date):
    """Convert python datetime.date to the salesforce string format, e.g.
    '2020-02-29'."""
    return date.strftime('%Y-%m-%d')


def dbs_urls():
    """Return list of DBS urls"""
    urls = []
    base = 'https://cmsweb.cern.ch/dbs/prod/global/DBSReader/'
    for inst in ['prod', 'phys01', 'phys02', 'phys03']:
        urls.append(base.replace('prod', inst))
    return urls


def uninstall():
    """Disables gettext translations."""
    global _translations
    _translations = None


def notifyException(ob, action, exc):
    """ Notify all applicable workflows that an action failed.

        o 'ob' is the content object which is the target of the action.

        o 'action' usually corresponds to a method name.

        o 'exc' is the 'sys.exec_info' triple for the exception.

        o Permission:  Private (Python only)
        """


def _dict_mod_replace(to_dict, attrs_dict):
    """Replaces attribute values in to_dict with those from attrs_dict.

    :param to_dict: The dictionary to modify
    :type to_dict: dict(str, list[str]) or AttrsDict
    :param attrs_dict: Dictionary of attributes to set in ``to_dict``
    :type attrs_dict: dict(str, list[str]) or AttrsDict
    :return: None, modifies ``to_dict`` in place.
    :rtype: None
    """
    to_dict.update(attrs_dict)


def createStyle(kmlDoc, netcolor, size, labtype='net', op=0):
    """
    Creates a Style Environment with a variable size and colour.
    The last argument selects between two different icon types.
    """
    if labtype == 'event':
        link = 'http://maps.google.com/mapfiles/kml/shapes/caution.png'
        netcolor = 'ff0000ff'
    elif labtype == 'knots':
        link = 'http://maps.google.com/mapfiles/kml/paddle/red-stars-lv.png'
        netcolor = 'ff0000ff'
    elif op > 0:
        link = 'http://maps.google.com/mapfiles/kml/shapes/triangle.png'
        size = str(float(size) * 0.75)
    elif op < 0:
        link = 'http://maps.google.com/mapfiles/kml/shapes/star.png'
        size = str(float(size) * 0.75)
    else:
        link = 'http://maps.google.com/mapfiles/kml/pal4/icon57.png'
    styleElement = kmlDoc.createElement('Style')
    iconstyle = kmlDoc.createElement('IconStyle')
    styleElement.appendChild(iconstyle)
    scale = kmlDoc.createElement('scale')
    scale.appendChild(kmlDoc.createTextNode(size))
    iconstyle.appendChild(scale)
    iconcolor = kmlDoc.createElement('color')
    iconcolor.appendChild(kmlDoc.createTextNode(netcolor))
    iconstyle.appendChild(iconcolor)
    icon = kmlDoc.createElement('Icon')
    iconlink = kmlDoc.createElement('href')
    iconlink.appendChild(kmlDoc.createTextNode(link))
    icon.appendChild(iconlink)
    iconstyle.appendChild(icon)
    return styleElement


def fixup_columns(cols):
    """Replace index location column to name with `col` prefix

    Args:
        cols (list): List of original columns

    Returns:
        list: List of column names

    """
    out_cols = []
    for col in cols:
        if type(col) == int:
            out_cols.append('col{:d}'.format(col))
        else:
            out_cols.append(col)
    return out_cols


def _to_str(field):
    """ Transform to str """
    return str(field)


def userpref_autoexec_path_add():
    """Add path to exclude from autoexecution

    """
    pass


def hasChildren():
    """Return true if child objects are available
        """


def fetch_intron(chrom, st, cigar):
    """ fetch intron regions defined by cigar. st must be zero based
	return list of tuple of (chrom,st, end)
	"""
    chrom_st = st
    intron_bound = []
    for c, s in cigar:
        if c == 0:
            chrom_st += s
        elif c == 1:
            continue
        elif c == 2:
            chrom_st += s
        elif c == 3:
            intron_bound.append((chrom, chrom_st, chrom_st + s))
            chrom_st += s
        elif c == 4:
            chrom_st += s
        else:
            continue
    return intron_bound


def getid(obj):
    """Return id if argument is a Resource.

    Abstracts the common pattern of allowing both an object or an object's ID
    (UUID) as a parameter when dealing with relationships.
    """
    try:
        if obj.uuid:
            return obj.uuid
    except AttributeError:
        pass
    try:
        return obj.id
    except AttributeError:
        return obj


@classmethod
def geojson_schema_url(cls, version, filename='geojson.json'):
    """
        Return path to item geojson spec
        :param version: version to validate
        :param filename: json file to find
        :return: url

        """
    return cls(version, 'json-schema', filename).ITEM_URL


def _get_default_route(version, subnet):
    """Get a default route for a network

    :param version: IP version as an int, either '4' or '6'
    :param subnet: Neutron subnet
    """
    if subnet.get('gateway') and subnet['gateway'].get('address'):
        gateway = subnet['gateway']['address']
    else:
        return []
    if version == 4:
        return [{'network': '0.0.0.0', 'netmask': '0.0.0.0', 'gateway':
            gateway}]
    elif version == 6:
        return [{'network': '::', 'netmask': '::', 'gateway': gateway}]


def damaged_self(info):
    """
        Process 'user damaged himself' event.

        Input:
        `info`  # An object with information about event's time, user's
                # callsign and aircraft, position on map.
        """


def _points2bbox(points):
    """Calculate the smallest bbox that contains the points.
    NOTE: When performing transformations, the bboxes have to be recalculated.

    Parameters
    ----------
    points: [(x int, y int)]
        list of x,y points.

    Return
    ------
    retval: (x int,y int,x int,y int)
        bbox
    """
    xs, ys = zip(*points)
    return min(xs), min(ys), max(xs), max(ys)


def create_project(conn, project):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :return: project id
    """
    sql = """ INSERT INTO data(name,begin_date,end_date)
              VALUES(?,?,?) """
    cur = conn.cursor()
    cur.execute(sql, project)
    return cur.lastrowid


def nrows(series):
    """
    Determine # of rows
    """
    if not hasattr(series, 'shape'):
        return len(series)
    else:
        return series.shape[0]


def _is_dim(distribution, dims):
    """Check if ``X``'s dimension is the same as the tuple ``dims``."""
    shape = tuple(distribution.loc.shape)
    return shape == dims


def get_clearance(context, box, collapsed_margin=0):
    """Return None if there is no clearance, otherwise the clearance value."""
    clearance = None
    hypothetical_position = box.position_y + collapsed_margin
    for excluded_shape in context.excluded_shapes:
        if box.style['clear'] in (excluded_shape.style['float'], 'both'):
            y, h = excluded_shape.position_y, excluded_shape.margin_height()
            if hypothetical_position < y + h:
                clearance = max(clearance or 0, y + h - hypothetical_position)
    return clearance


@staticmethod
def get_quadkeys(col: int, row: int, zoom: int) ->str:
    """This function is used to encode (col, row, zoom) as quadkey. For details, refer to
        https://developer.here.com/rest-apis/documentation/traffic/common/map_tile/topics/quadkeys.html

        Args:
            col (int): column
            row (int): row
            zoom (int): the zoom level

        Returns:
            str: quadkey

        Example:
            >>> # or checkout the unittest for this function
            >>> settings = {
                    'app_id': 'F8aPRXcW3MmyUvQ8Z3J9',
                    'app_code' : 'IVp1_zoGHdLdz0GvD_Eqsw',
                    'map_tile_base_url': 'https://1.traffic.maps.cit.api.here.com/maptile/2.1/traffictile/newest/normal.day/',
                    'json_tile_base_url': 'https://traffic.cit.api.here.com/traffic/6.2/flow.json?'
                }
            >>> util = Utility(settings)
            >>> util.get_quadkeys(35210, 21493, 16)
            "1202102332221212"
        """
    quadkey = ''
    for i in range(zoom, 0, -1):
        digit = 0
        mask = 1 << i - 1
        if col & mask != 0:
            digit += 1
        if row & mask != 0:
            digit += 2
        quadkey += str(digit)
    return quadkey


def get_silva_root():
    """Return the Silva Root object.
        """


def matcher(pattern, url, strict=True):
    """
        Checks if the pattern matches the url
    """
    if strict:
        return pattern == url
    return pattern in url


def _transform_data(data, data_mapper=None):
    """Use mapper or transformer to convert raw data to engineered before explanation.

    :param data: The raw data to transform.
    :type data: numpy, pandas, dense, sparse data matrix
    :param data_mapper: A list of lists of generated feature indices for each raw feature.
    :type data_mapper: list[list[]]
    :return: The transformed data.
    :rtype: numpy, pandas, dense, sparse data matrix
    """
    if data_mapper is not None:
        return data_mapper.transform(data)
    return data


@classmethod
def unregister(cls, entry, cls_):
    """ Method to remove the blok from a type of declaration

        :param entry: declaration entry of the model where the ``cls_``
            must be removed
        :param ``cls_``: The ``class`` object to remove from the
            Declaration
        :rtype: ``cls_``
        """
    declaration = cls.declaration_types[entry.__declaration_type__]
    declaration.unregister(entry, cls_)
    return cls_


def reverse(input_string):
    """Reverse a string. Useful for strings of binary numbers.

    >>> reverse('abc')
    'cba'

    """
    return input_string[::-1]


def df_order_columns(df, columns_ordered=[]):
    """
    Order some columns, and remain other as was
    """
    columns = []
    for c in columns_ordered:
        if c in df.columns:
            columns.append(c)
    remains = [c for c in df.columns if c not in columns]
    columns = columns + remains
    assert len(columns) == len(df.columns)
    return df[columns]


def get_not_none(node, attr, default):
    """
    Returns ``node[attr]``. If it doesn't exists or is ``None``, return
    `default`.

    Parameters
    ----------
    node: collections.abc.Mapping
    attr: collections.abc.Hashable
    default
        The value to return if ``node[attr]`` is either ``None``, or does not
        exist.

    Returns
    -------
    object
        The value of ``node[attr]`` if it exists and is not ``None``, else
        `default`.
    """
    value = node.get(attr)
    if value is None:
        value = default
    return value


def require_type(pipeline_item, ty):
    """
    Helper function to require that a pipeline item has a particular type
    """
    if 'type' not in pipeline_item:
        raise Exception('Pipeline item has no type')
    if pipeline_item['type'] != ty:
        raise Exception('Invalid pipeline item type')


@classmethod
def get_largest_right_eigs(cls, mx):
    """Get largest right eigenvectors and eigenvalues of matrix  `mx`
        """
    raise NotImplementedError


def _split_privs(privspec):
    """Split the aclitem into three parts

    :param privspec: privilege specification (aclitem)
    :return: tuple with grantee, privilege codes and granto
    """
    usr, prvgrant = privspec.split('=')
    if usr == '':
        usr = 'PUBLIC'
    privcodes, grantor = prvgrant.split('/')
    return usr, privcodes, grantor


def test_module_names(modules):
    """Test module name."""
    valid_modules = ['couchdb-sync', 'kernel', 'odk']
    for module in modules:
        if module not in valid_modules:
            print('{} is not a valid Aether module'.format(module))
            print('Valid options are {}'.format(str(valid_modules)))


def a_test_function():
    """This is a test function."""


def device_presence(fritz, args):
    """Command that prints the device presence."""
    print(int(fritz.get_device_present(args.ain)))


def non_interactions(graph, t=None):
    """Returns the non-existent edges in the graph at time t.

        Parameters
        ----------

        graph : NetworkX graph.
            Graph to find non-existent edges.

        t : snapshot id (default=None)
            If None the non-existent edges are identified on the flattened graph.

        Returns
        -------
        non_edges : iterator
            Iterator of edges that are not in the graph.
        """
    nodes = set(graph)
    while nodes:
        u = nodes.pop()
        for v in (nodes - set(graph[u])):
            yield u, v


def import_apt_key_from_url(url):
    """
    Import a GPG key for a repository into apt's keychain from given url
    """
    return 'wget -qO - {url} | apt-key add -'.format(url=url)


@classmethod
def registerObserver(cls, observer):
    """Register observers to be updated.

        Args:
            observer (object): Object to be registered.
        """
    if observer not in cls._observers and observer is not None:
        cls._observers.append(observer)


def _Native(*data, **kwargs):
    """Stub for implementing an operator implemented in native frontend language.

    Parameters
    ----------
    data : Symbol[]
        Input data for the custom operator.
    info : ptr, required
    need_top_grad : boolean, optional, default=1
        Whether this layer needs out grad for backward. Should be false for loss layers.

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

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


def merge_pres_feats(pres, features):
    """
    Helper function to merge pres and features to support legacy features argument
    """
    sub = []
    for psub, fsub in zip(pres, features):
        exp = []
        for pexp, fexp in zip(psub, fsub):
            lst = []
            for p, f in zip(pexp, fexp):
                p.update(f)
                lst.append(p)
            exp.append(lst)
        sub.append(exp)
    return sub


def scroll_page_up(event):
    """
    Scroll page up. (Prefer the cursor at the bottom of the page, after scrolling.)
    """
    w = event.app.layout.current_window
    b = event.app.current_buffer
    if w and w.render_info:
        line_index = max(0, min(w.render_info.first_visible_line(), b.
            document.cursor_position_row - 1))
        b.cursor_position = b.document.translate_row_col_to_index(line_index, 0
            )
        b.cursor_position += b.document.get_start_of_line_position(
            after_whitespace=True)
        w.vertical_scroll = 0


def sentence_position(i, size):
    """Different sentence positions indicate different
        probability of being an important sentence.
    """
    normalized = i * 1.0 / size
    if 0 < normalized <= 0.1:
        return 0.17
    elif 0.1 < normalized <= 0.2:
        return 0.23
    elif 0.2 < normalized <= 0.3:
        return 0.14
    elif 0.3 < normalized <= 0.4:
        return 0.08
    elif 0.4 < normalized <= 0.5:
        return 0.05
    elif 0.5 < normalized <= 0.6:
        return 0.04
    elif 0.6 < normalized <= 0.7:
        return 0.06
    elif 0.7 < normalized <= 0.8:
        return 0.04
    elif 0.8 < normalized <= 0.9:
        return 0.04
    elif 0.9 < normalized <= 1.0:
        return 0.15
    else:
        return 0


def convert_entity(input_entity):
    """Convert an individual entity from byte strings to regular strings

    Parameters
    ----------
    input_entity : list
       entities to decode

    Returns
    -------
    dict
       decoded entity
    """
    output_entity = {}
    for key in input_entity:
        if key in [b'description', b'type', b'sequence']:
            output_entity[key.decode('ascii')] = input_entity[key].decode(
                'ascii')
        else:
            output_entity[key.decode('ascii')] = input_entity[key]
    return output_entity


def _insert_automodapi_configs(c):
    """Add configurations related to automodapi, autodoc, and numpydoc to the
    state.
    """
    c['numpydoc_show_class_members'] = False
    c['autosummary_generate'] = True
    c['automodapi_toctreedirnm'] = 'py-api'
    c['automodsumm_inherited_members'] = True
    c['autodoc_inherit_docstrings'] = True
    c['autoclass_content'] = 'class'
    c['autodoc_default_flags'] = ['show-inheritance', 'special-members']
    return c


@classmethod
def register(cls, email):
    """
        Use to create an object using the /register API endpoints

        :param email: Email to use for registration
        :type email: str
        """
    instance = cls()
    url = '{}/{}'.format(cls.class_url(), 'register')
    payload = {'email': email}
    return instance.request('post', url, data=payload, response_field_name=
        'data', klass_name='user')


def event_creation_link(start=None, stop=None):
    """Returns a url to a page that can create an event.

        Optional start and stop times to pre-fill start and end of event.
        """


def eval_float_from_string(value_str):
    """
    Allows for basic calculator functionality in legend menus.

    ..note :: I don't really care about the speed since it's for a GUI.
    """
    value_str = str(value_str)
    if not isinstance(value_str, str):
        raise ValueError('%s  must be a string' % value_str)
    if len(value_str) > 50:
        raise ValueError('%s must be less than 50 characters' % value_str)
    allowed_letters = '0123456789.()+-*/e'
    for letter in value_str:
        if letter not in allowed_letters:
            raise ValueError('%r is an invalid character' % allowed_letters)
    try:
        value = float(eval(value_str))
    except:
        print('value_str=%r is invalid' % value_str)
    return value


@classmethod
def from_list(cls, node, leafs):
    """ Initiate a balanced tree with one node and a list of leafs

        :param node: node for all node of the tree
        :param leafs: list of leafs

        :example:
        >>> t = Tree.from_list("+", [1, 2])
        >>> print(t)
        +
         > 1
         > 2
        >>> t = Tree.from_list("+", [1, 2, 3])
        >>> print(t)
        +
         > 1
         > +
         | > 2
         | > 3
        >>> t = Tree.from_list("+", [1, 2, 3, 4])
        >>> print(t)
        +
         > +
         | > 1
         | > 2
         > +
         | > 3
         | > 4
        >>> t = Tree.from_list("+", [1, 2])
        >>> t2 = Tree.from_list("*", [1, t])
        >>> print(t2)
        *
         > 1
         > +
         | > 1
         | > 2

        """
    len_leafs = len(leafs)
    if len_leafs < 2:
        raise ValueError(f'Not enough leafs. Need at least 2 got {len(leafs)}')
    elif len_leafs == 2:
        l_value = leafs[0]
        r_value = leafs[1]
    elif len_leafs == 3:
        l_value = leafs[0]
        r_value = cls.from_list(node, leafs[1:])
    else:
        l_value = cls.from_list(node, leafs[:len_leafs // 2])
        r_value = cls.from_list(node, leafs[len_leafs // 2:])
    return cls(node, l_value, r_value)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a EntityMention object from a json dictionary."""
    args = {}
    if 'text' in _dict:
        args['text'] = _dict.get('text')
    if 'location' in _dict:
        args['location'] = _dict.get('location')
    return cls(**args)


def _table_row(line):
    """
    Return all elements of a data line.

    Return all elements of a data line. Simply splits it.

    Parameters
    ----------
    line: string
        A stats line.

    Returns
    -------
    list of strings
        A list of strings, containing the data on the line, split at white space.
    """
    return line.split()


def scroll_one_line_down(event):
    """
    scroll_offset += 1
    """
    w = event.app.layout.current_window
    b = event.app.current_buffer
    if w:
        if w.render_info:
            info = w.render_info
            if w.vertical_scroll < info.content_height - info.window_height:
                if (info.cursor_position.y <= info.
                    configured_scroll_offsets.top):
                    b.cursor_position += b.document.get_cursor_down_position()
                w.vertical_scroll += 1


def candidatesFromDandRlimits(*, eventType='DandR', dLimits=None, rLimits=None
    ):
    """
    This is implemented as a generator because if large limits are given, it is
    easy to get a very large candidate list, so it's best to
    create the candidates one at a time.
    """
    if eventType == 'Donly':
        for D in range(dLimits[0], dLimits[1] + 1):
            yield D, None
    elif eventType == 'Ronly':
        for R in range(rLimits[0], rLimits[1] + 1):
            yield None, R
    elif eventType == 'DandR':
        for D in range(dLimits[0], dLimits[1] + 1):
            for R in range(rLimits[0], rLimits[1] + 1):
                yield D, R
    else:
        raise Exception('Unrecognized edvent type')


@classmethod
def from_key(cls, key):
    """Build Exception from Key."""
    return cls('Key {} must be a valid OEIS id.'.format(key))


@classmethod
def check_args_for_activation(cls, cli_args):
    """ Returns true if the arguments indicate that this extension should be activated otherwise false.
        The default implementation looks for the extension name has any value.
        It is recommended to override this unless it's just a flag to enable the plugin."""
    return True if cli_args.get(cls.get_name()) else False


def merge_subunits(genes):
    """ Merge list of protein subunit genes into complex

    Args:
        genes (pandas.Series): list of genes

    Returns:
        str: boolean rule

    """
    genes = genes.dropna()
    if len(genes) == 0:
        return None
    else:
        protein = ' and '.join(sorted(genes))
        if len(genes) > 1:
            return '(' + protein + ')'
        else:
            return protein


def common_suffix(text1, text2):
    """
    Determine the common suffix of two strings.

    Args:
      text1: First string.
      text2: Second string.

    Returns:
      The number of characters common to the end of each string.
    """
    if not text1 or not text2 or text1[-1] != text2[-1]:
        return 0
    pointermin = 0
    len_text1 = len(text1)
    len_text2 = len(text2)
    pointermax = min(len_text1, len_text2)
    pointermid = pointermax
    pointerend = 0
    while pointermin < pointermid:
        if text1[-pointermid:len_text1 - pointerend] == text2[-pointermid:
            len(text2) - pointerend]:
            pointermin = pointermid
            pointerend = pointermin
        else:
            pointermax = pointermid
        pointermid = (pointermax - pointermin) // 2 + pointermin
    return pointermid


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


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

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

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


def _any_trits(left, right):
    """
    Adds two individual trits together and returns a single trit
    indicating whether the result is positive or negative.
    """
    res = left + right
    return (res > 0) - (res < 0)


def from_builtin(shader_name: str):
    """Shaders that are embedded in the blender internal code. They all read the uniform ‘mat4 ModelViewProjectionMatrix’, which can be edited by the ‘gpu.matrix’ module. For more details, you can check the shader code with the function ‘gpu.shader.code_from_builtin’;

    :param shader_name: One of these builtin shader names: { ‘2D_UNIFORM_COLOR’, ‘2D_FLAT_COLOR’, ‘2D_SMOOTH_COLOR’, ‘2D_IMAGE’, ‘3D_UNIFORM_COLOR’, ‘3D_FLAT_COLOR’, ‘3D_SMOOTH_COLOR’}
    :type shader_name: str
    :return:  Shader object corresponding to the given name.
    """
    pass


def sym_interval_around(x, xm, alpha=0.32):
    """
    In a distribution represented by a set of samples, find the interval that contains (1-alpha)/2 to each the left and
    right of xm. If xm is too marginal to allow both sides to contain (1-alpha)/2, add the remaining fraction to the
    other side.

    :param x: data values in the distribution
    :param xm: symmetric center value for which to find the interval
    :param alpha: fraction that will be outside of the interval (default 0.32, corresponds to 68 percent quantile)
    :return: interval (lower, upper) which contains 1-alpha symmetric around xm
    """
    assert (alpha > 0) & (alpha < 1)
    xt = x.copy()
    xt.sort()
    i = xt.searchsorted(xm)
    n = len(x)
    ns = int((1 - alpha) * n)
    i0 = i - ns / 2
    i1 = i + ns / 2
    if i0 < 0:
        i0 = 0
        i1 -= i0
    if i1 >= n:
        i1 = n - 1
        i0 -= i1 - n + 1
    return xt[int(i0)], xt[int(i1)]


def get_supported_pythons(classifiers):
    """Return min and max supported Python version from meta as tuples."""
    py_ver_classifier = 'Programming Language :: Python :: '
    vers = filter(lambda c: c.startswith(py_ver_classifier), classifiers)
    vers = map(lambda c: c[len(py_ver_classifier):], vers)
    vers = filter(lambda c: c[0].isdigit() and '.' in c, vers)
    vers = map(lambda c: tuple(c.split('.')), vers)
    vers = sorted(vers)
    del vers[1:-1]
    if len(vers) < 2:
        vers *= 2
    return vers


def channels_group(name: str='NewGroup'):
    """Add selected F-Curves to a new group

    :param name: Name, Name of newly created group
    :type name: str
    """
    pass


def import_backend(path):
    """Import a backend class by dotted path."""
    module_name, class_name = path.rsplit('.', 1)
    module = __import__(module_name, fromlist=[class_name])
    return getattr(module, class_name)


def project_users():
    """Return list of users and permissions from TimeSync"""
    users = {u'malcolm': [u'member', u'manager'], u'jayne': [u'member'],
        u'kaylee': [u'member'], u'zoe': [u'member'], u'hoban': [u'member'],
        u'simon': [u'spectator'], u'river': [u'spectator'], u'derrial': [
        u'spectator'], u'inara': [u'spectator']}
    return users


def assert_is_dict(var):
    """Assert variable is from the type dictionary."""
    if var is None or not isinstance(var, dict):
        return {}
    return var


def homogeneous_to_cartesian_vectors(homogeneous_vector):
    """Convert an homogeneous vector to cartesian vector"""
    return homogeneous_vector[:-1]


def errfunc(p, x, y, fitfunc):
    """Error function used in fitting.

    Args:
        p (list): List of parameters.
        x (:class:`numpy.ndarray`): x values.
        fitfunc (function): Fitting function.

    Returns:
        :class:`numpy.ndarray`: Values of residuals.
    """
    return y - fitfunc(p, x)


def select_constraint_target():
    """Select bones used as targets for the currently selected bones

    """
    pass


def chunks(iterable, n):
    """Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 """
    for i in range(0, len(iterable), n):
        yield iterable[i:i + n]


def get_structure(pdb_file, model=None, altloc=[], extra_fields=[]):
    """
    Create an :class:`AtomArray` or :class:`AtomArrayStack` from a
    :class:`PDBFile`.

    This function is a thin wrapper around the :class:`PDBFile` method
    :func:`get_structure()` for the sake of consistency with other
    ``structure.io`` subpackages.

    Parameters
    ----------
    pdb_file : PDBFile
        The file object.
    model : int, optional
        If this parameter is given, the function will return an
        :class:`AtomArray` from the atoms corresponding to the given
        model number.
        If this parameter is omitted, an :class:`AtomArrayStack`
        containing all models will be returned, even if the
        structure contains only one model.
    altloc : list of tuple, optional
        In case the structure contains *altloc* entries, those can be
        specified here:
        Each tuple consists of the following elements:

            - A chain ID, specifying the residue
            - A residue ID, specifying the residue
            - The desired *altoc* ID for the specified residue

        For each of the given residues the atoms with the given *altloc*
        ID are filtered.
        By default the location with the *altloc* ID "A" is used.
    extra_fields : list of str, optional
        The strings in the list are optional annotation categories
        that should be stored in the output array or stack.
        These are valid values:
        ``'atom_id'``, ``'b_factor'``, ``'occupancy'`` and ``'charge'``.

    Returns
    -------
    array : AtomArray or AtomArrayStack
        The return type depends on the `model` parameter.

    """
    return pdb_file.get_structure(model, altloc, extra_fields)


def format_cell(v_obj, exp):
    """ return a formatted cell value for one combination of var_mip and mod_ens """
    value = v_obj.version
    if exp[0:6] == 'decadal':
        value = exp[7:] + ' ' + v_obj.version
    if value[0:2] == 've':
        value += ' (estimate) '
    if value == 'NA':
        value = 'version not defined'
    if v_obj.is_latest:
        value += ' latest on ' + v_obj.checked_on
    if v_obj.to_update:
        value += ' to update '
    return value + ' | '


def closeDatabase(connection):
    """Close SQLite db connection"""
    if connection is not None:
        connection.close()


def get_x() ->int:
    """Get the acceleration measurement in the ``x`` axis, as a positive or
    negative integer, depending on the direction.
    """


def update_configuration(cfgfile):
    """Update configuration from file.

    :param cfgfile: Configuration file to load.
    """
    global config
    from configobj import ConfigObj
    from pyca.config import cfgspec
    from validate import Validator
    config = ConfigObj(cfgfile, configspec=cfgspec)
    validator = Validator()
    config.validate(validator)
    return config


@conf
def find_xlcxx(conf):
    """
	Detects the Aix C++ compiler
	"""
    cxx = conf.find_program(['xlc++_r', 'xlc++'], var='CXX')
    conf.get_xlc_version(cxx)
    conf.env.CXX_NAME = 'xlc++'


def Bool(value):
    """A function to convert a value into a Boolean

    :param value: any value that can be passed to bool
    :return: a :class:`bool` or None
    """
    if value is None:
        return None
    return bool(value)


def as_contract_id(cid, template_id=None):
    """
    Convert something that resembles a contract ID to a :class:`ContractId` or
    :class:`RelativeContractRef`.
    """
    from .core import ContractId
    if cid is None:
        raise ValueError('cid is required')
    elif isinstance(cid, str):
        return ContractId(cid, template_id)
    elif isinstance(cid, ContractId):
        return cid
    raise TypeError('Could not serialize an object to a contract ID: {!r}'.
        format(cid))


def strip_string(string):
    """Strip whitespace and others from a string"""
    string = string.strip(' \t\n\r"')
    return ' '.join(string.split())


def send_message(message, shortname, client, channel, nick):
    """
    Send a message to channel.
    """
    if message:
        client.msg(channel, message)


def is_group(group):
    """Return ``True`` if passed object is Group and ``False`` otherwise."""
    return type(group).__name__ == 'Group'


@staticmethod
def _get_intervals(data):
    """Compute intervals for each categorical value.

        Args:
            data (pandas.Series):
                Data to analyze.

        Returns:
            dict:
                intervals for each categorical value (start, end).
        """
    frequencies = data.value_counts(dropna=False).reset_index()
    name = data.name or 0
    sorted_freqs = frequencies.sort_values([name, 'index'], ascending=False)
    frequencies = sorted_freqs.set_index('index', drop=True)[name]
    start = 0
    end = 0
    elements = len(data)
    intervals = dict()
    for value, frequency in frequencies.items():
        prob = frequency / elements
        end = start + prob
        intervals[value] = start, end
        start = end
    return intervals


@staticmethod
def callback(model, where):
    """ A callback function for Gurobi that is able to terminate the MIP solver if a solution
        which is better than the sent codeword has been found.
        """
    from gurobimh import GRB
    if where == GRB.Callback.MIPNODE:
        if model.cbGet(GRB.Callback.MIPNODE_OBJBST
            ) < model._realObjective - 1e-06:
            model._incObj = model.cbGet(GRB.Callback.MIPNODE_OBJBST)
            model.terminate()


def STDV(src_column):
    """
    Builtin standard deviation aggregator for groupby. Synonym for tc.aggregate.STD

    Example: Get the rating standard deviation of each user.

    >>> sf.groupby("user",
    ...            {'rating_stdv':tc.aggregate.STDV('rating')})
    """
    return '__builtin__stdv__', [src_column]


def poke_32(library, session, address, data):
    """Write an 32-bit value from the specified address.

    Corresponds to viPoke32 function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param address: Source address to read the value.
    :param data: value to be written to the bus.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viPoke32(session, address, data)


def conditional_items(conditional_steps):
    """Adds items to a list if a condition is fulfilled.

    Parameters
    ----------
    conditional_steps: tuple (item, condition, [alternative])
        A tuple with an item, a boolean condition, and an optional alternative item that will be added instead if the
        condition does not hold
    Returns
    -------
    The list of items (or alternatives) that fulfill the conditions
    """
    result = []
    for conditional_step in conditional_steps:
        if len(conditional_step) == 3:
            step, condition, alternative = conditional_step
            if condition:
                result.append(step)
            else:
                result.append(alternative)
        else:
            step, condition = conditional_step
            if condition:
                result.append(step)
    return result


def t_php_CONSTANT_ENCAPSED_STRING(t):
    """'([^\\\\']|\\\\(.|\\n))*'"""
    t.lexer.lineno += t.value.count('\n')
    return t


def _send_c_store_rsp(event):
    """Logging handler when a C-STORE-RSP is sent.

    **C-STORE Response Elements**

    | (U) Message ID
    | (M) Message ID Being Responded To
    | (U) Affected SOP Class UID
    | (U) Affected SOP Instance UID
    | (M) Status

    Parameters
    ----------
    event : events.Event
        The evt.EVT_DIMSE_SENT event that occurred.
    """
    pass


def SyncCondition(ClockName, EveryEdge=False, Rising=True):
    """
	Return code for clock synchronous condition.
	"""
    if EveryEdge:
        return "{0}'event".format(ClockName)
    elif Rising:
        return 'rising_edge({0})'.format(ClockName)
    else:
        return 'falling_edge({0})'.format(ClockName)


def semester(date, *, base=1):
    """
    Returns the semester index of the given date
    """
    return (date.month - 1) // 6 + base


def do_OP_LEFT(vm):
    """
    >>> s = [b'abcdef', b'']
    >>> do_OP_LEFT(s, require_minimal=True)
    >>> print(len(s)==1 and s[0]==b'abc')
    True
    >>> s = [b'abcdef', b'']
    >>> do_OP_LEFT(s, require_minimal=True)
    >>> print(len(s) ==1 and s[0]==b'')
    True
    """
    pos = vm.pop_nonnegative()
    vm.append(vm.pop()[:pos])


def read(length):
    """
        Returns a list of strings that, when concatenated, are the next
        length bytes of the file, or fewer if there are fewer bytes
        between the current location and the end of the file.
        """


def estimate():
    """Estimate running time of upgrade in seconds (optional)."""
    return 1


def send_bounce(OriginalMessageId=None, BounceSender=None, Explanation=None,
    MessageDsn=None, BouncedRecipientInfoList=None, BounceSenderArn=None):
    """
    Generates and sends a bounce message to the sender of an email you received through Amazon SES. You can only use this API on an email up to 24 hours after you receive it.
    For information about receiving email through Amazon SES, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

    :example: response = client.send_bounce(
        OriginalMessageId='string',
        BounceSender='string',
        Explanation='string',
        MessageDsn={
            'ReportingMta': 'string',
            'ArrivalDate': datetime(2015, 1, 1),
            'ExtensionFields': [
                {
                    'Name': 'string',
                    'Value': 'string'
                },
            ]
        },
        BouncedRecipientInfoList=[
            {
                'Recipient': 'string',
                'RecipientArn': 'string',
                'BounceType': 'DoesNotExist'|'MessageTooLarge'|'ExceededQuota'|'ContentRejected'|'Undefined'|'TemporaryFailure',
                'RecipientDsnFields': {
                    'FinalRecipient': 'string',
                    'Action': 'failed'|'delayed'|'delivered'|'relayed'|'expanded',
                    'RemoteMta': 'string',
                    'Status': 'string',
                    'DiagnosticCode': 'string',
                    'LastAttemptDate': datetime(2015, 1, 1),
                    'ExtensionFields': [
                        {
                            'Name': 'string',
                            'Value': 'string'
                        },
                    ]
                }
            },
        ],
        BounceSenderArn='string'
    )

    :type OriginalMessageId: string
    :param OriginalMessageId: [REQUIRED]
            The message ID of the message to be bounced.

    :type BounceSender: string
    :param BounceSender: [REQUIRED]
            The address to use in the 'From' header of the bounce message. This must be an identity that you have verified with Amazon SES.

    :type Explanation: string
    :param Explanation: Human-readable text for the bounce message to explain the failure. If not specified, the text will be auto-generated based on the bounced recipient information.

    :type MessageDsn: dict
    :param MessageDsn: Message-related DSN fields. If not specified, Amazon SES will choose the values.
            ReportingMta (string) -- [REQUIRED]The reporting MTA that attempted to deliver the message, formatted as specified in RFC 3464 (mta-name-type; mta-name ). The default value is dns; inbound-smtp.[region].amazonaws.com .
            ArrivalDate (datetime) --When the message was received by the reporting mail transfer agent (MTA), in RFC 822 date-time format.
            ExtensionFields (list) --Additional X-headers to include in the DSN.
            (dict) --Additional X-headers to include in the Delivery Status Notification (DSN) when an email that Amazon SES receives on your behalf bounces.
            For information about receiving email through Amazon SES, see the Amazon SES Developer Guide .
            Name (string) -- [REQUIRED]The name of the header to add. Must be between 1 and 50 characters, inclusive, and consist of alphanumeric (a-z, A-Z, 0-9) characters and dashes only.
            Value (string) -- [REQUIRED]The value of the header to add. Must be less than 2048 characters, and must not contain newline characters ('r' or 'n').

    :type BouncedRecipientInfoList: list
    :param BouncedRecipientInfoList: [REQUIRED]
            A list of recipients of the bounced message, including the information required to create the Delivery Status Notifications (DSNs) for the recipients. You must specify at least one BouncedRecipientInfo in the list.
            (dict) --Recipient-related information to include in the Delivery Status Notification (DSN) when an email that Amazon SES receives on your behalf bounces.
            For information about receiving email through Amazon SES, see the Amazon SES Developer Guide .
            Recipient (string) -- [REQUIRED]The email address of the recipient of the bounced email.
            RecipientArn (string) --This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to receive email for the recipient of the bounced email. For more information about sending authorization, see the Amazon SES Developer Guide .
            BounceType (string) --The reason for the bounce. You must provide either this parameter or RecipientDsnFields .
            RecipientDsnFields (dict) --Recipient-related DSN fields, most of which would normally be filled in automatically when provided with a BounceType . You must provide either this parameter or BounceType .
            FinalRecipient (string) --The email address to which the message was ultimately delivered. This corresponds to the Final-Recipient in the DSN. If not specified, FinalRecipient will be set to the Recipient specified in the BouncedRecipientInfo structure. Either FinalRecipient or the recipient in BouncedRecipientInfo must be a recipient of the original bounced message.
            Note
            Do not prepend the FinalRecipient email address with rfc 822; , as described in RFC 3798 .
            Action (string) -- [REQUIRED]The action performed by the reporting mail transfer agent (MTA) as a result of its attempt to deliver the message to the recipient address. This is required by RFC 3464 .
            RemoteMta (string) --The MTA to which the remote MTA attempted to deliver the message, formatted as specified in RFC 3464 (mta-name-type; mta-name ). This parameter typically applies only to propagating synchronous bounces.
            Status (string) -- [REQUIRED]The status code that indicates what went wrong. This is required by RFC 3464 .
            DiagnosticCode (string) --An extended explanation of what went wrong; this is usually an SMTP response. See RFC 3463 for the correct formatting of this parameter.
            LastAttemptDate (datetime) --The time the final delivery attempt was made, in RFC 822 date-time format.
            ExtensionFields (list) --Additional X-headers to include in the DSN.
            (dict) --Additional X-headers to include in the Delivery Status Notification (DSN) when an email that Amazon SES receives on your behalf bounces.
            For information about receiving email through Amazon SES, see the Amazon SES Developer Guide .
            Name (string) -- [REQUIRED]The name of the header to add. Must be between 1 and 50 characters, inclusive, and consist of alphanumeric (a-z, A-Z, 0-9) characters and dashes only.
            Value (string) -- [REQUIRED]The value of the header to add. Must be less than 2048 characters, and must not contain newline characters ('r' or 'n').

    :type BounceSenderArn: string
    :param BounceSenderArn: This parameter is used only for sending authorization. It is the ARN of the identity that is associated with the sending authorization policy that permits you to use the address in the 'From' header of the bounce. For more information about sending authorization, see the Amazon SES Developer Guide .

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

    """
    pass


def index(value, field, context):
    """ Processes the value before indexing
        """


def dedupe(iterable, key=None, seen=None):
    """
    Yields items from `iterable` barring duplicates.

    If `seen` is provided it contains elements which are not to be
    yielded at all.

    Parameters
    ----------
    iterable : :class:`iterable`
        An iterable of elements which are to be yielded, only once.

    key : :class:`callable`
        A function which gets applied to every member of `iterable`.
        The return of this function is checked for duplication rather
        than the member itself.

    seen : :class:`set`, optional
        Holds items which are not to be yielded.

    Yields
    ------
    :class:`object`
        Element in `iterable` which is not in `seen` and has not been
        yielded before.

    """
    if seen is None:
        seen = set()
    for x in iterable:
        val = key(x) if key is not None else x
        if val not in seen:
            seen.add(val)
            yield x


def MAE_dust_caponi(wavelengths, formulation='libya25'):
    """class defining dust Mass Absorption Efficiency (MAE) for several dust sources according to
       Caponi et al. 2017 """
    MAE400_AAE = {'libya25': (110.0, 4.1), 'marocco25': (90.0, 2.6),
        'algeria25': (73.0, 2.8), 'mali25': (630.0, 3.4), 'saudi_arabia25':
        (130.0, 4.5), 'kuwait25': (310.0, 3.4), 'namibia25': (135.0, 5.1),
        'china25': (180.0, 3.2), 'australia25': (293.0, 2.9), 'libya10': (
        77.0, 3.2), 'algeria10': (82.0, 2.5), 'bodele10': (27.0, 3.3),
        'saudi_arabia10': (81.0, 4.1), 'namibia10': (50.0, 4.7), 'china10':
        (59.0, 3.0), 'arizona10': (103.0, 3.1), 'patagonia10': (83.0, 2.9),
        'australia10': (124.0, 2.9)}
    if formulation not in MAE400_AAE.keys():
        formulation = 'libya25'
        raise ValueError('Bad caponi formulaion')
    MAE400, AAE = MAE400_AAE[formulation]
    MAE = MAE400 * (wavelengths / 4e-07) ** -AAE
    return MAE


def normalize_email(email):
    """
    Normalize the email address by lowercasing the domain/email name part of it.
    """
    email = email or ''
    try:
        email_name, domain_part = email.strip().rsplit('@', 1)
    except ValueError:
        pass
    else:
        email = '@'.join([email_name.lower(), domain_part.lower()])
    return email


def get_on_premises_instance(instanceName=None):
    """
    Gets information about an on-premises instance.
    See also: AWS API Documentation

    :example: response = client.get_on_premises_instance(
        instanceName='string'
    )

    :type instanceName: string
    :param instanceName: [REQUIRED]
            The name of the on-premises instance about which to get information.

    :rtype: dict
    :return: {
        'instanceInfo': {
            'instanceName': 'string',
            'iamSessionArn': 'string',
            'iamUserArn': 'string',
            'instanceArn': 'string',
            'registerTime': datetime(2015, 1, 1),
            'deregisterTime': datetime(2015, 1, 1),
            'tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ]
        }
    }

    """
    pass


def col_isdt(df, col_name=None):
    """ Returns a list of columns that are of type 'datetime'. If col_name is specified, returns
    whether the column in the DataFrame is of type 'datetime' instead.
    Parameters:
    df - DataFrame
        DataFrame to check
    col_name - string, default None
        If specified, this function will True if df[col_name] is of type 'datetime'
    """
    col_list = df.select_dtypes(include='datetime').columns
    if col_name is None:
        return col_list
    else:
        return col_name in col_list


def _H3(x):
    """Third Hermite polynomial."""
    return (2 * x ** 3 - 3 * x) * 3 ** -0.5


def _iter_population(draws, tune, popstep, steppers, traces, points):
    """Generator that iterates a PopulationStepper.

    Parameters
    ----------
    draws : int
        number of draws per chain
    tune : int
        number of tuning steps
    popstep : PopulationStepper
        the helper object for (parallelized) stepping of chains
    steppers : list
        The step methods for each chain
    traces : list
        Traces for each chain
    points : list
        population of chain states
    """
    try:
        with popstep:
            for i in range(draws):
                updates = popstep.step(i == tune, points)
                for c, strace in enumerate(traces):
                    if steppers[c].generates_stats:
                        points[c], stats = updates[c]
                        if strace.supports_sampler_stats:
                            strace.record(points[c], stats)
                        else:
                            strace.record(points[c])
                    else:
                        points[c] = updates[c]
                        strace.record(points[c])
                yield traces
    except KeyboardInterrupt:
        for c, strace in enumerate(traces):
            strace.close()
            if hasattr(steppers[c], 'report'):
                steppers[c].report._finalize(strace)
        raise
    except BaseException:
        for c, strace in enumerate(traces):
            strace.close()
        raise
    else:
        for c, strace in enumerate(traces):
            strace.close()
            if hasattr(steppers[c], 'report'):
                steppers[c].report._finalize(strace)


def shape_array(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns a 1D int64 array containing the shape of data.

    Example::

      shape_array([[1,2,3,4], [5,6,7,8]]) = [2,4]

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L574

    Parameters
    ----------
    data : Symbol
        Input Array.

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

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


@staticmethod
def _remove_value(x, value):
    """
        Remove certain valued elements from a vector
        x: vector (must); value: scalar
        return a vector with all elements = 'value' removed
        """
    return (x - value).nonzero_values() + value


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


def extract_7z(archive, compression, cmd, verbosity, interactive, outdir):
    """Extract a 7z archive."""
    cmdlist = [cmd, 'x']
    if not interactive:
        cmdlist.append('-y')
    cmdlist.extend(['-o%s' % outdir, '--', archive])
    return cmdlist


def brush_select(index: int=0):
    """Select a Grease Pencil drawing brush

    :param index: Index, Index of Drawing Brush
    :type index: int
    """
    pass


def getRuleset(id):
    """Returns the ruleset with the given id or raise
        zExceptions.NotFound if no such ruleset is known."""


@classmethod
def get_namespace(cls):
    """Returns the namespace of the class. Defaults to the python module
        name."""
    return cls.__namespace__


def is_stream_binary_plist(stream):
    """
    Module function to check, if the stream is a binary plist.

    @param stream plist stream (file object)
    @return flag indicating a binary plist (boolean)
    """
    stream.seek(0)
    header = stream.read(7)
    if header == b'bplist0':
        return True
    else:
        return False


@classmethod
def header(cls):
    """Header for CSV file."""
    return cls.keys.values()


def normalize(score, base=2048):
    """ Use 2048 as base score if the performance equals baseline  """
    return int(base * score)


def run(args, modules=None):
    """This method is used for parsing commands"""
    if args[0] in globals():
        globals()[args[0]](args)
    else:
        try:
            cmd_parser = modules[args[0] + '.py']
            cmd_parser.run(args[1:])
        except KeyError:
            print('command not found')


def verify_package(config):
    """Verify the package section of the configuration file."""
    if 'package' not in config:
        yield 'The "package" section is missing.'
        return
    package = config['package']
    if not isinstance(package, dict):
        yield 'The "package" section has to be a dictionary.'
        return
    if 'volumes' not in package:
        yield '"volumes" is required in the package section.'
    if 'fpm' not in package:
        yield '"fpm" is required in the package section.'


@staticmethod
def _basic_input(dst_embed_i, _):
    """
        In this function the destination embedding is passed directly to into the decoder.  The output of previous H
        is ignored.  This is implemented using a bound method to a field in the class for speed so that this decision
        is handled at initialization, not as a conditional in the training or inference

        :param embed_i: The embedding at i
        :param _: Ignored
        :return: basic input
        """
    return dst_embed_i.squeeze(0)


def split_url(url):
    """
    Split the given URL ``base#anchor`` into ``(base, anchor)``,
    or ``(base, None)`` if no anchor is present.

    In case there are two or more ``#`` characters,
    return only the first two tokens: ``a#b#c => (a, b)``.

    :param string url: the url
    :rtype: list of str
    """
    if url is None:
        return None, None
    array = url.split('#')
    if len(array) == 1:
        array.append(None)
    return tuple(array[0:2])


def load_mapping(key_columns=[], value_modifiers=[], time_columns=[],
    frequency=None, value_label_columns=[], time_tuples=[]):
    """
    Describes how the tabular data should load into lines.
    Modified in the Datavore client.
    """
    return {'keyColumns': key_columns, 'valueModifiers': value_modifiers,
        'timeColumns': time_columns, 'frequency': frequency,
        'valueLabelColumn': value_label_columns, 'timeTuples': time_tuples}


def conform_to_original_data(cdata, cols_input, data):
    """Reset column names and add dropped columns back"""
    cdata.output = cdata.output.rename(columns=cols_input)
    cdata.output = cdata.output.merge(data, how='outer', on=list(cols_input
        .values()))
    return cdata


def tex_label(varname):
    """
    Many variable names used in the Ridley Ionosphere Model look much better
    in LaTeX format with their proper Greek letters.  This function takes
    a variable name, and if it is recognized, returns a properly formatted
    string that uses MatPlotLib's MathText functionality to display the
    proper characters.  If it is not recognized, the varname is returned.

    Parameters
    ==========
    varname : string
       The variable to convert to a LaTeX label.

    Examples
    ========
    >>>tex_label('n_phi')
    '\\Phi_{Ionosphere}'
    >>>tex_label('Not Recognized')
    'Not Recognized'

    """
    if varname[:2] == 'n_' or varname[:2] == 's_':
        varname = varname[2:]
    known = {'phi': '$\\Phi_{Ionosphere}$', 'sigmah': '$\\sigma_{Hall}$',
        'sigmap': '$\\sigma_{Peder}$', 'jr': '$J_{radial}$', 'mA/m^2':
        '$\\mu A/m^{2}$', 'W/m2': '$W/m^2$', 'eV': '$eV$'}
    if varname in known:
        label = known[varname]
    else:
        label = varname
    return label


def oscillate(iterable):
    """Oscillate forward and backward through an iterable."""
    forward = iterable
    backward = iterable[::-1][1:-1]
    while True:
        yield from forward
        yield from backward


def set_access_key_status(log, user, enable=True):
    """Enable or disable an IAM user's access keys"""
    for key in user.access_keys.all():
        if enable and key.status == 'Inactive':
            log.info('enabling access key %s for user %s' % (key.
                access_key_id, user.name))
            key.activate()
        elif not enable and key.status == 'Active':
            log.info('disabling access key %s for user %s' % (key.
                access_key_id, user.name))
            key.deactivate()


def get_topic_name(prefix, table, operation, host=None):
    """Create a topic name.

    The topic name needs to be synced between the agent and the
    plugin. The plugin will send a fanout message to all of the
    listening agents so that the agents in turn can perform their
    updates accordingly.

    :param prefix: Common prefix for the plugin/agent message queues.
    :param table: The table in question (NETWORK, SUBNET, PORT).
    :param operation: The operation that invokes notification (CREATE,
                      DELETE, UPDATE)
    :param host: Add host to the topic
    :returns: The topic name.
    """
    if host:
        return '%s-%s-%s.%s' % (prefix, table, operation, host)
    return '%s-%s-%s' % (prefix, table, operation)


def xgcd(A, B):
    """
    Finds g=gcd(A,B) and solves the equation A*n+B*m=gcd(A,B).  Returns g, n, m.
    """
    a, b = A, B
    n1, m1, n, m = 0, 1, 1, 0
    if B == 0:
        return A, 1, 0
    r = b
    while r > 0:
        g = r
        q, r = divmod(a, b)
        n1, m1, n, m = n - q * n1, m - q * m1, n1, m1
        a, b = b, r
    return g, n, m


@classmethod
def get_range(cls, begin, end):
    u"""
        Итератор, выдающий строковые представления колонок между
        начальной и конечной колонкой

        :param begin: строковое представление начальной колонки
        :type begin: str
        :param end: строковое представление конечной колонки
        :type end: str
        """
    for i in range(cls.column_to_number(begin), cls.column_to_number(end) + 1):
        yield cls.number_to_column(i)


def list_security_configurations(Marker=None):
    """
    Lists all the security configurations visible to this account, providing their creation dates and times, and their names. This call returns a maximum of 50 clusters per call, but returns a marker to track the paging of the cluster list across multiple ListSecurityConfigurations calls.
    See also: AWS API Documentation

    :example: response = client.list_security_configurations(
        Marker='string'
    )

    :type Marker: string
    :param Marker: The pagination token that indicates the set of results to retrieve.

    :rtype: dict
    :return: {
        'SecurityConfigurations': [
            {
                'Name': 'string',
                'CreationDateTime': datetime(2015, 1, 1)
            },
        ],
        'Marker': 'string'
    }

    """
    pass


def refresh():
    """Refresh object from file on disk (reload)."""


def tree_socket_remove():
    """Remove an input or output socket to the current node tree

    """
    pass


def type_is(type_code):
    """Test field type is certain type.
    """
    return {'$type': type_code}


def tonal_adjustment(tonal_audibility):
    """Adjustment :math:`K`.

    :param tonal_audibility: Tonal audibility :math:`L_{ta}`.

    See equations C.4, C.5 and C.6 in section C.2.4.
    """
    if tonal_audibility > 10.0:
        return 6.0
    elif tonal_audibility < 4.0:
        return 0.0
    else:
        return tonal_audibility - 4.0


def default_options(default: dict={}, override: dict=None,
    allow_unknown_keys: bool=True):
    """
    Combines the dictionaries provided as parameters into one, where keys in override will replace keys in default.
    The inputs are not mutated.
    :param default: the default dictionary containing fall-backs
    :param override: the custom options provided by a user
    :param allow_unknown_keys: flag to determine whether parameters from the override for which there is no default
    should be included as well
    :return: a dictionary containing the combined keys (or just default keys) and values from the override using
    defaults as fall-back.
    """
    if override is None or default is None:
        return default
    result = {}
    for key in default:
        result[key] = default[key]
    for key in override:
        if key in default or allow_unknown_keys:
            result[key] = override[key]
    return result


@classmethod
def from_string(cls, data, **kwds):
    """create new object from raw string.

        :type data: unicode or bytes
        :arg data:
            database to load, as single string.

        :param \\*\\*kwds:
            all other keywords are the same as in the class constructor
        """
    if 'path' in kwds:
        raise TypeError("'path' not accepted by from_string()")
    self = cls(**kwds)
    self.load_string(data)
    return self


@classmethod
def _from_dict(cls, _dict):
    """Initialize a QueryPassages object from a json dictionary."""
    args = {}
    if 'document_id' in _dict:
        args['document_id'] = _dict.get('document_id')
    if 'passage_score' in _dict:
        args['passage_score'] = _dict.get('passage_score')
    if 'passage_text' in _dict:
        args['passage_text'] = _dict.get('passage_text')
    if 'start_offset' in _dict:
        args['start_offset'] = _dict.get('start_offset')
    if 'end_offset' in _dict:
        args['end_offset'] = _dict.get('end_offset')
    if 'field' in _dict:
        args['field'] = _dict.get('field')
    return cls(**args)


@staticmethod
def is_multizone_reader():
    """Can this reader read bundles which contain more zones?.

        This implementation returns always False.
        """
    return False


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 set_gs_executable_to_string(gs_executable_path):
    """Used to simply set the value to whatever the user asks for.  The path
    is not tested first, and takes priority over all other settings."""
    global gs_executable
    gs_executable = gs_executable_path
    return


@classmethod
def _decr_instances(cls, instance):
    """
        Remove from list and reposition other bars
        so that newer bars won't overlap previous bars
        """
    with cls._lock:
        try:
            cls._instances.remove(instance)
        except KeyError:
            pass
        if not instance.gui:
            for inst in cls._instances:
                if inst.pos > abs(instance.pos):
                    inst.pos -= 1
    if not cls._instances and cls.monitor:
        try:
            cls.monitor.exit()
            del cls.monitor
        except AttributeError:
            pass
        else:
            cls.monitor = None


def cgr_neighbor_function(contact_graph, node, destination,
    current_distance, set_visited, suppressed_contacts, lookahead_time):
    """Neighbor function of CGR used by the Dijkstra algorithm.

     Used to determine feasible direct neigbors of a given node.

    Args:
        contact_graph (ContactGraph): The topology information in the form
            of a contact graph
        node (tuple): The evaluated node in the contact graph node form
            ``(from_node, to_node, from_time, to_time, data_rate)``.
        destination (tuple): The nominal destination node in the form
            ``(destination_id, destination_id, 0, math.inf, math.inf)``
        current_distance (int): Contains the weight of the shortest path
            to the currently investigated node (in ms).
        set_visited (set): Set used for storing the visited flag
            of nodes during the Dijkstra runs. Also used for excluding
            suppressed (physical) nodes.
        suppressed_contacts (list): List of contacts that shall not be
            considered for forwarding (and thus neighbor selection)
        lookahead_time (int): Time value that specifies a time window
            (or rather a maximum time) only in which routes are searched.
            This reduces the time necessary to find a shortest route.

    Returns:
        list: A list of all feasible neighbors with items of the form
        ``(<node_id>, weight)`` with ``<node_id>`` representing a certain
        contact in the contact graph.

    """
    neighbors = []
    set_visited.add(node.from_node)
    for edge in contact_graph.graph[node].successors:
        if edge.to_time <= current_distance:
            break
        if ((lookahead_time is None or edge.from_time < lookahead_time) and
            edge.to_node not in set_visited and edge not in
            suppressed_contacts and edge.to_time > current_distance):
            if edge == destination or edge.from_node != edge.to_node:
                weight = edge.from_time - current_distance
                if weight < 0:
                    weight = 0
                neighbors.append((edge, weight))
    return neighbors


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Variant` from a :code:`variant` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Variant`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


def _convert_split(builder, node, graph, err):
    """
    convert to CoreML Squeeze Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#5003
    """
    axis = node.attrs.get('axis', 0)
    split = node.attrs.get('split', None)
    num_splits = len(node.outputs) if split is None else 2
    builder.add_split_nd(name=node.name, input_name=node.inputs[0],
        output_names=node.outputs, axis=axis, num_splits=num_splits,
        split_sizes=split)


def flush(interval, timestamp):
    """
        Returns a string with new line separated list of metrics to report.

        @type interval: C{float}
        @param interval: The time since last flush.
        @type timestamp: C{float}
        @param timestamp: The timestamp for now.
        """


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 distant_iv_pairs_rowdata(mobj, rec):
    """Generate list of 'Distant I-V pairs' record data, which is output in csv format

    mobj is parsed object given by Parser.parse()
    rec is record data in mobj['Cascade Detail']['records']
    """
    rowdata = [mobj['Index']['Cascade'], mobj['Index']['Group'], mobj[
        'Index']['Number']]
    rowdata += [rec['Pair Number'], rec['Vacancy Site'], rec['Vacancy File'
        ], rec['Interstitial Atom'], rec['Interstitial File'], rec['Distance']]
    vacfile = rec['Vacancy File']
    intfile = rec['Interstitial File']
    if 'Lattice Sites' in mobj:
        vacdata = mobj['Lattice Sites']['records'][vacfile - 1]
        vacrowdata = [vacdata['Location X'], vacdata['Location Y'], vacdata
            ['Location Z']]
    else:
        vacrowdata = [None] * 3
    if 'Cascade Detail' in mobj:
        intdata = mobj['Cascade Detail']['records'][intfile - 1]
        introwdata = [intdata['Final Location X'], intdata[
            'Final Location Y'], intdata['Final Location Z']]
    else:
        introwdata = [None] * 3
    rowdata += vacrowdata
    rowdata += introwdata
    return rowdata


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

        :param MemberSpaceLimitsChangePolicyType val:
        :rtype: EventType
        """
    return cls('member_space_limits_change_policy', val)


def setCompletedForUser():
    """Set completed for a user"""


@classmethod
def _clone(cls, source, target, branch=None):
    """Clone svn repository with git-svn."""
    args, revision = cls.get_remote_args(source, target)
    if revision:
        args.insert(0, revision)
    cls._popen(['svn', 'clone'] + args)


def log_create_user(user_dict, created_by, **kwargs):
    """
    Post create user Hook.

    :param user_dict: dict dump of user object

    available keys for user_dict:

     'username',
     'full_name_or_username',
     'full_contact',
     'user_id',
     'name',
     'firstname',
     'short_contact',
     'admin',
     'lastname',
     'ip_addresses',
     'ldap_dn',
     'email',
     'api_key',
     'last_login',
     'full_name',
     'active',
     'password',
     'emails',

    """
    from kallithea import EXTENSIONS
    callback = getattr(EXTENSIONS, 'CREATE_USER_HOOK', None)
    if callable(callback):
        return callback(created_by=created_by, **user_dict)
    return 0


@classmethod
def getSyncPropertyName(cls, propName):
    """Returns the name of the boolean property which can be used to
        toggle binding of the given property to the parent property of
        this instance.
        """
    return cls.__saltSyncPropertyName(propName)


def remove_section_header(text):
    """Return text with section header removed.

    >>> remove_section_header('----\\nfoo\\nbar\\n')
    'foo\\nbar\\n'

    >>> remove_section_header('===\\nfoo\\nbar\\n')
    'foo\\nbar\\n'

    """
    stripped = text.lstrip()
    if not stripped:
        return text
    first = stripped[0]
    if not (first.isalnum() or first.isspace() or stripped.splitlines()[0].
        strip(first).strip()):
        return stripped.lstrip(first).lstrip()
    return text


def get_phi0(sys, b_, bp_):
    """
    Get the reduced density matrix element corresponding to
    many-body states b and bp.

    Parameters
    ----------
    sys : Approach, Approach2vN, or Builder
        The system given as Approach, Approach2vN, or Builder object.
    b\\_,bp\\_ : int
        Labels of the many-body states.

    Returns
    --------
    phi0bbp : complex
        A matrix element of the reduced density matrix (complex number).
    """
    b = sys.si.states_order[b_]
    bp = sys.si.states_order[bp_]
    bcharge = sum(sys.si.get_state(b))
    bpcharge = sum(sys.si.get_state(bp))
    phi0bbp = 0.0
    if sys.funcp.kerntype == 'Pauli':
        if b == bp:
            ind = sys.si.get_ind_dm0(b, b, bcharge, maptype=1)
            phi0bbp = sys.phi0[ind]
    elif bcharge == bpcharge:
        ind = sys.si.get_ind_dm0(b, bp, bcharge, maptype=1)
        conj = sys.si.get_ind_dm0(b, bp, bcharge, maptype=3)
        if ind != -1:
            if type(sys.si).__name__ == 'StateIndexingDMc':
                phi0bbp = sys.phi0[ind]
            else:
                ndm0, npauli = sys.si.ndm0, sys.si.npauli
                phi0bbp = sys.phi0[ind] + 1.0j * sys.phi0[ndm0 - npauli + ind
                    ] * (+1 if conj else -1) * (0 if ind < npauli else 1)
    return phi0bbp


def calculate_side_point_azimuth(absolute_angle_to_point, azimuth):
    """ Calculate absolute azimuth of given point based on relative azimuth

    :param absolute_angle_to_point: Relative angle to point
    :type absolute_angle_to_point: float
    :param azimuth: global azimuth
    :type azimuth: float
    """
    side_point_azimuth = absolute_angle_to_point + azimuth
    side_point_full_azimuth = (side_point_azimuth + 360) % 360
    return side_point_full_azimuth


def fun(f, q_in, q_out):
    """
    A helper function for the parmap function.

    Parameters
    ----------
    f : function
        Function to be evaluated using arguments in the queue q_in.
    q_in : multiprocessing Queue object
        A queue for the input arguments.
    q_out : multiprocessing Queue object
        A queue for the output of the function evaluation.
    """
    while True:
        i, x = q_in.get()
        if i is None:
            break
        q_out.put((i, f(x)))


@staticmethod
def _zExtentCamera(viewport):
    """Return (far, near) planes Z in camera coordinates.

        :param Viewport viewport:
        :return: (far, near) position in camera coords (from 0 to -inf)
        """
    bounds = viewport.camera.extrinsic.transformBounds(viewport.scene.
        bounds(transformed=True, dataBounds=True))
    return bounds[:, (2)]


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

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

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


def rawdata(node, _df=None):
    """Obtain raw data for a node."""


@staticmethod
def model(options, hparams):
    """Build and return the model."""
    raise NotImplementedError()


def multiple_determinants(matrix):
    """
    calculates 2D determinant on every level of given 3D matrix

    :param matrix: np.array (Nx2x2), where i-th slice looks like:
                                    [[xi1, yi1],
                                     [xi2, yi2]]
    :return: np.array - N-dim vector where each element is 2D determinant of 2 2D vectors stored on given level in
                        `matrix`
    """
    return matrix[:, (0), (0)] * matrix[:, (1), (1)] - matrix[:, (0), (1)
        ] * matrix[:, (1), (0)]


@classmethod
def user_model(cls):
    """Return the user model"""
    raise NotImplementedError('Implement in subclass')


def lookup_policy(DirectoryArn=None, ObjectReference=None, NextToken=None,
    MaxResults=None):
    """
    Lists all policies from the root of the  Directory to the object specified. If there are no policies present, an empty list is returned. If policies are present, and if some objects don't have the policies attached, it returns the ObjectIdentifier for such objects. If policies are present, it returns ObjectIdentifier , policyId , and policyType . Paths that don't lead to the root from the target object are ignored. For more information, see Policies .
    See also: AWS API Documentation

    :example: response = client.lookup_policy(
        DirectoryArn='string',
        ObjectReference={
            'Selector': 'string'
        },
        NextToken='string',
        MaxResults=123
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The Amazon Resource Name (ARN) that is associated with the Directory . For more information, see arns .

    :type ObjectReference: dict
    :param ObjectReference: [REQUIRED]
            Reference that identifies the object whose policies will be looked up.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

    :type NextToken: string
    :param NextToken: The token to request the next page of results.

    :type MaxResults: integer
    :param MaxResults: The maximum number of items to be retrieved in a single call. This is an approximate number.

    :rtype: dict
    :return: {
        'PolicyToPathList': [
            {
                'Path': 'string',
                'Policies': [
                    {
                        'PolicyId': 'string',
                        'ObjectIdentifier': 'string',
                        'PolicyType': 'string'
                    },
                ]
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


@classmethod
def changed(cls, user):
    """The given user instance is ready to be saved"""
    raise NotImplementedError('Implement in subclass')


def _check_param_dims(params):
    """
    `params` are either `ar` or `ma`
    """
    if len(params.shape) != 3:
        raise ValueError('AR and MA should each be 1 or 3-dimensional.',
            params.shape)
    if params.shape[1] != params.shape[2]:
        raise ValueError(
            'Dimensions 1 and 2 of AR coefficients should be equal.  i.e. K x N x N'
            , params.shape)


def _structure_has_element(structure, element):
    """Does structure have the specified element?"""
    if element in structure.atomtypes:
        return True
    else:
        return False


def get_key(instance, field_name):
    """ Returns the key that will be used to identify dynamic fields in the DOM. """
    m = instance._meta
    return '-'.join(('data', m.app_label, m.object_name, str(instance.pk),
        field_name))


def fatigue(raw_activities, energies, fatigue_rate=0.0003, recharge_rate=0.0001
    ):
    """
    Limit the frequency and intensity of activities with a model of fatigue.

    @param raw_activities: array of floats
        The activities before fatigue has been applied.
    @param energies: array of floats
        The accumulated energy a channel has at its disposal.
    @param fatigue_rate
        The rate at which energy is depleted when a channel is active.
    @param recharge_rate:
        The rate at which energy is re-accumulated.

    @return activities: array of floats
        The activities after fatigue has been applied.
    """
    energies -= fatigue_rate * raw_activities * energies
    energies += recharge_rate * (1.0 - raw_activities) * (1.0 - energies)
    activities = raw_activities * energies
    return activities


@classmethod
def mimetype(cls):
    """Return most common media type for format."""
    return cls.get_class().Mimetypes[0]


def inherit_doc(cls):
    """
    A decorator that makes a class inherit documentation from its parents.
    """
    for name, func in vars(cls).items():
        if name.startswith('_'):
            continue
        if not func.__doc__:
            for parent in cls.__bases__:
                parent_func = getattr(parent, name, None)
                if parent_func and getattr(parent_func, '__doc__', None):
                    func.__doc__ = parent_func.__doc__
                    break
    return cls


def set_top_cursor(receiver, cursor):
    """ Scrolls the viewport so that the specified cursor is at the top.
    """
    scrollbar = receiver.verticalScrollBar()
    scrollbar.setValue(scrollbar.maximum())
    original_cursor = receiver.textCursor()
    receiver.setTextCursor(cursor)
    receiver.ensureCursorVisible()
    receiver.setTextCursor(original_cursor)


def keep_partial_grad(grad, topk):
    """
    Keep only the topk rows of grads.
    """
    assert topk < grad.size(0)
    grad.data[topk:].zero_()
    return grad


def env_flag(env_var, default=False):
    """
    Return the specified environment variable coerced to a bool, as follows:

    - When the variable is unset, or set to the empty string, return `default`.
    - When the variable is set to a truthy value, returns `True`.
      These are the truthy values:
          - 1
          - true, yes, on
    - When the variable is set to the anything else, returns False.
       Example falsy values:
          - 0
          - no
    - Ignore case and leading/trailing whitespace.
    """
    import os
    environ_string = os.environ.get(env_var, '').strip().lower()
    if not environ_string:
        return default
    return environ_string in ['1', 'true', 'yes', 'on']


def _pick_external_repo_priority(session, tag):
    """pick priority after current ones, leaving space for later insertions"""
    repolist = session.getTagExternalRepos(tag_info=tag)
    if not repolist:
        priority = 5
    else:
        priority = (repolist[-1]['priority'] + 7) // 5 * 5
    return priority


def blk_coverage_1d(blk, size):
    """Return the part of a 1d array covered by a block.

    :param blk: size of the 1d block
    :param size: size of the 1d a image
    :return: a tuple of size covered and remaining size

    Example:

        >>> blk_coverage_1d(7, 100)
        (98, 2)

    """
    rem = size % blk
    maxpix = size - rem
    return maxpix, rem


@staticmethod
def _format_value_to_lower_case(value):
    """
        Formats and replaces values with escape character into value without quotes
        :param value: str
        :return: str
        """
    values = []
    if isinstance(value, list):
        for each in value:
            values.append('{}'.format(each).lower())
        value = values
    else:
        value = value.lower()
    return value


def bC_Na_F_PM73(T, P):
    """"c-a: sodium fluoride [PM73]."""
    b0 = 0.0215
    b1 = 0.2107
    b2 = 0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def updated_date():
    """Returns updated date."""


def log_level(l):
    """Allow log level to be symbolic or a plain integer
    """
    try:
        ll = int(l)
    except:
        ll = eval(l)
    return ll


def indexes_seqs(ol, value, seqs):
    """
        from elist.elist import *
        ol = [1,'a',3,'a',4,'a',5]
        indexes_seqs(ol,'a',{0,2})
        indexes_seqs(ol,'a',{0,1})
        indexes_seqs(ol,'a',{1,2})
        indexes_seqs(ol,'a',{3,4})
    """
    seqs = list(seqs)
    length = ol.__len__()
    indexes = []
    seq = -1
    for i in range(0, length):
        if value == ol[i]:
            seq = seq + 1
            if seq in seqs:
                indexes.append(i)
            else:
                pass
        else:
            pass
    return indexes


@classmethod
def scale(cls, value) ->'ParamPlaybackAdjustment':
    """
        Class method for a simple scaling adjustment.

        :param value: the factor to scale by
        """
    return cls(value)


def ReadList(infile, column=0, map_function=str, map_category={}):
    """read a list of values from infile.

    Use map_function to convert values.
    Use map_category, to map read values directory
    """
    m = []
    errors = []
    for l in infile:
        if l[0] == '#':
            continue
        try:
            d = map_function(l[:-1].split('\t')[column])
        except ValueError:
            continue
        try:
            if map_category:
                d = map_category[d]
        except KeyError:
            errors.append(d)
            continue
        m.append(d)
    return m, errors


@classmethod
def metric_path(cls, project, metric):
    """Returns a fully-qualified metric resource name string."""
    return cls._METRIC_PATH_TEMPLATE.render({'project': project, 'metric':
        metric})


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['configSourceType']
    if type == 'ZIP_UPLOAD':
        return 'CreateZipUploadConfigSourceDetails'
    else:
        return 'CreateConfigSourceDetails'


def is_valid_fit(fit):
    """ Checks fit parameter """
    values = ['none', 'rot+trans', 'rotxy+transxy', 'translation',
        'transxy', 'progressive']
    return fit in values


def splitListItems(items, paste=False):
    """리스트 원소의 string을 space 기준으로 다시 원소로 분리합니다
    paste: 공백 단위로 다시 붙여서 하나의 원소를 만들어야 하는 경우"""
    new_items = []
    for item in items:
        if paste:
            item = ' '.join(item)
        new_items.append(item.split())
    return new_items


def pad(s, width, align):
    """Return string padded with spaces,
    based on alignment parameter."""
    if align == 'l':
        s = s.ljust(width)
    elif align == 'r':
        s = s.rjust(width)
    else:
        s = s.center(width)
    return s


def propertyLabel(id):
    """Return a label for the given property id
        """


@classmethod
def process_filters(cls, query, filters):
    """Process filters and update the query.

    query: dict
    filters: dict

    return dict.
    """
    if filters.get('must') or filters.get('must_not') or filters.get(
        'must_or_should'):
        query = {'bool': {}}
        if filters.get('must'):
            query['bool']['must'] = [{'bool': {'must': filters['must']}}]
        if filters.get('must_not'):
            if not query['bool'].get('must'):
                query['bool']['must'] = []
            query['bool']['must'].append({'bool': {'must_not': filters[
                'must_not']}})
        if filters.get('must_or_should'):
            if not query['bool'].get('must'):
                query['bool']['must'] = []
            query['bool']['must'].append({'bool': {'should': filters[
                'must_or_should']}})
    return query


def bin2int(s):
    """
    binary string to integer
    """
    o = 0
    k = len(s) - 1
    for i, v in enumerate(s):
        o = o + int(v) * 2 ** (k - i)
    return o


def makename2refdct(commdct):
    """make the name2refs dict in the idd_index"""
    refdct = {}
    for comm in commdct:
        try:
            idfobj = comm[0]['idfobj'].upper()
            field1 = comm[1]
            if 'Name' in field1['field']:
                references = field1['reference']
                refdct[idfobj] = references
        except (KeyError, IndexError) as e:
            continue
    return refdct


def get_assign_name(element):
    """
    Get name assignment associated with the element. The element might be the
    value or the target or something but we just want to identify the closest
    Assign ancestor and get its Name.

    If Assign appears more than once in the ancestral chain e.g.
    body-Assign-spam-eggs-Assign-targets-Name then we get a list like this:
    [body-Assign, body-Assign-spam-eggs-Assign] and we want the closest one to
    the element i.e. assign_els[-1]

    Ordered set of nodes, from parent to ancestor?
    https://stackoverflow.com/a/15645846
    """
    assign_els = element.xpath('ancestor::Assign')
    assign_el = assign_els[-1]
    name_els = assign_el.xpath('targets/Name')
    if len(name_els) == 1:
        name = name_els[0].get('id')
    else:
        name = None
    return name


def squeeze(input, dim):
    """Remove the given dimension of size 1.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The dimension to be squeezed.

    Returns
    -------
    Tensor
        The result tensor.
    """
    pass


def try_convert2float(obj, default=None):
    """Try converting "obj" to a float.
    :param obj: the object to be converted:param default: the default return value when conversion fails.
    :param default: the default return value when conversion fails. Type: float.
    :rtype: float or original object.
    """
    if isinstance(obj, float):
        return obj
    elif isinstance(obj, (bool, int)):
        return float(obj)
    elif isinstance(obj, str):
        obj = obj.strip()
        if obj:
            minus = '-' == obj[0]
            dot = 1 == obj.count('.')
            if minus and dot:
                if obj[1:].replace('.', '').isnumeric():
                    return float(obj)
            elif minus:
                if obj[1:].isnumeric():
                    return float(obj)
            elif dot:
                if any(obj.split('.')):
                    return float(obj)
            elif obj.isnumeric():
                return float(obj)
    return default if isinstance(default, float) else obj


def set_detail_size():
    """Set the mesh detail (either relative or constant one, depending on current dyntopo mode)

    """
    pass


@staticmethod
def g_transform(x):
    """The function used in the second transformation stage."""
    if 29 * x > 6:
        return x ** 3
    return 108.0 / 841.0 * (x - 4 / 29.0)


def uniform(shape, dtype, ctx, low, high):
    """Crear a tensor with random value in an uniform
    distribution between low (inclusive) and high (exclusive).

    Parameters
    ----------
    shape : tuple of int
        The tensor shape.
    dtype : data type
        It should be one of the values in the data type dict.
    ctx : context
        The device of the result tensor.

    Returns
    -------
    Tensor
        The random tensor.
    """
    pass


def save_all_modified():
    """Save all modified images

    """
    pass


def _peImageDisplay(overlay, overlayList, displayCtx):
    """Automatically configure display settings for the given PE/COPE
    :class:`.Image` overlay.
    """
    opts = displayCtx.getOpts(overlay)
    opts.cmap = 'Red-Yellow'
    opts.negativeCmap = 'Blue-LightBlue'
    opts.useNegativeCmap = True
    opts.displayRange = [1.0, 100.0]
    opts.clippingRange = [1.0, overlay.dataRange[1]]


def create_node_from_uri(uri, rouri):
    """Create a new IFilesystemNode instance from the uri, synchronously.
        @param uri: a string or IURI-providing instance, or None. This could
                    be for a LiteralFileNode, a CHK file node, a mutable file
                    node, or a directory node
        @param rouri: a string or IURI-providing instance, or None. If the
                      main uri is None, I will use the rouri instead. If I
                      recognize the format of the main uri, I will ignore the
                      rouri (because it can be derived from the writecap).

        @return: an instance that provides IFilesystemNode (or more usefully
                 one of its subclasses). File-specifying URIs will result in
                 IFileNode-providing instances, like ImmutableFileNode,
                 LiteralFileNode, or MutableFileNode. Directory-specifying
                 URIs will result in IDirectoryNode-providing instances, like
                 DirectoryNode.
        """


def bC_Ca_HSO4_HMW84(T, P):
    """c-a: calcium bisulfate [HMW84]."""
    b0 = 0.2145
    b1 = 2.53
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def get_id_from_urn(urn):
    """
    Return the ID of a given Linkedin URN.

    Example: urn:li:fs_miniProfile:<id>
    """
    return urn.split(':')[3]


def describe_account_limits(Marker=None, PageSize=None):
    """
    Describes the current Elastic Load Balancing resource limits for your AWS account.
    For more information, see Limits for Your Classic Load Balancer in the Classic Load Balancer Guide .
    See also: AWS API Documentation

    :example: response = client.describe_account_limits(
        Marker='string',
        PageSize=123
    )

    :type Marker: string
    :param Marker: The marker for the next set of results. (You received this marker from a previous call.)

    :type PageSize: integer
    :param PageSize: The maximum number of results to return with this call.

    :rtype: dict
    :return: {
        'Limits': [
            {
                'Name': 'string',
                'Max': 'string'
            },
        ],
        'NextMarker': 'string'
    }

    :returns:
    classic-listeners
    classic-load-balancers

    """
    pass


def _create_zip(*iterables, fillvalue=None, type_longest=False):
    """Zips supplied iterables and returns a generator.

    Aggregates `*iterables` using `zip` or `itertools.zip_longest`,
    depending on the value of the `type_longest` parameter.

    Parameters
    ----------
    *iterables : iterable
        Iterable objects passed as positional arguments. Passed on to
        `zip` or `zip_longest` depending on the `type_longest` flag.
    fillvalue : optional
        Set all missing values to this default value. Only specified
        when called by `namedzip_longest`. (default is None).
    type_longest : bool, optional
        Specifies whether to use `zip_longest` over `zip`. Used by
        `namedzip_longest`. (default is False).

    Returns
    ------
    generator object

    """
    if type_longest:
        from itertools import zip_longest
        zipped = zip_longest(*iterables, fillvalue=fillvalue)
    else:
        zipped = zip(*iterables)
    return zipped


def get_events_for_month(month, timezone=None):
    """Get all events which belong to `month` sorted by datetime.

        All events = single events and recurred events in month but no deleted
        events.

        month ... ``gocept.month.Month`` object.
        timezone ... str, None defaults to UTC.

        """