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

        :param SfFbInviteDetails val:
        :rtype: EventDetails
        """
    return cls('sf_fb_invite_details', val)


def parse_host_string(host_string):
    """Parse a string to get user, protocol, host, etc.

    Args:
        host_string (str): the string
    Returns:
        dict: a dict containing the differnt parts
    """
    if not host_string:
        return {}
    username = None
    protocol = None
    host = None
    port = None
    if '://' in host_string:
        protocol, host = host_string.split('://')
    else:
        host = host_string
    if '@' in host:
        username, host = host.split('@')
    if ':' in host:
        host, port = host.split(':')
    result = {}
    if protocol:
        result['protocol'] = protocol
    if username:
        result['user'] = username
    if host:
        result['host'] = host
    if port:
        result['port'] = int(port)
    return result


def fromBytes(value):
    """Convert a byte string to a value.
        """


def df_keep_block_first_line(df_with_blocks, filtered_col_name):
    """
    To get the first line when the file is consist of many blocks which means some same values are in the same column in neighboring lines
    This may keep same values in the selected columns because the blocks have same values in the selected column may not be neighboring
    :param df_with_blocks:
    :param filtered_col_name:
    :return:
    """
    non_block_df = df_with_blocks[df_with_blocks[filtered_col_name] !=
        df_with_blocks[filtered_col_name].shift(1)]
    return non_block_df


def retransmit_timeout(group_state: 'GroupState'):
    """
    retransmit timer associated with group GroupState object has expired
    """
    group_state.group_state_logger.debug(
        'Querier NoMembersPresent: retransmit_timeout')
    return


def prune_comp_sel(sel_list, comp_names):
    """Discover and remove vector component from selection list"""
    comp_slc = slice(None)
    comp_idx = None
    for i, s in enumerate(sel_list):
        try:
            s = s.strip().lower()
            if s in comp_names:
                if comp_idx is not None:
                    raise IndexError(
                        'Multiple vector component slices given, {0}'.
                        format(tuple(sel_list)))
                comp_slc = comp_names.index(s)
                comp_idx = i
        except (TypeError, AttributeError):
            pass
    if comp_idx is not None:
        sel_list.pop(comp_idx)
        comp_idx = None
    return sel_list, comp_slc


def default_reactor(reactor):
    """
    Return the specified reactor or the default.
    """
    if reactor is None:
        from twisted.internet import reactor
    return reactor


def remove_permutations(Par, _Nucsvec, w, Force=False):
    """remove_double_combinations(Sys,Sys__Nucsvec,w,Force =False)

    in:  Sys             (one class with definitions of spin system parameters)
         Sys__Nucsvec     (vector with all combinations of isotopes)
         w               (corresponding weighting factors)
         Force=False    (forces the operations independent of the conditions)

    Caution: Works directly on the passed variables due to call by reference.
    Removes permutations which are doubled. Assume a spin system with
    n = [2,2], Nucs = "N,H" is transformed in the fast-motion regime to a
    system "N,N,H,H". There requirement is still that the coupling is
    to equivalent nuclei (in general the A-tensor is identical within the
    H's and N's). The isotopes combiniations above the probability threshhold
    will be:

        1. "14N,14N,1H,1H"
        2. "14N,15N,1H,1H"
        3. "15N,14N,1H,1H"
        4. "14N,14N,2H,1H"
        5. "14N,14N,1H,2H"

    Since 2. and 3. (and 4 and 5) are indentical (just a perumation of a
    isotope within the equivalent coupling nuclei group) one of them can be
    removed and the other douled in weight. Leaving:

        1. "14N,14N,1H,1H"
        2. "14N,15N,1H,1H"    weight*2
        3. "14N,14N,1H,2H"    weight*2

    This was a description using an example of the very general procedure
    implemented in this function. The new reduced list of isotope combinations
    as well as the new weighting factors are produced (call by reference).
    """
    if (Force or Par.tcorr is not None) and Par._m is not None:
        s = len(_Nucsvec) - 1
        if isinstance(Par._m, int):
            Par._m = [Par._m]
        for s in range(s, -1, -1):
            str_tmp1 = _Nucsvec[s].split(',')
            for k in range(0, s):
                str_tmp2 = _Nucsvec[k].split(',')
                q = 0
                str1 = []
                str2 = []
                issame = True
                for t in range(0, len(Par._m)):
                    str1.append(str_tmp1[q:q + Par._m[t]])
                    str2.append(str_tmp2[q:q + Par._m[t]])
                    if sorted(str1[t]) != sorted(str2[t]):
                        issame = False
                    q += Par._m[t]
                if issame:
                    del _Nucsvec[s]
                    w[k] += w[s]
                    del w[s]
                    break
    return


def remove(key):
    """Remove the key from the set.

        Raises :class:`KeyError` if key is not in the set.
        """


def notifyBefore(ob, action):
    """ Notify all applicable workflows of an action before it happens.

        o 'ob' is the content object which is the target of the action.

        o 'action' usually corresponds to a method name.

        o Participating workflows may veto the action by raising
          WorkflowException.

        o Unless vetoed, the tool will later call either a 'notifySuccess' or
          'notifyException'

        o Permission:  Private (Python only)
        """


@staticmethod
def prepare_data(X):
    """Convert dataset to the way when no additional work is needed inside fitting or predicting.
        This method is called once to transform dataset.
        """
    raise NotImplementedError('should be overriden in descendant')


def get_packages():
    """
    Returns a list of tuples containing the (package, root_dir) of the list of
    packages specified in the `Pipfile.lock`.
    """


@staticmethod
def is_latin(alt):
    """
        Check if a string is in Latin cause, in our specific case, we will
        only care about Latin characters
        """
    lower_s = range(ord('a'), ord('z') + 1)
    upper_s = range(ord('A'), ord('Z') + 1)
    for alt_c in alt:
        if ord(alt_c) not in lower_s and ord(alt_c) not in upper_s:
            return False
    return True


def html_code__macro_confluence(text):
    """
    Wrap into html macro
    :param text:
    :return:
    """
    return (
        """                <ac:structured-macro ac:name="html" ac:schema-version="1">
                    <ac:plain-text-body><![CDATA[{text}]]></ac:plain-text-body>
                </ac:structured-macro>
            """
        .format(text=text))


def pgexecute(dbconn, oper, args=None):
    """Execute an operation using a cursor"""
    curs = dbconn.cursor()
    try:
        curs.execute(oper, args)
    except:
        curs.close()
        dbconn.rollback()
        raise
    return curs


def paginate(query, page, per_page_num):
    """Paginate a query, returning also the total before pagination."""
    total = query.count()
    return query.offset(page * per_page_num).limit(per_page_num).all(), total


def string_to_bytes(value: str) ->bytes:
    """Converts a kOS STRING or STRING_VALUE into a bytes object"""
    len_bytes = bytes([len(value)])
    str_bytes = value.encode('UTF-8')
    return len_bytes + str_bytes


def left_right_iter(shape, *args):
    """Iterator for the left and right boundary indices of a structured grid.

    This iterates over the indices in order rather than iterating all of
    the left boundary and then all of the right boundary.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.utils.structured_grid import left_right_iter
    >>> np.fromiter(left_right_iter((4, 3)), dtype=np.int)
    array([ 0,  2,  3,  5,  6,  8,  9, 11])
    >>> np.fromiter(left_right_iter((4, 3), 2), dtype=np.int)
    array([0, 2, 3, 5])
    >>> np.fromiter(left_right_iter((4, 3), 2, 4), dtype=np.int)
    array([ 6,  8,  9, 11])
    >>> np.fromiter(left_right_iter((4, 3), 1, 4, 2), dtype=np.int)
    array([ 3,  5,  9, 11])
    """
    if len(args) == 0:
        iter_rows = range(0, shape[0], 1)
    elif len(args) == 1:
        iter_rows = range(0, args[0], 1)
    elif len(args) == 2:
        iter_rows = range(args[0], args[1], 1)
    elif len(args) == 3:
        iter_rows = range(args[0], args[1], args[2])
    for row in iter_rows:
        yield row * shape[1]
        yield row * shape[1] + shape[1] - 1


@classmethod
def where_username(cls, username):
    """ Get db model by username """
    return cls.query.filter_by(email=username).first()


@classmethod
def destroy(cls, *ids):
    """
        Destroy the models for the given IDs

        :param ids: The ids of the models to destroy
        :type ids: tuple

        :return: The number of models destroyed
        :rtype: int
        """
    count = 0
    if len(ids) == 1 and isinstance(ids[0], list):
        ids = ids[0]
    ids = list(ids)
    instance = cls()
    key = instance.get_key_name()
    for model in instance.new_query().where_in(key, ids).get():
        if model.delete():
            count += 1
    return count


def _macro_defn_action(_s, _l, tokens):
    """
    Builds a dictionary structure which defines the given macro.
    """
    assert len(tokens) == 3
    assert tokens[0] == '@'
    return {tokens[1]: tokens[2]}


def jd_to_mjd(jd):
    """
    Converts Julian Date to Modified Julian Date.

    Parameters
    ----------

    jd : float
        The Julian date measured at UTC.

    Returns
    -------

    mjd : float
        `mjd = jd - 2400000.5`

    """
    return jd - 2400000.5


def p_arregloE(p):
    """arregloE : expresion ',' arregloE
                | expresion
                | empty
    """
    if len(p) > 2:
        p[0] = 1 + p[3]
    else:
        p[0] = 1


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

        :param str val:
        :rtype: DeleteSecondaryEmailResult
        """
    return cls('success', val)


def month_name(month):
    """Returns the month name for ETH juniors Salesforce"""
    month_names = {(1): 'Januar', (2): 'Februar', (3): 'März', (4): 'April',
        (5): 'Mai', (6): 'Juni', (7): 'Juli', (8): 'August', (9):
        'September', (10): 'Oktober', (11): 'November', (12): 'Dezember'}
    return month_names[month]


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


def cpu():
    """Return a context object for CPU device."""
    pass


def addPrettyTable(text):
    """ Unused at the moment. """
    newtext = '
\n
 '
    newtext2 = '
\n
 '
    text = text.replace('
', newtext)
    text = text.replace('
', newtext2)
    othertext = 'class="pretty-table">'
    text = text.replace('class="docutils">', othertext)
    text = text.replace('class="last docutils">', othertext)
    return text


def add(status):
    """Add a IStatusUpdate.

        Actual storage may be queued for later insertion by
        the implementation.

        Returns 1 on completion of synchronous insertion.
        Returns 0 when the actual insertion is queued for later processing.
        """


@classmethod
def zone_quick_veto(cls, temperature: float):
    """
        Payload to set a quick veto for a *Zone*.
        The duration is not configurable by the API, it's 6 hours
        """
    return {'setpoint_temperature': temperature}


def nodata(status_code):
    """Translate NODATA status codes from GnuPG to messages."""
    lookup = {'1': 'No armored data.', '2':
        'Expected a packet but did not find one.', '3':
        'Invalid packet found, this may indicate a non OpenPGP message.',
        '4': 'Signature expected but not found.'}
    for key, value in lookup.items():
        if str(status_code) == key:
            return value


@classmethod
def _edit_distance_from_alignment_strings(cls, str1, str2):
    """Input should be seqs output by _needleman_wunsch().
        Returns the edit distance between the sequences"""
    assert len(str1) == len(str2)
    edit_distance = 0
    in_gap = False
    for i, char1 in enumerate(str1):
        if char1 == '-' or str2[i] == '-':
            if not in_gap:
                in_gap = True
                edit_distance += 1
        else:
            in_gap = False
            if char1 != str2[i]:
                edit_distance += 1
    return edit_distance


def make_directories(field_root='j142724+334246', HOME_PATH='./'):
    """
    Make RAW, Prep, Persistence, Extractions directories
    """
    import os
    for dir in [os.path.join(HOME_PATH, field_root), os.path.join(HOME_PATH,
        field_root, 'RAW'), os.path.join(HOME_PATH, field_root, 'Prep'), os
        .path.join(HOME_PATH, field_root, 'Persistence'), os.path.join(
        HOME_PATH, field_root, 'Extractions')]:
        if not os.path.exists(dir):
            os.mkdir(dir)
            os.system('chmod ugoa+rwx {0}'.format(dir))


@staticmethod
def fix_permissions(connection, config):
    """
         Fix Permissions.
        """
    connection.sudo('chown -R {0}:{1} {2}'.format(config.project_user,
        config.project_group, config.project_path), warn=True, hide='both')
    connection.sudo('chmod -R g+w {0}'.format(config.project_path), warn=
        True, hide='both')


def parse_grouping(p):
    """Parse primary and secondary digit grouping

    >>> parse_grouping('##')
    (1000, 1000)
    >>> parse_grouping('#,###')
    (3, 3)
    >>> parse_grouping('#,####,###')
    (3, 4)
    """
    width = len(p)
    g1 = p.rfind(',')
    if g1 == -1:
        return 1000, 1000
    g1 = width - g1 - 1
    g2 = p[:-g1 - 1].rfind(',')
    if g2 == -1:
        return g1, g1
    g2 = width - g1 - g2 - 2
    return g1, g2


def int_scale(val, val_range, out_range):
    """
    Scale val in the range [0, val_range-1] to an integer in the range
    [0, out_range-1].  This implementation uses the "round-half-up" rounding
    method.

    >>> "%x" % int_scale(0x7, 0x10, 0x10000)
    '7777'
    >>> "%x" % int_scale(0x5f, 0x100, 0x10)
    '6'
    >>> int_scale(2, 6, 101)
    40
    >>> int_scale(1, 3, 4)
    2
    """
    num = int(val * (out_range - 1) * 2 + (val_range - 1))
    dem = (val_range - 1) * 2
    return num // dem


def _lists_share_element(list_a, list_b):
    """ _lists_share_element
    Check if list_a shares and element with list_b
    """
    return not set(list_a).isdisjoint(list_b)


@classmethod
def fromstring(cls, data, checksum=False, ignore_missing_end=False, **kwargs):
    """
        Creates a new HDU object of the appropriate type from a string
        containing the HDU's entire header and, optionally, its data.

        Note: When creating a new HDU from a string without a backing file
        object, the data of that HDU may be read-only.  It depends on whether
        the underlying string was an immutable Python str/bytes object, or some
        kind of read-write memory buffer such as a `memoryview`.

        Parameters
        ----------
        data : str, bytearray, memoryview, ndarray
           A byte string containing the HDU's header and data.

        checksum : bool, optional
           Check the HDU's checksum and/or datasum.

        ignore_missing_end : bool, optional
           Ignore a missing end card in the header data.  Note that without the
           end card the end of the header may be ambiguous and resulted in a
           corrupt HDU.  In this case the assumption is that the first 2880
           block that does not begin with valid FITS header data is the
           beginning of the data.

        kwargs : optional
           May consist of additional keyword arguments specific to an HDU
           type--these correspond to keywords recognized by the constructors of
           different HDU classes such as `PrimaryHDU`, `ImageHDU`, or
           `BinTableHDU`.  Any unrecognized keyword arguments are simply
           ignored.
        """
    return cls._readfrom_internal(data, checksum=checksum,
        ignore_missing_end=ignore_missing_end, **kwargs)


def svm(num_classes):
    """Support vector machine.
    -*- ref: mtobeiyf https://github.com/mtobeiyf/audio-classification -*-
    """
    from sklearn.svm import SVC
    return SVC(C=20.0, gamma=1e-05)


def commit(repo, message):
    """Commit the index to the repository

    The equivalent of :code:`git commit`

    Parameters
    ----------
    repo : dulwich.repo.Repo
    message : str
    """
    message = bytes(message, encoding='UTF-8')
    repo.do_commit(message)


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

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

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


def __call__(*args, **kwargs):
    """Return the possible site names"""


def truncate_value(limit, value):
    """
    Truncate ``value`` to a maximum of ``limit`` characters.
    """
    values = value.split(u'\n')
    value = values[0]
    if len(value) > limit or len(values) > 1:
        return u'{}…'.format(value[:limit])
    return value


def _test():
    """Run ``doctest`` on this module."""
    import doctest
    doctest.testmod()


def _load_tf_tensor(name, graph, session):
    """Loads a TensorFlow tensor object"""
    return graph.get_tensor_by_name(name)


def view_lock_clear():
    """Clear all view locking

    """
    pass


def prepareModel(modelClass=None, varList=[], dataCounterList=[], width=34,
    height=34, agentActivationPolicy='casual', cellActivationPolicy=
    'casual', bgcolor='#000000', modelInitFunc=None, wrapPolicy=None):
    """
    wrapPolicy有四种选择：
    'torus'(两方向绕转) 'box':xy边界均不可通过, 'vcylinder'：垂直回绕，水平不可通过,'hcylender'：水平回绕，垂直不可通过。
    """
    modelClass.varList = varList
    modelClass.dataCounters = dataCounterList
    modelClass.width = width
    modelClass.height = height
    modelClass.agentActivationPolicy = agentActivationPolicy
    modelClass.cellActivationPolicy = cellActivationPolicy
    modelClass.initAgents = modelInitFunc
    modelClass.wrapPolicy = wrapPolicy
    modelClass.bgColor = bgcolor
    return modelClass


@classmethod
def from_message(cls, message):
    """
        Create a public blob from a network `.Message`.

        Specifically, a cert-bearing pubkey auth packet, because by definition
        OpenSSH-style certificates 'are' their own network representation."
        """
    type_ = message.get_text()
    return cls(type_=type_, blob=message.asbytes())


def is_color_code(instance, attribute, value):
    """
    A validator that raises a :exc:`ValueError` if attribute value
    is not valid color code.
    Value considered as valid color code if it starts with # char
    followed by hexadecimal.
    """
    err = '{attr} should be a valid color code'.format(attr=attribute.name)
    if not value.startswith('#'):
        raise ValueError(err)
    if len(value) != 7:
        raise ValueError(err)
    try:
        int(value[1:], 16)
    except ValueError:
        raise ValueError(err)


def is_jwt(token):
    """Perform basic check if token is a JWT token."""
    return len(token.split('.')) == 3


def find_concat_dim(da, possible_concat_dims):
    """ look for available dimensions in dataaray and pick the one
    from a list of candidates

    PARAMETERS
    ----------
    da : xarray.DataArray
        xmitgcm llc data array
    possible_concat_dims : list
        list of potential dims

    RETURNS
    -------
    out : str
        dimension on which to concatenate

    """
    out = None
    for d in possible_concat_dims:
        if d in da.dims:
            out = d
    return out


def _add_line_str(target_str, line_str):
    """
    Add target line string for string concatenation.

    Parameters
    ----------
    target_str : str
        The string to be concatenated.
    line_str : str
        String of target line.

    Returns
    -------
    target_str : str
        Concatenated string.
    """
    if target_str != '':
        target_str += '\n'
    target_str += line_str
    return target_str


@classmethod
def _convert_facebook_data(cls, facebook_profile_data, username=True):
    """
        Takes facebook user data and converts it to a format for
        usage with Django
        """
    user_data = facebook_profile_data.copy()
    profile = facebook_profile_data.copy()
    website = profile.get('website')
    if website:
        user_data['website_url'] = cls._extract_url(website)
    user_data['facebook_profile_url'] = profile.get('link')
    user_data['facebook_name'] = profile.get('name')
    if len(user_data.get('email', '')) > 75:
        del user_data['email']
    gender = profile.get('gender', None)
    if gender == 'male':
        user_data['gender'] = 'm'
    elif gender == 'female':
        user_data['gender'] = 'f'
    user_data['username'] = cls._retrieve_facebook_username(user_data)
    user_data['password2'], user_data['password1'] = (cls.
        _generate_fake_password(),) * 2
    facebook_map = dict(birthday='date_of_birth', about='about_me', id=
        'facebook_id')
    for k, v in facebook_map.items():
        user_data[v] = user_data.get(k)
    user_data['facebook_id'] = int(user_data['facebook_id'])
    if not user_data['about_me'] and user_data.get('quotes'):
        user_data['about_me'] = user_data.get('quotes')
    user_data['date_of_birth'] = cls._parse_data_of_birth(user_data[
        'date_of_birth'])
    if username:
        user_data['username'] = cls._create_unique_username(user_data[
            'username'])
    if 'first_name' in user_data:
        user_data['first_name'] = user_data['first_name'][:30]
    if 'last_name' in user_data:
        user_data['last_name'] = user_data['last_name'][:30]
    return user_data


def int2onehot(labels):
    """Convert list of lists to a onehot matrix for multi-labels

    Parameters
    ----------
    labels: list of lists of integers
      e.g. [[0,1], [3], [1,2,3], [1], [2]]
      All integers from 0,1,...,K-1 must be represented."""
    from sklearn.preprocessing import MultiLabelBinarizer
    mlb = MultiLabelBinarizer()
    return mlb.fit_transform(labels)


def is_probably_part_of_multiline(line):
    """Return True if line is likely part of a multiline string.

    When multiline strings are involved, pep8 reports the error as being
    at the start of the multiline string, which doesn't work for us.

    """
    return '"""' in line or "'''" in line or line.rstrip().endswith('\\')


def get_ip_addresses(isamAppliance, check_mode=False, force=False):
    """
    Listing IP addresses for all interfaces
    """
    return isamAppliance.invoke_get('Listing IP addresses for all interfaces',
        '/isam/wga_templates/ipaddress')


def parameters_ui(layout, params):
    """ Create the ui for the rig parameters."""
    layers = ['primary_layers', 'secondary_layers']
    for layer in layers:
        r = layout.row()
        r.prop(params, layer + '_extra')
        r.active = getattr(params, layer + '_extra')
        col = r.column(align=True)
        row = col.row(align=True)
        for i in range(8):
            row.prop(params, layer, index=i, toggle=True, text='')
        row = col.row(align=True)
        for i in range(16, 24):
            row.prop(params, layer, index=i, toggle=True, text='')
        col = r.column(align=True)
        row = col.row(align=True)
        for i in range(8, 16):
            row.prop(params, layer, index=i, toggle=True, text='')
        row = col.row(align=True)
        for i in range(24, 32):
            row.prop(params, layer, index=i, toggle=True, text='')


def from_hex(hex_string):
    """
    Converts the given hex string to a byte array.

    This is a convenience method useful for testing values during development.

    :param hex_string: The hex String to parse to bytes.
    :return: A byte array, as parsed from the given String
    """
    result = None
    if hex_string is not None:
        result = bytearray.fromhex(hex_string)
    return result


def num_row_elements(row):
    """Get number of elements in CSV row."""
    try:
        rowset = set(row)
        rowset.discard('')
        return len(rowset)
    except TypeError:
        return 0


@classmethod
def connect(cls, connection_string, options=None, **kwargs):
    """
        Create a Cluster object.
        An Authenticator must be provided, either as the authenticator named parameter, or within the options argument.

        :param connection_string: the connection string for the cluster.
        :param options: options for the cluster.
        :param Any kwargs: Override corresponding value in options.
        """
    return cls(connection_string, options, **kwargs)


@classmethod
def disable(cls):
    """Stops observing for sinks and issues.
        """
    return cls.build_send_payload('disable', {}), None


@classmethod
def find_module(cls, fullname, path=None):
    """Find the built-in module.

        If 'path' is ever specified then the search is considered a failure.

        This method is deprecated.  Use find_spec() instead.

        """
    spec = cls.find_spec(fullname, path)
    return spec.loader if spec is not None else None


def get_op(operators, opcodes):
    """
    Get first operator that is present or None
    """
    for opcode in opcodes:
        if opcode in operators:
            return operators[opcode]
    return None


def describe_listeners(LoadBalancerArn=None, ListenerArns=None, Marker=None,
    PageSize=None):
    """
    Describes the specified listeners or the listeners for the specified Application Load Balancer. You must specify either a load balancer or one or more listeners.
    See also: AWS API Documentation

    Examples
    This example describes the specified listener.
    Expected Output:

    :example: response = client.describe_listeners(
        LoadBalancerArn='string',
        ListenerArns=[
            'string',
        ],
        Marker='string',
        PageSize=123
    )

    :type LoadBalancerArn: string
    :param LoadBalancerArn: The Amazon Resource Name (ARN) of the load balancer.

    :type ListenerArns: list
    :param ListenerArns: The Amazon Resource Names (ARN) of the listeners.
            (string) --

    :type Marker: string
    :param Marker: The marker for the next set of results. (You received this marker from a previous call.)

    :type PageSize: integer
    :param PageSize: The maximum number of results to return with this call.

    :rtype: dict
    :return: {
        'Listeners': [
            {
                'ListenerArn': 'string',
                'LoadBalancerArn': 'string',
                'Port': 123,
                'Protocol': 'HTTP'|'HTTPS',
                'Certificates': [
                    {
                        'CertificateArn': 'string'
                    },
                ],
                'SslPolicy': 'string',
                'DefaultActions': [
                    {
                        'Type': 'forward',
                        'TargetGroupArn': 'string'
                    },
                ]
            },
        ],
        'NextMarker': 'string'
    }

    """
    pass


def createNode(node, text):
    """ Create a child text node """
    root = node
    while root.nodeType != root.DOCUMENT_NODE:
        root = root.parentNode
    node.appendChild(root.createTextNode(text))
    return node


def get(obj):
    """Retrieve an iterable of the values associated with the object.

        If there are no references for `obj`, an iterable with no entries is
        returned.
        """


def get_constraints_value(constr):
    """
    Gets the final resulting number for the constraint expression so we can see how far we got from the limit.
    :LPAffineExpression constr: The constraint expression
    :returns float: The final resulting number
    """
    return constr._lhs.getValue()


def reload():
    """Update objects paths list with new data from the archive

    """
    pass


def location_dict_to_geojson(org_location_dict, filename, hashed_usernames=True
    ):
    """
    CURRENTLY BROKEN!
    Outputs a dict of users : locations to a CSV file.

    Requires org_location_dict and filename, optional hashed_usernames parameter.

    Uses hashes of usernames by default for privacy reasons. Think carefully
    about publishing location data about uniquely identifiable users. Hashing
    allows you to check unique users without revealing personal information.
    """
    import hashlib
    with open(filename, 'w') as f:
        header = '\n{ "type": "FeatureCollection",\n    "features": [\n'
        f.write(header)
        for user, location in org_location_dict.items():
            if location is not None:
                if hashed_usernames:
                    user_output = hashlib.sha1(user.encode('utf-8')).hexdigest(
                        )
                else:
                    user_output = user
                line = (
                    """
    {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": [%s, %s]
        },
        "properties": {
            "name": "%s"
        }
    },
"""
                     % (location.longitude, location.latitude, user_output))
                f.write(line)
        f.write(']}')
    f.close()


def smooth_window_size(npts: int) ->int:
    """Returns the a heuristic for the window size for smoothing an array with
    the given number of points. Specifically, this is 1/10 the number of points
    or 101, whichever is smaller.

    :param int npts: the number of data points you have

    :returns: suggested window size for smoothing the data
    """
    result = int(npts) // 10
    if result >= 100:
        return 101
    if result < 3:
        return 3
    if result % 2 == 0:
        result += 1
    return result


@classmethod
def name(cls):
    """
        Returns the name of the pass
        """
    return cls._name


def get_community_kernel(G, C: [frozenset]):
    """
    To get community kernels with most degrees.
    Parameters
    ----------
    G : graph
        An undirected graph.
    C : int
        #communities

    Returns
    -------
    kernels
    """
    area = []
    for i in range(len(G)):
        area.append(0)
    for i, cc in enumerate(C):
        for each_node in cc:
            area[each_node - 1] += 1 << i
    kernels = []
    cnt = 0
    for i in range(len(C)):
        mask = 1 << i
        cnt += 1
        q = []
        p = []
        for i in range(len(G)):
            if area[i] & mask == mask:
                q.append((G.degree[i + 1], i + 1))
        q.sort()
        q.reverse()
        for i in range(max(int(len(q) / 100), min(2, len(q)))):
            p.append(q[i][1])
        kernels.append(p)
    if len(kernels) < 2:
        print('ERROR: WE should have at least 2 communities.')
    for i in range(len(kernels)):
        if len(kernels[i]) == 0:
            print('Comunity %d is too small.' % i)
            return None
    return kernels


@classmethod
def get_latest(cls, class_name_or_obj, unique_id):
    """
        Get the latest Entry.
        """
    try:
        return cls.get_all_history(class_name_or_obj, unique_id).order_by(
            '-modified')[0]
    except IndexError:
        return None


@classmethod
def fromSuccessResponse(cls, success_response):
    """Create a C{L{Response}} object from a successful OpenID
        library response
        (C{L{openid.consumer.consumer.SuccessResponse}}) response
        message

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

        @rtype: Response or None
        @returns: A provider authentication policy response from the
            data that was supplied with the C{id_res} response or None
            if the provider sent no signed PAPE response arguments.
        """
    self = cls()
    args = success_response.getSignedNS(self.ns_uri)
    is_openid1 = success_response.isOpenID1()
    if args is not None:
        self.parseExtensionArgs(args, is_openid1)
        return self
    else:
        return None


def _get_xray_lines_family(xray_line):
    """
    Returns the family to which a particular X-ray line belongs.

    By example, if xray_line = 'Mn_Ka' this function returns 'Mn_K'
    """
    return xray_line[:xray_line.find('_') + 2]


@classmethod
def get_name(cls) ->str:
    """
        Tentacle name based on class name
        :return: the tentacle name
        """
    return cls.__name__


def rebuild_environment(EnvironmentId=None, EnvironmentName=None):
    """
    Deletes and recreates all of the AWS resources (for example: the Auto Scaling group, load balancer, etc.) for a specified environment and forces a restart.
    See also: AWS API Documentation

    Examples
    The following operation terminates and recreates the resources in an environment named my-env:
    Expected Output:

    :example: response = client.rebuild_environment(
        EnvironmentId='string',
        EnvironmentName='string'
    )

    :type EnvironmentId: string
    :param EnvironmentId: The ID of the environment to rebuild.
            Condition: You must specify either this or an EnvironmentName, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :type EnvironmentName: string
    :param EnvironmentName: The name of the environment to rebuild.
            Condition: You must specify either this or an EnvironmentId, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :return: response = client.rebuild_environment(
        EnvironmentName='my-env',
    )

    print(response)

    """
    pass


def load_policy_line(line, model):
    """loads a text line as a policy rule to model."""
    if line == '':
        return
    if line[:1] == '#':
        return
    tokens = line.split(', ')
    key = tokens[0]
    sec = key[0]
    if sec not in model.model.keys():
        return
    if key not in model.model[sec].keys():
        return
    model.model[sec][key].policy.append(tokens[1:])


def flushBrowserIdCookie():
    """Deletes the browser id cookie from the client browser.

        o Permission required: Access contents information

        o Raise BrowserIdManagerErr if the 'cookies' namespace isn't
          a browser id namespace.
        """


def default_info_response():
    """Default response when asking for info."""
    return dict(name='', argspec='', note='', docstring='', calltip='')


def ReplaceDict(Item, AvailableDict={}):
    """
	Replace each occurence of a parameter by its driver.
	"""
    for Key, Val in AvailableDict.items():
        if Item is None or isinstance(Item, (int, float)):
            pass
        elif isinstance(Item, (list, tuple)):
            pass
        else:
            Item = Item.replace(Key, str(AvailableDict[Key]))
    return Item


def begin_group(xml):
    """Begin of a fieldgroup
        """


def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

    :type operation_name: string
    :param operation_name: The operation name. This is the same name
            as the method name on the client. For example, if the
            method name is create_foo, and you'd normally invoke the
            operation as client.create_foo(**kwargs), if the
            create_foo operation can be paginated, you can use the
            call client.get_paginator('create_foo').

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


@classmethod
def register(cls, name: str) ->None:
    """Add a new label to the mapping.

        # Arguments
        name (): string label to register as new enum value

        """
    if name not in cls._values:
        cls._values.append(name)


def register():
    """
    Backward compatibility
    """
    pass


def wei_to_ether(wei):
    """
    Convert wei to ether
    """
    return 1.0 * wei / 10 ** 18


def __add__(form_fields):
    """Add two form fieldsets (IFormFieldsets) or add additional fields to
        an existing fieldset.

        Return a new IFormFieldsets which is a nested representation of the two.

        In order to fullfill the IFormFields API we make all fields available
        from the base IFormFieldsets.
        """


def replace_missing_fill(x_train, x_test=None, list_of_cols=[], method='',
    **extra_kwargs):
    """
    Replaces missing values with the known values ahead of it and behind it.

    Parameters
    ----------
    x_train: Dataframe or array like - 2d
        Dataset

    x_test: Dataframe or array like - 2d
        Testing dataset, by default None.

    list_of_cols : list
        A list of specific columns to apply this technique to, by default []

    method : str
        Type of fill, by default ''

    Returns
    -------
    Dataframe, *Dataframe
        Transformed dataframe with rows with a missing values in a specific row are missing

    Returns 2 Dataframes if x_test is provided.
    """
    extra_kwargs.pop('method', method)
    for col in list_of_cols:
        x_train[col] = x_train[col].fillna(method=method, **extra_kwargs)
        if x_test is not None:
            x_test[col] = x_test[col].fillna(method=method, **extra_kwargs)
    return x_train, x_test


def __init__(A):
    """PaymentInformationId - a model defined in Swagger"""
    A.discriminator = None


@classmethod
def make_static_url(cls, settings, path, include_version=True):
    """Constructs a versioned url for the given path.

        This method may be overridden in subclasses (but note that it
        is a class method rather than an instance method).  Subclasses
        are only required to implement the signature
        ``make_static_url(cls, settings, path)``; other keyword
        arguments may be passed through `~RequestHandler.static_url`
        but are not standard.

        ``settings`` is the `Application.settings` dictionary.  ``path``
        is the static path being requested.  The url returned should be
        relative to the current host.

        ``include_version`` determines whether the generated URL should
        include the query string containing the version hash of the
        file corresponding to the given ``path``.

        """
    url = settings.get('static_url_prefix', '/static/') + path
    if not include_version:
        return url
    version_hash = cls.get_version(settings, path)
    if not version_hash:
        return url
    return '%s?v=%s' % (url, version_hash)


def bitstrBE(byte):
    """
    make a bit string from big endian byte

    :param byte byte: a byte
    :return: a string of ones and zeros, the bbits in the byte
    """
    bits = ''
    for i in range(8):
        if byte[0] >> i & 1:
            bits += '1'
        else:
            bits += '0'
    return bits


def path_reference_copy(copy_set: set, report='print'):
    """Execute copying files of path_reference

    :param copy_set: set of (from, to) pairs to copy.
    :type copy_set: set
    :param report: function used for reporting warnings, takes a string argument.
    """
    pass


def cartesian(x, y):
    """Iterator for an 'outer' or cartesian join of
    x iterator and y iterator
    """
    for i in x:
        for j in y:
            yield i, j


@property
def batch_index(harn):
    """ The index of the current batch in the current epoch """
    return harn.bxs.get(harn.current_tag, 0)


def _makefpartparamsizes(nbparams):
    """return a struct format to read part parameter sizes

    The number parameters is variable so we need to build that format
    dynamically.
    """
    return b'>' + b'BB' * nbparams


def bool_formatter(bool_value):
    """
    convert Python boolean to json/xml format of boolean

    Parameters
    ----------
    bool_value: bool
        the boolean value that needs to be converted

    Returns
    -------
    str
        either "true" or "false"

    """
    if isinstance(bool_value, bool):
        if bool_value:
            return 'true'
        else:
            return 'false'
    else:
        msg = 'bool_value must be a boolean'
        raise ValueError(msg)


def update_parameter(old_parameter, new_parameter):
    """
    Works as the 'update' of dictionnaries but instead of replacing a list
    by another one, this method add each element of a list to the other by
    skipping duplicate.
    """
    for key in new_parameter:
        if key in old_parameter:
            if isinstance(old_parameter[key], list):
                for string_ in new_parameter[key]:
                    if string_ not in old_parameter[key]:
                        old_parameter[key].append(string_)
            else:
                old_parameter[key] = new_parameter[key]
        else:
            old_parameter[key] = new_parameter[key]


def update_config(source, data, path):
    """
    Tool function to update nested dict values.
    It creates sub-dictionaries to eventually end up with the proper dest key.
    """
    items = path.split('.')
    dest = items[-1]
    keys = items[:-1]
    last = source
    for k in keys:
        last = last.setdefault(k, {})
    last[dest] = data


def binary_eval(op, left, right):
    """token_lst has length 3 and format: [left_arg, operator, right_arg]
    operator(left_arg, right_arg) is returned"""
    return op(left, right)


@staticmethod
def fg(value: int) ->str:
    """
        Returns the foreground escape code for a 256 color id.
        See https://jonasjacek.github.io/colors/ for full list.
        """
    return f'\x1b[38;5;{value}m'


def split_translated_columns(df, on='SCP_Title', sep='\\[', min_title=10,
    initialize=''):
    """
    Creates new columns with the splite results of translates titles in the format lang1 `sep`lang2]`sep`.
    The new colums are called `on`_0 (not translated) `on`_1, and `on`_2.
    """
    if sep == '\\[':
        trail = '\\]'
    elif sep == '\\(':
        trail = '\\)'
    else:
        trail = ''
    it0 = df[~df[on].str.contains('.* %s[A-Za-z0-0\\s]{%d}' % (sep, min_title))
        ][on].str.split('\\s%s' % sep).str[0]
    it1 = df[df[on].str.contains('.* %s[A-Za-z0-0\\s]{%d}' % (sep, min_title))
        ][on].str.split('\\s%s' % sep).str[0]
    it2 = df[df[on].str.contains('.* %s[A-Za-z0-0\\s]{%d}' % (sep, min_title))
        ][on].str.replace('%s$' % trail, '').str.split('\\s%s' % sep).str[1]
    df['%s_0' % on] = initialize
    df['%s_1' % on] = initialize
    df['%s_2' % on] = initialize
    df.loc[it0.index.values, '%s_0' % on] = it0
    df.loc[it1.index.values, '%s_1' % on] = it1
    df.loc[it2.index.values, '%s_2' % on] = it2
    return df


def soil_thermal_conductivity(se_top):
    """
    Computes the soil thermal conductivity

    .. math ::
        k=0.15+18.5S_{e,top}

    Parameters
    ----------
    se_top : float
        effective saturation of the topsoil
        :math:`S_{e,top}`
        [-]

    Returns
    -------
    stc : float
        soil thermal conductivity
        :math:`k`
        [W m-1 K-1]

    Examples
    --------
    >>> import ETLook.radiation as rad
    >>> rad.soil_thermal_conductivity(se_top=0.4)
    0.8900000000000001
    """
    return 0.15 + 1.85 * se_top


def _join_prefix(prefix, name):
    """Filter certain superflous parameter name suffixes
    from argument names.
    :param str prefix: The potential prefix that will be filtered.
    :param str name: The arg name to be prefixed.
    :returns: Combined name with prefix.
    """
    if prefix.endswith('_specification'):
        return prefix[:-14] + '_' + name
    if prefix.endswith('_patch_parameter'):
        return prefix[:-16] + '_' + name
    if prefix.endswith('_update_parameter'):
        return prefix[:-17] + '_' + name
    return prefix + '_' + name


@staticmethod
def p_a2ml_array_specifier(p):
    """a2ml_array_specifier : BRACE_OPEN a2ml_constant BRACE_CLOSE
                                | BRACE_OPEN a2ml_constant BRACE_CLOSE a2ml_array_specifier"""
    p[0] = p[1]


@classmethod
def upload(cls):
    """Builds a package and uploads it to PyPI."""
    cls.run_command('clean --all sdist bdist_wheel upload')


def suppress_exceptions(callables, *exceptions):
    """
    Call each callable in callables, suppressing any exceptions supplied. If
    no exception classes are supplied, all Exceptions will be suppressed.

    >>> import functools
    >>> c1 = functools.partial(int, 'a')
    >>> c2 = functools.partial(int, '10')
    >>> list(suppress_exceptions((c1, c2)))
    [10]
    >>> list(suppress_exceptions((c1, c2), KeyError))
    Traceback (most recent call last):
    ...
    ValueError: invalid literal for int() with base 10: 'a'
    """
    if not exceptions:
        exceptions = Exception,
    for callable in callables:
        try:
            yield callable()
        except exceptions:
            pass


def uuid_convert(value):
    """Strips the leading 'uuid:' part from the string."""
    return value.split(':')[-1]


def pad(number, divisor):
    """
    Pads an integer up to the given divisor.
    """
    if number % divisor:
        number = (number // divisor + 1) * divisor
    return number


@staticmethod
def _get_router_ids_from_removed_devices_info(removed_devices_info):
    """Extract router_ids from the removed devices info dict.

        :param removed_devices_info: Dict of removed devices and their
               associated resources.
        Format:
                {
                  'hosting_data': {'hd_id1': {'routers': [id1, id2, ...]},
                                   'hd_id2': {'routers': [id3, id4, ...]},
                                   ...
                                  },
                  'deconfigure': True/False
                }
        :return removed_router_ids: List of removed router ids
        """
    removed_router_ids = []
    for hd_id, resources in removed_devices_info['hosting_data'].items():
        removed_router_ids += resources.get('routers', [])
    return removed_router_ids


def safe_getitem(dct, key, item):
    """Return either dct[key][item],  dct[key].item, or None, whichever
    is appropriate
    """
    if key not in dct:
        return None
    value = dct[key]
    try:
        result = value[item]
    except TypeError:
        if isinstance(item, str):
            result = getattr(value, item, None)
        else:
            result = None
    except (KeyError, IndexError) as ex:
        result = None
    return result


def maybe_flatten(value):
    """Extract values from 0-d numpy arrays, if necessary"""
    if hasattr(value, 'shape') and not value.shape:
        return value.flatten()[0]
    return value


def _format_date_param(params, key, format='%Y-%m-%d %H:%M:%S'):
    """
    Utility function to convert datetime values to strings.

    If the value is already a str, or is not in the dict, no change is made.

    :param params: A `dict` of params that may contain a `datetime` value.
    :param key: The datetime value to be converted to a `str`
    :param format: The `strftime` format to be used to format the date. The default value is '%Y-%m-%d %H:%M:%S'
    """
    if key in params:
        param = params[key]
        if hasattr(param, 'strftime'):
            params[key] = param.strftime(format)


def mun2i_NH3_NH3_K_CB89(T, P):
    """n-n-c: ammonia ammonia potassium [CB89]."""
    mun2i = -0.000321
    valid = T == 298.15
    return mun2i, valid


def print_query(query):
    """ Pretty prints the given query. """
    formatted = format(query.decode('utf-8'), reindent=True)
    formatted = formatted.replace('\n', '\n  ')
    print('> {}'.format(formatted))


def function_or_class_name(obj):
    """
    Given a callable, try to determine its name. Return 'None' if None.
    """
    try:
        return obj.__name__
    except AttributeError:
        return obj.__class__.__name__


def retry_if_result_none(result):
    """Return True if we should retry (in this case when result is None), False otherwise"""
    return result is None


def beg_ends(starting_dt, extent_duration, z=None):
    """
    >>> starting = parse('2018-03-02 9am')
    >>> beg_ends(starting, parse_duration('2d2h20m')[1])
    [(DateTime(2018, 3, 2, 9, 0, 0, tzinfo=Timezone('UTC')), DateTime(2018, 3, 2, 23, 59, 59, 999999, tzinfo=Timezone('UTC'))), (DateTime(2018, 3, 3, 0, 0, 0, tzinfo=Timezone('UTC')), DateTime(2018, 3, 3, 23, 59, 59, 999999, tzinfo=Timezone('UTC'))), (DateTime(2018, 3, 4, 0, 0, 0, tzinfo=Timezone('UTC')), DateTime(2018, 3, 4, 11, 20, 0, tzinfo=Timezone('UTC')))]
    >>> beg_ends(starting, parse_duration('8h20m')[1])
    [(DateTime(2018, 3, 2, 9, 0, 0, tzinfo=Timezone('UTC')), DateTime(2018, 3, 2, 17, 20, 0, tzinfo=Timezone('UTC')))]
    """
    pairs = []
    beg = starting_dt
    ending = starting_dt + extent_duration
    while ending.date() > beg.date():
        end = beg.end_of('day')
        pairs.append((beg, end))
        beg = beg.start_of('day').add(days=1)
    pairs.append((beg, ending))
    return pairs


def copy():
    """Copy the material settings and nodes

    """
    pass


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


def update_minmax(dic, data):
    """
    Update the MAX/MIN dictionary keys.
    """
    dic['FDMAX'] = float(data.max().real)
    dic['FDDISPMAX'] = dic['FDMAX']
    dic['FDMIN'] = float(data.min().real)
    dic['FDDISPMIN'] = dic['FDMIN']
    dic['FDSCALEFLAG'] = 1.0
    return dic


def gross_profit_margin(gross_profit, revenue):
    """Computes gross profit margin.

    @params
    -------
    gross_profit: gross profit
    revenue: revenue (or sales)

    returns
    -------
    Gross profit margin, int or float

    explanation
    -----------

    """
    return gross_profit / revenue


def _get_boolean_elements():
    """
    Returns sets of elements recognisable as booleans
    """
    true_set = {'True', 'true', 'TRUE', 'tru', 1, 't', 'T', '1', float(1),
        True, 'yes', 'Yes', 'YES', 'Y', 'y'}
    false_set = {'False', 'false', 'FALSE', 'fals', 0, 'f', 'F', '0', float
        (0), False, 'no', 'No', 'NO', 'N', 'n'}
    return true_set, false_set


def _truncate_seq_pair(tokens_a, tokens_b, max_length: int):
    """
    Copied exactly from: https://github.com/huggingface/pytorch-pretrained-BERT/blob/78462aad6113d50063d8251e27dbaadb7f44fbf0/examples/extract_features.py#L150
    Truncates a sequence pair in place to the maximum length.
    """
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_length:
            break
        if len(tokens_a) > len(tokens_b):
            tokens_a.pop()
        else:
            tokens_b.pop()


def normalize(returns, starting_value=1):
    """
    Normalizes a returns timeseries based on the first value.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    starting_value : float, optional
       The starting returns (default 1).

    Returns
    -------
    pd.Series
        Normalized returns.
    """
    return starting_value * (returns / returns.iloc[0])


def _is_valid_quarter(quarter):
    """Is quarter within 1..4?"""
    return quarter and quarter > 0 and quarter <= 4


def default(inst):
    """Default routine to be applied when loading data.

    Note
    ----
        Removes ICON preamble on variable names.

    """
    import pysat.instruments.icon_ivm as icivm
    inst.tag = 'level_2'
    icivm.remove_icon_names(inst, target='ICON_L2_MIGHTI_')


def delete_account_password_policy():
    """
    Deletes the password policy for the AWS account. There are no parameters.
    See also: AWS API Documentation

    Examples
    The following command removes the password policy from the current AWS account:
    Expected Output:

    :example: response = client.delete_account_password_policy()

    :return: response = client.delete_account_password_policy(
    )

    print(response)

    """
    pass


@classmethod
def format_str(cls):
    """ Return a string describing the fitted function.

        The string must contain one formatting argument for each coefficient.
        """
    return 'FORMAT STRING NOT DEFINED'


def get(isamAppliance, check_mode=False, force=False):
    """
    Retrieve existing debug level.
    """
    return isamAppliance.invoke_get('Retrieving debug level for embedded ldap',
        '/isam/embedded_ldap/debug_level/v1')


@classmethod
def from_orientation_lists(cls, identifiers, structures, orientations):
    """
        Creates a structure library from "manual" orientation lists

        Parameters
        ----------
        identifiers : list of strings/ints
            A list of phase identifiers referring to different atomic structures.
        structures : list of diffpy.structure.Structure objects.
            A list of diffpy.structure.Structure objects describing the atomic
            structure associated with each phase in the library.
        orientations : list of lists of tuples
            A list over identifiers of lists of euler angles (as tuples) in the rzxz
            convention and in degrees.
        Returns
        -------
        StructureLibrary
        """
    return cls(identifiers, structures, orientations)


@staticmethod
def maybe_unwrap(func):
    """Return the given function, without its probe_wrapper if it has one."""
    if getattr(getattr(func, '__code__', None), 'co_name', ''
        ) == 'probe_wrapper':
        return func.__closure__[0].cell_contents
    else:
        return func


def render_html(content: str) ->str:
    """
    Return a html fragment unchanged.

    Parameters
    ----------
    content : str
        Html text.

    Returns
    -------
    html : str
    """
    return content


def _andparam(params):
    """
    string join parameter list with &
    """
    return '&'.join(params)


def user_open(url_or_command):
    """Open the specified paramater in the web browser if a URL is detected,
    othewrise pass the paramater to the shell as a subprocess. This function
    is inteded to bu used in on_leftclick/on_rightclick callbacks.

    :param url_or_command: String containing URL or command
    """
    from urllib.parse import urlparse
    scheme = urlparse(url_or_command).scheme
    if scheme == 'http' or scheme == 'https':
        import webbrowser
        import os
        savout = os.dup(1)
        os.close(1)
        os.open(os.devnull, os.O_RDWR)
        try:
            webbrowser.open(url_or_command)
        finally:
            os.dup2(savout, 1)
    else:
        import subprocess
        subprocess.Popen(url_or_command, shell=True)


def compute_meandiff_bias_correction(bootstraps, effsize):
    """
    Computes the bias correction required for the BCa method
    of confidence interval construction.

    Keywords
    --------
    bootstraps: array-like
        An numerical iterable, comprising bootstrap resamples
        of the effect size.

    effsize: numeric
        The effect size for the original sample.

    Returns
    -------
    bias: numeric
        The bias correction value for the given bootstraps
        and effect size.

    """
    from scipy.stats import norm
    from numpy import array
    B = array(bootstraps)
    prop_less_than_es = sum(B < effsize) / len(B)
    return norm.ppf(prop_less_than_es)


def get_caching_servers():
    """return the set of frontend caching servers"""


def mark_region(ax, low, high, vline_style, span_style):
    """
    Mark a region of a graph with vertical lines and an axvspan

    Parameters
    ----------
    ax : Axes
        The `Axes` object to add the artist too

    low, high : float
        The low and high threshold values, points for `low < x < high` are
        styled using `inner_style` and points for `x < low or x > high` are
        styled using `outer_style`

    vline_style : dict, optional
        The style to use for the vertical lines

    span_stlye : dict, optional
        Style for axvspan behind central region

    Returns
    -------

    vline_low, vline_hi : Line2D
        Vertical lines at the thresholds

    hspan : Patch
        Patch over middle region

    """
    vline_low = ax.axvline(low, **vline_style)
    vline_high = ax.axvline(high, **vline_style)
    hspan = ax.axvspan(low, high, **span_style)
    return vline_low, vline_high, hspan


def hide_tracks(unselected: bool=False):
    """Hide selected tracks

    :param unselected: Unselected, Hide unselected tracks
    :type unselected: bool
    """
    pass


def n_params(model):
    """Return the number of parameters in a pytorch model.

    Args:
        model (nn.Module): The model to analyze.

    Returns:
        int: The number of parameters in the model.
    """
    pp = 0
    for p in list(model.parameters()):
        nn = 1
        for s in list(p.size()):
            nn = nn * s
        pp += nn
    return pp


@classmethod
def get_from_collected_values(cls, contextual_vals, option_vals):
    """
        When the menu class also subclasses django.db.models.Model, this
        method is called by ``render_from_tag()`` to 'get' a menu object
        appropriate for the provided contextual and option values.
        """
    raise NotImplementedError(
        "Subclasses of 'Menu' and 'django.db.models.Model' must define their own 'get_from_collected_values' method."
        )


def override_dict(a, overrides):
    """Override a dict with another one **only first non nested keys**.

    Notes
    -----
    This works only with non-nested dict. If dictionarries are nested then the
    nested dict needs to be completly overriden.
    The Operation is performed inplace.

    Parameters
    ----------
    a : dict
        a dictionary to merge.
    overrides : dict
        another dictionary to merge.
    """
    for key, val in overrides.items():
        try:
            if type(a[key]) == dict:
                print(
                    "**warning**: key '{}' contained a dict make sure to override each value in the nested dict."
                    .format(key))
        except KeyError:
            pass
        a[key] = val


def get_current_site_pk(request):
    """Seemingly pointless function is so calling code doesn't have to worry
    about the import issues between Django 1.6 and later."""
    from django.contrib.sites.models import Site
    try:
        from django.contrib.sites.shortcuts import get_current_site
    except ImportError:
        from django.contrib.sites.models import get_current_site
    return get_current_site(request).pk


@staticmethod
def in_back(progress):
    """.. image:: images/anim_in_back.png
        """
    return progress * progress * ((1.70158 + 1.0) * progress - 1.70158)


def pad_line(line):
    """Helper function to pad line to 80 characters in case it is shorter"""
    size_of_line = len(line)
    if size_of_line < 80:
        padding = 80 - size_of_line + 1
        line = line.strip('\n') + ' ' * padding + '\n'
    return line[:81]


def energy_to_wavelength(energy):
    """
    Converts photon energy (keV) to wavelength (A)
    """
    return 12.39842 / energy


def camera_add(view_align: bool=False, enter_editmode: bool=False, location:
    float=(0.0, 0.0, 0.0), rotation: float=(0.0, 0.0, 0.0), layers: bool=(
    False, False, False, False, False, False, False, False, False, False,
    False, False, False, False, False, False, False, False, False, False)):
    """Add a camera object to the scene

    :param view_align: Align to View, Align the new object to the view
    :type view_align: bool
    :param enter_editmode: Enter Editmode, Enter editmode when adding this object
    :type enter_editmode: bool
    :param location: Location, Location for the newly added object
    :type location: float
    :param rotation: Rotation, Rotation for the newly added object
    :type rotation: float
    :param layers: Layer
    :type layers: bool
    """
    pass


def short_to_bytes(short_value):
    """
    Transforms a short to a byte array (using Big-Endian!)

    :param short_value: Any integer that is greater than 0 and smaller than 65535
    :return: A bytes array with the highest byte at position 0 and the lowest at position 1
    """
    return bytes([int(short_value) >> 8]) + bytes([int(short_value) & 255])


def time_complexities():
    """
    Return information on functions
    time complexity
    :return: string
    """
    return 'Best Case: O(n), Average Case: O(n), Worst Case: O(n)'


def list_rpm(archive, compression, cmd, verbosity, interactive):
    """List a RPM archive."""
    cmdlist = [cmd, '-q', '-l']
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.extend(['-p', '--', archive])
    return cmdlist


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 _get_subclasses(klass):
    """ Adapted from http://stackoverflow.com/a/29106313/1938621. """
    result = [klass]
    classes_to_inspect = [klass]
    while classes_to_inspect:
        class_to_inspect = classes_to_inspect.pop()
        for subclass in class_to_inspect.__subclasses__():
            if subclass not in result:
                result.append(subclass)
                classes_to_inspect.append(subclass)
    return result


def p_extends_from(p):
    """extends_from : empty
                    | EXTENDS fully_qualified_class_name"""
    if len(p) == 3:
        p[0] = p[2]


@staticmethod
def time_remaining(current, total, time_remaining):
    """Returns the time remaining."""
    return '~{} remaining'.format(time_remaining)


@staticmethod
def interval_vector_mid_points(vec):
    """
        Given a vector of complex intervals, return the midpoints (as 0-length
        complex intervals) of them.
        """
    BaseField = vec[0].parent()
    return vec.apply_map(lambda shape: BaseField(shape.center()))


@staticmethod
def _directive_del_attribute(directive_body):
    """Directive for :py:meth:`del_attribute`"""
    instance, attribute_name = directive_body
    return delattr(instance, attribute_name)


def mesh_to_bmesh(bm: 'bmesh.types.BMesh', mesh: 'bpy.types.Mesh', object:
    'bpy.types.Object', use_shapekey: bool):
    """Load the contents of a mesh into the bmesh. this bmop is private, it’s reserved exclusively for entering editmode.

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param mesh: Undocumented.
    :type mesh: 'bpy.types.Mesh'
    :param object: Undocumented.
    :type object: 'bpy.types.Object'
    :param use_shapekey: load active shapekey coordinates into verts
    :type use_shapekey: bool
    """
    pass


def build_plural_mappings(special_mappings, resource_map):
    """Create plural to singular mapping for all resources.

    Allows for special mappings to be provided, like policies -> policy.
    Otherwise, will strip off the last character for normal mappings, like
    routers -> router.
    """
    plural_mappings = {}
    for plural in resource_map:
        singular = special_mappings.get(plural)
        if not singular:
            if plural.endswith('ies'):
                singular = '%sy' % plural[:-3]
            else:
                singular = plural[:-1]
        plural_mappings[plural] = singular
    return plural_mappings


def filter(tracks, condition_func):
    """A workaround for a bug in pandas 0.12

    Parameters
    ----------
    tracks : DataFrame
        must include column named 'particle'
    condition_func : function
        The function is applied to each group of data. It must
        return True or False.

    Returns
    -------
    DataFrame
        a subset of tracks
    """
    grouped = tracks.reset_index(drop=True).groupby('particle')
    filtered = grouped.filter(condition_func)
    return filtered.set_index('frame', drop=False)


def PrettyOS(os, os_v1=None, os_v2=None, os_v3=None, os_v4=None):
    """Pretty os string."""
    if os_v4:
        return '%s %s.%s.%s.%s' % (os, os_v1, os_v2, os_v3, os_v4)
    if os_v3:
        if os_v3[0].isdigit():
            return '%s %s.%s.%s' % (os, os_v1, os_v2, os_v3)
        else:
            return '%s %s.%s%s' % (os, os_v1, os_v2, os_v3)
    elif os_v2:
        return '%s %s.%s' % (os, os_v1, os_v2)
    elif os_v1:
        return '%s %s' % (os, os_v1)
    return os


def _npx_reshape(a, newshape, reverse=False, order='C'):
    """
    Gives a new shape to an array without changing its data.
    This function always returns a copy of the input array if
    ``out`` is not provided.

    Parameters
    ----------
    a : ndarray
        Array to be reshaped.
    newshape : int or tuple of ints
        The new shape should be compatible with the original shape.
        If an integer, then the result will be a 1-D array of that length.
        One shape dimension can be -1. In this case, the value is inferred
        from the length of the array and remaining dimensions.
        -2 to -6 are used for data manipulation.

        - -2 copy this dimension from the input to the output shape.
        - -3 will skip current dimension if and only if the current dim size is one.
        - -4 copy all remain of the input dimensions to the output shape.
        - -5 use the product of two consecutive dimensions of the input
          shape as the output.
        - -6 split one dimension of the input into two dimensions passed
          subsequent to -6 in the new shape.

    reverse : bool, optional
        If set to true, the special values will be inferred from right to left.
    order : {'C'}, optional
        Read the elements of `a` using this index order, and place the
        elements into the reshaped array using this index order.  'C'
        means to read / write the elements using C-like index order,
        with the last axis index changing fastest, back to the first
        axis index changing slowest. Other order types such as 'F'/'A'
        may be added in the future.

    Returns
    -------
    reshaped_array : ndarray
        It will be always a copy of the original array. This behavior is different
        from the official NumPy ``reshape`` operator where views of the original array may be
        generated.

    Examples
    --------
    >>> x = np.ones((2, 3, 8))
    >>> npx.reshape(x, (-2, -2, 2, -1)).shape
    (2, 3, 2, 4)
    >>> x = np.ones((8, 3, 3, 3, 4, 4))
    >>> npx.reshape(x, (-6, 2, -1, -4)).shape
    (2, 4, 3, 3, 3, 4, 4)
    >>> x = np.ones((8, 3, 3, 3, 4, 4))
    >>> npx.reshape(x, (-5, -4)).shape
    (24, 3, 3, 4, 4)
    >>> x = np.ones((8, 1, 1, 1, 3))
    >>> npx.reshape(x, (-2, -3, -3, -3, -2)).shape
    (8, 3)
    >>> x = np.ones((8, 3, 3, 3, 3, 8))
    >>> npx.reshape(x, (-4, -5), reverse=True).shape
    (8, 3, 3, 3, 24)
    >>> x = np.ones((8, 3, 2, 4, 8))
    >>> npx.reshape(x, (-4, -1, 2, -6), reverse=True).shape
    (8, 3, 2, 4, 4, 2)
    """
    pass


@classmethod
def format_tstamp_secs(cls, tstamp):
    """Return epoch seconds only from timestamp."""
    t_tup = cls.timestamp_to_dbtime(tstamp)
    return str(t_tup[0])


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


def substitute_half_a_bitvector(pattern: str, args: 'List[int]') ->int:
    """
    Helper function for `substitute_bitvector`. Takes an 8-bit pattern and returns a
    single byte.
    """
    ret = 0
    for shift, pattern_bit in enumerate(reversed(pattern)):
        if pattern_bit == '0':
            real_bit = 0
        elif pattern_bit == '1':
            real_bit = 1
        else:
            index = ord(pattern_bit.lower()) - ord('a')
            real_bit = args[index] & 1
            args[index] >>= 1
        ret += real_bit << shift
    return ret


def search(query, **kwargs):
    """
        Given a string or unicode object as a query, search for
        user by full name or user login name.  Return a
        iterator of tuples of (username, user) for each match.
        Fielded search keywords can be passed for use by underlying
        user query mechanism provided by PluggableAuthService.
        """


def pollutant():
    """
    Water treatment example from BHH2, Ch 5, Question 19.

    Description
    -----------
    The data are from the first 8 rows of the pollutant water treatment example
    n the book by Box, Hunter and Hunter, 2nd edition, Chapter 5, Question 19.

    The 3 factors (C, T, and S) are in coded units where:
    C = -1 is chemical brand A; C = +1 is chemical brand B
    T = -1 is 72F for treatment temperature; T = +1 is 100F for the temperature
    S = -1 is No stirring; S = +1 is with fast stirring

    The outcome variable is:
    y = the pollutant amount in the discharge [lb/day].

    The aim is to find treatment conditions that MINIMIZE the amount of pollutant
    discharged each day, where the limit is 10 lb/day.

    Dimensions
    ----------
    A data frame containing 8 observations of 4 variables (C, S, T and y).

    Source
    ------
    Box, G. E. P. and Hunter, J. S. and Hunter, W. G.r, Statistics for
    Experimenters, Wiley, 2nd edition, Chapter 5, Question 19, page 232.

    Example
    -------

    """


def list_items(obj):
    """
    Returns a list of key,value pairs for the content of an object
    Creates an abstraction layer so that we do not have to worry.
    """
    try:
        return obj.items()
    except AttributeError:
        return obj.__dict__.items()
    except TypeError:
        return enumerate(list(obj))


def _handle_inplace_replacements(document, link, link_ancestors):
    """
    Given a new document, and the link/ancestors it was created,
    determine if we should:

    * Make an inline replacement and then return the modified document tree.
    * Return the new document as-is.
    """
    if not link.transform:
        if link.action.lower() in ('put', 'patch', 'delete'):
            transform = 'inplace'
        else:
            transform = 'new'
    else:
        transform = link.transform
    if transform == 'inplace':
        root = link_ancestors[0].document
        keys_to_link_parent = link_ancestors[-1].keys
        if document is None:
            return root.delete_in(keys_to_link_parent)
        return root.set_in(keys_to_link_parent, document)
    return document


def extrude_faces_indiv(mirror: bool=False):
    """Extrude individual faces only

    :param mirror: Mirror Editing
    :type mirror: bool
    """
    pass


def _id_key_func(x: str):
    """ID key function."""
    try:
        s = int(x.split('_')[0])
    except ValueError:
        return x
    else:
        return s


def _trim_bounds(arr):
    """ Returns the bounds which would be used in numpy.trim_zeros """
    first = 0
    for i in arr:
        if i != 0.0:
            break
        else:
            first = first + 1
    last = len(arr)
    for i in arr[::-1]:
        if i != 0.0:
            break
        else:
            last = last - 1
    return first, last


def addlist():
    """
    @api {post} /music/collect/addlist 收藏歌单
    @apiVersion 1.0.0
    @apiGroup Collect
    @apiDescription 收藏歌单

    @apiParam (Headers) {string} token 令牌
    @apiParam (Headers) {String} device_token 设备令牌
    @apiParam (Headers) {String} content_type 内容类型
    @apiParam (Headers) {String} timestamp 时间戳

    @apiParam (Body) {String} selflist 自建列表
    @apiParam (Body) {String} playlistid 播放列表编号

    @apiSuccessExample {json} Success-Response:
    "Success."

    @apiError (Error) 31019 UnSupport type in the request params!
    @apiError (Error) 31006 No playlist id in the request params!

    @apiErrorExample {json} Error-Response1:
    {
        "data": "No type in the request params!"
    }
    @apiErrorExample {json} Error-Response2:
    {
        "data": "No playlist id in the request params!"
    }
    """


def nextpowb(b, n):
    """Find :math:`p` that satisfies :math:`b^p \\ge |n|`.

    Parameters
    ----------
    b : int or float
        the base of the power :math:`p`. That is, the base :math:`b` in
        :math:`b^p`.
    n : int or float
        the value with absolute value that :math:`b^p` must be greater than
        or equal to.

    Returns
    -------
    p : int or float
        the power of :math:`b` satisfying :math:`b^p \\ge |n|`.

    """
    p = 0
    powb = b ** p
    while powb < abs(n):
        p = p + 1
        powb = b ** p
    return p


def swapaxes(input, axis1, axis2):
    """Interchange the two given axes of a tensor.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    axis1, axis2 : int
        The two axes.

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


def get_first_image(obj):
    """
    Returns the first image related to the object or None
    if there is no images. The first image is the image
    with the smallest value of the 'position' field.
    """
    images = obj.content_gallery.all().order_by('position')[:1]
    if not images:
        return None
    return images[0]


def __new__(mcs, name, bases, cls_dict):
    """Return a new class with predefined comparison operators"""
    for method_name in ('__lt__', '__le__', '__gt__', '__ge__', '__eq__',
        '__ne__'):
        if method_name not in cls_dict:
            cls_dict[method_name] = mcs._make_operator(method_name)
    return type.__new__(mcs, name, bases, cls_dict)


def query_float(message: str):
    """Ask the user for a float"""
    while True:
        try:
            user_input = float(input(message))
        except ValueError:
            print('Please enter a valid float.')
            continue
        else:
            return user_input


@staticmethod
def a_static_method():
    """This is a static method."""


def _combine_threshold(d, threshold):
    """
    calculate combination number
    :param d:
    :return: a list of combination number
    """
    result = []
    sign = -1
    result.append(1)
    i = 1
    while True:
        number = (d - i + 1) / i * result[-1] * sign
        if abs(number) > threshold:
            result.append(number)
            i += 1
        else:
            break
    return result


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 electrical_mobility_from_D(D, charge, T, constants=None, units=None):
    """
    Calculates the electrical mobility through Einstein-Smoluchowski relation.

    Parameters
    ----------
    D: float with unit
        Diffusion coefficient
    charge: integer
        charge of the species
    T: float with unit
        Absolute temperature
    constants: object (optional, default: None)
        if None:
            T assumed to be in Kelvin and b0 = 1 mol/kg
        else:
            see source code for what attributes are used.
            Tip: pass quantities.constants
    units: object (optional, default: None)
        attributes accessed: meter, Kelvin and mol

    Returns
    -------
    Electrical mobility

    """
    if constants is None:
        kB = 1.38064852e-23
        e = 1.60217662e-19
        if units is not None:
            kB *= units.joule / units.kelvin / units.mol
            e *= units.coulomb
    else:
        kB = constants.Boltzmann_constant
        e = constants.elementary_charge
    return D * charge * e / (kB * T)


def get_vht_capa(type_, data):
    """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n889

    Positional arguments:
    type_ -- corresponding `ieprinters` dictionary key for the instance.
    data -- bytearray data to read.
    """
    raise NotImplementedError


@classmethod
def run(cls, config, dry_run=False):
    """Run the reV batch job from a config file.

        Parameters
        ----------
        config : str
            File path to config json (str).
        dry_run : bool
            Flag to make job directories without running.
        """
    b = cls(config)
    b._make_job_dirs()
    if not dry_run:
        b._run_pipelines()


def ModifyGroup(r, group, **kwargs):
    """
    Modifies a node group.

    More details for parameters can be found in the RAPI documentation.

    @type group: string
    @param group: Node group name
    @rtype: int
    @return: job id
    """
    return r.request('put', '/2/groups/%s/modify' % group, content=kwargs)


def drange(v0, v1, d):
    """Returns a discrete range."""
    assert v0 < v1
    return range(int(v0) // d, int(v1 + d) // d)


def get_out_of_order(list_of_numbers):
    """Returns elements that break the monotonically non-decreasing trend.

  This is used to find instances of global step values that are "out-of-order",
  which may trigger TensorBoard event discarding logic.

  Args:
    list_of_numbers: A list of numbers.

  Returns:
    A list of tuples in which each tuple are two elements are adjacent, but the
    second element is lower than the first.
  """
    result = []
    for i in range(len(list_of_numbers)):
        if i == 0:
            continue
        if list_of_numbers[i] < list_of_numbers[i - 1]:
            result.append((list_of_numbers[i - 1], list_of_numbers[i]))
    return result


def _clear():
    """Remove the registries (for use by tests)."""
    global _vocabularies
    _vocabularies = None


def get_name(friendly=False):
    """Get name of this resource

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Service escalation'
    return 'serviceescalation'


def add_punctuation(text):
    """add punctuation at the end of each chunk. Mimic2
    expects some form of punctuations
    """
    punctuations = ['.', '?', '!']
    if len(text) < 1:
        return text
    if text[-1] not in punctuations:
        text += '.'
    return text


def extract_method_name(method_func):
    """Extract method name from lambda function."""
    return '_'.join(method_func.__code__.co_names)


@staticmethod
def support_global_request_object():
    """
            whether current framework supports global request object like Flask
        """
    raise NotImplementedError


def __hash__():
    """
        Generate a hash value for the request.

        @return: The request's hash value.
        @rtype: L{int}
        """


def __call__(cls, *args, name=None, **kwargs):
    """
        name is reserved kwarg for naming instances

        TODO: Generalize handling of instance parameters
        """
    inst_kwargs = {}
    if name is not None:
        inst_kwargs['name'] = name
    return cls.generate(*args, **kwargs)(**inst_kwargs)


def update(*args, **kwds):
    """od.update(E, **F) -> None.  Update od from dict/iterable E and F.

        If E is a dict instance, does:           for k in E: od[k] = E[k]
        If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]
        Or if E is an iterable of items, does:   for k, v in E: od[k] = v
        In either case, this is followed by:     for k, v in F.items(): od[k] = v

        """
    if len(args) > 2:
        raise TypeError(
            'update() takes at most 2 positional arguments (%d given)' % (
            len(args),))
    elif not args:
        raise TypeError('update() takes at least 1 argument (0 given)')
    self = args[0]
    other = ()
    if len(args) == 2:
        other = args[1]
    if isinstance(other, dict):
        for key in other:
            self[key] = other[key]
    elif hasattr(other, 'keys'):
        for key in other.keys():
            self[key] = other[key]
    else:
        for key, value in other:
            self[key] = value
    for key, value in kwds.items():
        self[key] = value


def get_vms(app, scope='deployment'):
    """Return the VMs in an application."""
    return app.get(scope, {}).get('vms', [])


def iris(round_limit=2, random_method='uniform_mersenne'):
    """Performs a Scan with Iris dataset and simple dense net"""
    import talos as ta
    scan_object = ta.Scan(ta.templates.datasets.iris()[0], ta.templates.
        datasets.iris()[1], ta.templates.params.iris(), ta.templates.models
        .iris, 'test', round_limit=round_limit)
    return scan_object


def get_priority(case_dict):
    """Get the topic's priority（equivalent to the importance of the testcase)"""
    if isinstance(case_dict['markers'], list):
        for marker in case_dict['markers']:
            if marker.startswith('priority'):
                return int(marker[-1])


def upsert_box(data, newdata, who):
    """
    Given a new box, figure out if an existing box needs to be destroyed.
    If it appears to be the same thing, merge the two boxes or overwrite the old one.
    """


@classmethod
def table_name_col(cls):
    """
        Return the name of the metadata column used to store the feature table
        name.
        """
    return 'table_name'


def dissect_time(sec):
    """changes total seconds into hours, minutes, seconds"""
    seconds = sec % 60
    minutes = sec // 60 % 60
    hours = sec // 60 // 60
    return hours, minutes, seconds


def signalProcess(signalID):
    """
        Send a signal to the process.

        @param signalID: can be
          - one of C{"KILL"}, C{"TERM"}, or C{"INT"}.
              These will be implemented in a
              cross-platform manner, and so should be used
              if possible.
          - an integer, where it represents a POSIX
              signal ID.

        @raise twisted.internet.error.ProcessExitedAlready: If the process has
            already exited.
        @raise OSError: If the C{os.kill} call fails with an errno different
            from C{ESRCH}.
        """


def transpose_cuda(a):
    """Return the transpose of a GPUArray.

     Parameters
    ----------
    a : GPUArray
        Array on GPU memory.

    Returns
    -------
    gpuarray
        Tranpose of the input GPUArray.

    Examples
    --------
    >>> a = transpose_cuda(give_cuda([[0, 1], [2, 3]]))
    array([[ 0.,  2.],
           [ 1.,  3.]])

    >>> type(a)
    <class 'pycuda.gpuarray.GPUArray'>
    """
    return a.transpose()


@staticmethod
def __check_probability(p):
    """ Checks p is valid, i.e. a float value x ∈ [0.0, 1.0]. """
    if p is None or not isinstance(p, float) or not 0.0 <= p <= 1.0:
        error_msg = 'The term p should be an float x ∈ [0.0, 1.0]'
        raise ValueError(error_msg)
    else:
        return p


def overlap(span1, span2):
    """ Return a list `[start,end]` denoting the overlap of two spans.

      Example:

          >>> overlap([1,9], [5,13])
          [5, 9]
  """
    lo = max(span1[0], span2[0])
    hi = min(span1[1], span2[1])
    return [lo, max(lo, hi)]


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


@classmethod
def register_component(cls, component):
    """Register a Component."""
    try:
        cls.component_by_name(component.name)
        raise Exception('Component with name %s exists' % component.name)
    except IndexError:
        cls.components.append(component)


def _make_header():
    """
    Make vcf header for SNPs in miRs
    """


def write_bytes(data: (bytes or bytearray), bs: (bytes or bytearray),
    data_index: int):
    """将bs写入到data中的index位置"""
    data[data_index:data_index + len(bs)] = bs


def is_scoped_package(name):
    """
    Return True if name contains a namespace.

    For example::
    >>> is_scoped_package('@angular')
    True
    >>> is_scoped_package('some@angular')
    False
    >>> is_scoped_package('linq')
    False
    >>> is_scoped_package('%40angular')
    True
    """
    return name.startswith(('@', '%40'))


def YilmIndexVector(i, l, m):
    """
    Compute the index of an 1D array of spherical harmonic coefficients
    corresponding to i, l, and m.

    Usage
    -----
    index = YilmIndexVector (i, l, m)

    Returns
    -------
    index : integer
        Index of an 1D array of spherical harmonic coefficients corresponding
        to i, l, and m.

    Parameters
    ----------
    i : integer
        1 corresponds to the cosine coefficient cilm[0,:,:], and 2 corresponds
        to the sine coefficient cilm[1,:,:].
    l : integer
        The spherical harmonic degree.
    m : integer
        The angular order.

    Notes
    -----
    YilmIndexVector will calculate the index of a 1D vector of spherical
    harmonic coefficients corresponding to degree l, angular order m and i
    (1 = cosine, 2 = sine). The index is given by l**2+(i-1)*l+m.
    """
    return l ** 2 + (i - 1) * l + m


def normalise(vec):
    """
    Scales a vector so its magnitude is unity.

    :param vec: a vector.
    :type vec: Homogeneous
    :returns: a new vector object.
    :rtype: Homogeneous
    :requires: vec to be a vector.
    """
    m = vec.magnitude
    return vec / m


@classmethod
def get(klass, name):
    """
        Return a specific subclass by slug
        """
    for sub in klass.list():
        if sub.get_slug() == name:
            return sub
    raise ValueError('No {0} implementation with slug {1}'.format(klass, name))


def __call__():
    """Returns JSON compatible python data.
        """


def get_lambda_endpoints(full_schema):
    """
    returns a unique list of lambda endpoints from the Lex Schema
    :param full_schema:
    :return:
    """
    lambda_endpoints = set()
    for intent in full_schema['resource']['intents']:
        if 'fulfillmentActivity' in intent and 'codeHook' in intent[
            'fulfillmentActivity']:
            lambda_endpoints.add(intent['fulfillmentActivity']['codeHook'][
                'uri'])
        if 'dialogCodeHook' in intent:
            lambda_endpoints.add(intent['dialogCodeHook']['uri'])
    return lambda_endpoints


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

        :param UserCustomQuotaResult val:
        :rtype: CustomQuotaResult
        """
    return cls('success', val)


@staticmethod
def get_jenkins_plugin_name():
    """Gets the name of the Jenkins plugin associated with this PyJen plugin

        This static method is used by the PyJen plugin API to associate this
        class with a specific Jenkins plugin, as it is encoded in the config.xml

        :rtype: :class:`str`
        """
    return 'hudson.model.FreeStyleProject'


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

        :param SsoErrorType val:
        :rtype: EventType
        """
    return cls('sso_error', val)


@classmethod
def disable(cls):
    """Disable collecting and reporting metrics.
        """
    return cls.build_send_payload('disable', {}), None


def parse_no(txt):
    """parse a decimal unsigned integer from string,
       e.g. "12", number, e.g. 12, None on error"""
    fields = txt.strip().split()
    if len(fields) > 1:
        return None
    try:
        no = int(fields[0])
    except:
        return None
    if no < 0:
        return None
    return no


def page_assembly_testcase_handler(page_instructions, renderer, assembly):
    """
    Used to add the testcase yaml file to the page instructions if we are being
    instrumented (testing)
    """
    assembly.add_page_instructions(page_instructions,
        'chirp/testrunner/testcase.yaml')


def set_http_propagator_factory(factory):
    """Sets the propagator factory to be used globally"""
    global _PROGPAGATOR_FACTORY
    _PROGPAGATOR_FACTORY = factory


@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
    """Make a new Quad object from a sequence or iterable"""
    result = new(cls, iterable)
    if len(result) != 4:
        raise TypeError('Expected 4 arguments, got %d' % len(result))
    return result


def parse_script_args(args):
    """
	Separate the command line arguments into arguments for pip
	and arguments to Python.

	>>> parse_script_args(['foo', '--', 'bar'])
	(['foo'], ['bar'])

	>>> parse_script_args(['foo', 'bar'])
	(['foo', 'bar'], [])
	"""
    try:
        pivot = args.index('--')
    except ValueError:
        pivot = len(args)
    return args[:pivot], args[pivot + 1:]


def split_title(title, delim):
    """Return largest title piece."""
    largest_len = 0
    largest_piece = None
    piece_len = 0
    for piece in title.split(delim):
        piece_len = len(piece)
        if piece_len > largest_len:
            largest_len = piece_len
            largest_piece = piece
    return largest_piece or title


def format_arn(partition=None, service=None, region=None, account=None,
    resource=None, resource_type=None, resource_name=None, defaults_from=None):
    """Return an ARN composed from the specified components.

    Provide either resource or both resource_type and resource_name.

    defaults_from can be an existing ARN, which will be used to fill in any
    missing components.

    See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html
    for the format.
    """
    if resource is None and resource_type is not None:
        resource = f'{resource_type}/{resource_name}'
    if defaults_from is not None:
        try:
            _arn, _partition, _service, _region, _account, _resource = (
                defaults_from.split(':'))
        except (TypeError, ValueError):
            raise ValueError(f'Invalid ARN in defaults_from={defaults_from!r}')
        partition = partition if partition is not None else _partition
        service = service if service is not None else _service
        region = region if region is not None else _region
        account = account if account is not None else _account
        resource = resource if resource is not None else _resource
    return f'arn:{partition}:{service}:{region}:{account}:{resource}'


def screen_full_area(use_hide_panels: bool=False):
    """Toggle display selected area as fullscreen/maximized

    :param use_hide_panels: Hide Panels, Hide all the panels
    :type use_hide_panels: bool
    """
    pass


@staticmethod
def _expand_intervals_a_little(shapes):
    """
        Make the intervals a tiny bit larger.
        """
    return shapes.apply_map(lambda z: z + (z - z) / 64)


def _two_powers(num):
    """
    https://stackoverflow.com/a/51859187/1177288
    """
    while num > 0:
        rest = num & num - 1
        yield num - rest
        num = rest


def pad_with_object(sequence, new_length, obj=None):
    """
    Returns :samp:`sequence` :obj:`list` end-padded with :samp:`{obj}`
    elements so that the length of the returned list equals :samp:`{new_length}`.

    :type sequence: iterable
    :param sequence: Return *listified* sequence which has been end-padded.
    :type new_length: :obj:`int`
    :param new_length: The length of the returned list.
    :type obj: :obj:`object`
    :param obj: Object used as padding elements.
    :rtype: :obj:`list`
    :return: A :obj:`list` of length :samp:`{new_length}`.
    :raises ValueError: if :samp:`len({sequence}) > {new_length})`.

    Example::

       >>> pad_with_object([1, 2, 3], 5, obj=0)
       [1, 2, 3, 0, 0]
       >>> pad_with_object([1, 2, 3], 5, obj=None)
       [1, 2, 3, None, None]

    """
    if len(sequence) < new_length:
        sequence = list(sequence) + [obj] * (new_length - len(sequence))
    elif len(sequence) > new_length:
        raise ValueError('Got len(sequence)=%s which exceeds new_length=%s' %
            (len(sequence), new_length))
    return sequence


def getValue(token):
    """Return a value for a given identifier token

        LookupError is raised if there isn't a value in the source.
        """


def is_marubozu(body, top, bottom):
    """Se existir marubozu retorna True."""
    if abs(body) == 100:
        return True
    return False


def pvalue(rl, score, threshold):
    """ Returns all repeats in ``rl`` with a p-Value below a certain threshold.

    Returns all repeats in ``rl`` with a p-Value below a certain threshold.

    Args:
        rl (RepeatList): An instance of the RepeatList class.
        score (str): The type of score defines the pvalue that is used for filtering
        threshold (float): All repeats with a pvalue of type `score` above this threshold
            are filtered out.

    """
    threshold = float(threshold)
    res = []
    for i_repeat in rl.repeats:
        if i_repeat.pvalue(score) <= threshold:
            res.append(i_repeat)
    return res


def _initialization_display_message_prelude(db_name, working_directory,
    table_name, directory_name, data_file, alias):
    """ Display summary of input parameters before creating database

    :param db_name: (str)   Name of db
    :param working_directory: (str) Path to working directory
    :param table_name: (str)    Record that will be created
    :param directory_name: (str)    Directory with files to add
    :param data_file: (str)     File with metadata for storing in database
    :return:
    """
    print('INIT:\tCreate project database and initialize')
    print(' Project root directory:\t%s' % working_directory)
    print(' Name of database:\t\t%s.db' % db_name.strip('.db'))
    print(' Name of table:\t\t\t%s' % table_name)
    print(' Table aliases:\t\t\t%s' % alias, '\n')
    print('DATA:\tPopulate table')
    print(' Get metadata from\t\t%s' % data_file)
    print(' Copy fastx files from\t\t%s' % directory_name, '\n')


@staticmethod
def _from_db_object(quota, db_quota):
    """Converts a database entity to a formal object"""
    for field in quota.fields:
        if field == 'uuid':
            continue
        setattr(quota, field, db_quota[field])
    quota.obj_reset_changes()
    return quota


def show_instructions():
    """show command line instructions"""
    info = """
--------------------------
preprocess a single file
--------------------------

# write output to screen
> python preprocess.py [input csv file] [--old-format]

# write output to screen and file
> python preprocess.py [input csv file] [output file name] [--old-format]

OR

# test input and output files
> python preprocess.py test

"""
    print(info)


def merge_dicts(*dict_args):
    """
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result


def unquote_header_value(value, is_filename=False):
    """Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    :rtype: str
    """
    if value and value[0] == value[-1] == '"':
        value = value[1:-1]
        if not is_filename or value[:2] != '\\\\':
            return value.replace('\\\\', '\\').replace('\\"', '"')
    return value


@classmethod
def get(cls, name):
    """We create a custom get() class method
        to support then get() interface"""
    return getattr(cls, name)


def is_joined_str(node):
    """Returns whether node is a JoinedStr node, used to represent f-strings."""
    return node.__class__.__name__ == 'JoinedStr'


def remove_duplicates(text, separator):
    """ Removes possible duplicates from a separator-separated list. """
    entries = text.split(separator)
    cleaned_entries = list(set(entries))
    text = separator.join(cleaned_entries)
    return text


def find_child_node(_node, _nodename):
    """Find all child nodes of an XML tree"""
    for node in _node.childNodes:
        if node.nodeName.lower() == _nodename.lower():
            return node
    return None


def get_args():
    """
    Get and parse arguments.

    """
    import argparse
    parser = argparse.ArgumentParser(description=
        'Mavlink to SBP JSON converter')
    parser.add_argument('dataflashfile', help='the dataflashfile to convert.')
    parser.add_argument('-t', '--timestep', default=[10], nargs=1, help=
        'number of seconds gap at which to split a file')
    parser.add_argument('-p', '--prefix', default=[None], nargs=1, help=
        'file prefix')
    parser.add_argument('-v', '--verbose', action='store_true', help=
        'print extra debugging information.')
    args = parser.parse_args()
    return args


def get_first_name(user):
    """Given a canvas api user object representing a student
    returns the first name
    """
    return user.sortable_name.split(',')[1]


def _cv_delta(x, eps=1.0):
    """Returns the result of a regularised dirac function of the
    input value(s).
    """
    return eps / (eps ** 2 + x ** 2)


def preset_order(apps, schema_editor):
    """Set initial ordering of category list plugin categories."""
    SelectedCategory = apps.get_model('aldryn_faq', 'SelectedCategory')
    order = 0
    for obj in SelectedCategory.objects.all():
        order += 1
        obj.position = order
        obj.save()


def check_compatibility(selected_usb_size: int, iso_rec_size: str) ->bool:
    """
    Function to test whether or not the usb is large enough for selected ISO
    :param:string: selected_usb_size pointer to selected usb device size
    :param:int: iso_rec_size recommended size selected ISO needs
    :return: true if size is large enough
    """
    if selected_usb_size >= int(iso_rec_size.split()[0]) * 1000000000:
        return True
    else:
        return False


def select_all():
    """Select all text

    """
    pass