def tokenize(chars):
    """Convert a string of characters into a list of tokens."""
    return chars.replace('(', ' ( ').replace(')', ' ) ').split()


def get_prefix_from_ns_name(ns_name):
    """Parses prefix from prefix-identifier

    :param ns_name: The name of a namespace
    :returns: The prefix ending with a '-' or None if there is no '-'
    """
    dash_index = ns_name.find('-')
    if 0 <= dash_index:
        return ns_name[:dash_index + 1]


def list2cmdline(seq):
    """
    Translate a sequence of arguments into a command line
    string, using the same rules as the MS C runtime:

    1) Arguments are delimited by white space, which is either a
       space or a tab.

    2) A string surrounded by double quotation marks is
       interpreted as a single argument, regardless of white space
       or pipe characters contained within.  A quoted string can be
       embedded in an argument.

    3) A double quotation mark preceded by a backslash is
       interpreted as a literal double quotation mark.

    4) Backslashes are interpreted literally, unless they
       immediately precede a double quotation mark.

    5) If backslashes immediately precede a double quotation mark,
       every pair of backslashes is interpreted as a literal
       backslash.  If the number of backslashes is odd, the last
       backslash escapes the next double quotation mark as
       described in rule 3.
    """
    result = []
    needquote = False
    for arg in seq:
        bs_buf = []
        if result:
            result.append(' ')
        needquote = ' ' in arg or '\t' in arg or '|' in arg or not arg
        if needquote:
            result.append('"')
        for c in arg:
            if c == '\\':
                bs_buf.append(c)
            elif c == '"':
                result.append('\\' * len(bs_buf) * 2)
                bs_buf = []
                result.append('\\"')
            else:
                if bs_buf:
                    result.extend(bs_buf)
                    bs_buf = []
                result.append(c)
        if bs_buf:
            result.extend(bs_buf)
        if needquote:
            result.extend(bs_buf)
            result.append('"')
    return ''.join(result)


def generator(*args):
    """
    A utility function for creating a generator that will yield the
    supplied arguments.
    """
    for i in args:
        yield i


@classmethod
def create(cls, mbody, **kwargs):
    """
        Return LudolphMessage instance.
        """
    if isinstance(mbody, cls):
        return mbody
    return cls(mbody, **kwargs)


@classmethod
def decipher(cls, cyphered):
    """
        Reverse engineered version of the part of the script
        http://www.nonograms.org/js/nonogram.min.059.js
        that produces a nonogram solution for given cyphered solution
        (it can be found in puzzle HTML in the form 'var d=[...]').
        """
    x = cyphered[1]
    width = x[0] % x[3] + x[1] % x[3] - x[2] % x[3]
    x = cyphered[2]
    height = x[0] % x[3] + x[1] % x[3] - x[2] % x[3]
    x = cyphered[3]
    colors_number = x[0] % x[3] + x[1] % x[3] - x[2] % x[3]
    colors = []
    x = cyphered[4]
    for i in range(colors_number):
        color_x = cyphered[i + 5]
        a = color_x[0] - x[1]
        b = color_x[1] - x[0]
        c = color_x[2] - x[3]
        rgb = hex(a + 256)[3:] + hex((b + 256 << 8) + c)[3:]
        colors.append(rgb)
    solution = [([0] * width) for _ in range(height)]
    a = colors_number + 5
    x = cyphered[a]
    solution_size = x[0] % x[3] * (x[0] % x[3]) + x[1] % x[3] * 2 + x[2] % x[3]
    x = cyphered[a + 1]
    for i in range(solution_size):
        y = cyphered[a + 2 + i]
        vv = y[0] - x[0] - 1
        for j in range(y[1] - x[1]):
            v = j + vv
            solution[y[3] - x[3] - 1][v] = y[2] - x[2]
    return [colors, solution]


@classmethod
def generate_key(cls, secret_key, region, service, date, intermediates=False):
    """
        Generate the signing key string as bytes.

        If intermediate is set to True, returns a 4-tuple containing the key
        and the intermediate keys:

        ( signing_key, date_key, region_key, service_key )

        The intermediate keys can be used for testing against examples from
        Amazon.

        """
    init_key = ('HYPER' + secret_key).encode('utf-8')
    date_key = cls.sign_sha256(init_key, date)
    region_key = cls.sign_sha256(date_key, region)
    service_key = cls.sign_sha256(region_key, service)
    key = cls.sign_sha256(service_key, 'hyper_request')
    if intermediates:
        return key, date_key, region_key, service_key
    else:
        return key


def account_level(account_name):
    """Get the depth of an account."""
    return account_name.count(':') + 1


def err_ratio(predict, dataset, examples=None, verbose=0):
    """Return the proportion of the examples that are NOT correctly predicted.
    verbose - 0: No output; 1: Output wrong; 2 (or greater): Output correct"""
    if examples is None:
        examples = dataset.examples
    if len(examples) == 0:
        return 0.0
    right = 0.0
    for example in examples:
        desired = example[dataset.target]
        output = predict(dataset.sanitize(example))
        if output == desired:
            right += 1
            if verbose >= 2:
                print('   OK: got {} for {}'.format(desired, example))
        elif verbose:
            print('WRONG: got {}, expected {} for {}'.format(output,
                desired, example))
    return 1 - right / len(examples)


def update_text(s, **kws):
    """
    Replace arbitrary placeholders in string

    Placeholder names should be supplied as keywords
    with the corresponding values being the text to
    replace them with in the supplied string.

    When placeholders appear in the string they
    should be contained within '<...>'.

    For example:

    >>> text = "Hello my name is <NAME>"
    >>> update_text(text,NAME="Joe")
    ... "Hello my is name is Joe"

    Arguments:
      s (str): text to be updated
      kws (mapping): keywords mapping placeholder
        names to new values

    Returns:
      String: the original text updated by
        substituting
    """
    for kw in kws:
        placeholder = '<%s>' % kw
        new_text = kws[kw]
        if new_text is None:
            continue
        s = s.replace(placeholder, new_text)
    return s


@classmethod
def get(cls, *args, **kwargs):
    """Get an Association instance"""
    raise NotImplementedError('Implement in subclass')


@classmethod
def fixed_length(cls, l, allow_empty=False):
    """Create a sedes for text data with exactly `l` encoded characters."""
    return cls(l, l, allow_empty=allow_empty)


def format_bytes(nbytes):
    """Format ``nbytes`` as a human-readable string with units"""
    if nbytes > 2 ** 50:
        return '%0.2f PiB' % (nbytes / 2 ** 50)
    if nbytes > 2 ** 40:
        return '%0.2f TiB' % (nbytes / 2 ** 40)
    if nbytes > 2 ** 30:
        return '%0.2f GiB' % (nbytes / 2 ** 30)
    if nbytes > 2 ** 20:
        return '%0.2f MiB' % (nbytes / 2 ** 20)
    if nbytes > 2 ** 10:
        return '%0.2f KiB' % (nbytes / 2 ** 10)
    return '%d B' % nbytes


def collapse(season):
    """Collects all the ratings of episodes from a season"""
    l = []
    for epi in season:
        l.append(epi['rating'])
    return l


def sanitize_data(data):
    """Create neo4j safe properties"""
    from pandas import isnull
    sanitized = dict()
    for k, v in data.items():
        if isinstance(v, list):
            sanitized[k] = v
            continue
        if isnull(v):
            continue
        if v is None:
            continue
        sanitized[k] = v
    return sanitized


def convert_to_int(value_string, parser_info_out=None, suc_return=True):
    """
    Tries to make a int out of a string. If it can't it logs a warning
    and returns True or False if convertion worked or not.

    :param value_string: a string
    :returns value: the new int or value_string: the string given
    :returns: True or False, if suc_return=True
    """
    if parser_info_out is None:
        parser_info_out = {'parser_warnings': []}
    try:
        value = int(value_string)
    except TypeError:
        parser_info_out['parser_warnings'].append(
            'Could not convert: "{}" to int, TypeError'.format(value_string))
        if suc_return:
            return value_string, False
        else:
            return value_string
    except ValueError:
        parser_info_out['parser_warnings'].append(
            'Could not convert: "{}" to int, ValueError'.format(value_string))
        if suc_return:
            return value_string, False
        else:
            return value_string
    if suc_return:
        return value, True
    else:
        return value


@classmethod
def get_compo_name(cls):
    """
        Get current component name.
        :return str
        :rtype str
        """
    return cls._compo_name


def raising(info, request=None):
    """
        Logs an exception.

        :param info: The exception info, as determined by :func:`sys.exc_info`.
        """


def getMeasurementId(measurementStartTime, measurementName):
    """
    the unique id for this measurement.
    :param measurementStartTime: the measurement startTime
    :param measurementName: the measurement name
    :return: the id.
    """
    return measurementStartTime.strftime('%Y%m%d_%H%M%S'
        ) + '_' + measurementName


def baseconv(num, alphabet, minimum_characters=0):
    """
    convert base 10 number to custom base w/ alphabet
    :param num: base 10 input
    :param alphabet: alphabet to use for conversion
    :return:
    """
    arr = []
    base = len(alphabet)
    if not num:
        converted_value = alphabet[0]
    else:
        while num:
            rem = num % base
            num //= base
            arr.append(alphabet[rem])
        arr.reverse()
        converted_value = str(''.join(arr))
    while len(converted_value) < minimum_characters:
        converted_value = alphabet[0] + converted_value
    return converted_value


def inverse_norm(x, unit=1.0, order=1):
    """
  The simple inverse function: z(x) = 1.0 / x

  Args:
    x: Union[float, np.ndarray] as the inputs to scale.
    unit: a dummy variable.
    order: a dummy variable.

  Returns:
    z: the inversed inputs.

  """
    return 1.0 / x


def listdir(dirname):
    """Returns a list of filenames contained in the named directory."""
    import os
    return os.listdir(dirname)


def get_chapter_id(url: str=None) ->str:
    """
    Returns the ID number from a given MangaDex chapter URL.

    Parameters:
        url (str): MangaDex chapter URL

    Returns:
        str: MangaDex chapter ID number
    """
    if url is None or 'mangadex.' not in url or '/chapter/' not in url:
        return ''
    start = url.index('/chapter/')
    id = url[start:]
    return str(id)


def sub_dfs_by_size(df, size):
    """Get a generator yielding consecutive sub-dataframes of the given size.

    Arguments
    ---------
    df : pandas.DataFrame
        The dataframe for which to get sub-dataframes.
    size : int
        The size of each sub-dataframe.

    Returns
    -------
    generator
        A generator yielding consecutive sub-dataframe of the given size.

    Example
    -------
    >>> import pandas as pd; import pdutil;
    >>> data = [[23, "Jen"], [42, "Ray"], [15, "Fin"]]
    >>> df = pd.DataFrame(data, columns=['age', 'name'])
    >>> for subdf in pdutil.iter.sub_dfs_by_size(df, 2): print(subdf)
       age name
    0   23  Jen
    1   42  Ray
       age name
    2   15  Fin
    """
    for i in range(0, len(df), size):
        yield df.iloc[i:i + size]


def isint(val):
    """
    check if the entry can become an integer (integer or string of integer)

    Parameters
    ----------
    val
        an entry of any type

    Returns
    -------
    bool
        True if the input can become an integer, False otherwise

    """
    try:
        int(val)
        return True
    except ValueError:
        return False


@staticmethod
def equal(arg_name, arg_value, cond_str, cond):
    """Judging valid value."""
    if not cond:
        raise ValueError(
            f'The `{arg_name}` must be {cond_str}, but got {arg_value}.')


@classmethod
def GetAnalyzers(cls):
    """Retrieves the registered analyzers.

    Yields:
      tuple: containing:

        str: the uniquely identifying name of the analyzer
        type: the analyzer class.
    """
    for analyzer_name, analyzer_class in iter(cls._analyzer_classes.items()):
        yield analyzer_name, analyzer_class


def parse_fasta(data):
    """Load sequences in Fasta format.

    This generator function yields a tuple containing a defline and a sequence
    for each record in the Fasta data. Stolen shamelessly from
    http://stackoverflow.com/a/7655072/459780.
    """
    name, seq = None, []
    for line in data:
        line = line.rstrip()
        if line.startswith('>'):
            if name:
                yield name, ''.join(seq)
            name, seq = line, []
        else:
            seq.append(line)
    if name:
        yield name, ''.join(seq)


def is_csrf_token_expired(token):
    """Checks whether a CSRF token is still valid

    Expects a token of the form "YYYYMMDDHHMMSS##..."

    Returns:
        True if the token has expired
        False if the token is still valid
    """
    from datetime import datetime
    expiry = token.split('##')[0]
    if expiry <= datetime.now().strftime('%Y%m%d%H%M%S'):
        return True
    return False


@staticmethod
def _get_name_from_dn(dn):
    """
        Get the instance name from the dn

        :param dn: string containing the distinguished name URL
        :return: string containing the name
        """
    name = dn.split('/sys/actrl/filt-')[1].split('/')[0]
    return name


def compression_level(n, q, oversampling=10, min_subspace_size=20):
    """ Compression level to use in svd_compressed

    Given the size ``n`` of a space, compress that that to one of size
    ``q`` plus oversampling.

    The oversampling allows for greater flexibility in finding an
    appropriate subspace, a low value is often enough (10 is already a
    very conservative choice, it can be further reduced).
    ``q + oversampling`` should not be larger than ``n``.  In this
    specific implementation, ``q + oversampling`` is at least
    ``min_subspace_size``.

    >>> compression_level(100, 10)
    20
    """
    return min(max(min_subspace_size, q + oversampling), n)


def _preprocess_trials(trial_gen):
    """Preprocess trials

    Add level and tooltip to trials

    Return:
    trials -- preprocessed trials
    ids -- preprocessed trial ids
    tmap -- map trial.id to trial

    Arguments:
    trial_gen -- trial generator
    """
    trials = []
    ids = []
    tmap = {}
    for trial in trial_gen:
        trial.level = 0
        trial.tooltip = (
            """
            {0.script}

            {status}

            Start: {0.start}

            Finish: {0.finish}
            """
            .format(trial, status=trial.status.capitalize()))
        if trial.finish:
            trial.tooltip += (
                """

            Duration: {duration}
            """
                .format(duration=trial.duration_text))
        tmap[trial.id] = trial
        trials.append(trial)
        ids.append(trial.id)
    return trials, ids, tmap


def get_note_flags(note):
    """
    get the note flags

    Returns a fixed length string:
      'X' - needs sync
      '*' - favorite
    """
    flags = ''
    flags += 'X' if float(note['modified']) > float(note['syncdate']) else ' '
    if 'favorite' in note:
        flags += '*' if note['favorite'] else ' '
    else:
        flags += '  '
    return flags


def bounds(total_docs, start_client_index, end_client_index, num_clients,
    includes_action_and_meta_data):
    """

    Calculates the start offset and number of documents for a range of clients.

    :param total_docs: The total number of documents to index.
    :param start_client_index: The first client index.  Must be in the range [0, `num_clients').
    :param end_client_index: The last client index.  Must be in the range [0, `num_clients').
    :param num_clients: The total number of clients that will run bulk index operations.
    :param includes_action_and_meta_data: Whether the source file already includes the action and meta-data line.
    :return: A tuple containing: the start offset (in lines) for the document corpus, the number documents that the
             clients should index, and the number of lines that the clients should read.
    """
    source_lines_per_doc = 2 if includes_action_and_meta_data else 1
    docs_per_client = total_docs / num_clients
    start_offset_docs = round(docs_per_client * start_client_index)
    end_offset_docs = round(docs_per_client * (end_client_index + 1))
    offset_lines = start_offset_docs * source_lines_per_doc
    docs = end_offset_docs - start_offset_docs
    lines = docs * source_lines_per_doc
    return offset_lines, docs, lines


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

        :param MemberSpaceLimitsRemoveExceptionType val:
        :rtype: EventType
        """
    return cls('member_space_limits_remove_exception', val)


@staticmethod
def stateMap():
    """
        For a given condor status mapped, return a global state used by the agent
        NOTE: these keys are populated into bl_status table.
        NOTE2: Timeout must be present in all future plugins (New is recommended too)
        """
    stateMap = {'New': 'Pending', 'Idle': 'Pending', 'Running': 'Running',
        'Removed': 'Error', 'Completed': 'Complete', 'Held': 'Error',
        'TransferOutput': 'Running', 'Suspended': 'Error', 'Timeout':
        'Error', 'Unknown': 'Error'}
    return stateMap


def get_str_value_from_property_value(property_value, separator):
    """ Evaluate string value of property """
    if isinstance(property_value, list):
        return separator.join(property_value)
    raise str('property value must be a list')


def merge_two_dictionaries(dict1, dict2):
    """
    Merge two dictionaries.

    Merge two dictionaries, return the result. Does not alter the input dictionaries. Note that the order matters if the input dictionaries contain identical keys: the values from the second one will show up in the merged result.

    Parameters
    ----------
    dict1: dictionary
        The first dictionary.

    dict2: dictionary
        The second dictionary. Note that the order matters if the input dictionaries contain identical keys: the values from the second one will show up in the merged result.

    Returns
    -------
    dictionary
        The merged, new dictionary.
    """
    new_dict = dict1.copy()
    new_dict.update(dict2)
    return new_dict


def single_element(x):
    """If x contains a single element, return it; otherwise return x"""
    try:
        if len(x) == 1:
            x = x[0]
    except TypeError:
        return x
    return x


def option_name(path, delimiter='--'):
    """
    Returns a cli option name from attribute path

    **Arguments**

    - path (`list`): attribute path
    - delimiter (`str`): delimiter for nested attributes

    **Returns**

    cli option name (`str`)
    """
    return '--{}'.format(delimiter.join(path).replace('_', '-'))


def prepare_s3_prefix(bucket, pre_date_part, y=None, mo=None, d=None, h=
    None, after_date_part=''):
    """
    compose an s3 path from given parts and date values
    example:
        {bucket}/{pre_date_part}/mo={y}-{mo}/day={d}/hour={h}/after_date_part
    Parameters
    ----------
    bucket
        bucket name, may include "s3://"
    pre_date_part
        part of the path before date strings
    y
        year number
    mo
        month number
    d
        day number
    h
        hour number
    after_date_part
        part of the path after date strings
    Returns
    -------
        composed s3 path
    """
    if not bucket.startswith('s3://'):
        bucket = 's3://' + bucket
    s = '/'.join([bucket.strip('/'), pre_date_part.strip('/')])
    if y is not None and mo is not None:
        s += '/mo={y}-{mo}'.format(y=y, mo=mo)
    if d is not None:
        s += '/day={d}'.format(d=d)
    if h is not None:
        s += '/hour={h}'.format(h=h)
    if len(after_date_part) > 0:
        s += '/' + after_date_part
    return s


def merge_list(list1, list2):
    """
    Merges the contents of two lists into a new list.

    :param list1: the first list
    :type list1: list
    :param list2: the second list
    :type list2: list
    :returns: list
    """
    merged = list(list1)
    for value in list2:
        if value not in merged:
            merged.append(value)
    return merged


@classmethod
def merge(cls, session, items):
    """Models should override this to perform a merge"""
    return items


def psi_H_Na_CO3_HMW84(T, P):
    """c-c'-a: hydrogen sodium carbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def edge_rotate(edge: 'bmesh.types.BMEdge', ccw: bool=False
    ) ->'bmesh.types.BMEdge':
    """Rotate the edge and return the newly created edge. If rotating the edge fails, None will be returned.

    :param edge: The edge to rotate.
    :type edge: 'bmesh.types.BMEdge'
    :param ccw: When True the edge will be rotated counter clockwise.
    :type ccw: bool
    :return:  The newly rotated edge.
    """
    pass


def get_signed_headers(headers):
    """
    Get signed headers.

    :param headers: input dictionary to be sorted.
    """
    headers_to_sign = dict(headers)
    signed_headers = []
    for header in headers:
        signed_headers.append(header)
    signed_headers.sort()
    return signed_headers


def createMainWidget(argv):
    """
    Function to create the main widget.

    @param argv list of commandline parameters (list of strings)
    @return reference to the main widget (QWidget)
    """
    from Plugins.WizardPlugins.QRegularExpressionWizard import QRegularExpressionWizardDialog
    return QRegularExpressionWizardDialog.QRegularExpressionWizardWindow()


@classmethod
def dump_bulk(cls, parent=None, keep_ids=True):
    """
        Dumps a tree branch to a python data structure.

        :param parent:

            The node whose descendants will be dumped. The node itself will be
            included in the dump. If not given, the entire tree will be dumped.

        :param keep_ids:

            Stores the id value (primary key) of every node. Enabled by
            default.

        :returns: A python data structure, described with detail in
                  :meth:`load_bulk`
        """
    raise NotImplementedError


def c2max(f, c1, c2):
    """Take the maximum value between two columns in a dataframe.

    Parameters
    ----------
    f : pandas.DataFrame
        Dataframe containing the two columns ``c1`` and ``c2``.
    c1 : str
        Name of the first column in the dataframe ``f``.
    c2 : str
        Name of the second column in the dataframe ``f``.

    Returns
    -------
    max_val : float
        The maximum value of the two columns.

    """
    max_val = max(f[c1], f[c2])
    return max_val


def __repr__(cls) ->str:
    """ Should always raise an ImportError. """
    cls._import()
    return super().__repr__()


def is_index_in_queue(index, queue_length):
    """Helper function to verify if index exists"""
    if index > 0 and index <= queue_length:
        return True
    return False


def is_valid_model_filters(model, filters):
    """Return True if filter values exist on the model

    :param model: a Cinder model
    :param filters: dictionary of filters
    """
    for key in filters.keys():
        if not hasattr(model, key):
            return False
    return True


def dict_find(in_dict, value):
    """ Helper function for looking up directory keys by their values.
     This isn't robust to repeated values

    Parameters
    ----------
    in_dict : dictionary
        A dictionary containing `value`

    value : any type
        What we wish to find in the dictionary

    Returns
    -------
    key: basestring
        The key at which the value can be found

    Examples
    --------
    >>> dict_find({'Key1': 'A', 'Key2': 'B'}, 'B')
    'Key2'

    """
    return list(in_dict.keys())[list(in_dict.values()).index(value)]


def log_info(message):
    """Log a message to STDOUT"""
    print(message)


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


@staticmethod
def compute_block_metric(block):
    """Compute sortable metric to rank blocks."""
    return NotImplementedError


def revnum_to_revref(rev, old_marks):
    """Convert an hg revnum to a git-fast-import rev reference (an SHA1
  or a mark)"""
    return old_marks.get(rev) or ':%d' % (rev + 1)


def _on_figure_window_close(figure, function):
    """Connects a close figure signal to a given function.

    Parameters
    ----------

    figure : mpl figure instance
    function : function

    """
    window = figure.canvas.manager.window
    if not hasattr(figure, '_on_window_close'):
        figure._on_window_close = list()
    if function not in figure._on_window_close:
        figure._on_window_close.append(function)
    window.closing.connect(function)


def is_retryable(txn, error):
    """Check if this transaction is one caused by database conflict.

    These transactions should not be caught in catch all exception expressions.

    :param txn:
    :param error:
    :return:
    """
    if txn is None:
        return False
    for dm in txn._resources:
        should_retry = getattr(dm, 'should_retry', None)
        if should_retry is not None and should_retry(error):
            return True


def sum_arrays(vertices, offset):
    """Sum the value to the coordinates."""
    new_vertices = []
    for v in vertices:
        a = v[0] + offset[0], v[1] + offset[1], v[2] + offset[2]
        new_vertices.append(a)
    return new_vertices


def get_connectors(nextToken=None, maxResults=None):
    """
    The GetConnectors API returns a list of connectors that are registered with the Server Migration Service.
    See also: AWS API Documentation

    :example: response = client.get_connectors(
        nextToken='string',
        maxResults=123
    )

    :type nextToken: string
    :param nextToken: Pagination token to pass as input to API call

    :type maxResults: integer
    :param maxResults: The maximum number of results to return in one API call. If left empty, this will default to 50.

    :rtype: dict
    :return: {
        'connectorList': [
            {
                'connectorId': 'string',
                'version': 'string',
                'status': 'HEALTHY'|'UNHEALTHY',
                'capabilityList': [
                    'VSPHERE',
                ],
                'vmManagerName': 'string',
                'vmManagerType': 'VSPHERE',
                'vmManagerId': 'string',
                'ipAddress': 'string',
                'macAddress': 'string',
                'associatedOn': datetime(2015, 1, 1)
            },
        ],
        'nextToken': 'string'
    }

    :returns:
    (dict) --
    connectorList (list) -- List of connectors
    (dict) -- Object representing a Connector
    connectorId (string) -- Unique Identifier for Connector
    version (string) -- Connector version string
    status (string) -- Status of on-premise Connector
    capabilityList (list) -- List of Connector Capabilities
    (string) -- Capabilities for a Connector

    vmManagerName (string) -- VM Manager Name
    vmManagerType (string) -- VM Management Product
    vmManagerId (string) -- Unique Identifier for VM Manager
    ipAddress (string) -- Internet Protocol (IP) Address
    macAddress (string) -- Hardware (MAC) address
    associatedOn (datetime) -- Timestamp of an operation

    nextToken (string) -- Pagination token to pass as input to API call

    """
    pass


def inter_point_convexpolyhedron(p, cph):
    """intersection function for Point and ConvexPolyhedron
    input:
    p: Point
    cph: ConvexPolyhedron

    output:
    intersection
    """
    if p in cph:
        return p
    else:
        return None


@classmethod
def from_DataFrame(cls, df, name, description, refgen, rawtype=None,
    normalize=True, norm_method=None, quantile=False, quality_control=True,
    **kwargs):
    """
            Creates an Expr instance from a pandas DataFrame. Expects that the
            DataFrame index is gene names and the column names are accessions
            (i.e. experiments).  This is the preferred method for creating an
            Expr instance, in other words, other classmethods transform their
            data so they can call this method.

            Parameters
            ----------
            df : pandas.DataFrame
                a DataFrame containing expression data. Assumes index is the
                genes and columns is the accessions (experiment names)
            name : str
                A short name to refer to from the camoco dataset API.
            description : str
                A short description for the dataset
            refgen : camoco.RefGen
                A Camoco refgen object which describes the reference
                genome referred to by the genes in the dataset. This
                is cross references during import so we can pull information
                about genes we are interested in during analysis.
            rawtype : str (one of: 'RNASEQ' or 'MICROARRAY')
                Specifies the fundamental datatype used to measure expression.
                During importation of the raw expression data, this value is
                used to make decisions in converting data to log-space.
            normalize : bool (Default: True)
                Specifies whether or not to normalize the data so raw
                expression values lie within a log space. This is best
                practices for generating interpretable expression analyses. See
                Expr._normalize method for more information.  info.
            norm_method : None OR python function
                If rawtype is NOT RNASEQ or MICROARRY AND normalize is still
                True, the normalization method for the raw expression values
                needs to be passed in. This is for extreme customization
                situations.
            quantile : bool (Default : False)
                Specifies whether or not to perform quantile normalization on
                import.
            quality_control : bool (Default: True)
                A flag which specifies whether or not to perform QC. Parameters
                for QC are passed in using the **kwargs arguments. For default
                parameters and options see Expr._quality_control.
            **kwargs : key value pairs
                additional parameters passed to subsequent methods.
                See arguments for Expr._normalize(), Expr._quality_control()

            Returns
            -------
            An Expr instance

        """
    self = cls.create(name, description, refgen)
    self._reset(raw=True)
    if rawtype is None:
        raise TypeError("raw_type must be one of ['RNASEQ', 'MICROARRAY']")
    self._global('rawtype', rawtype)
    self.log('Importing Raw Expression Values')
    self._update_values(df, 'Raw' + rawtype, raw=True)
    if quality_control:
        self.log('Performing Quality Control on genes')
        self._quality_control(**kwargs)
        assert self.anynancol() == False
    else:
        self.log('Skipping Quality Control!')
    if normalize:
        self.log('Performing Raw Expression Normalization')
        self._normalize(**kwargs)
        assert self.anynancol() == False
    if quantile:
        self.log('Performing Quantile Gene Normalization')
        self._quantile()
        assert self.anynancol() == False
    self.log('Filtering refgen: {}', refgen.name)
    self._set_refgen(refgen, filter=True)
    return self


@classmethod
def get_saml_slos(cls, logout_request):
    """returns saml logout ticket info"""
    from lxml import etree
    try:
        root = etree.fromstring(logout_request)
        return root.xpath('//samlp:SessionIndex', namespaces={'samlp':
            'urn:oasis:names:tc:SAML:2.0:protocol'})
    except etree.XMLSyntaxError:
        pass


def get_loss(name):
    """Returns loss function by the name."""
    try:
        return globals()[name]
    except:
        raise ValueError('Invalid metric function.')


def weighted_eps(net_income, dividend, outstanding_shares):
    """Computes weighted earnings per share.

    @params
    -------
    net_income: net income of company for the last 1-year period
    dividend: dividend payment of company for the last period
    outstanding_shares: # of outstanding shares, can be used dilluted shares

    returns
    -------
    Returns weighted earnings per share, int or float
    """
    weighted_eps = (net_income - dividend) / outstanding_shares
    return weighted_eps


def always(matching_invocations, all_invocations):
    """
    This predicate verifies that all invocations must have matched.

    :param matching_invocations: All found matching invocations.
    :param all_invocations: All invocations of the Spy
    :return: True or False.
    """
    return len(matching_invocations) == len(all_invocations)


def qbytearray_to_str(qba):
    """Convert QByteArray object to str in a way compatible with Python 2/3"""
    return str(bytes(qba.toHex()).decode())


def get_chost_stuff(conf):
    """
	Get the CHOST environment variable contents
	"""
    chost = None
    chost_envar = None
    if conf.env.CHOST:
        chost = conf.env.CHOST[0]
        chost_envar = chost.replace('-', '_')
    return chost, chost_envar


def get_user_bound(info):
    """ user specified bound for measurements filter """
    v = [info['tshift_reference'] - info['tshift_acceptance_level'], info[
        'tshift_reference'] + info['tshift_acceptance_level'], info[
        'dlna_reference'] - info['dlna_acceptance_level'], info[
        'dlna_reference'] + info['dlna_acceptance_level']]
    if v[0] > v[1] or v[2] > v[3]:
        raise ValueError('error on user bound: %s' % v)
    return v


def read_samples(fn):
    """Read samples from the header of a GFF file.

    Args:
        *fn(str)*: GFF file to read.

    Returns:
        *(list)*: character list with sample names.
    """
    with open(fn) as inh:
        for line in inh:
            if line.startswith('## COLDATA'):
                return line.strip().split(': ')[1].strip().split(',')
    raise ValueError("%s doesn't contain COLDATA header." % fn)


@classmethod
def PUT(cls, *n, **kw):
    """
        Perform a PUT request using `RESTClient.request()`
        """
    return cls.IMPL.PUT(*n, **kw)


def ShowDockingGuides(guides, show):
    """
    Shows or hide the docking guide windows.

    :param `guides`: a list of :class:`AuiDockingGuide` classes;
    :param bool `show`: whether to show or hide the docking guide windows.
    """
    for target in guides:
        if show and not target.host.IsShown():
            target.host.Show()
            target.host.Update()
        elif not show and target.host.IsShown():
            target.host.Hide()


def get_config_defaults():
    """Get the default configuration values."""
    config = {}
    config['quiet'] = False
    config['daemon-mode'] = False
    config['config'] = None
    config['log-file'] = None
    config['pid-file'] = '~/.gitautodeploy.pid'
    config['http-enabled'] = True
    config['http-host'] = '0.0.0.0'
    config['http-port'] = 8001
    config['https-enabled'] = True
    config['https-host'] = '0.0.0.0'
    config['https-port'] = 8002
    config['wss-enabled'] = False
    config['wss-host'] = '0.0.0.0'
    config['wss-port'] = 8003
    config['ssl-key'] = None
    config['ssl-cert'] = '~/cert.pem'
    config['web-ui-enabled'] = False
    config['web-ui-username'] = None
    config['web-ui-password'] = None
    config['web-ui-whitelist'] = ['127.0.0.1']
    config['web-ui-require-https'] = True
    config['web-ui-auth-enabled'] = True
    config['web-ui-prevent-root'] = True
    config['log-level'] = 'NOTSET'
    config['intercept-stdout'] = True
    config['ssh-keyscan'] = False
    config['allow-root-user'] = False
    config['log-test-case'] = False
    config['log-test-case-dir'] = None
    return config


def mapiv(ol, map_func, map_func_args=[]):
    """
        #mapiv            共享相同的o,共享相同的f              share common map_func,share common other_args
        #map_func         common_func(index,value,*common_args)
    """
    lngth = ol.__len__()
    rslt = []
    for i in range(0, lngth):
        index = i
        value = ol[i]
        func = map_func
        args = map_func_args
        ele = func(index, value, *args)
        rslt.append(ele)
    return rslt


@classmethod
def guess(cls, error, lm):
    """Return the initial guess at a good set of arguments.

        `error` -- `array[N; float]` -- example error scores

        `lm` -- `array[N; float]` -- example language model scores

        `return` -- `dict` -- `{"arg_name": initial_value}`
        """
    raise NotImplementedError


def write_edge_csv(edges, fname, delim=';'):
    """
    Write a three-field csv file formatted as
    (cleft_id, presyn_segid, postsyn_segid).
    """
    with open(fname, 'w+') as f:
        for cleft_id, presyn_id, postsyn_id in edges:
            content = delim.join(map(str, (cleft_id, presyn_id, postsyn_id)))
            f.write(f'{content}\n')


@staticmethod
def _is_keep_alive_response(response):
    """Check if received GraphQL response is keep-alive message."""
    return response.get('type') == 'ka'


def _add_person_to_group(person, group):
    """ Call datastores after adding a person to a group. """
    from karaage.datastores import add_accounts_to_group
    from karaage.datastores import add_accounts_to_project
    from karaage.datastores import add_accounts_to_institute
    a_list = person.account_set
    add_accounts_to_group(a_list, group)
    for project in group.project_set.all():
        add_accounts_to_project(a_list, project)
    for institute in group.institute_set.all():
        add_accounts_to_institute(a_list, institute)


@staticmethod
def _calculateIntervalResult(list, timeStamp, positiveResult, negativeResult):
    """
        A helper function to calculate black interval results or white interval
        results.

        :param list list: The set of RepetitiveInterval, which can be the white
          list or the black list.
        :param float timeStamp: The time stamp as milliseconds since Jan 1,
          1970 UTC.
        :param Interval positiveResult: The positive result which is updated.
        :param Interval negativeResult: The negative result which is updated.
        """
    for i in range(len(list)):
        element = list[i]
        result = element.getInterval(timeStamp)
        tempInterval = result.interval
        if result.isPositive == True:
            positiveResult.unionWith(tempInterval)
        elif not negativeResult.isValid():
            negativeResult.set(tempInterval)
        else:
            negativeResult.intersectWith(tempInterval)


@staticmethod
def get_message(build, commit):
    """Extract the message from the commit or comment.

        Arguments:
          build (:py:class:`dict`): The JSON data from the response.
          commit (:py:class:`dict`): The JSON data from the response.

        Returns:
          :py:class:`str`: The commit or comment message.

        """
    return build.get('comment') or commit.get('message')


def onStop(exit_code):
    """
        Called before exiting the forked process.
        """


def get_transitions_id(transition_name, transitions_list):
    """
    Function return ID of transition
    """
    for transition in transitions_list:
        if transition['name'] == transition_name:
            return transition['id']
    return None


@staticmethod
def p_a2ml_declaration(p):
    """a2ml_declaration : a2ml_type_definition SEMICOLON
                            | a2ml_block_definition SEMICOLON"""
    p[0] = p[1]


def uniform_int_from_avg(a, m, seed):
    """ Pick a random integer with uniform probability.

    Returns a random integer uniformly taken from a distribution with
    minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where
    b = 2*m - a.

    Notes
    -----
    p = (b-floor(b))/2
    X = X1 + X2; X1~U(a,floor(b)), X2~B(p)
    E[X] = E[X1] + E[X2] = (floor(b)+a)/2 + (b-floor(b))/2 = (b+a)/2 = m
    """
    from math import floor
    assert m >= a
    b = 2 * m - a
    p = (b - floor(b)) / 2
    X1 = int(round(seed.random() * (floor(b) - a) + a))
    if seed.random() < p:
        X2 = 1
    else:
        X2 = 0
    return X1 + X2


def build_secondary_axis(axis, on='x', **kwargs):
    """
    Build twin secondary axis.

    :param axis: Matplotlib axis instance.
    :type axis: :class:`matplotlib.axes.Axes`
    :param on: Name of axis to build secondary axis (x, y).
    :type on: str, default: x
    """
    methods = {'x': 'twinx', 'y': 'twiny'}
    method = getattr(axis, methods[on])
    return method()


@staticmethod
def create(*args, **kwargs):
    """A stub to be implemented by child class."""
    raise NotImplementedError(
        '[ERROR] Cannot call method on file.Node. It is an abstract class.')


def is_hashable(obj):
    """Return True if obj is hashable, else return False."""
    try:
        hash(obj)
        return True
    except:
        return False


@classmethod
def content_synchronize(cls, options):
    """Synchronize the content to the capsule."""
    cls.command_sub = 'content synchronize'
    result = cls.execute(cls._construct_command(options), output_format='csv')
    return result


def get_delays(trains):
    """Yields delays of trains where it is not `None`.

    Args:
        trains (iterable[Connection]): Iterable holding trains.
    """
    for train in trains:
        if train.delay:
            yield train.delay


def focus_next(event):
    """
    Focus the next visible Window.
    (Often bound to the `Tab` key.)
    """
    event.app.layout.focus_next()


def cursor_set(location: float=(0.0, 0.0)):
    """Set 2D cursor location

    :param location: Location, Cursor location in normalized clip coordinates
    :type location: float
    """
    pass


def _clean_author(author):
    """Clean the Author field of some unnecessary annotations."""
    author = author.replace('Auteur du texte', '').split('/')[0].split(';')[0]
    if '(' in author:
        author = author.split(')')[0] + ')'
    return author.strip(':.,; ')


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


def get_config_env_key(k: str) ->str:
    """
    Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for
    setting explicit varaibles.  This is unlike PULUMI_CONFIG which is just a JSON-serialized bag.
    """
    env_key = ''
    for c in k:
        if c == '_' or 'A' <= c <= 'Z' or '0' <= c <= '9':
            env_key += c
        elif 'a' <= c <= 'z':
            env_key += c.upper()
        else:
            env_key += '_'
    return 'PULUMI_CONFIG_%s' % env_key


@staticmethod
def _limit_string(string_, len_):
    """Limit the string length"""
    return string_ if len(string_) <= len_ else string_[0:len_ - 3] + '...'


@classmethod
def findViewers(cls, className, environment):
    """ Find the available viewers in this Domain for this class. """
    viewers = []
    clazz = cls.findClass(className)
    baseClasses = clazz.mro()
    preferredViewers = cls.getPreferredViewers(className)
    preferedFlag = 0
    for viewer in cls.getViewers().values():
        if environment in viewer._environments:
            for t in viewer._targets:
                if t in baseClasses:
                    for prefViewer in preferredViewers:
                        if viewer is prefViewer:
                            viewers.insert(0, viewer)
                            preferedFlag = 1
                            break
                    else:
                        if t == clazz:
                            viewers.insert(preferedFlag, viewer)
                        else:
                            viewers.append(viewer)
                        break
    return viewers


@classmethod
def _add_tracking(cls, pipeline, region, namespace, key):
    """Add's basic set members for tracking

        This is added to a Redis pipeline for a single round-trip to
        Redis.

        """
    pipeline.sadd('retools:regions', region)
    pipeline.sadd('retools:%s:namespaces' % region, namespace)
    pipeline.sadd('retools:%s:%s:keys' % (region, namespace), key)


def get_sign(x):
    """Get the sign of a number."""
    if x > 0:
        return 1
    if x == 0:
        return 0
    assert x < 0
    return -1


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 autopack_toggle():
    """Automatically pack all external files into the .blend file

    """
    pass


def keyconfig_preset_add(name: str='', remove_active: bool=False):
    """Add or remove a Key-config Preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_active: remove_active
    :type remove_active: bool
    """
    pass


def largest(upper, lower):
    """Returns largest of the two values."""
    val = max(upper, lower)
    return val, val


@staticmethod
def in_cubic(progress):
    """.. image:: images/anim_in_cubic.png
        """
    return progress * progress * progress


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


def strictstr(value):
    """
  Returns ``value`` unmodified if it is a :class:`str`, and fails otherwise.
  Notable difference with the behavior of :class:`str`:

  *   :func:`strictstr` does not call ``__str__`` methods of objects to
      automatically convert objects to :class:`str`\\s.

  Examples
  --------

  Passing a :class:`str` to :func:`strictstr` works:

  >>> strictstr('spam')
  'spam'

  Passing an :class:`int` will fail:

  >>> strictstr(1)
  Traceback (most recent call last):
      ...
  ValueError: not a 'str': 1
  """
    if not isinstance(value, str):
        raise ValueError("not a 'str': {!r}".format(value))
    return value


def move_language_preference(apps, schema_editor):
    """Move language from parameters to User model."""
    UserParameter = apps.get_model('lib', 'UserParameter')
    for uparam in UserParameter.objects.filter(name='core.LANG'):
        uparam.user.language = uparam.value
        uparam.user.save()
        uparam.delete()


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def to_bytes(size, power=1024, sep=' '):
    """Converts human size to raw bytes."""
    if not size:
        return 0
    size, suffix = size.split(sep, 1)
    suffix = suffix[0]
    try:
        factor = {'K': power, 'M': power ** 2, 'G': power ** 3, 'T': power **
            4, 'P': power ** 5}[suffix]
    except KeyError:
        factor = 1
    return int(float(size) * factor)


def preset_add(name: str='', remove_active: bool=False, use_focal_length:
    bool=False):
    """Add or remove a Camera Preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_active: remove_active
    :type remove_active: bool
    :param use_focal_length: Include Focal Length, Include focal length into the preset
    :type use_focal_length: bool
    """
    pass


def parse_iterator_result(result):
    """Gets features, labels from result."""
    if isinstance(result, (list, tuple)):
        if len(result) != 2:
            raise ValueError(
                'input_fn should return (features, labels) as a len 2 tuple.')
        return result[0], result[1]
    return result, None


def print_detailed_segment_results(detailed_segment_results):
    """
    Print segment length for each detailed segment category. Can be used with normed values as well.

    Arguments:
        detailed_segment_results (dictionary): as provided by the 3rd or 4th item in the results of eval_segments function

    Example:
        >>> print_detailed_segment_results(test_r)
        Detailed segment results (length or frame count):
            true positive segments:		40
            true negative segments:		91
            insertion segments:			10
            deletion segments:			10
            fragmenting segments:		7
            merge segments:			15
            start overfill segments:		10
            end overfill segments:		28
            start underfill segments:		13
            end underfill segments:		15
    """
    print('Detailed segment results (length or frame count):')
    print('\ttrue positive segments:\t\t' + str(detailed_segment_results['TP'])
        )
    print('\ttrue negative segments:\t\t' + str(detailed_segment_results['TN'])
        )
    print('\tinsertion segments:\t\t\t' + str(detailed_segment_results['I']))
    print('\tdeletion segments:\t\t\t' + str(detailed_segment_results['D']))
    print('\tfragmenting segments:\t\t' + str(detailed_segment_results['F']))
    print('\tmerge segments:\t\t\t\t' + str(detailed_segment_results['M']))
    print('\tstart overfill segments:\t' + str(detailed_segment_results['Os']))
    print('\tend overfill segments:\t\t' + str(detailed_segment_results['Oe']))
    print('\tstart underfill segments:\t' + str(detailed_segment_results['Us'])
        )
    print('\tend underfill segments:\t\t' + str(detailed_segment_results['Ue'])
        )


def format_elapsed_time(seconds):
    """
    Format time difference as "#d ##:##:##".

    :param seconds: [float] time difference in seconds
    :return: [str] formatted time difference
    """
    n_seconds = round(seconds)
    n_days, n_seconds = divmod(n_seconds, 3600 * 24)
    n_hours, n_seconds = divmod(n_seconds, 3600)
    n_minutes, n_seconds = divmod(n_seconds, 60)
    return '{}d {:02}:{:02}:{:02}'.format(n_days, n_hours, n_minutes, n_seconds
        )


def find_end_of_continued_line(lines, start_line: int):
    """Find the last line of a line explicitly extended using backslashes.

    Uses 0-indexed line numbers.
    """
    end_line = start_line
    while lines[end_line].endswith('\\\n'):
        end_line += 1
        if end_line >= len(lines):
            break
    return end_line


def dated(zelf, *args, **kwargs):
    """ retrieve the creation time of an ding. """
    val = ''
    if 'Date' in zelf:
        val = zelf.Date
    elif 'date' in zelf:
        val = zelf.date
    elif 'published' in zelf:
        val = zelf.published
    elif 'added' in zelf:
        val = zelf.added
    elif 'saved' in zelf:
        val = zelf.saved
    elif 'timed' in zelf:
        val = zelf.timed
    return val


@classmethod
def _reshape(cls, dsShape, rank, extends, extraD, exDim):
    """ recalculates shape

        :param dsShape: origin shape of the object
        :type dsShape: :obj:`list` <:obj:`int` >
        :param rank: rank of the object
        :type rank: : obj:`str` or obj:`int`
        :param extends: If True extends the shape up to rank value
        :type extends: :obj:`bool`
        :param exDim: grows growing dimension + 1
        :type exDim: :obj:`int`
        :param extraD: True if the object grows
        :type extraD: :obj:`bool`
        :returns: shape of the  h5 field
        :rtype: :obj:`list` <:obj:`int` >

        """
    shape = []
    if dsShape:
        for s in dsShape:
            if s and extends:
                shape.append(s)
            elif not extends and s and s > 0:
                shape.append(s)
        while extends and len(shape) < int(rank):
            shape.append(0)
        if extraD:
            shape.insert(exDim - 1, 0)
    return shape


def full_to_half(s):
    """
    Convert full-width character to half-width one
    将全角字符转换为半角字符
    """
    n = []
    for char in s:
        num = ord(char)
        if num == 12288:
            num = 32
        elif 65281 <= num <= 65374:
            num -= 65248
        char = chr(num)
        n.append(char)
    return ''.join(n)


def isReadOnly():
    """Returns True if the storage for this connection is read only."""


@classmethod
def _serialize_keys(cls, hash_key, range_key=None):
    """
        Serializes the hash and range keys

        :param hash_key: The hash key value
        :param range_key: The range key value
        """
    hash_key = cls._hash_key_attribute().serialize(hash_key)
    if range_key is not None:
        range_key = cls._range_key_attribute().serialize(range_key)
    return hash_key, range_key


def payoff_call_fprime(underlying, strike, gearing=1.0):
    """payoff_call_fprime
    derivative of payoff of call option with respect to underlying.

    :param underlying:
    :param strike:
    :param gearing:
    :return: value of derivative with respect to underlying.
    :rtype: float
    """
    if underlying > strike:
        return gearing
    else:
        return 0.0


def count_common_subsequences(seq_1, seq_2):
    """Find the number of common subsequences between two collections.

    This function finds the number of common subsequences between two
    collections but does not return an actual listing of those subsequences.
    This is more space efficient O(len(seq_1)) than find_common_subsequences.

    > number_of_subsequences = count_common_subsequences('qwer', 'qewr')
    > print number_of_subsequences
    12

    @param seq_1: The first collection to find subsequences in.
    @type seq_1: Any integer indexable collection (list, tuple, etc.)
    @param seq_2: The second collection to find subsequences in.
    @type seq_2: Any integer indexable collection (list, tuple, etc.)
    @return: The number of common subsequences between seq_1 and seq_2.
    @rtype: int
    """
    if len(seq_1) < len(seq_2):
        new_seq_1 = seq_2
        seq_2 = seq_1
        seq_1 = new_seq_1
    seq_1_len = len(seq_1)
    seq_2_len = len(seq_2)
    seq_1_len_plus_1 = seq_1_len + 1
    seq_2_len_plus_1 = seq_2_len + 1
    subseq_last_row = [1] * seq_2_len_plus_1
    subseq_current_row = [1] + [0] * seq_2_len
    for row in range(1, seq_1_len_plus_1):
        for col in range(1, seq_2_len_plus_1):
            if seq_1[row - 1] == seq_2[col - 1]:
                new_cell_value = 2 * subseq_last_row[col - 1]
            else:
                new_cell_value = subseq_last_row[col]
                new_cell_value += subseq_current_row[col - 1]
                new_cell_value -= subseq_last_row[col - 1]
            subseq_current_row[col] = new_cell_value
        subseq_last_row = subseq_current_row
        subseq_current_row = [1] + [0] * seq_2_len
    return subseq_last_row[seq_2_len]


@staticmethod
def deposit(data, *args, **kwargs):
    """
        Returns deposit address as str
        :param data: requests.response() obj
        :param args:
        :param kwargs:
        :return: str
        """
    return data


@classmethod
def WithData(cls, original_exc, model, fk, field_value):
    """
        Factory method for creating a deserialization error which has a more
        explanatory message.
        """
    return cls("%s: (%s:pk=%s) field_value was '%s'" % (original_exc, model,
        fk, field_value))


@staticmethod
def le_bytes_to_num(data):
    """Convert a number from little endian byte format"""
    ret = 0
    for i in range(len(data) - 1, -1, -1):
        ret <<= 8
        ret += data[i]
    return ret


@classmethod
def __initsubclass__(cls, subclass):
    """Called when MorpheusDict has been subclassed"""
    pass


def ladne_numery_prac(arr):
    """Wyświetla ładne numery prac, tzn. tablicę [1, 2, 5, 6, 7, 8, 12]
    przerobi na 1-2, 5-8, 12

    Filtr wykorzystywany do wyświetlania numerków prac w Kronice Uczelni
    """
    nu = list(arr)
    nu.sort()
    if not nu:
        return ''
    buf = str(nu[0])
    last_elem = nu[0]
    cont = False
    for elem in nu[1:]:
        if elem == last_elem + 1:
            last_elem = elem
            cont = True
            continue
        if cont:
            buf += '-' + str(last_elem) + ', ' + str(elem)
        else:
            buf += ', ' + str(elem)
        last_elem = elem
        cont = False
    if cont:
        buf += '-' + str(last_elem)
    return buf


def suppress_setattr(obj, attr, value, filter_none=False):
    """
    Set an attribute, suppressing any exceptions and skipping the attempt on failure.

    :param Any obj: Object to set the attribute on
    :param str attr: The attribute name to set
    :param Any value: The value to set the attribute to
    :param bool filter_none: [description], defaults to False
    :return: Nothing
    :rtype: None

    :Example:

    >>> class MyClass(object):
    ...     def __init__(self, name):
    ...         self.name = name
    ...         self.parent = None
    ...     def __repr__(self):
    ...         return "<{0!r} instance (name={1!r}, parent={2!r})>".format(
    ...             self.__class__.__name__, self.name, self.parent
    ...         )
    ...     def __str__(self):
    ...         return self.name
    >>> me = MyClass("Dan")
    >>> dad = MyClass("John")
    >>> grandfather = MyClass("Joe")
    >>> suppress_setattr(dad, "parent", grandfather)
    >>> dad
    <'MyClass' instance (name='John', parent=<'MyClass' instance (name='Joe', parent=None
    )>)>
    >>> suppress_setattr(me, "parent", dad)
    >>> me
    <'MyClass' instance (name='Dan', parent=<'MyClass' instance (name='John', parent=<'My
    Class' instance (name='Joe', parent=None)>)>)>
    >>> suppress_setattr(me, "grandparent", grandfather)
    >>> me
    <'MyClass' instance (name='Dan', parent=<'MyClass' instance (name='John', parent=<'My
    Class' instance (name='Joe', parent=None)>)>)>
    """
    if filter_none and value is None:
        pass
    try:
        setattr(obj, attr, value)
    except Exception:
        pass


@classmethod
def _fromInputHandlerProxy(cls, input_handler_proxy):
    """
        Internal Constructor to wrap around JAVA Class InputHandler
        :param input_handler_proxy:
        :return:
        """
    instance = cls.__new__(cls)
    instance.input_handler_proxy = input_handler_proxy
    return instance


def add_pen_up_moves(segments):
    """
    Takes a list of pen-down segments. Returns a list of (segment, pen_up)
    tuples, with additional segments added that pen-up move between segments.
    Also add segments at the beginning and end to do pen-up moves from and to
    the origin location.

    The output list should thus always have 2n+1 elements, where n is the
    length of the input list.
    """
    assert segments
    origin = 0, 0
    out_segments = []
    start_seg = [origin, segments[0][0]]
    out_segments.append((start_seg, True))
    count = len(segments)
    for n, seg in enumerate(segments, start=1):
        assert seg
        out_segments.append((seg, False))
        if n == count:
            next_seg_start = origin
        else:
            next_seg_start = segments[n][0]
        inter_seg = [seg[-1], next_seg_start]
        out_segments.append((inter_seg, True))
    return out_segments


def index_next_crossing(value, array, starting_index=0, direction=1):
    """
    starts at starting_index, and walks through the array until
    it finds a crossing point with value

    set direction=-1 for down crossing
    """
    for n in range(starting_index, len(array) - 1):
        if (value - array[n]) * direction >= 0 and (value - array[n + 1]
            ) * direction < 0:
            return n
    return -1


def websocket_recv(request_context=None):
    """Receives data from websocket.

    :param request_context:

    :rtype: bytes|str

    :raises IOError: If unable to receive a message.
    """


def moveField(field_name, new_pos):
    """ Move a field to the (new_pos)th position in the schema's sort ç
        order (indexed beginning at 0).

        Schema fields are assigned an 'order' attribute that increments for
        each new field instance.
        We shuffle these around in case it matters anywhere that they're
        unique.
        """


def offset(image, xoffset, yoffset=None):
    """Returns a copy of the image where data has been offset by the given
    distances. Data wraps around the edges. If **yoffset** is omitted, it
    is assumed to be equal to **xoffset**.

    :param xoffset: The horizontal distance.
    :param yoffset: The vertical distance.  If omitted, both
        distances are set to the same value.
    :rtype: :py:class:`~PIL.Image.Image`
    """
    if yoffset is None:
        yoffset = xoffset
    image.load()
    return image._new(image.im.offset(xoffset, yoffset))


@classmethod
def resolve(cls, accept, available_renderers):
    """
        Resolves a list of accepted MediaTypes and available renderers to the preferred renderer.

        Call as MediaType.resolve([MediaType], [renderer]).
        """
    assert isinstance(available_renderers, tuple)
    accept = sorted(accept)
    renderers, seen = [], set()
    accept_groups = [[accept.pop()]]
    for imt in accept:
        if imt.equivalent(accept_groups[-1][0]):
            accept_groups[-1].append(imt)
        else:
            accept_groups.append([imt])
    for accept_group in accept_groups:
        for renderer in available_renderers:
            if renderer in seen:
                continue
            for mimetype in renderer.mimetypes:
                for imt in accept_group:
                    if mimetype.provides(imt):
                        renderers.append(renderer)
                        seen.add(renderer)
                        break
    return renderers


@classmethod
def commit(cls):
    """
        Commit current configuration, this will:
            - Unmark updated objects
            - Unmark new objects
            - Completely delete objects mark as deleted
        """
    cls.objects.deleted().true_delete()
    cls.objects.changed().true_update(_new=False, _changed=False)


def lateral_shift(transform, shift):
    """Makes a lateral shift of the forward vector of a transform"""
    transform.rotation.yaw += 90
    return transform.location + shift * transform.get_forward_vector()


@staticmethod
def add_force_flaky_options(add_option):
    """
        Add options to the test runner that force all tests to be flaky.

        :param add_option:
            A function that can add an option to the test runner.
            Its argspec should equal that of argparse.add_option.
        :type add_option:
            `callable`
        """
    add_option('--force-flaky', action='store_true', dest='force_flaky',
        default=False, help=
        'If this option is specified, we will treat all tests as flaky.')
    add_option('--max-runs', action='store', dest='max_runs', type=int,
        default=2, help=
        'If --force-flaky is specified, we will run each test at most this many times (unless the test has its own flaky decorator).'
        )
    add_option('--min-passes', action='store', dest='min_passes', type=int,
        default=1, help=
        'If --force-flaky is specified, we will run each test at least this many times (unless the test has its own flaky decorator).'
        )


def _id():
    """Infinite generator for unique request IDs"""
    index = 0
    while 1:
        yield index
        index += 1


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


def log_msgs(process, response, quiet=False):
    """
    Log messages to `logger`

    `msgs` is an iterable of strings or exceptions.  Strings are logged to
    level INFO, exceptions are logged to level ERROR.

    If `quiet` evaluates to True, INFO messages are not logged.
    """
    if not quiet:
        for msg in response.msgs:
            process.info(msg)
    for error in response.errors:
        process.error(error)


def _get_responses(link):
    """
    Returns minimally acceptable responses object based
    on action / method type.
    """
    template = {'description': ''}
    if link.action.lower() == 'post':
        return {'201': template}
    if link.action.lower() == 'delete':
        return {'204': template}
    return {'200': template}


def take(data, indices, dim):
    """Takes elements from an input array along the given dim.

    Parameters
    ----------
    data : Tensor
        The data tensor.
    indices : Tensor
        The indices tensor.
    dim : Tensor
        The dimension to gather along.
    """
    pass


def _rec_to_ndarr(rec_arr, data_type=float):
    """
    Function to transform a numpy record array to a nd array.
    """
    return rec_arr.view((data_type, len(rec_arr.dtype.names)))


def image_to_image_filter(*args, **kwargs):
    """Procedural interface for ImageToImageFilter"""
    import itk
    instance = itk.ImageToImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


def sanitize_classifiers(classifiers: list, python_version_min_parts: tuple,
    python_version_minor_max: int) ->list:
    """
    List of all PyPI-specific trove classifier strings synopsizing this
    application, manufactured by appending classifiers synopsizing this
    application's support for Python major versions (e.g.,
    ``Programming Language :: Python :: 3.6``, a classifier implying this
    application to successfully run under Python 3.6) to the passed list.

    Parameters
    ----------
    classifiers : list
        List of all PyPI-specific trove classifier strings to be sanitized.
    python_version_min_parts : tuple
        Minimum fully-specified version of Python required by this application
        as a tuple of integers (e.g., ``(3, 5, 0)`` if this application
        requires at least Python 3.5.0).
    python_version_minor_max : int
        Maximum minor stable version of the current Python 3.x mainline (e.g.,
        ``9`` if Python 3.9 is the most recent stable version of Python 3.x).

    Returns
    ----------
    list
        List of all sanitized PyPI-specific trove classifier strings.
    """
    assert isinstance(classifiers, list), '"{}" not a list.'.format(classifiers
        )
    assert isinstance(python_version_min_parts, tuple
        ), '"{}" not a tuple.'.format(python_version_min_parts)
    assert isinstance(python_version_minor_max, int
        ), '"{}" not an integer.'.format(python_version_minor_max)
    PYTHON_VERSION_MAJOR = python_version_min_parts[0]
    classifiers_sane = classifiers[:]
    for python_version_minor in range(python_version_min_parts[1],
        python_version_minor_max):
        classifiers.append('Programming Language :: Python :: {}.{}'.format
            (PYTHON_VERSION_MAJOR, python_version_minor))
    return classifiers_sane


def cleanString(name):
    """ This function clears the given name from special characters """
    for character in '*."/\\[]:;|, ':
        name = name.replace(character, '')
    return name


def stream_out():
    """Obtain streaming clone data.

        Successful result should be a generator of data chunks.
        """


def normalize_time(timestamp):
    """Normalize time in arbitrary timezone to UTC naive object."""
    offset = timestamp.utcoffset()
    if offset is None:
        return timestamp
    return timestamp.replace(tzinfo=None) - offset


def bisect_df(df, v, col='variable_name_nd'):
    """Perform a binary search on a dataframe"""
    from math import log
    max_n = log(len(df)) / log(2) + 2
    low = 0
    high = len(df)
    mid = int((low + high) / 2)
    n = 0
    while True:
        e = df.iloc[mid]
        if v == e[col]:
            return e
        if v > e[col]:
            low = mid
        else:
            high = mid
        mid = int((low + high) / 2)
        if n > max_n:
            return None
        n += 1
    return None


def gprmc_to_degdec(lat, latDirn, lng, lngDirn):
    """Converts GPRMC formats (Decimal Minutes) to Degrees Decimal."""
    x = float(lat[0:2]) + float(lat[2:]) / 60
    y = float(lng[0:3]) + float(lng[3:]) / 60
    if latDirn == 'S':
        x = -x
    if lngDirn == 'W':
        y = -y
    return x, y


def set_cookie(name, value='', max_age=None, path='/', domain=None, secure=
    False, httponly=False, comment=None, expires=None, overwrite=False):
    """ Set (add) a cookie for the response """


def update_track_tags(fileinfo, release):
    """Return True if the track tags were changed."""
    changed = False
    for track in release['media'][0]['tracks']:
        track_number = track['number']
        tags = fileinfo.tags.track_tags(track_number)
        tags['TITLE'] = track['title']
        if 'artist' in track:
            tags['ARTIST'] = track['artist']
        if fileinfo.tags.update_track(track_number, tags):
            changed = True
    return changed


def _byte_to_int_python3(byte):
    """Converts a byte to a int for python 3."""
    return byte


def read_psd(psd_file, df):
    """Read in a psd file

    Parameters
    ----------
    strain: dict
        dictionary containing the psds for each detector
    df: float
        df to use when reading in the psd_file

    Returns
    -------
    psd_data: pycbc.frequencyseries.FrequencySeries
        data stored in the psd file
    """
    from pycbc.psd.read import from_txt
    return from_txt(psd_file, int(1024.0 / df) + 1, df, 20, is_asd_file=False)


def is_calibrated() ->bool:
    """Returns ``True`` if the compass has been successfully calibrated, and
    returns ``False`` otherwise.
    """


def random_layout(G, dim=2, scale=1.0, center=None):
    """Position nodes uniformly at random.

    For every node, a position is generated by choosing each of dim
    coordinates uniformly at random on the default interval [0.0, 1.0),
    or on an interval of length `scale` centered at `center`.

    NumPy (http://scipy.org) is required for this function.

    Parameters
    ----------
    G : NetworkX graph or list of nodes
       A position will be assigned to every node in G.

    dim : int
       Dimension of layout.

    scale : float (default 1)
        Scale factor for positions

    center : array-like (default scale*0.5 in each dim)
       Coordinate around which to center the layout.

    Returns
    -------
    pos : dict
       A dictionary of positions keyed by node

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> pos = nx.random_layout(G)
    """
    import numpy as np
    shape = len(G), dim
    pos = np.random.random(shape) * scale
    if center is not None:
        pos += np.asarray(center) - 0.5 * scale
    return dict(zip(G, pos))


def union(a, b):
    """ Return a list of items that are in `a` or `b`
    """
    u = []
    for item in a:
        if item not in u:
            u.append(item)
    for item in b:
        if item not in u:
            u.append(item)
    return u


def checkURL(cls, trust_root, url):
    """quick func for validating a url against a trust root.  See the
        TrustRoot class if you need more control."""
    tr = cls.parse(trust_root)
    return tr is not None and tr.validateURL(url)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a LanguageModel object from a json dictionary."""
    args = {}
    if 'customization_id' in _dict:
        args['customization_id'] = _dict.get('customization_id')
    else:
        raise ValueError(
            "Required property 'customization_id' not present in LanguageModel JSON"
            )
    if 'created' in _dict:
        args['created'] = _dict.get('created')
    if 'language' in _dict:
        args['language'] = _dict.get('language')
    if 'dialect' in _dict:
        args['dialect'] = _dict.get('dialect')
    if 'versions' in _dict:
        args['versions'] = _dict.get('versions')
    if 'owner' in _dict:
        args['owner'] = _dict.get('owner')
    if 'name' in _dict:
        args['name'] = _dict.get('name')
    if 'description' in _dict:
        args['description'] = _dict.get('description')
    if 'base_model_name' in _dict:
        args['base_model_name'] = _dict.get('base_model_name')
    if 'status' in _dict:
        args['status'] = _dict.get('status')
    if 'progress' in _dict:
        args['progress'] = _dict.get('progress')
    if 'error' in _dict:
        args['error'] = _dict.get('error')
    if 'warnings' in _dict:
        args['warnings'] = _dict.get('warnings')
    return cls(**args)


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

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


@staticmethod
def __default_callback(element):
    """
        Default callback when no callback is given in init method
        :param element: osm object
        """
    print(str(element))


@classmethod
def reset(cls):
    """Clears the API functions list so it will be reloaded from the server."""
    cls._api = None
    cls._bound_signatures = set()


def geomean(iterable):
    """
    Returns the geometric mean (the n-th root of the product of n terms) of an iterable
    """
    n = 0
    first_item = True
    for x in iterable:
        n += 1
        if first_item:
            product = x
            first_item = False
        else:
            product *= x
    return product ** (1 / float(n))


def Fourar_Bories(x, mul, mug, rhol, rhog):
    """Calculates a suggested definition for liquid-gas two-phase flow
    viscosity in internal pipe flow according to the form in [1]_ and shown
    in [2]_ and [3]_.

    .. math::
        \\mu_m = \\rho_m\\left(\\sqrt{x\\nu_g} + \\sqrt{(1-x)\\nu_l}\\right)^2

    Parameters
    ----------
    x : float
        Quality of the gas-liquid flow, [-]
    mul : float
        Viscosity of liquid, [Pa*s]
    mug : float
        Viscosity of gas, [Pa*s]
    rhol : float
        Density of the liquid, [kg/m^3]
    rhog : float
        Density of the gas, [kg/m^3]

    Returns
    -------
    mu_lg : float
        Liquid-gas viscosity (**a suggested definition, potentially useful
        for empirical work only!**) [Pa*s]

    Notes
    -----
    This model converges to the liquid or gas viscosity as the quality
    approaches either limits.

    This was first expressed in the equalivalent form as follows:

    .. math::
        \\mu_m = \\rho_m\\left(x\\nu_g + (1-x)\\nu_l + 2\\sqrt{x(1-x)\\nu_g\\nu_l}
        \\right)

    Examples
    --------
    >>> Fourar_Bories(x=0.4, mul=1E-3, mug=1E-5, rhol=850, rhog=1.2)
    2.127617150298565e-05

    References
    ----------
    .. [1] Fourar, M., and S. Bories. "Experimental Study of Air-Water
       Two-Phase Flow through a Fracture (Narrow Channel)." International
       Journal of Multiphase Flow 21, no. 4 (August 1, 1995): 621-37.
       doi:10.1016/0301-9322(95)00005-I.
    .. [2] Awad, M. M., and Y. S. Muzychka. "Effective Property Models for
       Homogeneous Two-Phase Flows." Experimental Thermal and Fluid Science 33,
       no. 1 (October 1, 2008): 106-13.
    .. [3] Aung, NZ, and T. Yuwono. "Evaluation of Mixture Viscosity Models in
       the Prediction of Two-Phase Flow Pressure Drops." ASEAN Journal on
       Science and Technology for Development 29, no. 2 (2012).
    """
    rhom = 1.0 / (x / rhog + (1.0 - x) / rhol)
    nul = mul / rhol
    nug = mug / rhog
    return rhom * ((x * nug) ** 0.5 + ((1.0 - x) * nul) ** 0.5) ** 2


def cuboid(target, throat_diameter='throat.diameter', throat_length=
    'throat.length'):
    """
    Calculate surface area for a cuboid throat

    Parameters
    ----------
    target : OpenPNM Object
        The object which this model is associated with. This controls the
        length of the calculated array, and also provides access to other
        necessary properties.

    throat_diameter : string
        Dictionary key to the throat diameter array.  Default is
        'throat.diameter'.

    throat_length : string
        Dictionary key to the throat length array.  Default is 'throat.length'.

    Returns
    -------
    value : NumPy ndarray
        Array containing throat surface area values.

    """
    return 4 * target[throat_diameter] * target[throat_length]


@classmethod
def is_dtype(cls, dtype) ->bool:
    """
        Return a boolean if we if the passed type is an actual dtype that we
        can match (via string or type)
        """
    if isinstance(dtype, str):
        if dtype.startswith('period[') or dtype.startswith('Period['):
            try:
                if cls._parse_dtype_strict(dtype) is not None:
                    return True
                else:
                    return False
            except ValueError:
                return False
        else:
            return False
    return super().is_dtype(dtype)


@classmethod
def check_observability(cls, targetid, epochs, observatory):
    """Check observability for specific target, given epochs, and
        observatory

        Parameters
        ----------
        targetid : str, mandatory
            target identifier
        epochs : `astropy.time` instance or list thereof, mandatory
            date to check observability
        observatory : str, mandatory
            MPC observatory code

        Returns
        -------
        `astropy.table`

        Examples
        --------
        >>> from sbpy.obsutil import Obsutil # doctest: +SKIP
        >>> from astropy.time import Time # doctest: +SKIP
        >>> epochs = [Time('2018-05-23 23:00', scale='utc'), # doctest: +SKIP
                      Time('2018-05-25 04:30', scale='utc'] # doctest: +SKIP
        >>> obs = Obsutil.check_observability('3552', epochs, '568') # doctest: +SKIP

        not yet implemented

        """


def build_role(uid, scu_role=False, scp_role=False):
    """Return a SCP/SCU Role Selection Negotiation item.

    Parameters
    ----------
    uid : str or UID or sop_class.SOPClass
        The UID or SOPClass instance to use as the *SOP Class UID* parameter
        value.
    scu_role : bool, optional
        True to propose the SCU role for the *Requestor*, False otherwise
        (default).
    scp_role : bool, optional
        True to propose the SCP role for the *Requestor*, False otherwise
        (default).

    Returns
    -------
    pdu_primitives.SCP_SCU_RoleSelectionNegotiation
        The role selection item.
    """
    from pynetdicom.pdu_primitives import SCP_SCU_RoleSelectionNegotiation
    role = SCP_SCU_RoleSelectionNegotiation()
    role.sop_class_uid = uid
    role.scu_role = scu_role
    role.scp_role = scp_role
    return role


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

        :param ApiSessionLogInfo val:
        :rtype: AccessMethodLogInfo
        """
    return cls('api', val)


def camel_case(string):
    """Makes a string camelCase

    :param string: String to convert
    """
    return ''.join((string[0].lower(), string[1:]))


@classmethod
def near(cls, collection, latitude, longitude, index_id, distance=None,
    skip=None, limit=None):
    """
            The default will find at most 100 documents near the given coordinate.
            The returned list is sorted according to the distance, with the nearest document being first in the list.
            If there are near documents of equal distance, documents are chosen randomly from this set until
            the limit is reached.

            In order to use the near operator, a geo index must be defined for the collection.
            This index also defines which attribute holds the coordinates for the document.
            If you have more then one geo-spatial index, you can use the geo field to select a particular index.

            :param collection Collection instance
            :param latitude The latitude of the coordinate
            :param longitude The longitude of the coordinate
            :param index_id ID of the index which should be used for the query

            :param distance If given, the attribute key used to return the distance to the given coordinate.
            If specified, distances are returned in meters.

            :param skip  The number of documents to skip in the query
            :param limit The maximal amount of documents to return. The skip is applied before the limit restriction.

            :returns Document list
        """
    kwargs = {'geo': index_id, 'latitude': latitude, 'longitude': longitude,
        'distance': distance, 'skip': skip, 'limit': limit}
    return cls._construct_query(name='near', collection=collection,
        multiple=True, **kwargs)


@staticmethod
def sanitize(payload):
    """
        Sanitize raw input payload to make decoding not croak.

        >>> BERadioProtocolBase().sanitize('hello_message\\0\\r\\n ')
        'hello_message'
        """
    return payload.strip('\x00\r\n ')


@classmethod
def _load_mx_exceptions(cls):
    """ Import mxODBC exception classes into the module namespace,
        as if they had been imported normally. This is done here
        to avoid requiring all SQLAlchemy users to install mxODBC.
        """
    global InterfaceError, ProgrammingError
    from mx.ODBC import InterfaceError
    from mx.ODBC import ProgrammingError


@classmethod
def common_prefix(cls, prefix, key):
    """Given 2 strings, return the longest prefix common to both.

        :param prefix: This has been the common prefix for other keys, so it is
            more likely to be the common prefix in this case as well.
        :param key: Another string to compare to
        """
    if key.startswith(prefix):
        return prefix
    pos = -1
    for pos, (left, right) in enumerate(zip(prefix, key)):
        if left != right:
            pos -= 1
            break
    common = prefix[:pos + 1]
    return common


def _symbolic_rotation_helper():
    """Use SymPy to generate the 3D rotation matrix and products for diffusion_stencil_3d."""
    from sympy import symbols, Matrix
    cpsi, spsi = symbols('cpsi, spsi')
    cth, sth = symbols('cth, sth')
    cphi, sphi = symbols('cphi, sphi')
    Rpsi = Matrix([[cpsi, spsi, 0], [-spsi, cpsi, 0], [0, 0, 1]])
    Rth = Matrix([[1, 0, 0], [0, cth, sth], [0, -sth, cth]])
    Rphi = Matrix([[cphi, sphi, 0], [-sphi, cphi, 0], [0, 0, 1]])
    Q = Rpsi * Rth * Rphi
    epsy, epsz = symbols('epsy, epsz')
    A = Matrix([[1, 0, 0], [0, epsy, 0], [0, 0, epsz]])
    D = Q * A * Q.T
    for i in range(3):
        for j in range(3):
            print('D[%d, %d] = %s' % (i, j, D[i, j]))


@classmethod
def inject(cls, span, obj):
    """ Injects the span context into a `carrier` object.

        :param opentracing.span.SpanContext span: the SpanContext instance
        :param Any obj: Object to use as context
        """
    obj.metadata['__parent-span__'] = dict()
    cls.inject_span(span, obj.metadata['__parent-span__'])


def cfg_section(config, section):
    """Return the configuration section if present, else an empty dict"""
    return config[section] if section in config else {}


def dataFromFile(file):
    """Loads the ``.txt`` file with all second-order tensors components.

    Parameters:
        file (`str`): ``txt`` file tabulated with tabular spaces as delimiter.
            The file is structured as a :math:`(n \\times 6)` array, where
            :math:`n` is the number of tensors and each row contains the
            vector form with the 6 components of a tensor in the following
            order :math:`t_{11}, t_{22}, t_{33}, t_{12}, t_{23}, t_{13}`.

    Returns:
        Two elements are returned; they are described below.

            - **sample** (`numpy.ndarray`): :math:`(n \\times 6)` array                that contains the same values than the ``.txt`` file.
            - **numTensors** (`int`): Number of tensors.

    Examples:
        >>> from jelinekstat.tools import dataFromFile
        >>> sample, numTensors = dataFromFile('inputDataExample.txt')
        >>> sample
        array([[ 1.02327,  1.02946,  0.94727, -0.01495, -0.03599, -0.05574],
               [ 1.02315,  1.01803,  0.95882, -0.00924, -0.02058, -0.03151],
               [ 1.02801,  1.03572,  0.93627, -0.03029, -0.03491, -0.06088],
               [ 1.02775,  1.00633,  0.96591, -0.01635, -0.04148, -0.02006],
               [ 1.02143,  1.01775,  0.96082, -0.02798, -0.04727, -0.02384],
               [ 1.01823,  1.01203,  0.96975, -0.01126, -0.02833, -0.03649],
               [ 1.01486,  1.02067,  0.96446, -0.01046, -0.01913, -0.03864],
               [ 1.04596,  1.01133,  0.94271, -0.0166 , -0.04711, -0.03636]])
        >>> numTensors
        8
    """
    import numpy as np
    sample = np.loadtxt(file)
    numTensors = int(np.shape(sample)[0])
    return sample, numTensors


@classmethod
def create(cls, **kwargs):
    """Create an instance of the associated class, with overriden attrs."""
    visibility = kwargs.pop('visibility', [])
    instance = super().create(**kwargs)
    if visibility:
        visibility_related = instance.get_visibility_relation()
        visibility_related.visibility = visibility
        visibility_related.save(update_fields=['visibility'])
    return instance


def is_quote(ch: str):
    """Check if given character code is a quote character"""
    return ch == '"' or ch == "'"


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_thumbnail_size(image_size, thumbnail_height):
    """
    Computes the size of a thumbnail
    :param image_size: original image size
    :param thumbnail_height: thumbnail height
    :return: thumbnail size tuple
    """
    width = round(float(thumbnail_height) / image_size[1] * image_size[0])
    return width, thumbnail_height


def getID():
    """Return the BuildSet's ID string, if any. The 'try' feature uses a
        random string as a BuildSetID to relate submitted jobs with the
        resulting BuildSet."""


def require_not_none(*values):
    """
    Checks that the specified objects references is not None and throws a
    :py:class:`ValueError` if it is.

    :param values: The objects.
    :type values: list(object)
    """
    for value in values:
        if value is None:
            raise ValueError()


def edge_split(edge: 'bmesh.types.BMEdge', vert: 'bmesh.types.BMVert', fac:
    float):
    """Split an edge, return the newly created data.

    :param edge: The edge to split.
    :type edge: 'bmesh.types.BMEdge'
    :param vert: One of the verts on the edge, defines the split direction.
    :type vert: 'bmesh.types.BMVert'
    :param fac: The point on the edge where the new vert will be created [0 - 1].
    :type fac: float
    :return:  The newly created (edge, vert) pair.
    """
    pass


def _idx_range(arr, a, b):
    """Returns a boolean array which is True where arr is between
    a and b.

    Parameters
    ----------
    arr : array
        Array to find the range in.
    a : float
        First edge of the region.
    b : float
        Second edge of the region.

    Returns
    -------
    : arr of bool
        The resulting boolean array
    """
    lower, upper = sorted([a, b])
    idx = (lower < arr) & (arr < upper)
    return idx


def do_OP_SWAP(stack):
    """
    >>> s = [1, 2, 3]
    >>> do_OP_SWAP(s)
    >>> print(s)
    [1, 3, 2]
    """
    stack.append(stack.pop(-2))


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


@staticmethod
def create_all_recipe(tmp_dir, filename, group='allnowindows', suffix=
    '_all.yml'):
    """
        Create the recipe "all" enabling to access all the ansible variables from all hosts
        Arguments:
           - tmp_dir(str): Temp directory where all the playbook files will be stored.
           - filename(str): name of he yaml to include (without the extension)
        """
    all_filename = filename + suffix
    conf_all_out = open(tmp_dir + '/' + all_filename, 'w')
    conf_all_out.write('---\n')
    conf_all_out.write('- hosts: ' + group + '\n')
    conf_all_out.write('- include: ' + filename + '.yml\n')
    conf_all_out.write('\n\n')
    conf_all_out.close()
    return all_filename


def ensure_hashtag(text):
    """Ensure that `text` begins with '#'."""
    if len(text) is 0:
        return '#' + text
    if text[0] == '#':
        return text
    return '#' + text


def Stack():
    """Return an empty list, suitable as a Last-In-First-Out Queue."""
    return []


def volume_view(bar, ch_trend, num_bar):
    """Retorna a view com os volumes."""
    return '%s %s %s %i' % (num_bar, ch_trend, bar.trend, bar.volume)


def _neq_attr(node, attr, gens, container):
    """
    Calcs fitness based on the fact that node's target shall not have an attr
    with a certain value.
    """
    trg_nd = container.nodes[gens[node]]
    if attr[0] in trg_nd and attr[1] == trg_nd[attr[0]]:
        return 10.1
    return 0.0


@classmethod
def resolve_dependencies(cls, job_list, visit_list=None):
    """
        Solve the dependency graph expressed as a list of job definitions.

        :param list job_list: list of known jobs
        :param list visit_list: (optional) list of jobs to solve

        The visit_list, if specified, allows to consider only a part of the
        graph while still having access and knowledge of all jobs.

        :returns list: the solution (a list of jobs to execute in order)
        :raises DependencyDuplicateError:
            if a duplicate job definition is present
        :raises DependencyCycleError:
            if a cyclic dependency is present.
        :raises DependencyMissingErorr:
            if a required job does not exist.
        """
    return cls(job_list)._solve(visit_list)


def match_movie_length():
    """Set image’s user’s length to the one of this video

    """
    pass


@staticmethod
def _inflect_verb(verb_morph):
    """
        Change the form of the verb to correlate with the beginning of the joke
        """
    tense = verb_morph.tag.tense
    inflected_verb_morph = verb_morph.inflect({'VERB', 'femn'}
        ) if tense == 'past' else verb_morph.inflect({'VERB', 'sing',
        '3per', tense}) if tense else None
    return inflected_verb_morph


def log_function_call(log_ref, func_name, extra=None):
    """
    Logs that we have reached func_name in the application
    Can log 'extra' information as well if specified
    Helpful in debugging 500 errors on routes and logging entry to any particular function
    """
    log_ref.info('DEBUG_FUNC -- Entering view config: %s' % func_name)
    if extra:
        log_ref.info('DEBUG_FUNC -- Extra info: %s' % extra)


@classmethod
def cfr(cls, *args):
    """Return a Layer entry in the appropriate namespace"""
    return cls('cfr', *args)


@staticmethod
def _find_permutations(top_partitions, bottom_partitions):
    """
        Return the pairs of top/bottom partitions where the partitions are
        different. Ensures that all partitions in both top and bottom
        partitions have size 1.
        """
    permutations = set()
    for top, bot in zip(top_partitions, bottom_partitions):
        if len(top) != 1 or len(bot) != 1:
            raise IndexError(
                'Not all nodes are coupled. This is impossible: {}, {}'.
                format(top_partitions, bottom_partitions))
        if top != bot:
            permutations.add(frozenset((next(iter(top)), next(iter(bot)))))
    return permutations


def is_comment(string):
    """Check wether a string is a comment (starts with #...).

    :param string: The string to be tested.

    :Example:

    >>> from pygtftk.utils import is_comment
    >>> assert is_comment("#bla")

    """
    return string.startswith('#')


def flux(data, segmap, source):
    """
    Total flux in segmap.

    Parameters
    ----------

    Returns
    -------

    """
    return {'flux': source.get_data(data=data, segmap=segmap).sum()}


def _some_atoms_left(tokens, atoms, natoms):
    """
    Return True if the token list expected to contain atoms.

    If the number of atoms is known before hand, then the function compares the
    number of already found atoms to the expected number. If the '--' token if
    found, it is removed from the token list and there is no atom left.

    Parameters
    ----------
    tokens: collections.deque[str]
        Deque of token to inspect. The deque **can be modified** in place.
    atoms: list
        List of already found atoms.
    natoms: int or None
        The number of expected atoms if known, else None.

    Returns
    -------
    bool
    """
    if not tokens:
        return False
    if tokens and tokens[0] == '--':
        tokens.popleft()
        return False
    if natoms is not None and len(atoms) >= natoms:
        return False
    return True


def relu(attrs, inputs, cls):
    """Computes rectified linear function."""
    return 'relu', attrs, inputs


def _module_repr_from_spec(spec):
    """Return the repr to use for the module."""
    name = '?' if spec.name is None else spec.name
    if spec.origin is None:
        if spec.loader is None:
            return '<module {!r}>'.format(name)
        else:
            return '<module {!r} ({!r})>'.format(name, spec.loader)
    elif spec.has_location:
        return '<module {!r} from {!r}>'.format(name, spec.origin)
    else:
        return '<module {!r} ({})>'.format(spec.name, spec.origin)


def describe_time_to_live(TableName=None):
    """
    Gives a description of the Time to Live (TTL) status on the specified table.
    See also: AWS API Documentation

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

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

    :rtype: dict
    :return: {
        'TimeToLiveDescription': {
            'TimeToLiveStatus': 'ENABLING'|'DISABLING'|'ENABLED'|'DISABLED',
            'AttributeName': 'string'
        }
    }

    """
    pass


@classmethod
def walk(cls, through_document_fields=False, visited_documents=frozenset()):
    """
        Iterates recursively over the fields of the document, resolving
        occurring :class:`resolvables <.Resolvable>` to their all possible values.

        Visits fields in a DFS order.

        :param bool through_document_fields:
            If ``True``, walks through nested :class:`.DocumentField` fields.
        :param set visited_documents:
            Keeps track of visited :class:`documents <.Document>` to avoid infinite
            recursion when ``through_document_field`` is ``True``.
        :returns: iterable of :class:`.BaseField`
        """
    fields = cls._backend.walk(through_document_fields=
        through_document_fields, visited_documents=visited_documents)
    next(fields)
    return fields


def str2int(inp):
    """
    Convert a set number of columns to integer, or returns None.

    Parameters
    ----------
    inp : str
        string with a list of floats in it

    Returns
    -------
    output : float
        all columns returned as integers
    """
    if inp.strip() == '':
        return None
    return int(inp)


def squareroot(attrs, inputs, proto_obj):
    """Returns element-wise square-root value of the input."""
    return 'sqrt', attrs, inputs


def get_logging_options():
    """
    Gets the logging options.
    See also: AWS API Documentation

    :example: response = client.get_logging_options()

    :rtype: dict
    :return: {
        'roleArn': 'string',
        'logLevel': 'DEBUG'|'INFO'|'ERROR'|'WARN'|'DISABLED'
    }

    """
    pass


def check_snp_reference(snp, ref, flip):
    """Utility function to check if a snp has the correct reference allele.

    :param snp: The :py:class:`gepyto.structures.variants.SNP` object.
    :type snp: :py:class:`gepyto.structures.variants.SNP`

    :param ref: The :py:class:`Reference` reference object.
    :type ref: :py:class:`Reference`

    :param flip: A flag. If True, the return value is a variant with alleles
                 flipped if necessary. If False, a bool is returned: True
                 if the alleles are correct.
    :type flip: bool

    :returns: Either a :py:class:`gepyto.structures.variant.SNP` with
              flipped alleles or a bool.

    This is used internally by :py:class:`Reference`, but it is also
    available to users, but you need to provide a pyfaidx Fasta object.

    """
    ref_allele = ref.get_nucleotide(snp.chrom, snp.pos)
    if ref_allele is None:
        s = "Can't find locus 'chr{}:{}' in the reference genome.".format(snp
            .chrom, snp.pos)
        raise ValueError(s)
    if ref_allele == snp.ref:
        return snp if flip else True
    if ref_allele == snp.alt:
        if flip:
            snp.ref, snp.alt = snp.alt, snp.ref
            return snp
        else:
            return False
    raise ValueError('Invalid alleles for variant {}. Reference is {}'.
        format(snp, ref_allele))