def display_fully_qualified(repo_list, list_content, display_callback):
    """Display installed collections in a format more or less like they would be referenced in a playbook"""
    INDENT = ' '
    for repo_item in repo_list:
        repo_msg = '{installed_repository.repository_spec.ns_n_v}'
        display_callback(repo_msg.format(**repo_item))
        if not list_content:
            continue
        for content_item_type_key, content_items_data in repo_item[
            'content_items'].items():
            content_type_msg = '{indent:2}- {content_item_type}'.format(
                content_item_type=content_item_type_key, indent=INDENT)
            display_callback(content_type_msg)
            content_msg = (
                '{indent:4}- {installed_repository.repository_spec.label}.{name}'
                )
            for content_item_data in content_items_data:
                content_item_data['indent'] = INDENT
                display_callback(content_msg.format(**content_item_data))
                if content_item_data['is_plugin']:
                    python_path_msg = (
                        '{indent:6}- (python path) ansible_collections.{installed_repository.repository_spec.label}.plugins.{type}.{name}'
                        )
                    content_item_data['indent'] = INDENT
                    display_callback(python_path_msg.format(**
                        content_item_data))


@classmethod
def _from_dict(cls, _dict):
    """Initialize a CredentialDetails object from a json dictionary."""
    args = {}
    if 'credential_type' in _dict:
        args['credential_type'] = _dict.get('credential_type')
    if 'client_id' in _dict:
        args['client_id'] = _dict.get('client_id')
    if 'enterprise_id' in _dict:
        args['enterprise_id'] = _dict.get('enterprise_id')
    if 'url' in _dict:
        args['url'] = _dict.get('url')
    if 'username' in _dict:
        args['username'] = _dict.get('username')
    if 'organization_url' in _dict:
        args['organization_url'] = _dict.get('organization_url')
    if 'site_collection.path' in _dict:
        args['site_collection_path'] = _dict.get('site_collection.path')
    if 'client_secret' in _dict:
        args['client_secret'] = _dict.get('client_secret')
    if 'public_key_id' in _dict:
        args['public_key_id'] = _dict.get('public_key_id')
    if 'private_key' in _dict:
        args['private_key'] = _dict.get('private_key')
    if 'passphrase' in _dict:
        args['passphrase'] = _dict.get('passphrase')
    if 'password' in _dict:
        args['password'] = _dict.get('password')
    if 'gateway_id' in _dict:
        args['gateway_id'] = _dict.get('gateway_id')
    if 'source_version' in _dict:
        args['source_version'] = _dict.get('source_version')
    if 'web_application_url' in _dict:
        args['web_application_url'] = _dict.get('web_application_url')
    if 'domain' in _dict:
        args['domain'] = _dict.get('domain')
    return cls(**args)


def to_marshallable_type(obj):
    """Helper for converting an object to a dictionary only if it is not
    dictionary already or an indexable object nor a simple type"""
    if obj is None:
        return None
    if hasattr(obj, '__marshallable__'):
        return obj.__marshallable__()
    if hasattr(obj, '__getitem__'):
        return obj
    return dict(obj.__dict__)


def isclass(object):
    """Return true if the object is a class.

    Class objects provide these attributes:
        __doc__         documentation string
        __module__      name of module in which this class was defined"""
    return isinstance(object, type)


def form_partitions(sv_signatures, max_distance):
    """Form partitions of signatures using mean distance."""
    sorted_signatures = sorted(sv_signatures, key=lambda evi: evi.get_key())
    partitions = []
    current_partition = []
    for signature in sorted_signatures:
        if len(current_partition) > 0 and current_partition[-1
            ].downstream_distance_to(signature) > max_distance:
            partitions.append(current_partition[:])
            current_partition = []
        current_partition.append(signature)
    if len(current_partition) > 0:
        partitions.append(current_partition[:])
    return partitions


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 '+'


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


def _filterfnodes(tagfnode, nodes):
    """return a list of unique fnodes

    The order of this list matches the order of "nodes". Preserving this order
    is important as reading tags in different order provides different
    results."""
    seen = set()
    fnodes = []
    for no in nodes:
        fnode = tagfnode.get(no)
        if fnode and fnode not in seen:
            seen.add(fnode)
            fnodes.append(fnode)
    return fnodes


@classmethod
def name(cls):
    """" Returns short-name of the command. """
    return cls.__name__[:-7].lower()


def genVolumes():
    """
    Populates volumes for a list of folders
    :return:
    """
    pass


def binom(n, k):
    """Binomial coefficients for :math:`n \\choose k`

    :param n,k: non-negative integers
    :complexity: O(k)
    """
    prod = 1
    for i in range(k):
        prod = prod * (n - i) // (i + 1)
    return prod


def supports(behavior_interface):
    """Determine if the context supports the given behavior, returning
        True or False.
        """


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 _pick_tcga_submitter(a, b):
    """Comparator function for barcodes, using the rules described in the GDAC
    FAQ entry for replicate samples: https://confluence.broadinstitute.org/display/GDAC/FAQ
    """
    analyte1 = a[19]
    analyte2 = b[19]
    plate1 = a[21:25]
    plate2 = b[21:25]
    if a == b:
        return a
    elif analyte1 == analyte2:
        return a if a >= b else b
    elif analyte1 == 'H':
        return a
    elif analyte1 == 'R':
        return a if analyte2 == 'T' else b
    elif analyte1 == 'T':
        return b
    elif analyte1 == 'D':
        return a if plate2 <= plate1 else b
    elif analyte2 == 'D':
        return b if plate1 <= plate2 else a
    else:
        return a if a >= b else b


def _generate_unique_agency_id(df, col_name):
    """
    Generate unique agency id

    Parameters
    ----------
    df : pandas:DataFrame
    col_name : str
        typically will be 'agency_name'

    Returns
    -------
    col_snake_no_amps : str
    """
    col = df[col_name].astype(str)
    col_snake_case = col.str.replace('\\s+', '_')
    col_snake_no_amps = col_snake_case.str.replace('&', 'and')
    return col_snake_no_amps.str.lower()


@staticmethod
def upsert_multi(db, collection, object, match_params=None):
    """
        Wrapper for pymongo.insert_many() and update_many()
        :param db: db connection
        :param collection: collection to update
        :param object: the modifications to apply
        :param match_params: a query that matches the documents to update
        :return: ids of inserted/updated document
        """
    if isinstance(object, list) and len(object) > 0:
        return str(db[collection].insert_many(object).inserted_ids)
    elif isinstance(object, dict):
        return str(db[collection].update_many(match_params, {'$set': object
            }, upsert=False).upserted_id)


def interactive(state):
    """Toggle interactive mode"""
    global _interactive
    _interactive = state


def receive(type=None):
    """Return all messages of the given type relevant to the current
        request.
        """


@staticmethod
def formatetfindexjson(fundbjson):
    """格式化集思录返回 指数ETF 的json数据,以字典形式保存"""
    result = {}
    for row in fundbjson['rows']:
        cell = row['cell']
        fundb_id = cell['fund_id']
        result[fundb_id] = cell
    return result


def mag_union(A, B):
    """
    Returns magnitude of multiset-union of A and B
    """
    val = 0
    for term in A:
        val += A[term]
    for term in B:
        val += B[term]
    return val


def removeeppykeys(idfmunch, rkeys=None):
    """remove the eppykeys"""
    if not rkeys:
        rkeys = ['eppykey', 'eppyname', 'eppy_objidd']
    for key, val in idfmunch.items():
        for key1, val1 in val.items():
            for rkey in rkeys:
                val1.pop(rkey, None)


def remove_media_permissions(apps, schema_editor):
    """Reverse the above additions of permissions."""
    ContentType = apps.get_model('contenttypes.ContentType')
    Permission = apps.get_model('auth.Permission')
    media_content_type = ContentType.objects.get(model='media', app_label=
        'wagtailmedia')
    Permission.objects.filter(content_type=media_content_type, codename__in
        =('add_media', 'change_media', 'delete_media')).delete()


def generatehamiltoniantring(n, s, onestring=None, pos=None, pad=None):
    """
    This generates a string that is used to construct tensor products terms in Hamiltonian with a certain kind of
    interaction term. For example suppose we have an ising Hamiltonian with 4 qubits. We generate strings in a
    list 1100, 0110,0011. The zero will be used to tensor an identity and the 1 will be used to tensor the pauli
    matrix.
    :param n: The number of qubits we have in our system
    :param s: This is a string of 1's that determines how local our hamiltonian is. So a three body interaction
    means we need '111' or a two body interaction will be '11'
    :param onestring: If you would rather generate one string than a list of strings
    :param pos: The position where the string s should start  (only if onestring is not none)
    :param pad: Rather than padding with zeros you could pad with some other number (only if onestring
    is not none)
    :return: Returns a list of strings that will be used to create the Hamiltonian
    """
    label = []
    if onestring is None:
        if isinstance(s, str):
            for i in range(0, n):
                strs = s
                strs = strs.ljust(n - i, '0')
                strs = strs.rjust(n, '0')
                label.append(strs)
        else:
            print(
                'Please enter string for second variable and integer for first'
                )
        return label
    else:
        strs = s
        strs = strs.ljust(n - pos, pad)
        strs = strs.rjust(n, pad)
        return strs


@staticmethod
def repr_value(val):
    """
        Return string representation for value

        """
    return val.__repr__()


def _key_press(event, params):
    """Handle key presses for the animation."""
    if event.key == 'left':
        params['pause'] = True
        params['frame'] = max(params['frame'] - 1, 0)
    elif event.key == 'right':
        params['pause'] = True
        params['frame'] = min(params['frame'] + 1, len(params['frames']) - 1)


def iter_validation_errors(validation_error):
    """
    **Example usage**

    >>> from django.core.exceptions import ValidationError
    >>> from pytoolbox.unittest import asserts
    >>> eq = lambda i, l: asserts.list_equal(list(i), l)
    >>> bad, boy = ValidationError('yo', code='bad'), ValidationError('yo', code='boy')
    >>> eq(iter_validation_errors(bad), [(None, bad)])
    >>> eq(iter_validation_errors(ValidationError({'__all__': boy})), [('__all__', boy)])
    >>> eq(iter_validation_errors(ValidationError([bad, boy])), [(None, bad), (None, boy)])
    """
    if hasattr(validation_error, 'error_dict'):
        for field, errors in validation_error.error_dict.iteritems():
            for error in errors:
                yield field, error
    else:
        for error in validation_error.error_list:
            yield None, error


def _getAreaFromMatch(dict_):
    """
    Returns code area based on the match dict
    """
    if dict_['entity_name'] is not None:
        return 'entity'
    if dict_['architecture_name'] is not None:
        return 'architecture'
    if dict_['package_name'] is not None:
        return 'package'
    if dict_['package_body_name'] is not None:
        return 'package_body'
    assert False, "Can't determine area from {}".format(dict_)


def findRelationships(query):
    """Given a single dictionary of {indexName: token}, return an iterable
        of relationships that match the query intransitively"""


def __iter__():
    """ An alias for ``keys``.

        Respect ``order``, if set.
        """


def is_kernelspec_model(spec_dict):
    """Returns True if spec_dict is already in proper form.  This will occur when using a gateway."""
    return (isinstance(spec_dict, dict) and 'name' in spec_dict and 'spec' in
        spec_dict and 'resources' in spec_dict)


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

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


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


def shortUUID(uuidStr):
    """Shorten an uuid string.
	"""
    uuidStr = str(uuidStr).strip()
    if len(uuidStr) == 36 and uuidStr[8] == '-' and uuidStr[13
        ] == '-' and uuidStr[18] == '-' and uuidStr[23] == '-':
        uuidStr = uuidStr[0:4] + '.' + uuidStr[-3:-1]
    return uuidStr


def leap(year):
    """Is a given year a leap year in the Persian calendar ?"""
    if year > 0:
        y = 474
    else:
        y = 473
    return (year - y % 2820 + 474 + 38) * 682 % 2816 < 682


def edict_to_csv(line):
    """
    Convert an EDICT dictionary entry into CSV.

    Given a line from an EDICT-format dictionary, attempt to convert it
    into CSV format using the "|" character. If no alternate form or
    pronunciation is available in square brackets, then it will default to
    an empty string in the corresponding CSV column. The basic format
    returned is 'term1|term2|alternate|gloss', where term1 and term2 are
    the terms, alternate is the transliteration (e.g. Pinyin or kana), and
    gloss is the set of meanings or definitions for the entry.

    """
    alt = ''
    if ' [' in line and '] ' in line and line.index(' [') < line.index('] '):
        alt = line[line.index(' [') + 2:line.index('] ')]
    if alt:
        term = line[:line.index(' [')]
    else:
        term = line[:line.index(' /')]
    gloss = line[line.index('/') + 1:line.rindex('/')].replace('/', '; ')
    if gloss[-1] != '.':
        gloss += '.'
    entry = []
    term = term.replace('|', '/')
    alt = alt.replace('|', '/')
    gloss = gloss.replace('|', '/')
    return '%s||%s|%s\n' % (term, alt, gloss)


@staticmethod
def _normalize_merge_diff(diff):
    """Make compare_config() for merge look similar to replace config diff."""
    new_diff = []
    for line in diff.splitlines():
        if line.strip():
            new_diff.append('+' + line)
    if new_diff:
        new_diff.insert(0,
            '! incremental-diff failed; falling back to echo of merge file')
    else:
        new_diff.append('! No changes specified in merge file.')
    return '\n'.join(new_diff)


def setup(app):
    """Run custom code with access to the Shinx application object

    Args:
        app: the Sphinx application object
    """
    app.add_stylesheet('custom.css')


def setup_http_session(session, args):
    """Sets the global HTTP settings, such as proxy and headers."""
    if args.http_proxy:
        session.set_option('http-proxy', args.http_proxy)
    if args.https_proxy:
        session.set_option('https-proxy', args.https_proxy)
    if args.http_cookie:
        session.set_option('http-cookies', dict(args.http_cookie))
    if args.http_header:
        session.set_option('http-headers', dict(args.http_header))
    if args.http_query_param:
        session.set_option('http-query-params', dict(args.http_query_param))
    if args.http_ignore_env:
        session.set_option('http-trust-env', False)
    if args.http_no_ssl_verify:
        session.set_option('http-ssl-verify', False)
    if args.http_disable_dh:
        session.set_option('http-disable-dh', True)
    if args.http_ssl_cert:
        session.set_option('http-ssl-cert', args.http_ssl_cert)
    if args.http_ssl_cert_crt_key:
        session.set_option('http-ssl-cert', tuple(args.http_ssl_cert_crt_key))
    if args.http_timeout:
        session.set_option('http-timeout', args.http_timeout)
    if args.http_cookies:
        session.set_option('http-cookies', args.http_cookies)
    if args.http_headers:
        session.set_option('http-headers', args.http_headers)
    if args.http_query_params:
        session.set_option('http-query-params', args.http_query_params)


def list_item_indexes(_list, item):
    """
    returns all indexes where an item appears in a list
    """
    ret = []
    for i, val in enumerate(_list):
        if val == item:
            ret.append(i)
    return ret


@classmethod
def first_or_initialize(cls, parent=None, **attributes):
    """
        Attempts to find the first resource with the same attributes, initialized the resource if no matches are found.
        This will trigger an api GET request.
        :param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
        :param **attributes: any number of keyword arguments as attributes to search/initialize the resource
        :returns: a resource instance - the existing one if found, otherwise the newly instantiated one
        """
    existing_resource = cls.find_by(parent, **attributes)
    if existing_resource:
        return existing_resource
    return cls(**attributes)


def delete_pyc_file(python_script):
    """
    Deletes the .pyc file that corresponds to the given .py file
    :param python_script: str
    """
    from tpDcc.libs.python import path, fileio
    script_name = path.get_basename(python_script)
    if not python_script.endswith('.py'):
        print('WARNING: Could not delete .pyc file for {}!'.format(script_name)
            )
        return
    compile_script = python_script + 'c'
    if path.is_file(compile_script):
        compile_name = path.get_basename(compile_script)
        compile_dir_name = path.get_dirname(compile_script)
        if not compile_name.endswith('.pyc'):
            return
        fileio.delete_file(name=compile_name, directory=compile_dir_name)


def compute_Rn_c(albedo_c, T_air, T_c, T_s, e_atm, Rs_c, F):
    """Compute Canopy Net Radiation

    Parameters
    ----------
    albedo_c : ee.Image
    T_air : ee.Image
        Air temperature (Kelvin).
    T_c : ee.Image
        Canopy temperature (Kelvin).
    T_s : ee.Image
        Soil temperature (Kelvin).
    e_atm : ee.Image
    Rs_c : ee.Image
    F : ee.Image

    Returns
    -------
    Rn_c : ee.Image

    """
    kL = 0.95
    eps_s = 0.94
    eps_c = 0.99
    Lc = T_c.expression('eps_c * 5.67E-8 * (T_c ** 4)', {'eps_c': eps_c,
        'T_c': T_c})
    Ls = T_s.expression('eps_s * 5.67E-8 * (T_s ** 4)', {'eps_s': eps_s,
        'T_s': T_s})
    Rle = T_air.expression('e_atm * 5.67E-8 * (T_air ** 4)', {'e_atm':
        e_atm, 'T_air': T_air})
    Rn_c = albedo_c.expression(
        '((1 - albedo_c) * Rs_c) + ((1 - exp(-kL * F)) * (Rle + Ls - 2 * Lc))',
        {'albedo_c': albedo_c, 'F': F, 'kL': kL, 'Lc': Lc, 'Ls': Ls, 'Rle':
        Rle, 'Rs_c': Rs_c})
    return Rn_c


def _try_compile(source, name):
    """Attempts to compile the given source, first as an expression and
       then as a statement if the first approach fails.

       Utility function to accept strings in functions that otherwise
       expect code objects
    """
    try:
        c = compile(source, name, 'eval')
    except SyntaxError:
        c = compile(source, name, 'exec')
    return c


def underline(line, underline='~'):
    """Return an underline string for ``line``.

    Intended for use with level 3 and lower headings.

    Note that the default for ``underline`` assumes that the level
    1 and 2 underlines are the standard ``=`` and ``-``. You can
    pass a different underline character to this function if needed.
    """
    if line.endswith('\n'):
        line = line[:-1]
    return '{}\n'.format(underline * len(line))


def upload(uploadable):
    """Upload some data into a CHK, get back the UploadResults for it.
        @param uploadable: something that implements IUploadable
        @return: a Deferred that fires with the UploadResults instance.
                 To get the URI for this file, use results.uri .
        """


def post_install(context):
    """Post install script"""


def processMail(request):
    """
           Extracts a message from an HTTP request and processes it for the
           mailing list.  Checks the validity of the sender and whether
           moderation is needed.  Expects a request variable 'Mail' containing
           the mail message with headers
        """


def get_calculation_annotation(calculation_field, calculation_method):
    """
    Returns the default django annotation
    @param calculation_field: the field to calculate ex 'value'
    @param calculation_method: the aggregation method ex: Sum
    @return: the annotation ex value__sum
    """
    return '__'.join([calculation_field.lower(), calculation_method.name.
        lower()])


def _normaliseBounds(shape, bounds):
    """Adjust the given ``bounds`` so that it is compatible with the given
    ``shape``.

    Bounds must be specified for at least three dimensions - if the shape
    has more than three dimensions, additional bounds are added.

    A :exc:`ValueError` is raised if the provided bounds are invalid.

    :arg bounds: Sequence of ``(lo, hi)`` bounds - see :func:`roi`.
    :returns:    An adjusted sequence of bounds.
    """
    bounds = list(bounds)
    if len(bounds) < 3:
        raise ValueError('')
    if len(bounds) > len(shape):
        raise ValueError('')
    for b in bounds:
        if len(b) != 2 or b[0] >= b[1]:
            raise ValueError('')
    if len(bounds) < len(shape):
        for s in shape[len(bounds):]:
            bounds.append((0, s))
    return bounds


@classmethod
def cancel_all(cls, pipeline):
    """Cancel all jobs via SLURM scancel corresponding to pipeline.

        Parameters
        ----------
        pipeline : str | dict
            Pipeline config file path or dictionary.
        """
    pipe = cls(pipeline)
    pipe._cancel_all_jobs()


def unaugment_tiles(y):
    """ reverse test-time augmentations for averaging

    Parameters
    ----------

    y: float32
        array that's ntiles x chan x Ly x Lx where chan = (dY, dX, cell prob)
        if unet is used, array is ntiles x 1 x Ly x Lx

    Returns
    -------

    y: float32

    """
    for k in range(y.shape[0]):
        if k % 4 == 1:
            y[(k), :, :, :] = y[(k), :, ::-1, :]
            y[(k), (0), :, :] *= -1
        if k % 4 == 2:
            y[(k), :, :, :] = y[(k), :, :, ::-1]
            y[(k), (1), :, :] *= -1
        if k % 4 == 3:
            y[(k), :, :, :] = y[(k), :, ::-1, ::-1]
            y[(k), (0), :, :] *= -1
            y[(k), (1), :, :] *= -1
    return y


def clean_whitespace(text):
    """Alternate method of cleaning whitespace"""
    return ' '.join(text.split())


def total_seconds(delta):
    """Determines total seconds with python < 2.7 compat."""
    return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) *
        1000000.0) / 1000000.0


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

        :param TeamMergeRequestAcceptedShownToPrimaryTeamType val:
        :rtype: EventType
        """
    return cls('team_merge_request_accepted_shown_to_primary_team', val)


@classmethod
def complete_new_graph(cls, service, uri, parameters, new_graph, resource=None
    ):
    """I implement :meth:`ILocalCore.complete_new_graph`.

        I leave the graph unchanged.
        """
    pass


@classmethod
def forciblyPurgeJavaScriptMemory(cls):
    """Simulate OomIntervention by purging V8 memory.
        """
    return cls.build_send_payload('forciblyPurgeJavaScriptMemory', {}), None


def replace_none(value, default, lazy=False):
    """Return value if it's not None, otherwise return default value

    Parameters
    ----------
    value: object, None
        An object that we intend to replace if None
    default: object, callable
        Either a default returned value or function to be called if value is
        None
    lazy: bool, optional
        If True, default is a 0-argument function that is run if value is None.
        If False, default is treated as a value

    Returns
    -------
    object
    """
    if value is None:
        if lazy:
            return default()
        else:
            return default
    else:
        return value


def prospect_defaultvalues():
    """
    Gives some mean values from Jacquemoud et al. 1996 (very rough calculations based on Table 1)
        anthocyanin from Table 1 (rows 2-5, based on R&T measurements) in Feret et al. 2017
    Note -- different PROSPECT flavors have different argument list lengths, but the same order
        0:N, 1:Cab, 2:Cw, 3:Cm, 4:Car=0, 5:Cbrown=0, 6:Anth=0, 7:Cp=0, 8:Ccl=0:
    N: Leaf structure parameter -- 1.2 (PrROSPECT 5B default from code)
    Cab: Leaf Chlorophyll a+b content [ug/cm2], mean 36.9+11.7 (A+B)
    Cw: Leaf Equivalent Water content [cm] (or [g/cm2] for fresh leaves), mean 0.0115 (Note: PROSPECT5 default 0.015)
    Cm: Leaf dry Mass per Area [g/cm2], mean 0.0045
    Car: Leaf Carotenoids content [ug/cm2], mean 10.5
    Cbrown: Fraction of brown leaves
    Anth: Leaf Anthocyanins content [ug/cm2], 7.8
    Cp: Leaf protein content [g/cm2], mean 0.00096
    Ccl: Leaf cellulose and lignin content [g/cm2] 0.00108+0.00080+0.00060 (cellulose+hemicellulose+lignin)

    :return: list of parameter values
    """
    return [2, 48.6, 0.0115, 0.0045, 10.5, 0, 7.8, 0.00096, 0.00228]


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

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


def get_file_ext(filetype):
    """
    get extname according filetype
    :param filetype: filetype (in config.get_key('valid_filetype'))
    :return: file's extend name
    """
    return {'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp',
        'image/gif': 'gif'}[filetype]


def accumulate(iterable, func, *, initial=None):
    """https://docs.python.org/3/library/itertools.html#itertools.accumulate

    Stolen but not used since I ddidn have ython 3.8 handy and wanted to use the initial
    keyword argument

    """
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total


def stack(seq, dim):
    """Stack the sequence of tensors along the given dimension.

    Parameters
    ----------
    seq : list of Tensor
        The tensor sequence.
    dim : int
        The concat dim.

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


def save(data, path, enc):
    u""" Save json file in data.

    Dict data dump to json file.
    @param data dict data
    @param path json path
    @param enc  json endoing
    """
    import json
    import codecs
    import os
    if os.access(os.path.dirname(os.path.abspath(path)), os.W_OK):
        with codecs.open(path, 'w', enc) as fo:
            json.dump(data, fo, sort_keys=True, indent=4, ensure_ascii=False)
    else:
        print('Cat not craete file!')


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

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


def removeprefix(text, prefix):
    """Remove a prefix from a string"""
    if text.startswith(prefix):
        text = text[len(prefix):]
        text = text.lstrip()
        return text
    return text


def lambd_NH3_K_CB89(T, P):
    """n-c: ammonia potassium [CB89]."""
    lambd = 0.0454 + (T - 298.15) * -0.000141
    valid = T == 298.15
    return lambd, valid


def _is_dunder(name):
    """Return True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2
        ] != '_' and len(name) > 4


def calc_photosynthesis_rate(T, CO2, light):
    """Calculate the rate of photosynthesis from environment properties.

    Args:
        T (float): Temperature.
        CO2 (float): CO2 concentration.
        light (float): Light intensity.

    Returns:
        float: Photosynthesis rate.

    """
    return light * CO2 / T


def unique_list(iterable, res=None, seen=None):
    """
    Returns a list of all unique elements, preserving order. Remember all elements ever seen.
    >>> unique_list('AAAABBBCCDAABBB')
    ['A', 'B', 'C', 'D']
    """
    if res is None:
        res = []
    res_append = res.append
    if seen is None:
        seen = set()
    seen_add = seen.add
    for element in iterable:
        if element not in seen:
            seen_add(element)
            res_append(element)
    return res


def num_iedges(graph):
    """ Returns the number of inhibitory connections. """
    num_einhib = len(graph['type'].a < 0)
    return float(num_einhib) / graph.edge_nb()


@staticmethod
def _dimensions_to_values(dimensions):
    """
        Replace dimensions specs with their `dimension`
        values, and ignore those without
        """
    values = []
    for dimension in dimensions:
        if isinstance(dimension, dict):
            if 'extractionFn' in dimension:
                values.append(dimension)
            elif 'dimension' in dimension:
                values.append(dimension['dimension'])
        else:
            values.append(dimension)
    return values


def get_clone_urls(session, args):
    """Get clone URLs for repositories"""
    cloneurls = {}
    for orgname in args.organizations:
        org = session.organization(orgname)
        cloneurls[orgname] = []
        for repo in org.repositories():
            if not repo.private:
                cloneurls[orgname].append(repo.clone_url)
    return cloneurls


def _n_event_report_handler(event):
    """Default handler for when an N-EVENT-REPORT request is received.

    See _handlers.doc_handle_event_report for detailed documentation.
    """
    raise NotImplementedError(
        "No handler has been bound to 'evt.EVT_N_EVENT_REPORT'")


def _cmlon(zone):
    """(INTERNAL) Central meridian longitude (C{degrees180}).
    """
    return zone * 6 - 183


def normalize_bbox(coords, ymax, scaler=2):
    """
    scales all coordinates and flip y axis due to different
    origin coordinates (top left vs. bottom left)
    """
    return [coords[0] * scaler, ymax - coords[3] * scaler, coords[2] *
        scaler, ymax - coords[1] * scaler]


def select_same_group(group: str=''):
    """Select object in the same group

    :param group: Group, Name of the group to select
    :type group: str
    """
    pass


@staticmethod
def strip_Nones(x):
    """
        Takes a 1D or 2D list, or a 1D or 2D numpy array.
        If x is 1D, when None is encountered, we return everything
        encountered before None.
        If x is 2D, we replace None with -1 and return.

        Parameters
        ----------
        x: list or numpy array

        Returns
        -------
        list
        """
    accum = []
    for val in x:
        if val is None:
            return accum
        if not isinstance(val, list):
            accum.append(val)
        else:
            for i, v in enumerate(val):
                if v is None:
                    val[i] = -1
            accum.append(val)
    return accum


def add_comment(jira_plugin, jira_issue, test, message, *, message_format):
    """
    Write comment to notify test success.

    :param jira_issue: the jira issue object
    :param test: the test case
    :param message: the success message
    :param message_format: the message format. As of 1.0 we use ``str.format`` syntax and accepted keys are ``test``
    and ``message``
    """
    if not jira_plugin.connected:
        return
    jira_plugin.jira_client.add_comment(jira_issue, message_format.format(
        test=test, message=message))
    jira_plugin.logger.info('Comment sent to %(jira_issue_id)s for %(test)s',
        extra=dict(jira_issue_id=jira_issue.id, test=test))


def copy_driver_button():
    """Copy the driver for the highlighted button

    """
    pass


def createSimulateAnalyze(netParams=None, simConfig=None, output=False):
    """ Sequence of commands create, simulate and analyse network """
    from .. import sim
    pops, cells, conns, stims, rxd, simData = sim.create(netParams,
        simConfig, output=True)
    sim.simulate()
    sim.analyze()
    if output:
        return pops, cells, conns, stims, simData


def _fr0(a):
    """fix rank-0 --> rank-1"""
    if a.ndim == 0:
        a = a.copy()
        a.shape = 1,
    return a


def safeguard(base_execution_url: str) ->str:
    """
    Build the URL to fetch safeguards from for an execution
    """
    return '/'.join([base_execution_url, 'policies'])


@classmethod
def list(cls, context, limit=None, marker=None, sort_key=None, sort_dir=None):
    """Return a list of DeployTemplate objects.

        :param context: security context. NOTE: This should only
                        be used internally by the indirection_api.
                        Unfortunately, RPC requires context as the first
                        argument, even though we don't use it.
                        A context should be set when instantiating the
                        object, e.g.: DeployTemplate(context).
        :param limit: maximum number of resources to return in a single result.
        :param marker: pagination marker for large data sets.
        :param sort_key: column to sort results by.
        :param sort_dir: direction to sort. "asc" or "desc".
        :returns: a list of :class:`DeployTemplate` objects.
        """
    db_templates = cls.dbapi.get_deploy_template_list(limit=limit, marker=
        marker, sort_key=sort_key, sort_dir=sort_dir)
    return cls._from_db_object_list(context, db_templates)


def poly(c, x):
    """ y = Sum { c(i)*x^i }, i=0,len(c)"""
    import numpy as N
    y = N.zeros(len(x))
    for i in range(len(c)):
        y += c[i] * x ** i
    return y


def get_all_ips(instance):
    """ Returns the public and private ip addresses of an GCP Compute instance
    """
    ip_list = []
    try:
        ip_list.append(instance['networkInterfaces'][0]['accessConfigs'][0]
            ['natIP'])
    except Exception as e:
        pass
    ip_list.append(instance['networkInterfaces'][0]['networkIP'])
    return ip_list


def loop():
    """Returns current event loop name or None if loop is not set.

    :rtype: st|unicode|None
    """


@classmethod
def from_str(cls, string):
    """
		Create a local version specifier from a PEP440-compliant local version
		string.

		:param str string: A PEP440-compliant local version string
		"""
    if not cls.EXPRESSION.fullmatch(string):
        raise ValueError(f'{string!r} is not a valid local version specifier')
    segments = []
    for segment in cls._SEPARATOR_EXPRESSION.split(string.strip()):
        try:
            segments.append(int(segment))
        except ValueError:
            segments.append(segment)
    return cls(segments=segments)


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

    .. code-block:: python

        out = ((image1 - image2) % MAX)

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


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


def repeat_last():
    """Repeat last action

    """
    pass


def is_vcs_link(ireq):
    """
    Returns whether an InstallRequirement is a version control link.
    """
    return ireq.link is not None and not ireq.link.is_artifact


def socket_set_hwm(socket, hwm=-1):
    """libzmq 2/3/4 compatible sethwm"""
    try:
        socket.sndhwm = socket.rcvhwm = hwm
    except AttributeError:
        socket.hwm = hwm


@staticmethod
def iter_values():
    """
        Returns a tuple with string descriptions of the dataset values that we
        want to iterate over
        """
    return tuple()


def cr_uid_records_context(method):
    """ Decorate a traditional-style method that takes ``cr``, ``uid``, a
        recordset of model ``self``, ``context`` as parameters. Such a method::

            @api.cr_uid_records_context
            def method(self, cr, uid, records, args, context=None):
                ...

        may be called in both record and traditional styles, like::

            # records = model.browse(cr, uid, ids, context)
            records.method(args)

            model.method(cr, uid, records, args, context=context)
    """
    method._api = 'cr_uid_records_context'
    return method


def adjust_annotations_shifts(fig, x_factor=1.0, y_factor=1.0):
    """ Adjust annotation shifts.

    Arguments:
        fig (plotly.graph_objs._figure.Figure): Plotly figure.
        x_factor (float): The X shifts are multiplied with this factor.
        y_factor (float): The Y shifts are multiplied with this factor.
    """
    attrs = ['xshift', 'yshift']
    factors = [x_factor, y_factor]
    annotations = getattr(fig.layout, 'annotations', [])
    for annotation in annotations:
        for attr, factor in zip(attrs, factors):
            if getattr(annotation, attr, None) is not None:
                annotation[attr] *= factor


def _rewrite_env_file(path, initial_content):
    """Rewrite the environment variable file.

    :param path: the path of the file
    :param initial_content: the original content of the file
    """
    with open(path, 'w+') as env_file:
        for line in initial_content:
            env_file.write(line)


def show_sparsity(matrix):
    """Show density and sparsity for binary matrix.

    Args:
        matrix:
    """
    matrix_density = matrix.mean().mean()
    print('Matrix density:', matrix_density)
    print('Matrix sparsity:', 1 - matrix_density)


def get_keys(dct, keys, default=None, raise_error=False):
    """retrieve the leaf of a key path from a dictionary

    :param dct: the dict to search
    :param keys: key path
    :param default: default value to return
    :param raise_error: whether to raise an error if the path isn't found
    :return:
    """
    subdct = dct
    for i, key in enumerate(keys):
        try:
            subdct = subdct[key]
        except (KeyError, IndexError):
            if raise_error:
                raise ValueError('could not find key path: {}'.format(keys[
                    0:i + 1]))
            else:
                return default
    return subdct


def configuration_information(simulator: 'Simulator') ->list:
    """
    Log information how pools and drones are configured, e.g. provided resources.

    :param simulator: the simulator
    :return: list of records for logging
    """
    return []


@classmethod
def is_capable(cls, df_type):
    """
        @param::df_type: the type of dataframe to join
        return boolean value indicates whether or not the two dataframes can be joined.
        """
    return df_type.lower() in cls.__support__


def is_lang_installed(lang):
    """Check to see if cis_interface can run models written in a programming
    language on the current machine.

    Args:
        lang (str): Programming language to check.

    Returns:
        bool: True if models in the provided language can be run on the current
            machine, False otherwise.

    """
    from cis_interface import schema, drivers
    s = schema.get_schema()
    drv = drivers.import_driver(s['model'].subtype2class[lang])
    return drv.is_installed()


def file_record_to_url(file_records, urls=[]):
    """
    Translate a Json dictionary to an usable http url for downlading files.

    :param file_records: json containing a 'data_url' field
    :type file_records: dict
    :param urls: a list of strings containing previous data_urls on which new urls
     will be appended
    :type urls: list

    :return: urls: (list) a list of strings representing full data urls
    """
    for fr in file_records:
        if fr['data_url'] is not None:
            urls.append(fr['data_url'])
    return urls


def commit(new_revision_number=None):
    """
    Need to be called after any changes in the index database.

    This increase revision number by 1 or set ``new_revision_number``.
    """
    global _RevisionNumber
    if new_revision_number:
        _RevisionNumber = new_revision_number
    else:
        _RevisionNumber += 1


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 _get_separator(num, sep_title, sep_character, sep_length):
    """Get a row separator for row *num*."""
    left_divider_length = right_divider_length = sep_length
    if isinstance(sep_length, tuple):
        left_divider_length, right_divider_length = sep_length
    left_divider = sep_character * left_divider_length
    right_divider = sep_character * right_divider_length
    title = sep_title.format(n=num + 1)
    return '{left_divider}[ {title} ]{right_divider}\n'.format(left_divider
        =left_divider, right_divider=right_divider, title=title)


@classmethod
def create_text(cls, position, *chars):
    """Create a node interpretable as text

        :type position: tuple[int]
        :param position: a tuple (row, col) to mark the positioning

        :type chars: tuple[unicode]
        :param chars: characters to add to the text

        :rtype: _InstructionNode
        """
    return cls(u''.join(chars), position=position)


def remove_trace(variable, mode, cbname):
    """
    Remove trace from variable.

    Ensure compatibility with old and new trace method.
    mode: "read", "write", "unset" (new syntax)
    """
    try:
        variable.trace_remove(mode, cbname)
    except AttributeError:
        variable.trace_vdelete(mode[0], cbname)


def ToLayer(width, material, role):
    """ Creates a Layer based on strings containing the width, the material and the role

    :param width: Width of the layer
    :param material: Material of the layer, as a string
    :param role: The role of the layer
    :return: A Solcore Layer
    """
    return eval('Layer( width=%s, material=%s, role="%s"  )' % (width,
        material, role))


def compute_color(w=2000, r=0, g=0, b=0):
    """Return the hex code for the specified colors"""
    color = '35'
    fading = '1101'
    unknow = '0a00'
    white = (int(w) | int(32768)).to_bytes(2, byteorder='little').hex()
    red = (int(r) | int(12288)).to_bytes(2, byteorder='little').hex()
    green = (int(g) | int(8192)).to_bytes(2, byteorder='little').hex()
    blue = (int(b) | int(4096)).to_bytes(2, byteorder='little').hex()
    return color + fading + unknow + white + red + green + blue


def _img_fname(img_url: str) ->str:
    """Return image file name including the extension given its url."""
    return img_url.split('/')[-1]


def evaluate_compliance(event, configuration_item, valid_rule_parameters):
    """Form the evaluation(s) to be return to Config Rules

    Return either:
    None -- when no result needs to be displayed
    a string -- either COMPLIANT, NON_COMPLIANT or NOT_APPLICABLE
    a dictionary -- the evaluation dictionary, usually built by build_evaluation_from_config_item()
    a list of dictionary -- a list of evaluation dictionary , usually built by build_evaluation()

    Keyword arguments:
    event -- the event variable given in the lambda handler
    configuration_item -- the configurationItem dictionary in the invokingEvent
    valid_rule_parameters -- the output of the evaluate_parameters() representing validated parameters of the Config Rule

    Advanced Notes:
    1 -- if a resource is deleted and generate a configuration change with ResourceDeleted status, the Boilerplate code will put a NOT_APPLICABLE on this resource automatically.
    2 -- if a None or a list of dictionary is returned, the old evaluation(s) which are not returned in the new evaluation list are returned as NOT_APPLICABLE by the Boilerplate code
    3 -- if None or an empty string, list or dict is returned, the Boilerplate code will put a "shadow" evaluation to feedback that the evaluation took place properly
    """
    return 'NOT_APPLICABLE'


@staticmethod
def text_query(phrase, operator='and'):
    """
        Static method to return a filter dict to match a text search. Can be
        overridden in a subclass to customize behavior.
        """
    return {'match': {'_all': {'query': phrase, 'operator': operator,
        'analyzer': 'content'}}}


def export_subscribers():
    """ Export mailing list subscribers """


@classmethod
def get_cached(cls):
    """ Returns a memory-cached class instance. """
    cached = getattr(cls, '_cached', cls())
    cls._cached = cached
    return cls._cached


def default_number_converter(number_str):
    """
    Converts the string representation of a json number into its python object equivalent, an
    int, long, float or whatever type suits.
    """
    is_int = number_str.startswith('-') and number_str[1:].isdigit(
        ) or number_str.isdigit()
    return int(number_str) if is_int else float(number_str)


def format_account(service_name, data):
    """
    Given profile data and the name of a
    social media service, format it for
    the zone file.

    @serviceName: name of the service
    @data: legacy profile verification

    Returns the formatted account on success,
    as a dict.
    """
    assert 'username' in data, 'Missing username'
    account = {'@type': 'Account', 'service': service_name, 'identifier':
        data['username'], 'proofType': 'http'}
    if data.has_key(service_name) and data[service_name].has_key('proof'):
        account['proofUrl'] = data[service_name]['proof']
    return account


def datetime_iso_format(value):
    """
    Serialise a datetime.datetime to ISO string format.
    """
    return value.isoformat()


def Convert(from_currency, to_currency, amount):
    """Convert from one currency to another currency."""


def portfolio_r(w, R):
    """
    comput portfolio (daily) return as Pr = w'R

    w: stock weight, series
    R: stock return, series
    """
    W_tmp = w.reindex(R.index).fillna(0)
    W_tmp = W_tmp / W_tmp.sum()
    return (R * W_tmp).sum()


def get_text(obj):
    """
    This function takes a GUI child widget that contains text and returns the text as string.
    :param obj: Any text yielding widget
    :return: Widget's text (str)
    """
    if str(type(obj)) == "<class 'PyQt5.QtWidgets.QLineEdit'>":
        if obj.text() == '':
            return obj.placeholderText()
        else:
            return obj.text()
    elif str(type(obj)) == "<class 'PyQt5.QtWidgets.QTextEdit'>":
        return obj.toPlainText()
    elif str(type(obj)) == "<class 'PyQt5.QtWidgets.QListWidget'>":
        return obj.currentItem().text()
    elif str(type(obj)) == "<class 'PyQt5.QtWidgets.QComboBox'>":
        return obj.currentText()
    elif str(type(obj)) == "<class 'PyQt5.QtWidgets.QTableWidgetItem'>":
        return obj.text()


@classmethod
def _get_BZ_integration_grid_shift(cls, calc, **kwargs):
    """Return an array with Brillouin zone point shifts along each vector of reciprocal lattice."""
    try:
        _, array = calc.inputs.kpoints.get_kpoints_mesh()
        return array
    except AttributeError:
        return None
    except KeyError:
        return None


def manage_permission(permission_to_manage, roles=[], acquire=0):
    """Change the settings for the given permission.

        If optional arg acquire is true, then the roles for the permission
        are acquired, in addition to the ones specified, otherwise the
        permissions are restricted to only the designated roles.
        """


@classmethod
def get_pretty_notification_info(cls, name, filename, line):
    """
        Return a sentence describing when this exception was already seen.
        """
    try:
        return cls.query.filter_by(name=name, filename=filename, line=line
            ).one().pretty_notification_info
    except:
        return 'It is the first time this exception has been seen.\n'


def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)


def Parallel(**kwargs):
    """Adapter for joblib.Parallel so we could if desired, centralize control
    """
    import joblib
    return joblib.Parallel(**kwargs)


def last_arg_byref(args):
    """Return the last C argument's value by reference."""
    return args[-1]._obj.value


def connectors_to_end(elem):
    """ Move connectors to the end of element """
    connectors = elem.find('./connectors')
    if connectors is not None:
        elem.remove(connectors)
        elem.append(connectors)


def less_than_version(value):
    """
    Converts the current version to the next one for inserting into requirements
    in the ' < version' format
    """
    items = list(map(int, str(value).split('.')))
    if len(items) == 1:
        items.append(0)
    items[1] += 1
    if value == '1.11':
        return '2.0'
    else:
        return '.'.join(map(str, items))


@classmethod
def delete(cls, dataset_id):
    """
        Soft deletes a dataset.  You cannot get it or list it or do actions with it, except for
        un-deleting it.

        Parameters
        ----------
        dataset_id: string
            The id of the dataset to mark for deletion

        Returns
        -------
        None
        """
    path = '{}{}/'.format(cls._path, dataset_id)
    cls._client.delete(path)


def get_module(plugin):
    """Turn a python module path into a module object.

    .. doctest::

       >>> import pysettings
       >>> pysettings == get_module('pysettings')
       True
       >>> pysettings.modules == get_module('pysettings.modules')
       True
       >>> get_module('pysettings.noexist')
       Traceback (most recent call last):
       ImportError: No module named noexist

    """
    try:
        modules = plugin.split('.')
        mod = __import__(plugin, {}, {}, [])
        for module in modules[1:]:
            mod = getattr(mod, module)
        return mod
    except ImportError:
        raise


def unique_list(inlist):
    """Prepare unique list

    >>> inlist = [1, 1, 2, 4, 5, 5, 6]

    >>> unique_list(inlist)
    [1, 2, 4, 5, 6]
    """
    return set(inlist)


def pos_in_rect(rect, pos):
    """Return True if pos is in the rectangle"""
    pos_x, pos_y = pos
    x, y, width, height = rect
    return x <= pos_x <= x + width and y <= pos_y <= y + height


def is_kernelspec_model(spec_dict):
    """Returns True if spec_dict is already in proper form.  This will occur when using a gateway."""
    return (isinstance(spec_dict, dict) and 'name' in spec_dict and 'spec' in
        spec_dict and 'resources' in spec_dict)


def datetime_to_string(_datetime, format='%Y-%m-%d %H:%M:%S'):
    """datetime to string"""
    return _datetime.strftime(format) if _datetime else None


@classmethod
def debug(cls, message):
    """Called to log debug messages.

        :param str message: A message of some sort.

        :return: None - any returned value is ignored.

        This method doesn't have much of a use.  It's just a way for
        :class:`~syncrepl_client.Syncrepl` to log debug messages.  There's no
        guarantee that you'll get anything meaningful, or anything at all.

        The safest thing to do is to just `pass` this method.  Or, subclass
        :class:`~syncrepl_client.callbacks.BaseCallback`.
        """
    pass


def find(iterable, selector):
    """
	Return the first item in the `iterable` that causes the `selector` to return
	`True`.
	"""
    for x in iterable:
        if selector(x):
            return x


def chmod(*unused_args, **unused_kwargs):
    """Method os.chmod() is forbidden"""
    raise RuntimeError(
        'Usage of os.chmod() is forbidden. Use certbot.compat.filesystem.chmod() instead.'
        )


@classmethod
def loadFiles(cls, filenames, renderer=None):
    """Load multiple files, yielding Page instances of this type."""
    for f in filenames:
        for page in cls.load(f, renderer):
            yield page


@classmethod
def dropGlobalIndex(cls, fields):
    """Drops an index, the opposite of ensureGlobalIndex()"""
    cls._wrapped_class.dropIndex(fields)


def preBuildPage(page, context, data):
    """
    Called prior to building a page.

    :param page: The page about to be built
    :param context: The context for this page (you can modify this, but you must return it)
    :param data: The raw body for this page (you can modify this).
    :returns: Modified (or not) context and data.
    """
    return context, data


def launch(url, wait=False, locate=False):
    """This function launches the given URL (or filename) in the default
    viewer application for this file type.  If this is an executable, it
    might launch the executable in a new session.  The return value is
    the exit code of the launched application.  Usually, ``0`` indicates
    success.

    Examples::

        click.launch('https://click.palletsprojects.com/')
        click.launch('/my/downloaded/file', locate=True)

    .. versionadded:: 2.0

    :param url: URL or filename of the thing to launch.
    :param wait: waits for the program to stop.
    :param locate: if this is set to `True` then instead of launching the
                   application associated with the URL it will attempt to
                   launch a file manager with the file located.  This
                   might have weird effects if the URL does not point to
                   the filesystem.
    """
    from ._termui_impl import open_url
    return open_url(url, wait=wait, locate=locate)


def lookupPointer(name, timeout=None):
    """
        Perform a PTR record lookup.

        @type name: C{str}
        @param name: DNS name to resolve.

        @type timeout: Sequence of C{int}
        @param timeout: Number of seconds after which to reissue the query.
            When the last timeout expires, the query is considered failed.

        @rtype: L{Deferred}
        @return: A L{Deferred} which fires with a three-tuple of lists of
            L{twisted.names.dns.RRHeader} instances.  The first element of the
            tuple gives answers.  The second element of the tuple gives
            authorities.  The third element of the tuple gives additional
            information.  The L{Deferred} may instead fail with one of the
            exceptions defined in L{twisted.names.error} or with
            C{NotImplementedError}.
        """


def merge_changes(source, changes):
    """Merge new changes with existing ones"""
    for intf, field_names in changes.items():
        source[intf] = source.get(intf, []) + field_names


def loop_select(extend: bool=False, deselect: bool=False, toggle: bool=
    False, ring: bool=False):
    """Select a loop of connected edges

    :param extend: Extend Select, Extend the selection
    :type extend: bool
    :param deselect: Deselect, Remove from the selection
    :type deselect: bool
    :param toggle: Toggle Select, Toggle the selection
    :type toggle: bool
    :param ring: Select Ring, Select ring
    :type ring: bool
    """
    pass


@classmethod
def write_str(cls, opc_sync: bool, total_size: int, context: str
    ) ->'IoTransferEventArgs':
    """Creates new IoTransferEventArgs of write string

		:param opc_sync: defines if the command is OPC-synchronised
		:param total_size: size of the data to write
		:param context: SCPI command write. It is truncated to maximum of 100 characters.
		:return: IoTransferEventArgs object of a write string operation."""
    obj = cls(False, opc_sync, total_size, context)
    obj.binary = False
    return obj


def make_string_pep440_compatible(raw_str):
    """
    pep440 only allows a subset of characters in the
    version name:

    - alphanumeric
    - dots

    this will restrict the string to that set.
    """
    final_chars = []
    for r in raw_str:
        if 'a' <= r <= 'z' or 'A' <= r <= 'Z' or '0' <= r <= '9' or r == '.':
            final_chars.append(r)
    return ''.join(final_chars)


def set_union(sets):
    """Non variadic version of set.union.
    """
    return set.union(*sets)


@staticmethod
def collect_netdev():
    """collect cummulated network device Rx/Tx bytes"""
    with open('/proc/net/dev', 'r') as f:
        f.readline()
        f.readline()
        for net in f:
            net = net.split()
            interface, rx, tx = net[0][:-1], int(net[1]), int(net[9])
            yield interface, {'rx_data': rx, 'tx_data': tx}


@classmethod
def restore(cls, file_request):
    """Restore an instance of this class from a file request.

        :param file_request: file request
        :return: class instance
        """
    return cls(file_request.filename)


def _reverse(array, dim):
    """Reverse an `xarray.DataArray` along a given dimension."""
    slicers = [slice(0, None)] * array.ndim
    slicers[dim] = slice(-1, None, -1)
    return array[tuple(slicers)]


def purge(history_id, selector, metadata={}, countPurged=True):
    """Purge a Version from a Resources History

        If ``countPurged`` is ``True`` version numbering counts purged
        versions also. If ``False`` purged versiona are not taken into
        account.

        Purge the given version from the given history. The metadata
        passed may be used to store informations about the reasons of
        the purging.
        """


def quoteStr(astr, escChar='\\', quoteChar='"'):
    """Escape all instances of quoteChar and escChar in astr
    with a preceding escChar and surrounds the result with quoteChar.

    Examples:
    astr = 'foo" ar'
    quoteStr(astr) = '"foo" \\bar"'
    quoteStr(astr, escChar = '"') = '"foo"" ar"'

    This prepares a string for output.
    """
    if escChar != quoteChar:
        astr = astr.replace(escChar, escChar + escChar)
    return quoteChar + astr.replace(quoteChar, escChar + quoteChar) + quoteChar


def get_user_pool_domain(prefix, region):
    """Return a user pool domain name based on the prefix received and region.

    Args:
        prefix (str): The domain prefix for the domain
        region (str): The region in which the pool resides
    """
    return '%s.auth.%s.amazoncognito.com' % (prefix, region)


def read_proc_mounts():
    """Read the /proc/mounts file.

    It's a dummy function but it eases the writing of unit tests as mocking
    __builtin__open() for a specific file only is not trivial.
    """
    with open('/proc/mounts') as mounts:
        return mounts.readlines()


def ndo_string(data, n):
    """mimic of gmx_fio_ndo_string in gromacs"""
    return [data.unpack_string() for i in range(n)]


def view_all(use_all_regions: bool=False, center: bool=False):
    """View all objects in scene

    :param use_all_regions: All Regions, View selected for all regions
    :type use_all_regions: bool
    :param center: Center
    :type center: bool
    """
    pass


def sequential_enum(*sequential, **named):
    """Returns a new enum with all given named and sequential nodes.

    sequential -- [str, str, ...]
    named -- str:int
    """
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)


def format_variable(variables, name, screen_width):
    """ Format regular variables """
    max_width = int(screen_width / 5)
    if "@<class '" in variables[name]['type']:
        typ = '[inst. ' + variables[name]['type'].split("'")[1] + ']'
    elif "<class '" in variables[name]['type']:
        typ = '[' + variables[name]['type'].split("'")[1] + ']'
    else:
        typ = '[' + variables[name]['type'] + ']'
    if 'module' in variables[name]['value']:
        val = variables[name]['value'].split("'")[1]
    elif 'elem' in variables[name]['value']:
        val1 = variables[name]['value'].split(':')[0]
        val2 = variables[name]['value'].split('`')[1]
        val = val1 + ' [' + val2 + ']'
    elif 'classmethod' in variables[name]['value']:
        val = 'classmethod'
    elif 'staticmethod' in variables[name]['value']:
        val = 'staticmethod'
    elif ' at' in variables[name]['value']:
        val = variables[name]['value'].split(' at ')[0] + '>'
    elif 'frozenset' in variables[name]['value']:
        val = variables[name]['value'].split('(')[1].split(')')[0]
    elif '<...>' in variables[name]['value']:
        val = variables[name]['value'].split('<')[0] + '...'
    else:
        val = variables[name]['value']
    if len(val) > 3 * max_width:
        val = val[0:3 * max_width - 4] + '... '
    if len(name) > max_width:
        name = name[0:max_width - 4] + '... '
    if len(typ) > max_width:
        typ = typ[0:max_width - 4] + '... '
    s1 = '{:{wname}} {:{wval}}'.format(name, val, wname=max_width, wval=3 *
        max_width)
    s2 = '{:{wtype}}'.format(typ, wtype=screen_width - len(s1))
    return s1, s2


@classmethod
def processQ(cls):
    """Pop functions from the parsing queue one by one and execute them"""
    while len(cls.parsingQ) > 0:
        cls.parsingQ.pop()()


def dps_to_prec(n):
    """Return the number of bits required to represent n decimals
    accurately."""
    return max(1, int(round((int(n) + 1) * 3.3219280948873626)))


@staticmethod
def write(config):
    """Commits any pending modifications, ie save a configuration file if
        it has been marked "dirty" as a result of an normal
        assignment. The modifications are written to the first
        writable source in this config object.

        .. note::

           This is a static method, ie not a method on any object
           instance. This is because all attribute access on a
           LayeredConfig object is meant to retrieve configuration
           settings.

        :param config: The configuration object to save
        :type  config: layeredconfig.LayeredConfig

        """
    root = config
    while root._parent:
        root = root._parent
    for source in root._sources:
        if source.writable and source.dirty:
            source.save()


def elemwise_sub(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
    """Subtracts arguments element-wise.

    The storage type of ``elemwise_sub`` output depends on storage types of inputs

       - elemwise_sub(row_sparse, row_sparse) = row_sparse
       - elemwise_sub(csr, csr) = csr
       - elemwise_sub(default, csr) = default
       - elemwise_sub(csr, default) = default
       - elemwise_sub(default, rsp) = default
       - elemwise_sub(rsp, default) = default
       - otherwise, ``elemwise_sub`` generates output with default storage

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

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

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


@classmethod
def class_method(cls, f):
    """Decorator which dynamically binds class methods to the model for later use."""
    setattr(cls, f.__name__, classmethod(f))
    return f


def repr_message(msg):
    """
    用于 Message 和 SentMessage 对象的 __repr__ 和 __unicode__
    """
    from wxpy.api.chats import Group
    text = str(msg.text or '').replace('\n', ' ↩ ')
    text += ' ' if text else ''
    if msg.sender == msg.core.self:
        ret = '↪ {self.receiver.name}'
    elif isinstance(msg.chat, Group
        ) and msg.member and msg.member != msg.receiver:
        ret = '{self.sender.name} >> {self.member.name}'
    else:
        ret = '{self.sender.name}'
    ret += ' : {text}({self.type})'
    return ret.format(self=msg, text=text)


def verify_integrity():
    """Tell whether referential integrity is given."""


def default_shared_folders():
    """Return the default shared folders config.
    """
    return [{'share_name': 'mech', 'host_path': '.'}]


def tonumber(test, alttext=None):
    """
    Checks if something is a number or matches alttext

    Parameters
    ----------
    test : str
        Text to test.
    alttext : str, optional
        Alternate text to test. The default is None.

    Returns
    -------
    str or int or float
        Returns a lower case verion of alttext, or a number.

    """
    if alttext is not None and test.lower() == alttext.lower():
        return test.lower()
    if not test.replace('.', '', 1).isdigit():
        return -999
    if '.' in test:
        return float(test)
    return int(test)


def is_vampire(oAbsCard):
    """Test if a card is a vampire or not"""
    return oAbsCard.cardtype[0].name == 'Vampire'


def __to_upper(val):
    """Convert val into ucase value."""
    try:
        return val.upper()
    except (ValueError, TypeError):
        return val


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


def setWriteToTrailer(flag=False):
    """Set the flag to indicate whether we should write to trailer files.

    flag: boolean
        Value to assign to the variable write_to_trailer (global to this
        file); if True, the printMsg function will write to the trailer
        file, in addition to the standard output
    """
    global write_to_trailer
    write_to_trailer = flag


def code_reload():
    """Reload all changed code."""


def ceil_shift(n, b):
    """Return ceil(n / 2**b) without performing any floating-point or division operations.

    This is done by right-shifting n by b bits and incrementing the result by 1
    if any '1' bits were shifted out.
    """
    if not isinstance(n, int) or not isinstance(b, int):
        raise TypeError('unsupported operand type(s): %r and %r' % (type(n)
            .__name__, type(b).__name__))
    assert n >= 0 and b >= 0
    mask = (1 << b) - 1
    if n & mask:
        return (n >> b) + 1
    else:
        return n >> b


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 __iter__():
    """Returns the FormFields as a dict
        """


def ns(v):
    """Return empty str if bool false"""
    return str(v) if bool(v) else ''


def delete_program(connection, program_name):
    """
    Remove the specified program from the database.

    Arguments:
        connection:
            The SextantConnection object managing the database connection.
        program_name:
            The name of the program to remove from the database.
    """
    connection.delete_program(program_name)


@staticmethod
def ftilde(logx, settings):
    """
        Helper function for finding the analytic value of the estimator.
        See "check_by_integrating" docstring for more details.

        ftilde(X) is mean of f(theta) on the iso-likelihood contour
        L(theta) = L(X).
        """
    return settings.r_given_logx(logx)


def parcialSums(labels, data, partials, partial_labels='', datarow_labels=''):
    """Returns a latex table with sums of data.

    Data is though to be unidimensional. Each row
    is transposed to a column to which partial sum
    are added.
    """
    lines = []
    for label in labels:
        lines.append('{} '.format(label))
    for datarow in data:
        for partial in partials:
            for line_num in range(len(datarow)):
                if line_num % partial == 0:
                    lines[line_num
                        ] += '& \\multirow{{{}}}{{*}}{{ {} }}  '.format(partial
                        , sum(datarow[line_num:line_num + partial]))
                else:
                    lines[line_num] += '& '
    for line_num in range(len(lines)):
        cuts = [(0 == (line_num + 1) % partial) for partial in partials]
        i = 0
        suffix = ''
        for cut in cuts:
            if cut:
                for datarownum in range(len(data)):
                    num = i + datarownum * len(partials)
                    suffix += '\\cline{{{}-{}}}'.format(num + 1, num + 1)
            i += 1
        lines[line_num] += '\\\\{}\n'.format(suffix)
    ltable = ''.join(lines)
    if partial_labels:
        header = (' & {}' * len(partial_labels)).format(*partial_labels) * len(
            data) + ' \\\\\\hline\n'
        ltable = header + ltable
    if datarow_labels:
        header = (' & \\multicolumn{{%i}}{{c|}}{{{}}}' % (len(partials),) *
            len(datarow_labels)).format(*datarow_labels) + ' \\\\\\hline\n'
        ltable = header + ltable
    header = '\\begin{center}\n\\begin{tabular}{l ||' + ' c |' * len(data
        ) * len(partials) + '}\\hline\n'
    footer = '\\end{tabular}\n\\end{center}'
    ltable = header + ltable + footer
    return ltable


@classmethod
def generate_custom_tree(cls, lgbm_args):
    """Generates a custom LightGBM Classifier wrapper.
        :param lgbm_args: parameters to pass into the LightGBM Classifier
        :type lgbm_args: dict
        :rtype: cls
        """
    return type('Custom' + cls.__name__, (cls,), {'lgbm_args': lgbm_args})


@classmethod
def getIsolateId(cls):
    """Returns the isolate id.
        """
    return cls.build_send_payload('getIsolateId', {}), cls.convert_payload({
        'id': {'class': str, 'optional': False}})


def __new__(cls, *argv, **argd):
    """Don't try to instance this class, just use the static methods."""
    raise NotImplementedError('Cannot instance static class %s' % cls.__name__)


def map_device_id_to_dict(instance, value):
    """Convert a device_id into a dictionary for BlockDevice."""
    return {'system_id': instance._data['system_id'], 'id': value,
        '__incomplete__': True}


def debug_stahp():
    """Toggles ``DEBUG`` value, useful for testing
    """
    global DEBUG
    DEBUG = not DEBUG


def email_for_user(username, check_exists=True):
    """Return email for a user.

    Currently, just appends @ocf.berkeley.edu, but could eventually do
    something more complicated.
    """
    if check_exists:
        from ocflib.account.search import user_exists
        if not user_exists(username):
            raise ValueError('Account "{}" does not exist.'.format(username))
    return '{}@ocf.berkeley.edu'.format(username)


def current_branch(branchs):
    """return current branch name"""
    for branch in branchs:
        if '*' in branch:
            return str(branch.split('* ')[1])


def _num_det_vars(det_string, seasons=0):
    """Gives the number of deterministic variables specified by det_string and
    seasons.

    Parameters
    ----------
    det_string : str {"nc", "co", "ci", "lo", "li"}
        * "nc" - no deterministic terms
        * "co" - constant outside the cointegration relation
        * "ci" - constant within the cointegration relation
        * "lo" - linear trend outside the cointegration relation
        * "li" - linear trend within the cointegration relation

        Combinations of these are possible (e.g. "cili" or "colo" for linear
        trend with intercept). See the docstring of the :class:`VECM`-class for
        more information.
    seasons : int
        Number of periods in a seasonal cycle.

    Returns
    -------
    num : int
        Number of deterministic terms and number dummy variables for seasonal
        terms.
    """
    num = 0
    if 'ci' in det_string or 'co' in det_string:
        num += 1
    if 'li' in det_string or 'lo' in det_string:
        num += 1
    if seasons > 0:
        num += seasons - 1
    return num


def ensure_unicode(x, encoding='ascii'):
    """
    Decode bytes to unicode if necessary.

    Parameters
    ----------
    obj : bytes or unicode
    encoding : str, default "ascii"

    Returns
    -------
    unicode
    """
    if isinstance(x, bytes):
        return x.decode(encoding)
    return x


def to_molar_ratio(massfrac_numerator, massfrac_denominator, numerator_mass,
    denominator_mass):
    """
    Converts per-mass concentrations to molar elemental ratios.

    Be careful with units.

    Parameters
    ----------
    numerator_mass, denominator_mass : float or array-like
        The atomic mass of the numerator and denominator.
    massfrac_numerator, massfrac_denominator : float or array-like
        The per-mass fraction of the numnerator and denominator.

    Returns
    -------
    float or array-like : The molar ratio of elements in the material
    """
    return massfrac_numerator / numerator_mass / (massfrac_denominator /
        denominator_mass)


def KK_RC67_fit(params, w, t_values):
    """
    Kramers-Kronig Function: -RC-

    Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
    """
    Rs = params['Rs']
    R1 = params['R1']
    R2 = params['R2']
    R3 = params['R3']
    R4 = params['R4']
    R5 = params['R5']
    R6 = params['R6']
    R7 = params['R7']
    R8 = params['R8']
    R9 = params['R9']
    R10 = params['R10']
    R11 = params['R11']
    R12 = params['R12']
    R13 = params['R13']
    R14 = params['R14']
    R15 = params['R15']
    R16 = params['R16']
    R17 = params['R17']
    R18 = params['R18']
    R19 = params['R19']
    R20 = params['R20']
    R21 = params['R21']
    R22 = params['R22']
    R23 = params['R23']
    R24 = params['R24']
    R25 = params['R25']
    R26 = params['R26']
    R27 = params['R27']
    R28 = params['R28']
    R29 = params['R29']
    R30 = params['R30']
    R31 = params['R31']
    R32 = params['R32']
    R33 = params['R33']
    R34 = params['R34']
    R35 = params['R35']
    R36 = params['R36']
    R37 = params['R37']
    R38 = params['R38']
    R39 = params['R39']
    R40 = params['R40']
    R41 = params['R41']
    R42 = params['R42']
    R43 = params['R43']
    R44 = params['R44']
    R45 = params['R45']
    R46 = params['R46']
    R47 = params['R47']
    R48 = params['R48']
    R49 = params['R49']
    R50 = params['R50']
    R51 = params['R51']
    R52 = params['R52']
    R53 = params['R53']
    R54 = params['R54']
    R55 = params['R55']
    R56 = params['R56']
    R57 = params['R57']
    R58 = params['R58']
    R59 = params['R59']
    R60 = params['R60']
    R61 = params['R61']
    R62 = params['R62']
    R63 = params['R63']
    R64 = params['R64']
    R65 = params['R65']
    R66 = params['R66']
    R67 = params['R67']
    return Rs + R1 / (1 + w * 1.0j * t_values[0]) + R2 / (1 + w * 1.0j *
        t_values[1]) + R3 / (1 + w * 1.0j * t_values[2]) + R4 / (1 + w *
        1.0j * t_values[3]) + R5 / (1 + w * 1.0j * t_values[4]) + R6 / (1 +
        w * 1.0j * t_values[5]) + R7 / (1 + w * 1.0j * t_values[6]) + R8 / (
        1 + w * 1.0j * t_values[7]) + R9 / (1 + w * 1.0j * t_values[8]
        ) + R10 / (1 + w * 1.0j * t_values[9]) + R11 / (1 + w * 1.0j *
        t_values[10]) + R12 / (1 + w * 1.0j * t_values[11]) + R13 / (1 + w *
        1.0j * t_values[12]) + R14 / (1 + w * 1.0j * t_values[13]) + R15 / (
        1 + w * 1.0j * t_values[14]) + R16 / (1 + w * 1.0j * t_values[15]
        ) + R17 / (1 + w * 1.0j * t_values[16]) + R18 / (1 + w * 1.0j *
        t_values[17]) + R19 / (1 + w * 1.0j * t_values[18]) + R20 / (1 + w *
        1.0j * t_values[19]) + R21 / (1 + w * 1.0j * t_values[20]) + R22 / (
        1 + w * 1.0j * t_values[21]) + R23 / (1 + w * 1.0j * t_values[22]
        ) + R24 / (1 + w * 1.0j * t_values[23]) + R25 / (1 + w * 1.0j *
        t_values[24]) + R26 / (1 + w * 1.0j * t_values[25]) + R27 / (1 + w *
        1.0j * t_values[26]) + R28 / (1 + w * 1.0j * t_values[27]) + R29 / (
        1 + w * 1.0j * t_values[28]) + R30 / (1 + w * 1.0j * t_values[29]
        ) + R31 / (1 + w * 1.0j * t_values[30]) + R32 / (1 + w * 1.0j *
        t_values[31]) + R33 / (1 + w * 1.0j * t_values[32]) + R34 / (1 + w *
        1.0j * t_values[33]) + R35 / (1 + w * 1.0j * t_values[34]) + R36 / (
        1 + w * 1.0j * t_values[35]) + R37 / (1 + w * 1.0j * t_values[36]
        ) + R38 / (1 + w * 1.0j * t_values[37]) + R39 / (1 + w * 1.0j *
        t_values[38]) + R40 / (1 + w * 1.0j * t_values[39]) + R41 / (1 + w *
        1.0j * t_values[40]) + R42 / (1 + w * 1.0j * t_values[41]) + R43 / (
        1 + w * 1.0j * t_values[42]) + R44 / (1 + w * 1.0j * t_values[43]
        ) + R45 / (1 + w * 1.0j * t_values[44]) + R46 / (1 + w * 1.0j *
        t_values[45]) + R47 / (1 + w * 1.0j * t_values[46]) + R48 / (1 + w *
        1.0j * t_values[47]) + R49 / (1 + w * 1.0j * t_values[48]) + R50 / (
        1 + w * 1.0j * t_values[49]) + R51 / (1 + w * 1.0j * t_values[50]
        ) + R52 / (1 + w * 1.0j * t_values[51]) + R53 / (1 + w * 1.0j *
        t_values[52]) + R54 / (1 + w * 1.0j * t_values[53]) + R55 / (1 + w *
        1.0j * t_values[54]) + R56 / (1 + w * 1.0j * t_values[55]) + R57 / (
        1 + w * 1.0j * t_values[56]) + R58 / (1 + w * 1.0j * t_values[57]
        ) + R59 / (1 + w * 1.0j * t_values[58]) + R60 / (1 + w * 1.0j *
        t_values[59]) + R61 / (1 + w * 1.0j * t_values[60]) + R62 / (1 + w *
        1.0j * t_values[61]) + R63 / (1 + w * 1.0j * t_values[62]) + R64 / (
        1 + w * 1.0j * t_values[63]) + R65 / (1 + w * 1.0j * t_values[64]
        ) + R66 / (1 + w * 1.0j * t_values[65]) + R67 / (1 + w * 1.0j *
        t_values[66])


def asynchronous_range(start, stop):
    """Range distributing numbers asynchronously among processes

    """
    from .managers import Manager
    config = Manager().get_DistributedConfiguration()
    if config.parallel_level == 1:
        pass
    else:
        return range(start, stop)


def _init_data(data, key, init_data):
    """Initialize the data at specified key, if needed"""
    if isinstance(key, int):
        try:
            data[key]
        except IndexError:
            data.append(init_data)
    else:
        data[key] = data.get(key, init_data)
    return data


def _as_range(iterable):
    """
    Return a tuple representing the bounds of the range.
    """
    l = list(iterable)
    return l[0], l[-1]


def get_sys_meta_prefix(server_type):
    """
    Returns the prefix for system metadata headers for given server type.

    This prefix defines the namespace for headers that will be persisted
    by backend servers.

    :param server_type: type of backend server i.e. [account|container|object]
    :returns: prefix string for server type's system metadata headers
    """
    return 'x-%s-%s-' % (server_type.lower(), 'sysmeta')


def p_start(p):
    """start : NEWLINE lines end
             | lines end"""
    if len(p) == 4:
        lines = p[2]
        end = p[3]
    elif len(p) == 3:
        lines = p[1]
        end = p[2]
    if end:
        lines.append(end)
    p[0] = lines


def load_pythoncom(finder, module):
    """the pythoncom module is actually contained in a DLL but since those
       cannot be loaded directly in Python 2.5 and higher a special module is
       used to perform that task; simply use that technique directly to
       determine the name of the DLL and ensure it is included as a normal
       extension; also load the pywintypes module which is implicitly
       loaded."""
    import pythoncom
    module.file = pythoncom.__file__
    module.code = None
    finder.IncludeModule('pywintypes')


def module(schemaName, tree):
    """Return the module name to use.
        """


def make_clust(net, dist_type='cosine', run_clustering=True, dendro=True,
    requested_views=['pct_row_sum', 'N_row_sum'], linkage_type='average',
    sim_mat=False, filter_sim=0.1, calc_cat_pval=False, sim_mat_views=[
    'N_row_sum'], run_enrichr=None, enrichrgram=None):
    """
  This will calculate multiple views of a clustergram by filtering the
  data and clustering after each filtering. This filtering will keep the top
  N rows based on some quantity (sum, num-non-zero, etc).
  """
    from copy import deepcopy
    import scipy
    from . import calc_clust, run_filter, make_views, make_sim_mat, cat_pval
    from . import enrichr_functions as enr_fun
    df = net.dat_to_df()
    threshold = 0.0001
    df = run_filter.df_filter_row_sum(df, threshold)
    df = run_filter.df_filter_col_sum(df, threshold)
    define_cat_colors = False
    if run_enrichr is not None:
        df = enr_fun.add_enrichr_cats(df, 'row', run_enrichr)
        define_cat_colors = True
    net.df_to_dat(df, define_cat_colors=True)
    inst_dm = calc_clust.cluster_row_and_col(net, dist_type=dist_type,
        linkage_type=linkage_type, run_clustering=run_clustering, dendro=
        dendro, ignore_cat=False, calc_cat_pval=calc_cat_pval)
    all_views = []
    send_df = deepcopy(df)
    if 'N_row_sum' in requested_views:
        all_views = make_views.N_rows(net, send_df, all_views, dist_type=
            dist_type, rank_type='sum')
    if 'N_row_var' in requested_views:
        all_views = make_views.N_rows(net, send_df, all_views, dist_type=
            dist_type, rank_type='var')
    if 'pct_row_sum' in requested_views:
        all_views = make_views.pct_rows(net, send_df, all_views, dist_type=
            dist_type, rank_type='sum')
    if 'pct_row_var' in requested_views:
        all_views = make_views.pct_rows(net, send_df, all_views, dist_type=
            dist_type, rank_type='var')
    which_sim = []
    if sim_mat == True:
        which_sim = ['row', 'col']
    elif sim_mat == 'row':
        which_sim = ['row']
    elif sim_mat == 'col':
        which_sim = ['col']
    if sim_mat is not False:
        sim_net = make_sim_mat.main(net, inst_dm, which_sim, filter_sim,
            sim_mat_views)
        net.sim = {}
        for inst_rc in which_sim:
            net.sim[inst_rc] = sim_net[inst_rc].viz
            if inst_rc == 'row':
                other_rc = 'col'
            elif inst_rc == 'col':
                other_rc = 'row'
            net.sim[inst_rc]['cat_colors'][inst_rc] = net.viz['cat_colors'][
                inst_rc]
            net.sim[inst_rc]['cat_colors'][other_rc] = net.viz['cat_colors'][
                inst_rc]
    else:
        net.sim = {}
    net.viz['views'] = all_views
    if enrichrgram != None:
        net.viz['enrichrgram'] = enrichrgram
    if 'enrichrgram_lib' in net.dat:
        net.viz['enrichrgram'] = True
        net.viz['enrichrgram_lib'] = net.dat['enrichrgram_lib']
    if 'row_cat_bars' in net.dat:
        net.viz['row_cat_bars'] = net.dat['row_cat_bars']


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


def set_cognito_events(IdentityPoolId=None, Events=None):
    """
    Sets the AWS Lambda function for a given event type for an identity pool. This request only updates the key/value pair specified. Other key/values pairs are not updated. To remove a key value pair, pass a empty value for the particular key.
    This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
    See also: AWS API Documentation

    :example: response = client.set_cognito_events(
        IdentityPoolId='string',
        Events={
            'string': 'string'
        }
    )

    :type IdentityPoolId: string
    :param IdentityPoolId: [REQUIRED]
            The Cognito Identity Pool to use when configuring Cognito Events

    :type Events: dict
    :param Events: [REQUIRED]
            The events to configure
            (string) --
            (string) --

    """
    pass


def replace_in_file(filepath, old, new):
    """Replace :py:obj:`old` string with :py:obj:`new` in a file.

    :param Path filepath:
    """
    with filepath.open() as f:
        content_as_string = f.read()
    content_as_string = content_as_string.replace(old, new)
    with filepath.open(mode='w') as f:
        f.write(content_as_string)


def get_rdml_lib_version():
    """Return the version string of the RDML library.

    Returns:
        The version string of the RDML library.
    """
    return '0.9.4'


def density_to_air_quality(density):
    """Map PM2.5 density to HomeKit AirQuality level."""
    if density <= 35:
        return 1
    if density <= 75:
        return 2
    if density <= 115:
        return 3
    if density <= 150:
        return 4
    return 5


def create_stack(Name=None, Description=None, DisplayName=None,
    StorageConnectors=None):
    """
    Create a new stack.
    See also: AWS API Documentation

    :example: response = client.create_stack(
        Name='string',
        Description='string',
        DisplayName='string',
        StorageConnectors=[
            {
                'ConnectorType': 'HOMEFOLDERS',
                'ResourceIdentifier': 'string'
            },
        ]
    )

    :type Name: string
    :param Name: [REQUIRED]
            The unique identifier for this stack.

    :type Description: string
    :param Description: The description displayed to end users on the AppStream 2.0 portal.

    :type DisplayName: string
    :param DisplayName: The name displayed to end users on the AppStream 2.0 portal.

    :type StorageConnectors: list
    :param StorageConnectors: The storage connectors to be enabled for the stack.
            (dict) --Contains the parameters for a storage connector.
            ConnectorType (string) -- [REQUIRED]The type of storage connector. The possible values include: HOMEFOLDERS.
            ResourceIdentifier (string) --The ARN associated with the storage connector.

    :rtype: dict
    :return: {
        'Stack': {
            'Arn': 'string',
            'Name': 'string',
            'Description': 'string',
            'DisplayName': 'string',
            'CreatedTime': datetime(2015, 1, 1),
            'StorageConnectors': [
                {
                    'ConnectorType': 'HOMEFOLDERS',
                    'ResourceIdentifier': 'string'
                },
            ],
            'StackErrors': [
                {
                    'ErrorCode': 'STORAGE_CONNECTOR_ERROR'|'INTERNAL_SERVICE_ERROR',
                    'ErrorMessage': 'string'
                },
            ]
        }
    }

    """
    pass


def cube_with_strides_center(center=[0, 0, 0], strides=[4, 2, 1]):
    """ Cube in an array of voxels with a given center and strides.

    This triangulates a cube with vertices [center[i] + 1].

    The dimension of the cube is determined by len(center)
    which should agree with len(center).

    The allowable dimensions are [1,2,3].

    Parameters
    ----------
    center : (d,) sequence of int, optional
       Default is [0, 0, 0]
    strides : (d,) sequence of int, optional
       Default is [4, 2, 1].  These are the strides given by
       ``np.ones((2,2,2), np.bool).strides``

    Returns
    -------
    complex : dict
       A dictionary with integer keys representing a simplicial
       complex. The vertices of the simplicial complex are the indices
       of the corners of the cube in a 'flattened' array with specified
       strides.
    """
    d = len(center)
    if not 0 < d <= 3:
        raise ValueError('dimensionality must be 0 < d <= 3')
    if len(strides) != d:
        raise ValueError('center and strides must have the same length')
    if d == 3:
        maximal = [(0, 3, 2, 7), (0, 6, 2, 7), (0, 7, 5, 4), (0, 7, 5, 1),
            (0, 7, 4, 6), (0, 3, 1, 7)]
        vertices = []
        for k in range(2):
            for j in range(2):
                for i in range(2):
                    vertices.append((center[0] + i) * strides[0] + (center[
                        1] + j) * strides[1] + (center[2] + k) * strides[2])
    elif d == 2:
        maximal = [(0, 1, 3), (0, 2, 3)]
        vertices = []
        for j in range(2):
            for i in range(2):
                vertices.append((center[0] + i) * strides[0] + (center[1] +
                    j) * strides[1])
    elif d == 1:
        maximal = [(0, 1)]
        vertices = [center[0], center[0] + strides[0]]
    mm = []
    for m in maximal:
        nm = [vertices[j] for j in m]
        mm.append(nm)
    maximal = [tuple([vertices[j] for j in m]) for m in maximal]
    return complex(maximal)


def repeat(input, repeats, dim):
    """Repeats elements of an array.

    Parameters
    ----------
    input : Tensor
        Input data array
    repeats : int
        The number of repetitions for each element
    dim : int
        The dim along which to repeat values.

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


def build_request_type(direction, type, recipient):
    """Build a bmRequestType field for control requests.

    These is a conventional function to build a bmRequestType
    for a control request.

    The direction parameter can be CTRL_OUT or CTRL_IN.
    The type parameter can be CTRL_TYPE_STANDARD, CTRL_TYPE_CLASS,
    CTRL_TYPE_VENDOR or CTRL_TYPE_RESERVED values.
    The recipient can be CTRL_RECIPIENT_DEVICE, CTRL_RECIPIENT_INTERFACE,
    CTRL_RECIPIENT_ENDPOINT or CTRL_RECIPIENT_OTHER.

    Return the bmRequestType value.
    """
    return recipient | type | direction


def is_youtube(raw_song):
    """ Check if the input song is a YouTube link. """
    status = len(raw_song) == 11 and raw_song.replace(' ', '%20') == raw_song
    status = status and not raw_song.lower() == raw_song
    status = status or 'youtube.com/watch?v=' in raw_song
    return status


@classmethod
def new(cls, key, mode, IV=None, **kwargs):
    """
        Returns a ciphering object, using the secret key contained in
        the string **key**, and using the feedback mode **mode**, which
        must be one of MODE_* defined in this module.

        If **mode** is MODE_CBC or MODE_CFB, **IV** must be provided and
        must be a string of the same length as the block size. Not
        providing a value of **IV** will result in a ValueError exception
        being raised.
        """
    return cls(key, mode, IV)


def visibility_test(centres, xlim, component):
    """
    Tests if given faces are visible from the other star.

    :param component: str;
    :param centres: numpy.array;
    :param xlim: visibility threshold in x axis for given component
    :return: numpy.array[bool];
    """
    return centres[:, (0)] >= xlim if component == 'primary' else centres[:,
        (0)] <= xlim


def hash32(value):
    """Platform independend 32bit hashing method"""
    return hash(value) & 4294967295


def rollingchecksum(removed, new, a, b, blocksize=4096):
    """
    Generates a new weak checksum when supplied with the internal state
    of the checksum calculation for the previous window, the removed
    byte, and the added byte.
    """
    a -= removed - new
    b -= removed * blocksize - a
    return b << 16 | a, a, b


@staticmethod
def get_level_summary(cues):
    """For a list of ICue, return the abundance of all levels"""
    levels = {'info': 0, 'alert': 0, 'violation': 0}
    for cue in cues:
        levels[cue.level] += 1
    return levels


def alias(requestContext, seriesList, newName):
    """
    Takes one metric or a wildcard seriesList and a string in quotes.
    Prints the string instead of the metric name in the legend.

    Example::

        &target=alias(Sales.widgets.largeBlue,"Large Blue Widgets")

    """
    try:
        seriesList.name = newName
    except AttributeError:
        for series in seriesList:
            series.name = newName
    return seriesList


def asUnit(data, unit, precision):
    """
Convert to rich-string with a certain unit and precision. The output is e.g. ``"1.1d"``.

:arguments:

  **data** (``<int>`` | ``<float>``)
    Numerical value (e.g. ``1.1``).

  **unit** (``<str>``)
    The unit (e.g. ``"d"``).

  **precision** (``<int>``)
    The precision with which to print (e.g. ``1``).

:returns:

  ``<str>``
    The rich-string.
  """
    if precision:
        return '{{0:.{precision:d}f}}{{1:s}}'.format(precision=precision
            ).format(data, unit)
    if abs(round(data)) < 10.0:
        return '{0:.1f}{1:s}'.format(data, unit)
    else:
        return '{0:.0f}{1:s}'.format(round(data), unit)


def decode_landmarks(anchors, deltas):
    """Apply the landmark delta predictions on the base anchor coordinates.

    Paramters
    ---------
    anchors : torch.Tensor of shape (A, 4)
    deltas : torch.Tensor of shape (N, A, 5, 2)

    Returns
    -------
    torch.Tensor of shape (N, A, 5, 2)
        Adjusted landmark coordinates.

    """
    widths = anchors[:, (2)] - anchors[:, (0)] + 1.0
    heights = anchors[:, (3)] - anchors[:, (1)] + 1.0
    ctr_x = anchors[:, (0)] + 0.5 * (widths - 1.0)
    ctr_y = anchors[:, (1)] + 0.5 * (heights - 1.0)
    pred = deltas
    for i in range(5):
        pred[..., i, 0] = deltas[..., i, 0] * widths + ctr_x
        pred[..., i, 1] = deltas[..., i, 1] * heights + ctr_y
    return pred


def write_file(file_name: str, contents: str):
    """Reads the bytes of a file.

  Args:
    file_name: The file to read.

  Returns:
    The bytes of the file.
  """
    with open(file_name, 'wb') as f:
        return f.write(contents)


def adoptStreamConnection(fileDescriptor, addressFamily, factory):
    """
        Add an existing connected I{SOCK_STREAM} socket to the reactor to
        monitor for data.

        Note that the given factory won't have its C{startFactory} and
        C{stopFactory} methods called, as there is no sensible time to call
        them in this situation.

        @param fileDescriptor: A file descriptor associated with a socket which
            is already connected.  The socket must be set non-blocking.  Any
            additional flags (for example, close-on-exec) must also be set by
            application code.  Application code is responsible for closing the
            file descriptor, which may be done as soon as
            C{adoptStreamConnection} returns.
        @type fileDescriptor: C{int}

        @param addressFamily: The address family (or I{domain}) of the socket.
            For example, L{socket.AF_INET6}.

        @param factory: A L{ServerFactory} instance to use to create a new
            protocol to handle the connection via this socket.

        @raise UnsupportedAddressFamily: If the given address family is not
            supported by this reactor, or not supported with the given socket
            type.

        @raise UnsupportedSocketType: If the given socket type is not supported
            by this reactor, or not supported with the given socket type.
        """


def vertex_group_select():
    """Select all the vertices assigned to the active vertex group

    """
    pass


def _call_bool_filter(context, value):
    """Pass a value through the 'bool' filter.

    :param context: Jinja2 Context object.
    :param value: Value to pass through bool filter.
    :returns: A boolean.
    """
    return context.environment.call_filter('bool', value, context=context)


def _generate_secret() ->str:
    """Generate a secret."""
    import pyotp
    return str(pyotp.random_base32())


def downgrade():
    """Migrations for the downgrade."""


def random_search():
    """
    随机搜索，包括了模拟退火，粒子群，等等， 后面慢慢写，由于simple_ml提供的参数较少，没有必要用到随机搜索
    :return:
    """
    pass


@classmethod
def clear_cache(cls):
    """ clear cache to prevent memory error"""
    del cls.cache
    cls.cache = {}


@staticmethod
def has_battery():
    """Return whether the device has a battery."""
    return False


def driver_button_remove(all: bool=True):
    """Remove the driver(s) for the property(s) connected represented by the highlighted button

    :param all: All, Delete drivers for all elements of the array
    :type all: bool
    """
    pass


def detrend_mean(x):
    """Return x minus the mean(x)"""
    return x - x.mean()