def komogorov(r, r0):
    """Calculate the phase structure function D_phi in the komogorov approximation

    Parameters
    ----------
    r : `numpy.ndarray`
        r, radial frequency parameter (object space)
    r0 : `float`
        Fried parameter

    Returns
    -------
    `numpy.ndarray`

    """
    return 6.88 * (r / r0) ** (5 / 3)


def _series_to_dict(x, index_name='index'):
    """
    Change Pandas Series to Dict With Index

    Parameters
    ----------
    x : pandas Series
    index_name : return dict key of index name
    """
    x_dict = x.to_dict()
    x_dict[index_name] = x.name
    return x_dict


def _set_contrib_foi(params, name: str, index: int, value: float):
    """Adjust the Disease.contrib_foi parameter"""
    params.disease_params.contrib_foi[index] = value


def _untag_depth(path):
    """Remove depth from path."""
    slash_ix = path.index('/')
    if slash_ix is None:
        return path
    return path[slash_ix:]


def get_row_count(socrata_client, dataset_id):
    """Get the row count of a Socrata dataset"""
    count = socrata_client.get(dataset_id, select='COUNT(*) AS count')
    return int(count[0]['count'])


@classmethod
def static(cls, obj, path, seen, *args):
    """
        Handle a static object or type, as defined by :attr:`.Walker.STATIC`.

        Arguments:
            obj (int, float, bool, str):
                Schema node.
            path (str):
                Path taken through the schema from the root.
            seen (.Schema list):
                Nodes already visited in the schema.
        """
    return obj


def writeToChild(childFD, data):
    """
        Similar to L{ITransport.write} but also allows the file descriptor in
        the child process which will receive the bytes to be specified.

        @type childFD: C{int}
        @param childFD: The file descriptor to which to write.

        @type data: C{str}
        @param data: The bytes to write.

        @return: C{None}

        @raise KeyError: If C{childFD} is not a file descriptor that was mapped
            in the child when L{IReactorProcess.spawnProcess} was used to create
            it.
        """


def _to_instance(x):
    """Converts x to an instance if its a class."""
    return x() if isinstance(x, type) else x


@classmethod
def get_user(cls, email=None, user_id=None):
    """ Return a dict for the user represented by the specified email
        or user_id.

        >>> user = Retaincc.get_user(user_id='123')
        >>> user['name']
        u'Somebody'

        """
    params = {'email': email, 'user_id': user_id}
    user_dict = cls._do_call('GET', cls.api_endpoint + 'users', params=params)
    return user_dict


def get_watcher_user_set(jira_client, issue):
    """Get a list of users ids that are watchers."""
    user_set = set()
    watchlist = jira_client.watchers(issue)
    for watcher in watchlist.watchers:
        user_set.add(watcher.name)
    return user_set


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


def encrypt(KeyId=None, Plaintext=None, EncryptionContext=None, GrantTokens
    =None):
    """
    Encrypts plaintext into ciphertext by using a customer master key. The Encrypt function has two primary use cases:
    Unless you are moving encrypted data from one region to another, you don't use this function to encrypt a generated data key within a region. You retrieve data keys already encrypted by calling the  GenerateDataKey or  GenerateDataKeyWithoutPlaintext function. Data keys don't need to be encrypted again by calling Encrypt .
    If you want to encrypt data locally in your application, you can use the GenerateDataKey function to return a plaintext data encryption key and a copy of the key encrypted under the customer master key (CMK) of your choosing.
    See also: AWS API Documentation

    Examples
    The following example encrypts data with the specified customer master key (CMK).
    Expected Output:

    :example: response = client.encrypt(
        KeyId='string',
        Plaintext=b'bytes',
        EncryptionContext={
            'string': 'string'
        },
        GrantTokens=[
            'string',
        ]
    )

    :type KeyId: string
    :param KeyId: [REQUIRED]
            A unique identifier for the customer master key. This value can be a globally unique identifier, a fully specified ARN to either an alias or a key, or an alias name prefixed by 'alias/'.
            Key ARN Example - arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
            Alias ARN Example - arn:aws:kms:us-east-1:123456789012:alias/MyAliasName
            Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
            Alias Name Example - alias/MyAliasName

    :type Plaintext: bytes
    :param Plaintext: [REQUIRED]
            Data to be encrypted.

    :type EncryptionContext: dict
    :param EncryptionContext: Name-value pair that specifies the encryption context to be used for authenticated encryption. If used here, the same value must be supplied to the Decrypt API or decryption will fail. For more information, see Encryption Context .
            (string) --
            (string) --

    :type GrantTokens: list
    :param GrantTokens: A list of grant tokens.
            For more information, see Grant Tokens in the AWS Key Management Service Developer Guide .
            (string) --

    :rtype: dict
    :return: {
        'CiphertextBlob': b'bytes',
        'KeyId': 'string'
    }

    :returns:
    KeyId (string) -- [REQUIRED]
    A unique identifier for the customer master key. This value can be a globally unique identifier, a fully specified ARN to either an alias or a key, or an alias name prefixed by "alias/".

    Key ARN Example - arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
    Alias ARN Example - arn:aws:kms:us-east-1:123456789012:alias/MyAliasName
    Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
    Alias Name Example - alias/MyAliasName

    Plaintext (bytes) -- [REQUIRED]
    Data to be encrypted.

    EncryptionContext (dict) -- Name-value pair that specifies the encryption context to be used for authenticated encryption. If used here, the same value must be supplied to the Decrypt API or decryption will fail. For more information, see Encryption Context .

    (string) --
    (string) --

    GrantTokens (list) -- A list of grant tokens.
    For more information, see Grant Tokens in the AWS Key Management Service Developer Guide .

    (string) --

    """
    pass


def print_users(user_list):
    """
    Prints the user list into a table

    Args:
        user_list: The user list to print
    """
    user_line_format = '  {:20s} | {:20s} | {:10s} | {:10s}'
    print('')
    print(user_line_format.format('Name', 'Role', 'Locked', 'Enabled'))
    for user in user_list:
        print(user_line_format.format(user['UserName'], user['RoleId'], str
            (user['Locked']), str(user['Enabled'])))
    print('')


def plot_quantities(ax, x, xunits, y, yunits, series_label, y_axlabel=None,
    x_axlabel=None):
    """ Utility function that will include the units into the plot."""
    xdata = x >> xunits
    ydata = y >> yunits


def _calcSum(data):
    """
	Sums the values of the reports.
	"""
    trend = []
    for line in data:
        sum = 0.0
        for i in range(1, len(line)):
            sum += line[i]
        dt = line[0]
        trend.append([dt, sum])
    return trend


def get_default_params(dim: int):
    """
        Returns the default parameters of the SHADE Differential Evolution Algorithm.
        :param dim: Size of the problem (or individual).
        :type dim: int
        :return: Dict with the default parameters of the SHADE Differential
        Evolution Algorithm.
        :rtype dict
    """
    return {'max_evals': 10000 * dim, 'memory_size': 100, 'individual_size':
        dim, 'population_size': 10 * dim, 'callback': None, 'seed': None,
        'opts': None}


def _crop(x, low=0, high=1):
    """Crop a number to an interval.

    Parameters
    ----------
    x : Number
    low : Number
    high : Number

    Returns
    -------
    Number
        `x` in the general case, but `low` if `x` is lower and `high` if `x` is higher.

    Examples
    --------
        >>> _crop(- 0.2)
        0
        >>> _crop(0.5)
        0.5
        >>> _crop(1.5)
        1
    """
    return min(max(x, low), high)


def _get_ax_size(fig, ax, unit='inches'):
    """
    Get size of axes within a figure, given fig and ax objects.

    https://stackoverflow.com/questions/19306510/determine-matplotlib-axis-size-in-pixels
    """
    bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    width, height = bbox.width, bbox.height
    if unit == 'pixels':
        width *= fig.dpi
        height *= fig.dpi
    return width, height


@classmethod
def from_json(cls, s, **kwargs):
    """
        Load and decode JSON data from url, filepath or data-string.
        Decoder specific options can be passed using kwargs:
        https://docs.python.org/3/library/json.html
        Return a new dict instance. A ValueError is raised in case of failure.
        """
    return cls(s, format='json', **kwargs)


def create_traffic_policy_version(Id=None, Document=None, Comment=None):
    """
    Creates a new version of an existing traffic policy. When you create a new version of a traffic policy, you specify the ID of the traffic policy that you want to update and a JSON-formatted document that describes the new version. You use traffic policies to create multiple DNS resource record sets for one domain name (such as example.com) or one subdomain name (such as www.example.com). You can create a maximum of 1000 versions of a traffic policy. If you reach the limit and need to create another version, you'll need to start a new traffic policy.
    See also: AWS API Documentation

    :example: response = client.create_traffic_policy_version(
        Id='string',
        Document='string',
        Comment='string'
    )

    :type Id: string
    :param Id: [REQUIRED]
            The ID of the traffic policy for which you want to create a new version.

    :type Document: string
    :param Document: [REQUIRED]
            The definition of this version of the traffic policy, in JSON format. You specified the JSON in the CreateTrafficPolicyVersion request. For more information about the JSON format, see CreateTrafficPolicy .

    :type Comment: string
    :param Comment: The comment that you specified in the CreateTrafficPolicyVersion request, if any.

    :rtype: dict
    :return: {
        'TrafficPolicy': {
            'Id': 'string',
            'Version': 123,
            'Name': 'string',
            'Type': 'SOA'|'A'|'TXT'|'NS'|'CNAME'|'MX'|'NAPTR'|'PTR'|'SRV'|'SPF'|'AAAA',
            'Document': 'string',
            'Comment': 'string'
        },
        'Location': 'string'
    }

    """
    pass


def is_exdir_object(directory):
    """
    WARNING: Does not test if inside exdir directory,
    only if the object can be an exdir object (i.e. a directory).
    """
    return directory.is_dir()


def user_images_directory(instance, filename):
    """ Prepend a directory path to uploaded filenames to prevent multiple files being uploaded with the same name

    If the same user uploads thes same filename twice the original file is overwritten.
    The FileField object places all uploaded files in MEDIA_ROOT/uid_<uid>/<filename>
    """
    return 'images/uid_{uid}/{filename}'.format(uid=getattr(instance.
        uploaded_by, 'id', 0), filename=filename)


def process(screen, parent, action, curline):
    """
    Traverse parent object & process the action returned from keys.parse
    """
    line = 0
    for child, depth in parent.traverse():
        if depth == 0:
            continue
        if line == curline:
            if action == 'expand':
                curline = child.expand(curline)
            elif action == 'expand_all':
                curline = child.expand(curline, recurse=True)
            elif action == 'toggle_expand':
                curline = child.expand(curline, toggle=True)
            elif action == 'collapse':
                curline = child.collapse(parent, curline, depth)
            elif action == 'collapse_all':
                curline = child.collapse(parent, curline, depth, recurse=True)
            elif action == 'toggle_pick':
                curline = child.pick(curline)
            elif action == 'pickall':
                curline = child.pick(curline, parent)
            elif action == 'nextparent':
                curline = child.nextparent(parent, curline, depth)
            elif action == 'prevparent':
                curline = child.prevparent(parent, curline, depth)[0]
            elif action == 'getsize':
                curline = child.getsize(curline, parent)
            elif action == 'getsizeall':
                curline = child.getsize(curline, parent, sizeall=True)
            action = None
        line += 1
    return curline, line


def get_default_sender(site):
    """get default sender (name, address) tuple"""
    sender = site.mail_from_name, site.mail_from_addr
    return sender


def edited_clear():
    """Undo all edition performed on the particle system

    """
    pass


def p_nonempty_lists(t):
    """case_spec_list      : case_spec case_spec_list
                           | case_spec
       case_statement_list : case_statement case_statement_list
                           | case_statement"""
    if len(t) == 2:
        t[0] = t[1]
    else:
        t[0] = t[1] + t[2]


@staticmethod
def _F2(a, b):
    """Integration term. See Yeadon 1990-ii Appendix 2."""
    return 0.5 + (a + b) / 3.0 + a * b * 0.25


def validate_args(args):
    """Validate the parsed command line arguments."""
    if args.basic and args.raw:
        raise ValueError(
            'The -b (--basic) and -r (--raw) options can not be used together.'
            )
    if args.debug and args.verbose:
        raise ValueError(
            'The -d (--debug) and -v (--verbose) options can not be used together.'
            )


@classmethod
def findClass(cls, className):
    """ Find a class object given its name.
        The search will start with protocols and then with protocols.
        """
    c = cls.getProtocols().get(className, cls.getObjects().get(className, None)
        )
    if c is None:
        raise Exception("findClass: class '%s' not found." % className)
    return c


def overbar(string):
    """
    Returns string preceeded by an overbar of the same length:
    >>> print(overbar('blee'))
    ____
    blee
    """
    return '%s\n%s' % ('_' * len(string), string)


@classmethod
def __width(cls, header):
    """ provides width of tine property

        :param header: tine frameHeader
        :type header: :obj:`dict` <:obj:`str`, `any`>
        :returns: numpy dtype
        :rtype: :obj:`str`
        """
    width = 0
    if 'aoiWidth' in header and header['aoiWidth'] > 0:
        width = header['aoiWidth']
    elif 'sourceWidth' in header:
        width = header['sourceWidth']
    if not 0 < width <= 65535:
        raise ValueError('Invalid width: %s' % width)
    return width


@classmethod
def read_tls_file(cls, file_path):
    """
        Shortcut method for reading a TLS file into a byte string.

        :param file_path: The location of the TLS certificate/key file
        :type file_path: str
        """
    if not file_path:
        return None
    with open(file_path, 'rb') as f:
        return f.read()


@classmethod
def key_to_dict(cls, key):
    """ Convert redis key to dict directly """
    key_items = key.split(u':')[1:]
    return dict(zip(cls.fields, key_items))


@classmethod
def CreateDataTypeMapByType(cls, data_type_definition):
    """Creates a specific data type map by type indicator.

    Args:
      data_type_definition (DataTypeDefinition): data type definition.

    Returns:
      DataTypeMap: data type map or None if the date type definition
          is not available.
    """
    data_type_map_class = cls._MAP_PER_DEFINITION.get(data_type_definition.
        TYPE_INDICATOR, None)
    if not data_type_map_class:
        return None
    return data_type_map_class(data_type_definition)


def _extract_column_names(headers):
    """
    Return an array containing the column names, extracted from the headers
    """
    if 'COLUMN_NAMES' in headers:
        name_string = headers['COLUMN_NAMES']
        return name_string.split('\t')
    else:
        return None


def sfr_from_L_nu(luminosity):
    """Use Kennicutt (1998) conversion from UV luminosity to star formation rate.

    Parameters
    ----------

    luminosity:
        the luminosity in units of ergs s^-1 Hz^-1 anywhere between
        1500-2800 Angstroms.

    Returns
    -------

    The SFR in Msun/year.

    Notes
    -----

    Kennicutt (1998ARA&A..36..189K) says:

       SFR/(MSun/year) = 1.4 * 10^-28 (L_nu/ergs s^-1 Hz^-1)

    where L_nu is the UV luminosity anywhere between 1500-2800 Angstroms.
    """
    return 1.4e-28 * luminosity


def is_test_account(data):
    """Return True if email is a test email account"""
    email = data.email
    return 'test' in email and email.endswith('@testco.com')


def inc(x):
    """ Add one to the current value """
    return x + 1


def get_domain(url):
    """
    Given the following a url extract domain ignoring scheme and params.
    Using urlparse->netloc seems to fail

    >>> get_domain(http://www.contosdo.com)
    www.contosdo.com
    >>> get_domain(www.contosdo.com)
    www.contosdo.com
    >>> get_domain(http://www.contosdo.com/example/?filter=test)
    www.contosdo.com
    >>> get_domain(http://contosdo.com/example/?filter=test)
    contosdo.com

    """
    url = url.split('://')
    index = (0, 1)[len(url) > 1]
    domain = url[index].split('?')[0].split('/')[0].split(':')[0].lower()
    return domain


def generate_hs_descriptor_raw(desc_id_base32, permanent_key_block,
    secret_id_part_base32, publication_time, introduction_points_part):
    """
    Generate hidden service descriptor string
    """
    doc = ['rendezvous-service-descriptor {}'.format(desc_id_base32),
        'version 2', 'permanent-key', permanent_key_block,
        'secret-id-part {}'.format(secret_id_part_base32),
        'publication-time {}'.format(publication_time),
        'protocol-versions 2,3', 'introduction-points',
        introduction_points_part, 'signature\n']
    unsigned_descriptor = '\n'.join(doc)
    return unsigned_descriptor


def psi_K_Mg_HCO3_HMW84(T, P):
    """c-c'-a: potassium magnesium bicarbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def int_to_hex(number, bits=16):
    """Convert int to a four-character hex string.

    This uses two's complement in encoding the integer, per Huber's
    manual.
    """
    return '{:04X}'.format((number + (1 << bits)) % (1 << bits))


def writeCTFModel(ctfObj, filename):
    """ Write a CTFModel object as Xmipp .ctfparam"""
    pass


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.train.TrainedClassifierModel'


def mass_setattr(obj, **attrs):
    """Set all given attributes and return the same object."""
    for attr in attrs:
        setattr(obj, attr, attrs[attr])
    return obj


def get_default_schema_manager():
    """
    internal: convenience function
    """
    from punx import cache_manager
    cm = cache_manager.CacheManager()
    assert cm is not None
    assert cm.default_file_set is not None
    return cm.default_file_set.schema_manager


def list_facet_names(SchemaArn=None, NextToken=None, MaxResults=None):
    """
    Retrieves the names of facets that exist in a schema.
    See also: AWS API Documentation

    :example: response = client.list_facet_names(
        SchemaArn='string',
        NextToken='string',
        MaxResults=123
    )

    :type SchemaArn: string
    :param SchemaArn: [REQUIRED]
            The Amazon Resource Name (ARN) to retrieve facet names from.

    :type NextToken: string
    :param NextToken: The pagination token.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to retrieve.

    :rtype: dict
    :return: {
        'FacetNames': [
            'string',
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def devectorize(vec):
    """Create a matrix from a symmetric vectorization."""
    from ..expressions.vectorizations import SymmetricVectorization
    v = vec.size[0]
    n = int((1 + 8 * v) ** 0.5 - 1) // 2
    return SymmetricVectorization((n, n)).devectorize(vec)


def is_iterable(obj):
    """
    Are we being asked to look up a list of things, instead of a single thing?
    We check for the `__iter__` attribute so that this can cover types that
    don't have to be known by this module, such as NumPy arrays.

    Strings, however, should be considered as atomic values to look up, not
    iterables. The same goes for tuples, since they are immutable and therefore
    valid entries.

    We don't need to check for the Python 2 `unicode` type, because it doesn't
    have an `__iter__` attribute anyway.
    """
    return hasattr(obj, '__iter__') and not isinstance(obj, str
        ) and not isinstance(obj, tuple)


def module_level_function(param1, param2=None, *args, **kwargs):
    """This is an example of a module level function.

    Function parameters should be documented in the ``Parameters`` section.
    The name of each parameter is required. The type and description of each
    parameter is optional, but should be included if not obvious.

    If ``*args`` or ``**kwargs`` are accepted,
    they should be listed as ``*args`` and ``**kwargs``.

    The format for a parameter is::

        name : type
            description

            The description may span multiple lines. Following lines
            should be indented to match the first line of the description.
            The ": type" is optional.

            Multiple paragraphs are supported in parameter
            descriptions.

    Parameters
    ----------
    param1 : int
        The first parameter.
    param2 : :obj:`str`, optional
        The second parameter.
    *args
        Variable length argument list.
    **kwargs
        Arbitrary keyword arguments.

    Returns
    -------
    bool
        True if successful, False otherwise.

        The return type is not optional. The ``Returns`` section may span
        multiple lines and paragraphs. Following lines should be indented to
        match the first line of the description.

        The ``Returns`` section supports any reStructuredText formatting,
        including literal blocks::

            {
                'param1': param1,
                'param2': param2
            }

    Raises
    ------
    AttributeError
        The ``Raises`` section is a list of all exceptions
        that are relevant to the interface.
    ValueError
        If `param2` is equal to `param1`.

    """
    if param1 == param2:
        raise ValueError('param1 may not be equal to param2')
    return True


def preview_toggle():
    """Toggle preview display for selected nodes

    """
    pass


def join(a, *p):
    """Taken from python posixpath."""
    sep = '/'
    path = a
    if not p:
        path[:0] + sep
    for b in p:
        if b.startswith(sep):
            path = b
        elif not path or path.endswith(sep):
            path += b
        else:
            path += sep + b
    return path


def cpdb_ui(cpe_config):
    """
    Starts the chessproblem basedata user interface.
    """
    from chessproblem.ui.database import MainFrame
    frame = MainFrame(cpe_config)
    frame.main()


def extract_archives(location, recurse=True):
    """
    Yield ExtractEvent while extracting archive(s) and compressed files at
    `location`. If `recurse` is True, extract nested archives-in-archives
    recursively.
    Archives and compressed files are extracted in a directory named
    "<file_name>-extract" created in the same directory as the archive.
    Note: this API is returning an iterable and NOT a sequence.
    """
    from extractcode.extract import extract
    from extractcode import default_kinds
    for xevent in extract(location, kinds=default_kinds, recurse=recurse):
        yield xevent


@classmethod
def parse_from_cmessage(cls, cmsg, **kwargs):
    """
        Parse a protobuf cmessage and create a class object.

        :param cmsg:    The probobuf cmessage object.
        :return:        A unserialized class object.
        :rtype:         cls
        """
    raise NotImplementedError()


def print_version(script_logger):
    """Simply prints version of rss_reader.py script."""
    script_logger.info('Check program version.....')
    version = 'rss_reader, version 2.0'
    return version


def extend_instance(obj, cls):
    """Apply mixins to a class instance after creation"""
    base_cls = obj.__class__
    base_cls_name = obj.__class__.__name__
    obj.__class__ = type(base_cls_name, (base_cls, cls), {})


def readBIM(fileName):
    """Reads a BIM file.

    :param fileName: the name of the BIM file to read.

    :type fileName: str

    :returns: the set of markers in the BIM file.

    Reads a Plink BIM file and extract the name of the markers. There is one
    marker per line, and the name of the marker is in the second column. There
    is no header in the BIM file.

    """
    snps = set()
    with open(fileName, 'r') as inputFile:
        for line in inputFile:
            row = line.rstrip('\r\n').split('\t')
            snpName = row[1]
            snps.add(snpName)
    return snps


def samplenamer(listofdata, indexposition=0):
    """Tries to replicate the Illumina rules to create file names from 'Sample_Name'
    :param listofdata: a list of data extracted from a file
    :param indexposition:
    """
    samplename = listofdata[indexposition].rstrip().replace(' ', '-').replace(
        '.', '-').replace('=', '-').replace('+', '').replace('/', '-').replace(
        '#', '').replace('---', '-').replace('--', '-')
    return samplename


def _get_package_status(package):
    """Get the status for a package."""
    status = package['status_str'] or 'Unknown'
    stage = package['stage_str'] or 'Unknown'
    if stage == 'Fully Synchronised':
        return status
    return '%(status)s / %(stage)s' % {'status': status, 'stage': stage}


def set_auto_predict(auto_predict_):
    """Sets whether the analysis routine automatically runs a predict on the
    *training* data whenever a fit is performed to score the machine on
    reproducing training data (useful for measuring over-fitting).

    Args:
        auto-predict_ (bool): when True, analysis *will* automatically perform a
          predict on `Xtrain` and `ytrain` to see how well it matches the training
          data.
    """
    global auto_predict
    auto_predict = auto_predict_


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


@staticmethod
def _make_second(sides, x):
    """
        Cyclically rotate sides = (a,b,c) so that x is the second entry"
        """
    i = (sides.index(x) + 2) % len(sides)
    return sides[i:] + sides[:i]


def is_packet_type(cls):
    """Check if class is one the packet types."""
    from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, EddystoneTLMFrame, EddystoneEIDFrame, IBeaconAdvertisement, EstimoteTelemetryFrameA, EstimoteTelemetryFrameB
    return cls in [EddystoneURLFrame, EddystoneUIDFrame,
        EddystoneEncryptedTLMFrame, EddystoneTLMFrame, EddystoneEIDFrame,
        IBeaconAdvertisement, EstimoteTelemetryFrameA, EstimoteTelemetryFrameB]


def add_object_align_init(context, operator):
    """
    Return a matrix using the operator settings and view context.

    :arg context: The context to use.
    :type context: :class:`bpy.types.Context`
    :arg operator: The operator, checked for location and rotation properties.
    :type operator: :class:`bpy.types.Operator`
    :return: the matrix from the context and settings.
    :rtype: :class:`mathutils.Matrix`
    """
    from mathutils import Matrix, Vector, Euler
    properties = operator.properties if operator is not None else None
    space_data = context.space_data
    if space_data and space_data.type != 'VIEW_3D':
        space_data = None
    if operator and properties.is_property_set('location'):
        location = Matrix.Translation(Vector(properties.location))
    else:
        if space_data:
            location = Matrix.Translation(space_data.cursor_location)
        else:
            location = Matrix.Translation(context.scene.cursor_location)
        if operator:
            properties.location = location.to_translation()
    view_align = context.user_preferences.edit.object_align == 'VIEW'
    view_align_force = False
    if operator:
        if properties.is_property_set('view_align'):
            view_align = view_align_force = operator.view_align
        elif properties.is_property_set('rotation'):
            value = properties.rotation[:]
            properties.view_align = view_align
            properties.rotation = value
            del value
        else:
            properties.view_align = view_align
    if operator and (properties.is_property_set('rotation') and not
        view_align_force):
        rotation = Euler(properties.rotation).to_matrix().to_4x4()
    else:
        if view_align and space_data:
            rotation = space_data.region_3d.view_matrix.to_3x3().inverted()
            rotation.resize_4x4()
        else:
            rotation = Matrix()
        if operator:
            properties.rotation = rotation.to_euler()
    return location * rotation


@classmethod
def from_json(cls, config):
    """ From configuration """
    return cls(**config)


def get_application_revision(applicationName=None, revision=None):
    """
    Gets information about an application revision.
    See also: AWS API Documentation

    :example: response = client.get_application_revision(
        applicationName='string',
        revision={
            'revisionType': 'S3'|'GitHub',
            's3Location': {
                'bucket': 'string',
                'key': 'string',
                'bundleType': 'tar'|'tgz'|'zip',
                'version': 'string',
                'eTag': 'string'
            },
            'gitHubLocation': {
                'repository': 'string',
                'commitId': 'string'
            }
        }
    )

    :type applicationName: string
    :param applicationName: [REQUIRED]
            The name of the application that corresponds to the revision.

    :type revision: dict
    :param revision: [REQUIRED]
            Information about the application revision to get, including type and location.
            revisionType (string) --The type of application revision:
            S3: An application revision stored in Amazon S3.
            GitHub: An application revision stored in GitHub.
            s3Location (dict) --Information about the location of application artifacts stored in Amazon S3.
            bucket (string) --The name of the Amazon S3 bucket where the application revision is stored.
            key (string) --The name of the Amazon S3 object that represents the bundled artifacts for the application revision.
            bundleType (string) --The file type of the application revision. Must be one of the following:
            tar: A tar archive file.
            tgz: A compressed tar archive file.
            zip: A zip archive file.
            version (string) --A specific version of the Amazon S3 object that represents the bundled artifacts for the application revision.
            If the version is not specified, the system will use the most recent version by default.
            eTag (string) --The ETag of the Amazon S3 object that represents the bundled artifacts for the application revision.
            If the ETag is not specified as an input parameter, ETag validation of the object will be skipped.
            gitHubLocation (dict) --Information about the location of application artifacts stored in GitHub.
            repository (string) --The GitHub account and repository pair that stores a reference to the commit that represents the bundled artifacts for the application revision.
            Specified as account/repository.
            commitId (string) --The SHA1 commit ID of the GitHub commit that represents the bundled artifacts for the application revision.

    :rtype: dict
    :return: {
        'applicationName': 'string',
        'revision': {
            'revisionType': 'S3'|'GitHub',
            's3Location': {
                'bucket': 'string',
                'key': 'string',
                'bundleType': 'tar'|'tgz'|'zip',
                'version': 'string',
                'eTag': 'string'
            },
            'gitHubLocation': {
                'repository': 'string',
                'commitId': 'string'
            }
        },
        'revisionInfo': {
            'description': 'string',
            'deploymentGroups': [
                'string',
            ],
            'firstUsedTime': datetime(2015, 1, 1),
            'lastUsedTime': datetime(2015, 1, 1),
            'registerTime': datetime(2015, 1, 1)
        }
    }

    :returns:
    S3: An application revision stored in Amazon S3.
    GitHub: An application revision stored in GitHub.

    """
    pass


def _make_3d(field, twod):
    """Add a dimension to field if necessary.

    Args:
        field (numpy.array): the field that need to be 3d.
        twod (str): 'XZ', 'YZ' or None depending on what is relevant.
    Returns:
        numpy.array: reshaped field.
    """
    shp = list(field.shape)
    if twod and 'X' in twod:
        shp.insert(1, 1)
    elif twod:
        shp.insert(0, 1)
    return field.reshape(shp)


def no_value_for_parameter(editor, item):
    """ Pylint method to fix no_value_for_parameter error """
    line_no = item.line_no
    return line_no, 0


@classmethod
def can_edit(cls, editor_type_name):
    """
        Must be implemented to return True if the given editor_type_name
        matches this editor.
        """
    raise NotImplementedError()


def nodeSet(node):
    """Return a nodeset containing a single node"""
    return [node]


def del_columns(df, columns):
    """
    从df中删除参数columns指定的整列数据
    :param df: 金融时间序列切割pd.DataFrame对象
    :param columns: 可迭代的字符序列，代表需要删除的指定列
    :return:
    """
    old_c = df.columns.tolist()
    for col in filter(lambda x: x in old_c, columns):
        df.drop(col, axis=1, inplace=True)


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

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


def check_param_type(p, t, ignore_none=False, param_name=''):
    """Checks if the informed param is the correct type."""
    if ignore_none and p is None:
        return
    if not isinstance(p, t):
        raise ValueError("Param. '{}' must be a '{}'".format(param_name, t))


@classmethod
def activate(cls, keymap=None, listen_events=None, run_thread=False):
    """Alternative constructor.

        Performs keys binding and runs a listener thread.

        :param dict keymap: Key name to function mapping.

        :param int listen_events: X Events or a combination of them.

        :param bool run_thread: Run a key listening loop in a thread.

        :rtype: KeyBinder

        """
    binder = cls(keymap=keymap, listen_events=listen_events)
    if keymap:
        binder.register_keys()
    else:
        binder.sniff()
    if run_thread:
        binder.run_thread()
    else:
        binder.listen()
    return binder


def _csr_gen_triples(A):
    """Converts a SciPy sparse matrix in **Compressed Sparse Row** format to
    an iterable of weighted edge triples.

    """
    nrows = A.shape[0]
    data, indices, indptr = A.data, A.indices, A.indptr
    for i in range(nrows):
        for j in range(indptr[i], indptr[i + 1]):
            yield i, indices[j], data[j]


def unique(df, columns=None):
    """
    Asserts that columns in the DataFrame only have unique values.

    Parameters
    ----------
    df : DataFrame
    columns : list or None
      list of columns to restrict the check to. If None, check all columns.

    Returns
    -------
    df : DataFrame
      same as the original
    """
    if columns is None:
        columns = df.columns
    for col in columns:
        if not df[col].is_unique:
            raise AssertionError('Column {!r} contains non-unique values'.
                format(col))
    return df


def file_as_blockiter(file, block_size=65536):
    """
    Treat a file handler as block generator of bytes
    :param typing.FileIO[bytes] file: The file object
    :param int block_size: The size of each block
    :return: A generator that can be used to iterate block chunks
    """
    block = file.read(block_size)
    while len(block) > 0:
        yield block
        block = file.read(block_size)


@staticmethod
def default_deal_fun_string_content(formular_obj, **kwargs):
    """
        默认公式计算函数-标签内容转为字符串
        将标签内容的字符串作为设置值

        @param {StructFormula} formular_obj - 要计算的公式

        """
    formular_obj.formula_value = formular_obj.content_string


def aps04_f(x, n, a):
    """Medium-degree polynomial"""
    return x ** n - a


@staticmethod
def write(automaton_in, filename, format='json'):
    """ write input automaton into a file with the given format.

        - Input:

        :param Automaton automaton_in: automaton to write into the file
        :param str filename: the name of the file. If it does not exist,
         the file is created.
        :param str format: 'json' or yaml'
        """
    from splearn.serializer import Serializer
    if format == 'json':
        data_str = Serializer.data_to_json(automaton_in)
    elif format == 'yaml':
        data_str = Serializer.data_to_yaml(automaton_in)
    else:
        raise ValueError('Invalid input format. Should be "json" or "yaml"')
    with open(filename, 'w') as outfile:
        outfile.write(data_str)


def is_float(x):
    """
    Given a string value, determine if it is a floating-point number.

    :param x: a string value to check if it is a floating-point number
    :type x: str
    :return: whether the specified value is a floating-point number
        or not
    :rtype: bool
    """
    try:
        float(x)
    except ValueError:
        return False
    return True


def _format_eval_result(value, show_stdv=True):
    """Format metric string."""
    if len(value) == 4:
        return "%s's %s: %g" % (value[0], value[1], value[2])
    elif len(value) == 5:
        if show_stdv:
            return "%s's %s: %g + %g" % (value[0], value[1], value[2], value[4]
                )
        else:
            return "%s's %s: %g" % (value[0], value[1], value[2])
    else:
        raise ValueError('Wrong metric value')


@classmethod
def get_route_prefix(cls):
    """
        Returns a prefix which (by default) applies to all routes provided by
        the master view class.  This is the plural, lower-cased name of the
        model class by default, e.g. 'products'.
        """
    model_name = cls.get_normalized_model_name()
    return getattr(cls, 'route_prefix', '{0}s'.format(model_name))


def getVisibleSections(request):
    """Get list of sections visible from given request"""


def dump_source_and_screen(driver, path_prefix=''):
    """Dumps a screenshot and page source"""
    driver.save_screenshot('{}screenshot.png'.format(path_prefix))
    html = driver.page_source
    with open('{}source.html'.format(path_prefix), 'wb') as fp:
        fp.write(html)


def dopesheet_view_all():
    """Reset viewable area to show full keyframe range

    """
    pass


def _parse_squad_name(team_id):
    """
    Parse and clean the team's name.

    To try and match requested team names with the master squad ID list, passed
    names should be parsed to remove the common 'FC' and 'CF' tags, as well as
    force all strings to be lowercase and excess whitespace removed.

    Parameters
    ----------
    team_id : string
        The requested team's name to be parsed.

    Returns
    -------
    string
        Returns a ``string`` of the parsed team's name.
    """
    name = team_id.replace(' FC', '')
    name = name.replace('FC ', '')
    name = name.replace(' CF', '')
    name = name.replace('CF ', '')
    name = name.lower()
    name = name.strip()
    return name


def incrDictEntry(d, k, v):
    """
    If dictionary ``d`` has key ``k``, then increment ``d[k]`` by ``v``.
    Else set ``d[k] = v``.

    :param d: dictionary
    :param k: legal dictionary key (doesn't have to be in ``d``)
    :param v: numeric value
    """
    if k in d:
        d[k] += v
    else:
        d[k] = v


def tuple2cknv(ckpt):
    """
        ckpt = ("TS","0105b666")
        ckname,ckvalue = tuple2cknv(ckpt)
        ckname
        ckvalue
    """
    return ckpt


def to_x_value(pixel, axis, layout):
    """ Given a pixel, determine its domain value. """
    domain = axis.domain
    a = domain / layout.chart_width
    value = axis.minimum + a * (pixel - layout.chart_left)
    return value


def time_avt(acceleration, delta_velocity):
    """Usage: time_avt(acceleration of object, change in speed)"""
    return delta_velocity / acceleration


def delete(use_global: bool=False, confirm: bool=True):
    """Delete selected objects

    :param use_global: Delete Globally, Remove object from all scenes
    :type use_global: bool
    :param confirm: Confirm, Prompt for confirmation
    :type confirm: bool
    """
    pass


def get_connect_kwargs(config):
    """Returns a dict of arguments from config accepted by pymssql.connect."""
    keys = ['timeout', 'login_timeout', 'charset', 'host', 'appname',
        'port', 'conn_properties', 'autocommit', 'tds_version']
    kwargs = {}
    for k in keys:
        try:
            kwargs[k] = getattr(config, k)
        except AttributeError:
            pass
    return kwargs


@classmethod
def addPKCS1SHA1Prefix(cls, hashBytes, withNULL=True):
    """Add PKCS#1 v1.5 algorithm identifier prefix to SHA1 hash bytes"""
    if not withNULL:
        prefixBytes = bytearray([48, 31, 48, 7, 6, 5, 43, 14, 3, 2, 26, 4, 20])
    else:
        prefixBytes = cls._pkcs1Prefixes['sha1']
    prefixedBytes = prefixBytes + hashBytes
    return prefixedBytes


def escape_cdata(data, encoding):
    """Escape character data using the given encoding."""
    if '&' in data:
        data = data.replace('&', '&')
    if '<' in data:
        data = data.replace('<', '<')
    if '>' in data:
        data = data.replace('>', '>')
    return data.encode(encoding, 'xmlcharrefreplace')


def _ignore_role(name, rawtext, text, lineno, inliner, options=None,
    content=None):
    """Stub for unknown roles."""
    return [], []


@classmethod
def from_overlaps(cls, overlaps):
    """Creates a :class:`WccLineData` object from a list containing the overlap matrices :math:`M_{m,n}^{\\mathbf{k}, \\mathbf{k+b}} = \\langle u_n^\\mathbf{k} | u_m^\\mathbf{k+b} \\rangle`."""
    return cls(cls._calculate_wannier(cls._wilson(overlaps))[0])


def calc_demagspatial(fcol, fcam):
    """Calculate the spatial demagnification

           returns the spatial demagnification
    """
    return fcol / fcam


def p_simple_stmt_2(p):
    """simple_stmt : small_stmt SEMI NEWLINE"""
    p[0] = [p[1]]


def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
    """Truncates a pair of sequences to a maximum sequence length."""
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_num_tokens:
            break
        trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
        assert len(trunc_tokens) >= 1
        if rng.random() < 0.5:
            del trunc_tokens[0]
        else:
            trunc_tokens.pop()


def _getitem_from_frame(f_locals, key, default=None):
    """
    f_locals is not guaranteed to have .get(), but it will always
    support __getitem__. Even if it doesnt, we return ``default``.
    """
    try:
        return f_locals[key]
    except Exception:
        return default


def CvMstat(data, model):
    """
	Cramér–von Mises statistic: Takes all deviances into account
	"""
    modelc = model.cumsum()
    datac = data.cumsum()
    maxmodelc = modelc.max()
    cvm = ((modelc / maxmodelc - datac / datac.max()) ** 2 * model / maxmodelc
        ).mean()
    return cvm


def pad(value: int, length: int=2) ->str:
    """
    Adds leading and trailing zeros to value ("pads" the value).

    >>> pad(5)
    05
    >>> pad(9, 3)
    009

    :param value: integer value to pad
    :param length: Length to pad to
    :return: string of padded value"""
    return '{0:0>{width}}'.format(value, width=length)


def is_key(sarg):
    """Check if `sarg` is a key (eg. -foo, --foo) or a negative number (eg. -33).
    """
    if not sarg.startswith('-'):
        return False
    if sarg.startswith('--'):
        return True
    return not sarg.lstrip('-').isnumeric()


def put_block(segmentnum, data):
    """
        @param segmentnum=int
        @param data=ShareData: For most segments, this data will be 'blocksize'
        bytes in length. The last segment might be shorter.
        @return: a Deferred that fires (with None) when the operation completes
        """


@classmethod
def to_int(cls, val):
    """make int from any value, nice error message if not possible"""
    try:
        return int(val, 0)
    except (TypeError, ValueError):
        raise ValueError('invalid integer')


def delete_bucket_policy(Bucket=None):
    """
    Deletes the policy from the bucket.
    See also: AWS API Documentation

    :example: response = client.delete_bucket_policy(
        Bucket='string'
    )

    :type Bucket: string
    :param Bucket: [REQUIRED]

    """
    pass


def get_document(DocumentId=None):
    """
    Retrieves the specified document object.
    See also: AWS API Documentation

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

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

    :rtype: dict
    :return: {
        'Metadata': {
            'Id': 'string',
            'CreatorId': 'string',
            'ParentFolderId': 'string',
            'CreatedTimestamp': datetime(2015, 1, 1),
            'ModifiedTimestamp': datetime(2015, 1, 1),
            'LatestVersionMetadata': {
                'Id': 'string',
                'Name': 'string',
                'ContentType': 'string',
                'Size': 123,
                'Signature': 'string',
                'Status': 'INITIALIZED'|'ACTIVE',
                'CreatedTimestamp': datetime(2015, 1, 1),
                'ModifiedTimestamp': datetime(2015, 1, 1),
                'ContentCreatedTimestamp': datetime(2015, 1, 1),
                'ContentModifiedTimestamp': datetime(2015, 1, 1),
                'CreatorId': 'string',
                'Thumbnail': {
                    'string': 'string'
                },
                'Source': {
                    'string': 'string'
                }
            },
            'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED'
        }
    }

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

    """
    pass


def evalcontextfilter(f):
    """Decorator for marking eval-context dependent filters.  An eval
    context object is passed as first argument.  For more information
    about the eval context, see :ref:`eval-context`.

    .. versionadded:: 2.4
    """
    f.evalcontextfilter = True
    return f


def encloses(a, b):
    """Returns True if `a` is within `b`, including when `a==b`.

        """
    return a.start <= b.start <= a.end and a.start <= b.end <= a.end


def unique(l):
    """Filters duplicates of iterable.

    Create a new list from l with duplicate entries removed,
    while preserving the original order.

    Parameters
    ----------
    l : iterable
        Input iterable to filter of duplicates.

    Returns
    -------
    list
        A list of elements of `l` without duplicates and in the same order.
    """
    new_list = []
    seen = set()
    for el in l:
        if el not in seen:
            new_list.append(el)
            seen.add(el)
    return new_list


def euclidean(feat, query, featl2norm=None, qryl2norm=None):
    """ Euclidean distance.
    Args:
        feat:       N x D feature matrix
        query:      Q x D feature vector
        featl2norm: 1 x N vector
        qryl2norm:  Q x 1 vector

    Returns:
        dist:       1 x N vector
    """
    dotprod = query.dot(feat.T)
    if qryl2norm is None:
        qryl2norm = (query ** 2).sum(1).reshape(-1, 1)
    if featl2norm is None:
        featl2norm = (feat ** 2).sum(1).reshape(1, -1)
    return -2 * dotprod + qryl2norm + featl2norm


def python_3000_not_equal(logical_line):
    """New code should always use != instead of <>.

    The older syntax is removed in Python 3.

    Okay: if a != 'no':
    W603: if a <> 'no':
    """
    pos = logical_line.find('<>')
    if pos > -1:
        yield pos, "W603 '<>' is deprecated, use '!='"


def _get_first_child_text(base, tag):
    """Get a child element of the base node with a given tag.

    Args:
        base: The base node element. (lxml node)
        tag: Child elements group tag used to select the elements. (string)

    Returns:
        The text of first child node element found or an empty string.
    """
    for node in base:
        if node.tag.replace('{http://www.rdml.org}', '') == tag:
            return node.text
    return ''


def is_true(argument):
    """Return True if argument is the word "true" case insensitive.

    :param str argument: Argument/value passed to directive's option.

    :return: Is argument true/True/TRUE.
    :rtype: bool
    """
    return argument.lower() == 'true'


def get(isamAppliance, check_mode=False, force=False):
    """
    Retrieve MMFA endpoint details
    """
    return isamAppliance.invoke_get('Retrieve MMFA endpoint details',
        '/iam/access/v8/mmfa-config')


@staticmethod
def run_cached(obj, algorithm, params):
    """
        Gets data from the cache if valid
        :param params:
        :param obj:
        :type algorithm: Algorithm
        :return: The data or None
        """
    key = algorithm.cache_key(params)
    if key not in obj._cache:
        algorithm.set_logger()
        val = algorithm.algorithm(obj, params)
        log = algorithm.unset_logger()
        obj._cache[key] = val, log
    else:
        val, log = obj._cache[key]
        algorithm.emulate_log(log)
    return val


def pixel_size(geo_trans):
    """Return pixel sizes

    :param geo_trans: geo transformation
    :type geo_trans: tuple with six values
    :return: pixel sizes (x, y): (column width, row height)
    :rtype: tuple
    """
    return geo_trans[1], -geo_trans[5]


def extract_metadata_value(metadata_value):
    """Converts a lxml.objectify.ObjectifiedElement metadata value to a string.

    The textual representation of the metadata value is extracted out of the
    metadata value object.

    :param lxml.objectify.ObjectifiedElement metadata_value: an object
        containing EntityType.METADATA_VALUE XML data.

    :return: string representation of the metadata value

    :rtype: str
    """
    return metadata_value.TypedValue.Value.text


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

        :param SharedLinkSettingsChangePasswordType val:
        :rtype: EventType
        """
    return cls('shared_link_settings_change_password', val)


def _get_float(src_proto, dst_dict, attr_name):
    """ Getter for a float """
    dst_dict[attr_name] = float(getattr(src_proto, attr_name))


def _kamb_radius(n, sigma):
    """Radius of kernel for Kamb-style smoothing."""
    a = sigma ** 2 / (float(n) + sigma ** 2)
    return 1 - a


def product(v1, v2):
    """
    Calculate the scalar product of two vectors
    """
    return v1[0] * v2[0] + v1[1] * v2[1]


def Scheme(endpoint):
    """Returns https scheme for all the endpoints except localhost."""
    if endpoint.startswith('localhost:'):
        return 'http'
    else:
        return 'https'


@classmethod
def from_code(cls, environment, code, globals, uptodate=None):
    """Creates a template object from compiled code and the globals.  This
        is used by the loaders and environment to create a template object.
        """
    namespace = {'environment': environment, '__file__': code.co_filename}
    exec(code, namespace)
    rv = cls._from_namespace(environment, namespace, globals)
    rv._uptodate = uptodate
    return rv


def cast(df, column: str, type: str, new_column=None):
    """
    Convert column's type into type

    ---

    ### Parameters

    *mandatory :*
    - `column` (*str*): name of the column to convert
    - `type` (*str*): output type. It can be :
        - `"int"` : integer type
        - `"float"` : general number type
        - `"str"` : text type

    *optional :*
    - `new_column` (*str*): name of the output column.
       By default the `column` arguments is modified.

    ---

    ### Example

    **Input**

    | Column 1 |  Column 2   |  Column 3  |
    |:-------:|:--------:|:--------:|
    |  'one'  |  '2014'  |   30.0   |
    |  'two'  |  2015.0  |    '1'   |
    |   3.1   |   2016   |    450   |

    ```cson
    postprocess: [
      cast:
        column: 'Column 1'
        type: 'str'
      cast:
        column: 'Column 2'
        type: 'int'
      cast:
        column: 'Column 3'
        type: 'float'
    ]
    ```

    **Output**

    | Column 1 |  Column 2  |  Column 3  |
    |:-------:|:------:|:--------:|
    |  'one'  |  2014  |   30.0   |
    |  'two'  |  2015  |    1.0   |
    |  '3.1'  |  2016  |  450.0   |
    """
    new_column = new_column or column
    df[new_column] = df[column].astype(type)
    return df


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


@classmethod
def as_dict_static(cls, state_obj):
    """Method to return a dict representation of the object. Necessary for storing.
        This method returns a dictionary *without any attribute that requires joined data*.
        As a static method, it is useful to be used outside of the class.
        :param state_obj: an instance of the HSP class or a
        collections.namedtuple object from a direct query

        :rtype : dict
        """
    keys = ['query_hsp_start', 'query_hsp_end', 'target_hsp_start',
        'target_hsp_end', 'hsp_evalue', 'hsp_bits', 'match', 'query_frame',
        'target_frame']
    state = dict().fromkeys(keys)
    for key in keys:
        state[key] = getattr(state_obj, key)
    return state


def p_all(p):
    """
    arguments : pos_arguments kw_arguments
    kw_argument : KEYWORD pos_arguments
    parameter_types : pos_parameter_types kw_parameter_types
    """
    p[0] = tuple(p[1:])


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

        :param CreateFolderEntryResult val:
        :rtype: CreateFolderBatchResultEntry
        """
    return cls('success', val)


@staticmethod
def get_connection_id(address):
    """Generates connection ids used for internal indexing.

        :param address: The IP address for the affected remote.
        :type address: string
        """
    return '%s' % address


def unicode_is_ascii(u_string):
    """Determine if unicode string only contains ASCII characters.

    :param str u_string: unicode string to check. Must be unicode
        and not Python 2 `str`.
    :rtype: bool
    """
    assert isinstance(u_string, str)
    try:
        u_string.encode('ascii')
        return True
    except UnicodeEncodeError:
        return False


def all_class_properties(cls):
    """Find all properties of the class, including those inherited"""
    found_names = set()
    for base in cls.__mro__:
        for k, v in base.__dict__.iteritems():
            if k in found_names:
                continue
            yield k, v
            found_names.add(k)


def from_dict(cls, settings, molecule, job_name, archive, status, warnings):
    """
        Methods to deserialize an `Result`` object.
        """
    raise NotImplementedError()


def remove_blank_line(oFile, iLineNumber):
    """
    Removes a line if it is blank.

    Parameters:

      oFile: (vhdlFile object)

      iLineNumber: (integer)
    """
    if oFile.lines[iLineNumber].isBlank:
        oFile.lines.pop(iLineNumber)


def get_example_configuration():
    """an example configuration"""
    example = """---
CFG:
    BUBBLE:
        DEBUG: True
        VERBOSE: True
        STORAGE_TYPE: json
    DEV:
        SOURCE:    #pull
            CLIENT: ./mysrcclient.py
        TRANSFORM:
            RULES: config/rules.bubble
        TARGET:    #push
            CLIENT: ./mytgtclient.py
...
#please see bubble/docs/configuration
"""
    return example


def plot_dlc01_powercurve(sim_ids, post_dirs, run_dirs, fig_dir_base):
    """
    Create power curve based on steady DLC01 results
    Use the same format as for HS2 for easy comparison!
    """


def fields_in_query(query):
    """
        >>> fields_in_query('a=1&b=2')
        {'a': '1', 'b': '2'}

        >>> fields_in_query('')
        {}

        >>> fields_in_query('?')
        {}

    """
    ret = {}
    if query and query[0] == '?':
        query = query[1:]
    if not query:
        return ret
    for seg in query.split('&'):
        k, v = seg.split('=', 1)
        ret[k] = v
    return ret


def del_cookie(response, value):
    """
    Funkcja usuwa ciasteczko.
    """
    response.set_cookie(value, '', expires=0)


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 calc_checksum(data):
    """
    Calculate data checksum
    """
    checksum = 0
    for byte in data:
        checksum += ord(byte)
    return checksum % 239 + 1


def _deprecated(msg, version='2.8'):
    """ display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write """
    try:
        from ansible.utils.display import Display
        Display().deprecated(msg, version=version)
    except Exception:
        import sys
        sys.stderr.write(' [DEPRECATED] %s, to be removed in %s\n' % (msg,
            version))


@classmethod
def get_allowance_for_user(cls, exam_id, user_id, key):
    """
        Returns an allowance for a user within a given exam
        """
    try:
        student_allowance = cls.objects.get(proctored_exam_id=exam_id,
            user_id=user_id, key=key)
    except cls.DoesNotExist:
        student_allowance = None
    return student_allowance


def xor_cipher_genkey(key, length=None):
    """Generates a byte array for use in XOR cipher encrypt and decrypt
    routines. In Python 2 either a byte string or Unicode string can be
    provided for the key. In Python 3, it must be a Unicode string. In
    either case, characters in the string must be within the ASCII
    character range.

    """
    return bytearray(key[:length], encoding='ascii')


def p_subscriptlist_star_2(p):
    """subscriptlist_star : subscriptlist_star COMMA subscript"""
    p[0] = p[1] + [p[3]]


def _fill(inst_class, frequencies):
    """This function initializes the frequencies dict with null values. If this
    is not done, it won't be possible to catch missing elements when validating
    the incoming document.
    """
    ctype_info = inst_class.get_flat_type_info(inst_class)
    cfreq_key = inst_class, 0
    for k, v in ctype_info.items():
        if v.Attributes.min_occurs > 0:
            frequencies[cfreq_key][k] = 0


def define(hub):
    """
    Define how the onchanges requisite should run
    """
    return {'result': True, 'changes': True}


def colourBarMinorAxisSize(fontSize):
    """Calculates a good size for the minor axis of a colour bar.

    The minor axis is the axis perpendicular to the colour bar axis.

    :arg fontSize: Font size of colour bar labels, in points.
    """
    fontSize = fontSize
    fontSize = 6 + 96 * fontSize / 72.0
    return round(2 * fontSize + 40)


def is_system_path(path):
    """Returns True if path is a system path"""
    return '\\' in path or '/' in path


@classmethod
def create_criteria(cls, query):
    """Return a criteria from a dictionary containing a query.

        Query should be a dictionary, keyed by field name. If the value is
        a list, it will be divided into multiple criteria as required.
        """
    criteria = []
    for name, value in query.items():
        if isinstance(value, list):
            for inner_value in value:
                criteria += cls.create_criteria({name: inner_value})
        else:
            criteria.append({'criteria': {'field': name, 'value': value}})
    return criteria or None


def _shell_escape(string):
    """
    Escape double quotes, backticks and dollar signs in given ``string``.

    For example::

        >>> _shell_escape('abc$')
        'abc\\\\$'
        >>> _shell_escape('"')
        '\\\\"'
    """
    for char in ('"', '$', '`'):
        string = string.replace(char, '\\%s' % char)
    return string


@classmethod
def untranslate_store(cls, store, language, fuzzy=False):
    """Remove translations from Translate Toolkit store."""
    store.settargetlanguage(cls.get_language_code(language.code))
    plural = language.plural
    for unit in store.units:
        if unit.istranslatable():
            if hasattr(unit, 'markapproved'):
                unit.markapproved(False)
            else:
                unit.markfuzzy(fuzzy)
            if unit.hasplural():
                unit.target = [''] * plural.number
            else:
                unit.target = ''


def timer(time):
    """
    A timer function.
    - input:
        - time of counting down
    """
    timer = int(timer)
    for i in range(timer):
        print(timer)
        time.sleep(1)
        timer -= 1


def column_strings(df, string):
    """remove strings from columns"""
    if len(df) > 1:
        for each in list(df.columns):
            df[each] = df[each].str.strip(string)
    return df


@classmethod
def is_bool(cls, my_bool):
    """
        Return true if the provided my_bool is a boolean.
        :param cls: Our class.
        :param my_bool: A boolean..
        :return: Return true if the provided my_bool is a boolean. False otherwise.
        """
    if my_bool is None:
        return False
    else:
        return isinstance(my_bool, bool)


@classmethod
def dual(cls, auxVarPrimals, auxConDuals, options):
    """Convert back the dual value of a constraint that was converted.

        Given a mapping of auxilary variable names (as named in :meth:`convert`)
        to primals and a list of auxilary constraint duals (in the order as the
        constraints were added in :meth:`convert`), returns a dual value for the
        converted constraint.

        :raises NotImplementedError: When dual format not decided upon or not
            known. This will be caught by the reformulation's backward method.
        """
    raise NotImplementedError(
        '{} does not describe how to convert back the dual.'.format(cls.
        __qualname__ if hasattr(cls, '__qualname__') else cls.__name__))


def _read_pid_file(filename):
    """
    Reads a pid file and returns the contents. PID files have 1 or 2 lines;
     - first line is always the pid
     - optional second line is the port the server is listening on.

    :param filename: Path of PID to read
    :return: (pid, port): with the PID in the file and the port number
                          if it exists. If the port number doesn't exist, then
                          port is None.
    """
    pid_file_lines = open(filename, 'r').readlines()
    if len(pid_file_lines) == 2:
        pid, port = pid_file_lines
        pid, port = int(pid), int(port)
    elif len(pid_file_lines) == 1:
        pid, port = int(pid_file_lines[0]), None
    else:
        raise ValueError('PID file must have 1 or two lines')
    return pid, port


def true_if_all_true_filter(*value):
    """
    Returns true if all values have a 'true-ish' value.

    Args:
        *value: list of values

    Returns: 'true' if all values have a 'true-ish' value
    """
    for v in value:
        if not v:
            return False
    return True


def afterCompletion(transaction):
    """Hook that is called by the transaction after completing a commit.
        """


def read_data():
    """ Read informations of the scale, returning an object
        that implements IScaleInfo interface.
        """


@staticmethod
def orientation(p, q, r):
    """Determine the clockwise, linear, or counterclockwise orientation of the given points"""
    val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
    if val == 0:
        return 0
    elif val > 0:
        return 1
    else:
        return 2


def decode_response(enc_response, task):
    """ Decodes an encoded syllogistic response by transforming it to the
    corresponding tuple representation and inserting the appropriate terms.

    Parameters
    ----------
    enc_response : str
        Encoded syllogistic response (e.g., 'Aac').

    task : list(str)
        Syllogistic task in the tuple list representation (e.g.,
        [['Some', 'models', 'managers'], ['All', 'models', 'clerks']]).

    Returns
    -------
    list
        List representation of the response to decode.

    """
    if enc_response == 'NVC':
        return [['NVC']]
    if enc_response == ['NVC']:
        return [enc_response]
    if enc_response == [['NVC']]:
        return enc_response
    obj_a = set(task[0][1:]) - set(task[1][1:])
    obj_c = set(task[1][1:]) - set(task[0][1:])
    quant = enc_response[0].replace('A', 'All').replace('I', 'Some').replace(
        'O', 'Some not').replace('E', 'No')
    if enc_response[1:] == 'ac':
        return [[quant, list(obj_a)[0], list(obj_c)[0]]]
    return [[quant, list(obj_c)[0], list(obj_a)[0]]]


@staticmethod
def _get_parent_class():
    """
        Gets the class of the parent object

        :returns: class of parent object
        """
    return None


def build_authenticate_header(realm=''):
    """Optional WWW-Authenticate header (401 error)"""
    return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}


@classmethod
def can_read(cls, filepath):
    """
        Checks whether this plugin is capable of operating
        on the given file

        :param filepath: Absolute path to the file to test
        :type filepath: str

        :return: True if the plugin can operate on the file
        :rtype: bool
        """
    return False


def update_animated_transform_constraints(use_convert_to_radians: bool=True):
    """Update fcurves/drivers affecting Transform constraints (use it with files from 2.70 and earlier)

    :param use_convert_to_radians: Convert To Radians, Convert fcurves/drivers affecting rotations to radians (Warning: use this only once!)
    :type use_convert_to_radians: bool
    """
    pass


def hide_fields_in_newer_versions(obj):
    """This method hides fields that were added in newer API versions.

    Certain node fields were introduced at certain API versions.
    These fields are only made available when the request's API version
    matches or exceeds the versions when these fields were introduced.
    """
    pass


def describe_addresses(DryRun=None, PublicIps=None, Filters=None,
    AllocationIds=None):
    """
    Describes one or more of your Elastic IP addresses.
    An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see Elastic IP Addresses in the Amazon Elastic Compute Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example describes your Elastic IP addresses.
    Expected Output:
    This example describes your Elastic IP addresses for use with instances in a VPC.
    Expected Output:
    This example describes your Elastic IP addresses for use with instances in EC2-Classic.
    Expected Output:

    :example: response = client.describe_addresses(
        DryRun=True|False,
        PublicIps=[
            'string',
        ],
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        AllocationIds=[
            'string',
        ]
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type PublicIps: list
    :param PublicIps: [EC2-Classic] One or more Elastic IP addresses.
            Default: Describes all your Elastic IP addresses.
            (string) --

    :type Filters: list
    :param Filters: One or more filters. Filter names and values are case-sensitive.
            allocation-id - [EC2-VPC] The allocation ID for the address.
            association-id - [EC2-VPC] The association ID for the address.
            domain - Indicates whether the address is for use in EC2-Classic (standard ) or in a VPC (vpc ).
            instance-id - The ID of the instance the address is associated with, if any.
            network-interface-id - [EC2-VPC] The ID of the network interface that the address is associated with, if any.
            network-interface-owner-id - The AWS account ID of the owner.
            private-ip-address - [EC2-VPC] The private IP address associated with the Elastic IP address.
            public-ip - The Elastic IP address.
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :type AllocationIds: list
    :param AllocationIds: [EC2-VPC] One or more allocation IDs.
            Default: Describes all your Elastic IP addresses.
            (string) --

    :rtype: dict
    :return: {
        'Addresses': [
            {
                'InstanceId': 'string',
                'PublicIp': 'string',
                'AllocationId': 'string',
                'AssociationId': 'string',
                'Domain': 'vpc'|'standard',
                'NetworkInterfaceId': 'string',
                'NetworkInterfaceOwnerId': 'string',
                'PrivateIpAddress': 'string'
            },
        ]
    }

    """
    pass


@staticmethod
def get_dialogflow_slot_value(data, slot=None):
    """Gets slots' values from the interaction model.

        Args:
            data: Response received from Google Home.
            slot (str): Name of the slot. If a name is not specified, all slots will be returned
                as a dictionary. If a name is specified but is not found, ``None`` will be returned.

        Returns:
            A string representing the value of the slot from the interaction model, or a hash of slots.

        Examples:
            >>> beer_type = ADAPI.get_dialogflow_intent(data, "beer_type")
            >>> all_slots = ADAPI.get_dialogflow_intent(data)

        """
    if 'result' in data:
        contexts = data['result']['contexts'][0]
        if contexts:
            parameters = contexts.get('parameters')
        else:
            parameters = data['result']['parameters']
        if slot is None:
            return parameters
        elif slot in parameters:
            return parameters[slot]
        else:
            return None
    elif 'queryResult' in data:
        contexts = data['queryResult']['outputContexts'][0]
        if contexts:
            parameters = contexts.get('parameters')
        else:
            parameters = data['queryResult']['parameters']
        if slot is None:
            return parameters
        elif slot in parameters:
            return parameters[slot]
        else:
            return None
    else:
        return None


def eval_continuation(line, open_par_nb):
    """
    Returns information whether the line continues
    """
    for char in line:
        if char == '(':
            open_par_nb += 1
        if char == ')':
            assert open_par_nb >= 1
            open_par_nb -= 1
    return open_par_nb, line.endswith('\\\n')


@classmethod
def get(cls, name, digits=None):
    """
        returns the time of the timer.

        :param name: the name of the timer
        :type name: string
        :rtype: the elapsed time
        """
    if name in cls.timer_end:
        try:
            diff = cls.timer_end[name] - cls.timer_start[name]
            if round is not None:
                cls.timer_elapsed[name] = round(diff, digits)
            else:
                cls.timer_elapsed[name] = diff
            return cls.timer_elapsed[name]
        except:
            return None
    else:
        return 'undefined'


def get_MLUm(tagged_sents, pos_to_ignore=None):
    """Mean length of utterance (MLU) in morphemes"""
    total_utterance_count = 0
    total_morpheme_count = 0
    for tagged_sent in tagged_sents:
        total_utterance_count += 1
        for tagged_word in tagged_sent:
            pos = tagged_word[1]
            morph = tagged_word[2]
            if pos_to_ignore and pos in pos_to_ignore:
                continue
            total_morpheme_count += 1
            total_morpheme_count += morph.count('-')
            total_morpheme_count += morph.count('~')
    if total_utterance_count:
        return total_morpheme_count / total_utterance_count
    else:
        return 0


def cut_to_pages(h, pgsz):
    """Cut each data block to pages.

    Args:
        h (list): response from `asaloader.ihex.padding_space`.
        pgsz (int): page size, e.g. 256, 512.

    Returns:
        list: data pages
    """
    res = []
    for sect in h:
        sect_addr = sect['address']
        sect_data = sect['data']
        for i in range(len(sect_data) // pgsz):
            res += [{'address': sect_addr + i * pgsz, 'data': sect_data[i *
                pgsz:i * pgsz + pgsz]}]
    return res


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


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


@classmethod
def _create_outerjoin(cls, left, right, onclause=None, full=False):
    """Return an ``OUTER JOIN`` clause element.

        The returned object is an instance of :class:`.Join`.

        Similar functionality is also available via the
        :meth:`~.FromClause.outerjoin()` method on any
        :class:`.FromClause`.

        :param left: The left side of the join.

        :param right: The right side of the join.

        :param onclause:  Optional criterion for the ``ON`` clause, is
          derived from foreign key relationships established between
          left and right otherwise.

        To chain joins together, use the :meth:`.FromClause.join` or
        :meth:`.FromClause.outerjoin` methods on the resulting
        :class:`.Join` object.

        """
    return cls(left, right, onclause, isouter=True, full=full)


def middleware(func):
    """ Decorator for func(store, get_next, action)
    to more tersely make a middleware function """
    return lambda store: lambda get_next: lambda action: func(store,
        get_next, action)


def assert_no_property_override(obj, base_class):
    """
    Use this to ensure that a Struct doesn't override properties of Field when using it as one.
    Structs can be used like fields when nesting structs or sequencing them.
    :raises: NameError if a property was overridden.
    """
    for attr_name in dir(obj):
        if hasattr(base_class, attr_name):
            if isinstance(getattr(base_class, attr_name), property
                ) and not isinstance(getattr(type(obj), attr_name), property):
                raise NameError(
                    f"'{attr_name}' is an invalid name for an attribute in a sequenced struct"
                    )


def force_list(var):
    """
    Returns the given variable as list
    :param var: variant
    :return: list
    """
    if var is None:
        return []
    if type(var) is not list:
        if type(var) in [tuple]:
            var = list(var)
        else:
            var = [var]
    return var


def inverse_weighting_function(distance, bin_width=None):
    """
    The "inverse" weighting function used in Yaffe and Tanay 2011.

    Parameters
    ----------
    distance : float
        The distance to compute a weight for, in base pairs.
    bin_width : Optional[int]
        The bin width in base pairs. Used to make results equivalent to Yaffe
        and Tanay 2011 by scaling ``distance`` to units of bins. Pass None to
        simply leave the distance in units of base pairs

    Returns
    -------
    float
        A weight appropriate for this distance.
    """
    if bin_width is not None:
        return 1 / (distance / float(bin_width) + 1)
    return float(1) / (distance + 1)


def set_prefs(prefs):
    """This function is called before opening the project"""
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg',
        '.svn', '_svn', '.git', '.tox', '.env', 'node_modules',
        'bower_components']
    prefs['save_objectdb'] = True
    prefs['compress_objectdb'] = False
    prefs['automatic_soa'] = True
    prefs['soa_followed_calls'] = 0
    prefs['perform_doa'] = True
    prefs['validate_objectdb'] = True
    prefs['max_history_items'] = 32
    prefs['save_history'] = True
    prefs['compress_history'] = False
    prefs['indent_size'] = 4
    prefs['extension_modules'] = []
    prefs['import_dynload_stdmods'] = True
    prefs['ignore_syntax_errors'] = False
    prefs['ignore_bad_imports'] = False
    prefs['split_imports'] = False
    prefs['sort_imports_alphabetically'] = False


def mm():
    """Return month as a 2 digit string"""


def zip_has_arcname(zp, arcname):
    """
    Returns True if the given zipfile instance contains the given archive

    Parameters
    ----------
    zp: ZipFile
        The zip archive to consider
    arcname: str
        The archive to look for
    """
    try:
        zp.getinfo(arcname)
        return True
    except KeyError:
        return False


def new_instance(before=None):
    """
        Create a new object to be used concurrently.

        If *before* is given, it is an integer TID, giving the *maximum*
        transaction that will be visible to this object (this only works
        correctly for history-preserving storages).

        .. caution::

           Failing to provide *before* for a historical connection
           will lead to consistency errors.
        """


@classmethod
def get_nameid_unspecified(cls, user_id: str, **kwargs) ->str:
    """ returns user_id as is
        """
    return user_id


def start():
    """Start for read-write requests placeholder

    Typically performed at the start of a request cycle, say for POST or PUT
    requests.
    """
    pass


@classmethod
def load_from_file(cls, file_path):
    """
        load Image from provided file

        :param file_path: str, path to the file
        :return: Image instance
        """
    raise NotImplementedError('load_from_file method is not implemented')


@staticmethod
def significant(pp, what):
    """Calculate significant expressed genes."""
    if what == 'gene':
        df_significant = pp.genes_detected[pp.genes_detected.loc[:, (pp.
            comparisons)].any(axis=1)]
    elif what == 'isoform':
        df_significant = pp.isoforms_detected[pp.isoforms_detected.loc[:, (
            pp.comparisons)].any(axis=1)]
    else:
        raise Exception('what= not known')
    return df_significant


def showOperandLines(rh):
    """
    Produce help output related to operands.

    Input:
       Request Handle
    """
    if rh.function == 'HELP':
        rh.printLn('N', '  For the GetVM function:')
    else:
        rh.printLn('N', 'Sub-Functions(s):')
    rh.printLn('N', '      consoleoutput - ' +
        'Obtains the console log from the virtual machine.')
    rh.printLn('N', '      directory     - ' +
        'Displays the user directory lines for the virtual machine.')
    rh.printLn('N', '      help          - ' +
        'Displays this help information.')
    rh.printLn('N', '      isreachable   - ' +
        'Determine whether the virtual OS in a virtual machine')
    rh.printLn('N', '                      is reachable')
    rh.printLn('N', '      status        - ' +
        'show the log on/off status of the virtual machine')
    rh.printLn('N', '      version       - ' +
        'show the version of the power function')
    if rh.subfunction != '':
        rh.printLn('N', 'Operand(s):')
    rh.printLn('N', '      <userid>      - ' +
        'Userid of the target virtual machine')
    rh.printLn('N', '      [ --all | --cpu | ' + '--memory | --power ]')
    rh.printLn('N', '                    - ' +
        'Returns information machine related to the number')
    rh.printLn('N', '                      ' +
        'of virtual CPUs, memory size, power status or all of the')
    rh.printLn('N', '                      information.')
    return


def AUID(val):
    """AuthorIdentifier
    one line only just need to undo the parser's effects"""
    retDict = {}
    for v in val:
        split = v.split(' : ')
        retDict[split[0]] = ' : '.join(split[1:])
    return retDict


@classmethod
def add_user(cls, options=None):
    """Associate a user"""
    cls.command_sub = 'add-user'
    return cls.execute(cls._construct_command(options))


def quote(s):
    """Quote a string for graphviz.

    This function is probably incomplete.
    """
    return s.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')


@staticmethod
def filter_with_english_letters(buf):
    """
        Returns a copy of ``buf`` that retains only the sequences of English
        alphabet and high byte characters that are not between <> characters.
        Also retains English alphabet and high byte characters immediately
        before occurrences of >.

        This filter can be applied to all scripts which contain both English
        characters and extended ASCII characters, but is currently only used by
        ``Latin1Prober``.
        """
    filtered = bytearray()
    in_tag = False
    prev = 0
    for curr in range(len(buf)):
        buf_char = buf[curr:curr + 1]
        if buf_char == b'>':
            in_tag = False
        elif buf_char == b'<':
            in_tag = True
        if buf_char < b'\x80' and not buf_char.isalpha():
            if curr > prev and not in_tag:
                filtered.extend(buf[prev:curr])
                filtered.extend(b' ')
            prev = curr + 1
    if not in_tag:
        filtered.extend(buf[prev:])
    return filtered


def get_full_version(version=None):
    """
    Returns a tuple of the mapr version.
    """
    if version is None:
        from omero_mapr import VERSION as version
    return version


def get_extension(filename):
    """
    returns extension of filename

    Args:
        filename (str): filename
    Returns:
        extension (str): returns extension in lowercase
    """
    return filename.rsplit('.', 1)[1]


def convert_OBvalue(byte_string, is_little_endian, struct_format=None):
    """Return the raw bytes from reading an OB value"""
    return byte_string


def select_all():
    """Select all text

    """
    pass


def clear_backlog(user_info_db):
    """clears backlog completely (for testing purposes)"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(user_info_db)
    cur = conn.cursor()
    cleanup = 'DELETE FROM "TelemBacklog"'
    cur.execute(cleanup)
    conn.commit()
    conn.close()