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

        :param SharedContentClaimInvitationDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_claim_invitation_details', val)


def convert_persistance_prof(vs, name, tenant_ref):
    """
    This function defines that it convert the persistent profile and
    return that profile
    :param vs: object of lb vs or pool
    :param name: name of application persteance profile
    :param tenant_ref: reference of tenant
    :return: application persistent profile
    """
    profile = None
    persistenceType = vs.get('persistenceType', '')
    timeout = vs.get('timeout', 2)
    if persistenceType == 'COOKIEINSERT':
        profile = {'http_cookie_persistence_profile': {'always_send_cookie':
            False, 'timeout': timeout}, 'persistence_type':
            'PERSISTENCE_TYPE_HTTP_COOKIE', 'server_hm_down_recovery':
            'HM_DOWN_PICK_NEW_SERVER', 'name': name}
    elif persistenceType == 'SOURCEIP':
        timeout = int(timeout) / 60
        if timeout < 1:
            timeout = 1
        profile = {'server_hm_down_recovery': 'HM_DOWN_PICK_NEW_SERVER',
            'persistence_type': 'PERSISTENCE_TYPE_CLIENT_IP_ADDRESS',
            'ip_persistence_profile': {'ip_persistent_timeout': timeout},
            'name': name}
    elif persistenceType == 'SSLSESSION':
        profile = {'server_hm_down_recovery': 'HM_DOWN_PICK_NEW_SERVER',
            'persistence_type': 'PERSISTENCE_TYPE_TLS', 'name': name}
    profile['tenant_ref'] = tenant_ref
    return profile


def _peirce_skill_score(table):
    """This score is borrowed with modification from the hagelslag repository
    MulticlassContingencyTable class. It is used here with permission of
    David John Gagne II <djgagne@ou.edu>

    Multiclass Peirce Skill Score (also Hanssen and Kuipers score, True Skill Score)
    """
    n = float(table.sum())
    nf = table.sum(axis=1)
    no = table.sum(axis=0)
    correct = float(table.trace())
    return (correct / n - (nf * no).sum() / n ** 2) / (1 - (no * no).sum() /
        n ** 2)


def squeeze(l):
    """ Squeeze Sequences with 1 item into a scalar

    Parameters
    ----------
    l : Sequence
        List, tuple, etc

    Returns
    -------
    object
        Either original object if ``len(l) != 1`` else ``l[0]``
    """
    return l[0] if len(l) == 1 else l


@classmethod
def from_dead(cls, char, **kwargs):
    """Creates a dead key.

        :param char: The dead key. This should be the unicode character
            representing the stand alone character, such as ``'~'`` for
            *COMBINING TILDE*.

        :return: a key code
        """
    return cls(char=char, is_dead=True, **kwargs)


def count_headings(elements):
    """put a level to each heading.

    returns a dict mapping heading levels to heading chars.
    Here is an example:

    >>> import pprint
    >>> lst=[
    ...      ('=', 'This is a heading'),
    ...      '',
    ...      'a text follows',
    ...      'here',
    ...      '',
    ...      ('+', 'here is another heading'),
    ...      '',
    ...      'with some text'
    ...     ]
    >>> pprint.pprint(count_headings(lst))
    {'+': 2, '=': 1}
    """
    heading_chars = {}
    last_level = 1
    for l in elements:
        if isinstance(l, tuple):
            ch = l[0]
            level = heading_chars.get(ch)
            if level is None:
                heading_chars[ch] = last_level
                level = last_level
                last_level += 1
    return heading_chars


def psi_Ca_HSO4_SO4_HMW84(T, P):
    """c-a-a': calcium bisulfate sulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def length_vector_sqrd_xy(vector):
    """Compute the squared length of a vector, assuming it lies in the XY plane.

    Parameters
    ----------
    vector : list
        XY(Z) components of the vector.

    Returns
    -------
    float
        The squared length.

    Examples
    --------
    >>> length_vector_sqrd_xy([1.0, 1.0])
    2.0

    >>> length_vector_sqrd_xy([1.0, 1.0, 0.0])
    2.0

    >>> length_vector_sqrd_xy([1.0, 1.0, 1.0])
    2.0

    """
    return vector[0] ** 2 + vector[1] ** 2


def GetLatestMeasurementScalar(*args, **kwargs):
    """ Stub Anduin function."""
    print('GetLatestMeasurementScalar', args, kwargs)


@staticmethod
def fetch_identifiers(connection_pool, server_to_exclude):
    """ Collects server identifiers
        :param connection_pool: The connection pool to iterate through
        :param server_to_exclude: Server identifier to exclude
        """
    for identifier in connection_pool.get_identifiers():
        server_address = connection_pool.get_connection(identifier)[
            'server_address']
        if server_address != server_to_exclude:
            yield server_address


def convolve(y, Ck):
    """Convolve y with Ck"""


def assert_interrupt_signal(library, session, mode, status_id):
    """Asserts the specified interrupt or signal.

    Corresponds to viAssertIntrSignal function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param mode: How to assert the interrupt. (Constants.ASSERT*)
    :param status_id: This is the status value to be presented during an interrupt acknowledge cycle.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viAssertIntrSignal(session, mode, status_id)


def saveSequenceEvents(events, notableEvents=None):
    """
    Convert a list of SequenceEvent objects to raw sequence event data.
    This is the inverse of readSequenceEvents().

    A second list will also be returned that contains the offsets in the
    output data of the elements from notableEvents.
    """
    if notableEvents is None:
        notableEvents = []
    events2Offsets = {}
    off = 0
    for e in events:
        events2Offsets[e] = off
        off += e.dataLength
    data = bytearray(off)
    for event, offset in events2Offsets.items():
        eData = event.save(events2Offsets)
        data[offset:offset + len(eData)] = eData
    notableOffsets = [events2Offsets[e] for e in notableEvents]
    return data, notableOffsets


def decode_surb(params, header, enc_dest):
    """ Decode the destination address of the SURB. """
    _, _, _, xid = header
    dest = params.xor_rho(xid, enc_dest)
    return dest


def format_system(A, Y):
    """Extract data from A/Y matrices."""
    assert Y.ndim > 0
    m, n = A.shape
    matrix_in = Y.ndim > 1
    d = Y.shape[1] if matrix_in else 1
    Y = Y if matrix_in else Y[:, (None)]
    return Y, m, n, d, matrix_in


def walk_exit_step(walk):
    """
    Determines the step at which a walk exits the upper quarterplane.
    """
    x, y = 0, 0
    i = 0
    for step in walk:
        x += step.x
        y += step.y
        i += 1
        if x < 0 or y < 0:
            return i
    return i


def get_client_ip(request):
    """
    Fetches the IP address of a client from Request and
    return in proper format.
    Source: https://stackoverflow.com/a/4581997
    Parameters
    ----------
    request: django.http.HttpRequest

    Returns
    -------
    ip: str
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def convert_list_props_to_comma_separated(data, props=None):
    """Convert the list-type properties to comma-separated strings

    :param data: the input dict object.
    :param props: the properties whose values will be converted.
        Default to None to convert all list-type properties of the input.
    :returns: the result dict instance.
    """
    result = dict(data)
    if props is None:
        props = data.keys()
    for prop in props:
        val = data.get(prop, None)
        if isinstance(val, list):
            result[prop] = ', '.join(map(str, val))
    return result


@staticmethod
def _node_key(layer, node_index):
    """Converts a layer and its index to a unique (immutable type) name.

        This function is used internally with `self._network_nodes`.

        # Arguments
            layer: The layer.
            node_index: The layer's position (e.g. via enumerate) in a list of
                nodes.

        # Returns
            The unique name.
        """
    return layer.name + '_ib-' + str(node_index)


@staticmethod
def equation(parameters: dict, rounding: int=8) ->str:
    """
        Create a string representation of the parameters
        :param parameters: the parameters describing the curve
        :param rounding: the number of digits to round to
        :return: a string representation
        """
    return ''


def UdJH_to_F0F2F4F6(Ud, JH):
    """
    Given :math:`U_d` and :math:`J_H`, return :math:`F_0`, :math:`F_2`, :math:`F_4` and :math:`F_6`,
    for :math:`f`-orbitals.

    Parameters
    ----------
    Ud: float
        Coulomb interaction :math:`U_d`.
    JH: float
        Hund's coupling :math:`J_H`.

    Returns
    -------
    F0: float
        Slater integral :math:`F_0`.
    F2: float
        Slater integral :math:`F_2`.
    F4: float
        Slater integral :math:`F_4`.
    F6: float
        Slater integral :math:`F_6`.

    """
    F0 = Ud
    F2 = 6435 / (286.0 + 195 * 451 / 675.0 + 250 * 1001 / 2025.0) * JH
    F4 = 451 / 675.0 * F2
    F6 = 1001 / 2025.0 * F2
    return F0, F2, F4, F6


def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None):
    """Generate common filters for any list request.

    :param marker: entity ID from which to start returning entities.
    :param limit: maximum number of entities to return.
    :param sort_key: field to use for sorting.
    :param sort_dir: direction of sorting: 'asc' or 'desc'.
    :returns: list of string filters.
    """
    filters = []
    if isinstance(limit, int):
        filters.append('filters.field=limit')
        filters.append('filters.value=%d' % limit)
    if marker is not None:
        filters.append('filters.field=marker')
        filters.append('filters.value=%s' % marker)
    if sort_key is not None:
        filters.append('filters.field=sort_key')
        filters.append('filters.value=%s' % sort_key)
    if sort_dir is not None:
        filters.append('filters.field=sort_dir')
        filters.append('filters.value=%s' % sort_dir)
    return filters


@classmethod
def modify_url_for_impersonation(cls, url, impersonate_user, username):
    """
        Modify the SQL Alchemy URL object with the user to impersonate if applicable.
        :param url: SQLAlchemy URL object
        :param impersonate_user: Bool indicating if impersonation is enabled
        :param username: Effective username
        """
    pass


@staticmethod
def p_frame_optional_list_optional(p):
    """frame_optional_list_optional : empty
                                        | frame_optional_list"""
    p[0] = tuple() if p[1] is None else p[1]


@classmethod
def parse_list(cls, ctxt, description, addr):
    """
        Parse a list of step descriptions.  "Eager" steps will also be
        evaluated, and the results of those calls will be presumed to
        be a list of steps to include in the list.  (The "eager"
        attribute of steps in the returned list will not be checked;
        the caller must implement the "eager" behavior, possibly by
        recursively calling the ``parse_list()`` method.)

        :param ctxt: An application-specific execution context.  Will
                     be passed to "eager" steps.
        :param description: A description of the list of steps.
        :type description: ``list`` of ``dict`` or ``str``.
        :param addr: The address of the list of steps.  This is to be
                     used when raising errors to help users determine
                     which step reported the error.
        :type addr: ``stepmaker.StepAddress``

        :returns: A list of parsed steps.
        :rtype: ``list`` of ``Step``
        """
    steps = []
    for idx, step_desc in enumerate(description):
        step = cls.parse(step_desc, addr.idx(idx))
        if step.eager:
            steps.extend(step(ctxt))
        else:
            steps.append(step)
    return steps


def compute_chunks(seq, num):
    """
    Splits up a sequence _seq_ into _num_ chunks of similar size.
    If len(seq) < num, (num-len(seq)) empty chunks are returned so that len(out) == num

    Parameters
    ----------
    seq : list of something [N_ele]
        List containing data or indices, which is divided into chunks
    num : int
        Number of chunks to generate

    Returns
    -------
    out : list of num sublists
        num sub-lists of seq with each of a similar number of elements (or empty).
    """
    assert len(seq) > 0
    assert num > 0
    avg = len(seq) / float(num)
    n_empty = 0
    if avg < 1:
        avg = 1
        n_empty = num - len(seq)
    out = []
    last = 0.0
    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg
    out += [[]] * n_empty
    return out


def sign(x, value=1):
    """Mathematical signum function.

    :param x:       Object of investigation
    :param value:   The size of the signum (defaults to 1)

    :returns:       Plus or minus value
    """
    return -value if x < 0 else value


def print_results(results):
    """Print `results` (the results of validation) to stdout.

    Args:
        results: A list of FileValidationResults or ObjectValidationResults
                 instances.

    """
    if not isinstance(results, list):
        results = [results]
    for r in results:
        try:
            r.log()
        except AttributeError:
            raise ValueError(
                'Argument to print_results() must be a list of FileValidationResults or ObjectValidationResults.'
                )


def PNT2Tidal_Tv12(XA):
    """ TaylorT2 1PN Quadrupolar Tidal Coefficient, v^12 Timing Term.
   XA = mass fraction of object """
    XATo2nd = XA * XA
    XATo3rd = XATo2nd * XA
    return 3179 / 4 - 919 * XA / 4 - 1143 * XATo2nd / 2 + 65 * XATo3rd


def pure(func):
    """
    Marks the function as pure (not having any side effects, except maybe argument mutation).
    """
    func.__peval_pure__ = True
    return func


@classmethod
def import_all_from_misfit(cls, misfit, uid):
    """
        This is used to import all data from misfit when a user is initially
        linked. By default it just runs import_from_misfit, but a model with
        more complex needs can override this
        """
    cls.import_from_misfit(misfit, uid)


def get_assertion_message(assertion_details):
    """
    Get a detailed message about the failing matcher.
    """
    return assertion_details


def parabola(x, a, b, c):
    """parabola polynomial function

    this function is used to fit the data to get good guesses for
    the equation of state fits

    a 4th order polynomial fit to get good guesses for
    was not a good idea because for noisy data the fit is too wiggly
    2nd order seems to be sufficient, and guarantees a single minimum"""
    return a + b * x + c * x ** 2


@classmethod
def _digest(cls, *signers):
    """Produce a unique, deterministic signature out of one or more
        ``signers`` objects."""
    items = []
    for i in signers:
        try:
            items.extend(list(i._signature_items()))
        except AttributeError:
            items.append(str(i))
    return cls._sign(items)


@classmethod
def grant_usage_privileges(cls, cur, schema_name, roles):
    """
        Sets search path
        """
    cur.execute(
        'GRANT USAGE ON SCHEMA {0} TO {1};GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA {0} TO {1};'
        .format(schema_name, roles))


def merge_metabolites(list_of_metabolites, base_metabolite):
    """ Merge duplicated metabolites

    Parameters
    ----------
    list_of_metabolites: list
    base_metabolite: GEMEditor.model.classes.cobra.Metabolite

    Returns
    -------
    list
    """
    merged = list()
    for metabolite in list_of_metabolites:
        if metabolite is not base_metabolite:
            for reaction in metabolite.reactions:
                stoichiometry = reaction.metabolites
                coefficient = stoichiometry.pop(metabolite)
                if base_metabolite in stoichiometry:
                    stoichiometry[base_metabolite] += coefficient
                else:
                    stoichiometry[base_metabolite] = coefficient
                reaction.subtract_metabolites(reaction.metabolites, combine
                    =True, reversibly=False)
                reaction.add_metabolites(stoichiometry)
            for evidence in metabolite.evidences.copy():
                evidence.substitute_item(metabolite, base_metabolite)
            base_metabolite.annotation.update(metabolite.annotation)
            merged.append(metabolite)
    if merged and merged[0].model:
        merged[0].model.gem_remove_metabolites(merged)
    return merged


@staticmethod
def get_connection_type():
    """
        This is needed so the build system knows what
        connection type this connection is considered.
        return::str The socket type of this connection.
        """
    return 'subscriber'


def standard_pcr(primer_df, outfile):
    """
    Creates standard PCR input file (one primer with one other) to run in silico PCR.
    Args:
        primer_df (pd.DataFrame): dataframe with primer info
    Returns:
        nothing: writes a file output
    """
    standard = open(outfile, 'w')
    for seqid, primer_left, primer_right in zip(primer_df['Sequence ID'],
        primer_df['Primer Left Seq'], primer_df['Primer Right Seq']):
        standard.write(str(seqid) + '\t' + str(primer_left) + '\t' + str(
            primer_right) + '\n')
    standard.close()


def rewrite_kwargs(conn_type, kwargs, module_name=None):
    """
    Manipulate connection keywords.

    Modifieds keywords based on connection type.

    There is an assumption here that the client has
    already been created and that these keywords are being
    passed into methods for interacting with various services.

    Current modifications:
    - if conn_type is not cloud and module is 'compute',
      then rewrite project as name.
    - if conn_type is cloud and module is 'storage',
      then remove 'project' from dict.

    :param conn_type: E.g. 'cloud' or 'general'
    :type conn_type: ``str``

    :param kwargs: Dictionary of keywords sent in by user.
    :type kwargs: ``dict``

    :param module_name: Name of specific module that will be loaded.
                        Default is None.
    :type conn_type: ``str`` or None

    :returns kwargs with client and module specific changes
    :rtype: ``dict``
    """
    if conn_type != 'cloud' and module_name != 'compute':
        if 'project' in kwargs:
            kwargs['name'] = 'projects/%s' % kwargs.pop('project')
    if conn_type == 'cloud' and module_name == 'storage':
        if 'project' in kwargs:
            del kwargs['project']
    return kwargs


def entity_to_props(entity):
    """Converts a Datastore Entity into props

    Converts a ndb.Model Entity into its props form. The props form
    contains all of the properties within the entity as a dict. The props
    form also contains a 'kind' that points to the string form
    of the matching class. The `props` form also contains a 'key'
    that contains the entity.key() object.
    """
    d = entity.to_dict()
    if entity.key:
        d['key'] = entity.key
    d['kind'] = entity._get_kind()
    return d


def get_arg(instr, var):
    """Returns the bracketed argument that immediately follows the first
        occurance of the 'var' string, along with the entire expression
        for easy replace

        example:
        >>> instr = "some text $var['user'] more text"
        >>> get_arg(instr,'$var')
        ("$var['user']", 'user')
    """
    s = len(var) + 1
    i = instr.find(var + '[')
    if i != -1:
        o = instr.find(']', i + s)
        if o != -1:
            arg = instr[i + s:o].strip('"\'')
            exp = instr[i:o + 1]
            return exp, arg
        else:
            return '', ''
    else:
        return '', ''


def _write_conne(clabels, isot, d1, d2, areas, angles):
    """Return a generator that iterates over the records of block CONNE."""
    fmt = '{:>10.10}{:>5}{:>5}{:>5}{:>5g}{:10.4e}{:10.4e}{:10.4e}{:10.3e}\n'
    iterables = zip(clabels, isot, d1, d2, areas, angles)
    for label, isot, d1, d2, area, angle in iterables:
        record = fmt.format(label, '', '', '', isot, d1, d2, area, angle)
        yield record


def get_process_id(process):
    """Return id attribute of the object if it is process, otherwise return given value."""
    return process.id if type(process).__name__ == 'Process' else process


def best_charset(text):
    """
    Find the most human-readable and/or conventional encoding for unicode text.

    Prefers `us-ascii` or `iso-8859-1` and falls back to `utf-8`.
    """
    if isinstance(text, bytes):
        text = text.decode('ascii')
    for charset in ('us-ascii', 'iso-8859-1', 'utf-8'):
        try:
            encoded = text.encode(charset)
        except UnicodeError:
            pass
        else:
            return charset, encoded


def _tint_code(color, place):
    """Get a color's tint code.

  Parameters
  ----------
  color : string
    Color to be coded
    If place is "font", it should be one of the following colors:
      ====================================================================
      "black", "red", "green", "yellow", "blue", "purple", "cyan", "white"
      ====================================================================

    If place is "bg", it should be one of the following colors:
      ====================================================================
      "black", "red", "green", "yellow", "blue", "purple", "cyan", "white"
      ====================================================================

  place : string
    Color's place, should be "font" or "bg"

  Returns
  -------
  tint_code: integer
    Color's tint code.

  """
    code_dict = {'font': {'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
        'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37}, 'bg': {'black':
        40, 'red': 41, 'green': 42, 'yellow': 43, 'blue': 44, 'purple': 45,
        'cyan': 46, 'white': 47}}
    if place not in code_dict:
        raise ValueError('Invalid place %s' % place)
    if color not in code_dict[place]:
        raise ValueError('Invalid color %s for place %s' % (color, place))
    return code_dict[place][color]


def create_route_short_name(relation):
    """Create a meaningful route short name."""
    return relation.tags.get('ref') or ''


def bytes2human(n, format='%(value).1f%(symbol)s'):
    """Used by various scripts. See:
    http://goo.gl/zeJZl

    >>> bytes2human(10000)
    '9.8K'
    >>> bytes2human(100001221)
    '95.4M'
    """
    symbols = 'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
    prefix = {}
    for i, s in enumerate(symbols[1:]):
        prefix[s] = 1 << (i + 1) * 10
    for symbol in reversed(symbols[1:]):
        if n >= prefix[symbol]:
            value = float(n) / prefix[symbol]
            return format % locals()
    return format % dict(symbol=symbols[0], value=n)


def set_last_status_length(length: int) ->None:
    """The length of the prefix to be cleared when printing something"""
    global last_status_length
    last_status_length = length


@staticmethod
def _generate_default_config() ->dict:
    """ This is the default config for the log. Generate this if no config exists. """
    data = {'file_logger': {'active': True, 'path': './logs/output.log'},
        'rotation': {'interval_unit': 'd', 'interval_value': 1,
        'backup_count': 30}, 'socket_logger': {'active': False, 'host':
        '127.0.0.1', 'port': 5000}, 'console_log_level': 'INFO',
        'file_log_level': 'INFO', 'human_mode': False}
    return data


def rotate_left(num: int, num_size: int, shift_bits: int) ->int:
    """
    Rotate a number num of num_size bits by shift_bits bits. See
    https://en.wikipedia.org/wiki/Bitwise_operation#Rotate_no_carry for more information.

    :param num: the number to rotate
    :param num_size: the size of the number in bits
    :param shift_bits: the number of bits the number is rotated by
    :return: the rotated number
    """
    mask = 2 ** shift_bits - 1 << num_size - shift_bits
    bits = (num & mask) >> num_size - shift_bits
    num = num << shift_bits & 2 ** num_size - 1
    num |= bits
    return num


def _fingerprint(row):
    """Generate a string-based fingerprint to characterize row diversity."""
    return ''.join(map(lambda x: str(type(x)), row))


def SI(val):
    """SecondarySourceID"""
    return val


def available_name(domain, template):
    """Return the next available variable name (from template) that is not
    already taken in domain"""
    for i in range(1000):
        name = '{}{}'.format(template, ' ({})'.format(i) if i else '')
        if name not in domain:
            return name


@classmethod
def random(cls):
    """ initializes stochastic process with some randomly generated parameters

        :rtype: StochasticProcess

        """
    return cls(None)


def prettify_registration_id(id_):
    """
    Convert a application ID to human-readable string.

    :param id_: Identification of a application.

    :return: A string version of the application ID decomposed in groups
        of 3 digits separated with a dash character.
    """
    segments = []
    while id_ > 0:
        segments.append(str(id_ % 1000).zfill(3))
        id_ //= 1000
    return '-'.join(reversed(segments))


def attributive(adjective):
    """ For a predicative adjective, returns the attributive form.
    """
    raise NotImplementedError


def add_reference_frame_arg(parser):
    """
    Add a reference frame argument.

    Reference frame is the frame to compute the parameter against.

    Depending on the client logic the reference frame might have different
    meanings.

    Is defined by ``-r`` and ``--ref-frame``.

    Defaults to ``0``.

    Parameters
    ----------
    parser : `argparse.ArgumentParser <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser>`_
        The argument parser to which add the refence-frame argument.
    """
    parser.add_argument('-r', '--ref-frame', help=
        'The frame in the trajectory that serves as reference to compute against.Defaults to 0.'
        , default=0, type=int)


def _get_front_ids_one_at_a_time(onset_fronts):
    """
    Yields one onset front ID at a time until they are gone. All the onset fronts from a
    frequency channel are yielded, then all of the next channel's, etc., though one at a time.
    """
    yielded_so_far = set()
    for row in onset_fronts:
        for id in row:
            if id != 0 and id not in yielded_so_far:
                yield id
                yielded_so_far.add(id)


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 json_response(request):
    """Determine if the request's response should be JSON."""
    if request.query.get('format') == 'json':
        return True
    else:
        return request.content_type == 'application/json'


def _skip_nonwhitespace(data, pos):
    """Return first position not before pos which contains a non-whitespace character."""
    for i, x in enumerate(data[pos:]):
        if x.isspace():
            return pos + i
    return len(data)


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

        :param ShowcaseChangeExternalSharingPolicyType val:
        :rtype: EventType
        """
    return cls('showcase_change_external_sharing_policy', val)


def format_sse(data: str, event=None) ->str:
    """

    >>> format_sse(data=json.dumps({'abc': 123}), event='Jackson 5')
    'event: Jackson 5\\ndata: {"abc": 123}\\n\\n'

    """
    msg = f'data: {data}\n\n'
    if event is not None:
        msg = f'event: {event}\n{msg}'
    return msg


def update_complited(status: bool):
    """
    上链完成后调用，更新数据库的状态
    :param status: 需要更新的状态值
    :return:
    """
    pass


def convert2json_type(obj: set) ->list:
    """Convert sets to lists for JSON serialization."""
    if isinstance(obj, set):
        return list(obj)
    else:
        raise TypeError(f'Object of type {type(obj)} is not JSON serializable.'
            )


def broadcastable_to_str(b):
    """Return string representation of broadcastable."""
    named_broadcastable = {(): 'scalar', (False,): 'vector', (False, True):
        'col', (True, False): 'row', (False, False): 'matrix'}
    if b in named_broadcastable:
        bcast = named_broadcastable[b]
    else:
        bcast = ''
    return bcast


def httpDate1123(dt):
    """Return a string representation of a date according to RFC 1123
    (HTTP/1.1).

    The supplied date must be in UTC.
    import datetime
    httpDate1123(datetime.datetime.utcnow())
    'Wed, 30 Sep 2015 14:29:18 GMT'
    """
    weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()]
    month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
        'Oct', 'Nov', 'Dec'][dt.month - 1]
    return '%s, %02d %s %04d %02d:%02d:%02d GMT' % (weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second)


def check(hub, rlist):
    """
    Check if any of the required list passes. If a single check passes then
    all is well, only return the errors is ALL FAIL
    """
    errors = []
    good = False
    for rdat in rlist:
        err = rdat.get('errors', [])
        if not err:
            good = True
        errors.extend(rdat.get('errors', []))
    if good:
        return []
    return errors


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

        :param SfTeamJoinType val:
        :rtype: EventType
        """
    return cls('sf_team_join', val)


def item():
    """Return the item at the current position
        """


@classmethod
def unrank_lex(cls, size, rank):
    """
        Lexicographic permutation unranking.

        Examples
        ========

        >>> from sympy.combinatorics.permutations import Permutation
        >>> Permutation.print_cyclic = False
        >>> a = Permutation.unrank_lex(5, 10)
        >>> a.rank()
        10
        >>> a
        Permutation([0, 2, 4, 1, 3])

        See Also
        ========

        rank, next_lex
        """
    perm_array = [0] * size
    psize = 1
    for i in range(size):
        new_psize = psize * (i + 1)
        d = rank % new_psize // psize
        rank -= d * psize
        perm_array[size - i - 1] = d
        for j in range(size - i, size):
            if perm_array[j] > d - 1:
                perm_array[j] += 1
        psize = new_psize
    return cls._af_new(perm_array)


@classmethod
def label_from_site(cls, site):
    """
        Get the label used in the codebase from the site object passed in.

        The possible site names are limited by SITELABELS. So, if we have the
        value of the site name, we can retrieve the associated choices label. By
        default, the label of a choice is the name of the attribute (nudge and
        eindhoven in this case).
        """
    try:
        return cls.values[site.name]
    except KeyError:
        return cls.values[site.domain]


def reset():
    """Empty stack and set to identity.

    """
    pass


def run_resample(resample, nexus_obj, log):
    """
    Resamples the trees in a nexus

    :param resample: Resample every `resample` trees
    :type resample: Integer

    :param nexus_obj: A `NexusReader` instance
    :type nexus_obj: NexusReader

    :return: A NexusReader instance with the given trees removed.
    """
    new = []
    log.info('Resampling ever %d trees' % resample)
    ignore_count = 0
    for index, tree in enumerate(nexus_obj.trees, 1):
        if index % resample == 0:
            new.append(tree)
        else:
            ignore_count += 1
    log.info('Ignored %d trees' % ignore_count)
    nexus_obj.trees.trees = new
    return nexus_obj


def step_filler(x, y, **kwargs):
    """Wrapper for a specific fill_between plot.

	Parameters
	----------
	x : array-like
		The x-axis values.
	y : array-like
		The y-axis values.
	Other arguments : **kwargs
		Optional kwargs supported by fill_between. Note that it will conflict if 'step' is given.
	Returns
	-------
	val : Recasted value
	"""
    from numpy import empty
    from matplotlib.pyplot import fill_between
    temp_y = empty(len(y) + 1)
    temp_y[1:] = y
    temp_y[0] = y[0]
    fill_between(x, temp_y, step='pre', **kwargs)
    return None


def create_transfer_params(api):
    """Takes a parameter from the authentication object.

    Args:
        api: Objects that have been authenticated.

    Returns:
        dict

    """
    params = {'config_bid': api.user_info['config_bid'], 'input_bid': api.
        user_info['input_bid'], 'output_bid': api.user_info['output_bid'],
        'domain': api.user_info['domain'], 'platform': api.user_info[
        'platform'], 'local_os': api.user_info['local_os'], 'user_id': api.
        user_info['user_id']}
    return params


def is_intersection_line_line_xy(l1, l2, tol=1e-06):
    """Verifies if two lines intersect on the XY-plane.

    Parameters
    ----------
    l1 : tuple
        A sequence of XYZ coordinates of two 3D points representing two points on the line.
    l2 : tuple
        A sequence of XYZ coordinates of two 3D points representing two points on the line.
    tol : float, optional
        A tolerance for intersection verification. Default is ``1e-6``.

    Returns
    --------
    bool
        ``True``if the lines intersect in one point
        ``False`` if the lines are skew, parallel or lie on top of each other.
    """
    raise NotImplementedError


def _get_audio_bitrate(rep, index: int=None):
    """
    @TODO: add documentation
    """
    if rep.bitrate.audio_ is not None and rep.bitrate.audio_ != 0:
        opt = 'b:a' if index is None else 'b:a:' + str(index)
        return {opt: rep.bitrate.audio}
    return {}


def sizeof_fmt(num):
    """Little helper to get size in human readable form.

    Size is rounded to a closest integer value (for simplicity).

    >>> sizeof_fmt(100)
    '100 B'
    >>> sizeof_fmt(1024)
    '1 KiB'
    >>> sizeof_fmt(1024*1024 + 100)
    '1 MiB'
    """
    for unit in ['B', 'KiB', 'MiB']:
        if abs(num) < 1024.0:
            return '%.0f %s' % (num, unit)
        num /= 1024.0
    return '%.0f %s' % (num, 'GiB')


def p_expression_group(p):
    """expression : LPAREN expression RPAREN"""
    p[0] = p[2]


def parser_text_layout(layout):
    """
    从LTTextBoxHorizontal中解析出文本.
    参数列表
    ----------
    layout : pdfminer.layout.LTTextBoxHorizontal

    Returns
    -------
    texts : str list
        多行文本数组.
    """
    texts = []
    text = layout.get_text()
    for _text in text.split('\n'):
        if len(_text) > 0:
            texts.append(_text.strip().replace(' ', ''))
    return texts


@staticmethod
def rel_output(output_id, percent):
    """Generate a command to change the value of an output-port.

        :param    int    output_id:    Output id 0..3
        :param    int    percent:      Relative percentage -100..100
        :return:    The PCK command (without address header) as text
        :rtype:    str
        """
    if output_id < 0 or output_id > 3:
        raise ValueError('Invalid output_id.')
    percent_round = round(percent * 2)
    if percent_round % 2 == 0:
        pck = 'A{:d}{:s}{:03d}'.format(output_id + 1, 'AD' if percent >= 0 else
            'SB', abs(percent_round // 2))
    else:
        pck = 'O{:d}{:s}{:03d}'.format(output_id + 1, 'AD' if percent >= 0 else
            'SB', abs(percent_round))
        return pck


def compute_DL_da_i(coeff_basis_sum, bases, time_index, i):
    """
    | Ref. Paper [LUDW2011]_ eq. [80]
    | Compute derivative of the attitude deviation wrt attitude params.
      See :meth:`compute_coeff_basis_sum`

    :param coeff_basis_sum: the sum :math:`\\sum_{n=L-M+1}^{L} a_n B_n(t_L)`
    :param bases: Bspline basis, B_n(t_L) in the equation above.
    :param time_index: [int] index that will get us to return B_n(t_L).
     Since we stored only B_n for all the observed times t_L, it is possible to
     access them only with the index
    :param i: number of the base that we want (**n in the equations above**)
    """
    dDL_da_i = -2 * coeff_basis_sum * bases[i, time_index]
    return dDL_da_i.reshape(4, 1)


def _make_class_name(name):
    """ Make a ufunc model class name from the name of the ufunc. """
    return name[0].upper() + name[1:] + 'Ufunc'


def convert2boolean(arg):
    """
    convert2boolean is used for environmental variables
    that must be returned as boolean
    """
    if not isinstance(arg, bool):
        return arg.lower() in ('yes', 'true', 't', '1', 'y')
    return arg


@classmethod
def _load_pkcs1_der(cls, keyfile):
    """Loads a key in PKCS#1 PEM format, implement in a subclass.

        :param keyfile: contents of a DER-encoded file that contains
            the public key.
        :type keyfile: bytes

        :return: the loaded key
        :rtype: AbstractKey
        """


def reset_default_theme():
    """Reset to the default theme colors

    """
    pass


def __iter_input_and_widget__():
    """Return an iterator of flag/widget pairs

        The flags indicate whether the corresponding widgets are used
        for input.  This is necessary because there is currently no
        way to introspect a widget to determine whether it is being
        used for input.
        """


@classmethod
def from_wfs_element(cls, feature, namespace):
    """Build `GrondwaterMonster` instance from a WFS feature element.

        Parameters
        ----------
        feature : etree.Element
            XML element representing a single record of the WFS layer.
        namespace : str
            Namespace associated with this WFS featuretype.

        Returns
        -------
        gwmonster : GrondwaterMonster
            An instance of this class populated with the data from the WFS
            element.

        """
    gwmonster = cls(feature.findtext('./{{{}}}grondwatermonsterfiche'.
        format(namespace)))
    for field in cls.get_fields(source=('wfs',)).values():
        gwmonster.data[field['name']] = cls._parse(func=feature.findtext,
            xpath=field['sourcefield'], namespace=namespace, returntype=
            field.get('type', None))
    return gwmonster


def cross_cube_constraint(c):
    """ convert gimbal constraint into cross_cube constraint
  """
    cc_c = c.copy()
    cc_c['crest_cnc_router_bit_radius'] = c['cross_cube_cnc_router_bit_radius']
    return cc_c


def ModificationDate():
    """Date resource last modified.

        The value of the first Dublin Core `Date` element qualified by
        'modification' is returned as a unicode string if a qualified
        element is defined, otherwise, an empty unicode string is
        returned. The string is formatted  'YYYY-MM-DD H24:MN:SS TZ'.
        """


@staticmethod
def tree_remains_active_and_my_rpc_changes(interface: 'TreeInterfaceDownstream'
    ) ->None:
    """
        Tree is Active AND
        interface not directly connected to the source AND
        MyRPC changes
        """
    interface.logger.debug('tree_remains_active_and_my_rpc_changes')
    interface.send_i_am_upstream()


@staticmethod
def log(text):
    """
        Output logs in ZOOpt.

        :param text: the text content
        :return: no return value
        """
    print('[zoopt] ' + text)


@classmethod
def make_post_local(cls, name, url, content):
    """Create local push notification using POST http verb."""
    return cls(name, {'url': url, 'verb': 'POST', 'content': content,
        'disabled': False, 'nat': True})


def _is_url(string):
    """
    Checks if the given string is an url path.
    Returns a boolean.
    """
    return 'http' in string


def insert_source_info(result):
    """Add info about source of test result if available."""
    comment = result.get('comment')
    if comment:
        return
    source = result.get('source')
    job_name = result.get('job_name')
    run = result.get('run')
    source_list = [source, job_name, run]
    if not all(source_list):
        return
    source_note = '/'.join(source_list)
    source_note = 'Source: {}'.format(source_note)
    result['comment'] = source_note


def apply_raw_r_assimilation(last_syllable: str) ->str:
    """
    -r preceded by an -s-, -l- or -n- becomes respectively en -s, -l or -n.

    >>> apply_raw_r_assimilation("arm")
    'armr'
    >>> apply_raw_r_assimilation("ás")
    'áss'
    >>> apply_raw_r_assimilation("stól")
    'stóll'
    >>> apply_raw_r_assimilation("stein")
    'steinn'
    >>> apply_raw_r_assimilation("vin")
    'vinn'

    :param last_syllable: last syllable of an Old Norse word
    :return:
    """
    if len(last_syllable) > 0:
        if last_syllable[-1] == 'l':
            return last_syllable + 'l'
        elif last_syllable[-1] == 's':
            return last_syllable + 's'
        elif last_syllable[-1] == 'n':
            return last_syllable + 'n'
    return last_syllable + 'r'


def ratio(fitness1, fitness2):
    """Fixation probability equals the ratio of new fitness over old fitness"""
    sij = fitness2 / fitness1
    return sij


def toot_visibility(mastodon, flag_visibility=None, parent_visibility=None):
    """ Return the visibility of a toot.
    We use the following precedence for flagging the privacy of a toot:
    flags > parent (if not public) > account settings
    """
    default_visibility = mastodon.account_verify_credentials()['source'][
        'privacy']
    if flag_visibility:
        return flag_visibility
    if parent_visibility and parent_visibility != 'public':
        return parent_visibility
    return default_visibility


def Grashof(L, beta, T1, T2=0, rho=None, mu=None, nu=None, g=g):
    """Calculates Grashof number or `Gr` for a fluid with the given
    properties, temperature difference, and characteristic length.

    .. math::
        Gr = \\frac{g\\beta (T_s-T_\\infty)L^3}{\\nu^2}
        = \\frac{g\\beta (T_s-T_\\infty)L^3\\rho^2}{\\mu^2}

    Inputs either of any of the following sets:

    * L, beta, T1 and T2, and density `rho` and kinematic viscosity `mu`
    * L, beta, T1 and T2, and dynamic viscosity `nu`

    Parameters
    ----------
    L : float
        Characteristic length [m]
    beta : float
        Volumetric thermal expansion coefficient [1/K]
    T1 : float
        Temperature 1, usually a film temperature [K]
    T2 : float, optional
        Temperature 2, usually a bulk temperature (or 0 if only a difference
        is provided to the function) [K]
    rho : float, optional
        Density, [kg/m^3]
    mu : float, optional
        Dynamic viscosity, [Pa*s]
    nu : float, optional
        Kinematic viscosity, [m^2/s]
    g : float, optional
        Acceleration due to gravity, [m/s^2]

    Returns
    -------
    Gr : float
        Grashof number []

    Notes
    -----
    .. math::
        Gr = \\frac{\\text{Buoyancy forces}}{\\text{Viscous forces}}

    An error is raised if none of the required input sets are provided.
    Used in free convection problems only.

    Examples
    --------
    Example 4 of [1]_, p. 1-21 (matches):

    >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)
    4656936556.178915
    >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)
    4657491516.530312

    References
    ----------
    .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
       Eighth Edition. McGraw-Hill Professional, 2007.
    .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    """
    if rho and mu:
        nu = mu / rho
    elif not nu:
        raise Exception(
            'Either density and viscosity, or dynamic viscosity,         is needed'
            )
    return g * beta * abs(T2 - T1) * L ** 3 / nu ** 2


@staticmethod
def upgrade():
    """Migrate the database to `version` or the most recent version."""


def _post_build(neurodocker_dict, post_build):
    """ extra instructions for the nfm framework"""
    instr_list = list(neurodocker_dict['instructions'])
    for key, val in post_build.items():
        if key == 'miniconda':
            env_nm = None
            for i, el in enumerate(instr_list):
                if el[0] == 'miniconda':
                    env_nm = el[1]['create_env']
            if env_nm:
                miniconda_dict = {'use_env': env_nm}
            else:
                miniconda_dict = {'create_env': 'testkraken'}
            miniconda_dict.update(val)
            instr_list.append(('miniconda', miniconda_dict))
        else:
            instr_list.append((key, val))
    neurodocker_dict['instructions'] = tuple(instr_list)
    return neurodocker_dict


@classmethod
def autoupdate_rebuild(cls):
    """
        Based on GIT updates - try to autorebuild the image that needs rebuilding.
        """
    pass


def select_subset_by_steps(dataframe, steps):
    """
    Given a pandas dataframe from PELE's result it returns a subset of n PELE steps.
    :param dataframe: pandas object
    :param steps: int
    :return: dataframe
    """
    subset = dataframe[dataframe['Step'] <= int(steps)]
    return subset


def _draw_rectangle(data, obj, draw_options):
    """Return the PGFPlots code for rectangles.
    """
    label = obj.get_label()
    if label == '':
        return data, []
    handles, labels = obj.axes.get_legend_handles_labels()
    labelsFound = [label for h, label in zip(handles, labels) if obj in h.
        get_children()]
    if len(labelsFound) == 1:
        label = labelsFound[0]
    left_lower_x = obj.get_x()
    left_lower_y = obj.get_y()
    ff = data['float format']
    do = ','.join(draw_options)
    right_upper_x = left_lower_x + obj.get_width()
    right_upper_y = left_lower_y + obj.get_height()
    cont = f"""\\draw[{do}] (axis cs:{left_lower_x:{ff}},{left_lower_y:{ff}}) rectangle (axis cs:{right_upper_x:{ff}},{right_upper_y:{ff}});
"""
    if label != '_nolegend_' and label not in data['rectangle_legends']:
        data['rectangle_legends'].add(label)
        cont += '\\addlegendimage{{ybar,ybar legend,{}}};\n'.format(','.
            join(draw_options))
        cont += f'\\addlegendentry{{{label}}}\n\n'
    return data, cont


@classmethod
def default_calls_done(cls):
    """ default: calls_done
        """
    return 0


def process_base_field(cls, field, key):
    """
        Preprocess field instances.

        :param field: Field object
        :param key: Key where field was found
        """
    if not field.name:
        field.name = key
    elif key != field.name:
        if not isinstance(field.alias, list):
            field.alias = [key]
        else:
            field.alias.insert(0, key)
        setattr(cls, field.name, field)
    cls.prepare_field(field)
    if field.alias:
        for alias_name in field.alias:
            if key is not alias_name:
                setattr(cls, alias_name, field)


def vectorLaTeX(entries, overRightArrow=True):
    """entries needs to be a string separted by a comma.
        if overRightArrow, will use \\overrightarrow instead of \\vec"""
    return ('\\overrightarrow{%s}' % entries if overRightArrow else
        '\\vec{%s}' % entries)


def check_file_name_ending(file_name, ending):
    """
    Check if the file_name has the expected file_ending

    If one of the provided endings is the file_name's ending return `True`, else `False`

    Parameters
    ----------
    file_name : str
        The file_name to check the ending for
        The file_name may contain a path, so ``file_name.ending`` as well as ``path/to/file_name.ending`` will work

    ending : str, set, list
        The desired ending or multiple desired endings
        For single entries e.g. ``.json`` or ``csv``, for multiple endings e.g. ``['.json', 'csv']``

    Returns
    -------
    bool
        `True` if the `file_name`'s ending is in the given `ending`, else `False`

    """
    if not isinstance(file_name, str):
        raise TypeError(
            f'file_name needs to be string, {type(file_name)} provided')
    if not isinstance(ending, (str, list, set)):
        raise TypeError(
            f'ending needs to be either a list or a string, {type(ending)} provided'
            )
    if not isinstance(ending, (set, list)):
        ending = [ending]
    for element in ending:
        if element[0] == '.':
            ending[ending.index(element)] = element[1:]
    if file_name.split('.')[-1] in ending:
        return True
    return False


def get_first_unindent(indent, file, start_line, annotation_dict,
    encapsulators, comments):
    """
    Get the first case of a valid unindentation.

    :param indent:          No. of spaces to check unindent against.
    :param file:            A tuple of strings.
    :param start_line:      The line from where to start searching for
                            unindent.
    :param annotation_dict: A dictionary containing sourceranges of all the
                            strings and comments within a file.
    :param encapsulators:   A tuple of SourceRanges of code regions trapped in
                            between a matching pair of encapsulators.
    :param comments:        A dict containing all the types of comments
                            specifiers in a language.
    :return:                The line where unindent is found (intial 0).
    """
    line_nr = start_line
    while line_nr < len(file):
        valid = True
        for comment in annotation_dict['comments']:
            if (comment.start.line < line_nr + 1 and comment.end.line >=
                line_nr + 1):
                valid = False
            first_char = file[line_nr].lstrip()[0] if file[line_nr].strip(
                ) else ''
            if first_char in comments:
                valid = False
        for encapsulator in encapsulators:
            if (encapsulator.start.line < line_nr + 1 and encapsulator.end.
                line >= line_nr + 1):
                valid = False
        line_indent = len(file[line_nr]) - len(file[line_nr].lstrip())
        if line_indent <= indent and valid:
            return line_nr
        line_nr += 1
    return line_nr


def _is_probably_task_error(error):
    """Used to identify task errors."""
    return 'subprocess failed' in error.get('hadoop_error', {}).get('message',
        '')


@classmethod
def instance(cls):
    """
        Singleton to return only one instance of BaseManager.

        :returns: instance of BaseManager
        """
    if not hasattr(cls, '_instance') or cls._instance is None:
        cls._instance = cls()
    return cls._instance


@classmethod
def get_key(cls, name):
    """
        This method creates a Redis key in which instance with given name will be saved.

        :param name: name of object for which a key is to be made.
        :returns: key used in Redis for given name.
        """
    return name


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

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


@staticmethod
def p_daq_list_optional_list_optional(p):
    """daq_list_optional_list_optional : empty
                                           | daq_list_optional_list"""
    p[0] = tuple() if p[1] is None else p[1]


def delone(dc, uri):
    """ delete a single object """
    if dc.is_collection(uri):
        return dc.rmcol(uri)
    else:
        return dc.rm(uri)


def _fr1(a):
    """fix rank > 0 --> rank-0"""
    if a.size == 1:
        a = a.copy()
        a.shape = ()
    return a


def ensure_listable(obj):
    """Ensures obj is a list-like container type"""
    return obj if isinstance(obj, (list, tuple, set)) else [obj]


def __len__():
    """Return the length of the batch. This might be different than the
        passed in batch size, since we could be at the end of the list and
        there are not enough elements left to fill the batch completely."""


def modeIsWriting(mode):
    """
    Determine whether a file mode will permit writing.
    """
    m = mode.lower()
    return m not in ('r', 'rb', 'ru', 'rub')


def same_values(l1, l2):
    """
        from elist.elist import *
        l1 = [1,2,3,5]
        l2 = [0,2,3,4]
        same_values(l1,l2)
    """
    rslt = []
    for i in range(0, l1.__len__()):
        if l1[i] == l2[i]:
            rslt.append(l1[i])
    return rslt


def find(itop, class_name, query):
    """
    Finds elements to delete
    :param itop: itop connection
    :param class_name: name of the class of the objects to delete
    :param query: query to filter objects to delete
    :return: None
    """
    elements = itop.get(class_name, query, output_fields='friendlyname')
    found = elements['message'].split(' ')[1]
    if found == '0':
        return None
    return list(elements['objects'].items())


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 render(request):
    """
        Render a request. This is called on the leaf resource for a request.

        @return: Either C{server.NOT_DONE_YET} to indicate an asynchronous or a
            C{bytes} instance to write as the response to the request.  If
            C{NOT_DONE_YET} is returned, at some point later (for example, in a
            Deferred callback) call C{request.write(b"<html>")} to write data to
            the request, and C{request.finish()} to send the data to the
            browser.

        @raise twisted.web.error.UnsupportedMethod: If the HTTP verb
            requested is not supported by this resource.
        """


def reduce_float(f):
    """
    Reduce a float to only 1 decimal place

    args:
        - float
    returns:
        float
    """
    return float('%0.1f' % f)


def signed(X):
    """
    unsigned -> signed correlation
    """
    return (X + 1) / 2


@classmethod
def run(cls, wind_dirs, sc_points, n_dirs=2, sort_on='total_lcoe', downwind
    =False, out_fpath=None):
    """
        Exclude given number of neighboring Supply Point gids based on most
        prominent wind directions

        Parameters
        ----------
        wind_dirs : pandas.DataFrame | str
            path to .csv or reVX.wind_dirs.wind_dirs.WindDirs output with
            the neighboring supply curve point gids and power-rose value at
            each cardinal direction
        sc_points : pandas.DataFrame | str
            Supply curve point summary table
        n_dirs : int, optional
            Number of prominent directions to use, by default 2
        sort_on : str, optional
            column to sort on before excluding neighbors,
            by default 'total_lcoe'
        downwind : bool, optional
            Flag to remove downwind neighbors as well as upwind neighbors,
            by default False
        out_fpath : str, optional
            Path to .csv file to save updated sc_points to,
            by default None

        Returns
        -------
        sc_points : pandas.DataFrame
            Updated supply curve points after removing non-competative
            wind farms
        """
    cwf = cls(wind_dirs, sc_points, n_dirs=n_dirs)
    sc_points = cwf.remove_noncompetitive_farm(sc_points, sort_on=sort_on,
        downwind=downwind)
    if out_fpath is not None:
        sc_points.to_csv(out_fpath, index=False)
    return sc_points


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


def grouper(n, fill=None):
    """
        split incoming things into sequences of length `n`, using `fill` thing
        to pad incomplete sequences

        @param n: number of things
        @param fill: fill thing (default: None)
        """


def joinGroup(addr, interface=''):
    """
        Join a multicast group. Returns L{Deferred} of success or failure.

        If an error occurs, the returned L{Deferred} will fail with
        L{error.MulticastJoinError}.
        """


def duplicate():
    """Duplicate the selected Grease Pencil strokes

    """
    pass


def _preprocess_corpus(corpus, max_dataset_rows, drop_columns, **kwargs):
    """
    Fix corpus if the user wants this on command line
    """
    if max_dataset_rows is not None:
        corpus = corpus.iloc[:max_dataset_rows, :]
    if drop_columns is not None:
        corpus = corpus.drop(drop_columns, axis=1, errors='ignore')
    return corpus


def parametersDefault(pars):
    """
    Build a dictionary of defaults values from list of parameters.
    """
    dic = {}
    for p in pars:
        dic[p[0]] = p[3]
    return dic


def plot_curve(x_axis, y_axis, figure_id=None, new_figure=True,
    legend_entries=None, title='', x_label='', y_label='', axes_x_limits=
    0.0, axes_y_limits=None, axes_x_ticks=None, axes_y_ticks=None,
    render_lines=True, line_colour=None, line_style='-', line_width=1,
    render_markers=True, marker_style='o', marker_size=5,
    marker_face_colour=None, marker_edge_colour='k', marker_edge_width=1.0,
    render_legend=True, legend_title='', legend_font_name='sans-serif',
    legend_font_style='normal', legend_font_size=10, legend_font_weight=
    'normal', legend_marker_scale=None, legend_location=2,
    legend_bbox_to_anchor=(1.05, 1.0), legend_border_axes_pad=None,
    legend_n_columns=1, legend_horizontal_spacing=None,
    legend_vertical_spacing=None, legend_border=True, legend_border_padding
    =None, legend_shadow=False, legend_rounded_corners=False, render_axes=
    True, axes_font_name='sans-serif', axes_font_size=10, axes_font_style=
    'normal', axes_font_weight='normal', figure_size=(7, 7), render_grid=
    True, grid_line_style='--', grid_line_width=1):
    """
    Plot a single or multiple curves on the same figure.

    Parameters
    ----------
    x_axis : `list` or `array`
        The values of the horizontal axis. They are common for all curves.
    y_axis : `list` of `lists` or `arrays`
        A `list` with `lists` or `arrays` with the values of the vertical axis
        for each curve.
    figure_id : `object`, optional
        The id of the figure to be used.
    new_figure : `bool`, optional
        If ``True``, a new figure is created.
    legend_entries : `list of `str` or ``None``, optional
        If `list` of `str`, it must have the same length as `errors` `list` and
        each `str` will be used to name each curve. If ``None``, the CED curves
        will be named as `'Curve %d'`.
    title : `str`, optional
        The figure's title.
    x_label : `str`, optional
        The label of the horizontal axis.
    y_label : `str`, optional
        The label of the vertical axis.
    axes_x_limits : `float` or (`float`, `float`) or ``None``, optional
        The limits of the x axis. If `float`, then it sets padding on the
        right and left of the graph as a percentage of the curves' width. If
        `tuple` or `list`, then it defines the axis limits. If ``None``, then the
        limits are set automatically.
    axes_y_limits : `float` or (`float`, `float`) or ``None``, optional
        The limits of the y axis. If `float`, then it sets padding on the
        top and bottom of the graph as a percentage of the curves' height. If
        `tuple` or `list`, then it defines the axis limits. If ``None``, then the
        limits are set automatically.
    axes_x_ticks : `list` or `tuple` or ``None``, optional
        The ticks of the x axis.
    axes_y_ticks : `list` or `tuple` or ``None``, optional
        The ticks of the y axis.
    render_lines : `bool` or `list` of `bool`, optional
        If ``True``, the line will be rendered. If `bool`, this value will be
        used for all curves. If `list`, a value must be specified for each
        curve, thus it must have the same length as `y_axis`.
    line_colour : `colour` or `list` of `colour` or ``None``, optional
        The colour of the lines. If not a `list`, this value will be
        used for all curves. If `list`, a value must be specified for each
        curve, thus it must have the same length as `y_axis`. If ``None``, the
        colours will be linearly sampled from jet colormap.
        Example `colour` options are ::

                {'r', 'g', 'b', 'c', 'm', 'k', 'w'}
                or
                (3, ) ndarray

    line_style : ``{'-', '--', '-.', ':'}`` or `list` of those, optional
        The style of the lines. If not a `list`, this value will be used for all
        curves. If `list`, a value must be specified for each curve, thus it must
        have the same length as `y_axis`.
    line_width : `float` or `list` of `float`, optional
        The width of the lines. If `float`, this value will be used for all
        curves. If `list`, a value must be specified for each curve, thus it must
        have the same length as `y_axis`.
    render_markers : `bool` or `list` of `bool`, optional
        If ``True``, the markers will be rendered. If `bool`, this value will be
        used for all curves. If `list`, a value must be specified for each
        curve, thus it must have the same length as `y_axis`.
    marker_style : `marker` or `list` of `markers`, optional
        The style of the markers. If not a `list`, this value will be used for
        all curves. If `list`, a value must be specified for each curve, thus it
        must have the same length as `y_axis`.
        Example `marker` options ::

                {'.', ',', 'o', 'v', '^', '<', '>', '+', 'x', 'D', 'd', 's',
                 'p', '*', 'h', 'H', '1', '2', '3', '4', '8'}

    marker_size : `int` or `list` of `int`, optional
        The size of the markers in points. If `int`, this value will be used
        for all curves. If `list`, a value must be specified for each curve, thus
        it must have the same length as `y_axis`.
    marker_face_colour : `colour` or `list` of `colour` or ``None``, optional
        The face (filling) colour of the markers. If not a `list`, this value
        will be used for all curves. If `list`, a value must be specified for
        each curve, thus it must have the same length as `y_axis`. If ``None``,
        the colours will be linearly sampled from jet colormap.
        Example `colour` options are ::

                {'r', 'g', 'b', 'c', 'm', 'k', 'w'}
                or
                (3, ) ndarray

    marker_edge_colour : `colour` or `list` of `colour` or ``None``, optional
        The edge colour of the markers. If not a `list`, this value will be used
        for all curves. If `list`, a value must be specified for each curve, thus
        it must have the same length as `y_axis`. If ``None``, the colours will
        be linearly sampled from jet colormap.
        Example `colour` options are ::

                {'r', 'g', 'b', 'c', 'm', 'k', 'w'}
                or
                (3, ) ndarray

    marker_edge_width : `float` or `list` of `float`, optional
        The width of the markers' edge. If `float`, this value will be used for
        all curves. If `list`, a value must be specified for each curve, thus it
        must have the same length as `y_axis`.
    render_legend : `bool`, optional
        If ``True``, the legend will be rendered.
    legend_title : `str`, optional
        The title of the legend.
    legend_font_name : See below, optional
        The font of the legend.
        Example options ::

            {'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}

    legend_font_style : ``{'normal', 'italic', 'oblique'}``, optional
        The font style of the legend.
    legend_font_size : `int`, optional
        The font size of the legend.
    legend_font_weight : See below, optional
        The font weight of the legend.
        Example options ::

            {'ultralight', 'light', 'normal', 'regular', 'book', 'medium',
             'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy',
             'extra bold', 'black'}

    legend_marker_scale : `float`, optional
        The relative size of the legend markers with respect to the original
    legend_location : `int`, optional
        The location of the legend. The predefined values are:

        =============== ===
        'best'          0
        'upper right'   1
        'upper left'    2
        'lower left'    3
        'lower right'   4
        'right'         5
        'center left'   6
        'center right'  7
        'lower center'  8
        'upper center'  9
        'center'        10
        =============== ===

    legend_bbox_to_anchor : (`float`, `float`), optional
        The bbox that the legend will be anchored.
    legend_border_axes_pad : `float`, optional
        The pad between the axes and legend border.
    legend_n_columns : `int`, optional
        The number of the legend's columns.
    legend_horizontal_spacing : `float`, optional
        The spacing between the columns.
    legend_vertical_spacing : `float`, optional
        The vertical space between the legend entries.
    legend_border : `bool`, optional
        If ``True``, a frame will be drawn around the legend.
    legend_border_padding : `float`, optional
        The fractional whitespace inside the legend border.
    legend_shadow : `bool`, optional
        If ``True``, a shadow will be drawn behind legend.
    legend_rounded_corners : `bool`, optional
        If ``True``, the frame's corners will be rounded (fancybox).
    render_axes : `bool`, optional
        If ``True``, the axes will be rendered.
    axes_font_name : See below, optional
        The font of the axes.
        Example options ::

            {'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}

    axes_font_size : `int`, optional
        The font size of the axes.
    axes_font_style : ``{'normal', 'italic', 'oblique'}``, optional
        The font style of the axes.
    axes_font_weight : See below, optional
        The font weight of the axes.
        Example options ::

            {'ultralight', 'light', 'normal', 'regular', 'book', 'medium',
             'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy',
             'extra bold', 'black'}

    figure_size : (`float`, `float`) or ``None``, optional
        The size of the figure in inches.
    render_grid : `bool`, optional
        If ``True``, the grid will be rendered.
    grid_line_style : ``{'-', '--', '-.', ':'}``, optional
        The style of the grid lines.
    grid_line_width : `float`, optional
        The width of the grid lines.

    Raises
    ------
    ValueError
        legend_entries list has different length than y_axis list

    Returns
    -------
    viewer : :map:`GraphPlotter`
        The viewer object.
    """
    from menpo.visualize import GraphPlotter
    if not isinstance(y_axis, list):
        y_axis = [y_axis]
    if legend_entries is not None and len(legend_entries) != len(y_axis):
        raise ValueError(
            'legend_entries list has different length than y_axis list')
    return GraphPlotter(figure_id=figure_id, new_figure=new_figure, x_axis=
        x_axis, y_axis=y_axis, title=title, legend_entries=legend_entries,
        x_label=x_label, y_label=y_label, x_axis_limits=axes_x_limits,
        y_axis_limits=axes_y_limits, x_axis_ticks=axes_x_ticks,
        y_axis_ticks=axes_y_ticks).render(render_lines=render_lines,
        line_colour=line_colour, line_style=line_style, line_width=
        line_width, render_markers=render_markers, marker_style=
        marker_style, marker_size=marker_size, marker_face_colour=
        marker_face_colour, marker_edge_colour=marker_edge_colour,
        marker_edge_width=marker_edge_width, render_legend=render_legend,
        legend_title=legend_title, legend_font_name=legend_font_name,
        legend_font_style=legend_font_style, legend_font_size=
        legend_font_size, legend_font_weight=legend_font_weight,
        legend_marker_scale=legend_marker_scale, legend_location=
        legend_location, legend_bbox_to_anchor=legend_bbox_to_anchor,
        legend_border_axes_pad=legend_border_axes_pad, legend_n_columns=
        legend_n_columns, legend_horizontal_spacing=
        legend_horizontal_spacing, legend_vertical_spacing=
        legend_vertical_spacing, legend_border=legend_border,
        legend_border_padding=legend_border_padding, legend_shadow=
        legend_shadow, legend_rounded_corners=legend_rounded_corners,
        render_axes=render_axes, axes_font_name=axes_font_name,
        axes_font_size=axes_font_size, axes_font_style=axes_font_style,
        axes_font_weight=axes_font_weight, figure_size=figure_size,
        render_grid=render_grid, grid_line_style=grid_line_style,
        grid_line_width=grid_line_width)


@staticmethod
def _dpi(px_per_meter):
    """
        Return the integer pixels per inch from *px_per_meter*, defaulting to
        96 if *px_per_meter* is zero.
        """
    if px_per_meter == 0:
        return 96
    return int(round(px_per_meter * 0.0254))


@staticmethod
def generate(config, spec):
    """Generate the mapping described in the module docstring."""
    raise NotImplementedError()


def _iterable(obj):
    """ Check if obj is iterable """
    try:
        iter(obj)
    except TypeError:
        return False
    else:
        return True


def is_blank(string):
    """
    Check is a string is black or not, either none or only contains whitespace.

    @param string: String to be checked
    @return: Is blank or not
    """
    return string is None or len(string) == 0 or string.isspace()


def print_activity(quest: dict):
    """Print content of activity."""
    val = 'Yes'
    print('========================')
    print('name         : {}'.format(quest['name']))
    print('coef         : {}'.format(quest['coefficient']))
    print('type         : {}'.format(quest['type']))
    if quest['eliminate'] is None:
        val = 'No'
    print('eliminate    : {}'.format(val))
    try:
        print('mark min     : {}'.format(quest['mark_min']))
        print('mark max     : {}'.format(quest['mark_max']))
        print('average mark : {}'.format(quest['average_mark']))
        print('student mark : {}'.format(quest['student_mark']))
    except KeyError:
        pass
    print('starts on    : {}'.format(quest['date_start']))
    print('ends on      : {}'.format(quest['date_end']))


def preloadCommonData() ->None:
    """
    Preload common data structures (used by many modules)
        This includes BibleBooksCode and USFMMarkers
    """
    global loadedBibleBooksCodes, loadedUSFMMarkers, USFMParagraphMarkers, internal_SFMs_to_remove
    from BibleOrgSys.Reference.BibleBooksCodes import BibleBooksCodes
    loadedBibleBooksCodes = BibleBooksCodes().loadData()
    assert loadedBibleBooksCodes
    from BibleOrgSys.Reference.USFM3Markers import USFM3Markers
    loadedUSFMMarkers = USFM3Markers().loadData()
    assert loadedUSFMMarkers
    USFMParagraphMarkers = loadedUSFMMarkers.getNewlineMarkersList(
        'CanonicalText')
    assert USFMParagraphMarkers
    USFMParagraphMarkers.remove('qa')
    internal_SFMs_to_remove = loadedUSFMMarkers.getCharacterMarkersList(
        includeBackslash=True, includeNestedMarkers=True, includeEndMarkers
        =True)
    internal_SFMs_to_remove.sort(key=len, reverse=True)


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 _read_params_from_file(filepath):
    """Extract key=value pairs from a file.

    :param filepath: path to a file containing key=value pairs separated by
                     whitespace or newlines.
    :returns: a dictionary representing the content of the file
    """
    with open(filepath) as f:
        cmdline = f.read()
    options = cmdline.split()
    params = {}
    for option in options:
        if '=' not in option:
            continue
        k, v = option.split('=', 1)
        params[k] = v
    return params


@classmethod
def init_bare(cls, path):
    """Create a new bare repository.

        ``path`` should already exist and be an emty directory.

        :param path: Path to create bare repository in
        :return: a `Repo` instance
        """
    return cls._init_maybe_bare(path, True)


def r_det(td, r_in):
    """Calculate detected countrate given dead time and incident countrate."""
    tau = 1 / r_in
    return 1.0 / (tau + td)


def int_cast_or_len(i):
    """
  >>> int_cast_or_len(range(10))
  10
  >>> int_cast_or_len('90 foo')
  6
  >>> int_cast_or_len('90')
  90

  """
    try:
        return int(i)
    except ValueError:
        return len(i)
    except TypeError:
        return len(i)


@classmethod
def get_login(cls, key, command, path):
    """Validate the key for the command and path
        Return the user id if succeed or None
        """
    shares = cls.search([('key', '=', key)])
    if not shares:
        return None
    for share in shares:
        if cls.match(share, command, path):
            return share.user.id
    return None


@staticmethod
def p_value_table_list(p):
    """value_table_list : value_table
                            | value_table value_table_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


def filter_vcf_variable(line):
    """Filter variable lines from the VCF file."""
    if line.startswith(b'##samtoolsVersion'):
        return True
    elif line.startswith(b'##reference'):
        return True
    elif line.startswith(b'##fileDate'):
        return True
    elif b'/data_all/' in line:
        return True


@classmethod
def _create_value_store(cls, parent, name):
    """
        Subclasses may override this class method to return
        the value store they want to use.
        Default is to return None, which will lead to using the parent's value_store
        """
    return None