def jac_saturation(x, cf, *args):
    """Function defining Jacobian of the inequality constraint
    on the saturation, defined as situations when the production from RES
    exceeds the theoretical limit that the network can support.

    :param x: State vector(not used).
    :param cf: Time-dependent capacity factors.
    :type x: :py:class:`numpy.array`
    :type cf: :py:class:`numpy.array`

    :returns: Value of Jacobian of constraint.
    :rtype: :py:class:`numpy.array`
    """
    return -cf


def assert_close(a, b, message=None):
    """wrapper for numpy all_close() method"""
    assert (a.numpy() == b.numpy() if hasattr(b, 'numpy') else b).all_close(
        ), message


def _split_header_entry(entry):
    """
    Split 3ds header entries by '=' character. If multiple values split
    those by ';' character.
    """
    key_str, val_str = entry.split('=', 1)
    if ';' in val_str:
        return key_str, val_str.strip('"').split(';')
    else:
        return key_str, val_str.strip('"')


def formatTearDown(computer):
    """Method called after `slapos node format` phase.

    :param computer: slapos.format.Computer, formatted computer
    """


@staticmethod
def get_5_largest(intensity_list):
    """
		Computes the indices of the largest 5 ion intensities for writing to console

		:param intensity_list: List of Ion intensities
		:type intensity_list: list

		:return: Indices of largest 5 ion intensities
		:rtype: list
		"""
    largest = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for i in range(len(intensity_list)):
        if intensity_list[i] > intensity_list[largest[0]]:
            largest[0] = i
    for j in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
        for i in range(len(intensity_list)):
            if intensity_list[largest[j]] < intensity_list[i] < intensity_list[
                largest[j - 1]]:
                largest[j] = i
    return largest


def subscribe(receiver):
    """Register an IStatusReceiver to receive new status events. The
        receiver will immediately be sent a set of 'builderAdded' messages
        for all current builders. It will receive further 'builderAdded' and
        'builderRemoved' messages as the config file is reloaded and builders
        come and go. It will also receive 'buildsetSubmitted' messages for
        all outstanding BuildSets (and each new BuildSet that gets
        submitted). No additional messages will be sent unless the receiver
        asks for them by calling .subscribe on the IBuilderStatus objects
        which accompany the addedBuilder message."""


@classmethod
def get_allowed_carriers_domain(cls):
    """This method returns domain to seach allowed carriers

        Downstream modules can inherit and update customize this domain.
        """
    return []


def show_details_one_frame(input_image, details, output_path):
    """
    simple_eval.write_to_file_printable(reduce_plus(segmentation_details), details_path)
    output_file_prefix = "SegDetails_"
    overlord = draw_details.EvaluationDetails([details_path, input_file_part])
    output_drawings_directory = ensure_directory_in(details_path, SEG_DRAWING_FOLDER)
    draw_details.run(overlord, input_directory, output_drawings_directory, output_file_prefix)
    debug_center.show_in_console(None, "Progress", "Done drawing detailed segmentation results...")
    """
    pass


@classmethod
def discover(cls, conf, repo, environments, commit_hash, regex=None, check=
    False):
    """
        Discover benchmarks in the given `benchmark_dir`.

        Parameters
        ----------
        conf : Config object
            The project's configuration

        repo : Repo object
            The project's repository

        environments : list of Environment
            List of environments available for benchmark discovery.

        commit_hash : list of str
            Commit hashes to use for benchmark discovery.

        regex : str or list of str, optional
            `regex` is a list of regular expressions matching the
            benchmarks to run.  If none are provided, all benchmarks
            are run.

        check : bool
            Run additional checks after discovery.

        """
    benchmarks = cls._disc_benchmarks(conf, repo, environments, commit_hash,
        check)
    return cls(conf, benchmarks, regex=regex)


@classmethod
def from_dict(cls, transaction):
    """
        Creates a transfer transaction

        :param transaction: transaction (dict)
        :return: (Transfer)
        """
    self = cls(transaction['fee'], _error_use_class_method=False)
    self._sender_public_key = transaction['senderPublicKey']
    self._timestamp = transaction['timestamp']
    self._recipient_id = transaction['recipientId']
    self._amount = transaction['amount']
    vendor_field = transaction.get('vendorField', None)
    if vendor_field and len(vendor_field) <= 64:
        self._vendor_field = vendor_field
    self.sign_from_dict(transaction)
    return self


def specified_users(users_arg, users):
    """Parse a comma-separated list of users

    Check that all specified users are valid, and return them as a list

    Parameters
    ----------
    users_arg : str
        Comma-separated list of users
    users : container
        Container of valid users

    Returns
    -------
    list
        List of specified users
    """
    if set(users_arg.split(',')) <= users:
        users = users_arg.split(',')
        return users
    else:
        raise Exception(
            'Some of the specified users have not yet been inducted into the policy. Use minduct -u to induct them before continuing.'
            )


@classmethod
def for_file(cls, fhandle, language='c++'):
    """method for new writer"""
    from beatle.model.writer import filewriter
    return filewriter(fhandle, language)


@staticmethod
def create_instance(class_, *args, **kwargs):
    """
        Prepares the return value for :py:meth:`get`.

        You may override this method in a subclass, if you want to
        customize the way new instances are created.

        :param class_:
            The requested class.

        :param args:
            Positional keywords passed to :py:meth:`get`.

        :param kwargs:
            Keyword arguments passed to :py:meth:`get`.
        """
    return class_(*args, **kwargs)


def Format():
    """Return the resource format.

        Return the resource's MIME type (e.g., 'text/html',
        'image/png', etc.).

        The first unqualified Dublin Core `Format` element value is
        returned as a unicode string if an unqualified element is
        defined, otherwise, an empty unicode string is returned.
        """


def get_sync_alias(alias):
    """Returns an alias to be used for the sync connection
    of alias."""
    return '{}-sync'.format(alias)


@property
def tastes(cls):
    """
        Get a dictionary of all taste names mapped to their
        :class:`coalib.bearlib.aspects.Taste` instances.
        """
    if cls.parent:
        return dict(cls.parent.tastes, **cls._tastes)
    return dict(cls._tastes)


def replace_kv_dict(d, tag, word):
    """ Replace tag by word for each key and value of dict

        :param d: The dict to replace tag by word in
        :param tag: The tag to replace in the dict
        :param word: The word to replace the tag
    """
    for k, v in d.items():
        new_k = k.replace(tag, word)
        new_v = v.replace(tag, word)
        d[new_k] = new_v
        if new_k != k:
            del d[k]
    return d


def get_wait_time(authenticated):
    """Get the wait time based on whether EUtils API use is autheticated or not.

    Parameters
    ----------
    authenticated : bool
        Whether EUtils API use is authenticated.

    Returns
    -------
    float
        Wait time to use between API calls, in seconds.

    Notes
    -----
    The wait time for requesting is set for the E-Utils API, which allows for:
    - 10 requests/second for authenticated users (using an API key)
    - 3 requests/second otherwise
    More information on rate limits is availabe here: https://www.ncbi.nlm.nih.gov/books/NBK25497/
    """
    return 1 / 10 if authenticated else 1 / 3


def change_object_type(obj, new_type):
    """Attempts to change an object (usually a string) to a different object type."""
    if new_type == 'str':
        return str(obj)
    elif new_type == 'int':
        return int(obj)
    elif new_type == 'float':
        return float(obj)
    else:
        raise IOError('expected_type "{}" is not supported in this function.'
            .format(new_type))


def prefix_match(list1, list2):
    """
    Find the length of the longest common prefix of list1 and list2.

    >>> prefix_match([], [])
    0
    >>> prefix_match('test', 'test')
    4
    >>> prefix_match('test', 'toast')
    1
    >>> prefix_match('test', 'best')
    0
    >>> prefix_match([1, 2, 3, 4], [1, 2, 4, 8])
    2
    """
    for i in range(min(len(list1), len(list2)), 0, -1):
        if list1[:i] == list2[:i]:
            return i
    return 0


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

    The ".dev0" means dirty.

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


def add_marker_move(CLIP_OT_add_marker=None, TRANSFORM_OT_translate=None):
    """Add new marker and move it on movie

    :param CLIP_OT_add_marker: Add Marker, Place new marker at specified location
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.type(
    """
    import re
    import unicodedata
    from six import text_type
    value = text_type(value)
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore'
        ).decode('utf8')
    value = re.sub('[^\\w\\s-]', '', value).strip().lower()
    value = re.sub('[-\\s]+', '_', value)
    return value


def _on_message_callback(c, userdata, message):
    """Internal callback"""
    userdata['callback'](c, userdata['userdata'], message)


def split_comma_space(datai):
    """normalizes the form of a SET into a comma separated list instead of being mixed"""
    if ',' in datai:
        sline = datai.replace(',', ' ').split()
    else:
        sline = datai.split()
    return sline


def removeWriter(writer):
    """
        Removes an object previously added with L{addWriter}.

        @return: L{None}.
        """


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True):
    """Select Grease Pencil strokes within a rectangular region

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


@classmethod
def drop_collection(cls):
    """Drops the entire collection associated with this
        :class:`mongomotor.Document` type from the database.
        """
    cls._collection = None
    db = cls._get_db()
    return db.drop_collection(cls._get_collection_name())


def listenUDP(port, protocol, interface='', maxPacketSize=8192):
    """
        Connects a given L{DatagramProtocol} to the given numeric UDP port.

        @param port: A port number on which to listen.
        @type port: C{int}

        @param protocol: A L{DatagramProtocol} instance which will be
            connected to the given C{port}.
        @type protocol: L{DatagramProtocol}

        @param interface: The local IPv4 or IPv6 address to which to bind;
            defaults to '', ie all IPv4 addresses.
        @type interface: C{str}

        @param maxPacketSize: The maximum packet size to accept.
        @type maxPacketSize: C{int}

        @return: object which provides L{IListeningPort}.
        """


def create_snapshot_copy_grant(SnapshotCopyGrantName=None, KmsKeyId=None,
    Tags=None):
    """
    Creates a snapshot copy grant that permits Amazon Redshift to use a customer master key (CMK) from AWS Key Management Service (AWS KMS) to encrypt copied snapshots in a destination region.
    For more information about managing snapshot copy grants, go to Amazon Redshift Database Encryption in the Amazon Redshift Cluster Management Guide .
    See also: AWS API Documentation

    :example: response = client.create_snapshot_copy_grant(
        SnapshotCopyGrantName='string',
        KmsKeyId='string',
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type SnapshotCopyGrantName: string
    :param SnapshotCopyGrantName: [REQUIRED]
            The name of the snapshot copy grant. This name must be unique in the region for the AWS account.
            Constraints:
            Must contain from 1 to 63 alphanumeric characters or hyphens.
            Alphabetic characters must be lowercase.
            First character must be a letter.
            Cannot end with a hyphen or contain two consecutive hyphens.
            Must be unique for all clusters within an AWS account.

    :type KmsKeyId: string
    :param KmsKeyId: The unique identifier of the customer master key (CMK) to which to grant Amazon Redshift permission. If no key is specified, the default key is used.

    :type Tags: list
    :param Tags: A list of tag instances.
            (dict) --A tag consisting of a name/value pair for a resource.
            Key (string) --The key, or name, for the resource tag.
            Value (string) --The value for the resource tag.

    :rtype: dict
    :return: {
        'SnapshotCopyGrant': {
            'SnapshotCopyGrantName': 'string',
            'KmsKeyId': 'string',
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ]
        }
    }

    """
    pass


def __init__(settings={}):
    """Initialize interface attributes with ``settings`` parameter.
        """


def keyframe_jump(next: bool=True):
    """Jump to previous/next keyframe

    :param next: Next Keyframe
    :type next: bool
    """
    pass


@classmethod
def reV_run(cls, site, site_df, inputs, output_request):
    """Run the SAM econ model for a single site.

        Parameters
        ----------
        site : int
            Site gid.
        site_df : pd.DataFrame
            Dataframe of site-specific input variables. Row index corresponds
            to site number/gid (via df.loc not df.iloc), column labels are the
            variable keys that will be passed forward as SAM parameters.
        inputs : dict
            Dictionary of SAM input parameters.
        output_request : list | tuple | str
            Requested SAM output(s) (e.g., 'ppa_price', 'lcoe_fcr').

        Returns
        -------
        sim.outputs : SAM.SiteOutput
            Slotted dictionary emulator keyed by SAM variable names with SAM
            numerical results.
        """
    sim = cls(parameters=inputs, site_parameters=dict(site_df.loc[(site), :
        ]), output_request=output_request)
    sim._site = site
    sim.assign_inputs()
    sim.execute()
    sim.collect_outputs()
    sim.outputs_to_utc_arr()
    return sim.outputs


def prettify(element, *, default_category):
    """Return element properties formatted as list. The type of the element
    (recurrent or standard) is inferred by the presence of the 'frequency'
    property.
    If the element's 'category' property is None, use 'default_category'.

    :type element: dict
    :type default_category: str
    """
    recurrent = 'frequency' in element
    if recurrent:
        properties = 'name', 'value', 'frequency', 'start', 'end', 'category'
    else:
        properties = 'name', 'value', 'date', 'category'
    longest_property_length = 0
    for p in properties:
        if len(p) > longest_property_length:
            longest_property_length = len(p)
    if element['category'] is None:
        element['category'] = default_category
    lines = []
    for p in properties:
        lines.append('{}: {}'.format(p.capitalize().ljust(
            longest_property_length), str(element[p]).title()))
    return '\n'.join(lines)


def input_float(prompt=''):
    """Ask for a human float input.

    Args:
        prompt (string): Text to prompt as input.
    """
    while True:
        try:
            float_input = float(input(prompt))
        except ValueError:
            print('Please enter a float.\n')
            continue
        else:
            break
    return float_input


def _close_file(filename, f):
    """Close the file if filename is a string."""
    if hasattr(f, 'close') and isinstance(filename, str):
        f.close()


def wns_payload(alert=None, toast=None, tile=None, badge=None):
    """WNS specific platform override payload.

    Must include exactly one of ``alert``, ``toast``, ``tile``, or ``badge``.

    """
    if sum(1 for x in (alert, toast, tile, badge) if x) != 1:
        raise ValueError('WNS payload must have one notification type.')
    payload = {}
    if alert is not None:
        payload['alert'] = alert
    if toast is not None:
        payload['toast'] = toast
    if tile is not None:
        payload['tile'] = tile
    if badge is not None:
        payload['badge'] = badge
    return payload


def skipline(line):
    """Determine whether a line is something to skip - a comment or blank"""
    stripped_line = line.strip()
    return not stripped_line or stripped_line.startswith('#')


def total_seconds(td):
    """
    simulates the total_seconds function added in python 3.2+ and 2.7+
    See
    :param td: timedelta
    :type td: timedelta
    :return: int representing total seconds from timedelta
    :rtype: int
    """
    return int((td.seconds + td.days * 24 * 3600) * 10 ** 6 / 10 ** 6)


def AND(list):
    """ and of all arguments in a list """
    for i in list:
        if not i:
            return False
    return True


def _is_short_sequence(sequence, threshold):
    """
    Return true if the provided sequence is shorter than the provided
    threshold.

    Parameters
    ----------
    sequence : Sequence object
        The sequence you wish to consider.
    threshold : int
        Minimum number of positions allowed in sequence.

    Returns
    -------
    True of False
        True if the sequence length is shorter than the provided threshold.
    """
    return len(sequence.ungapped()) < threshold


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 _split_by_comma(s, length=50):
    """Group a comma-separated string into a list of at-most
    ``length``-length words each."""
    str_split = s.split(',')
    str_list = []
    for i in range(0, len(str_split) + length, length):
        temp_str = ','.join(str_split[i:i + length])
        if temp_str:
            str_list.append(temp_str)
    return str_list


def wf_error_code(node):
    """
    It returns the error code for the specified action node, or an empty string if
    the action node has not exited with ERROR state.

    Each type of action node must define its complete error code list.
    """


def type_object_attrgetter(obj, attr, *defargs):
    """
    This implements an improved attrgetter for type objects (i.e. classes)
    that can handle class attributes that are implemented as properties on
    a metaclass.

    Normally `getattr` on a class with a `property` (say, "foo"), would return
    the `property` object itself.  However, if the class has a metaclass which
    *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find
    the "foo" property on the metaclass and resolve it.  For the purposes of
    autodoc we just want to document the "foo" property defined on the class,
    not on the metaclass.

    For example::

        >>> class Meta(type):
        ...     @property
        ...     def foo(cls):
        ...         return 'foo'
        ...
        >>> class MyClass(metaclass=Meta):
        ...     @property
        ...     def foo(self):
        ...         ""\"Docstring for MyClass.foo property.""\"
        ...         return 'myfoo'
        ...
        >>> getattr(MyClass, 'foo')
        'foo'
        >>> type_object_attrgetter(MyClass, 'foo')
        <property at 0x...>
        >>> type_object_attrgetter(MyClass, 'foo').__doc__
        'Docstring for MyClass.foo property.'

    The last line of the example shows the desired behavior for the purposes
    of autodoc.
    """
    for base in obj.__mro__:
        if attr in base.__dict__:
            if isinstance(base.__dict__[attr], property):
                return base.__dict__[attr]
            break
    return getattr(obj, attr, *defargs)


def add_line_breaks(string, min_length):
    """! @brief Adds line breaks on the next space after the minimum length of a line"""
    requirement = min_length
    replace = False
    positions = []
    for i, char in enumerate(string):
        if i > requirement:
            replace = True
        if replace and char == ' ':
            positions.append(i)
            requirement = i + min_length
            replace = False
    for rep in positions:
        string = string[:rep] + '\n' + string[rep + 1:]
    return string


def infer_dtype(value):
    """get correct data type for the first element."""
    import numpy as np
    array_dtype = 'none'
    if isinstance(value, np.ndarray):
        dtype = np.ndarray
        array_dtype = value.dtype.__str__()
    elif isinstance(value, str):
        dtype = str
    elif isinstance(value, int):
        dtype = int
    elif isinstance(value, list):
        dtype = list
    elif isinstance(value, dict):
        dtype = dict
    elif isinstance(value, float):
        dtype = float
    return dtype, array_dtype


def get_neighbor_distances(ntw, v0, l):
    """Get distances to the nearest vertex neighbors along
    connecting arcs.

    Parameters
    ----------

    ntw : spaghetti.Network
        A spaghetti network object.

    v0 : int
        The vertex ID.

    l : dict
        The key is a tuple (start vertex, end vertex); value is ``float``.
        Cost per arc to travel, e.g. distance.

    Returns
    -------

    neighbors : dict
       The key is an integer (vertex ID); value is ``float`` (distance).

    Examples
    --------

    >>> import spaghetti
    >>> from libpysal import examples
    >>> ntw = spaghetti.Network(examples.get_path("streets.shp"))
    >>> neighs = spaghetti.util.get_neighbor_distances(ntw, 0, ntw.arc_lengths)
    >>> numpy.round(neighs[1], 10)
    102.6235345344

    """
    arcs = ntw.enum_links_vertex(v0)
    neighbors = {}
    for arc in arcs:
        if arc[0] != v0:
            neighbors[arc[0]] = l[arc]
        else:
            neighbors[arc[1]] = l[arc]
    return neighbors


def pad_to(string, length):
    """Pad a string to a specified length"""
    return string + '_' * (length - len(string) - 1) + ' '


def orient(mag_azimuth, field_dip, or_con):
    """
    uses specified orientation convention to convert user supplied orientations
    to laboratory azimuth and plunge
    """
    or_con = str(or_con)
    if mag_azimuth == -999:
        return '', ''
    if or_con == '1':
        return mag_azimuth, -field_dip
    if or_con == '2':
        return mag_azimuth - 90.0, -field_dip
    if or_con == '3':
        return mag_azimuth, 90.0 - field_dip
    if or_con == '4':
        return mag_azimuth, field_dip
    if or_con == '5':
        return mag_azimuth, field_dip - 90.0
    if or_con == '6':
        return mag_azimuth - 90.0, 90.0 - field_dip
    if or_con == '7':
        return mag_azimuth - 90.0, 90.0 - field_dip
    print('Error in orientation convention')


def get_config(ClientArn=None, ClientVersion=None, HapgList=None):
    """
    Gets the configuration files necessary to connect to all high availability partition groups the client is associated with.
    See also: AWS API Documentation

    :example: response = client.get_config(
        ClientArn='string',
        ClientVersion='5.1'|'5.3',
        HapgList=[
            'string',
        ]
    )

    :type ClientArn: string
    :param ClientArn: [REQUIRED]
            The ARN of the client.

    :type ClientVersion: string
    :param ClientVersion: [REQUIRED]
            The client version.

    :type HapgList: list
    :param HapgList: [REQUIRED]
            A list of ARNs that identify the high-availability partition groups that are associated with the client.
            (string) --

    :rtype: dict
    :return: {
        'ConfigType': 'string',
        'ConfigFile': 'string',
        'ConfigCred': 'string'
    }

    """
    pass


def __call__(fileinfo, settings):
    """extracts one zip content file

        returns tuple with filename and content
        """


def reduce_max(input):
    """Returns the max of all elements in the input tensor.

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

    Returns
    -------
    Tensor
        A framework-specific tensor with shape (1,)
    """
    pass


@staticmethod
def warning(message):
    """
        Prints a warning message
        :param message: str
        :return:
        """
    print('[WARNING]: {}'.format(message))


@classmethod
def load_ignore_list(cls, regex_urls_to_ignore):
    """Receive and loads a list with regex urls to replace."""
    cls.regex_urls_to_ignore = regex_urls_to_ignore or []


def _simplify_dfas(dfas):
    """
    This is not theoretically optimal, but works well enough.
    Algorithm: repeatedly look for two states that have the same
    set of arcs (same labels pointing to the same nodes) and
    unify them, until things stop changing.

    dfas is a list of DFAState instances
    """
    changes = True
    while changes:
        changes = False
        for i, state_i in enumerate(dfas):
            for j in range(i + 1, len(dfas)):
                state_j = dfas[j]
                if state_i == state_j:
                    del dfas[j]
                    for state in dfas:
                        state.unifystate(state_j, state_i)
                    changes = True
                    break


def chiffre_barre_ligne(s, r, i):
    """
    Look into every number in line *i*,
    if the number in column *k* ``s[i][k]`` is not null,

    @param      s       current state of the sudoku
    @param      r       array ``r[n] == 0`` means number *n+1* is already taken on this line
    @param      i       line index (0 based)
    """
    for k in range(0, 9):
        if s[i][k] > 0:
            r[s[i][k] - 1] = 0


@classmethod
def decode_ssh_public(cls, packet):
    """Decode an SSH format EdDSA public key"""
    public_value = packet.get_string()
    return public_value,


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


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

        :param SharedContentRemoveLinkPasswordType val:
        :rtype: EventType
        """
    return cls('shared_content_remove_link_password', val)


def buildZooKeeperHosts(host_list):
    """
    Build the ZK cluster host list for client connections.

    :param list host_list: A list of
        :py:class:`~nodepool.zk.ZooKeeperConnectionConfig` objects (one
        per server) defining the ZooKeeper cluster servers.
    """
    if not isinstance(host_list, list):
        raise Exception("'host_list' must be a list")
    hosts = []
    for host_def in host_list:
        host = '%s:%s%s' % (host_def.host, host_def.port, host_def.chroot)
        hosts.append(host)
    return ','.join(hosts)


def merge_headers(header_map_list):
    """
    Helper function for combining multiple header maps into one.

    :param list(dict) header_map_list: list of maps

    :rtype: dict
    """
    headers = {}
    for header_map in header_map_list:
        if header_map:
            headers.update(header_map)
    return headers


def _ros_plot_pos(row, censorship, cohn):
    """
    ROS-specific plotting positions.

    Computes the plotting position for an observation based on its rank,
    censorship status, and detection limit index.

    Parameters
    ----------
    row : pandas.Series or dict-like
        Full observation (row) from a censored dataset. Requires a
        'rank', 'detection_limit', and `censorship` column.

    censorship : str
        Name of the column in the dataframe that indicates that a
        observation is left-censored. (i.e., True -> censored,
        False -> uncensored)

    cohn : pandas.DataFrame
        DataFrame of Cohn numbers.

    Returns
    -------
    plotting_position : float

    See Also
    --------
    cohn_numbers
    """
    DL_index = row['det_limit_index']
    rank = row['rank']
    censored = row[censorship]
    dl_1 = cohn.iloc[DL_index]
    dl_2 = cohn.iloc[DL_index + 1]
    if censored:
        return (1 - dl_1['prob_exceedance']) * rank / (dl_1['ncen_equal'] + 1)
    else:
        return 1 - dl_1['prob_exceedance'] + (dl_1['prob_exceedance'] -
            dl_2['prob_exceedance']) * rank / (dl_1['nuncen_above'] + 1)


def merge_blocks(func, pred, succ):
    """Merge two consecutive blocks (T2 transformation)"""
    assert pred.terminator.opcode == 'jump', pred.terminator.opcode
    assert pred.terminator.args[0] == succ
    pred.terminator.delete()
    pred.extend(succ)
    func.del_block(succ)


@classmethod
def _get_origin(cls):
    """Return list of Model names for origin Reference"""
    return ['payment_gateway.transaction']


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


def clip_(in_tensor, max_or_min, min_or_max):
    """limit the values in in_tensor to be within [min,max].
    values larger than max will be cut to max, respectively for mins.
    the order of max/min doesn't matter.
    the operation is not in-place, that saves you alot troubles.
    Notice: this clip is not inplace.
            But, for clipped values, the gradients will always be passed backwards.
            This is useful when you want `clip` as a value-normalizer, but don not want the gradient to vanish.
    """
    minv, maxv = sorted((max_or_min, min_or_max))
    greater_pos = (in_tensor.detach() > maxv).type_as(in_tensor)
    diff = (maxv - in_tensor.detach()) * greater_pos
    in_tensor = in_tensor + diff
    less_pos = (in_tensor.detach() < minv).type_as(in_tensor)
    diff = (minv - in_tensor.detach()) * less_pos
    in_tensor = in_tensor + diff
    return in_tensor


def get_bot(name=None, versionOrAlias=None):
    """
    Returns metadata information for a specific bot. You must provide the bot name and the bot version or alias.
    The GetBot operation requires permissions for the lex:GetBot action.
    See also: AWS API Documentation

    :example: response = client.get_bot(
        name='string',
        versionOrAlias='string'
    )

    :type name: string
    :param name: [REQUIRED]
            The name of the bot. The name is case sensitive.

    :type versionOrAlias: string
    :param versionOrAlias: [REQUIRED]
            The version or alias of the bot.

    :rtype: dict
    :return: {
        'name': 'string',
        'description': 'string',
        'intents': [
            {
                'intentName': 'string',
                'intentVersion': 'string'
            },
        ],
        'clarificationPrompt': {
            'messages': [
                {
                    'contentType': 'PlainText'|'SSML',
                    'content': 'string'
                },
            ],
            'maxAttempts': 123,
            'responseCard': 'string'
        },
        'abortStatement': {
            'messages': [
                {
                    'contentType': 'PlainText'|'SSML',
                    'content': 'string'
                },
            ],
            'responseCard': 'string'
        },
        'status': 'BUILDING'|'READY'|'FAILED'|'NOT_BUILT',
        'failureReason': 'string',
        'lastUpdatedDate': datetime(2015, 1, 1),
        'createdDate': datetime(2015, 1, 1),
        'idleSessionTTLInSeconds': 123,
        'voiceId': 'string',
        'checksum': 'string',
        'version': 'string',
        'locale': 'en-US',
        'childDirected': True|False
    }

    """
    pass


def multires_base_apply(modifier: str=''):
    """Modify the base mesh to conform to the displaced mesh

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    """
    pass


def isfloat(val):
    """
    Returns True if val is float, else False.
    """
    try:
        float(val)
        return True
    except ValueError:
        return False


def std_iqr(x):
    """Robust estimation of the standard deviation, based on the inter-quartile
    (IQR) distance of x.
    This computes the IQR of x, and applies the Gaussian distribution
    correction, making it a consistent estimator of the standard-deviation
    (when the sample looks Gaussian with outliers).

    Parameters
    ----------
    x : `np.ndarray`
        Input vector

    Returns
    -------
    output : `float`
        A robust estimation of the standard deviation
    """
    from scipy.stats import iqr
    from scipy.special import erfinv
    correction = 2 ** 0.5 * erfinv(0.5)
    return correction * iqr(x)


def getIconExprObject():
    """ Get the expression object representing the icon for this type.
        """


def t_GET_LEASE_HOSTNAMES(t):
    """get-lease-hostnames"""
    return t


def view_url():
    """URL to use for viewing

        Files and Images get downloaded when they are directly
        called, instead of with /view appended.  We want to avoid that.
        """


def aslist(something):
    """If something is not a list already make it one, otherwise simply return something"""
    return something if isinstance(something, list) else [something]


def getstatusoutput(cmd):
    """Get the status and output from the execution of a command in a shell.

    Returns: (Integer, String)

    """
    import subprocess
    pipe = subprocess.Popen(cmd, shell=True, universal_newlines=True,
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = str.join('', pipe.stdout.readlines())
    status = pipe.wait()
    if status is None:
        status = 0
    return status, output


def _cells(nb):
    """Yield all cells in an nbformat-insensitive manner

    Source: https://github.com/kynan/nbstripout/blob/master/nbstripout/_utils.py#L27
    """
    if nb.nbformat < 4:
        for ws in nb.worksheets:
            for cell in ws.cells:
                yield cell
    else:
        for cell in nb.cells:
            yield cell


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

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


@classmethod
def deserialize(cls, serializer, s_state):
    """
        Serializes the instance using the provided serializer.

        :type  serializer: :class:`SpiffWorkflow.serializer.base.Serializer`
        :param serializer: The serializer to use.
        :rtype:  object
        :returns: The serialized object.
        """
    return serializer.deserialize_pathattrib(s_state)


def get_label_identifier(label, current_file):
    """Return unique label identifier

    Parameters
    ----------
    label : str
        Database-internal label
    current_file
        Yielded by pyannote.database protocols

    Returns
    -------
    unique_label : str
        Global label
    """
    database = current_file['database']
    return database + '|' + label


def _get_queue_arguments(rabbit_ha_queues, rabbit_queue_ttl):
    """Construct the arguments for declaring a queue.

    If the rabbit_ha_queues option is set, we try to declare a mirrored queue
    as described here:

      http://www.rabbitmq.com/ha.html

    Setting x-ha-policy to all means that the queue will be mirrored
    to all nodes in the cluster. In RabbitMQ 3.0, queue mirroring is
    no longer controlled by the x-ha-policy argument when declaring a
    queue. If you just want to make sure that all queues (except those
    with auto-generated names) are mirrored across all nodes, run:
      rabbitmqctl set_policy HA '^(?!amq\\.).*' '{"ha-mode": "all"}'

    If the rabbit_queue_ttl option is > 0, then the queue is
    declared with the "Queue TTL" value as described here:

      https://www.rabbitmq.com/ttl.html

    Setting a queue TTL causes the queue to be automatically deleted
    if it is unused for the TTL duration.  This is a helpful safeguard
    to prevent queues with zero consumers from growing without bound.
    """
    args = {}
    if rabbit_ha_queues:
        args['x-ha-policy'] = 'all'
    if rabbit_queue_ttl > 0:
        args['x-expires'] = rabbit_queue_ttl * 1000
    return args


@classmethod
def is_datasource_for(cls, data, header, **kwargs):
    """Determines if header corresponds to an MDI image"""
    return header.get('instrume') == 'MDI' or header.get('camera') == 'MDI'


@classmethod
def from_httplib(cls, message):
    """Read headers from a Python 2 httplib message object."""
    headers = []
    for line in message.headers:
        if line.startswith((' ', '\t')):
            key, value = headers[-1]
            headers[-1] = key, value + '\r\n' + line.rstrip()
            continue
        key, value = line.split(':', 1)
        headers.append((key, value.strip()))
    return cls(headers)


def saveinr(vol, h, fname):
    """
    Save a volume (described as a numpy array) to INR format.
    Code inspired by iso2mesh (http://iso2mesh.sf.net) by Q. Fang
    INPUTS:
    - vol: volume as numpy array
    - h: voxel sizes as list or numpy array
    - fname: filename for saving the inr file
    """
    fid = open(fname, 'wb')
    vol_type = vol.dtype
    if vol_type == 'uint8':
        btype = 'unsigned fixed'
        bitlen = 8
    elif vol_type == 'uint16':
        btype = 'unsigned fixed'
        bitlen = 16
    elif vol_type == 'float32':
        btype = 'float'
        bitlen = 32
    elif vol_type == 'float64':
        btype = 'float'
        bitlen = 64
    else:
        raise vol_type
    header = (
        '#INRIMAGE-4#{8:s}\nXDIM={0:d}\nYDIM={1:d}\nZDIM={2:d}\nVDIM=1\nTYPE={3:s}\n'
         + """PIXSIZE={4:d} bits
CPU=decm
VX={5:f}
VY={6:f}
VZ={7:f}
"""
        ).format(*vol.shape, btype, bitlen, h[0], h[1], h[2], '{')
    header = header + '\n' * (256 - 4 - len(header)) + '##}\n'
    fid.write(header.encode('ascii'))
    fid.write(vol.tobytes(order='F'))


@classmethod
def _reconstruct_nested_objects(cls, state_dict):
    """
        Nested serializable objects will be represented as dictionaries so we
        allow manual reconstruction of those objects in this method.

        By default just returns the state dictionary unmodified.
        """
    return state_dict


def are_of_compatible_type(val1, val2) ->bool:
    """
    Check if types are compatibles
    :param val1: the first value
    :param val2: the second value
    :return: True if types are compatible
    """
    return (isinstance(val1, val2.__class__) or isinstance(val1, (float,
        int)) and isinstance(val2, (float, int))) and isinstance(val1, (
        bool, str, float, int))


@classmethod
def get_object(cls, api_token, firewall_id):
    """
            Class method that will return a Firewall object by ID.
        """
    firewall = cls(token=api_token, id=firewall_id)
    firewall.load()
    return firewall


@staticmethod
def ccw(p1, p2, p3):
    """
        Three points are a counter-clockwise turn if ccw > 0, clockwise if
        ccw < 0, and collinear if ccw = 0 because ccw is a determinant that
        gives the signed area of the triangle formed by p1, p2 and p3.

        @type p1: tuple of (float, float)
        @type p2: tuple of (float, float)
        @type p3: tuple of (float, float)
        @rtype: float
        """
    return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0]
        )


def apply_repulsion(repulsion, nodes, barnes_hut_optimize=False, region=
    None, barnes_hut_theta=1.2):
    """
    Iterate through the nodes or edges and apply the forces directly to the node objects.
    """
    if not barnes_hut_optimize:
        for i in range(0, len(nodes)):
            for j in range(0, i):
                repulsion.apply_node_to_node(nodes[i], nodes[j])
    else:
        for i in range(0, len(nodes)):
            region.apply_force(nodes[i], repulsion, barnes_hut_theta)


def set_to_list(s: set) ->list:
    """
    Convert a set to a list.

    :param s: a set.
    :return: a list. The result is similar to list(s), but if the elements of the set are comparable, they appear in
        ascending order.

    >>> set_to_list({2, 42, 12})
    [2, 12, 42]
    """
    try:
        return sorted(s)
    except TypeError:
        return list(s)


def string_between(string, start, end):
    """
    Returns a new string between the start and end range.

    Args:
        string (str): the string to split.
        start (str): string to start the split at.
        end (str): string to stop the split at.

    Returns:
        new string between start and end.
    """
    try:
        return str(string).split(str(start), 1)[1].split(str(end))[0]
    except IndexError:
        return ''


def map_(func):
    """A strict (non-iterator), curried version of map for convenience in parser chains."""
    return lambda values: list(map(func, values))


def is_leaf(dmrs, nodeid):
    """
    Check if a node has no outgoing links
    """
    return not any(dmrs.get_out(nodeid, itr=True))


def renderHeadRow():
    """Render the table header rows."""


@classmethod
def get_keyrings(cls):
    """Get a list of currently available keyrings."""
    return cls.keyring.backend.get_all_keyring()


def roman2arabic(num):
    """Convert numbers from roman to arabic

    This function expects a string like XXII
    and outputs an integer
    """
    t = 0
    p = 0
    for r in num:
        n = 10 ** (205558 % ord(r) % 7) % 9995
        t += n - 2 * p % n
        p = n
    return t


@staticmethod
def atmospheric_pressure(z):
    """ Return the atmospheric pressure (:math:`P`) *[kPa]* as a function of the elevation above sea level as
        defined in `FAO 56 <http://www.fao.org/tempref/SD/Reserved/Agromet/PET/FAO_Irrigation_Drainage_Paper_56.pdf>`_
        (eq. 7, p. 31):

        .. math::

            P = 101.3\\left(\\frac{293-0.0065z}{293}\\right)^{5.26}

        The atmospheric pressure (:math:`P`) is the pressure exerted by the weight of the earth's atmosphere.
        Evaporation at high altitudes is promoted due to low atmospheric pressure as expressed in the psychrometric
        constant. The effect is, however, small and in the calculation procedures, the average value for a location
        is sufficient. A simplification of the ideal gas law, assuming :math:`20` *°C* for a standard atmosphere,
        can be employed to calculate :math:`P`
        (`FAO 56 <http://www.fao.org/tempref/SD/Reserved/Agromet/PET/FAO_Irrigation_Drainage_Paper_56.pdf>`_).

        :param z: elevation above sea level *[m]*
        :type z: float or np.array
        :return: (*float or np.array*) atmospheric pressure (:math:`P`) *[kPa]*
        """
    return 101.3 * ((293.0 - 0.0065 * z) / 293.0) ** 5.26


def assert_has_text(output, text):
    """ Asserts specified output contains the substring specified by
    the argument text."""
    assert output.find(text
        ) >= 0, "Output file did not contain expected text '%s' (output '%s')" % (
        text, output)


def init_email_error_handler(app):
    """
    Initialize a logger to send emails on error-level messages.
    Unhandled exceptions will now send an email message to app.config.ADMINS.
    """
    if app.debug:
        return
    host = app.config['MAIL_SERVER']
    port = app.config['MAIL_PORT']
    from_addr = app.config['MAIL_DEFAULT_SENDER']
    secure = () if app.config.get('MAIL_USE_TLS') else None
    to_addr_list = app.config['ADMINS']
    subject = app.config.get('APP_SYSTEM_ERROR_SUBJECT_LINE', 'System Error')
    import logging
    from logging.handlers import SMTPHandler
    mail_handler = SMTPHandler(mailhost=(host, port), fromaddr=from_addr,
        toaddrs=to_addr_list, subject=subject, credentials=None, secure=secure)
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)


def get_saved(obj):
    """ return the saved attribue of an object. """
    p = ''
    if '_container' in obj:
        p = getattr(obj._container, 'saved', '')
        if p:
            return p


def _dict_factory(cursor, row):
    """
    Creates a dict with row-names as keys for every query.
    """
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d


@classmethod
def local(cls, binding_str):
    """Parse local port forwarding binding string to dict."""
    return cls._parse(cls.local_pf_re, binding_str)


def file_size_display(size, precision):
    """Displays human-readable file information, to [precision] decimal places"""
    suffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
    suffixIndex = 0
    while size > 1024 and suffixIndex < 5:
        suffixIndex += 1
        size = size / 1024.0
    return '%.*f%s' % (precision, size, suffixes[suffixIndex])


def _extract_class_dict(cls):
    """Retrieve a copy of the dict of a class without the inherited methods"""
    clsdict = dict(cls.__dict__)
    if len(cls.__bases__) == 1:
        inherited_dict = cls.__bases__[0].__dict__
    else:
        inherited_dict = {}
        for base in reversed(cls.__bases__):
            inherited_dict.update(base.__dict__)
    to_remove = []
    for name, value in clsdict.items():
        try:
            base_value = inherited_dict[name]
            if value is base_value:
                to_remove.append(name)
        except KeyError:
            pass
    for name in to_remove:
        clsdict.pop(name)
    return clsdict


def write_log(response, filetype, name):
    """ Write a requests response object as a file for logging """
    with open(f'{name}_response.{filetype}', 'w') as response_file:
        response_file.writelines(response)


def Test(sentence='Default sentence'):
    """ Print sentence to screen - Test module activation

	Parameters
	----------
	sentence :	str
		input sentence

	Returns
	-------
	None

	Returns
	-------
	None

	Reference
	---------
	None

	Examples
	--------
	>>> import magnelPy.ML as ML
	>>> ML.regression.Test()
	Default sentence
 	>>> ML.regression.Test("Another test")
 	Another test
	"""
    print(sentence)


def provider_parser(subparser):
    """Configure provider parser for Zeit"""
    subparser.description = """
        Zeit Provider requires a token to access its API.
        You can generate one for your account on the following URL:
        https://zeit.co/account/tokens"""
    subparser.add_argument('--auth-token', help='specify your API token')


def _str(val):
    """Ensure that the val is the default str() type for python2 or 3."""
    if str == bytes:
        if isinstance(val, str):
            return val
        else:
            return str(val)
    elif isinstance(val, str):
        return val
    else:
        return str(val, 'ascii')


@classmethod
def _makeDocumentUrl(cls, documentId):
    """Make a chapter URL given a document ID."""
    return 'https://%s/publ/%s' % (cls.getSiteDomain(), documentId)


@staticmethod
def get_opt(opt_name, args):
    """Return option name and value.

        :param opt_name: name of the option, e.g., "username"
        :param args: parsed arguments
        """
    return opt_name, getattr(args, 'os_%s' % opt_name, None)


def optimize():
    """ optimize solr indexes """


def youtube_time_format(seconds):
    """Takes time in seconds, returns YouTube format time code."""
    hours = int(seconds / 3600)
    seconds = seconds - hours * 3600
    minutes = int(seconds / 60)
    rest = seconds - minutes * 60
    final_str = ''
    if hours:
        final_str += str(hours) + 'h'
    if minutes:
        final_str += str(minutes) + 'm'
    if seconds:
        final_str += str(rest) + 's'
    return final_str


def allocate(reservations, total=1.0):
    """
    Allocate resources among slices with specified and unspecified reservations.

    Returns a new list of values with the following properties:
    - Every value is >= the corresponding input value.
    - The result sums to `total`.

    Examples:
    allocate([0.25, None, None]) -> [0.5, 0.25, 0.25]
    allocate([0.4, None, None]) -> [0.6, 0.2, 0.2]
    allocate([0.2, 0.2, 0.2]) -> [0.33, 0.33, 0.33]
    allocate([None, None, None]) -> [0.33, 0.33, 0.33]
    allocate([0.5, 0.5, 0.5]) -> ERROR
    """
    n = len(reservations)
    if n <= 0:
        return []
    remaining = total
    for r in reservations:
        if r is not None:
            remaining -= r
    result = list(reservations)
    if remaining > 0:
        share = float(remaining) / n
        for i in range(n):
            if result[i] is None:
                result[i] = share
            else:
                result[i] += share
    elif remaining < 0:
        raise Exception('Resource allocation is infeasible (total {} > {})'
            .format(sum(result), total))
    return result


def negative(argument):
    """ Turn a number negative. """
    return -abs(int(argument))


def find_line_starting_with_seq(the_list, seq, from_index=0, to_index=-1):
    """
    Returns index of line in the document that starts with specified char sequence. Or -1 if sequence not found.
    :param the_list: list of strings
    :param seq: char sequence to find;
    :param from_index: index in the list;
    :param to_index: index in the list, open range; if is negative, the list will be searched till the end;
    :return: index of the first occurrence of 'seq' in the list or -1 if not found
    """
    if to_index < 0:
        to_index = len(the_list)
    if from_index > to_index:
        from_index = to_index
    for i in range(from_index, to_index):
        if the_list[i].startswith(seq):
            return i
    return -1


def swap4(data):
    """swap data elements in groups of 4"""
    size = 4
    nsets = len(data) // size
    if nsets <= 0:
        return
    for ind in range(nsets):
        off = ind * size
        v = data[off]
        data[off] = data[off + 3]
        data[off + 3] = v
        v = data[off + 1]
        data[off + 1] = data[off + 2]
        data[off + 2] = v


def bench1(x):
    """A benchmark function for test purposes.

        f(x) = x ** 2

    It has a single minima with f(x*) = 0 at x* = 0.
    """
    return x[0] ** 2


def missing_newline(physical_line):
    """

    >>> missing_newline('SELECT 1\\n')
    >>> missing_newline('SELECT 1')
    (8, 'W292 no newline at end of file')
    """
    if physical_line.rstrip() == physical_line:
        return len(physical_line), 'W292 no newline at end of file'


def received(item):
    """
        An item was received from 'upstream', i.e. the framework, or the
        lower-level data source that this L{ITube} is interacting with.

        @return: An iterable of values to propagate to the downstream drain
            attached to this L{ITube}.
        @rtype: iterable of L{ITube.outputType}
        """


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 reset_features_logging():
    """
        reset_features_logging

        Reset features logging mode

        @return: None
        """


def get_fileobject(title, objtype):
    """
    Returns the id of the object if it exists, otherwise returns
    False.

    Arguments:
    title -- The filename to be queried.
    objtype -- Image, Document from Wagtail.

    Returns:
    False if the object does not exist in this environment,
    object's integer ID if it does exist.
    """
    try:
        localobj = objtype.objects.get(file=title)
        if localobj:
            return localobj.id
    except objtype.DoesNotExist:
        return False
    return False


def atom_total_degree(atom):
    """The degree of an atom including Hs.

    Returns
    -------
    list
        List containing one int only.

    See Also
    --------
    atom_total_degree_one_hot
    atom_degree
    atom_degree_one_hot
    """
    return [atom.GetTotalDegree()]


def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None,
    HttpMethod=None):
    """
    Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
            ClientMethod.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
            default, the http method is whatever is used in the method's model.

    """
    pass


def define(name: str, value: str='') ->str:
    """
    Return C++ macro-string #define name value

    Used for header defines.

    Parameters
    ----------
    name : str
        Name of macro to be defined
    value : str, optional
        Value of defined macro (if any),

    Returns
    -------
    str:
        "#define name" or "#define name value"
    """
    return '#define {} {}'.format(name, value)


def test_invoke_method(restApiId=None, resourceId=None, httpMethod=None,
    pathWithQueryString=None, body=None, headers=None, clientCertificateId=
    None, stageVariables=None):
    """
    Simulate the execution of a  Method in your  RestApi with headers, parameters, and an incoming request body.
    See also: AWS API Documentation

    :example: response = client.test_invoke_method(
        restApiId='string',
        resourceId='string',
        httpMethod='string',
        pathWithQueryString='string',
        body='string',
        headers={
            'string': 'string'
        },
        clientCertificateId='string',
        stageVariables={
            'string': 'string'
        }
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            Specifies a test invoke method request's API identifier.

    :type resourceId: string
    :param resourceId: [REQUIRED]
            Specifies a test invoke method request's resource ID.

    :type httpMethod: string
    :param httpMethod: [REQUIRED]
            Specifies a test invoke method request's HTTP method.

    :type pathWithQueryString: string
    :param pathWithQueryString: The URI path, including query string, of the simulated invocation request. Use this to specify path parameters and query string parameters.

    :type body: string
    :param body: The simulated request body of an incoming invocation request.

    :type headers: dict
    :param headers: A key-value map of headers to simulate an incoming invocation request.
            (string) --
            (string) --

    :type clientCertificateId: string
    :param clientCertificateId: A ClientCertificate identifier to use in the test invocation. API Gateway will use the certificate when making the HTTPS request to the defined back-end endpoint.

    :type stageVariables: dict
    :param stageVariables: A key-value map of stage variables to simulate an invocation on a deployed Stage .
            (string) --
            (string) --

    :rtype: dict
    :return: {
        'status': 123,
        'body': 'string',
        'headers': {
            'string': 'string'
        },
        'log': 'string',
        'latency': 123
    }

    :returns:
    (string) --
    (string) --

    """
    pass


def thermal_diffusivity(thermal_conductivity, specific_heat_capacity, density):
    """
    The rate of transfer of heat of a material from the hot end to the cold end.

    .. math:

       \\alpha = \\frac{k}{\\rho c_p}

    Args:
        thermal_conductivity: :math:`k`
        specific_heat_capacity: :math:`c_p`
        density: :math:`\\rho`

    Returns:

    """
    return thermal_conductivity / (density * specific_heat_capacity)


def parse_cmdLine_instructions(args):
    """ Parses command-line arguments.  These are
        instruction to the manager to create instances and
        put settings. """
    instructions = dict()
    rargs = list()
    for arg in args:
        if arg[:2] == '--':
            tmp = arg[2:]
            bits = tmp.split('=', 1)
            if len(bits) == 1:
                bits.append('')
            instructions[bits[0]] = bits[1]
        else:
            rargs.append(arg)
    return instructions, rargs


def decode_response_version_from_config(confbytes: bytes) ->str:
    """ Decode the string version from the bytearray response from Ledger device """
    return '{}.{}.{}'.format(confbytes[1], confbytes[2], confbytes[3])


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

    The ".dev0" means dirty.

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


def merge_dicts(*dicts):
    """
    >>> sorted(merge_dicts({'foo': 'bar'}, {'bar': 'baz'}).items())
    [('bar', 'baz'), ('foo', 'bar')]
    """
    res = {}
    for d in dicts:
        res.update(d)
    return res


def listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=438):
    """
        Listen on a datagram UNIX socket.

        @param address: a path to a unix socket on the filesystem.

        @param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.

        @param maxPacketSize: maximum packet size to accept

        @param mode: The mode (B{not} umask) to set on the unix socket.  See
            platform specific documentation for information about how this
            might affect connection attempts.
        @type mode: C{int}

        @return: An object which provides L{IListeningPort}.
        """


def iter_transactions_range(cursor, start=None, stop=None):
    """
        Return an indexable object over the transactions in the given range, oldest
        first.

        Includes packed transactions.

        Has an object with the properties ``tid_int``, ``username``
        (bytes) ``description`` (bytes) ``extension`` (bytes) and
        ``packed`` (boolean) for each transaction.
        """


def get_selected_fedge() ->'freestyle.types.FEdge':
    """Returns the selected FEdge.

    :return:  The selected FEdge.
    """
    pass


def getAllUtilitiesRegisteredFor(interface):
    """Return all registered utilities for an interface

        This includes overridden utilities.

        An iterable of utility instances is returned.  No names are
        returned.
        """


def dynamics(state, time, config, intervention=None):
    """Update equations for the Zika simulaton.

    Parameters
    ----------
        state:  np.ndarray, list, or tuple
            State of the dynamics
        time:   float
        config: hiv.Config
            Simulator configuration object that determines the coefficients
        intervantion: hiv.Intervention
            Simulator intervention object that determines when/how to update the
            dynamics.

    Returns
    -------
        ds_dt: list
            Derivative of the dynamics with respect to time

    """
    if intervention and time >= intervention.time:
        config = config.update(intervention)
    S_h, A_h, I_h, R_h, S_v, E_v, I_v, N_h, N_v = state
    newly_susceptible = config.lambda_h + config.recovery_rate * (1.0 -
        config.nu) * I_h + config.varphi_h * R_h
    exposure_rate = (config.mosquito_human_infection_rate * I_v * S_h / N_h +
        config.asymptomatic_infection_rate * A_h * S_h / N_h + config.
        symptomatic_infection_rate * I_h * S_h / N_h)
    dS_h = newly_susceptible - exposure_rate - config.mu_h * S_h
    dA_h = exposure_rate - config.alpha_h * A_h - config.mu_h * A_h
    dI_h = config.alpha_h * A_h - (config.recovery_rate + config.mu_h +
        config.delta_h) * I_h
    dR_h = config.recovery_rate * config.nu * I_h - (config.varphi_h +
        config.mu_h) * R_h
    dN_h = config.lambda_h - config.delta_h * I_h - config.mu_h * N_h
    dS_v = (config.lambda_v - config.human_mosquito_infection_rate * I_h *
        S_v / N_h - config.mu_v * S_v - config.theta * config.
        indoor_spray_use * S_v)
    dE_v = (config.human_mosquito_infection_rate * I_h * S_v / N_h - config
        .alpha_v * E_v - config.mu_v * E_v - config.theta * config.
        indoor_spray_use * E_v)
    dI_v = (config.alpha_v * E_v - config.mu_v * I_v - config.theta *
        config.indoor_spray_use * I_v)
    dN_v = config.lambda_v - (config.mu_v + config.theta * config.
        indoor_spray_use) * N_v
    ds_dt = [dS_h, dA_h, dI_h, dR_h, dS_v, dE_v, dI_v, dN_h, dN_v]
    return ds_dt


def convert_cbaois_to_kpsois(cbaois):
    """Convert coordinate-based augmentables to KeypointsOnImage instances.

    Added in 0.4.0.

    Parameters
    ----------
    cbaois : list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or imgaug.augmentables.bbs.BoundingBoxesOnImage or imgaug.augmentables.bbs.PolygonsOnImage or imgaug.augmentables.bbs.LineStringsOnImage
        Coordinate-based augmentables to convert, e.g. bounding boxes.

    Returns
    -------
    list of imgaug.augmentables.kps.KeypointsOnImage or imgaug.augmentables.kps.KeypointsOnImage
        ``KeypointsOnImage`` instances containing the coordinates of input
        `cbaois`.

    """
    if not isinstance(cbaois, list):
        return cbaois.to_keypoints_on_image()
    kpsois = []
    for cbaoi in cbaois:
        kpsois.append(cbaoi.to_keypoints_on_image())
    return kpsois


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

        :param SfExternalInviteWarnDetails val:
        :rtype: EventDetails
        """
    return cls('sf_external_invite_warn_details', val)


def _update_to_merge_list(to_merge, subexon_1, subexon_2):
    """
    Add subexon_1 and subexon_2 to the to_merge list.

    >>> _update_to_merge_list([], 1, 2)
    [{1, 2}]
    >>> _update_to_merge_list([{1, 2}], 2, 3)
    [{1, 2, 3}]
    >>> _update_to_merge_list([{1, 2}], 8, 9)
    [{1, 2}, {8, 9}]
    """
    group = {subexon_1, subexon_2}
    for existing_group in to_merge:
        if existing_group.intersection(group):
            existing_group.update(group)
            return to_merge
    to_merge.append(group)
    return to_merge


@staticmethod
def consumer_work(cfg, data):
    """
        function specify how the consumer processses the data from producers.

        Args:
            cfg (easycore.common.config.CfgNode): config of this process, you can use it to get data from
                `consumer_init` function and transfer data to the next `consumer_work` and `consumer_end`
                function.
        """
    pass


@classmethod
def get_social_auth_for_user(cls, user, provider=None, id=None):
    """Return all the UserSocialAuth instances for given user"""
    raise NotImplementedError('Implement in subclass')


@classmethod
def generate_single_string_sql_eq(cls, column_name, filter_value):
    """Return tuple with sql and replacement.

        This function builds the sql partial and replacement dict for
        an equivalency match for one value against a single column in
        the database.

        Args:
            column_name (str): Name of column in DB.
            filter_value (str): This is what we look for in the column.

        Returns:
            tuple: Item 0 contains the SQL partial string. Item 1 contains
                the replacement dictionary.

        """
    sql = '{} = :{}'.format(column_name, column_name)
    replacement = {column_name: str(filter_value)}
    return sql, replacement


def per_sqmi(value, square_miles, fail_silently=True):
    """
    Accepts two numbers, a value and an area, and returns the
    per square mile rate.

    Not much more going on here than a simple bit of division.

    If you divide into zero -- an illegal operation -- a null value
    is returned by default. If you prefer for an error to be raised,
    set the kwarg 'fail_silently' to False.

    h3. Example usage

        >> import calculate
        >> calculate.per_sqmi(20, 10)
        2.0
    """
    try:
        return float(value) / square_miles
    except ZeroDivisionError:
        if fail_silently:
            return None
        else:
            raise ZeroDivisionError("Sorry. You can't divide into zero.")


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


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

        :param NonTrustedTeamDetails val:
        :rtype: FederationStatusChangeAdditionalInfo
        """
    return cls('non_trusted_team_details', val)


def default_label(index):
    """Default label for a node."""
    return 'n{}'.format(index)


def vertex_group_copy_to_selected():
    """Replace vertex groups of selected objects by vertex groups of active object

    """
    pass


@classmethod
def _get_apic_classes(cls):
    """
        Get the APIC classes used by this acitoolkit class.

        :returns: list of strings containing APIC class names
        """
    return ['l2extOut']


def get_data_index(hdul):
    """
    Get the index of the data HDU in the given HDUList, and return (i, data).
    Raises ValueError if no data HDU is found
    """
    for i, hdu in enumerate(hdul):
        if hdu.data is not None and hdu.data.ndim == 2:
            return i, hdu.data
    raise ValueError('no data HDU found')


def map_bedtools_options(bedtools_options):
    """
    Create a dict of bedtools intersect options
    """
    kwargs = {}
    try:
        for args in bedtools_options.split(','):
            args = args.split('=')
            if len(args) > 1:
                if args[1] in ['true', 'True']:
                    kwargs[args[0]] = True
                else:
                    kwargs[args[0]] = args[1]
            else:
                kwargs[args[0]] = True
    except:
        pass
    return kwargs


def format_url(url):
    """if url not contains schema, add shema
    eg. httpbin.org -> http://httpbin.org"""
    if not (url.startswith('//') or url.startswith('http')):
        url = 'http://' + url
    return url


def write_xyz_file(name, names, positions):
    """Create an xyz file

    Parameters
    ----------
    name : str
      output file name
    names : list
      atom names
    positions : np.ndarray
      positions of atoms
    """
    with open(name, 'w') as out:
        out.write('{}\n\n'.format(len(positions)))
        for nm, (x, y, z) in zip(names, positions):
            out.write('{} {} {} {}\n'.format(nm, x, y, z))


def convert_docker_params(stack_env=None):
    """Convert Docker* params to "Container" varients for compatibility.

    """
    if stack_env:
        pd = stack_env.get('parameter_defaults', {})
        for k, v in pd.copy().items():
            if k.startswith('Docker') and k.endswith('Image'):
                name = 'Container%s' % k[6:]
                pd.setdefault(name, v)


def _jmomentsurfaceIntegrand(vz, vR, vT, R, z, df, sigmaR1, gamma, sigmaz1,
    n, m, o):
    """Internal function that is the integrand for the vmomentsurface mass integration"""
    return df(R, vR * sigmaR1, vT * sigmaR1 * gamma, z, vz * sigmaz1,
        use_physical=False, func=lambda x, y, z: x ** n * y ** m * z ** o)


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 get_histogram_from_args(parser, args):
    """To be used with add_histogram_args.

	Check that the supplied arguments are valid and returns the number of bins
	requested.

	Returns
	-------
	int
		The number of bins to use in the wire-length histogram.
	"""
    if args.histogram_bins < 1:
        parser.error('--histogram-bins must be at least 1')
    return args.histogram_bins


@classmethod
def copy(cls, options=None):
    """Copy an activation key"""
    cls.command_sub = 'copy'
    return cls.execute(cls._construct_command(options))


def pickle_processor(processor, outfile, **kwargs):
    """
    Pickle the Processor to a file.

    Parameters
    ----------
    processor : :class:`Processor` instance
        Processor to be pickled.
    outfile : str or file handle
        Output file (handle) where to pickle it.

    """
    processor.dump(outfile)


def select_linked_pick(extend: bool=False, deselect: bool=False, location:
    float=(0.0, 0.0)):
    """Select all UV vertices linked under the mouse

    :param extend: Extend, Extend selection rather than clearing the existing selection
    :type extend: bool
    :param deselect: Deselect, Deselect linked UV vertices rather than selecting them
    :type deselect: bool
    :param location: Location, Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds
    :type location: float
    """
    pass


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


@classmethod
def get_name(cls, name):
    """
        Return the calendar id of the name
        """
    calendar_id = cls._get_name_cache.get(name, default=-1)
    if calendar_id == -1:
        calendars = cls.search([('name', '=', name)], limit=1)
        if calendars:
            calendar_id = calendars[0].id
        else:
            calendar_id = None
        cls._get_name_cache.set(name, calendar_id)
    return calendar_id


def is_empty(value):
    """Test if value is None, empty string, list, tuple or dict.

    @rtype: bool
    """
    if value is None:
        return True
    if type(value) in (list, tuple, dict):
        return len(value) == 0
    if not value:
        return True
    return False


def comma_separated_pairs(value):
    """Handle comma-separated key/values passed in command-line."""
    pairs = value.split(',')
    results = {}
    for pair in pairs:
        key, pair_value = pair.split('=')
        results[key] = pair_value
    return results


def contrast_ratio(l1, l2):
    """Given two relative luminances, calculate their contrast ratio."""
    return (l1 + 0.05) / (l2 + 0.05)


def p_if_stmt(p):
    """if_stmt : IF OPEN_PAREN expression CLOSE_PAREN maybe_nline suite
               | if_stmt ELSEIF OPEN_PAREN expression CLOSE_PAREN maybe_nline suite """
    if len(p) == 7:
        p[0] = ['IF_EXPR']
        p[0].append(p[3])
        p[0].append(p[6])
        p[0].append([])
    else:
        p[0] = p[1]
        p[0][3].append([p[4], p[7]])


def sfloat(S):
    """convert a string to a float, treating an all-blank string as zero"""
    if S.strip():
        return float(S)
    else:
        return 0.0


@staticmethod
def get_floating_ip(node):
    """Get the floating ip for a vm.

        :param node: libcloud node object
        """
    for key in node.extra['addresses']:
        for network in node.extra['addresses'][key]:
            if network['OS-EXT-IPS:type'] != 'floating':
                continue
            return network['addr']


def disconnectClient():
    """Drop connection to client"""


@staticmethod
def _escape_string(string):
    """
        Replace quotes with two quotes.
        :param string: string to escape
        :return: escaped string
        """
    return string.replace("'", "''")


def create_account(Email=None, AccountName=None, RoleName=None,
    IamUserAccessToBilling=None):
    """
    Creates an AWS account that is automatically a member of the organization whose credentials made the request. This is an asynchronous request that AWS performs in the background. If you want to check the status of the request later, you need the OperationId response element from this operation to provide as a parameter to the  DescribeCreateAccountStatus operation.
    AWS Organizations preconfigures the new member account with a role (named OrganizationAccountAccessRole by default) that grants administrator permissions to the new account. Principals in the master account can assume the role. AWS Organizations clones the company name and address information for the new account from the organization's master account.
    For more information about creating accounts, see Creating an AWS Account in Your Organization in the AWS Organizations User Guide .
    This operation can be called only from the organization's master account.
    See also: AWS API Documentation

    :example: response = client.create_account(
        Email='string',
        AccountName='string',
        RoleName='string',
        IamUserAccessToBilling='ALLOW'|'DENY'
    )

    :type Email: string
    :param Email: [REQUIRED]
            The email address of the owner to assign to the new member account. This email address must not already be associated with another AWS account.

    :type AccountName: string
    :param AccountName: [REQUIRED]
            The friendly name of the member account.

    :type RoleName: string
    :param RoleName: (Optional)
            The name of an IAM role that Organizations automatically preconfigures in the new member account. This role trusts the master account, allowing users in the master account to assume the role, as permitted by the master account administrator. The role has administrator permissions in the new member account.
            If you do not specify this parameter, the role name defaults to OrganizationAccountAccessRole .
            For more information about how to use this role to access the member account, see Accessing and Administering the Member Accounts in Your Organization in the AWS Organizations User Guide , and steps 2 and 3 in Tutorial: Delegate Access Across AWS Accounts Using IAM Roles in the IAM User Guide .
            The regex pattern that is used to validate this parameter is a string of characters that can consist of uppercase letters, lowercase letters, digits with no spaces, and any of the following characters: =,.@-

    :type IamUserAccessToBilling: string
    :param IamUserAccessToBilling: If set to ALLOW , the new account enables IAM users to access account billing information if they have the required permissions. If set to DENY , then only the root user of the new account can access account billing information. For more information, see Activating Access to the Billing and Cost Management Console in the AWS Billing and Cost Management User Guide .
            If you do not specify this parameter, the value defaults to ALLOW, and IAM users and roles with the required permissions can access billing information for the new account.

    :rtype: dict
    :return: {
        'CreateAccountStatus': {
            'Id': 'string',
            'AccountName': 'string',
            'State': 'IN_PROGRESS'|'SUCCEEDED'|'FAILED',
            'RequestedTimestamp': datetime(2015, 1, 1),
            'CompletedTimestamp': datetime(2015, 1, 1),
            'AccountId': 'string',
            'FailureReason': 'ACCOUNT_LIMIT_EXCEEDED'|'EMAIL_ALREADY_EXISTS'|'INVALID_ADDRESS'|'INVALID_EMAIL'|'INTERNAL_FAILURE'
        }
    }

    :returns:
    ACCOUNT_LIMIT_EXCEEDED: The account could not be created because you have reached the limit on the number of accounts in your organization.
    EMAIL_ALREADY_EXISTS: The account could not be created because another AWS account with that email address already exists.
    INVALID_ADDRESS: The account could not be created because the address you provided is not valid.
    INVALID_EMAIL: The account could not be created because the email address you provided is not valid.
    INTERNAL_FAILURE: The account could not be created because of an internal failure. Try again later. If the problem persists, contact Customer Support.

    """
    pass


def escape_rdn(rdn):
    """
    Escape rdn characters to prevent injection according to RFC 4514.
    """
    for char in ['\\', ',', '+', '"', '<', '>', ';', '=', '\x00']:
        rdn = rdn.replace(char, '\\' + char)
    if rdn[0] == '#' or rdn[0] == ' ':
        rdn = ''.join(('\\', rdn))
    if rdn[-1] == ' ':
        rdn = ''.join((rdn[:-1], '\\ '))
    return rdn


@staticmethod
def is_dbbc_e_firmware(entry):
    """
        Returns whether the setup entry represent a setup with e-series
        DBBC firmware (True|False).
        """
    if entry.dbbcfw == '':
        return False
    return entry.dbbcfw[-1] in ('E', 'F')


def downgrade():
    """Downgrade database."""


def cmd_writes(scope, samba, args):
    """Write STRING to ADDRESS.  A trailing 0 byte will stored after the
    end of the string.

    """
    addr = args[0]
    blist = bytearray(args[1].encode('utf-8'))
    for byte in blist:
        samba.write_byte(addr, int(byte))
        addr += 1
    samba.write_byte(addr, 0)


def select_border(pinned: bool=False, gesture_mode: int=0, xmin: int=0,
    xmax: int=0, ymin: int=0, ymax: int=0, extend: bool=True):
    """Select UV vertices using border selection

    :param pinned: Pinned, Border select pinned UVs only
    :type pinned: bool
    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


def smart_map(func, i, *args, **kwargs):
    """
    将单个对象或列表中的每个项传入给定的函数，并返回单个结果或列表结果，类似于 map 函数

    :param func: 传入到的函数
    :param i: 列表或单个对象
    :param args: func 函数所需的 args
    :param kwargs: func 函数所需的 kwargs
    :return: 若传入的为列表，则以列表返回每个结果，反之为单个结果
    """
    if isinstance(i, (list, tuple, set)):
        return list(map(lambda x: func(x, *args, **kwargs), i))
    else:
        return func(i, *args, **kwargs)


def flatten_list(l, ltypes=(list, tuple)):
    """Flatten a nested list.

    **Arguments:**

    - *l*: List (may be nested to an arbitrary depth)

          If the type of *l* is not in ltypes, then it is placed in a list.

    - *ltypes*: Tuple (not list) of accepted indexable types

    **Example:**

    >>> flatten_list([1, [2, 3, [4]]])
    [1, 2, 3, 4]
    """
    ltype = type(l)
    if ltype not in ltypes:
        return [l]
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], ltypes):
            if l[i]:
                l[i:i + 1] = l[i]
            else:
                l.pop(i)
                i -= 1
                break
        i += 1
    return ltype(l)


def formula(foyer_fiscal, period, parameters):
    """
        Renvoie True si le foyer est imposable, False sinon
        """
    iai = foyer_fiscal('iai', period)
    credits_impot = foyer_fiscal('credits_impot', period)
    cehr = foyer_fiscal('cehr', period)
    return iai - credits_impot + cehr > 0


def __new__(cls, obj, *args, **kwargs):
    """
        creates an proxy instance referencing `obj`. (obj, *args, **kwargs) are
        passed to this class' __init__, so deriving classes can define an
        __init__ method of their own.
        note: _class_proxy_cache is unique per deriving class (each deriving
        class must hold its own cache)
        """
    try:
        cache = cls.__dict__['_class_proxy_cache']
    except KeyError:
        cls._class_proxy_cache = cache = {}
    try:
        theclass = cache[obj.__class__]
    except KeyError:
        cache[obj.__class__] = theclass = cls._create_class_proxy(obj.__class__
            )
    ins = object.__new__(theclass)
    theclass.__init__(ins, obj, *args, **kwargs)
    return ins


@staticmethod
def _empty_iterable_exception():
    """
        Create the exception instance to be thrown when no descriptors are
        provided to ``build_index``/``update_index``.

        :return: ValueError instance to be thrown.
        :rtype: ValueError

        """
    return ValueError('No hash vectors in provided iterable.')


def lists_match(list_data, item_data):
    """
    Returns True if the two list items are of the same type,
    with the same delimiter and bullet character.  This is used
    in agglomerating list items into lists.
    """
    return list_data.get('type') == item_data.get('type') and list_data.get(
        'delimiter') == item_data.get('delimiter') and list_data.get(
        'bullet_char') == item_data.get('bullet_char')


def packed_unit8_to_int(in_array):
    """
    Packs a uint8 array into a single int.

    >>> packed_unit8_to_int(np.array([ 26, 105,  85], dtype=np.uint8))
    1730901

    :param in_array:
    :return:
    """
    num_i = int(0)
    for i, a in enumerate(reversed(in_array)):
        num_i += int(a) << 8 * i
    return num_i


def update_link_configuration(state, action):
    """Update link configuration"""
    return {**state, 'link_configuration': action['link_configuration']}


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


def ParseEnum(field, value):
    """Parse an enum value.

  The value can be specified by a number (the enum value), or by
  a string literal (the enum name).

  Args:
    field: Enum field descriptor.
    value: String value.

  Returns:
    Enum value number.

  Raises:
    ValueError: If the enum value could not be parsed.
  """
    enum_descriptor = field.enum_type
    try:
        number = int(value, 0)
    except ValueError:
        enum_value = enum_descriptor.values_by_name.get(value, None)
        if enum_value is None:
            raise ValueError('Enum type "%s" has no value named %s.' % (
                enum_descriptor.full_name, value))
    else:
        if hasattr(field.file, 'syntax'):
            if field.file.syntax == 'proto3':
                return number
        enum_value = enum_descriptor.values_by_number.get(number, None)
        if enum_value is None:
            raise ValueError('Enum type "%s" has no value with number %d.' %
                (enum_descriptor.full_name, number))
    return enum_value.number


@classmethod
def get(class_, options):
    """Get and convert PDF options to a dict"""
    if not options:
        return
    r = {}
    for option in options.split(','):
        if not option:
            continue
        elems = option.split('=')
        if len(elems) != 2:
            continue
        key, value = elems
        if not key or not value:
            continue
        if value in class_.values:
            value = class_.values[value]
        elif value.isdigit():
            value = int(value)
        r[key] = value
    return r


@classmethod
def _get_scom(cls):
    """Returns the SCOM interface on which the device can be reached.

        There may be more then on SCOM interface connected to the system.
        This method is used by the base class (ScomDevice) to receive the right
        SCOM interface.
        """
    pass


@classmethod
def from_frame(cls, frame):
    """Creates a quaternion object from a frame.

        Parameters
        ----------
        frame : :class:`compas.geometry.Frame`

        Returns
        -------
        :class:`compas.geometry.Quaternion`
            The new quaternion.

        Example
        -------
        >>> from compas.geometry import Frame
        >>> q = [1., -2., 3., -4.]
        >>> F = Frame.from_quaternion(q)
        >>> Q = Quaternion.from_frame(F)
        >>> allclose(list(Q.canonized()), quaternion_canonize(quaternion_unitize(q)))
        True
        """
    w, x, y, z = frame.quaternion
    return cls(w, x, y, z)


def filter_atoms(fhandle, atomname_set):
    """Removes specific atoms that do not match a given atom name.
    """
    records = 'ATOM', 'HETATM', 'ANISOU'
    for line in fhandle:
        if line.startswith(records):
            if line[12:16].strip() not in atomname_set:
                continue
        yield line


@classmethod
def close_registry_entry(cls, value):
    """Close a registry entry."""
    out = False
    if not value.closed:
        value.close()
        out = True
    return out


@classmethod
def list(cls, options=None):
    """Build foreman-maintain health list"""
    cls.command_sub = 'list'
    if options is None:
        options = {}
    result = cls._construct_command(options)
    return result


def num_months_between(start, end):
    """
    Returns number  of months between two dates.

    Ignores day of month.
    """
    m1 = start.year * 12 + (start.month - 1)
    m2 = end.year * 12 + (end.month - 1)
    return m2 - m1


def copy_ancestor_docstring(fn):
    """Copy docstring for method from superclass

    For this decorator to work, the class has to use the `InheritableDocstrings`
    metaclass.
    """
    raise RuntimeError(
        'Decorator can only be used in classes using the `InheritableDocstrings` metaclass'
        )


def mergeDataCodingTable(vartable, dctable):
    """Merges information from the data coding table into the variable
    table.

    Called by :func:`loadVariableTable`.

    :arg vartable: The variable table.
    :arg dctable:  The data coding table.
    """
    with_datacoding = vartable['DataCoding'].notna()
    for field in ['NAValues', 'RawLevels', 'NewLevels']:
        mask = vartable[field].isna() & with_datacoding
        newvals = vartable.loc[mask].merge(dctable, left_on='DataCoding',
            right_index=True, suffixes=('_v', '_dc'), copy=False)['{}_dc'.
            format(field)]
        vartable.loc[mask, field] = newvals


def convertTimeToTimeString(time):
    """
    Convert a time (float) to string --- [hh:mm:ss.ssss]
    """
    hours = int(time // (60 * 60))
    if hours > 23 or hours < 0:
        return ''
    time -= hours * 60 * 60
    minutes = int(time // 60)
    time -= minutes * 60
    seconds = time
    timeStr = '[{:02d}:{:02d}:{:07.4f}]'.format(hours, minutes, seconds)
    return timeStr


def rename(name, new_name, force=False):
    """Renames object from `name` to `new_name`. If `force` is ``True``
        then target is lost"""
    raise NotImplementedError


@classmethod
def infect(cls, graph, key, default_scope=None):
    """
        Forcibly convert an entry-point based factory to a ScopedFactory.

        Must be invoked before resolving the entry point.

        :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding

        """
    func = graph.factory_for(key)
    if isinstance(func, cls):
        func = func.func
    factory = cls(key, func, default_scope)
    graph._registry.factories[key] = factory
    return factory


@staticmethod
def _copy_element_meta_data_to_meta_file_data(meta_data, element_m,
    element_name, element_id):
    """Helper method to generate meta data for meta data file for the given element

        The methods loads teh meta data of the given element and copies it into the given meta data dictionary
        intended for being stored on the filesystem.

        :param meta_data: The meta data to be stored
        :param element_m: The element model to get the meta data from
        :param element_name: The name string of the element type in the dictionary
        :param element_id: The id of the element
        """
    meta_data_element_id = element_name + str(element_id)
    meta_data_element = element_m.meta
    meta_data[meta_data_element_id] = meta_data_element


def _accumulate(iterable):
    """Return running totals"""
    it = iter(iterable)
    total = next(it)
    yield [total[0], total[1]]
    for e1, e2 in it:
        total[0] = total[0] + e1
        total[1] = total[1] + e2
        yield [total[0], total[1]]


def get_stages(config):
    """
    Return a list of stages
    :param config:
    :return:
    """
    return config.get('stages', ['test'])


def unzip_package(package_path, target_path):
    """
    Unzip package in the target_path.

    The package path has the full path of the zipped file.

    For example: package_path = /workspace/ops.zip
                 target_path = /workspace/target/

    :param package_path: path of the package file
    :param target_path: target path to unzip the package into
    """
    import zipfile
    with zipfile.ZipFile(package_path, 'r') as zip_file:
        zip_file.extractall(target_path)


def get_principals_and_permissions():
    """Get all principal permission settings.

        Get the principal security assertions here in the form
        of a list of three tuple containing
        (permission id, principal id, setting)
        """


def ip_is_ipv6(ip):
    """IP address is IPv6 or not, return True if it is"""
    if ip.find(':') != -1:
        return True
    elif ip.find('.') != -1:
        return False
    else:
        raise ValueError(
            "Formatting error in IP address input. Contains neither ':' or '.'"
            )


def reinterpret(source, vocab=None):
    """Reinterpret *source* Semantic Pointer as part of vocabulary *vocab*.

    The *vocab* parameter can be set to *None* to clear the associated
    vocabulary and allow the *source* to be interpreted as part of the
    vocabulary of any Semantic Pointer it is combined with.
    """
    if hasattr(source, 'reinterpret'):
        return source.reinterpret(vocab)
    else:
        raise TypeError("bad operand type for 'reinterpret'")


def LevenshteinDistance(s, t):
    """字符串相似度算法（Levenshtein Distance算法）
  一个字符串可以通过增加一个字符，删除一个字符，替换一个字符得到另外一个
  字符串，假设，我们把从字符串A转换成字符串B，前面3种操作所执行的最少
  次数称为AB相似度
  这算法是由俄国科学家Levenshtein提出的。
  Step Description
  1 Set n to be the length of s.
    Set m to be the length of t.
    If n = 0, return m and exit.
    If m = 0, return n and exit.
    Construct a matrix containing 0..m rows and 0..n columns.
  2 Initialize the first row to 0..n.
    Initialize the first column to 0..m.
  3 Examine each character of s (i from 1 to n).
  4 Examine each character of t (j from 1 to m).
  5 If s[i] equals t[j], the cost is 0.
    If s[i] doesn't equal t[j], the cost is 1.
  6 Set cell d[i,j] of the matrix equal to the minimum of:
    a. The cell immediately above plus 1: d[i-1,j] + 1.
    b. The cell immediately to the left plus 1: d[i,j-1] + 1.
    c. The cell diagonally above and to the left plus the cost:
       d[i-1,j-1] + cost.
  7 After the iteration steps (3, 4, 5, 6) are complete, the distance is
    found in cell d[n,m]. """
    m, n = len(s), len(t)
    if not (m and n):
        return m or n
    matrix = [[(0) for i in range(n + 1)] for j in range(m + 1)]
    matrix[0] = list(range(n + 1))
    for i in range(m + 1):
        matrix[i][0] = i
    for i in range(m):
        for j in range(n):
            cost = int(s[i] != t[j])
            matrix[i + 1][j + 1] = min(matrix[i][j + 1] + 1, matrix[i + 1][
                j] + 1, matrix[i][j] + cost)
    return matrix[m][n]


def cleanup(achalls):
    """Revert changes and shutdown after challenges complete.

        This method should be able to revert all changes made by
        perform, even if perform exited abnormally.

        :param list achalls: Non-empty (guaranteed) list of
            :class:`~certbot.achallenges.AnnotatedChallenge`
            instances, a subset of those previously passed to :func:`perform`.

        :raises PluginError: if original configuration cannot be restored

        """


def truncate_tail(node, xpath):
    """
    Find sub-node by its xpath and remove it and all adjacent nodes following
    after found node.
    """
    subnode = node.xpath(xpath)[0]
    for item in subnode.xpath('following-sibling::*'):
        item.getparent().remove(item)
    subnode.getparent().remove(subnode)


@classmethod
def next_text_version(cls, text):
    """Method which returns next number from the string.

        From string ``build10s`` it returns 11.

        :param str text: Line to search in.
        :return: Next number
        :rtype: int
        """
    return 1 + cls.parse_text_version(text)


def add_point_slide(PAINTCURVE_OT_add_point=None, PAINTCURVE_OT_slide=None):
    """Add new curve point and slide it

    :param PAINTCURVE_OT_add_point: Add New Paint Curve Point, Add New Paint Curve Point
    :param PAINTCURVE_OT_slide: Slide Paint Curve Point, Select and slide paint curve point
    """
    pass


def is_redirection(status):
    """
    Check if HTTP status code is redirection.

    :param status: http status code
    :returns: True if status is redirection, else False
    """
    return 300 <= status <= 399


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 color_true_green(val):
    """DataFrame Styler:
    Changes text color to green if value is True
    Ex: style_df = df.style.applymap(color_true_green)
        style_df #to display"""
    color = 'green' if val == True else 'black'
    return f'color: {color}'


@classmethod
def get_offset(cls, idx):
    """Shorthand for self.get_type().get_offset(idx)."""
    return cls.get_type().get_offset(idx)


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


def list(project):
    """Return the list of versions which have eggs stored (for the given
        project) in order (the latest version is the currently used)."""


@classmethod
def execute(cls, cursor, query: str, **kwargs):
    """
        Execute a SQL query

        :param cursor: Cursor instance
        :param query: Query to execute
        :param kwargs: kwargs to be passed to cursor.execute()
        :return:
        """
    if cls.arraysize:
        cursor.arraysize = cls.arraysize
    cursor.execute(query)


def reset_cache():
    """Reset the cache, mainly for testing purposes and update
    availability_zone for host aggregate
    """
    global MC
    MC = None


def copy_prev_settings():
    """Copy settings from previous version

    """
    pass


def split_signature(signature):
    """Split the given signature

    :param signature:
    :rtype: str, str
    :return: The r part for signature, The s part for signature
    """
    if not signature:
        raise ValueError(
            "Missing the required parameter 'signature' when calling split_signature"
            )
    if signature.startswith('0x'):
        signature = signature[2:]
    sig_half_len = int(len(signature) / 2)
    r = '0x' + signature[:sig_half_len]
    s = '0x' + signature[sig_half_len:]
    return r, s


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``OverlayDisplayToolBar`` is only intended to be added to
        :class:`.OrthoPanel`, :class:`.LightBoxPanel`, or
        :class:`.Scene3DPanel` views.
        """
    from fsleyes.views.orthopanel import OrthoPanel
    from fsleyes.views.lightboxpanel import LightBoxPanel
    from fsleyes.views.scene3dpanel import Scene3DPanel
    return [OrthoPanel, LightBoxPanel, Scene3DPanel]