def soft_min_max(values, soft_add=1, soft_bounds=1):
    """ Returns [min, max + soft_add] if difference of min and max is less
        than the soft bound.

    Args:
        values: Iterable of numeric.
        soft_add:  Increment to max if difference is too small.
        soft_bounds:  If difference is smaller than this, add a soft increment.

    Returns:
        A list [min, max + soft_add] if abs(max-min) is less than soft bound.
    """
    min_val = min(values)
    max_val = max(values)
    diff_val = max_val - min_val
    max_increment = soft_add if abs(diff_val) < soft_bounds else 0
    return [min_val, max_val + max_increment]


def _read_file(filepath):
    """This function reads file as str

    Parameters
    ----------
    filename : str
        filepath of the file to read as string

    Returns
    -------
    file_content : str
    """
    with open(filepath, 'r') as fp:
        return fp.read()


def _get_digits(mantissa, n_digits, remove_trailing):
    """Get the digits for an int."""
    digitstr = (b'%d' % abs(mantissa)).rjust(n_digits, b'0')
    if remove_trailing:
        return digitstr.rstrip(b'0')
    else:
        return digitstr


def format_arg_value(arg_val):
    """
    Return a string representing a (name, value) pair.

    Example::

      >>> 'x=(1, 2, 3)' == format_arg_value(('x', (1, 2, 3)))
      True
    """
    arg, val = arg_val
    return '%s=%r' % (arg, val)


def validate(item, **kwargs):
    """Updates the abstract field"""
    if not item.get('headline', '').strip():
        raise KeyError('Headline cannot be empty!')


def is_free(amount):
    """
    Explit zero amounts are interpreted as Free!
    """
    return amount == 0 or amount == 0.0 or amount == '0' or amount == '0.00'


def open_truncate(filename):
    """Open the file name.  Return its handle."""
    return open(filename, 'wb+')


@staticmethod
def _http_range(start=0, end=0):
    """
        Returns an HTTP Range request for a specified python range.

        Args:
            start (int): Start of the range.
            end (int): End of the range.
                0 To not specify end.

        Returns:
            str: range.
        """
    if end:
        return 'bytes=%d-%d' % (start, end - 1)
    return 'bytes=%d-' % start


def delete_track():
    """Delete selected tracks

    """
    pass


def generate_progress_bar(curr, max, n_characters):
    """Returns an ascii progress bar"""
    phases = ' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'
    n_phases = len(phases)
    progress = 0 if max == 0 else curr / max * n_characters
    progress_bar = ''
    for i in range(n_characters):
        if progress > 1:
            phase = phases[-1]
        elif 0 <= progress < 1:
            index = int(round(progress * n_phases))
            phase = phases[index if index < len(phases) else -1]
        else:
            phase = phases[0]
        progress -= 1
        progress_bar += phase
    return progress_bar


@classmethod
def validate_user(cls, req):
    """hook method to allow <app>.User subclass to override the default validation and permit setting"""
    req.user = cls.validated_user(req)
    req.user.get_permits()


@staticmethod
def address_exists(profile, address):
    """
        try to detect if a address is already in a profile
        :param profile: haystack
        :param address: needle
        :return: Boolean True/False
        """
    for item in profile['addresses']:
        thisisit = True
        for key in address:
            if key == 'country' and not item.get('country', False):
                continue
            if not (item[key] == address[key] or item[key] == '' and
                address[key] is None):
                thisisit = False
        if thisisit:
            return True
    return False


def get_day_name(date):
    """
    returns the day name for a give date

    @param      date        datatime
    @return                 month name

    .. faqref::
        :tag: python
        :title: Récupérer le nom du jour à partir d'une date

        ::

            import datetime
            dt = datetime.datetime(2016, 1, 1)
            print(dt.strftime("%A"))
    """
    return date.strftime('%A')


def query_cmdline():
    """Query command line for variable details."""


def _freshly_booted(commands, step_type):
    """Check if the ramdisk has just started.

    On the very first boot we fetch the available steps, hence the only command
    agent executed will be get_XXX_steps. For later reboots the list of
    commands will be empty.
    """
    return not commands or len(commands) == 1 and commands[0]['command_name'
        ] == 'get_%s_steps' % step_type


def get_result(response):
    """
    Get the desired result from an API response.

    :param response: Requests API response object
    """
    try:
        payload = response.json()
    except AttributeError:
        payload = response
    if 'results' in payload:
        return payload['results']
    return payload


def groupby(func, seq):
    """ Group a collection by a key function

    >>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']
    >>> groupby(len, names)  # doctest: +SKIP
    {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}

    >>> iseven = lambda x: x % 2 == 0
    >>> groupby(iseven, [1, 2, 3, 4, 5, 6, 7, 8])  # doctest: +SKIP
    {False: [1, 3, 5, 7], True: [2, 4, 6, 8]}

    See Also:
        ``countby``
    """
    d = dict()
    for item in seq:
        key = func(item)
        if key not in d:
            d[key] = list()
        d[key].append(item)
    return d


def set_nested(dictionary, keys, value):
    """Use period-separated keys to set nested dictionary value."""
    d = dictionary
    keys = keys.split('.')
    nodes, leaf = keys[:-1], keys[-1]
    for node in nodes:
        if node not in d:
            d[node] = {}
        d = d[node]
    d[leaf] = value


@staticmethod
def _getMessageHtml(msg, palette):
    """get query information in as an HTML string"""
    if msg is None:
        msg_str = ''
    elif isinstance(msg, list):
        msg_str = '
'.join(msg)
    elif isinstance(msg, str):
        msg_str = msg
    else:
        msg_str = str(msg)
    if len(msg_str) > 0:
        palette_color = palette['color']
        palette_background_color = palette['background-color']
        palette_border_color = palette['border-color']
        msg_str = msg_str.replace('"', '"').replace("'", '''
            ).replace('\n', '
').replace(' ', ' ')
        body = (
            f"

{msg_str}

"
            )
    else:
        body = ''
    return {'body': body}


def hide(unselected: bool=False):
    """Hide (un)selected vertices, edges or faces

    :param unselected: Unselected, Hide unselected rather than selected
    :type unselected: bool
    """
    pass


@classmethod
def local_checksum(cls, package, algorithm='md5'):
    """
        Computes the checksum value on the local package file.

        :param str package:
          File-path to the package (\\*.tgz) file on the local server
        :param str algorithm:
          The algorithm to use for computing the checksum. Valid values are:
          'md5', 'sha1', and 'sha256'. Defaults to 'md5'.

        :returns: checksum (str)
        :raises IOError: when **package** file does not exist
        """
    if algorithm == 'md5':
        return cls.local_md5(package)
    elif algorithm == 'sha1':
        return cls.local_sha1(package)
    elif algorithm == 'sha256':
        return cls.local_sha256(package)
    else:
        raise ValueError('Unknown checksum algorithm: %s' % algorithm)


def create_route(app, engineio_server, engineio_endpoint):
    """This function sets up the engine.io endpoint as a route for the
    application.

    Note that both GET and POST requests must be hooked up on the engine.io
    endpoint.
    """
    app.add_route(engineio_server.handle_request, engineio_endpoint,
        methods=['GET', 'POST', 'OPTIONS'])
    try:
        app.enable_websocket()
    except AttributeError:
        pass


def append_lines(file, lines, encoding=None, errors=None):
    """Append the lines to a file.

    :param file: path to file or file descriptor
    :type file: :term:`path-like object` or int
    :param list(str) lines: list of strings w/o newline
    :param str encoding: name of the encoding
    :param str errors: error handler
    :return: number of characters written
    :rtype: int
    :raises OSError: on I/O failure

    .. versionchanged:: 0.6.0
       Add parameter ``errors``
    """
    with open(file, 'a', encoding=encoding, errors=errors) as fh:
        cnt = fh.write('\n'.join(lines))
        cnt += fh.write('\n')
        return cnt


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


@classmethod
def _parse_file(cls, filepath):
    """
        Parses a file - to be implemented in any subclass that may use files.

        Parameters
        ----------
        filepath : `str`
            The path to the file you want to parse.
        """
    return NotImplemented


def hexToString(hexString):
    """
        Simple method to convert an hexadecimal string to ascii string

        @param hexString: A string in hexadecimal format
        @return: A tuple (status,statusContent), where statusContent is an ascii string in case status = 0 or an error in case status = -1
    """
    string = ''
    if len(hexString) % 2 != 0:
        hexString = '0' + hexString
    try:
        for i in range(0, len(hexString), 2):
            string += chr(int(hexString[i] + hexString[i + 1], 16))
    except:
        return -1, 'Error in hexadecimal conversion'
    return 0, string


def parse_encoding_header(header):
    """
    Parse the HTTP Accept-Encoding header into a dict of the form,
    {encoding: qvalue}.

    >>> parse_encoding_header('') == {'': 1, 'identity': 1.0}
    True

    >>> parse_encoding_header('*') == {'*': 1, 'identity': 1.0}
    True

    >>> expected = {'identity': 1.0, 'gzip': 1.0, 'compress': 0.5}
    >>> parse_encoding_header('compress;q=0.5, gzip;q=1.0') == expected
    True

    >>> expected = {'*': 0.0, 'gzip': 1.0, 'identity': 0.5}
    >>> parse_encoding_header('gzip;q=1.0, identity; q=0.5, *;q=0') == expected
    True
    """
    encodings = {'identity': 1.0}
    for encoding in header.split(','):
        encoding, sep, params = encoding.partition(';')
        encoding = encoding.strip()
        key, sep, qvalue = params.partition('=')
        encodings[encoding] = float(qvalue or 1)
    return encodings


@staticmethod
def get_accept():
    """
        todo 获取请求头Accept参数
        :return:
        """
    return (
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
        )


def postDeploy(site):
    """
    Called after deploying the site (built files)

    :param site: The site that was just built.
    :returns: None
    """
    pass


def get_embedded_tags(embedded):
    """Returns the tags in the embedded response from wp.
    The group is in the fourth object of the wp:term list of the response:
    embedded["wp:term"][1]

    :param embedded: The embedded dictionnary in the response
    :returns: Dictionnary of tags
    """
    terms = embedded.get('wp:term', [{}, {}])
    return terms[1]


@classmethod
def exists(cls, key):
    """Whether the key exists in Redis.

        :param string key: The Redis key.
        :returns boolean: ``True`` if the key exists, and ``False`` otherwise.
        """
    return cls._instance.exists(key)


@staticmethod
def val2bool(val):
    """
            Converts standard input to boolean values

            True:  'on',  '1', 1, True
            False: 'off', '0', 0, False
            """
    if isinstance(val, str):
        val = val.lower()
        if val == 'on' or val == '1':
            return True
        elif val == 'off' or val == '0':
            return False
        else:
            raise ValueError('Invalid input')
    return bool(val)


def calculate_cluster_purity(contingency_mat):
    """
    Will calculate the cluster purity given a contingency matrix.

    :param contingency_mat: Contingency matrix containing the observations.
    :return: Cluster purity value
    """
    return contingency_mat.max().sum() / contingency_mat.values.sum()


def get_nav_root(context):
    """Returns the navigation root"""
    plone_state = context.restrictedTraverse('@@plone_portal_state')
    return plone_state.navigation_root()


def assign_and_remove(source_dict, dest_dict, key):
    """Assign a value to a destination dict from a source dict
    if the key exists
    """
    if key in source_dict:
        dest_dict[key] = source_dict.pop(key)


def arg_require_any(dict, args):
    """
    Check if any of the args is in the dict.

    :raises KeyError: If none of the args is present in the dict.
    """
    for arg in args:
        if arg in dict:
            return
    raise KeyError('Neither argument present: "{}"'.format(str(args)))


def centroid_points_xy(points):
    """Compute the centroid of a set of points lying in the XY-plane.

    Warning
    -------
    Duplicate points are **NOT** removed. If there are duplicates in the
    sequence, they should be there intentionally.

    Parameters
    ----------
    points : list of list
        A sequence of points represented by their XY(Z) coordinates.

    Returns
    -------
    list
        XYZ coordinates of the centroid (Z = 0.0).

    Examples
    --------
    >>>
    """
    p = len(points)
    x, y = list(zip(*points))[:2]
    return [sum(x) / p, sum(y) / p, 0.0]


def deconv_length(dim_size, stride_size, kernel_size, padding,
    output_padding, dilation=1):
    """Determines output length of a transposed convolution given input length.

    # Arguments
        dim_size: Integer, the input length.
        stride_size: Integer, the stride along the dimension of `dim_size`.
        kernel_size: Integer, the kernel size along the dimension of
            `dim_size`.
        padding: One of `"same"`, `"valid"`, `"full"`.
        output_padding: Integer, amount of padding along the output dimension,
            Can be set to `None` in which case the output length is inferred.
        dilation: dilation rate, integer.

    # Returns
        The output length (integer).
    """
    assert padding in {'same', 'valid', 'full'}
    if dim_size is None:
        return None
    kernel_size = (kernel_size - 1) * dilation + 1
    if output_padding is None:
        if padding == 'valid':
            dim_size = dim_size * stride_size + max(kernel_size -
                stride_size, 0)
        elif padding == 'full':
            dim_size = dim_size * stride_size - (stride_size + kernel_size - 2)
        elif padding == 'same':
            dim_size = dim_size * stride_size
    else:
        if padding == 'same':
            pad = kernel_size // 2
        elif padding == 'valid':
            pad = 0
        elif padding == 'full':
            pad = kernel_size - 1
        dim_size = (dim_size - 1
            ) * stride_size + kernel_size - 2 * pad + output_padding
    return dim_size


def get_projection_matrix() ->'mathutils.Matrix':
    """Return a copy of the projection matrix.

    :return:  A 4x4 projection matrix.
    """
    pass


def InstanceName(BaseName, NameList):
    """
	Return a new name that is not in the list.
	"""
    N = 0
    while BaseName + '_' + str(N) in NameList:
        N += 1
    return BaseName + '_' + str(N)


def gather_pieces(fmtstr, placeholder):
    """
    Takes a format string where % marks replacements by placeholder, and %%
    marks replacements by %. The returned object is a list of substrings and
    placeholders.
    """
    pieces = []
    substr = []
    escape = False
    for c in fmtstr:
        if escape:
            if c == '%':
                substr.append(c)
            else:
                pieces.append(''.join(substr))
                substr = []
                pieces.append(placeholder)
                substr.append(c)
            escape = False
        elif c == '%':
            escape = True
        else:
            substr.append(c)
    pieces.append(''.join(substr))
    if escape:
        pieces.append(placeholder)
    return pieces


@classmethod
def from_site_model(cls, site_model):
    """
        Создание MenuItem из модели admin.site
        """
    return cls(label=site_model['name'], url=site_model.get('admin_url') or
        site_model.get('add_url'))


def get_persistent_rep(env=None):
    """Return `(rep, args, imports)`.

        Define a persistent representation `rep` of the instance self where
        the instance can be reconstructed from the string rep evaluated in the
        context of dict args with the specified imports = list of `(module,
        iname, uiname)` where one has either `import module as uiname`, `from
        module import iname` or `from module import iname as uiname`.
        """


def F0F2F4_to_UdJH(F0, F2, F4):
    """
    Given :math:`F_0`, :math:`F_2` and :math:`F_4`, return :math:`U_d` and :math:`J_H`,
    for :math:`d`-orbitals.

    Parameters
    ----------
    F0: float
        Slater integral :math:`F_0`.
    F2: float
        Slater integral :math:`F_2`.
    F4: float
        Slater integral :math:`F_4`.

    Returns
    -------
    Ud: float
        Coulomb interaction :math:`U_d`.
    JH: float
        Hund's coupling :math:`J_H`.
    """
    Ud = F0
    JH = (F2 + F4) / 14.0
    return Ud, JH


@staticmethod
def parameters_list(num_agents, crossover_probability, differential_weight):
    """
        Create a list with DE parameters in the correct order.

        :param num_agents:
            Number of agents in the population (aka. NP in the research literature).

        :param crossover_probability:
            Crossover probability (aka. CR in the research literature).

        :param differential_weight:
            Differential weight (aka. F in the research literature).

        :return:
            List with parameters in correct order.
        """
    return [num_agents, crossover_probability, differential_weight]


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


@classmethod
def delete_cases_by_flow_definition(cls, flow_definition):
    """
        Deletes all cases by flow definition
        """
    for flow_case in flow_definition.flow_case_set.select_related().all():
        for user_notification_option in flow_case.user_notification_option_set.select_related(
            ).all():
            user_notification_option.delete()
        for flow_property in flow_case.property_set.select_related().all():
            flow_property.delete()
        for doc in flow_case.document_set.select_related().all():
            doc.delete()
        for note in flow_case.note_set.select_related().all():
            note.delete()
        for status in flow_case.source.status_set.select_related().all():
            status.delete()
        for activity in flow_case.activity_set.select_related().all():
            for log in activity.activity_log_set.select_related().all():
                log.delete()
            activity.delete()
        flow_case.delete()


def add_symbolic_constraints(namespace):
    """ Add constraints to a namespace that are LinearExpressions of basic
    constraints.

    """
    bottom = namespace.bottom
    left = namespace.left
    width = namespace.layout_width
    height = namespace.layout_height
    namespace.right = left + width
    namespace.top = bottom + height
    namespace.h_center = left + width / 2.0
    namespace.v_center = bottom + height / 2.0


def _mergeOrderings(orderings):
    """Merge multiple orderings so that within-ordering order is preserved

    Orderings are constrained in such a way that if an object appears
    in two or more orderings, then the suffix that begins with the
    object must be in both orderings.

    For example:

    >>> _mergeOrderings([
    ... ['x', 'y', 'z'],
    ... ['q', 'z'],
    ... [1, 3, 5],
    ... ['z']
    ... ])
    ['x', 'y', 'q', 1, 3, 5, 'z']

    """
    seen = {}
    result = []
    for ordering in reversed(orderings):
        for o in reversed(ordering):
            if o not in seen:
                seen[o] = 1
                result.insert(0, o)
    return result


def _pop(src):
    """Pops the first item in ``src``."""
    src.pop(0)


def performance_measure(tp, tn, fp, fn):
    """
    For output of confusion table gives various perfomance performance_measures:
      :return: tpr, fpr, precision, recall, balanced accuracy, accuracy, f1-score
    """
    tpr = float(tp) / (tp + fn) if tp + fn != 0 else 0
    fpr = float(fp) / (fp + tn) if fp + tn != 0 else 0
    tnr = float(tn) / (tn + fp) if tn + fp != 0 else 0
    recall = float(tp) / (tp + fn) if tp + fn != 0 else 0
    precision = float(tp) / (tp + fp) if tp + fp != 0 else 1
    bal_accur = 0.5 * tpr + 0.5 * tnr
    accur = float(tp + tn) / (tp + tn + fp + fn)
    if precision + recall != 0:
        f1 = 2 * precision * recall / (precision + recall)
    else:
        f1 = 0
    return tpr, fpr, precision, recall, bal_accur, accur, f1


@classmethod
def task_names(cls):
    """
        List of task names as strings
        """
    return sorted(cls._get_reg().keys())


@classmethod
def xpath(C, node, path, namespaces=None, extensions=None, smart_strings=
    True, **args):
    """shortcut to Element.xpath()"""
    return node.xpath(path, namespaces=namespaces or C.NS, extensions=
        extensions, smart_strings=smart_strings, **args)


def _asdict(t):
    """Return a new dict which maps field names to their values"""
    return {'value': t[0], 'language': t[1], 'datatype': t[2]}


@classmethod
def from_request(cls, request):
    """
        Factory constructor from intent and session.
        """
    attributes = cls.session_attributes_cls.from_request(request)
    return cls(attributes)


def has_change_path_cmd(sql):
    """Determines if the search_path should be refreshed by checking if the
    sql has 'set search_path'."""
    return 'set search_path' in sql.lower()


@staticmethod
def flush():
    """
        Flush is a NO OP in VOFile: only really flush on close.
        @return:
        """
    return


def unregister_reference(target, count=1):
    """Register that references to the given target were removed."""


@classmethod
def power_level(cls, game, power_name):
    """ Create and return a game power level with given game data and power name. """
    return cls(game, 'power', power_name)


def _validate_placement(options, parser):
    """Ensure one unit has been requested if machine is not None."""
    if options.machine is not None and options.num_units != 1:
        parser.error('cannot use --num-units > 1 with --to')


def _cache_run_start(run_start, run_start_cache):
    """Cache a RunStart document

    Parameters
    ----------
    run_start : dict
        raw pymongo dictionary. This is expected to have
        an entry `_id` with the ObjectId used by mongo.

    run_start_cache : dict
        Dict[str, Document]

    Returns
    -------
    run_start : dict
        Document instance for this RunStart document.
        The ObjectId has been stripped.
    """
    run_start = dict(run_start)
    run_start.pop('beamline_config_id', None)
    oid = run_start.pop('_id', None)
    run_start_cache[run_start['uid']] = run_start
    run_start_cache[oid] = run_start
    return run_start


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 default_claims_verification_callback(user_claims):
    """
    By default, we do not do any verification of the user claims.
    """
    return True


@classmethod
def unregister_dict_to_class(cls, classname):
    """
        Removes the converter registered for the given classname. Dicts with that classname tag
        will be deserialized by the default mechanism again.

        This mechanism is not used for the pickle serializer.
        """
    if classname in cls.__custom_dict_to_class_registry:
        del cls.__custom_dict_to_class_registry[classname]


def multimember(name, *varlist, **kwargs):
    """
    A classification effect whose levels are determined by one or more class variables

    Parameters
    ----------
    name : string
        specifies the name of the effect.
    details : boolean, optional
        requests a table that shows additional details related to this
        effect.
        Default: False
    varlist : list of strings
        specifies classification variables for the multimember effect.
        The levels of a multimember effect consist of the union of
        formatted values of the variables that define this effect. Each
        such level contributes one column to the design matrix. For each
        observation, the value that corresponds to each level of the
        multimember effect in the design matrix is the number of times
        that this level occurs for the observation.
        Default: []
    noeffect : boolean, optional
        when set to True, specifies that for observations with all
        missing levels of the multimember variables, the values in the
        corresponding design matrix columns be set to zero.
        Default: False
    stdize : boolean, optional
        when set to True, specifies that for each observation, the
        entries in the design matrix that corresponds to the multimember
        effect be scaled to have a sum of one.
        Default: False
    weight : list of strings, optional
        specifies numeric variables used to weigh the contributions of
        each classification variable that define the multimember effect.
        The number of weight variables must match the number of
        classification variables that define the effect.
        Default: []

    Returns
    -------
    dict

    """
    return dict(name=name, varlist=list(varlist), **kwargs)


@classmethod
def check_element(cls, items, subtype=False):
    """Check that all elements in set of elements (e.g. row or
        column) are consistent.

        Args:
            items (list): Set of element type definitions.
            subtype (bool, optional): If True, subtype, precision, and
                title information are used in the comparison. Defaults
                to False. subtype should be True if checking column
                elements and False if checking row elements.

        Raises:
            AssertionError: If any elements are not consistent.

        """
    base_summary = cls.get_summary(items[0], subtype=subtype)
    for i, x in zip(range(1, len(items)), items[1:]):
        x_summary = cls.get_summary(x, subtype=subtype)
        cls.check_summary(x_summary, i, base_summary, 0)


def registerProducer(producer, streaming):
    """
        Register to receive data from a producer.

        This sets self to be a consumer for a producer.  When this object runs
        out of data (as when a send(2) call on a socket succeeds in moving the
        last data from a userspace buffer into a kernelspace buffer), it will
        ask the producer to resumeProducing().

        For L{IPullProducer} providers, C{resumeProducing} will be called once
        each time data is required.

        For L{IPushProducer} providers, C{pauseProducing} will be called
        whenever the write buffer fills up and C{resumeProducing} will only be
        called when it empties.

        @type producer: L{IProducer} provider

        @type streaming: C{bool}
        @param streaming: C{True} if C{producer} provides L{IPushProducer},
        C{False} if C{producer} provides L{IPullProducer}.

        @raise RuntimeError: If a producer is already registered.

        @return: C{None}
        """


@classmethod
def notify(cls, self, obj):
    """ Specifies what to do with the view model newly generated
                from an update.

        :param obj:
        :return:
        """
    self.emit('updated', obj.to_view_dict())


def combine_values(*values):
    """Return the last value in *values* that is not ``None``.

    The default combiner; good for simple values (booleans, strings, numbers).
    """
    for v in reversed(values):
        if v is not None:
            return v
    else:
        return None


def override(func):
    """
    Decorator that indicates that the method is overriding an abstract or extension
    method defined in a base class. Note that this decorator has no impact on
    the method's functionality.
    """
    if isinstance(func, (staticmethod, classmethod)):
        actual_func = func.__func__
    elif callable(func):
        actual_func = func
    else:
        raise Exception("This type cannot be decorated with 'override'")
    setattr(actual_func, '__override_method', True)
    return func


def save_cookiestxt(fp, cookies):
    """Write 'cookies' in Netscape cookies.txt format to 'fp'"""
    fp.write('# Netscape HTTP Cookie File\n\n')
    for cookie in cookies:
        if cookie.value is None:
            name = ''
            value = cookie.name
        else:
            name = cookie.name
            value = cookie.value
        fp.write('\t'.join((cookie.domain, 'TRUE' if cookie.domain.
            startswith('.') else 'FALSE', cookie.path, 'TRUE' if cookie.
            secure else 'FALSE', '0' if cookie.expires is None else str(
            cookie.expires), name, value)) + '\n')


def converse_nonimplication(a, b):
    """ if a is False, b must be True """
    return not a and b


@classmethod
def prepare(cls, options, round_manager):
    """Allows a resolver to add additional product requirements to the NodeResolver task."""
    pass


def rename():
    """Rename file or file directory

    """
    pass


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


def _hypot(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Given the "legs" of a right triangle, return its hypotenuse.

    Defined in src/operator/tensor/elemwise_binary_op_extended.cc:L79

    Parameters
    ----------
    lhs : NDArray
        first input
    rhs : NDArray
        second input

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def get_separation(source_id1, source_id2):
    """Use Gaia DR2 source ids to return the separation between two sources in arcsec"""
    import warnings
    warnings.filterwarnings('ignore')
    import numpy as np
    from astroquery.gaia import Gaia
    from myastrotools.gaia_tools import to_polar
    deg_to_mas = 3600000.0
    mas_to_deg = 1.0 / 3600000.0
    job = Gaia.launch_job(
        'SELECT * FROM gaiadr2.gaia_source WHERE source_id = ' + str(
        source_id1))
    j = job.get_results()
    job = Gaia.launch_job(
        'SELECT * FROM gaiadr2.gaia_source WHERE source_id = ' + str(
        source_id2))
    k = job.get_results()
    RAa, RAaerr = j[0]['ra'], j[0]['ra_error'] * mas_to_deg
    RAb, RAberr = k[0]['ra'], k[0]['ra_error'] * mas_to_deg
    Deca, Decaerr = j[0]['dec'], j[0]['dec_error'] * mas_to_deg
    Decb, Decberr = k[0]['dec'], k[0]['dec_error'] * mas_to_deg
    raa_array = np.random.normal(RAa, RAaerr, 10000)
    rab_array = np.random.normal(RAb, RAberr, 10000)
    deca_array = np.random.normal(Deca, Decaerr, 10000)
    decb_array = np.random.normal(Decb, Decberr, 10000)
    rho_array, pa_array = to_polar(raa_array, rab_array, deca_array, decb_array
        )
    rho, rhoerr = np.mean(rho_array).value, np.std(rho_array).value
    return rho / 1000, rhoerr / 1000


def detection_poobah(poobah_df, pval_cutoff):
    """ given a dataframe of p-values with sample_ids in columns and probes in index,
    calculates the percent failed probes per sample. Part of QC report."""
    out = {}
    for sample_id in poobah_df.columns:
        total = poobah_df.shape[0]
        failed = poobah_df[sample_id][poobah_df[sample_id] >= pval_cutoff
            ].count()
        percent_failed = round(100 * failed / total, 1)
        out[sample_id] = percent_failed
    return out


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

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


def iterate_attributes(cls):
    """iterate all the keys and attributes associated
       with a class, without using getattr().

       Does not use getattr() so that class-sensitive
       descriptors (i.e. property.__get__()) are not called.

    """
    keys = dir(cls)
    for key in keys:
        for c in cls.__mro__:
            if key in c.__dict__:
                yield key, c.__dict__[key]
                break


@classmethod
def from_queue_key(cls, queue_key, connection=None, job_class=None):
    """Returns a Queue instance, based on the naming conventions for naming
        the internal Redis keys.  Can be used to reverse-lookup Queues by their
        Redis keys.
        """
    prefix = cls.redis_queue_namespace_prefix
    if not queue_key.startswith(prefix):
        raise ValueError('Not a valid RQ queue key: {0}'.format(queue_key))
    name = queue_key[len(prefix):]
    return cls(name, connection=connection, job_class=job_class)


def _ndec(x):
    """
    Return input float value rounded up to nearest tenth decimal place.

    Parameters
    ----------
    x: float
        Input value to be rounded up.

    Returns
    -------
    rounded: float
        input value rounded up to nearest tenth decimal place
    """
    if x > 0:
        return int(x * 10 + 0.5) / 10.0
    else:
        return int(x * 10 - 0.5) / 10.0


def string_int_tuple(ctx, param, value=None):
    """Works around Click bug

    https://github.com/pallets/click/issues/789#issuecomment-535121714"""
    if not value:
        return None
    else:
        return value[0], int(value[1])


def get_balance(s, asTuple=False):
    """Returns a string formatted 'X|X' which describes the balance of a given split string"""
    s = s.split('|')
    if not asTuple:
        return str(len(s[0])) + '|' + str(len(s[1]))
    else:
        return len(s[0]), len(s[1])


def _get_queryset(klass):
    """
    Return a QuerySet or a Manager.
    Duck typing in action: any class with a `get()` method (for
    get_object_or_404) or a `filter()` method (for get_list_or_404) might do
    the job.
    """
    if hasattr(klass, '_default_manager'):
        return klass._default_manager.all()
    return klass


def get_bot(zelf, id):
    """ return bot with botid in the fleet. """
    for bot in zelf.bots:
        if bot.id() == id:
            return bot


def extended_cigar(aligned_template, aligned_query):
    """ Convert mutation annotations to extended cigar format

   https://github.com/lh3/minimap2#the-cs-optional-tag

   USAGE:
      >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA'
      >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA'
      >>> extended_cigar(template, query) == ':6-ata:10+gtc:4*at:3'
      True
   """
    insertion = []
    deletion = []
    matches = []
    cigar = []
    for r_aa, q_aa in zip(aligned_template.lower(), aligned_query.lower()):
        gap_ref = r_aa == '-'
        gap_que = q_aa == '-'
        match = r_aa == q_aa
        if matches and not match:
            cigar.append(':%s' % len(matches))
            matches = []
        if insertion and not gap_ref:
            cigar.append('+%s' % ''.join(insertion))
            insertion = []
        elif deletion and not gap_que:
            cigar.append('-%s' % ''.join(deletion))
            deletion = []
        if gap_ref:
            if insertion:
                insertion.append(q_aa)
            else:
                insertion = [q_aa]
        elif gap_que:
            if deletion:
                deletion.append(r_aa)
            else:
                deletion = [r_aa]
        elif match:
            if matches:
                matches.append(r_aa)
            else:
                matches = [r_aa]
        else:
            cigar.append('*%s%s' % (r_aa, q_aa))
    if matches:
        cigar.append(':%s' % len(matches))
        del matches
    if insertion:
        cigar.append('+%s' % ''.join(insertion))
        del insertion
    elif deletion:
        cigar.append('-%s' % ''.join(deletion))
        del deletion
    return ''.join(cigar)


@classmethod
def convert_code(cls, code, redirect_uri=
    'http://local.mellowmorning.com:8000/facebook/connect/'):
    """
        Turns a code into an access token

        **Example**::

            FacebookAuthorization.convert_code(code)

        :param code:
            The code to convert

        :param redirect_uri:
            The redirect uri with which the code was requested

        :returns: dict

        """
    kwargs = cls._client_info()
    kwargs['code'] = code
    kwargs['redirect_uri'] = redirect_uri
    response = cls.request('oauth/access_token', **kwargs)
    return response


@staticmethod
def check(request, handler):
    """
        Check permission method.

        :param request: instance of Request class.
        :param handler: view, invoked later for the request.
        """
    return request.user and request.user.is_authenticated()


def is_form_post(environ):
    """Determine whether the request is a POSTed html form"""
    content_type = environ.get('CONTENT_TYPE', '').lower()
    if ';' in content_type:
        content_type = content_type.split(';', 1)[0]
    return content_type in ('application/x-www-form-urlencoded',
        'multipart/form-data')


def isUnspecified(str):
    """
    Checks whether a string is None or an
    empty string. Returns a boolean.
    """
    return str == '' or str is None


def _copy_without_ignore_items(the_dict, ignored_keys=['ignore']):
    """
    get a copy of *the_dict* without entries having substring
    'ignore' in key
    """
    new_dict = {}
    for key, val in list(the_dict.items()):
        if key not in ignored_keys:
            new_dict[key] = val
    return new_dict


@staticmethod
def get_text_status(json):
    """
        Extracts textual status from the response - statusdetail, if present.
        Otherwise extracts status field.

        :param json:
        :return:
        """
    if json is None:
        return None
    elif 'statusdetail' in json:
        return json['statusdetail']
    elif 'status' in json:
        return json['status']
    else:
        return None


def to_digital(d, num):
    """
    进制转换，从10进制转到指定机制
    :param d:
    :param num:
    :return:
    """
    if not isinstance(num, int) or not 1 < num < 10:
        raise ValueError('digital num must between 1 and 10')
    d = int(d)
    result = []
    x = d % num
    d = d - x
    result.append(str(x))
    while d > 0:
        d = d // num
        x = d % num
        d = d - x
        result.append(str(x))
    return ''.join(result[::-1])


@classmethod
def begin(cls):
    """
        Initialize a thread-local transaction. An exception is raised if
        there's already a pending transaction.
        """
    if cls.app.local.sqla_tx is not None:
        raise Exception('there is already an open transaction')
    cls.app.local.sqla_tx = cls.app.local.sqla_conn.begin()


def resolver_has_tag(f, tag):
    """
        Checks to see if a function has a specific tag.
    """
    if not hasattr(f, '_resolver_tags'):
        return False
    return tag in f._resolver_tags


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

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


def write(packet, addr=None):
    """
        Write packet to given address.

        @param addr: a tuple of (ip, port). For connected transports must
                     be the address the transport is connected to, or None.
                     In non-connected mode this is mandatory.

        @raise twisted.internet.error.MessageLengthError: C{packet} was too
        long.
        """


def raise_no_pyne(msg, have_pyne=False):
    """Raise an error when PyNE cannot be found."""
    if not have_pyne:
        raise ImportError('pyne could not be imported: ' + msg)


def ceil(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise ceiling of the input.

    The ceil of the scalar x is the smallest integer i, such that i >= x.

    Example::

       ceil([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-2., -1.,  2.,  2.,  3.]

    The storage type of ``ceil`` output depends upon the input storage type:

       - ceil(default) = default
       - ceil(row_sparse) = row_sparse
       - ceil(csr) = csr

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

    Parameters
    ----------
    data : Symbol
        The input array.

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

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


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

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

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


def check_domain_running(conn, guestname, logger):
    """ check if the domain exists and in running state as well """
    guest_names = []
    ids = conn.listDomainsID()
    for id in ids:
        obj = conn.lookupByID(id)
        guest_names.append(obj.name())
    if guestname not in guest_names:
        logger.error('%s is not running or does not exist' % guestname)
        return False
    else:
        return True


def matches_tag(scenario_tags, tag_list):
    """ If tags indicated on command line, returns True if a Scenario_tag matches
    one given on the command line"""
    if not tag_list:
        return True
    else:
        return set(scenario_tags).intersection(tag_list)


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 render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

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

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


def fix_ensure_time_attrib(json):
    """Ensure that requested attributes include the 'time' attribute"""
    if 'attrs' not in json:
        json['attrs'] = []
    if 'time' not in json['attrs']:
        json['attrs'].append('time')
    return json


def legendre_symbol(a, p):
    """ Compute the Legendre symbol a|p using
    Euler's criterion. p is a prime, a is
    relatively prime to p (if p divides
    a, then a|p = 0)

    Returns 1 if a has a square root modulo
    p, -1 otherwise.
    """
    ls = pow(a, (p - 1) // 2, p)
    return -1 if ls == p - 1 else ls


def mean(a, b, distance):
    """Return the mean of the given distance."""
    result, n = distance(a, b, overlap=True)
    return result / n


def hide_password(url, start=6):
    """Returns the http url with password part replaced with '*'.

    :param url: URL to upload the plugin to.
    :type url: str

    :param start: Position of start of password.
    :type start: int
    """
    start_position = url.find(':', start) + 1
    end_position = url.find('@')
    return '%s%s%s' % (url[:start_position], '*' * (end_position -
        start_position), url[end_position:])


def check_colormap(cmap):
    """
    Check if cmap is one of the colorbrewer maps
    """
    names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu',
        'RdYlGn', 'Spectral', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens',
        'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples',
        'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'Accent',
        'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3',
        'Lightning'])
    if cmap not in names:
        raise Exception("Invalid cmap '%s',  must be one of %s" % (cmap, names)
            )
    else:
        return cmap


def getQuestionsCount():
    """Return a count of questions asked"""


def retrieve_environment_info(EnvironmentId=None, EnvironmentName=None,
    InfoType=None):
    """
    Retrieves the compiled information from a  RequestEnvironmentInfo request.
    Related Topics
    See also: AWS API Documentation

    Examples
    The following operation retrieves a link to logs from an environment named my-env:
    Expected Output:

    :example: response = client.retrieve_environment_info(
        EnvironmentId='string',
        EnvironmentName='string',
        InfoType='tail'|'bundle'
    )

    :type EnvironmentId: string
    :param EnvironmentId: The ID of the data's environment.
            If no such environment is found, returns an InvalidParameterValue error.
            Condition: You must specify either this or an EnvironmentName, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :type EnvironmentName: string
    :param EnvironmentName: The name of the data's environment.
            If no such environment is found, returns an InvalidParameterValue error.
            Condition: You must specify either this or an EnvironmentId, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :type InfoType: string
    :param InfoType: [REQUIRED]
            The type of information to retrieve.

    :rtype: dict
    :return: {
        'EnvironmentInfo': [
            {
                'InfoType': 'tail'|'bundle',
                'Ec2InstanceId': 'string',
                'SampleTimestamp': datetime(2015, 1, 1),
                'Message': 'string'
            },
        ]
    }

    :returns:
    EnvironmentId (string) -- The ID of the data's environment.
    If no such environment is found, returns an InvalidParameterValue error.
    Condition: You must specify either this or an EnvironmentName, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    EnvironmentName (string) -- The name of the data's environment.
    If no such environment is found, returns an InvalidParameterValue error.
    Condition: You must specify either this or an EnvironmentId, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    InfoType (string) -- [REQUIRED]
    The type of information to retrieve.

    """
    pass


def remove_namespaces(tree):
    """Remove namespaces from all elements in the tree."""
    import re
    for elem in tree.iter():
        if isinstance(elem.tag, ''.__class__):
            elem.tag = re.sub('^\\{[^}]*\\}', '', elem.tag)


def is_iterable(obj):
    """
    Returns whether or not given Python object is iterable
    :param obj: object
    :return: bool
    """
    try:
        it = iter(obj)
    except TypeError:
        return False
    return True


def mean_normalization(array):
    """ Normalize the features to zero mean. """
    return (array - array.mean(axis=0)) / (array.max(axis=0) - array.min(
        axis=0))


@classmethod
def from_data(cls, data):
    """Construct a graph from structured data.

        Parameters
        ----------
        data : dict
            The data dictionary.

        Returns
        -------
        object
            An object of the type of ``cls``.

        Note
        ----
        This constructor method is meant to be used in conjuction with the
        corresponding *to_data* method.

        """
    graph = cls()
    graph.data = data
    return graph


def get_number_of_classes(labelsCounts):
    """
    Counts how many classes there are in the dataset.

    :param labelsCounts : a dictionary mapping labels to a count of their occurrences.
    :type labelsCounts  : dict

    :return             : the number of different labels in the dataset.
    """
    return len(labelsCounts)


def transfer_suggestions():
    """Return suggested transfers based on expected points for next 5 Gameweeks"""
    pass


@classmethod
def istypeof(cls, obj):
    """Check if `cls` is the type of `obj`

        In the normal case, as implemented here, a simple isinstance check is
        used. However, there are more complex checks possible. For instance,
        EmailAddress.istypeof(obj) checks if obj is an Address object with
        a category of Address.CAT_EMAIL
        """
    return isinstance(obj, cls)


def vo2(velocity):
    """
    a regression equation relating VO2 with running velocity. Used in conjuction with the "velocity" equation to create the Jack Daniel's VDOT tables. Initially retrieved from "Oxygen Power: Performance Tables for Distance Runners" by Jack Daniels.

    Conditioning for Distance Running - the Scientific Aspects, 1978

    args:
        velocity (float): given in meters/second

    Returns:
        float: vO2, given in mL/kg/minute
    """
    return -4.6 + 0.182258 * velocity + 0.000104 * pow(velocity, 2)


def format_version(major, minor, patch, prerelease=None, build=None):
    """Format a version according to the Semantic Versioning specification

    :param str major: the required major part of a version
    :param str minor: the required minor part of a version
    :param str patch: the required patch part of a version
    :param str prerelease: the optional prerelease part of a version
    :param str build: the optional build part of a version
    :return: the formatted string
    :rtype: str

    >>> import semver
    >>> semver.format_version(3, 4, 5, 'pre.2', 'build.4')
    '3.4.5-pre.2+build.4'
    """
    version = '%d.%d.%d' % (major, minor, patch)
    if prerelease is not None:
        version = version + '-%s' % prerelease
    if build is not None:
        version = version + '+%s' % build
    return version


def _do_periodic():
    """Do some arbitrary periodic processing.

        Called every once in a while both from the runner's main loop, and
        from the runner's hash slice processing loop.  You can do whatever
        special periodic processing you want here.
        """


def fatal_process_sample_error(err):
    """Give up retrying if the error code is different from 403.

    If the error code is 403, we need to refresh the download url and try
    processing the sample again.

    Returns:
        bool: True if to giveup on backing off, False it to continue.
    """
    return err.response.status_code != 403


@classmethod
def from_py_package(cls, package_name: str, config_path: str=None,
    darty_profile: str=None):
    """Creates an instance of DependencyManager by Python package name.
        It automatically finds a path to dependency file within a Python package.

        :param package_name:
        :param config_path:
        :param darty_profile:
        :return:
        """
    import pkg_resources
    if not config_path:
        config_path = cls.DEFAULT_CONFIG_FILE
    return cls(pkg_resources.resource_filename(package_name, config_path),
        darty_profile)


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


@classmethod
def get_table_names(cls, inspector, schema):
    """Need to disregard the schema for Sqlite"""
    return sorted(inspector.get_table_names())


@staticmethod
def pad(data, *args, **kwargs):
    """Pads data with given padding.

        :returns: Padded data.
        :rtype: list

        """
    raise NotImplementedError()


def unit_to_microunit(measure):
    """
    Convert measures in whole units to millionths of units.

    Parameters
    ----------
    measure : array_like
        The measure(s) to be converted

    Returns
    -------
    out : float or :py:class:`numpy.ndarray`
        The converted measure(s)

    Raises
    ------
    TypeError
        If ``measure`` cannot be converted to a :py:class:`numpy.ndarray`

    Examples
    --------
    >>> unit_to_microunit(1) == 1. * 1000000
    True
    """
    return measure * 1000000.0


def step(x):
    """Return activation value of x with sign function"""
    return 1 if x >= 0 else 0


def atse_getRegisteredSchemata():
    """
        Returns all registered schemata
        """


@staticmethod
def _parse_error(response):
    """
        Parses any version of the API payload when the status code is != 200

        :param response: a response object
        :return: Error message
        """
    if response.headers.get('Content-Type') == 'application/json':
        try:
            payload = response.json()
            if 'msg' in payload:
                return payload['msg']
            elif 'error' in payload and 'message' in payload:
                return payload['error'] + '. ' + payload['message']
            elif 'error' in payload:
                return payload['error']
        except ValueError:
            return None


def dynamic_load(name):
    """Equivalent of "from X import Y" statement using dot notation to specify
    what to import and return.  For example, foo.bar.thing returns the item
    "thing" in the module "foo.bar" """
    pieces = name.split('.')
    item = pieces[-1]
    mod_name = '.'.join(pieces[:-1])
    mod = __import__(mod_name, globals(), locals(), [item])
    return getattr(mod, item)


@classmethod
def from_requirement(cls, requirement, file_path=None):
    """A requirement in this method's context is a
        pkg_resources.Requirement
        """
    return cls(requirement.project_name, file_path=file_path)


def PolsSurg(t):
    """Number of policies: Surgery"""
    return 0


def create_date_formats():
    """Generate time and date formats with different delimeters."""
    base_formats = ['%d %m %Y', '%d %m %y', '%Y %m %d']
    base_formats += ['%m %d %Y', '%m %d %y', '%Y %m %d']
    base_formats += ['%d %b %Y', '%d %B %Y']
    date_formats = []
    for separator in ('-', '.', '/', ' '):
        for date_format in base_formats:
            date_formats.append(date_format.replace(' ', separator))
    datetime_formats = []
    time_formats = '%H:%M%Z', '%H:%M:%S', '%H:%M:%S%Z', '%H:%M%z', '%H:%M:%S%z'
    for date_format in date_formats:
        for time_format in time_formats:
            for separator in ('', 'T', ' '):
                datetime_formats.append(date_format + separator + time_format)
    return tuple(date_formats), tuple(datetime_formats)


def doi_url(id: str=''):
    """
  Convert the doi to a url
  """
    return f'http://{id}' if id.startswith('doi.org'
        ) else f'http://doi.org/{id}'


@staticmethod
def _getlayers(pkt):
    """Returns the layers of a scapy package."""
    yield pkt
    while pkt.payload:
        pkt = pkt.payload
        yield pkt


def bookmark_add():
    """Add a bookmark for the selected/active directory

    """
    pass


@classmethod
def find_me(cls):
    """Issue a ``GET /developers/<developer_sid>``

        ::

           developer = poundpay.Developer.find_me()
           assert developer.sid == 'YOUR_DEVELOPER_SID'
           developer.callback_url = 'http://marketplace.com/callback/'
           developer.charge_permissioncallback_url = 'http://marketplace.com/charge_permission_callback/'
           developer.save()
           developer = poundpay.Developer.find_me()
           assert developer.callback_url == 'http://marketplace.com/callback/'
           assert developer.callback_url == 'http://marketplace.com/charge_permission_callback/'

        """
    return cls.find(cls.client.developer_sid)


@staticmethod
def _get_parameters_dict(param_keys, param_values):
    """Override the inherited _get_parameters_dict() method to allow passing boolean values directly"""
    params_dict = {}
    for i, key in enumerate(param_keys):
        if param_values[i] is not None:
            params_dict.update({key: param_values[i]})
    return params_dict


def create_comms_and_role_node(comm, node_comm, node_root):
    """Approach: each node root builds, everyone waits on their node group."""
    copy_comm = None
    wait_comm = node_comm
    if node_comm.rank == 0:
        assert comm.rank == node_root
        role = 'builder'
    else:
        assert comm.rank != node_root
        role = 'waiter'
    return copy_comm, wait_comm, role


def external_files():
    """
    A snippet to propagate the external files directory
    to the submodules
    """
    try:
        from ConfigParser import ConfigParser
    except ImportError:
        from configparser import ConfigParser
    conf = ConfigParser()
    conf.read(['../setup.cfg'])
    metadata = dict(conf.items('metadata'))
    return metadata.get('external_files')


def _line_exists(wavelengths, y, z, x0, xRes, fluxMin):
    """For a group of lines finds if the there is some change in flux greater
    than some minimum at the same redshift with different initial wavelengths

    Parameters
    ----------
    wavelengths : (N) ndarray
        array of initial wavelengths to check
    y : (N) ndarray
        flux array to check
    x0 : float
        wavelength of the first value in y
    xRes : float
        difference in wavelength between consecutive cells in flux array
    fluxMin : float
        maximum flux to count as a line existing.

    Returns
    -------

    flag : boolean
        value indicating whether all lines exist. True if all lines exist
    """
    for wl in wavelengths:
        redWl = (z + 1) * wl
        indexRedWl = (redWl - x0) / xRes
        if indexRedWl > len(y):
            return False
        if y[int(indexRedWl)] > fluxMin:
            return False
    return True


def estimate_n_guesses(matrix, n_states, singles_only=True):
    """
    Implementation of a basic heuristic to find a good number of guess
    vectors to be searched for using the find_guesses function.
    Internal function called from run_adc.

    matrix             ADC matrix
    n_states           Number of states to be computed
    singles_only       Try to stay withing the singles excitation space
                       with the number of guess vectors.
    """
    n_guesses = max(4, 2 * n_states)
    if singles_only:
        mospaces = matrix.mospaces
        sp_occ = 'o2' if matrix.is_core_valence_separated else 'o1'
        n_virt_a = mospaces.n_orbs_alpha('v1')
        n_occ_a = mospaces.n_orbs_alpha(sp_occ)
        n_guesses = min(n_guesses, n_occ_a * n_virt_a)
    return max(n_states, n_guesses)


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


def isValidCreditCard(cardNum):
    """Returns True if the credit card number is a valid Luhn (Mod 10) number
       and False if not. This, of course, does not validate the number, but
       will catch typos. There is the chance that two typographic errors could
       return a false positive if they offset one another, but the likelihood
       is low and pre-validating is fast"""
    financialIndustries = ['3', '4', '5', '6']
    if cardNum[0] not in financialIndustries:
        return False
    total = pos = 0
    for digit in cardNum[::-1]:
        if pos % 2 == 0:
            multiplier = 1
        else:
            multiplier = 2
        product = int(digit) * multiplier
        total += product // 10 + product % 10
        pos += 1
    if total % 10 == 0:
        return True
    return False


@classmethod
def get_classname(cls, my_instance):
    """
        Return the class name of my_instance, or "Instance.None".
        :param cls: Our class.
        :param my_instance: Instance to use.
        :return: Return the class name of my_instance, or "Instance.None" in case of error/None value.
        """
    if my_instance is None:
        return 'Instance.None'
    else:
        return my_instance.__class__.__name__


def is_sequence(arg):
    """
    Checks if arg is a sequence
    """
    if isinstance(arg, str):
        return False
    return not hasattr(arg, 'strip') and hasattr(arg, '__getitem__'
        ) or hasattr(arg, '__iter__')


def was_active(reference_date_value, asset):
    """
    Whether or not `asset` was active at the time corresponding to
    `reference_date_value`.

    Parameters
    ----------
    reference_date_value : int
        Date, represented as nanoseconds since EPOCH, for which we want to know
        if `asset` was alive.  This is generally the result of accessing the
        `value` attribute of a pandas Timestamp.
    asset : Asset
        The asset object to check.

    Returns
    -------
    was_active : bool
        Whether or not the `asset` existed at the specified time.
    """
    return (asset.start_date.value <= reference_date_value <= asset.
        end_date.value)


@classmethod
def decode(cls, msg):
    """
        Decodes messages following Jupyter messaging protocol.
        If JSON decoding fails data is assumed to be a regular string.
        """
    return msg['content']['data']


def __delitem__(key):
    """
        Remove the entry from the cache.

        If it does not exist, it is an error.
        """


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


@staticmethod
def __new__(*args, **kwargs):
    """ Create and return a new object.  See help(type) for accurate signature. """
    pass


def parse_dict(var_dict: dict, backend, **kwargs) ->dict:
    """Parses a dictionary with variable information and creates backend variables from that information.

    Parameters
    ----------
    var_dict
        Contains key-value pairs for each variable that should be translated into the backend graph.
        Each value is a dictionary again containing the variable information (needs at least a field for `vtype`).
    backend
        Backend instance that the variables should be added to.
    kwargs
        Additional keyword arguments to be passed to the backend methods.

    Returns
    -------
    dict
        Key-value pairs with the backend variable names and handles.
    """
    var_dict_new = {}
    for var_name, var in var_dict.items():
        if var['vtype'] == 'raw':
            var_dict_new[var_name] = var['value']
        else:
            var.update(kwargs)
            if var_name == 'y' or var_name == 'y_delta':
                print(
                    f'Warning: Variable name {var_name} is reserved for pyrates-internal state variables. Variable was renamed to {var_name}1.'
                    )
                var_name = f'{var_name}1'
            var_dict_new[var_name] = backend.add_var(name=var_name, **var)
    return var_dict_new


def evalCpuNeeds(totLn, algorithm=None, debug=False):
    """
    Estimates the number of needed threads (cores) based on the total lines to be processed
    For the supported algorithms an estimation is given but should be updated when possible
    NOTES: it is very experimental and based on a very few samples
    """
    import multiprocessing
    maxCores = multiprocessing.cpu_count()
    buckets = [2, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128]
    if debug:
        print('\n evalCpuNeeds START:')
        print('TOT LINES ::\t%s' % str(totLn))
        print('ALGORITHM ::\t%s' % str(algorithm))
    chunkDict = {'bwa': 720000, 'map_pct_calc': 400000, 'avg': 560000}
    if algorithm == None:
        algorithm = 'avg'
    chunkSize = chunkDict[algorithm]
    if chunkSize >= totLn:
        if debug:
            print(
                'Chunk size is bigger than the line to be porcessed, 1 core will do just fine...'
                )
        return 1
    cores = int(totLn / chunkSize)
    if debug:
        print('Selected Algorimth for Estimation:\t%s' % algorithm)
        print('CHUNK SIZE FOR %s ALGORITHM:\t%d' % (algorithm.upper(),
            chunkSize))
    if cores >= maxCores:
        return maxCores
    if algorithm != 'map_pct_calc':
        for el in buckets:
            if float(cores / el) <= 1:
                return el
    return cores


def history_track_wrapper(player, opponent, action):
    """Wrapper to track a player's history in a variable `._recorded_history`."""
    try:
        player._recorded_history.append(action)
    except AttributeError:
        player._recorded_history = [action]
    return action


@staticmethod
def execute_sp_table(sql: str, *params) ->int:
    """
        Executes a stored routine with designation type "table". Returns the number of rows.

        :param str sql: The SQL calling the the stored procedure.
        :param iterable params: The arguments for calling the stored routine.

        :rtype: int
        """
    raise NotImplementedError()


def isolate_code():
    """Exits the program showing message. Easy way to protect test/conversion scripts from running again"""
    import sys
    sys.exit(
        """

Not running this program again, sorry.

This program was designed to run only once.

"""
        )


@staticmethod
def plot_file_distances(dist_matrix):
    """
        Plots dist_matrix

        Parameters
        ----------
        dist_matrix: np.ndarray
        """
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.matshow(dist_matrix, interpolation='nearest', cmap=plt.cm.get_cmap(
        'PuBu'))


def ln(label):
    """Draw a 70-char-wide divider, with label in the middle.

    >>> ln('hello there')
    '---------------------------- hello there -----------------------------'
    """
    label_len = len(label) + 2
    chunk = (70 - label_len) // 2
    out = '%s %s %s' % ('-' * chunk, label, '-' * chunk)
    pad = 70 - len(out)
    if pad > 0:
        out = out + '-' * pad
    return out


def match_type(obj, matchers):
    """Matches a given object using the given matchers list/iterable.

    NOTE(harlowja): each element of the provided list/iterable must be
    tuple of (valid types, result).

    Returns the result (the second element of the provided tuple) if a type
    match occurs, otherwise none if no matches are found.
    """
    for match_types, match_result in matchers:
        if isinstance(obj, match_types):
            return match_result
    else:
        return None


def driver_variables_copy():
    """Copy the driver variables of the active F-Curve

    """
    pass


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


def skip(_in, out, **kw):
    """filter to skip content of assets which are fetched from CDN in production."""
    out.write('')


def parse_set(string):
    """Parse set from comma separated string."""
    string = string.strip()
    if string:
        return set(string.split(','))
    else:
        return set()


@staticmethod
def annotates_memlets():
    """ Indicates whether the transformation annotates the edges it creates
            or modifies with the appropriate memlets. This determines
            whether to apply memlet propagation after the transformation.
        """
    return False


@classmethod
def get_subject_name_for_key(cls, base_namespace: str,
    schema_fully_qualified_name: str) ->str:
    """
        Returns the Avro subject name given the schema fully qualified name.

        The fully qualified name of a schema is generated according to
        "io.confluent.kafka.serializers.subject.TopicRecordNameStrategy"

        # It uses the "io.confluent.kafka.serializers.subject.TopicNameStrategy",
        # i.e. "<topic>-key"

        :param base_namespace: The schemas base namespace
        :param schema_fully_qualified_name: Fully qualified name of the schema
        :return: The subject name
        """
    topic = cls.get_topic(base_namespace, schema_fully_qualified_name)
    return topic + '-' + schema_fully_qualified_name


def fastqReader(inputFile):
    """A fast and robust fastq parser.

    Deals with multiline sequences and quality scores.
    Allows arbitrary numbers of empty lines anywhere in the file.
    Performs (only) the following file format checks while parsing:
    - each title line MUST start with @ symbol
    - each record MUST have a sequence
    - sequence and quality score of each record MUST be of equal length
    No alphabet checks are done on sequences or quality scores."""
    title_token = ord('@')
    sep_token = ord('+')
    while True:
        try:
            title = next(inputFile)
        except StopIteration:
            return
        if not title[0] == title_token:
            if not title.rstrip():
                continue
            raise AssertionError(
                'Invalid file format: Title line not starting with @')
        title = title.rstrip()
        line_tmp = []
        try:
            while True:
                currentLine = next(inputFile)
                if currentLine[0] == sep_token:
                    break
                line_tmp.append(currentLine.rstrip())
            seq = b''.join(line_tmp)
            seqlen = len(seq)
            if seqlen == 0:
                raise AssertionError(
                    'Invalid file format: Record without sequence')
            quallen = 0
            line_tmp = []
            while seqlen > quallen:
                currentLine = next(inputFile).rstrip()
                line_tmp.append(currentLine)
                quallen += len(currentLine)
        except StopIteration:
            raise AssertionError(
                'Invalid file format: Truncated record at end of file')
        if seqlen < quallen:
            raise AssertionError(
                'Invalid file format: Inconsistent lengths of sequence and quality score'
                )
        qual = b''.join(line_tmp)
        yield title, seq, qual


def camel_case_from_underscores(string):
    """generate a CamelCase string from an underscore_string."""
    components = string.split('_')
    string = ''
    for component in components:
        string += component[0].upper() + component[1:]
    return string


def hyphen_range(s, first=None, last=None):
    """ creates a list with each integer from a complex range string like "1-9,12, 15-20,23".
        The wildcard '*' returns [first, last+1].

    >>> list(hyphen_range('1-9,12, 15-20,23'))
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]

    >>> list(hyphen_range('1-9,12, 15-20,2-3-4'))
    Traceback (most recent call last):
        ...
    ValueError: format error in 2-3-4
    """
    res = []
    if s == '*':
        if first is None or last is None:
            raise ValueError(
                'Wildcard range requires first and last of index list')
        res = list(range(first, last + 1))
    else:
        for x in s.split(','):
            elem = x.split('-')
            if len(elem) == 1:
                res.append(int(elem[0]))
            elif len(elem) == 2:
                start, end = map(int, elem)
                for i in range(start, end + 1):
                    res.append(i)
            else:
                raise ValueError('format error in %s' % x)
    return res


@staticmethod
def get_environment_metadata():
    """
        For debugging purposes, returns a dict containing information
        about the environment, like the version of the SCM client, or
        version of libraries involved.
        Suggest considering keywords "version", "dependency", "features" first.
        :returns: a dict containing relevant information
        :rtype: dict
        """
    raise NotImplementedError(
        'Base class get_environment_metadata method must be overridden')


def symlink(srcPath, destPath):
    """create a symbolic link from srcPath to destPath"""
    import os
    return os.symlink(srcPath, destPath)


def fill_categorical_na(df, nan_cat='NA'):
    """Fill categoricals with 'NA', possibly creating a new category,
    and fill other NaNa with blanks """
    for col in df.columns[df.isna().any()].tolist():
        if df[col].dtype.name != 'category':
            df[col] = df[col].fillna('')
        else:
            try:
                df[col].cat.add_categories([nan_cat], inplace=True)
            except ValueError:
                pass
            df[col] = df[col].fillna(nan_cat)
    return df


def first(iterable):
    """Return first element of iterable"""
    try:
        return next(iter(iterable))
    except StopIteration:
        raise IndexError


def timedelta_seconds(delta):
    """Convert :class:`datetime.timedelta` to seconds.

    Doesn't account for negative values.

    """
    return max(delta.total_seconds(), 0)


def ones_like(data=None, out=None, name=None, **kwargs):
    """Return an array of ones with the same shape and type
    as the input array.

    Examples::

      x = [[ 0.,  0.,  0.],
           [ 0.,  0.,  0.]]

      ones_like(x) = [[ 1.,  1.,  1.],
                      [ 1.,  1.,  1.]]

    Parameters
    ----------
    data : NDArray
        The input

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def manage_getPermissionMapping():
    """Return the permission mapping for the object

        This is a list of dictionaries with:

          permission_name -- The name of the native object permission

          class_permission -- The class permission the permission is
             mapped to.
        """


def parse_infernal_table(infernal_table):
    """
    Function to parse the `--tblout` file from Infernal, generating a list of sequence names
    that meet pre-defined thresholds and their start and end positions on their contig
    :return: A dictionary containing contig names, and the start and end positions of an rRNA sequence (tuple)
    """
    rrna_seqs = dict()
    return rrna_seqs


def bind(**kw):
    """Bind subscribers to events.

        :param kw: Each keyword argument is the event name and the argument
            value is the subscriber callable.
        """


@staticmethod
def matrix_multiply(m, s):
    """
        [a c e]      [a c e]   [a b 0]
        [b d f]   %  [b d f] = [c d 0]
        [0 0 1]      [0 0 1]   [e f 1]

        :param m0: matrix operand
        :param m1: matrix operand
        :return: muliplied matrix.
        """
    r0 = (s.a * m.a + s.c * m.b + s.e * 0, s.a * m.c + s.c * m.d + s.e * 0,
        s.a * m.e + s.c * m.f + s.e * 1)
    r1 = (s.b * m.a + s.d * m.b + s.f * 0, s.b * m.c + s.d * m.d + s.f * 0,
        s.b * m.e + s.d * m.f + s.f * 1)
    return float(r0[0]), float(r1[0]), float(r0[1]), float(r1[1]), r0[2], r1[2]


def _write_output_file(json_filename, json_contents):
    """ _write_output_file
    Just writes text to a file.
    """
    with open(json_filename, 'w') as file_obj:
        file_obj.write(json_contents)
        file_obj.close()


def resolve_ref(schema_dict, ref):
    """
    Resolves a local ref in the form of ``#/definitions/dog`` or
    ``#/parameters/cat``.

    :param dict schema_dict: A raw, json-decoded schema.
    """
    kind, name = ref.split('/')[1:]
    return schema_dict[kind][name]


@classmethod
def from_cell(cls, cell):
    """
        Class method to convert cell comment
        """
    comment = cell._comment
    ref = cell.coordinate
    self = cls(ref=ref, author=comment.author)
    self.text.t = comment.content
    self.height = comment.height
    self.width = comment.width
    return self


def p_tablemaker2(p):
    """tablemaker2 : "," maybe_nline stringliteral ":" expression
                   | tablemaker2 "," maybe_nline stringliteral ":" expression
                   |  """
    if len(p) == 6:
        p[0] = [(p[3], p[5])]
    elif len(p) < 2:
        p[0] = []
    else:
        p[0] = p[1] + [(p[4], p[6])]


def not_resource_cachable(bel_resource):
    """Check if the BEL resource is cacheable.

    :param dict bel_resource: A dictionary returned by :func:`get_bel_resource`.
    """
    return bel_resource['Processing'].get('CacheableFlag') not in {'yes',
        'Yes', 'True', 'true'}


def zerocopy_to_dlpack(input):
    """Create a dlpack tensor that shares the input memory.

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

    Returns
    -------
    dlpack capsule
        A dlpack capsule that can be used by other framework.
    """
    pass


def oracle_create_auto_increment(_table, _column):
    """Work around Oracle's silly unwillingness to support auto increment."""
    result = list()
    _new_seq = (_table.name + '_' + _column.name + '_seq')[0:29]
    result.append('')
    result[0] = 'CREATE SEQUENCE ' + _new_seq + _table.row_separator
    result[0] += 'start with 1' + _table.row_separator
    result[0] += 'increment by 1 ' + _table.row_separator
    result[0] += 'nomaxvalue'
    result.append('')
    result[1] = 'CREATE TRIGGER ' + ('tr_' + _table.name + '_' + _column.name)[
        0:29] + _table.row_separator
    result[1
        ] += 'BEFORE INSERT ON "' + _table.name + '"' + _table.row_separator
    result[1] += ('FOR EACH ROW WHEN (new."' + _column.name +
        '" IS NULL) BEGIN' + _table.row_separator)
    result[1] += ('SELECT ' + _new_seq + '.nextval INTO :new."' + _column.
        name + '" FROM dual;' + _table.row_separator)
    result[1] += 'END;'
    return result


@classmethod
def from_arg_kinds(cls, arch, fp_args, ret_fp=False, sizes=None, sp_delta=
    None, func_ty=None):
    """
        Get an instance of the class that will extract floating-point/integral args correctly.

        :param arch:        The Archinfo arch for this CC
        :param fp_args:     A list, with one entry for each argument the function can take. True if the argument is fp,
                            false if it is integral.
        :param ret_fp:      True if the return value for the function is fp.
        :param sizes:       Optional: A list, with one entry for each argument the function can take. Each entry is the
                            size of the corresponding argument in bytes.
        :param sp_delta:    The amount the stack pointer changes over the course of this function - CURRENTLY UNUSED
        :parmm func_ty:     A SimType for the function itself
        """
    basic = cls(arch, sp_delta=sp_delta, func_ty=func_ty)
    basic.args = basic.arg_locs(fp_args, sizes)
    basic.ret_val = basic.fp_return_val if ret_fp else basic.return_val
    return basic


def hasProperty(tag):
    """
        Return boolean indicating whether the named property exists has
        a dead property for the current resource.
        """


def parse_pubsub_numpat(command, res, **options):
    """
    Result callback, handles different return types
    switchable by the `aggregate` flag.
    """
    aggregate = options.get('aggregate', True)
    if not aggregate:
        return res
    numpat = 0
    for node, node_numpat in res.items():
        numpat += node_numpat
    return numpat


def xml_element_to_dict(e):
    """
    Creates a dictionary of the given xml tree.

    Parameters
    ----------
    e : str
        str of an xml tree

    Returns
    -------
    A dictionary of the given xml tree
    """
    d = {}
    for c in e.getchildren():
        d[c.tag] = c.text
    return d


def meantensor(sample, normalized=False):
    """Estimates the mean tensor :math:`\\boldsymbol{k}` of a randomly chosen
    sample of :math:`n` specimens by using the equation (11) of
    `Jelínek (1978) <https://doi.org/10.1007/BF01613632>`_ after being
    normalized the specimens through the ``normalizeTensors`` function.

    Parameters:
        sample (`numpy.ndarray`): :math:`(n \\times 6)` array that
            contains the values of the tensors after being imported with the
            ``extractdata`` function.
        normalize (`bool`): Logical variable to indicate if the tensors in
            the ``sample`` variable are already normalized by using the
            equation (11) of
            (`Jelínek (1978) <https://doi.org/10.1007/BF01613632>`_). ``False``
            is the default value. In the case they are not normalized,
            they will be.

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

            - **meanTensorVect** (`numpy.ndarray`): Mean tensor in vector                form.
            - **meanTensorMtx** (`numpy.ndarray`): Mean tensor in matrix                form.
            - **numTensors** (`int`): Number of tensors.

    Examples:
        >>> from jelinekstat.tools import dataFromFile
        >>> from jelinekstat.jelinekstat import meantensor
        >>> sample, numTensors = dataFromFile('inputDataExample.txt')
        >>> meanTensorVect, meanTensorMtx, numTensors = meantensor(
                sample, normalized=False)
        >>> meanTensorVect
        array([ 1.02533293,  1.01891542,  0.95575165, -0.01714126, -0.03435001,
        >>>    -0.03794001])
        >>> meanTensorMtx
        array([[ 1.02533293, -0.01714126, -0.03794001],
               [-0.01714126,  1.01891542, -0.03435001],
               [-0.03794001, -0.03435001,  0.95575165]])
        >>> numTensors
        8
    """
    import numpy as np
    from jelinekstat.tools import tensorvect2matrixform
    sample = sample.T
    numTensors = np.shape(sample)[1]
    tensorsList = list()
    normalizedTensorsList = list()
    for i in range(numTensors):
        T = sample[:, (i)]
        tensorsList.append(T)
        if normalized:
            normalizedTensorsList.append(T)
        else:
            inv1 = sum(T[0:3]) / 3
            normalizedTensorsList.append(T / inv1)
    meanTensorVect = np.mean(normalizedTensorsList, axis=0)
    meanTensorMtx = tensorvect2matrixform(meanTensorVect)
    return meanTensorVect, meanTensorMtx, numTensors


def zerocopy_from_numpy(np_array):
    """Create a tensor that shares the numpy array.

    Parameters
    ----------
    np_array : numpy.ndarray
        The numpy ndarray.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


def update_plugin_data(dashboard_entry, request=None):
    """Update plugin data of a dashboard entry."""
    if dashboard_entry:
        plugin = dashboard_entry.get_plugin(request=request)
        if plugin:
            return plugin._update_plugin_data(dashboard_entry)


def start(st_reg_number):
    """Checks the number valiaty for the Sergipe state"""
    divisor = 11
    if len(st_reg_number) > 9:
        return False
    if len(st_reg_number) < 9:
        return False
    sum_total = 0
    peso = 9
    for i in range(len(st_reg_number) - 1):
        sum_total = sum_total + int(st_reg_number[i]) * peso
        peso = peso - 1
    rest_division = sum_total % divisor
    digit = divisor - rest_division
    if digit == 10 or digit == 11:
        digit = 0
    return digit == int(st_reg_number[len(st_reg_number) - 1])


def translate_resourcetypes(url):
    """ translate urls such as /sources/{uid}/ -> sources/{uid} """
    trimmed = url.strip('/')
    split = trimmed.split('/')
    if len(split) >= 2:
        return '{}/{}'.format(split[0], split[1].lower())
    elif len(split) == 1:
        return split[0]
    else:
        return ''


def setMembers(value):
    """
        Set members of group to the principal IDs in the iterable
        *value*.
        """


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

        :param TeamMergeRequestCanceledDetails val:
        :rtype: EventDetails
        """
    return cls('team_merge_request_canceled_details', val)


def identify_requirment(r):
    """Produce an identifier for a requirement to use in the resolver.

    Note that we are treating the same package with different extras as
    distinct. This allows semantics like "I only want this extra in
    development, not production".

    This also makes the resolver's implementation much simpler, with the minor
    costs of possibly needing a few extra resolution steps if we happen to have
    the same package apprearing multiple times.
    """
    return '{0}{1}'.format(r.normalized_name, r.extras_as_pip)


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

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

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


def set_axes_color(ax, color):
    """Set the axes, tick marks, etc of `ax` to mpl color `color`. Also,
    "doegreen" has special significance as the color associated with the
    US department of energy."""
    if color == 'doegreen':
        color = 33 / 255, 99 / 255, 50 / 255
    ax.spines['bottom'].set_color(color)
    ax.spines['top'].set_color(color)
    ax.spines['right'].set_color(color)
    ax.spines['left'].set_color(color)
    ax.tick_params(axis='x', colors=color)
    ax.tick_params(axis='y', colors=color)
    ax.yaxis.label.set_color(color)
    ax.xaxis.label.set_color(color)


def is_tty(stream):
    """Returns True if the given stream is a tty, else False"""
    return hasattr(stream, 'isatty') and stream.isatty()


def isCurrentDay():
    """Return true if this object represents a date/time that
        falls within the current day, in the context of this object's
        timezone representation"""


@classmethod
def to_binary(cls, val, protocol_version):
    """
        Serialize a value into a bytestring. See the serialize() method for
        more information. This method differs in that if None is passed in,
        the result is the empty string.
        """
    return b'' if val is None else cls.serialize(val, protocol_version)


def first(seq):
    """
    return the first element in a python sequence
    for graphs, use graph.value instead
    """
    for result in seq:
        return result
    return None


@classmethod
def compute_rewritestring(cls, strip_extensions=False, digestlength=None,
    keep_dirs=False, hashfun='sha1'):
    """
        >>> Rewriter.compute_rewritestring()
        '%(abspath|content|sha1|base64)s%(suffix)s'
        >>> Rewriter.compute_rewritestring(strip_extensions=True)
        '%(abspath|content|sha1|base64)s'
        >>> Rewriter.compute_rewritestring(digestlength=3)
        '%(abspath|content|sha1|base64|3)s%(suffix)s'
        """
    if hashfun == 'identity':
        return '%(relpath)s'
    initial = ['abspath', 'content', hashfun, 'base64']
    if digestlength:
        initial.append(str(digestlength))
    rewritestring = '%(' + '|'.join(initial) + ')s'
    if keep_dirs:
        rewritestring = '%(reldir)s' + rewritestring
    if not strip_extensions:
        rewritestring += '%(suffix)s'
    return rewritestring


@classmethod
def from_lines(cls, lines, delete_boundary_face=False, precision=None):
    """Construct a mesh object from a list of lines described by start and end point coordinates.

        Parameters
        ----------
        lines : list
            A list of pairs of point coordinates.
        delete_boundary_face : bool, optional
            The algorithm that finds the faces formed by the connected lines
            first finds the face *on the outside*. In most cases this face is not expected
            to be there. Therefore, there is the option to have it automatically deleted.
        precision: str, optional
            The precision of the geometric map that is used to connect the lines.

        Returns
        -------
        Mesh
            A mesh object.

        Examples
        --------
        >>>
        """
    from compas.datastructures import Network
    from compas.datastructures import network_find_cycles
    network = Network.from_lines(lines, precision=precision)
    vertices = network.to_points()
    faces = network_find_cycles(network)
    mesh = cls.from_vertices_and_faces(vertices, faces)
    if delete_boundary_face:
        mesh.delete_face(0)
        mesh.cull_vertices()
    return mesh


def runLengthDecode(stream):
    """
        Method to decode streams using the Run-Length algorithm

        @param stream: A PDF stream
        @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1
    """
    decodedStream = ''
    index = 0
    try:
        while index < len(stream):
            length = ord(stream[index])
            if length >= 0 and length < 128:
                decodedStream += stream[index + 1:index + length + 2]
                index += length + 2
            elif length > 128 and length < 256:
                decodedStream += stream[index + 1] * (257 - length)
                index += 2
            else:
                break
    except:
        return -1, 'Error decoding string'
    return 0, decodedStream


@staticmethod
def list_from_matrix(A, m, n):
    """Convert a Matlab matrix to a Python list."""
    nlist = []
    for row in range(m):
        nlist.append([None] * n)
        for col in range(n):
            nlist[row][col] = A[row, col]
    return nlist


def __new__(cls, *args, **kwds):
    """
        This is necessary to be a subclass of `type`, which is necessary to be used in a
        Union.
        """
    return super().__new__(cls, cls.__name__, (), {})


def undo(cursor, undo_tid, self_tid):
    """Undo a transaction.

        Parameters: "undo_tid", the integer tid of the transaction to undo,
        and "self_tid", the integer tid of the current transaction.

        Returns the states copied forward by the undo operation as a
        list of (oid, old_tid).

        May raise UndoError.
        """


@staticmethod
def p_dp_blob(p):
    """dp_blob : DP_BLOB"""
    p[0] = p[1]


@classmethod
def filter_key(cls, json_result_file, max_num, *key_file_list):
    """
        过滤出包含当前query的结果行
        """
    keys = list()
    assert len(key_file_list) >= 1
    for words in cls.get_combination_word(*key_file_list):
        keys.append(' '.join(words))
    max_num = int(max_num)
    with open(json_result_file) as json_result_f:
        for line in json_result_f:
            line = line.strip()
            key, url, index = line.split('\t')
            index = int(index)
            if index <= max_num and key in keys:
                print(line)


def _old_api_error(obj_name):
    """
    Cause PyInstall to exit when .spec file uses old api.
    :param obj_name: Name of the old api that is no longer suppored.
    """
    raise SystemExit(
        '%s has been removed in PyInstaller 2.0. Please update your spec-file. See http://www.pyinstaller.org/wiki/MigrateTo2.0 for details'
         % obj_name)


def __call__(name, module):
    """Create an object with the given name in the given (dynamic) module.

        This will only be called once for each name. __module__ is the module
        that the object will live in, and name is the name of the object
        itself. That is,  the full dotted name of the generated object will be
        "{0}.{1}".format(module.__name__, name).

        This function should return a new object, or return None, in which
        case the dynamic module will generate an AttributeError. There is
        no need to mess with sys.modules or modify the 'module' object.
        """


def getStakeOutSubscript(pkScript):
    """Extracts the subscript (P2PKH or P2SH) from a stake output."""
    return pkScript[1:]


def _get_headers(headers, k):
    """
    Private function for abstracting differences in getting HTTP request
    headers on Python 2 vs. Python 3
    """
    if hasattr(headers, 'get_all'):
        return headers.get_all(k)
    else:
        return headers.getheaders(k)


def clamp(x, xmin, xmax):
    """Return the value of x, clamped from below by `xmin` and from above by `xmax`."""
    return max(xmin, min(x, xmax))


def with_files(function, files):
    """
    Call the function with the files opened.
    Files are received as a list opened in the order they occur in the
    input.
    """
    return function(files)


def datetime_to_str(dt):
    """
    Convert default datetime format to str & remove digits after int part of seconds
    """
    result = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-7]
    return result


def _check_library(string):
    """Returns a unicode number representing an alphabetical symbol

    Parameters
    ----------
    string : string
        String contains alphabetical symbol which should be transformed to unicode number

    Returns
    -------
    integer
        returns unicode number if transformation is successfull or '1' if TypeError occurs.
    """
    try:
        return ord(string)
    except TypeError:
        return 1


def convert_module(module, dtype):
    """
    Converts a module's immediate parameters and buffers to dtype.
    """
    for param in module.parameters(recurse=False):
        if param is not None:
            if param.data.dtype.is_floating_point:
                param.data = param.data.to(dtype=dtype)
            if (param._grad is not None and param._grad.data.dtype.
                is_floating_point):
                param._grad.data = param._grad.data.to(dtype=dtype)
    for buf in module.buffers(recurse=False):
        if buf is not None and buf.data.dtype.is_floating_point:
            buf.data = buf.data.to(dtype=dtype)


def bounding_box(bw, bh, w, h):
    """
    Returns a tuple (new_width, new_height) which has the property
    that it fits within box_width and box_height and has (close to)
    the same aspect ratio as the original size
    """
    new_width, new_height = w, h
    if bw and new_width > bw:
        new_width = bw
        new_height = new_width / (w / h)
    if bh and new_height > bh:
        new_height = bh
        new_width = new_height * (w / h)
    return new_width, new_height


def are_equal_nodes(n1, n2):
    """Returns True if nodes n1 and n2 have the same predicate and sortinfo."""
    return (n1.pred == n2.pred and n1.sortinfo == n2.sortinfo and n1.carg ==
        n2.carg)


def decibels_to_amplitude_ratio(decibels):
    """The ratio between two amplitudes given a decibel change"""
    return 2 ** (decibels / 10)


def _command_to_string(cmd):
    """Convert a list with command raw bytes to string."""
    return ' '.join(cmd)


def plot_cat_feature_importances(cb_clf):
    """Accepts a fitted CatBoost classifier model and plots the feature importances as a bar chart.
    Returns the results as a Series."""
    import pandas as pd
    important_feature_names = cb_clf.feature_names_
    important_feature_scores = cb_clf.feature_importances_
    important_features = pd.Series(important_feature_scores, index=
        important_feature_names)
    important_features.sort_values().plot(kind='barh')
    return important_features


def re_fix(reg):
    """
        Replace the invalid regex r'*' with the valid, wildcard regex r'/.*' to
        enable the CORS app extension to have a more user friendly api.
    """
    return '.*' if reg == '*' else reg


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


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


def usage(myname='xia2ccp4i.py'):
    """return a usage string"""
    msg = """%s [options]

Options:
-h, --help               show this help message and exit
-p FOO, --project=FOO    override the project name taken from xia2, and call
                         the CCP4 project FOO
-x BAR, --xia2dir=BAR    specify the location of the top-level xia2 processing
                         directory (omission implies BAR=".")

Extract project name and data from a xia2 processing run, create a standalone
ccp4i project and start ccp4i with that project.

Please note that this standalone ccp4i project will not be in the global
projects database of ccp4i. However it may be added later using the
'Directories&ProjectDir' button in ccp4i. The list of jobs performed in the
standalone project will remain intact after the import.
"""
    return msg % myname