def get_attributes():
    """
    Function to get a dictionary with all attributes.

    Returns
    -------
    dict
        Attribute information.
    """
    attr = {'PIXSCALE': {'attribute': 'static', 'config': 'settings',
        'value': 0.027, 'type': 'float'}, 'MEMORY': {'attribute': 'static',
        'config': 'settings', 'value': 1000, 'type': 'int'}, 'CPU': {
        'attribute': 'static', 'config': 'settings', 'value': 1, 'type':
        'int'}, 'INSTRUMENT': {'attribute': 'static', 'config': 'header',
        'value': 'INSTRUME', 'type': 'str'}, 'NFRAMES': {'attribute':
        'non-static', 'config': 'header', 'value': 'NAXIS3', 'type': 'int'},
        'EXP_NO': {'attribute': 'non-static', 'config': 'header', 'value':
        'ESO DET EXP NO', 'type': 'int'}, 'DIT': {'attribute': 'static',
        'config': 'header', 'value': 'ESO DET DIT', 'type': 'int'}, 'NDIT':
        {'attribute': 'non-static', 'config': 'header', 'value':
        'ESO DET NDIT', 'type': 'int'}, 'PARANG_START': {'attribute':
        'non-static', 'config': 'header', 'value': 'ESO ADA POSANG', 'type':
        'float'}, 'PARANG_END': {'attribute': 'non-static', 'config':
        'header', 'value': 'ESO ADA POSANG END', 'type': 'float'},
        'DITHER_X': {'attribute': 'non-static', 'config': 'header', 'value':
        'ESO SEQ CUMOFFSETX', 'type': 'float'}, 'DITHER_Y': {'attribute':
        'non-static', 'config': 'header', 'value': 'ESO SEQ CUMOFFSETY',
        'type': 'float'}, 'PUPIL': {'attribute': 'non-static', 'config':
        'header', 'value': 'ESO ADA PUPILPOS', 'type': 'float'}, 'DATE': {
        'attribute': 'non-static', 'config': 'header', 'value': 'DATE-OBS',
        'type': 'str'}, 'LATITUDE': {'attribute': 'static', 'config':
        'header', 'value': 'ESO TEL GEOLAT', 'type': 'float'}, 'LONGITUDE':
        {'attribute': 'static', 'config': 'header', 'value':
        'ESO TEL GEOLON', 'type': 'float'}, 'RA': {'attribute':
        'non-static', 'config': 'header', 'value': 'RA', 'type': 'float'},
        'DEC': {'attribute': 'non-static', 'config': 'header', 'value':
        'DEC', 'type': 'float'}, 'PARANG': {'attribute': 'non-static',
        'config': 'header', 'value': 'None', 'type': 'float'},
        'STAR_POSITION': {'attribute': 'non-static', 'config': None,
        'value': None, 'type': 'float'}, 'INDEX': {'attribute':
        'non-static', 'config': None, 'value': None, 'type': 'int'},
        'FILES': {'attribute': 'non-static', 'config': None, 'value': None,
        'type': 'str'}}
    return attr


def client_host(server_host):
    """Return the host on which a client can connect to the given listener."""
    if server_host == '0.0.0.0':
        return '127.0.0.1'
    if server_host in ('::', '::0', '::0.0.0.0'):
        return '::1'
    return server_host


@staticmethod
def _avg(value1, value2, weight):
    """Returns the weighted average of two values and handles the case where
            one value is None. If both values are None, None is returned.
        """
    if value1 is None:
        return value2
    if value2 is None:
        return value1
    return value2 * weight + value1 * (1 - weight)


def authenticated_userid(request):
    """ Return the authenticated :term:`userid` or ``None`` if
        no authenticated userid can be found. This method of the
        policy should ensure that a record exists in whatever
        persistent store is used related to the user (the user
        should not have been deleted); if a record associated with
        the current id does not exist in a persistent store, it
        should return ``None``.

        """


def _chain_from_iterable_of_lists(iterable):
    """
    Specialized implementation of itertools.chain.from_iterable.
    Each item in *iterable* should be a list.  This function is
    careful not to keep references to yielded objects.
    """
    for element in iterable:
        element.reverse()
        while element:
            yield element.pop()


def fromSuccessResponse(cls, success_response, signed_only=True):
    """Create a C{L{TeamsResponse}} object from a successful OpenID
        library response
        (C{L{openid.consumer.consumer.SuccessResponse}}) response
        message

        @param success_response: A SuccessResponse from consumer.complete()
        @type success_response: C{L{openid.consumer.consumer.SuccessResponse}}

        @param signed_only: Whether to process only data that was
            signed in the id_res message from the server.
        @type signed_only: bool

        @rtype: TeamsResponse
        @returns: A Launchpad teams response containing the data
            that was supplied with the C{id_res} response.
        """
    self = cls()
    self.ns_uri = self._getTeamsNS(success_response.message)
    if signed_only:
        args = success_response.getSignedNS(self.ns_uri)
    else:
        args = success_response.message.getArgs(self.ns_uri)
    if 'is_member' in args:
        is_member_str = args['is_member']
        self.is_member = is_member_str.split(',')
    return self


def get_card_from_board(trello_token, board_id, card_id):
    """ Get Card JSON data from short id (ie, #123) from specific board.
    """
    client = trello_token.client
    return client.boards.get_card_idCard(card_id, board_id)


def hardware_reference(device='K300'):
    """Print useful hardware information about the device

    Displays hardware information about the DIO device, such as pinouts.
    Then pinouts assume that the user is facing the front if the device, and that the fins
    are pointed up.

    Args:
        device (str, optional): The karbon series being used. Defaults to the K300
    """
    ref_k300 = """
    Info: Isolated digital input/ouput. To function properly, dio should be connect to
    external power and grund.

    Pinout: || GND | DO_1 | DO_2 | DO_3 | DO_4 | DI_1 | DI_2 | DI_3 | DI_4 | PWR ||
        """
    ref_dict = {'K300': ref_k300}
    try:
        print(ref_dict[device.upper()])
    except KeyError:
        print('Please select from: [K300]')


def search(data, **attrs):
    """Return subset of data array with elements that have
    the same attrs that in **attrs

    Data should be in form array of dictionary:

    data = [
        {
            attr1: attr1_value,
            attr2: attr2_value,
            ...
        },
        ...
    ]

    **attrs is a values to filter something

    search return array of elements elements from data
    if all **attrs are equal to attrs of element.
    It doesn't metter if len(**attrs) < len(element)

    search returns None if no result found
    """
    return filter(lambda x: attrs.items() <= x.items(), data)


def clip(X, lcorr):
    """ perform 2D fftshift and crop with lcorr """
    x00 = X[:, :lcorr + 1, :lcorr + 1]
    x11 = X[:, -lcorr:, -lcorr:]
    x01 = X[:, :lcorr + 1, -lcorr:]
    x10 = X[:, -lcorr:, :lcorr + 1]
    return x00, x01, x10, x11


def is_int(s):
    """
    Short helper for duration conversion.
    """
    try:
        int(s)
    except (ValueError, TypeError):
        return False
    else:
        return True


def parseBoolValue(value):
    """
    Utility function to parse booleans and none from strings
    """
    if value == 'false':
        return False
    elif value == 'true':
        return True
    elif value == 'none':
        return None
    else:
        return value


def find_base_transform(transform):
    """Given a domain transform, find its base class"""
    for base in transform.__bases__:
        if hasattr(base, 'domain'):
            return base
    name = transform.__name__
    raise TypeError('{} is not a domain transform'.format(name))


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

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


def _disabled_method(*_):
    """Disabled method."""
    raise AttributeError


@classmethod
def class_print_help(cls, inst=None):
    """Get the help string for a single trait and print it."""
    print(cls.class_get_help(inst))


def constraints_copy():
    """Copy constraints to other selected objects

    """
    pass


def is_bit_set(vector, position):
    """
    Check if bit parameter is present in integer value.

    >>> is_bit_set(0, 0)
    False
    >>> is_bit_set(1, 0)
    True
    >>>
    >>> is_bit_set(5, 0)
    True
    >>> is_bit_set(5, 1)
    False
    >>> is_bit_set(5, 2)
    True
    """
    return 1 << position & vector > 0


def default_arg(*arg):
    """
    Auxiliar function to be used if type is not provided.

    :return: input arg
    """
    return arg[0]


def build_sample(notification):
    """Build sample from provided notification."""
    pass


def string2list_of_integers(s, separator=', '):
    """Convers a string of integer separated by comma, into a list of integer"""
    arr = []
    if s != '':
        arrs = s.split(separator)
        for a in arrs:
            arr.append(int(a))
    return arr


@classmethod
def has(cls, blok):
    """ Return True if the blok was imported

        :param blok: name of the blok to add
        :rtype: boolean
        """
    return blok in cls.modules


def subdivision_set(level: int=1, relative: bool=False):
    """Sets a Subdivision Surface Level (1-5)

    :param level: Level
    :type level: int
    :param relative: Relative, Apply the subsurf level as an offset relative to the current level
    :type relative: bool
    """
    pass


@classmethod
def _call_and_serialize(cls, method, data, refresh=False):
    """Call the remote method with data, and optionally refresh.

        Args:
            method (callable): The method on the Authenticated Five9 object
                that should be called.
            data (dict): A data dictionary that will be passed as the first
                and only position argument to ``method``.
            refresh (bool, optional): Set to ``True`` to get the record data
                from Five9 before returning the record.

        Returns:
            BaseModel: The newly created record. If ``refresh`` is ``True``,
                this will be fetched from Five9. Otherwise, it's the data
                record that was sent to the server.
        """
    method(data)
    if refresh:
        return cls.read(method.__self__, data[cls.__uid_field__])
    else:
        return cls.deserialize(cls._get_non_empty_dict(data))


@staticmethod
def is_collapsed(node):
    """A "collapsed" paragraph is one which has no text, immediately
        starting a subparagraph. For example:
        (a)(1) Some text    <- (a) is collapsed
        (a) Some text - (1) Other text   <- (a) is not collapsed
        """
    marker = '({})'.format(node['label'][-1])
    text_without_marker = node['text'].replace(marker, '')
    return node['text'].strip() and not text_without_marker.strip()


@staticmethod
def button_state_change(but, state, style_settings):
    """
		Used for setting TTK buttons as selected or unselected.

		str 'toggle' to toggle from the current state
		1 to set default to active 		- Pressed state
		0 to set default state to normal

		To see how to create the style of the selected state see below.
		Or see button_styling.py used by demo.py, get from github

		tkinter.ttk.Style().theme_create("toggle", "default", settings={
		"ToggleButton": {
			"configure": {"width": 10, "anchor": "center"},
			"layout": [
				("ToggleButton.button", {"children":
					[("ToggleButton.focus", {"children":
						[("ToggleButton.padding", {"children":
				[("ToggleButton.label", {"side": "left", "expand": 1})]
						})]
					})]
				})
			]
		}
		"ToggleButton.button": {"element create":
			("image", 'button-n',
		("pressed", 'button-p'), ("active","!alternate", 'button-h'),
				("alternate", "button-s"),#THIS IS THE MAGIC tbutton-p
				{"border": [4, 10], "padding": 4, "sticky":"ewns"}
			)}
		})

		style.theme_use('toggle')
		"""
    if state == 'toggle':
        if str(but.cget('default')) == 'normal':
            but.config(default='active')
        else:
            but.config(default='normal')
    elif state:
        but.config(default='active')
    else:
        but.config(default='normal')


def get_destroyed_volume(module, array):
    """Return Destroyed Volume or None"""
    try:
        if array.get_volume(module.params['name'], pending=True)[
            'time_remaining'] != '':
            return True
        else:
            return False
    except Exception:
        return False


def get_dict_by_related(query, related):
    """
    Retorna un diccionario con los ids de los objetos de query como claves y
    como valores a sus respectivos objetos que estan nombrados como *related*.

    Por ejemplo dado una lista de posts que cada uno tiene un atributo llamado
    'user' que referencia a un objeto Usuario, retorna un diccionario con los
    ids de los posts como claves y sus respectivos usuarios como valores::

        {
            <id_post>: <user>
            ...
        }

    """
    object_dict = {}
    for obj in query:
        field = getattr(obj, related)
        key = str(field)
        object_dict[key] = obj
    return object_dict


def p_allow_deny_params_pool_ctxt(p):
    """ allow_deny_params_pool_ctxt : MEMBERS_OF STRING_ENCLOSED_DOUBLE_QUOTE
                                    | KNOWN_CLIENTS
                                    | UNKNOWN_CLIENTS
                                    | DYNAMIC_BOOTP_CLIENTS
                                    | AUTHENTICATED_CLIENTS
                                    | UNAUTHENTICATED_CLIENTS
                                    | ALL_CLIENTS
                                    | AFTER date_time
    """
    p[0] = ' '.join(p[1:])


def describe_images(registryId=None, repositoryName=None, imageIds=None,
    nextToken=None, maxResults=None, filter=None):
    """
    Returns metadata about the images in a repository, including image size, image tags, and creation date.
    See also: AWS API Documentation

    :example: response = client.describe_images(
        registryId='string',
        repositoryName='string',
        imageIds=[
            {
                'imageDigest': 'string',
                'imageTag': 'string'
            },
        ],
        nextToken='string',
        maxResults=123,
        filter={
            'tagStatus': 'TAGGED'|'UNTAGGED'
        }
    )

    :type registryId: string
    :param registryId: The AWS account ID associated with the registry that contains the repository in which to describe images. If you do not specify a registry, the default registry is assumed.

    :type repositoryName: string
    :param repositoryName: [REQUIRED]
            A list of repositories to describe. If this parameter is omitted, then all repositories in a registry are described.

    :type imageIds: list
    :param imageIds: The list of image IDs for the requested repository.
            (dict) --An object with identifying information for an Amazon ECR image.
            imageDigest (string) --The sha256 digest of the image manifest.
            imageTag (string) --The tag used for the image.

    :type nextToken: string
    :param nextToken: The nextToken value returned from a previous paginated DescribeImages request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.

    :type maxResults: integer
    :param maxResults: The maximum number of repository results returned by DescribeImages in paginated output. When this parameter is used, DescribeImages only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeImages request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then DescribeImages returns up to 100 results and a nextToken value, if applicable.

    :type filter: dict
    :param filter: The filter key and value with which to filter your DescribeImages results.
            tagStatus (string) --The tag status with which to filter your DescribeImages results. You can filter results based on whether they are TAGGED or UNTAGGED .

    :rtype: dict
    :return: {
        'imageDetails': [
            {
                'registryId': 'string',
                'repositoryName': 'string',
                'imageDigest': 'string',
                'imageTags': [
                    'string',
                ],
                'imageSizeInBytes': 123,
                'imagePushedAt': datetime(2015, 1, 1)
            },
        ],
        'nextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def validate(string):
    """Verify input string correctly represents a number in Roman numerals.
    For example, IV is valid while IIII is not, NM is not.
    """
    pass


def subtract_modulo(image1, image2):
    """Subtract two images, without clipping the result. At least one of the
    images must have mode "1".

    .. code-block:: python

        out = ((image1 - image2) % MAX)

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image1.load()
    image2.load()
    return image1._new(image1.im.chop_subtract_modulo(image2.im))


@staticmethod
def __find_location(elem):
    """HTML要素から場所名を抽出する

        HTMLをBeautifulSoupでパースしてできたTagオブジェクトから
        場所名の記述を抽出し文字列で返す

        Args:
           elem(:obj:bs4.element.Tag): HTML要素

        Returns:
            str: 場所名
        """
    location = ''
    for string in elem.find(string='開催地').find_next('span').stripped_strings:
        if 'マップ' in string:
            break
        location += string
    return location


@staticmethod
def _get_task_requirement(task, reqname, default):
    """
        Return attribute `reqname` of `task`.

        If the attribute is not set or is ``None``, then return `default`
        instead.
        """
    req = getattr(task, reqname, None)
    if req is None:
        req = default
    return req


def _equiv_refresh_interval():
    """Get smallest interval for which the browser should follow redirects.

    Redirection happens if the given interval is smaller than this.
    """
    from .commands import options
    return options.get('equiv_refresh_interval')


@staticmethod
def uniform_changepoints(T, n_inter):
    """Return optimal uniform changepoints for n intervals of data

        We have to deal with the special cases of divisions with rest
        for the intervals.

        Parameters
        ----------
        T : number of timesteps
        n_inter : number of intervals

        Returns
        -------
        changepoints : list[int]
            changepoint indices
        """
    raw_dist = T / n_inter
    fair_dist = round(raw_dist)
    if fair_dist < raw_dist:
        return range(fair_dist, T - fair_dist, fair_dist)
    else:
        return range(fair_dist, T, fair_dist)


def _factors_avg(idadf, columnlist, valuelist):
    """
    Compute the arithmetic average for all columns in a list (valuelist) over
    the IdaDataFrame grouped by a list of columns (columnlist).

    Parameters
    ----------
    columnlist : list
        List of column names that exist in self.
    valuelist : list
        List of column names that exist in self.

    Notes
    -----
    The function assumes the following:

        * The columns given as parameter exists in the IdaDataframe
        * The parameter columnlist and valuelist are array-like
        * Columns are referenced by their own name (character string)

    Returns
    -------
        DataFrame
    """
    column_string = '"' + '", "'.join(columnlist) + '"'
    name = idadf.internal_state.current_state
    agg_list = []
    for value in valuelist:
        agg = (
            'CAST(AVG(CAST("%s" AS DECIMAL(10,6))) AS DECIMAL(10,6)) "%s"' %
            (value, value))
        agg_list.append(agg)
    agg_string = ', '.join(agg_list)
    value_string = '"' + '", "'.join(valuelist) + '"'
    query = 'SELECT %s,%s FROM %s GROUP BY %s ORDER BY %s,%s ASC' % (
        column_string, agg_string, name, column_string, column_string,
        value_string)
    return idadf.ida_query(query)


def byte_to_megabyte(byte):
    """
    Convert byte value to megabyte
    """
    return byte / 1048576


def check_fileflag(fileflags, expect_flag, logger):
    """Check the file flags """
    if fileflags == expect_flag:
        logger.info('file flags include %s.' % expect_flag)
        return True
    else:
        logger.error("file flags doesn't include %s." % expect_flag)
        return False


@staticmethod
def _transpose_metadata(values):
    """Utility function to translate metadata field."""
    if 'metadata' in values:
        value = values.pop('metadata')
        values['meta_data'] = value
    return values


def unfreeze_parameter(param):
    """Convenience function to unfreeze a passed torch parameter.
    Used by ``skorch.callbacks.Unfreezer``
    """
    param.requires_grad = True


def isRemoteDir(sftp, path):
    """ Check if one remote directory exists
    Params:
        sftp: Sftp session.
        path: Path to check.
    Returns: True if the given path is a directory, false if it is not a directory.
    """
    raise NotImplementedError('No dependence on paramiko yet')


def multiple_dot_products(A, B, out):
    """
    Dot product of matrices of A times matrices of B as follows:
        out[0] = A[0] * B[0]
        out[1] = A[1] * B[1]
        out[2] = A[2] * B[2]
        ...

    Parameters
    ----------
    A : ndarray
        Input array with n matrices.
        Shape = (n, size, size)
    B : ndarray
        Single matrix.
        Shape = (size, size)
    out : ndarray
        The calculation is done into this array.
        Shape : (n, size, size)
    """
    raise NotImplementedError


def get_domains(pageToken=None):
    """
    Returns a list of all domains in the user's account.
    See also: AWS API Documentation

    :example: response = client.get_domains(
        pageToken='string'
    )

    :type pageToken: string
    :param pageToken: A token used for advancing to the next page of results from your get domains request.

    :rtype: dict
    :return: {
        'domains': [
            {
                'name': 'string',
                'arn': 'string',
                'supportCode': 'string',
                'createdAt': datetime(2015, 1, 1),
                'location': {
                    'availabilityZone': 'string',
                    'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
                },
                'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
                'domainEntries': [
                    {
                        'id': 'string',
                        'name': 'string',
                        'target': 'string',
                        'type': 'string',
                        'options': {
                            'string': 'string'
                        }
                    },
                ]
            },
        ],
        'nextPageToken': 'string'
    }

    """
    pass


def classifier(pages, classification_column, classification_wanted,
    pages_columns_dict):
    """
    Classify classification that won't be used in 'other'

    Parameters
    ----------
        pages: pandas dataframe of pages

        classification_column: string, classification column wanted to be classified

        classification_wanted: list of string, classication wanted to be kept

        pages_columns_dict: dict

    Returns
    -------
        Pandas Series
    """
    pages = pages.copy(deep=True)
    pages.loc[~pages[classification_column].isin(classification_wanted),
        classification_column] = 'Other'
    return pages[classification_column]


@staticmethod
def addVertex(sourceindex, v_map, sourcedata, destdata):
    """Add a vertex from source to destination. Returns index in
        destdata of the vertex."""
    try:
        return v_map[sourceindex]
    except KeyError:
        v_map[sourceindex] = destdata.num_vertices
        destdata.num_vertices += 1
        destdata.vertices.update_size()
        destdata.vertices[-1].x = sourcedata.vertices[sourceindex].x
        destdata.vertices[-1].y = sourcedata.vertices[sourceindex].y
        destdata.vertices[-1].z = sourcedata.vertices[sourceindex].z
        if sourcedata.has_normals:
            destdata.normals.update_size()
            destdata.normals[-1].x = sourcedata.normals[sourceindex].x
            destdata.normals[-1].y = sourcedata.normals[sourceindex].y
            destdata.normals[-1].z = sourcedata.normals[sourceindex].z
        if sourcedata.has_vertex_colors:
            destdata.vertex_colors.update_size()
            destdata.vertex_colors[-1].r = sourcedata.vertex_colors[sourceindex
                ].r
            destdata.vertex_colors[-1].g = sourcedata.vertex_colors[sourceindex
                ].g
            destdata.vertex_colors[-1].b = sourcedata.vertex_colors[sourceindex
                ].b
            destdata.vertex_colors[-1].a = sourcedata.vertex_colors[sourceindex
                ].a
        if sourcedata.has_uv:
            for sourceuvset, destuvset in zip(sourcedata.uv_sets, destdata.
                uv_sets):
                destuvset.update_size()
                destuvset[-1].u = sourceuvset[sourceindex].u
                destuvset[-1].v = sourceuvset[sourceindex].v
        return destdata.num_vertices


@classmethod
def parse_args(cls, subparsers):
    """Add Cloud Object Storage arguments to command line parser."""
    cos_oo_parser = subparsers.add_parser('cos', description=cls.__doc__)
    cos_oo_parser.add_argument('-e', '--endpoint-url', help=
        'endpoint URL of the S3 storage')
    cos_oo_parser.add_argument('-s', '--instance-id', help=
        'service instance id')
    cos_oo_parser.add_argument('-u', '--access-key', help=
        'acccess key id of HMAC credentials')
    cos_oo_parser.add_argument('-p', '--secret-key', help=
        'secret access key of HMAC credentials')
    cos_oo_parser.add_argument('local_path', nargs='?', default=None, help=
        'path in the local file system of the file to be uploaded')
    cos_oo_parser.add_argument('bucket', help='target s3 bucket')
    cos_oo_parser.add_argument('remote_path', help=
        """path on Cloud Object Storage where the file
                                  will be stored"""
        )


def select_row():
    """Select a row of control points including active one

    """
    pass


def getGroupIds():
    """
        Returns a list of the available groups
        """


def elgamal_enc(params, gamma, m, h):
    """ encrypts the values of a message (h^m) """
    G, o, g1, hs, g2, e = params
    k = o.random()
    a = k * g1
    b = k * gamma + m * h
    return a, b, k


def _is_delayed(obj):
    """Check that object follows the ``class:neurtu.Delayed`` API
    """
    return hasattr(obj, 'compute') and hasattr(obj, 'get_tags') and callable(
        obj.compute) and callable(obj.get_tags)


def get_decoded_dimension_from_polyline(polyline, index):
    """
    Helper method for decoding polylines that returns
    new polyline index and decoded int part of one dimension
    """
    result = 1
    shift = 0
    while True:
        b = ord(polyline[index]) - 63 - 1
        index += 1
        result += b << shift
        shift += 5
        if b < 31:
            break
    return index, ~result >> 1 if result & 1 != 0 else result >> 1


def sign(value):
    """
    Returns the sign of the given value
    :param value: float
    :return: -1 of the value is negative; 1 if the value is positive; 0 if the value is zero
    """
    return value and (1, -1)[value < 0]


def get_seqrecord_description(phage_genome):
    """Helper function to construct a description SeqRecord attribute.

    :param phage_genome:
        Input a Genome object.
    :type phage_genome: genome
    :returns:
        description is a formatted string parsed
        from genome data
    """
    description = (
        f'{phage_genome.host_genus} phage {phage_genome.id}, complete genome')
    return description


def block_or_file(storage_type_keyname):
    """returns either 'block' or 'file'

    :param storage_type_keyname: the Network_Storage['storageType']['keyName']
    :returns: 'block' or 'file'
    """
    return 'block' if 'BLOCK_STORAGE' in storage_type_keyname else 'file'


@staticmethod
def get_opt(opt_name, args):
    """Return option name and value.

        :param opt_name: name of the option, e.g., "username"
        :param args: parsed arguments
        """
    return opt_name, getattr(args, 'os_%s' % opt_name, None)


def iscontextprocessor(x):
    """
    Check if the given argument is an instance of :class:`bonobo.config.ContextProcessor`.

    :param mixed:
    :return: bool
    """
    from bonobo.config.processors import ContextProcessor
    return isinstance(x, ContextProcessor)


def quoting_types():
    """Returns a list of the supported quoting modes"""
    return ['QUOTE_MINIMAL', 'QUOTE_ALL', 'QUOTE_NONE']


@classmethod
def is_compatible(cls, download_target, osutil):
    """Determines if the target for the download is compatible with manager

        :param download_target: The target for which the upload will write
            data to.

        :param osutil: The os utility to be used for the transfer

        :returns: True if the manager can handle the type of target specified
            otherwise returns False.
        """
    raise NotImplementedError('must implement is_compatible()')


@staticmethod
def _get_page(page):
    """
        fetch the page parameter from request query
        """
    try:
        page = int(page)
        return page if page > 0 else -page
    except ValueError:
        return 1


@staticmethod
def majority(it):
    """
        Specifies which type of vote(True or False) is major

        :param it: len(int) of s(described in decide_fame), votes(bool)
        :type it: generator object
        :return: v - majority vote in s, t - number of events in s with a vote of v
        :rtype: v: bool, t: int
        """
    hits = [0, 0]
    for s, x in it:
        hits[int(x)] += s
    if hits[0] > hits[1]:
        return False, hits[0]
    else:
        return True, hits[1]


def _find_top_left_tile(map):
    """
    Calculate the tile coordinate and its position relative to top-left
    offset of the map image.

    :param map: Map instance.
    """
    origin = map.origin
    w, h = map.size
    tw = map.provider.tile_width
    th = map.provider.tile_height
    px = map.offset[0] + w // 2
    py = map.offset[1] + h // 2
    dx = px // tw + (px % tw > 0)
    dy = py // th + (py % th > 0)
    px -= dx * tw
    py -= dy * th
    offset = px, py
    coord = origin[0] - dx, origin[1] - dy
    assert -tw < offset[0] <= 0 and -th < offset[1] <= 0, offset
    return coord, offset


def calculate_target(category, lambda_vars, coefficients):
    """ Returns a target value for a given category.

        Args:
            category (str): category name.
            lambda_vars (dict of str to double): dictionary
                    that maps DMU codes to the corresponding value
                    of lambda variables.
            coefficients (dict of tuple of str, str to double}): dictionary
                that maps internal DMU code and category to the
                corresponding coefficient, e.g. {(DMU, category) : value}.

        Returns:
            double: target value.
    """
    target = 0
    for dmu, value in lambda_vars.items():
        target += value * coefficients[dmu, category]
    return target


def parseGBLoc(s, l, t):
    """retwingles parsed genbank location strings, assumes no joins of RC and FWD sequences """
    strand = 1
    locationlist = []
    for entry in t[0]:
        if entry == 'complement':
            strand = -1
    for entry in t[0]:
        if type(entry) != type('string'):
            locationlist.append([entry[0], entry[1]])
    return [['location', locationlist], ['strand', strand]]


@staticmethod
def _transform_session_persistence(persistence, feature_compatibility):
    """Transforms session persistence into an object that will

            be processed by the templating system
        """
    return {'type': persistence.type, 'cookie_name': persistence.cookie_name}


def zeros_like(input):
    """Create a zero tensor with the same shape, dtype and context of the
    given tensor.

    Parameters
    ----------
    input : Tensor
        The input

    Returns
    -------
    Tensor
        The result
    """
    pass


@classmethod
def white(cls, string, auto=False):
    """Color-code entire string.

        :param str string: String to colorize.
        :param bool auto: Enable auto-color (dark/light terminal).

        :return: Class instance for colorized string.
        :rtype: Color
        """
    return cls.colorize('white', string, auto=auto)


@staticmethod
def _get_hydrogen(df, invert):
    """Return only hydrogen atom entries from a DataFrame"""
    if invert:
        return df[df['element_symbol'] != 'H']
    else:
        return df[df['element_symbol'] == 'H']


def get_overview_page_analysis_table_args(overview_page_analysis):
    """Creates a gviz DataTable object from an OverviewPageAnalysis proto.

  Args:
    overview_page_analysis: An overview_page_pb2.OverviewPageAnalysis.

  Returns:
    Returns a gviz_api.DataTable
  """
    table_description = [('selfTimePercent', 'number', 'Time (%)'), (
        'cumulativeTimePercent', 'number', 'Cumulative time (%)'), (
        'category', 'string', 'Category'), ('operation', 'string',
        'Operation'), ('flopRate', 'number', 'GFLOPs/Sec')]
    data = []
    for op in overview_page_analysis.top_device_ops:
        row = [op.self_time_fraction, op.cumulative_time_fraction, str(op.
            category), str(op.name), op.flop_rate]
        data.append(row)
    device_compute_16bit_percent = '{:.1f}'.format(overview_page_analysis.
        device_compute_16bit_percent)
    device_compute_32bit_percent = '{:.1f}'.format(overview_page_analysis.
        device_compute_32bit_percent)
    remark_text = overview_page_analysis.remark_text
    remark_color = overview_page_analysis.remark_color
    custom_properties = {'device_compute_16bit_percent':
        device_compute_16bit_percent, 'device_compute_32bit_percent':
        device_compute_32bit_percent, 'remark_text': remark_text,
        'remark_color': remark_color}
    return table_description, data, custom_properties


def format_args_check(**kwargs):
    """
    Check types of parameters used in `format_arr`.

    """
    if 'depth' in kwargs and not isinstance(kwargs['depth'], int):
        raise ValueError('`depth` must be an integer.')
    if 'indent' in kwargs and not isinstance(kwargs['indent'], str):
        raise ValueError('`indent` must be a string.')
    if 'col_delim' in kwargs and not isinstance(kwargs['col_delim'], str):
        raise ValueError('`col_delim` must be a string.')
    if 'row_delim' in kwargs and not isinstance(kwargs['row_delim'], str):
        raise ValueError('`row_delim` must be a string.')
    if 'dim_delim' in kwargs and not isinstance(kwargs['dim_delim'], str):
        raise ValueError('`dim_delim` must be a string.')
    if 'format_spec' in kwargs and not isinstance(kwargs['format_spec'], (
        str, list)):
        raise ValueError('`format_spec` must be a string or list of strings.')
    if 'assign' in kwargs:
        if not isinstance(kwargs['assign'], str):
            raise ValueError('`assign` must be a string.')


def _bp_static_url(blueprint):
    """ builds the absolute url path for a blueprint's static folder """
    u = u'%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or '')
    return u


def set_organism_condition(query: str, organism: str) ->str:
    """Replaces a placeholder in a query with a condition restricting results to a certain organism"""
    if not organism:
        modified_query = query.replace(':ORGANISM_CONDITION', 'TRUE')
    else:
        modified_query = query.replace(':ORGANISM_CONDITION',
            'abbreviation = :organism')
    return modified_query


def invert_dict(d, is_val_tuple=False, unique=True):
    """
    Invert a dictionary by making its values keys and vice versa.

    Parameters
    ----------
    d : dict
        The input dictionary.
    is_val_tuple : bool
        If True, the `d` values are tuples and new keys are the tuple items.
    unique : bool
        If True, the `d` values are unique and so the mapping is
        one to one. If False, the `d` values (possibly) repeat, so the inverted
        dictionary will have as items lists of corresponding keys.

    Returns
    -------
    di : dict
        The inverted dictionary.
    """
    di = {}
    for key, val in d.iteritems():
        if unique:
            if is_val_tuple:
                for v in val:
                    di[v] = key
            else:
                di[val] = key
        elif is_val_tuple:
            for v in val:
                item = di.setdefault(v, [])
                item.append(key)
        else:
            item = di.setdefault(val, [])
            item.append(key)
    return di


def prepare_response(data):
    """
    Transforms a string, Exception or tuple to consistently structured output.
    """
    data = data.args if isinstance(data, Exception) else data
    if isinstance(data, str):
        detail = data
        objects = []
    else:
        detail = str(data[0])
        objects = data[1] if len(data) > 1 else []
    if objects and not isinstance(objects, list):
        objects = [objects]
    count = len(objects) if objects else 0
    return {'detail': detail, 'objects': objects, 'count': count}


def sigmoid(input, eps=1e-07):
    """Same as `torch.sigmoid`, plus clamping to `(eps,1-eps)"""
    return input.sigmoid().clamp(eps, 1 - eps)


def does_ticker_exist(connector, ticker):
    """
    Check if a given ticker exists in the stock database.

    """
    cur = connector.cursor()
    cur.execute('SELECT TICKER FROM stock_data WHERE TICKER = %s', (ticker,))
    return cur.fetchone() is not None


def fast_exponentiation2(a, b, q):
    """Compute (a pow b) % q

    :param int a b: non negative
    :param int q: positive
    :complexity: O(log b)
    """
    assert a >= 0 and b >= 0 and q >= 1
    p = 0
    p2 = 1
    ap2 = a % q
    result = 1
    while b > 0:
        if p2 & b > 0:
            b -= p2
            result = result * ap2 % q
        p += 1
        p2 *= 2
        ap2 = ap2 * ap2 % q
    return result


def shader_script_update():
    """Update shader script node with new sockets and options from the script

    """
    pass


def download(**attrs):
    """
		This function is used to download the corpus. Leave as-is to use built-in LLP download system.
		Provide a

		So far, downloadable data types (for certain corpora) are:
			a) `txt` files
			b) `xml` files
			c) `metadata` files
			d) `freqs` files

		If you have another zip folder of txt files you'd like to download,
		you can specify with `url_txt` (i.e. url_`type`, where type is in `quotes` in (a)-(d) above):
			corpus.download(url_txt="https://www.etcetera.com/etc.zip")
		"""
    return super().download(**attrs)


@classmethod
def get_class_action_url_lazy(cls, action, *args, **kwargs):
    """
        `action` needs to be a valid Python identifier.
        """
    url_name = cls.get_action_url_formatter(action)
    attr_name = '_%s_url' % action
    return cls.get_class_url_lazy(url_name, attr_name, *args, **kwargs)


@staticmethod
def supported_operations():
    """Return the supportedOperations object."""
    return []


@classmethod
def msg_handler(cls, sock, cmd):
    """Main function to handle the incoming (received) command.

        Args:
            sock (multiprocessing.connection.Connection): Client socket in case you need to respond to the given command
            cmd (object): Command object that was sent to this process
        """
    pass


def applies_to_all_images(fileobject):
    """Set image filetype"""
    return fileobject.filetype == 'Image'


def p_ArgumentList(p):
    """ArgumentList : Argument Arguments"""
    p[0] = [p[1]] + p[2]


@classmethod
def parse_prefixed_args(cls, args):
    """Similar to parse_args(), but stripping leading colons from the first argument
        of a line (usually the sender field)."""
    args = cls.parse_args(args)
    args[0] = args[0].split(':', 1)[1]
    return args


def is_iterable(obj):
    """Check if `obj` is iterable."""
    try:
        iter(obj)
    except TypeError:
        return False
    else:
        return True


def diz_from_dms(binary, filename):
    """
    Amiga diskmasher format. Depends on the external binary 'xdms'.
    """
    import subprocess
    args = 'd', filename
    proc = subprocess.Popen((binary,) + args, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    output, _ = proc.communicate()
    if proc.returncode == 0:
        return output.decode('cp437_art')
    else:
        return u'No description'


def resolve(name, module=None):
    """Resole dotted name to python module
    """
    name = name.split('.')
    if not name[0]:
        if module is None:
            raise ValueError('relative name without base module')
        module = module.split('.')
        name.pop(0)
        while not name[0]:
            module.pop()
            name.pop(0)
        name = module + name
    used = name.pop(0)
    found = __import__(used)
    for n in name:
        used += '.' + n
        try:
            found = getattr(found, n)
        except AttributeError:
            __import__(used)
            found = getattr(found, n)
    return found


@staticmethod
def truncate(coord):
    """
        Formats a coordinate to within an acceptable degree of accuracy (2
        decimal places for mercator).
        """
    return '%.2f' % (int(coord * 100) / float(100))


def _loadCAsFromDir(directoryPath):
    """
    Load certificate-authority certificate objects in a given directory.

    @param directoryPath: a L{FilePath} pointing at a directory to load .pem
        files from.

    @return: a C{list} of L{OpenSSL.crypto.X509} objects.
    """
    from twisted.internet import ssl
    caCerts = {}
    for child in directoryPath.children():
        if not child.basename().split('.')[-1].lower() == 'pem':
            continue
        try:
            data = child.getContent()
        except IOError:
            continue
        try:
            theCert = ssl.Certificate.loadPEM(data)
        except ssl.SSL.Error:
            pass
        else:
            caCerts[theCert.digest()] = theCert.original
    return caCerts.values()


def register_signal(number, target, func):
    """Registers a signal handler.

    :param int number: Signal number.

    :param str|unicode target:

        * ``workers``  - run the signal handler on all the workers
        * ``workerN`` - run the signal handler only on worker N
        * ``worker/worker0`` - run the signal handler on the first available worker
        * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers

        * ``mules`` - run the signal handler on all of the mules
        * ``muleN`` - run the signal handler on mule N
        * ``mule/mule0`` - run the signal handler on the first available mule

        * ``spooler`` - run the signal on the first available spooler
        * ``farmN/farm_XXX``  - run the signal handler in the mule farm N or named XXX

        * http://uwsgi.readthedocs.io/en/latest/Signals.html#signals-targets

    :param callable func:

    :rtype: None

    :raises ValueError: If unable to register
    """


def aa_energies():
    """Function holding free energies of transfer between cyclohexane and water for all natural amino acids.
    H. G. Boman, D. Wade, I. a Boman, B. Wåhlin, R. B. Merrifield, *FEBS Lett*. **1989**, *259*, 103–106.

    :return: dictionary with amino acid letters and corresponding energies.
    """
    energies = {'L': -4.92, 'I': -4.92, 'V': -4.04, 'F': -2.98, 'M': -2.35,
        'W': -2.33, 'A': -1.81, 'C': -1.28, 'G': -0.94, 'Y': 0.14, 'T':
        2.57, 'S': 3.4, 'H': 4.66, 'Q': 5.54, 'K': 5.55, 'N': 6.64, 'E':
        6.81, 'D': 8.72, 'R': 14.92, 'P': 0.0}
    return energies


@classmethod
def get_object(cls, api_token, id):
    """
        Class method that will return a LoadBalancer object by its ID.

        Args:
            api_token (str): DigitalOcean API token
            id (str): Load Balancer ID
        """
    load_balancer = cls(token=api_token, id=id)
    load_balancer.load()
    return load_balancer


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 fitPlane(points):
    """Best fits a plane to a cloud of points"""
    import numpy as np
    XYZ = np.array(points)
    [rows, cols] = XYZ.shape
    p = np.ones((rows, 1))
    AB = np.hstack([XYZ, p])
    [u, d, v] = np.linalg.svd(AB, 0)
    B = v[(3), :]
    nn = np.linalg.norm(B[0:3])
    B = B / nn
    pplane = [0, 0, -(B[3] / B[2])]
    vplane = B[0:3].tolist()
    return pplane, vplane


def save_model(model, filename):
    """Save a model to file"""
    pass


def get_ind_mat_average_uniqueness(ind_mat):
    """
    Snippet 4.4. page 65, Compute Average Uniqueness
    Average uniqueness from indicator matrix

    :param ind_mat: (np.matrix) indicator binary matrix
    :return: (float) average uniqueness
    """
    concurrency = ind_mat.sum(axis=1)
    uniqueness = ind_mat.T / concurrency
    avg_uniqueness = uniqueness[uniqueness > 0].mean()
    return avg_uniqueness


def print_joinlist(joins, indent=0, StringType=str):
    """ Print the joinlist joins using the given indent level
    """
    for j in joins:
        if type(j) == StringType:
            text = repr(j)
            if len(text) > 40:
                text = text[:40] + '...'
            print(' ' + indent * ' |', text, ' (len = %i)' % len(j))
        else:
            text = j[0]
            l, r = j[1:3]
            text = repr(text[l:r])
            if len(text) > 40:
                text = text[:40] + '...'
            print(' ' + indent * ' |', text, ' (len = %i)' % (r - l), (l, r))


def ensure_object_is_string(item, title):
    """
    Checks that the item is a string. If not, raises ValueError.
    """
    assert isinstance(title, str)
    if not isinstance(item, str):
        msg = '{} must be a string. {} passed instead.'
        raise TypeError(msg.format(title, type(item)))
    return None


def input_test(a):
    """
    Injected function for Get_Input testing.

    :param a: input
    :return: "1"
    """
    _ = a
    return '1'


def list_organizational_units_for_parent(ParentId=None, NextToken=None,
    MaxResults=None):
    """
    Lists the organizational units (OUs) in a parent organizational unit or root.
    This operation can be called only from the organization's master account.
    See also: AWS API Documentation

    :example: response = client.list_organizational_units_for_parent(
        ParentId='string',
        NextToken='string',
        MaxResults=123
    )

    :type ParentId: string
    :param ParentId: [REQUIRED]
            The unique identifier (ID) of the root or OU whose child OUs you want to list.
            The regex pattern for a parent ID string requires one of the following:
            Root: a string that begins with 'r-' followed by from 4 to 32 lower-case letters or digits.
            Organizational unit (OU): a string that begins with 'ou-' followed by from 4 to 32 lower-case letters or digits (the ID of the root that the OU is in) followed by a second '-' dash and from 8 to 32 additional lower-case letters or digits.

    :type NextToken: string
    :param NextToken: Use this parameter if you receive a NextToken response in a previous request that indicates that there is more output available. Set it to the value of the previous call's NextToken response to indicate where the output should continue from.

    :type MaxResults: integer
    :param MaxResults: (Optional) Use this to limit the number of results you want included in the response. If you do not include this parameter, it defaults to a value that is specific to the operation. If additional items exist beyond the maximum you specify, the NextToken response element is present and has a value (is not null). Include that value as the NextToken request parameter in the next call to the operation to get the next part of the results. Note that Organizations might return fewer results than the maximum even when there are more results available. You should check NextToken after every operation to ensure that you receive all of the results.

    :rtype: dict
    :return: {
        'OrganizationalUnits': [
            {
                'Id': 'string',
                'Arn': 'string',
                'Name': 'string'
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def quaternion_real(quaternion):
    """Return real part of quaternion.

    >>> quaternion_real([3, 0, 1, 2])
    3.0

    """
    return float(quaternion[0])


def update_normalized_mp3s(mp3_files):
    """
    Regenerate normalized files corresponding to some mp3_files

    :param mp3_files: List of Mp3File objects
    """
    for mp3_file in mp3_files:
        mp3_file.save_normalized(overwrite=True)


def _trunc_el_planning(el_planning, starttime, endtime):
    """Modify (start, stop) tuple that are not within the (starttime, endtime) interval """
    if len(el_planning) > 0:
        el_planning.sort()
        i = 0
        while True:
            if i == len(el_planning):
                break
            start, stop = el_planning[i]
            if stop < starttime or start > endtime:
                el_planning.remove((start, stop))
            elif start < starttime:
                if stop < endtime:
                    el_planning.remove((start, stop))
                    el_planning.append((starttime, stop))
                else:
                    el_planning.remove((start, stop))
                    el_planning.append((starttime, endtime))
            elif stop > endtime:
                el_planning.remove((start, stop))
                el_planning.append((start, endtime))
            else:
                i += 1
            if i == len(el_planning):
                break
        el_planning.sort()


def _local_name(name: str) ->str:
    """
    Removes namespace from node name
    """
    assert name and isinstance(name, str), name
    return name.split('}')[1] if '}' in name else name


def restore_mysqldb():
    """Restores mysqldb"""
    try:
        import MySQLdb
    except ImportError:
        pass
    else:
        setattr(MySQLdb, 'connect', getattr(MySQLdb.connect, '__wrapped__',
            MySQLdb.connect))


def architecture_is_64bit(arch):
    """
	Check if the architecture specified in *arch* is 64-bit.

	:param str arch: The value to check.
	:rtype: bool
	"""
    return bool(arch.lower() in ('amd64', 'x86_64'))


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


@classmethod
def split_project(cls, name):
    """
        Split a directory name into project, core-version, version and patches.

        Patches should be separated from the main project string and one another
        using a '+'.
        """
    p = name.split('+')
    name, extras = p[0], tuple(p[1:])
    match = cls.package_pattern.fullmatch(name)
    if match:
        return match.group(1), match.group(2), match.group(3), extras
    raise ValueError('Not a valid package string: "{}"'.format(name))


@classmethod
def recognizeCaptcha(cls, image_path, extension, pixel_min=0, captcha_name=
    'chaptcha'):
    """ 识别验证码， 返回二值化验证码和字符分割横坐标，以及图片扩展名 """
    from PIL import Image
    image_object = Image.open(image_path)
    image_object = image_object.convert('P')
    d_histogram = image_object.histogram()
    values = dict(enumerate(d_histogram, 0))
    temp = sorted(values.items(), key=lambda x: x[1], reverse=True)[:10]
    temp = sorted(temp, key=lambda x: x[0], reverse=True)[3:]
    pixel_max = temp[0][0]
    binary_object = cls.captchaImageBinary(pixel_min, pixel_max,
        image_object=image_object, image_path=image_path)
    letters = cls.longitudinalSplit(binary_object)
    return binary_object, letters, extension


@classmethod
def suggestParser(cls, ext, text):
    """ suggestParser(ext, text)

        Given a filename extension and text, returns the name of the suggested
        parser corresponding to the language of the file.

        See also registerFilenameExtension() and registerShebangKeyword()
        """
    parser = cls.suggestParserfromText(text)
    if parser == '':
        parser = cls.suggestParserfromFilenameExtension(ext)
    parser = cls.getParserByName(parser).disambiguate(text)
    return parser


def labelTextWidth(label):
    """ Returns the width of label text of the label in pixels.

        IMPORTANT: does not work when the labels are styled using style sheets.

        Unfortunately it is possible to retrieve the settings (e.g. padding) that were set by the
        style sheet without parsing the style sheet as text.
    """
    fontMetrics = label.fontMetrics()
    contentsWidth = fontMetrics.size(label.alignment(), label.text()).width()
    if label.indent() < 0 and label.frameWidth():
        indent = fontMetrics.width('x') / 2 - label.margin()
        indent *= 2
    else:
        indent = label.indent()
    result = contentsWidth + indent + 2 * label.frameWidth(
        ) + 2 * label.margin()
    if 1:
        print('contentsWidth: {}'.format(contentsWidth))
        print('lineWidth: {}'.format(label.lineWidth()))
        print('midLineWidth: {}'.format(label.midLineWidth()))
        print('frameWidth: {}'.format(label.frameWidth()))
        print('margin: {}'.format(label.margin()))
        print('indent: {}'.format(label.indent()))
        print('actual indent: {}'.format(indent))
        print('RESULT: {}'.format(result))
        print()
    return result


def roundfloat(x, tol):
    """
    Return the float nearest to x stepsize tol
    """
    return x.__divmod__(tol)[0] * tol


def update():
    """Update content ot view information based on user input
        """


def move_relaydomain_to_transport(apps, schema_editor):
    """Transform relaydomains to transports."""
    RelayDomain = apps.get_model('relaydomains', 'RelayDomain')
    RecipientAccess = apps.get_model('relaydomains', 'RecipientAccess')
    Transport = apps.get_model('transport', 'Transport')
    ra_to_create = []
    for rd in RelayDomain.objects.select_related('domain', 'service'):
        next_hop = '[{}]:{}'.format(rd.target_host, rd.target_port)
        tr = Transport.objects.create(pattern=rd.domain.name, service=
            'relay', next_hop=next_hop, _settings={'relay_target_host': rd.
            target_host, 'relay_target_port': rd.target_port,
            'relay_verify_recipients': rd.verify_recipients})
        rd.domain.transport = tr
        rd.domain.save(update_fields=['transport'])
        if not rd.verify_recipients:
            continue
        ra_to_create.append(RecipientAccess(pattern=rd.domain.name, action=
            'reject_unverified_recipient'))
    RecipientAccess.objects.bulk_create(ra_to_create)


def sort_spec(spec):
    """Helper to provide a key function for `sorted`

    Provide key to sort by type first and by whatever identifies a particular
    type of spec dict

    Parameters
    ----------
    spec: dict
      study specification dictionary

    Returns
    -------
    string
    """
    if spec['type'] == 'dicomseries':
        return 'dicomseries' + spec['uid']
    else:
        return spec['type'] + spec['location']


def subject(text):
    """
    Generates a Subject header with a given *text*.
    """
    yield 'Subject'
    yield text


def list_split(string, split_list, removechar=('<', '>')):
    """
        Take a string and remove the item inside a list and return the splited string as a list

    Modified (heavily) from https://stackoverflow.com/a/4697047/7332922

    :param string: The string to process
    :param split_list: Element to remove from the string -> MUST BE IN ORDER
    :param removechar: Special characters to remove
    :return: List of the remaining elements in the string
    """
    try:
        splited_string = []
        for c in split_list:
            v = string.split(c)
            string = v[1]
            splited_string.append(v[0])
            try:
                splited_string.remove('')
            except:
                pass
        for c in removechar:
            string = string.replace(c, '')
        if string != '':
            splited_string.append(string)
        return splited_string
    except:
        return []


def iter_except(func, exception, first=None):
    """ Call a function repeatedly until an exception is raised.

    Converts a call-until-exception interface to an iterator interface.
    Like __builtin__.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.

    Examples:
        iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator
        iter_except(d.popitem, KeyError)                         # non-blocking dict iterator
        iter_except(d.popleft, IndexError)                       # non-blocking deque iterator
        iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue
        iter_except(s.pop, KeyError)                             # non-blocking set iterator

    """
    try:
        if first is not None:
            yield first()
        while 1:
            yield func()
    except exception:
        pass


@classmethod
def json_to_models(cls, data):
    """ Converts a list of json to a list of models using a Schema """
    models = cls.to_model(data, {'many': True})
    for model_data, model in zip(data, models):
        model.raw = model_data
        cls._unlock_unmarshalling(model)
        cls.set_additional_fields(model, model_data)
    return models


def convertTempoByReferent(numberSrc, quarterLengthBeatSrc,
    quarterLengthBeatDst=1.0):
    """
    Convert between equivalent tempi, where the speed stays the
    same but the beat referent and number change.

    60 bpm at quarter, going to half

    >>> tempo.convertTempoByReferent(60, 1, 2)
    30.0

    60 bpm at quarter, going to 16th

    >>> tempo.convertTempoByReferent(60, 1, .25)
    240.0

    60 at dotted quarter, get quarter

    >>> tempo.convertTempoByReferent(60, 1.5, 1)
    90.0

    60 at dotted quarter, get half

    >>> tempo.convertTempoByReferent(60, 1.5, 2)
    45.0

    60 at dotted quarter, get trip

    >>> tempo.convertTempoByReferent(60, 1.5, 1/3)
    270.0

    A Fraction instance can also be used:

    >>> tempo.convertTempoByReferent(60, 1.5, common.opFrac(1/3))
    270.0

    """
    srcDurPerBeat = 60 / numberSrc
    dur = srcDurPerBeat / quarterLengthBeatSrc
    dstDurPerBeat = dur * float(quarterLengthBeatDst)
    return float(60 / dstDurPerBeat)


def get_parameters():
    """
    retrieve a list of parameter codes available.
    Reference for GSOD parameters : https://www1.ncdc.noaa.gov/pub/data/gsod/readme.txt

    Parameters
    ----------
        None

    Returns
    -------
        dictionary of variables with parameter codes as keys
        and GSOD codes as values.
    """
    VARIABLES = {'mean_temp': 'TEMP', 'mean_temp_count': 'TEMP',
        'dew_point': 'DEWP', 'dew_point_count': 'DEWP',
        'sea_level_pressure': 'SLP     ', 'sea_level_pressure_count':
        'SLP     ', 'station_pressure': 'STP', 'station_pressure_count':
        'STP', 'visibility': 'VISIB', 'visibility_count': 'VISIB',
        'mean_wind_speed': 'WDSP', 'mean_wind_speed_count': 'WDSP',
        'max_wind_speed': 'MXSPD', 'max_gust': 'GUST', 'max_temp': 'MAX',
        'max_temp_flag': 'MAX', 'min_temp': 'MIN', 'min_temp_flag': 'MIN',
        'precip': 'PRCP', 'precip_flag': 'PRCP', 'snow_depth': 'SNDP',
        'FRSHTT': 'FRSHTT'}
    return VARIABLES


@staticmethod
def score_c_to_5_classes(score_c):
    """
        Score C to 5 risk-classes

        :param score_c:  Score C
        :return: Risk-class
        """
    if score_c == 1:
        ret = 0
    elif 2 <= score_c <= 3:
        ret = 1
    elif 4 <= score_c <= 7:
        ret = 2
    elif 8 <= score_c <= 10:
        ret = 3
    else:
        ret = 4
    return ret


def build_repository(pharses):
    """
    Build the bible repository as a dict from identifier to context
    Jhn 3:10 --> text in John chapter 3 pharse 10
    """
    repository = {}
    for pharse in pharses:
        book, _, other = pharse.partition(' ')
        locator, _, context = other.partition(' ')
        repository[' '.join([book, locator])] = context
    return repository


def _go_to_line(editor, line):
    """
    Move cursor to this line in the current buffer.
    """
    b = editor.application.current_buffer
    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(
        line) - 1), 0)


def trailing_whitespace(physical_line):
    """
    JCR: Trailing whitespace is superfluous.
    FBM: Except when it occurs as part of a blank line (i.e. the line is
         nothing but whitespace). According to Python docs[1] a line with only
         whitespace is considered a blank line, and is to be ignored. However,
         matching a blank line to its indentation level avoids mistakenly
         terminating a multi-line statement (e.g. class declaration) when
         pasting code into the standard Python interpreter.

         [1] http://docs.python.org/reference/lexical_analysis.html#blank-lines

    The warning returned varies on whether the line itself is blank, for easier
    filtering for those who want to indent their blank lines.

    >>> trailing_whitespace('SELECT 1   ')
    (8, 'W291 trailing whitespace')
    >>> trailing_whitespace('   ')
    (0, 'W293 blank line contains whitespace')
    >>> trailing_whitespace('SELECT 1')
    >>> trailing_whitespace('')
    """
    physical_line = physical_line.rstrip('\n')
    physical_line = physical_line.rstrip('\r')
    physical_line = physical_line.rstrip('\x0c')
    stripped = physical_line.rstrip()
    if physical_line != stripped:
        if stripped:
            return len(stripped), 'W291 trailing whitespace'
        else:
            return 0, 'W293 blank line contains whitespace'


def vapour_pressure(svp, rh):
    """
    Computes the vapour pressure :math:`e_a` in [mbar]

    .. math ::
        e_{a}=\\frac{\\phi}{100}e_{s}

    Parameters
    ----------
    svp : float
        saturated vapour pressure
        :math:`e_s`
        [mbar]
    rh : float
        relative humidity
        :math:`\\phi`
        [%]

    Returns
    -------
    vp : float
        vapour pressure
        :math:`e_{a}`
        [mbar]

    Examples
    --------
    >>> from ETLook import meteo
    >>> meteo.vapour_pressure(rh=75, svp=meteo.saturated_vapour_pressure(20))
    17.537109531955842

    """
    return 0.01 * rh * svp


def perm_one(n):
    """
    The identity permutation

    EXAMPLES::

        sage: from surface_dynamics.misc.permutation import perm_one
        sage: perm_one(0)
        []
        sage: perm_one(3)
        [0, 1, 2]
    """
    return list(range(n))


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


def _MakeTile(repeated_string):
    """Make exactly 1Mb tile of the repeated string."""
    total_size = 1024 * 1024
    tile = repeated_string * (total_size // len(repeated_string))
    tile += repeated_string[:total_size % len(repeated_string)]
    return tile


def get_all_model_perms(model):
    """Returns an iterator of all model permissions."""
    meta = model._meta
    app_label = meta.app_label
    model_name = meta.model_name
    for p in meta.permissions:
        yield '%s.%s' % (app_label, p[0])
    for p in meta.default_permissions:
        yield '%s.%s_%s' % (app_label, p, model_name)


def chmod(path, mode):
    """change pernmissions of path"""
    import os, stat
    st = os.stat(path)
    return os.chmod(path, mode)


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

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


def reduce_matrix_size(transition_matrix):
    """Reduces matrix size."""
    while not transition_matrix.has_only_source_and_drain():
        while transition_matrix.loop_exists():
            transition_matrix.exclude_first_loop()
        transition_matrix.exclude_last_vertex()


def hist2D(x, y, bin_type=None, bins=None, dens=True, scale=None, c=None,
    cstat=None, xlim=None, ylim=None, clim=[None, None], nmin=0, xinvert=
    False, yinvert=False, cbar_invert=False, xlog=False, ylog=False, clog=
    None, title=None, xlabel=None, ylabel=None, clabel=None, lab_loc=0, ax=
    None, grid=None, output=None, plot_kw={}, **kwargs):
    """2D histogram function.

	Parameters
	----------
	x : array-like
		Position of data points in the x axis.
	y : array-like
		Position of data points in the y axis.
	bin_type : {'number','width','edges','equal'}, optional
		Defines how is understood the value given in bins: 'number' for givinf the desired number of bins, 'width' for
		the width of the bins, 'edges' for the edges of bins, and 'equal' for making bins with equal number of elements
		(or as close as possible). If not given it is inferred from the data type of bins: 'number' if int, 'width' if
		float and 'edges' if ndarray.
	bins : int, float, array-like or list, optional
		Gives the values for the bins, according to bin_type.
	dens : bool or list, optional
		If false the histogram returns raw counts.
	scale : float or list, optional
		Scaling of the data counts.
	c : array-like, optional
		If a valid argument is given in cstat, defines the value used for the binned statistics.
	cstat : str or function, optional
		Must be one of the valid str arguments for the statistics variable in scipy.stats.binned_statistic_2d
		('mean’, 'median’, 'count’, 'sum’, 'min’ or 'max’) or a function that takes a 1D array and outputs an integer
		 or float.
	xlim : tuple-like, optional
		Defines the limits of the x-axis, it must contain two elements (lower and higer limits).
	ylim : tuple-like, optional
		Defines the limits of the y-axis, it must contain two elements (lower and higer limits).
	clim : list, optional
		Defines the limits of the colour map ranges, it must contain two elements (lower and higer limits).
	nmin : int, optional (default: 0)
		The minimum number of points required in a bin in order to be plotted.
	xinvert : bool, optional
		If True, inverts the x-axis.
	yinvert : bool, optional
		If True, inverts the y-axis.
	cbar_invert : bool, optional
		If True, inverts the direction of the colour bar (not the colour map).
	xlog : bool, optional
		If True, the scale of the x-axis is logarithmic.
	ylog : bool, optional
		If True, the scale of the x-axis is logarithmic.
	clog : bool, optional
		If True, the colour map is changed from linear to logarithmic.
	title : str, optional
		Sets the title of the plot
	xlabel : str, optional
		Sets the label of the x-axis.
	ylabel : str, optional
		Sets the label of the y-axis.
	clabel : str, optional
		Sets the legend for the colour axis.
	lab_loc : int, optional
		Defines the position of the legend
	ax : pyplot.Axes, optional
		Use the given axes to make the plot, defaults to the current axes.
	grid : boolean, optional
		If not given defaults to the value defined in splotch.Params.
	output : boolean, optional
		If True, returns the edges and values of the histogram.
	plot_kw : dict, optional
		Explicit dictionary of kwargs to be parsed to matplotlib scatter function.
		Parameters will be overwritten if also given implicitly as a **kwarg.
	**kwargs : pcolormesh properties, optional
		kwargs are used to specify matplotlib specific properties such as cmap, norm, edgecolors etc.
		https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html

	Returns
	-------
	n : array
		The values of the histogram. Only provided if output is True.
	bin_edges_x : array
		The bin edges for the x axis. Only provided if output is True.
	bin_edges_y : array
		The bin edges for the y axis. Only provided if output is True.
	"""
    from numpy import nan, size, zeros, shape
    from matplotlib.colors import LogNorm
    from matplotlib.pyplot import pcolormesh, colorbar
    from .base_func import axes_handler, basehist2D, plot_finalizer
    if ax is not None:
        old_axes = axes_handler(ax)
    if type(bin_type) is not list:
        bin_type = [bin_type] * 2
    if type(bins) not in [list, tuple]:
        if bins is None:
            bins = max([10, int(len(x) ** 0.4)])
        bins = [bins] * 2
    if None in (clog, output):
        from .defaults import Params
        if clog is None:
            clog = Params.hist2D_caxis_log
        if output is None:
            output = Params.hist2D_output
    if size([x, y]) == 0:
        if clog == True:
            raise ValueError("Cannot set 'clog'=True if zero-size array given."
                )
        if cstat != None:
            raise ValueError(
                f"Cannot compute statistic (cstat='{cstat}') on zero-size array, set cstat=None if no data given."
                )
    X, Y, Z = basehist2D(x, y, c, bin_type, bins, scale, dens, cstat, xlog,
        ylog)
    if size([x, y]) == 0:
        counts = zeros(shape=shape(Z))
    else:
        _, _, counts = basehist2D(x, y, c, bin_type, bins, scale, dens,
            'count', xlog, ylog)
    Z[counts < nmin] = nan
    plot_par = plot_kw.copy()
    plot_par.update(kwargs)
    if clog:
        pcolormesh(X, Y, Z.T, norm=LogNorm(vmin=clim[0], vmax=clim[1], clip
            =True), **plot_par)
    else:
        pcolormesh(X, Y, Z.T, vmin=clim[0], vmax=clim[1], **plot_par)
    if clabel is not None:
        cbar = colorbar()
        cbar.set_label(clabel)
        if cbar_invert:
            cbar.ax.invert_yaxis()
    plot_finalizer(xlog, ylog, xlim, ylim, title, xlabel, ylabel, xinvert,
        yinvert, grid)
    if ax is not None:
        old_axes = axes_handler(old_axes)
    if output:
        return Z.T, X, Y


def clearcache():
    """Clear the cache entirely."""
    global cache
    cache = {}


def extract_version(txt):
    """This function tries to extract the version from the help text of any
    program."""
    words = txt.replace(',', ' ').split()
    version = None
    for x in reversed(words):
        if len(x) > 2:
            if x[0].lower() == 'v':
                x = x[1:]
            if '.' in x and x[0].isdigit():
                version = x
                break
    return version


def grayscale(image):
    """
    Convert the image to grayscale.

    :param image: The image to convert.
    :return: An image.
    """
    return image.convert('L')


def hyperbolic_load(y, pu, a, b):
    """
    Static hyperbolic model developed by Lee

    Parameters
    ----------------
    y -- displacement
    pu -- ultimate load
    a, b -- coefficients

    Output
    ----------------
    p -- soil resistence pressure
    """
    p = y / (a + b * y) * pu
    return p


@staticmethod
def _phase_finalize__write_problems__one_error_tobj(tobj, problem_writer):
    """
        This is invoked on each TargetObj in the ERROR state during _phase_finalize().
        Write the source file path to the problem file using problem_writer.
        """
    problem_writer.write(tobj.source_path_bytes)
    problem_writer.write(b'\n')
    return False


def set_session_id(session_id):
    """Set session id to value."""
    global LAST_SESSION_ID
    LAST_SESSION_ID = session_id


def check_indices(seq, seq_idx):
    """
    Given a sequence (e.g. list, tuple, ndarray) which is indexed by another,
    check the indices are sensible.

    TODO: check integers as well?

    Parameters
    ----------
    seq : sequence
    seq_idx : sequence of int

    """
    if min(seq_idx) < 0:
        raise IndexError('Found index < 0.')
    if max(seq_idx) > len(seq) - 1:
        raise IndexError('Found index larger than sequence length.')


def get_resource_description(resource, format='default', context=None, **kwargs
    ):
    """Return a string representation of the resource, according to the
        `format`.

        :param resource: the `Resource` to describe
        :param format: the kind of description wanted. Typical formats are:
                       `'default'`, `'compact'` or `'summary'`.
        :param context: an optional rendering context to allow rendering rich
                        output (like markup containing links)
        :type context: `ResourceContext`

        Additional keyword arguments can be given as extra information for
        some formats.

        For example, the ticket with the id 123 is represented as:
         - `'#123'` in `'compact'` format,
         - `'Ticket #123'` for the `default` format.
         - `'Ticket #123 (closed defect): This is the summary'` for the
           `'summary'` format

        Note that it is also OK to not define this method if there's no
        special way to represent the resource, in which case the standard
        representations 'realm:id' (in compact mode) or 'Realm id' (in
        default mode) will be used.
        """


def topological_sort(graph_unsorted):
    """
    Repeatedly go through all of the nodes in the graph, moving each of
    the nodes that has all its edges resolved, onto a sequence that
    forms our sorted graph. A node has all of its edges resolved and
    can be moved once all the nodes its edges point to, have been moved
    from the unsorted graph onto the sorted one.
    """
    graph_sorted = []
    graph_unsorted = dict(graph_unsorted)
    while graph_unsorted:
        acyclic = False
        for node, edges in list(graph_unsorted.items()):
            if edges is None:
                edges = []
            for edge in edges:
                if edge in graph_unsorted:
                    break
            else:
                acyclic = True
                del graph_unsorted[node]
                graph_sorted.append((node, edges))
        if not acyclic:
            raise RuntimeError('A cyclic dependency occurred')
    return graph_sorted


def stroke_trim():
    """Trim selected stroke to first loop or intersection

    """
    pass


def _return_param(val):
    """just return passed parameter - make a callable from any value"""
    return val


def canDelete():
    """True iff user can be removed from the Plone UI."""


@staticmethod
def maybe_remove_last_empty_line(split_lines):
    """Remove the last empty line

        which might be a relict from the split.
        """
    sl_len = len(split_lines)
    if sl_len == 0:
        return
    if not split_lines[sl_len - 1]:
        del split_lines[sl_len - 1]
    return


def _element_identification_string(element):
    """
    Gets a string that will hopefully help in identifing an element when there
    is an error.
    """
    info_string = 'tag: {}'.format(element.tag)
    try:
        elem_id = element.attrib['id']
        info_string += ' id: {}'.format(elem_id)
    except KeyError:
        pass
    return info_string


def parse_boolean(value):
    """Simple function to get a boolean value from string."""
    if not value:
        return False
    if str(value).lower() == 'true':
        return True
    return False


def set_sms_attributes(attributes=None):
    """
    Use this request to set the default settings for sending SMS messages and receiving daily SMS usage reports.
    You can override some of these settings for a single message when you use the Publish action with the MessageAttributes.entry.N parameter. For more information, see Sending an SMS Message in the Amazon SNS Developer Guide .
    See also: AWS API Documentation

    :example: response = client.set_sms_attributes(
        attributes={
            'string': 'string'
        }
    )

    :type attributes: dict
    :param attributes: [REQUIRED]
            The default settings for sending SMS messages from your account. You can set values for the following attribute names:
            MonthlySpendLimit   The maximum amount in USD that you are willing to spend each month to send SMS messages. When Amazon SNS determines that sending an SMS message would incur a cost that exceeds this limit, it stops sending SMS messages within minutes.
            Warning
            Amazon SNS stops sending SMS messages within minutes of the limit being crossed. During that interval, if you continue to send SMS messages, you will incur costs that exceed your limit.
            By default, the spend limit is set to the maximum allowed by Amazon SNS. If you want to exceed the maximum, contact AWS Support or your AWS sales representative for a service limit increase.
            DeliveryStatusIAMRole   The ARN of the IAM role that allows Amazon SNS to write logs about SMS deliveries in CloudWatch Logs. For each SMS message that you send, Amazon SNS writes a log that includes the message price, the success or failure status, the reason for failure (if the message failed), the message dwell time, and other information.DeliveryStatusSuccessSamplingRate   The percentage of successful SMS deliveries for which Amazon SNS will write logs in CloudWatch Logs. The value can be an integer from 0 - 100. For example, to write logs only for failed deliveries, set this value to 0 . To write logs for 10% of your successful deliveries, set it to 10 .
            DefaultSenderID   A string, such as your business brand, that is displayed as the sender on the receiving device. Support for sender IDs varies by country. The sender ID can be 1 - 11 alphanumeric characters, and it must contain at least one letter.
            DefaultSMSType   The type of SMS message that you will send by default. You can assign the following values:
            Promotional   (Default) Noncritical messages, such as marketing messages. Amazon SNS optimizes the message delivery to incur the lowest cost.
            Transactional   Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication. Amazon SNS optimizes the message delivery to achieve the highest reliability.
            UsageReportS3Bucket   The name of the Amazon S3 bucket to receive daily SMS usage reports from Amazon SNS. Each day, Amazon SNS will deliver a usage report as a CSV file to the bucket. The report includes the following information for each SMS message that was successfully delivered by your account:
            Time that the message was published (in UTC)
            Message ID
            Destination phone number
            Message type
            Delivery status
            Message price (in USD)
            Part number (a message is split into multiple parts if it is too long for a single message)
            Total number of parts
            To receive the report, the bucket must have a policy that allows the Amazon SNS service principle to perform the s3:PutObject and s3:GetBucketLocation actions.
            For an example bucket policy and usage report, see Monitoring SMS Activity in the Amazon SNS Developer Guide .
            (string) --
            (string) --

    :rtype: dict
    :return: {}

    :returns:
    Time that the message was published (in UTC)
    Message ID
    Destination phone number
    Message type
    Delivery status
    Message price (in USD)
    Part number (a message is split into multiple parts if it is too long for a single message)
    Total number of parts

    """
    pass


def cobyla_positivity_constraint(volume_fractions, *args):
    """COBYLA positivity constraint on volume fractions"""
    return volume_fractions - 0.001


def _record_job_status(job_model, job_id, status_str):
    """
    Record a status and return the job object
    """
    from autonomie_base.models.base import DBSESSION
    job = DBSESSION().query(job_model).filter(job_model.id == job_id).first()
    job.status = status_str
    return job


def distinguishable_paths(path1, path2):
    """
    Checks if two model paths are distinguishable in a deterministic way, without looking forward
    or backtracking. The arguments are lists containing paths from the base group of the model to
    a couple of leaf elements. Returns `True` if there is a deterministic separation between paths,
    `False` if the paths are ambiguous.
    """
    e1, e2 = path1[-1], path2[-1]
    for k, e in enumerate(path1):
        if e not in path2:
            depth = k - 1
            break
    else:
        depth = 0
    if path1[depth].max_occurs == 0:
        return True
    univocal1 = univocal2 = True
    if path1[depth].model == 'sequence':
        idx1 = path1[depth].index(path1[depth + 1])
        idx2 = path2[depth].index(path2[depth + 1])
        before1 = any(not e.is_emptiable() for e in path1[depth][:idx1])
        after1 = before2 = any(not e.is_emptiable() for e in path1[depth][
            idx1 + 1:idx2])
        after2 = any(not e.is_emptiable() for e in path1[depth][idx2 + 1:])
    else:
        before1 = after1 = before2 = after2 = False
    for k in range(depth + 1, len(path1) - 1):
        univocal1 &= path1[k].is_univocal()
        idx = path1[k].index(path1[k + 1])
        if path1[k].model == 'sequence':
            before1 |= any(not e.is_emptiable() for e in path1[k][:idx])
            after1 |= any(not e.is_emptiable() for e in path1[k][idx + 1:])
        elif any(e.is_emptiable() for e in path1[k] if e is not path1[k][idx]):
            univocal1 = False
    for k in range(depth + 1, len(path2) - 1):
        univocal2 &= path2[k].is_univocal()
        idx = path2[k].index(path2[k + 1])
        if path2[k].model == 'sequence':
            before2 |= any(not e.is_emptiable() for e in path2[k][:idx])
            after2 |= any(not e.is_emptiable() for e in path2[k][idx + 1:])
        elif any(e.is_emptiable() for e in path2[k] if e is not path2[k][idx]):
            univocal2 = False
    if path1[depth].model != 'sequence':
        if before1 and before2:
            return True
        elif before1:
            return univocal1 and e1.is_univocal() or after1 or path1[depth
                ].max_occurs == 1
        elif before2:
            return univocal2 and e2.is_univocal() or after2 or path2[depth
                ].max_occurs == 1
        else:
            return False
    elif path1[depth].max_occurs == 1:
        return before2 or (before1 or univocal1) and (e1.is_univocal() or
            after1)
    else:
        return (before2 or (before1 or univocal1) and (e1.is_univocal() or
            after1)) and (before1 or (before2 or univocal2) and (e2.
            is_univocal() or after2))


@classmethod
def from_profile(cls, profile, fontsize=18, figure_size=8.0):
    """
        Instantiate a PhasePlot object from a profile object created
        with :func:`~yt.data_objects.profiles.create_profile`.

        Parameters
        ----------
        profile : An instance of :class:`~yt.data_objects.profiles.ProfileND`
             A single profile object.
        fontsize : float
             The fontsize to use, in points.
        figure_size : float
             The figure size to use, in inches.

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>> extrema = {
        ... 'density': (1e-31, 1e-24),
        ... 'temperature': (1e1, 1e8),
        ... 'cell_mass': (1e-6, 1e-1),
        ... }
        >>> profile = yt.create_profile(ds.all_data(), ['density', 'temperature'],
        ...                             fields=['cell_mass'],extrema=extrema,
        ...                             fractional=True)
        >>> ph = yt.PhasePlot.from_profile(profile)
        >>> ph.save()
        """
    obj = cls.__new__(cls)
    data_source = profile.data_source
    return cls._initialize_instance(obj, data_source, profile, fontsize,
        figure_size)


def should_record(method):
    """ Decide whether or not a given API call should be recorded (persisted to disk) """
    return method in ['PUT', 'POST', 'DELETE']


def lchop(string, prefix):
    """Removes a prefix from string

    :param string: String, possibly prefixed with prefix
    :param prefix: Prefix to remove from string
    :returns: string without the prefix
    """
    if string.startswith(prefix):
        return string[len(prefix):]
    return string


def is_input_valid(char: str) ->bool:
    """
    Helper that checks if input is valid
    """
    if char is None:
        return False
    if char == '\x00':
        return False
    return True


@classmethod
def from_json(cls, jsonstr):
    """
        Create an xdict object from a JSON string

        Parameters
        ----------
        jsonstr : string
           Valid JSON string that represents an object

        Returns
        -------
        xdict object

        """
    import json
    out = cls()
    out.update(json.loads(jsonstr))
    return out


def get_quant_NAs(quantdata, quantheader):
    """Takes quantdata in a dict and header with quantkeys
    (eg iTRAQ isotopes). Returns dict of quant intensities
    with missing keys set to NA."""
    out = {}
    for qkey in quantheader:
        out[qkey] = quantdata.get(qkey, 'NA')
    return out


def df_shuffled_split(df, split_size, random_state=None):
    """ Returns tuple of shuffled and split DataFrame.
        split_size: proportion of rows to include in tuple[0]
    """
    df = df.sample(frac=1, random_state=random_state).reset_index(drop=True)
    split_at = int(len(df) * split_size)
    return df[:split_at], df[split_at:]


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

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

    Example::

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

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

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

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

    Supported sparse operations:

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

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

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

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

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


@classmethod
def _is_optional_claim(cls, claim_name: str) ->bool:
    """
            Determine if the given claim is optional and may thus be empty or missing in the claim set.

            A claim is optional if it is listed in :attr:`_optional_claims`.

            :param claim_name: The name of the claim to check.
            :return: `True` if the given claim is optional, `False` otherwise.
        """
    return claim_name in cls._optional_claims


def bool_to_yes_or_no(value):
    """
    Converts a boolean value into a string saying "YES" or "NO"

    :param value: A boolean value
    :type value: bool
    :return: "YES" or "NO"
    :rtype: str
    """
    return 'YES' if value else 'NO'


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

        :param SharingUserError val:
        :rtype: GetFileMetadataError
        """
    return cls('user_error', val)


def resolve_name(name):
    """Resolve a name like ``module.object`` to an object and return it.

    Raise `ImportError` if the module or name is not found.
    """
    parts = name.split('.')
    cursor = len(parts) - 1
    module_name = parts[:cursor]
    attr_name = parts[-1]
    while cursor > 0:
        try:
            ret = __import__('.'.join(module_name), fromlist=[attr_name])
            break
        except ImportError:
            if cursor == 0:
                raise
            cursor -= 1
            module_name = parts[:cursor]
            attr_name = parts[cursor]
            ret = ''
    for part in parts[cursor:]:
        try:
            ret = getattr(ret, part)
        except AttributeError:
            raise ImportError(name)
    return ret


def get_all_sectors_of_narratives(narratives):
    """Get all defined sectors of all narratives

    ARguments
    --------
    narratives : list
        All defined narratives

    Returns
    -------
    all_sectors : list
        All sectors
    """
    all_sectors = set()
    for narrative in narratives:
        all_sectors.add(narrative['sector'])
    all_sectors = list(all_sectors)
    return all_sectors


def is_target_inside_container(container):
    """Verify that the target of the reference is located inside
        the given container. This always return False if the reference
        as no target.
        """


def LookForExternals(externalDemos, demoName):
    """
    Checks if a demo name is in any of the external packages (like AGW) or
    if the user clicked on one of the external packages parent items in the
    tree, in which case it returns the html overview for the package.
    """
    pkg = overview = None
    for key, package in externalDemos.items():
        treeName, treeDemos = package.GetDemos()
        treeOverview = package.GetOverview()
        if treeName == demoName:
            return pkg, treeOverview
        elif demoName in treeDemos:
            return key, overview
    return pkg, overview


@classmethod
def create_from_value(cls, dict_repr: dict):
    """
        Create Object representation from dict

        :return DataStructure
        """
    data = cls(dict_repr[cls.OUTPUT_KEY])
    data.metadata = dict_repr[cls.METADATA_KEY]
    return data


def get_many_to_many_fields_from_model(model_class):
    """Return only M2M fields, including inherited ones?"""
    return model_class._meta.many_to_many


@classmethod
def is_unix(cls):
    """
        Checks if the current platform is in our unix list.

        :rtype: bool
        """
    return cls.get() in cls.UNIX


def restexpose(func):
    """
    Decorate a function to clearly mark it as an exposed REST method
    """
    setattr(func, 'restexposed', True)
    setattr(func, 'exposed', False)
    return func


def str_to_int(exp):
    """
    Convert a string to an integer.

    The method is primitive, using a simple hash based on the
    ordinal value of the characters and their position in the string.

    Parameters
    ----------
    exp : str
        The string expression to convert to an int.

    Returns
    -------
    sum : int
        An integer that is likely (though not extremely so) to be unique
        within the scope of the program.
    """
    sum_ = 0
    for i, character in enumerate(exp):
        sum_ += i + ord(character) + i * ord(character)
    return sum_


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

        :param str val:
        :rtype: AddMemberSelectorError
        """
    return cls('invalid_dropbox_id', val)


def parseValue(key):
    """
    Attempts to parse the key value, so if the string is 'False' it will parse a boolean false.

    :param key: the key to parse
    :type key: string

    :returns: the parsed key.
    """
    if key == 'True' or key == 'true':
        return True
    if key == 'False' or key == 'false':
        return False
    if key == 'None' or key == 'none':
        return None
    if '.' in key:
        try:
            f = float(key)
            return f
        except:
            pass
    try:
        i = int(key)
        return i
    except:
        pass
    return key


@classmethod
def default_options(cls):
    """Default configuration options

        Parameters
        ----------
        None

        Returns
        -------
        dict
        """
    return {'CHECK_WITH_INVERT_PROJ': True, 'GTIFF_IMPLICIT_JPEG_OVR':
        False, 'FIONA_ENV': True}


@staticmethod
def construct_image_reference_id(subscription_id, resource_group_name,
    image_name):
    """construct image id"""
    return (
        '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/images/{}'
        .format(subscription_id, resource_group_name, image_name))


@classmethod
def read_chunk(cls, opc_sync: bool, context: str) ->'IoTransferEventArgs':
    """Creates new IoTransferEventArgs of read string

		:param opc_sync: defines if the command is OPC-synchronised
		:param context: SCPI query. It is truncated to maximum of 100 characters.
		:return: IoTransferEventArgs object of a read string operation."""
    return cls(True, opc_sync, None, context)


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 zero_dataset(train=False, dev=False, test=False, train_rows=256,
    dev_rows=64, test_rows=64):
    """
    Load the Zero dataset.

    The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for
    integration testing. The extreme simplicity of the dataset allows for models to learn the task
    quickly allowing for quick end-to-end testing.

    Args:
        train (bool, optional): If to load the training split of the dataset.
        dev (bool, optional): If to load the development split of the dataset.
        test (bool, optional): If to load the test split of the dataset.
        train_rows (int, optional): Number of training rows to generate.
        dev_rows (int, optional): Number of development rows to generate.
        test_rows (int, optional): Number of test rows to generate.

    Returns:
        :class:`tuple` of :class:`iterable` or :class:`iterable`:
        Returns between one and all dataset splits (train, dev and test) depending on if their
        respective boolean argument is ``True``.

    Example:
        >>> from torchnlp.datasets import zero_dataset
        >>> train = zero_dataset(train=True)
        >>> train[0:2]
        [{'source': '0', 'target': '0'}, {'source': '0', 'target': '0'}]
    """
    ret = []
    for is_requested, n_rows in [(train, train_rows), (dev, dev_rows), (
        test, test_rows)]:
        if not is_requested:
            continue
        rows = [{'source': str(0), 'target': str(0)} for i in range(n_rows)]
        ret.append(rows)
    if len(ret) == 1:
        return ret[0]
    else:
        return tuple(ret)


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

        :param PaperContentAddMemberType val:
        :rtype: EventType
        """
    return cls('paper_content_add_member', val)


def get_code(text):
    """Wrapper for input so as to mock."""
    return input(text)


def renumber(atoms):
    """
    Renumber the atoms and the residues from a list of atom.

    :Parameters:
        - atoms: a list of atom, each atom is stored as a dictionary

    :Returns:
        - new_atoms: the new list renumbered
    """
    new_atoms = []
    resid = 0
    prev_resid = 0
    for atomid, atom in enumerate(atoms, start=1):
        if atom['resid'] != prev_resid:
            resid += 1
            prev_resid = atom['resid']
        atom['resid'] = resid % 100000
        atom['atomid'] = atomid % 100000
        new_atoms.append(atom)
    return new_atoms


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 virtual(func: 'callable'):
    """
    mark a function as "virtual", which means that this function can be override.
    any base class should use this or @abstractmethod to decorate all functions
    that can be (re)implemented by subclasses.
    """
    return func


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


@classmethod
def from_values(cls, a):
    """
        Return the shape of the moments for a fixed value.
        """
    return cls()