def deletePloneFolders(p):
    """Delete the standard Plone stuff that we don't need
    """
    existing = p.objectIds()
    itemsToDelete = ['Members', 'news', 'events', 'front-page']
    for item in itemsToDelete:
        if item in existing:
            p.manage_delObjects(item)


def is_none(value):
    """Checks if `value` is `None`.

    Args:
        value (mixed): Value to check.

    Returns:
        bool: Whether `value` is ``None``.

    Example:

        >>> is_none(None)
        True
        >>> is_none(False)
        False

    .. versionadded:: 1.0.0
    """
    return value is None


@classmethod
def create_new_file(cls, filename, language, base):
    """Handle creation of new translation file."""
    if base:
        store = cls.parse_store(base)
        cls.untranslate_store(store, language)
        store.savefile(filename)
    elif cls.new_translation is None:
        raise ValueError('Not supported')
    else:
        with open(filename, 'wb') as output:
            output.write(cls.get_new_file_content())


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 _write_datetime(value):
    """Helper that validates a date time object."""
    if value.utcoffset() is None:
        raise ValueError('Expected datetime with time zone')
    return value.isoformat()


def resolve_labels(model_label):
    """
    Seperate model_label into parts.
    Returns dictionary with app, model and app_model strings.
    """
    labels = {}
    labels['app'] = model_label.split('.')[0]
    labels['model'] = model_label.split('.')[-1]
    labels['app_model'] = '%s.%s' % (labels['app'], labels['model'])
    return labels


def reply(zelf, *args, **kwargs):
    """ send reply to origin. """
    if 'outer' in zelf:
        zelf.outer.write(str(args[0]) + '\n')
        zelf.outer.flush()
        return
    txt = args[0]
    if 'channel' in zelf:
        zelf._target.say(zelf.channel, txt)
    else:
        zelf._target.say(zelf.origin, txt)


def p_option_header(p):
    """ OPTION :   HEADERVALUE """
    p[0] = p[1]


def case_toggle():
    """Toggle font case

    """
    pass


@classmethod
def get_friendly_name(cls):
    """Returns a human-readable name of the curve that can be
        used in messages."""
    return 'concentrated ROC curve'


def move_dates(apps, schema_editor):
    """Move dates to models."""
    RelayDomain = apps.get_model('relaydomains', 'RelayDomain')
    for model in [RelayDomain]:
        for instance in model.objects.all():
            instance.creation = instance.dates.creation
            instance.last_modification = instance.dates.last_modification
            instance.save()


def merge(base, custom):
    """
	Create a new font by choosing glyphs from two other fonts.

	:param Font base: The lower-priority font.
	:param Font custom: The higher-priority font.
	:returns: A font where each glyph comes from ``base`` or ``custom``.

	For any given codepoint, the resulting font will use the corresponding
	glyph from ``custom`` if there is one, falling back to the glyph from
	``base``. The new font's properties and other metadata are all copied
	from ``custom``.
	"""
    res = custom.copy()
    for cp in base.codepoints():
        if cp not in res:
            old_glyph = base[cp]
            res.new_glyph_from_data(old_glyph.name, old_glyph.get_data(),
                old_glyph.bbX, old_glyph.bbY, old_glyph.bbW, old_glyph.bbH,
                old_glyph.advance, old_glyph.codepoint)
    return res


def list_cpio(archive, compression, cmd, verbosity, interactive):
    """List a CPIO archive."""
    cmdlist = [cmd, '-i', '-t']
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.extend(['-F', archive])
    return cmdlist


def __init__(content):
    """ The object needs to be initalised with the data content
        """


def iter_except(func, exception, first=None):
    """ Call a function repeatedly until an exception is raised.

    Converts a call-until-exception interface to an iterator interface.
    Like builtins.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.

    Examples:
        iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator
        iter_except(d.popitem, KeyError)                         # non-blocking dict iterator
        iter_except(d.popleft, IndexError)                       # non-blocking deque iterator
        iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue
        iter_except(s.pop, KeyError)                             # non-blocking set iterator

    """
    try:
        if first is not None:
            yield first()
        while True:
            yield func()
    except exception:
        pass


def threshold_propagator(P, estimated_snr=15.0):
    """
    Applies hard threshold on the propagator to remove background noise for the
    deconvolution.
    """
    P_thresholded = P.copy()
    threshold = P_thresholded.max() / float(estimated_snr)
    P_thresholded[P_thresholded < threshold] = 0
    return P_thresholded / P_thresholded.sum()


def _bisearch(ucs, table, ubound):
    """
    Auxiliary function for binary search in interval table.

    :arg int ucs: Ordinal value of unicode character.
    :arg list table: List of starting and ending ranges of ordinal values,
        in form of ``[(start, end), ...]``.
    :rtype: int
    :returns: 1 if ordinal value ucs is found within lookup table, else 0.
    """
    lbound = 0
    if ucs < table[0][0] or ucs > table[ubound][1]:
        return 0
    while ubound >= lbound:
        mid = (lbound + ubound) // 2
        if ucs > table[mid][1]:
            lbound = mid + 1
        elif ucs < table[mid][0]:
            ubound = mid - 1
        else:
            return 1
    return 0


def format_name(name, depth=0):
    """Format a string for nested data printing

    Args:
        name (str): input string
        depth (int, optional): depth of the nested information
    Returns:
        str: formatted string
    """
    if depth == 0:
        return name
    elif depth == 1:
        return f'├─{name}'
    else:
        return f"{'|    ' * (depth - 1)}└─{name}"


def _handle_debug(config, debug_enabled):
    """ Only modify debug if it was specified.
    """
    if debug_enabled is None:
        return
    elif debug_enabled:
        config.debug_mode = True
    else:
        config.debug_mode = False


def robustness(ds, name='PCM_POST', classdimname='pcm_class', outname=
    'PCM_ROBUSTNESS'):
    """ Compute classification robustness

        Parameters
        ----------
        name: str, default is 'PCM_POST'
            Name of the :class:`xarray.DataArray` with prediction probability (posteriors)

        classdimname: str, default is 'pcm_class'
            Name of the dimension holding classes

        outname: 'PCM_ROBUSTNESS' or str
            Name of the :class:`xarray.DataArray` with robustness

        inplace: boolean, False by default
            If False, return a :class:`xarray.DataArray` with robustness
            If True, return the input :class:`xarray.Dataset` with robustness added as a new :class:`xarray.DataArray`

        Returns
        -------
        :class:`xarray.Dataset` if inplace=True
        or
        :class:`xarray.DataArray` if inplace=False

    """
    maxpost = ds[name].max(dim=classdimname)
    K = len(ds[classdimname])
    robust = (maxpost - 1.0 / K) * K / (K - 1.0)
    id = dict()
    id[classdimname] = 0
    da = ds[name][id].rename(outname)
    da.values = robust
    da.attrs['long_name'] = 'PCM classification robustness'
    da.attrs['units'] = ''
    da.attrs['valid_min'] = 0
    da.attrs['valid_max'] = 1
    da.attrs['llh'] = ds[name].attrs['llh']
    return da


def items():
    """The key/value pairs of the pending event data.

        Both the keys and values must be strings.
        """


def get_description():
    """Get dictionary specifying FOOOF attributes, and what kind of data they store.

    Returns
    -------
    attributes : dict
        Mapping of FOOOF object attributes, and what kind of data they are.

    Notes
    -----
    This function organizes public FOOOF object attributes into:

    - results : parameters for and measures of the model
    - settings : model settings
    - data : input data
    - meta_data : meta data of the inputs
    - arrays : data stored in arrays
    - model_components : component pieces of the model
    - descriptors : descriptors of the object status and model results
    """
    attributes = {'results': ['aperiodic_params_', 'gaussian_params_',
        'peak_params_', 'r_squared_', 'error_'], 'settings': [
        'peak_width_limits', 'max_n_peaks', 'min_peak_height',
        'peak_threshold', 'aperiodic_mode'], 'data': ['power_spectrum',
        'freq_range', 'freq_res'], 'meta_data': ['freq_range', 'freq_res'],
        'arrays': ['freqs', 'power_spectrum', 'aperiodic_params_',
        'peak_params_', 'gaussian_params_'], 'model_components': [
        'fooofed_spectrum_', '_spectrum_flat', '_spectrum_peak_rm',
        '_ap_fit', '_peak_fit'], 'descriptors': ['has_data', 'has_model',
        'n_peaks_']}
    return attributes


def _equal_phases(downloaded_phase, calculated_phase):
    """
    Compare calculated and downloaded phases.

    If the downloaded_phase is -1, this function returns True, otherwise,
    the phases are compared and True is returned if they are equal.

    >>> _equal_phases(0, 0)
    True
    >>> _equal_phases(-1, 1)
    True
    >>> _equal_phases(2, 1)
    False
    """
    if downloaded_phase != -1:
        if downloaded_phase != calculated_phase:
            return False
    return True


@classmethod
def parse(cls, name, data_size, reader, parsers):
    """given a 4 byte name, data_size int, BitstreamReader
        and dict of {"atom":handler} sub-parsers,
        returns an atom of this class"""
    assert name == b'data'
    return cls(*reader.parse('64p 16p 16u 16u 16p'))


def rank(items, item, max_rank=None):
    """Find the rank of 'item' in the list 'items',
    returning None if the item is missing, where the first element is
    considered rank=1.

    `items` -- `list` -- to search through

    `item` -- `any` -- target

    `max_rank` -- `int` or `None` -- stop the search early at this rank;
                  if not found, return `None`

    `return` -- `int` or `None` -- `rank >= 1`, or `None` if the item was
                not found
    """
    try:
        stop = max_rank if max_rank is not None else len(items)
        return 1 + items.index(item, 0, stop)
    except ValueError:
        return None


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


@classmethod
def from_script(cls, script):
    """Creates and address object from a Script object"""
    return cls(script=script)


def feather_weight_clear():
    """Reset the feather weight to zero

    """
    pass


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 delete():
    """
        Remove configurations for a given tile
        """


def verifyPayment(context, order):
    """checks whether the payment was successfull or not"""


def context(input):
    """Return the context/device of the input tensor.

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

    Returns
    -------
    Context object
        A framework-specific context object.
    """
    pass


@classmethod
def run_node(cls, node, inputs, device=None, outputs_info=None, **kwargs):
    """
        This method is not implemented as it is much more efficient
        to run a whole model than every node independently.
        """
    raise NotImplementedError(
        'It is much more efficient to run a whole model than every node independently.'
        )


def file_length(file_obj):
    """
    Returns the length in bytes of a given file object.
    Necessary because os.fstat only works on real files and not file-like
    objects. This works on more types of streams, primarily StringIO.
    """
    file_obj.seek(0, 2)
    length = file_obj.tell()
    file_obj.seek(0)
    return length


def identity(name, _):
    """
    Name-generating/mangling function that simply returns the name given it
    :param name: name of the attribute the host descriptor is stored under
    :param _: (unused) - the descriptor object the name is being generated/
    mangled for
    :return: `name`
    """
    return name


def del_cols(me, ids):
    """delete many cols with transparent index mapping."""
    me._colmap.delmany(ids, me._del_cols)


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


@staticmethod
def in_out_quint(progress):
    """.. image:: images/anim_in_out_quint.png
        """
    p = progress * 2
    if p < 1:
        return 0.5 * p * p * p * p * p
    p -= 2.0
    return 0.5 * (p * p * p * p * p + 2.0)


@classmethod
def from_values(cls, vals):
    """
        Returns a Layout given a list (or tuple) of viewable
        elements or just a single viewable element.
        """
    return cls(items=cls._process_items(vals))


def e_diss(defl, f_ts, dt, fo1):
    """This function calculates the tip-sample dissipation per oscillating period.

    Parameters
    ----------
    defl : numpy.ndarray
        tip deflection
    f_ts : numpy.ndarray
        tip-sample interacting force
    dt : float
        simulation timestep
    fo1 : float
        eigenmode resonance frequency

    Returns
    -------
    energy_diss/number_of_periods : float
        total dissipated energy per oscillating period
    """
    energy_diss = 0.0
    for i in range(1, len(defl) - 1):
        energy_diss -= f_ts[i] * (defl[i + 1] - defl[i - 1]) / 2.0
    total_time = dt * len(defl)
    period1 = 1.0 / fo1
    number_of_periods = total_time / period1
    return energy_diss / number_of_periods


def full_model_name(model, sep='.'):
    """Returns the "full name" of the given model, e.g. "contacts.Person" etc.
    """
    return model._meta.app_label + sep + model._meta.object_name


@staticmethod
def create_instance(class_: type, *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 _rebuild_reduction(cls, *args):
    """
    Global hook to rebuild a given class from its __reduce__ arguments.
    """
    return cls._rebuild(*args)


def default_wcs_grid(axes):
    """
    Apply some default `~astropy.visualization.wcsaxes.WCSAxes` grid
    formatting.

    Parameters
    ----------
    axes : `~astropy.visualization.wcsaxes.WCSAxes`
        The `~astropy.visualization.wcsaxes.WCSAxes` object to draw the world
        coordinate grid on.
    """
    axes.coords.grid(color='white', alpha=0.6, linestyle='dotted',
        linewidth=0.5)


def extract_haml(fileobj, keywords, comment_tags, options):
    """ babel translation token extract function for haml files """
    import haml
    from mako import lexer, parsetree
    from mako.ext.babelplugin import extract_nodes
    encoding = options.get('input_encoding', options.get('encoding', None))
    template_node = lexer.Lexer(haml.preprocessor(fileobj.read()),
        input_encoding=encoding).parse()
    for extracted in extract_nodes(template_node.get_children(), keywords,
        comment_tags, options):
        yield extracted


def _get_project_url_root(uri, roots):
    """Find the top-level project for some URL / file-path.

    Note:
        The matching `uri` must match an item `roots` exactly.

    Args:
        uri (str):
            The URL / file-path that presumably came from an intersphinx inventory
            file. This path is inside some Sphinx project (which we will find the root of).
        roots (iter[str]):
            Potential file paths / URLs that `uri` is a child of.

    Returns:
        str: The found root. If no root was found, return an empty string.

    """
    for root in roots:
        if uri.startswith(root):
            return root
    return ''


def GetBraviasNum(center, system):
    """Determine the Bravais lattice number, as used in GenHBravais

    :param center: one of: 'P', 'C', 'I', 'F', 'R' (see SGLatt from GSASIIspc.SpcGroup)
    :param system: one of 'cubic', 'hexagonal', 'tetragonal', 'orthorhombic', 'trigonal' (for R)
      'monoclinic', 'triclinic' (see SGSys from GSASIIspc.SpcGroup)
    :return: a number between 0 and 13
      or throws a ValueError exception if the combination of center, system is not found (i.e. non-standard)

    """
    if center.upper() == 'F' and system.lower() == 'cubic':
        return 0
    elif center.upper() == 'I' and system.lower() == 'cubic':
        return 1
    elif center.upper() == 'P' and system.lower() == 'cubic':
        return 2
    elif center.upper() == 'R' and system.lower() == 'trigonal':
        return 3
    elif center.upper() == 'P' and system.lower() == 'hexagonal':
        return 4
    elif center.upper() == 'I' and system.lower() == 'tetragonal':
        return 5
    elif center.upper() == 'P' and system.lower() == 'tetragonal':
        return 6
    elif center.upper() == 'F' and system.lower() == 'orthorhombic':
        return 7
    elif center.upper() == 'I' and system.lower() == 'orthorhombic':
        return 8
    elif center.upper() == 'A' and system.lower() == 'orthorhombic':
        return 9
    elif center.upper() == 'B' and system.lower() == 'orthorhombic':
        return 10
    elif center.upper() == 'C' and system.lower() == 'orthorhombic':
        return 11
    elif center.upper() == 'P' and system.lower() == 'orthorhombic':
        return 12
    elif center.upper() == 'C' and system.lower() == 'monoclinic':
        return 13
    elif center.upper() == 'P' and system.lower() == 'monoclinic':
        return 14
    elif center.upper() == 'P' and system.lower() == 'triclinic':
        return 15
    raise ValueError('non-standard Bravais lattice center=%s, cell=%s' % (
        center, system))


def format_relative_dirname(directory, base_directory):
    """Formats a relative directory path in a way that's compatible with the
    presigned POST URLs.

    Parameters
    ----------
    directory : `pathlib.Path`
        The directory to compute a relative path/name for.
    base_directory : `pathlib.Path`
        The base directory.

    Returns
    -------
    name : `str`
        The relative directory name.

        Examples:

        - ``"base/`` relative to ``"/base/"`` is ``"/"``.
        - ``"base/a/`` relative to ``"/base/"`` is ``"a/"``.
        - ``"base/a/b`` relative to ``"/base/"`` is ``"a/b/"``.
    """
    name = str(directory.relative_to(base_directory))
    if name == '.':
        return '/'
    elif not name.endswith('/'):
        return name + '/'
    else:
        return name


def remove(category_name, discriminator):
    """ Remove the IIntrospectable related to ``category_name`` and
        ``discriminator`` from the introspector, and fix up any relations
        that the introspectable participates in. This method will not raise
        an error if an introspectable related to the category name and
        discriminator does not exist."""


@property
def is_infinitesimal(G):
    """
        A game is infinitesimal if it is non-zero and smaller than any positive number and greater
        than any negative number. Equivalently, it's left and right stops are both zero. Note, this
        does not imply that an infinitesimal can not be positive (> 0) or negative (< 0).

        Returns
        -------
        infinitesimal : bool
            Whether the game is infinitesimal or not.
        """
    from .tools import left_stop, right_stop
    a = left_stop(G, adorn=False) == right_stop(G, adorn=False) == 0
    b = G != 0
    return a and b


def is_outside_of(i1, i2):
    """ Test whether the interval is outside of i2? """
    return i1.inf < i2.inf or i2.sup < i1.sup


def _parse_string(value):
    """Coerce value into a string.

    This is usually a no-op, but if value is a unicode string, it will be
    encoded as UTF-8 before returning.

    :param str value: Value to parse.
    :returns: str
    """
    if not isinstance(value, str):
        return value.decode('utf-8')
    return value


def version():
    """ Returns version string of this library. """
    from . import __version__
    return __version__


def get_object_torrent(Bucket=None, Key=None, RequestPayer=None):
    """
    Return torrent files from a bucket.
    See also: AWS API Documentation

    :example: response = client.get_object_torrent(
        Bucket='string',
        Key='string',
        RequestPayer='requester'
    )

    :type Bucket: string
    :param Bucket: [REQUIRED]

    :type Key: string
    :param Key: [REQUIRED]

    :type RequestPayer: string
    :param RequestPayer: Confirms that the requester knows that she or he will be charged for the request. Bucket owners need not specify this parameter in their requests. Documentation on downloading objects from requester pays buckets can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html

    :rtype: dict
    :return: {
        'Body': StreamingBody(),
        'RequestCharged': 'requester'
    }

    :returns:
    (dict) --
    Body (StreamingBody) --
    RequestCharged (string) -- If present, indicates that the requester was successfully charged for the request.

    """
    pass


def wf_action_external_status(node):
    """
    It returns the external status for an action node, or an empty string if the
    action has not being executed or it has not completed yet.
    """


@classmethod
def post(cls, func):
    """Create an authenticate object with a POST method

        Arguments:
            func: a function to decorate

        """
    return cls(func, method='POST')


def arrayReplaceAt(src: list, pos: int, newElements: list):
    """
  Remove element from array and put another array at those position.
  Useful for some operations with tokens
  """
    return src[0:pos] + newElements + src[pos + 1:]


def enqueue(_msg, _metadata=None, **_kws):
    """Store the message and metadata in the switchboard's queue.

        When metadata is not given, an empty metadata dictionary is used.  The
        keyword arguments are added to the metadata dictonary, with precedence
        given to the keyword arguments.

        The base name of the message file is returned.
        """


def renormalize_value(val, _min, _max):
    """
    Renormalize value `val` to value from interval specific for given parameter defined my `_min` and `_max`.

    :param val: float;
    :param _min: float;
    :param _max: float;
    :return: float;
    """
    return val * (_max - _min) + _min


@classmethod
def extensions(cls):
    """A list of file extensions of files which this process can process.
        """
    return cls._extensions


def _key_for_segment(segment, topic_words):
    """A segment may have a single number of an iterable of them."""
    segment_key = tuple(segment) if hasattr(segment, '__iter__') else segment
    return segment_key, topic_words


def frame_offset(delta: int=0):
    """Move current frame forward/backward by a given number

    :param delta: Delta
    :type delta: int
    """
    pass


@classmethod
def enable(cls):
    """Enables tracking security state changes.
        """
    return cls.build_send_payload('enable', {}), None


def format_float_or_int_string(text: str) ->str:
    """Formats a float string like "1.0"."""
    if '.' not in text:
        return text
    before, after = text.split('.')
    return f'{before or 0}.{after or 0}'


def get_prefix(fullname: str) ->str:
    """Drop the final component of a qualified name (e.g. ('x.y' -> 'x')."""
    return fullname.rsplit('.', 1)[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 release_local(local):
    """Releases the contents of the local for the current context.
    This makes it possible to use locals without a manager.

    Example::

        >>> loc = Local()
        >>> loc.foo = 42
        >>> release_local(loc)
        >>> hasattr(loc, 'foo')
        False

    With this function one can release :class:`Local` objects as well
    as :class:`StackLocal` objects.  However it is not possible to
    release data held by proxies that way, one always has to retain
    a reference to the underlying local object in order to be able
    to release it.

    .. versionadded:: 0.6.1
    """
    local.__release_local__()


def check_min_permission_length(permission, minchars=None):
    """
    Adapted version of policyuniverse's _check_permission_length. We are commenting out the skipping prefix message
    https://github.com/Netflix-Skunkworks/policyuniverse/blob/master/policyuniverse/expander_minimizer.py#L111
    """
    if minchars and len(permission) < int(minchars) and permission != '':
        return True
    return False


def is_user_an_admin():
    """ Check user admin """
    import os
    if os.name == 'nt':
        try:
            os.listdir(os.sep.join([os.environ.get('SystemRoot',
                'C:\\windows'), 'temp']))
        except Exception:
            return False
        else:
            return True
    else:
        return 'SUDO_USER' in os.environ and os.geteuid() == 0


def configure_report(args, run):
    """Configure training report"""
    if args.load_weights is None:
        weights = 'scratch'
    else:
        weights = args.load_weights
    experiment_name = (
        f'{args.dataset}_{args.level}_{args.task}_{weights}_{args.arch}_0{run}'
        )
    f = f'reports/{args.dataset}/{experiment_name}.tsv'
    print('epoch\ttraining_loss\ttraining_acc\tvalid_loss\tvalid_acc', file
        =open(f, 'a'))
    return experiment_name, f


@staticmethod
def get_cell(obj, pos):
    """
        From a graph `graph` and a tuple `pos`,
        return the object cell value at position `pos`.

        TESTS ::

            sage: from sage.graphs.generators.families import AztecDiamondGraph
            sage: from sage_widget_adapters.graphs.graph_grid_view_adapter import GraphGridViewAdapter
            sage: g = AztecDiamondGraph(2)
            sage: GraphGridViewAdapter.get_cell(g, (1,3)) is None
            True
        """
    return None


def dict_del(dct, key):
    """
    removes a dictionary element given by `key' but without failing if it
    does not exist
    """
    try:
        del dct[key]
    except KeyError:
        pass


def set_flag():
    """Set 'Reload request' flag state
    """
    global _flag
    _flag = True


def is_quote(ch: str):
    """Check if given character code is a quote character"""
    return ch == '"' or ch == "'"


def __len__():
    """Return the number of valid values, or sys.maxint."""


@classmethod
def has_archiving(cls):
    """Returns whether it supports archiving items on the fetch process.

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


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

        :param GenericErrorTag val:
        :rtype: LockingErrorTagUnion
        """
    return cls('generic_error', val)


def crop_beginning(data):
    """Crop constant padding at the begin of the data column"""
    assert data.shape[1] == 2
    start = data[0, 1]
    for ii in range(1, data.shape[0]):
        if data[ii, 1] != start:
            break
    else:
        raise ValueError('Encountered all-constant data!')
    return data[ii - 1:, :]


def disable_relation_fields(*models, all_metadata=None):
    """
    Remplace la liste de choix par un simple champ de saisie pour toutes les relations des modèles donnés
    (Permet d'améliorer significativement les performances lors de l'affichage du formulaire dans les APIs)
    :param models: Liste des modèles
    :param all_metadata: Toutes les métadonnées créées jusqu'à présent
    :return: Rien
    """
    from common.api.base import METADATA
    all_metadata = all_metadata or METADATA
    for model in models:
        if not model:
            continue
        metas = {}
        for field in model._meta.get_fields():
            if (field.concrete and not field.auto_created and field.
                related_model):
                metas[field.name] = dict(style={'base_template':
                    'input.html', 'placeholder': str(field.verbose_name)})
        if metas:
            metadata = all_metadata[model] = all_metadata.get(model, {})
            extra_kwargs = metadata['extra_kwargs'] = metadata.get(
                'extra_kwargs', {})
            for key, value in metas.items():
                extra_kwargs[key] = extra_kwargs.get(key, {})
                extra_kwargs[key].update(value)


@staticmethod
def win_timestamp_to_unix(seconds):
    """
        Convert Windows timestamp (100 ns since 1 Jan 1601) to
        unix timestamp.
        """
    seconds = int(seconds)
    if seconds == 0:
        return -1
    return int((seconds - 116444736000000000) / 10000000)


def formula(foyer_fiscal, period, parameters):
    """
        PPE: coefficient de conversion en cas de changement en cours d'année
        """
    jour_xyz = foyer_fiscal('jour_xyz', period)
    nb_jour = (jour_xyz == 0) + jour_xyz
    return 360 / nb_jour


@staticmethod
def http_exception_message(status_code, result_json):
    """Craft a short Exception message given an HTTP status code, error, and
        message.
        """
    error = result_json['status']
    message = result_json['message']
    return 'HTTP Exception: Status code: {}; Error: {}, Message: {}'.format(
        status_code, error, message)


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

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

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


@classmethod
def load(cls, name=None, parent_name=None, profile_is_live=False, values=
    None, defaults=None) ->'EnvvarProfile':
    """
        Get a loaded frozen instance of a specific profile.
        """
    instance = cls(name=name, parent_name=parent_name, profile_is_live=
        profile_is_live, values=values, defaults=defaults)
    instance._do_load()
    return instance


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 prolongate_injection(n):
    """Copy data to each child."""
    data = [None] * n.nchildren
    if n.data is not None:
        for i, c in enumerate(n.child):
            data[i] = n.data.copy()
    return data


def _add_lab_command(subparsers, parents):
    """
    Adds lab to the edition parsers.
    """
    parser_lab = subparsers.add_parser('lab', help='Lab edition', parents=
        parents)
    mutex = parser_lab.add_mutually_exclusive_group(required=True)
    mutex.add_argument('--project', required=False, help='Id of project')
    mutex.add_argument('--group', required=False, help='Id of group')


@staticmethod
def save(file_path, model):
    """
        Save the model onto the file identified by file_path.

        Parameters
        ----------
        file_path : str
            The path to the filename where the model has to be saved
        model : RTEnsemble
            The model RTEnsemble model to save on file

        Returns
        -------
        status : bool
            Returns true if the save is successful, false otherwise
        """
    raise NotImplementedError('Feature not implemented!')


def readline_invisible(code):
    """
    Wrap ``code`` with the special characters to tell readline that it is
    invisible.
    """
    return '\x01%s\x02' % code


@classmethod
def from_defaults(cls, ctx, **defaults):
    """Creates context `ctx` introducing only new keys given in `defaults`.

        The normal behavior when you enter a new level in the context is to
        override the values with the new one.

        Example:

           >>> with context.from_defaults('A', a=1):
           ...    with context.from_defaults('A', a=2, b=1) as c:
           ...        assert c['a'] == 1

        """
    return cls.from_dicts(ctx, defaults=defaults)


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


def read(path):
    """Yields line by line from the file path provided.

    Args:
        path (str): File path provided.

    Yields:
        int: Line number.
        str: Line of text corresponding to the line number from the file.

    .. versionadded:: 1.0.0
    """
    with open(path, 'r', encoding='utf-8') as fp:
        count = 0
        for line in fp:
            count += 1
            yield count, line.strip('\n')


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 get_instance_id_to_volume_id_map(volume_info):
    """Generate instance_id to volume id map.  Unattached volumes will be ignored."""
    instance_id_to_volume_id_map = {}
    for volume_id in volume_info:
        volume = volume_info.get(volume_id)
        if volume.get('Attachments'):
            ec2_instance_id = volume.get('Attachments')[0].get('InstanceId')
            current_volumes = instance_id_to_volume_id_map.get(ec2_instance_id)
            if current_volumes is None:
                current_volumes = []
            current_volumes.append(volume_id)
            instance_id_to_volume_id_map[ec2_instance_id] = current_volumes
    return instance_id_to_volume_id_map


def isiterable(coll):
    """Return True if the collection is any iterable except a string

    :param coll: a collection
    :returns: a boolean

    >>> isiterable(1)
    False
    >>> isiterable('iterable')
    False
    >>> isiterable([1, 2, 3])
    True

    """
    return hasattr(coll, '__iter__')


@classmethod
def _from_dict(cls, _dict):
    """Initialize a ClassResult object from a json dictionary."""
    args = {}
    if 'class' in _dict or 'class_name' in _dict:
        args['class_name'] = _dict.get('class') or _dict.get('class_name')
    else:
        raise ValueError(
            "Required property 'class' not present in ClassResult JSON")
    if 'score' in _dict:
        args['score'] = _dict.get('score')
    else:
        raise ValueError(
            "Required property 'score' not present in ClassResult JSON")
    if 'type_hierarchy' in _dict:
        args['type_hierarchy'] = _dict.get('type_hierarchy')
    return cls(**args)


@classmethod
def default_chunk_size(cls):
    """ Returns the default chunk size for this source.
        """
    return 256


def set_attributes(instance, **kwargs):
    """
    sets the provided keyword arguments as attributes in given object instance.

    :param CoreObject instance: instance to set attributes for.

    :returns: instance with updated attributes.
    :rtype: CoreObject
    """
    if instance is None:
        return instance
    for name, value in kwargs.items():
        setattr(instance, name, value)
    return instance


def overrides(method):
    """Decorator to indicate that the decorated method overrides a method in
    superclass.

    The decorator code is executed while loading class. Using this method should
    have minimal runtime performance implications.

    This is based on my idea about how to do this and fwc:s highly improved
    algorithm for the implementation
    fwc:s algorithm : http://stackoverflow.com/a/14631397/308189
    my answer : http://stackoverflow.com/a/8313042/308189

    How to use:
    from overrides import overrides

    class SuperClass:

        def method(self):
            return 2

    class SubClass(SuperClass):

        @overrides
        def method(self):
            return 1

    :raises  AssertionError if no match in super classes for the method name
    :return  method with possibly added (if the method doesn't have one)
     docstring from super class
    """
    return method


def viz_tr(body, port=None):
    """Create HTML tr for graphviz"""
    if port:
        return '
{}
'.format(port, body)
    return '
{}
'.format(body)


def roundlist(inlist, digits):
    """
Goes through each element in a 1D or 2D inlist, and applies the following
function to all elements of float ... round(element,digits).

Usage:   roundlist(inlist,digits)
Returns: list with rounded floats
"""
    if type(inlist[0]) in [int, float]:
        inlist = [inlist]
    l = inlist * 1
    for i in range(len(l)):
        for j in range(len(l[i])):
            if isinstance(l[i][j], float):
                l[i][j] = round(l[i][j], digits)
    return l


def pa2mbar(press_pa):
    """Convert pressure value from Pascal to mbar"""
    return press_pa * 0.01


@staticmethod
def _clifford_application_payload(clifford, pauli):
    """
        Prepares a JSON payload for conjugating a Pauli by a Clifford.

         See :py:func:`apply_clifford_to_pauli`.

        :param Program clifford: A Program that consists only of Clifford operations.
        :param PauliTerm pauli: A PauliTerm to be acted on by clifford via conjugation.
        :return: The JSON payload, with keys "clifford" and "pauli".
        """
    indices_and_terms = zip(*list(pauli.operations_as_set()))
    return {'clifford': clifford.out(), 'pauli': list(indices_and_terms)}


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

        :param ShowcaseDocumentLogInfo val:
        :rtype: AssetLogInfo
        """
    return cls('showcase_document', val)


def getSquareSegmentDistance(p, p1, p2):
    """
    Square distance between point and a segment
    """
    x = p1['x']
    y = p1['y']
    dx = p2['x'] - x
    dy = p2['y'] - y
    if dx != 0 or dy != 0:
        t = ((p['x'] - x) * dx + (p['y'] - y) * dy) / (dx * dx + dy * dy)
        if t > 1:
            x = p2['x']
            y = p2['y']
        elif t > 0:
            x += dx * t
            y += dy * t
    dx = p['x'] - x
    dy = p['y'] - y
    return dx * dx + dy * dy


def get_all(isamAppliance, check_mode=False, force=False):
    """
    Get existing activations
    """
    return isamAppliance.invoke_get('Retrieving activations',
        '/isam/capabilities/v1')


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

        :param TeamFolderAccessError val:
        :rtype: BaseTeamFolderError
        """
    return cls('access_error', val)


def _splitrange(a, b):
    """Split range with bounds a and b into two ranges at 0 and return two
    tuples of numbers for use as startdepth and stopdepth arguments of
    revancestors and revdescendants.

    >>> _splitrange(-10, -5)     # [-10:-5]
    ((5, 11), (None, None))
    >>> _splitrange(5, 10)       # [5:10]
    ((None, None), (5, 11))
    >>> _splitrange(-10, 10)     # [-10:10]
    ((0, 11), (0, 11))
    >>> _splitrange(-10, 0)      # [-10:0]
    ((0, 11), (None, None))
    >>> _splitrange(0, 10)       # [0:10]
    ((None, None), (0, 11))
    >>> _splitrange(0, 0)        # [0:0]
    ((0, 1), (None, None))
    >>> _splitrange(1, -1)       # [1:-1]
    ((None, None), (None, None))
    """
    ancdepths = None, None
    descdepths = None, None
    if a == b == 0:
        ancdepths = 0, 1
    if a < 0:
        ancdepths = -min(b, 0), -a + 1
    if b > 0:
        descdepths = max(a, 0), b + 1
    return ancdepths, descdepths


def node_list_sort(lst_of_nodes):
    """Sorts the list ost nodes based on their name"""
    return sorted(lst_of_nodes, key=lambda node: node.name)


def delete_tags(Tags=None):
    """
    Deletes the specified tags.
    See also: AWS API Documentation

    Examples
    This example deletes the specified tag from the specified Auto Scaling group.
    Expected Output:

    :example: response = client.delete_tags(
        Tags=[
            {
                'ResourceId': 'string',
                'ResourceType': 'string',
                'Key': 'string',
                'Value': 'string',
                'PropagateAtLaunch': True|False
            },
        ]
    )

    :type Tags: list
    :param Tags: [REQUIRED]
            One or more tags.
            (dict) --Describes a tag for an Auto Scaling group.
            ResourceId (string) --The name of the group.
            ResourceType (string) --The type of resource. The only supported value is auto-scaling-group .
            Key (string) -- [REQUIRED]The tag key.
            Value (string) --The tag value.
            PropagateAtLaunch (boolean) --Determines whether the tag is added to new instances as they are launched in the group.

    :return: response = client.delete_tags(
        Tags=[
            {
                'Key': 'Dept',
                'ResourceId': 'my-auto-scaling-group',
                'ResourceType': 'auto-scaling-group',
                'Value': 'Research',
            },
        ],
    )

    print(response)

    """
    pass


def swapcase(text):
    """
    Creates a copy of ``text`` with uppercase characters converted to lowercase and vice versa.

    Note that it is not necessarily true that ``swapcase(swapcase(s)) == s``.  That is
    because of how the Unicode Standard defines cases.

    :param text: The string to convert
    :type text:  ``str``

    :return: A copy of ``text`` with uppercase characters converted to lowercase and vice versa.
    :rtype: ``str``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.swapcase()


def colwidth(n):
    """Translate human-readable units to BIFF column width units"""
    if n <= 0:
        return 0
    if n <= 1:
        return n * 456
    return 200 + n * 256


def constant(_):
    """
    Returns a constant value for the Scheduler

    :param _: ignored
    :return: (float) 1
    """
    return 1.0


def distmod2dist(distmod):
    """distance modulus to distance in kpc"""
    return 10.0 ** (distmod / 5.0 - 2.0)


def decode(packet):
    """
    https://github.com/telldus/telldus/blob/master/telldus-core/service/ProtocolEverflourish.cpp
    """
    data = packet['data']
    house = data & 16776192
    house >>= 10
    unit = data & 768
    unit >>= 8
    unit += 1
    method = data & 15
    if house > 16383 or unit < 1 or unit > 4:
        return
    if method == 0:
        method = 'turnoff'
    elif method == 15:
        method = 'turnon'
    elif method == 10:
        method = 'learn'
    else:
        return
    return dict(packet, _class='command', model='selflearning', house=house,
        unit=unit, method=method)


def breaks(n=0):
    """Return n number of newline characters"""
    return '\n' * n


def evalUnits(unitStr):
    """
    Evaluate a unit string into ([numerators,...], [denominators,...])
    Examples:
        N m/s^2   =>  ([N, m], [s, s])
        A*s / V   =>  ([A, s], [V,])
    """
    pass


def _make_links_absolute(html, base_url):
    """
    Make all links absolute in the given HTML (relative to the given base_url).
    """
    from lxml.html import fromstring, tostring
    parsed = fromstring(html)
    parsed.make_links_absolute(base_url)
    return tostring(parsed)


def dict_from_param(param):
    """Get Parameter properties as a dictionary

    Parameters
    ----------
    param: Parameter

    Returns
    -------
    opts: dict

    See Also
    --------
    add_text_to_elt, walk_parameters_to_xml, dict_from_param
    """
    opts = dict([])
    param_type = str(param.type())
    opts.update(dict(type=param_type))
    title = param.opts['title']
    if title is None:
        title = param.name()
    opts.update(dict(title=title))
    if param.opts['visible']:
        visible = '1'
    else:
        visible = '0'
    opts.update(dict(visible=visible))
    if param.opts['removable']:
        removable = '1'
    else:
        removable = '0'
    opts.update(dict(removable=removable))
    if param.opts['readonly']:
        readonly = '1'
    else:
        readonly = '0'
    opts.update(dict(readonly=readonly))
    if 'values' in param.opts:
        values = str(param.opts['values'])
        opts.update(dict(values=values))
    if 'limits' in param.opts:
        limits = str(param.opts['limits'])
        opts.update(dict(limits=limits))
        opts.update(dict(values=limits))
    if 'addList' in param.opts:
        addList = str(param.opts['addList'])
        opts.update(dict(addList=addList))
    if 'detlist' in param.opts:
        detlist = str(param.opts['detlist'])
        opts.update(dict(detlist=detlist))
    if 'movelist' in param.opts:
        movelist = str(param.opts['movelist'])
        opts.update(dict(movelist=movelist))
    if 'show_pb' in param.opts:
        if param.opts['show_pb']:
            show_pb = '1'
        else:
            show_pb = '0'
        opts.update(dict(show_pb=show_pb))
    if 'filetype' in param.opts:
        if param.opts['filetype']:
            filetype = '1'
        else:
            filetype = '0'
        opts.update(dict(filetype=filetype))
    return opts


def no_log_warn(logical_line):
    """Disallow 'LOG.warn('

    Deprecated LOG.warn(), instead use LOG.warning
    https://bugs.launchpad.net/senlin/+bug/1508442

    M331
    """
    msg = 'M331: LOG.warn is deprecated, please use LOG.warning!'
    if 'LOG.warn(' in logical_line:
        yield 0, msg


def qualifying_prefix(modname, qualname):
    """
    Returns a new string that is used for the first half of the mangled name.
    """
    return '{}.{}'.format(modname, qualname) if modname else qualname


def get_model_phi1_phi2(model):
    """
    Ratio of distances between the second minimum and first maximum, and the
    second minimum and second maximum, of the fitted Lomb-Scargle model.
    """
    return model['phi1_phi2']


def hdf5_open(fid, mode='w'):
    """Open an hdf5 file.

  **Parameters:**

  fid : str
    Contains the filename of the hdf5 file.
  mode : str, optional
    Specifies the mode used to open the file. ('r', 'w', 'a')

  **Usage:**

  for hdf5_file in hdf5_open(fid,mode='w'):
    # Do something with hdf5_file...
  """
    import h5py
    if isinstance(fid, h5py.File):
        yield fid
    if not (fid.endswith('h5') or fid.endswith('hdf5')):
        fid += '.h5'
    hdf5_file = h5py.File(fid, mode)
    try:
        yield hdf5_file
    finally:
        hdf5_file.close()


@staticmethod
def ensure_part(piece_id, part_name, conn, cursor):
    """
        Ensure given part is included
            :param piece_id: Id of source piece
            :param part_name: Name of the part
            :param conn: Connection to sqlite instance
            :param cursor: Cursor to use
        """
    cursor.execute('SELECT id FROM parts WHERE piece_id=? AND name=? LIMIT 1',
        (piece_id, part_name))
    results = cursor.fetchall()
    if results:
        return results[0][0]
    cursor.execute('INSERT INTO parts (piece_id, name) VALUES (?, ?)', (
        piece_id, part_name))
    conn.commit()
    return cursor.lastrowid


def bC_K_HSO4_HMW84(T, P):
    """c-a: potassium bisulfate [HMW84]."""
    b0 = -0.0003
    b1 = 0.1735
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


@classmethod
def clean_cache(cls):
    """
        Clean internal objects cache and reset the internal counters
        """
    cls._next_id = 1
    cls._count = 0
    cls._total_count = -1
    cls._cache = {}


def is_view_func_public(func):
    """
    Returns whether a view is public or not (ie/ has the REQUIRE_LOGIN_IS_PUBLIC
    attribute set)
    """
    return getattr(func, 'REQUIRE_LOGIN_IS_PUBLIC', False)


def _lrbt(lrbt, w, h):
    """Calculate coordinate system limits"""
    n = len(lrbt)
    if n < 4:
        if not isinstance(lrbt, list):
            lrbt = list(lrbt)
        dy = h * (lrbt[1] - lrbt[0]) / w
        if n == 2:
            dy /= 2
            lrbt = lrbt + [-dy, dy]
        else:
            lrbt = lrbt + [lrbt[2] + dy]
    else:
        lrbt = lrbt[:4]
    return lrbt


def parselines(input):
    """Return a buienradard input file as (level, (hh, mm)) tuples."""
    for line in input:
        line = line.strip()
        levelStr, hhmmStr = line.split('|')
        hhStr, mmStr = hhmmStr.split(':')
        yield int(levelStr), (int(hhStr), int(mmStr))


@classmethod
def GetAContainerNumber(cls):
    """
        Not user callable!
        :return: A simple counter that makes each container element unique
        """
    cls.container_element_counter += 1
    return cls.container_element_counter


def remove(source: list, els=None):
    """
    Remove elements.

    :param list source: Source list
    :param els: Element(s) to be removed
    :return: list
    """
    r = []
    if els is None:
        els = ['', None]
    elif not isinstance(els, list):
        els = [els]
    for el in source:
        if el not in els:
            r.append(el)
    return r


def add_prefix(string, prefix=None):
    """Add ``prefix`` to ``string``, if not ``None``.
    """
    return string if prefix is None else '%s%s' % (prefix, string)


@staticmethod
def is_interface():
    """
        Indicates whether this object is considered an Interface.        The default is False.

        :returns: False
        """
    return False


@staticmethod
def do_multirow_insert(connection, table, values):
    """
        Insert multiple rows into the given table.
        This method may be overridden by models that use more powerful SQL dialects.
        """
    if values:
        with connection.begin():
            connection.execute(table.insert(), values)


@classmethod
def register_adapter(cls, from_cls, func):
    """
        Register a function that can handle adapting from `from_cls` for this
        field.

        TODO This may be a bad idea, re-evaluate how to register adapters.
        """
    if not cls.__adapters__:
        cls.__adapters__ = {}
    cls.__adapters__[from_cls] = func


def cheb_dis(contrast_pose, stand_pose):
    """
    功能：以切比雪夫距离衡量两个舞姿的相似度。相似度的计算思路为：直接计算两个舞姿的切比雪夫距离。
    输入：
    contrast_pose:要对比的舞姿
    stand_pos: 基准舞姿
    返回：
    similarity:两个舞姿的切比雪夫距离，格式为：numpy.float64
    """
    d = abs(contrast_pose - stand_pose)
    similarity = 1 - d.max()
    return similarity


def select_pick(report_index: int=0):
    """Select reports by index

    :param report_index: Report, Index of the report
    :type report_index: int
    """
    pass


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``OrthoEditToolBar`` is only intended to be added to
        :class:`.OrthoPanel` views.
        """
    from fsleyes.views.orthopanel import OrthoPanel
    return [OrthoPanel]


def defaultCalibration():
    """Default calibration data

    Returns
    -------
    data : np.ndarray
        Data lines converted to a float array
    staticGain : float
        Static gain
    """
    return [1] * 10, 1


def records_from_db(fn):
    """Naively parse db/template files looking for record names

    Returns
    -------
    records : list
        [(record type, record name), ...]
    """
    ret = []
    for line in open(fn, 'rt').readlines():
        line = line.strip()
        if line.startswith('#'):
            continue
        if not (line.startswith('record') or line.startswith('grecord')):
            continue
        if '(' not in line:
            continue
        line = line[line.index('(') + 1:]
        if ',' not in line:
            continue
        rtype, record = line.split(',', 1)
        rtype = rtype.strip()
        record = record.strip()
        if record.startswith('"'):
            record = record[1:]
            record = record[:record.index('"')]
        else:
            in_paren = 0
            for i, c in enumerate(record):
                if c == '(':
                    in_paren += 1
                elif c == ')':
                    in_paren -= 1
                    if in_paren < 0:
                        record = record[:i]
                        break
        ret.append((rtype, record))
    return ret


def list_volume_initiators(VolumeARN=None):
    """
    Lists iSCSI initiators that are connected to a volume. You can use this operation to determine whether a volume is being used or not. This operation is only supported in the cached volume and stored volume gateway architecture.
    See also: AWS API Documentation

    :example: response = client.list_volume_initiators(
        VolumeARN='string'
    )

    :type VolumeARN: string
    :param VolumeARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the volume. Use the ListVolumes operation to return a list of gateway volumes for the gateway.

    :rtype: dict
    :return: {
        'Initiators': [
            'string',
        ]
    }

    """
    pass


def print_vtr_metadata(vtr_object, use_json=False):
    """
    Quick diagnostic tool for printing the metadata of VTR objects

    :param vtr_object: input vtr model object
    :type vtr_object: vtrtool.VTRModel
    """
    if use_json:
        print(vtr_object.meta_info(return_json=True))
    else:
        print('VTR filename: ', vtr_object.file)
        print('Number of properties: ', vtr_object.num_properties)
        print('Number of dimensions: ', vtr_object.num_dimensions)
        print('NX1: ', vtr_object.nx1)
        print('NX2: ', vtr_object.nx2)
        print('NX3(fastest): ', vtr_object.nx3)


def parse_string_list_from_string(a_string):
    """
    This just parses a comma separated string and returns an string list

    Args:
        a_string (str): The string to be parsed

    Returns:
        A list of strings

    Author: SMM

    Date: 10/01/2018
    """
    print("Hey pardner, I'm a gonna parse a string into a list. Yeehaw.")
    if len(a_string) == 0:
        print('No items found, I am returning and empty list.')
        return_list = []
    else:
        return_list = a_string.split(',')
        print('The parsed string is:')
        print(return_list)
    return return_list


@staticmethod
def segment_coupler_scan():
    """Generate a scan-command for LCN segment-couplers.

        Used to detect the local segment (where the physical bus connection is
        located).

        :return:    The PCK command (without address header) as text
        :rtype:    str
        """
    return 'SK'


def get_s3acc(module, blade):
    """Return Object Store Account or None"""
    s3acc = None
    accts = blade.object_store_accounts.list_object_store_accounts()
    for acct in range(0, len(accts.items)):
        if accts.items[acct].name == module.params['account']:
            s3acc = accts.items[acct]
    return s3acc


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 unescape(v):
    """Take the unicode string and return a list containing the broken
    up values from the unicode string (separated by spaces).

      >>> unescape(u'foo bar')
      [u'foo', u'bar']

      >>> unescape(u'foo "testing spaces" bar')
      [u'foo', u'testing spaces', u'bar']

      >>> unescape(u'"testing spaces" bar')
      [u'testing spaces', u'bar']

    """
    result = []
    last = u''
    inquote = False
    for x in v:
        if x == u'"':
            if not inquote:
                inquote = True
            elif inquote:
                inquote = False
        elif x == u' ' and not inquote:
            last = last.strip()
            if last:
                result.append(last)
            last = u''
        else:
            last += x
    last = last.strip()
    if last:
        result.append(last)
    return result


def ruby_object_constructor(loader, suffix, node):
    """YAML constructor for Ruby objects.

    This constructor may be registered with '!ruby/object:' tag as multi
    constructor supporting Ruby objects. This will handle give objects as maps,
    so any non mapping based object may produce some issue.
    """
    return loader.construct_yaml_map(node)


def areaBetween(requestContext, *seriesLists):
    """
    Draws the vertical area in between the two series in seriesList. Useful for
    visualizing a range such as the minimum and maximum latency for a service.

    areaBetween expects **exactly one argument** that results in exactly two
    series (see example below). The order of the lower and higher values
    series does not matter. The visualization only works when used in
    conjunction with ``areaMode=stacked``.

    Most likely use case is to provide a band within which another metric
    should move. In such case applying an ``alpha()``, as in the second
    example, gives best visual results.

    Example::

      &target=areaBetween(service.latency.{min,max})&areaMode=stacked

      &target=alpha(areaBetween(service.latency.{min,max}),0.3)&areaMode=stacked

    If for instance, you need to build a seriesList, you should use the
    ``group`` function, like so::

      &target=areaBetween(group(minSeries(a.*.min),maxSeries(a.*.max)))
    """
    if len(seriesLists) == 1:
        [seriesLists] = seriesLists
    assert len(seriesLists
        ) == 2, 'areaBetween series argument must reference *exactly* 2 series'
    lower, upper = seriesLists
    if len(lower) == 1:
        [lower] = lower
    if len(upper) == 1:
        [upper] = upper
    lower.options['stacked'] = True
    lower.options['invisible'] = True
    upper.options['stacked'] = True
    lower.name = upper.name = 'areaBetween(%s)' % upper.pathExpression
    return [lower, upper]


def get_validation_fields():
    """
    Returns a list of tuples (each a field)
      required for a valid json
      (field,value,type)
          field: the field name
          value: indicates minimum required entires
          type: indicates the variable type

    """
    return [('name', 1, str), ('tag', 1, list), ('corpus', 1, str), (
        'terms', 1, str), ('dependencies', 0, dict), ('arguments', 0, str),
        ('contributors', 0, str), ('doi', 0, str)]


def ParseBool(text):
    """Parse a boolean value.

  Args:
    text: Text to parse.

  Returns:
    Boolean values parsed

  Raises:
    ValueError: If text is not a valid boolean.
  """
    if text in (b'true', b't', b'1'):
        return True
    elif text in (b'false', b'f', b'0'):
        return False
    else:
        raise ValueError('Expected "true" or "false".')


def __call__(*args, **kwargs):
    """Generate the field."""
    pass


@staticmethod
def combine_results_and_polls(results, polls):
    """Merge national polling, and geo-level polling if available, into results dataframe."""
    results = results.merge(right=polls.query('geo == "uk"')[['party',
        'voteshare']].rename(columns={'voteshare': 'national_polls'}), on=
        'party', how='outer').sort_values(['ons_id', 'party']).reset_index(drop
        =True)
    if set(polls.geo.unique()) != {'uk'}:
        results = results.merge(right=polls.query('geo != "uk"')[['geo',
            'party', 'voteshare']].rename(columns={'voteshare': 'geo_polls'
            }), on=['geo', 'party'], how='outer').sort_values(['ons_id',
            'party']).reset_index(drop=True)
    return results


def int_shape(x):
    """ short for x.shape.as_list() """
    return x.shape.as_list()


def __len__():
    """Return the number of items.
        """


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

        :param FileLikeCommentType val:
        :rtype: EventType
        """
    return cls('file_like_comment', val)


def validate_fillna_kwargs(value, method, validate_scalar_dict_value=True):
    """Validate the keyword arguments to 'fillna'.

    This checks that exactly one of 'value' and 'method' is specified.
    If 'method' is specified, this validates that it's a valid method.

    Parameters
    ----------
    value, method : object
        The 'value' and 'method' keyword arguments for 'fillna'.
    validate_scalar_dict_value : bool, default True
        Whether to validate that 'value' is a scalar or dict. Specifically,
        validate that it is not a list or tuple.

    Returns
    -------
    value, method : object
    """
    from pandas.core.missing import clean_fill_method
    if value is None and method is None:
        raise ValueError("Must specify a fill 'value' or 'method'.")
    elif value is None and method is not None:
        method = clean_fill_method(method)
    elif value is not None and method is None:
        if validate_scalar_dict_value and isinstance(value, (list, tuple)):
            raise TypeError(
                f'"value" parameter must be a scalar or dict, but you passed a "{type(value).__name__}"'
                )
    elif value is not None and method is not None:
        raise ValueError("Cannot specify both 'value' and 'method'.")
    return value, method


def argsort(seq):
    """
    Generate the sorted arguments of a collection of values

    Parameters
    ----------
    seq : dict

    Returns
    -------
    list
        list of keys sorted by value
    """
    return sorted(range(len(seq)), key=seq.__getitem__)


def zidz(numerator, denominator):
    """
    This function bypasses divide-by-zero errors,
    implementing Vensim's ZIDZ function

    Parameters
    ----------
    numerator: float
        value to be divided
    denominator: float
        value to devide by

    Returns
    -------
    result of division numerator/denominator if denominator is not zero,
    otherwise zero.
    """
    small = 1e-06
    if abs(denominator) < small:
        return 0
    else:
        return numerator * 1.0 / denominator


def match_items(lines, content_old):
    """Create items for mangled lines.

    This function tries to match the lines in ``lines`` with the items (source
    file references and line numbers) in ``content_old``. The
    ``mangle_docstrings`` function changes the actual docstrings, but doesn't
    keep track of where each line came from. The manging does many operations
    on the original lines, which are hard to track afterwards.

    Many of the line changes come from deleting or inserting blank lines. This
    function tries to match lines by ignoring blank lines. All other changes
    (such as inserting figures or changes in the references) are completely
    ignored, so the generated line numbers will be off if ``mangle_docstrings``
    does anything non-trivial.

    This is a best-effort function and the real fix would be to make
    ``mangle_docstrings`` actually keep track of the ``items`` together with
    the ``lines``.

    Examples
    --------
    >>> lines = ['', 'A', '', 'B', '   ', '', 'C', 'D']
    >>> lines_old = ['a', '', '', 'b', '', 'c']
    >>> items_old = [('file1.py', 0), ('file1.py', 1), ('file1.py', 2),
    ...              ('file2.py', 0), ('file2.py', 1), ('file2.py', 2)]
    >>> content_old = ViewList(lines_old, items=items_old)
    >>> match_items(lines, content_old) # doctest: +NORMALIZE_WHITESPACE
    [('file1.py', 0), ('file1.py', 0), ('file2.py', 0), ('file2.py', 0),
     ('file2.py', 2), ('file2.py', 2), ('file2.py', 2), ('file2.py', 2)]
    >>> # first 2 ``lines`` are matched to 'a', second 2 to 'b', rest to 'c'
    >>> # actual content is completely ignored.

    Notes
    -----
    The algorithm tries to match any line in ``lines`` with one in
    ``lines_old``.  It skips over all empty lines in ``lines_old`` and assigns
    this line number to all lines in ``lines``, unless a non-empty line is
    found in ``lines`` in which case it goes to the next line in ``lines_old``.

    """
    items_new = []
    lines_old = content_old.data
    items_old = content_old.items
    j = 0
    for i, line in enumerate(lines):
        while j < len(lines_old) - 1 and not lines_old[j].strip():
            j += 1
        items_new.append(items_old[j])
        if line.strip() and j < len(lines_old) - 1:
            j += 1
    assert len(items_new) == len(lines)
    return items_new


def find_asset_by_code(asset_finder, asset_code, all_commits):
    """
    Find an asset by the asset code.

    :param asset_finder: The cached asset finder to use.
    :param asset_code: The code of the asset to search for.
    :param all_commits: All the commits to look for.
    :returns: A pair containing the result from the 'test' and the commit.
    """
    asset_finder.search(code=asset_code)
    for commit in all_commits:
        res = asset_finder.test(commit.tree)
        if res:
            return res, commit


def parse_url(url):
    """Return provider and project id
    >>> parse_url("github.com/user/repo")
    ('github.com', 'user/repo')
    >>> parse_url("bitbucket.org/user/repo")
    ('bitbucket.org', 'user/repo')
    >>> parse_url("gitlab.com/user/repo")
    ('gitlab.com', 'user/repo')
    >>> parse_url("A quick brown fox jumps over the lazy dog")
    (None, None)
    >>> parse_url(None)
    (None, None)
    """
    if url:
        url = url.split('://', 1)[-1]
        provider, rest = url.split('/', 1)
        if provider == 'sourceforge.net':
            return provider, rest.rsplit('/', 1)[-1]
        return provider, rest
    return None, None


def transform_entity_synonyms(synonyms, known_synonyms=None):
    """Transforms the entity synonyms into a text->value dictionary"""
    entity_synonyms = known_synonyms if known_synonyms else {}
    for s in synonyms:
        if 'value' in s and 'synonyms' in s:
            for synonym in s['synonyms']:
                entity_synonyms[synonym] = s['value']
    return entity_synonyms


def get_failover_state(value):
    """
    Create result dictionary for failover IP's value.

    The value ``None`` represents unrouted.
    """
    return dict(value=value, state='routed' if value else 'unrouted')


def dt_eveformat(dt: object) ->str:
    """converts a datetime to a string in eve format
    e.g. '2019-06-25T19:04:44'
    """
    from datetime import datetime
    dt2 = datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
    return dt2.isoformat()


def insert_explicit_nulls(unischema, row_dict):
    """If input dictionary has missing fields that are nullable, this function will add the missing keys with
    None value.

    If the fields that are missing are not nullable, a ``ValueError`` is raised.

    :param unischema: An instance of a unischema
    :param row_dict: dictionary that would be checked for missing nullable fields. The dictionary is modified inplace.
    :return: None
    """
    for field_name, value in unischema.fields.items():
        if field_name not in row_dict:
            if value.nullable:
                row_dict[field_name] = None
            else:
                raise ValueError(
                    'Field {} is not found in the row_dict, but is not nullable.'
                    .format(field_name))


def atfile_sci(filename):
    """
    Return the filename of the science image
    which is assumed to be the first word
    in the atfile the user gave.
    """
    return filename.split()[0]


def is_property(obj, attribute):
    """ Check if object attribute is a property

    :param obj:
    :param attribute:
    :return:
    """
    try:
        return isinstance(type(obj).__getattribute__(obj, attribute), property)
    except AttributeError:
        return False


def __getattr__(name):
    """Return property by attribute access.

        Never throws an AttributeError if attribute does not exists, return
        None instead.
        """


def shadow_x(A, B):
    """
    Overlap between shapes A and B in the x direction.
    """
    return min(A.xmax, B.xmax) - max(A.xmin, B.xmin)


def _mod_op_repr(operation_obj):
    """Uses laurelin constant name representation for mod operations"""
    try:
        intval = int(operation_obj)
        name = operation_obj.namedValues.getName(intval)
        if name == 'add':
            return 'Mod.ADD'
        elif name == 'replace':
            return 'Mod.REPLACE'
        elif name == 'delete':
            return 'Mod.DELETE'
        else:
            return '{0}({1})'.format(operation_obj.__class__.__name__, repr
                (name))
    except Exception:
        return '{0}(<schema object>)'.format(operation_obj.__class__.__name__)


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 anp_from_scaled_supermatrix(supermatrix):
    """
    Creates an ANPNetwork object from a scaled supermatrix.  We do this by:
    1. Parsing the supermatrix and using row sums across columns to figure out clusters
    2. We use pairwise comparison objects for each node and cluster comparison
    3. We use the ratio of the priorities from the supermatrix to get the votes

    :param supermatrix: The super matrix
    :return:
    """
    pass


def is_subscribed(subscriber, type_name=None):
    """
        Checks to see if 'subscriber' is a subscriber.  'subscriber' can be
        any of the set of supported subscription types (e.g. email address,
        userid).  If type_name is provided, this specifies the intended
        subscription type; if not, the implementation is responsible for
        making a best guess about the intended type.
        """


@staticmethod
def vars_fixed_point(config):
    """ substitute variables in paths """
    keys = config.keys()
    something_changed = True
    while something_changed:
        something_changed = False
        for i in keys:
            for j in keys:
                if j == i:
                    continue
                replaced = config[i].replace('$' + j, config[j])
                if replaced != config[i]:
                    something_changed = True
                    config[i] = replaced


def read(filename: str):
    """
    Read CSV and make a dictionary list
    :param filename: csv
    :return: dictionary list
    """
    import csv
    return list(csv.DictReader(open(filename)))


def decipherInput(input):
    """
	resolution input format
	"""
    extension = input.split('.')[-1].lower()
    choice = {'bam': 0, 'sam': 1, 'fasta': 2, 'fastq': 2, 'fa': 2, 'fq': 2}
    return choice[extension]


def __delitem__(key):
    """Delete the value associated with the given key.

        Raise class:`KeyError` if :meth:`~BTrees.Interfaces.IKeyed.has_key` is false
        with the given key.
        """


def connect(username, password):
    """STOMP connect command.

    username, password:
        These are the needed auth details to connect to the
        message server.

    After sending this we will receive a CONNECTED
    message which will contain our session id.

    """
    return 'CONNECT\nlogin:%s\npasscode:%s\n\n\x00\n' % (username, password)


def z2_n_detection_level(epsilon=0.01, n=2, n_summed_spectra=1, ntrial=1):
    """Return the detection level for the Z^2_n statistics.

    See Buccheri et al. (1983), Bendat and Piersol (1971).

    Parameters
    ----------
    n : int, default 2
        The ``n`` in $Z^2_n$
    epsilon : float, default 0.01
        The fractional probability that the signal has been produced by noise

    Other Parameters
    ----------------
    ntrial : int
        The number of trials executed to find this profile
    n_summed_spectra : int
        Number of Z_2^n periodograms that are being averaged

    Returns
    -------
    detlev : float
        The epoch folding statistics corresponding to a probability
        epsilon * 100 % that the signal has been produced by noise
    """
    from scipy import stats
    retlev = stats.chi2.isf(epsilon / ntrial, 2 * int(n_summed_spectra) * n
        ) / n_summed_spectra
    return retlev


@classmethod
def match_metric_from_metric_name(cls, metric_name):
    """Parses the metric from a metric resource.

        Args:
          metric_name (string): A fully-qualified path representing a metric
            resource.

        Returns:
          A string representing the metric.
        """
    return cls._METRIC_PATH_TEMPLATE.match(metric_name).get('metric')


@classmethod
def deny(cls, action, **kwargs):
    """Deny the given action need.

        :param action: The action to deny.
        :returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
        """
    return cls.create(action, exclude=True, **kwargs)


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

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

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


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

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

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


def inside_box(p1, p2, p3, space=0):
    """Checks if p3 is inside a box formed by p1 and p2."""
    if p1[0] < p3[0] and p3[0] < p2[0] or p1[0] > p3[0] and p3[0] > p2[0]:
        if p1[1] < p3[1] and p3[1] < p2[1] or p1[1] > p3[1] and p3[1] > p2[1]:
            return True
        else:
            return False


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

        :param list of [str] val:
        :rtype: GroupMembersAddError
        """
    return cls('users_not_found', val)


@staticmethod
def actions():
    """Dictionary of actions that can be performed on object

        Returns:
            Dict[str, str]: Dictionary of actions that can be performed on object
        """
    return {'show': 'organization_show', 'update': 'organization_update',
        'create': 'organization_create', 'delete': 'organization_delete',
        'list': 'organization_list'}


def deferred(func):
    """A decorator to mark the migration as deferred."""
    func.dbmigrator_deferred = True
    return func


def group_opts(opts):
    """Sorts options by group (as defined in opts.py).

    Returns a list of options, with suboptions arranged in a list inside the
    main list and directly following the main options. Options belonging to the
    "hidden" group are excluded from the returned list (as defined in opts.py).
    """
    groups = []
    gp = []
    for i in range(len(opts)):
        grp = opts[i][1].group()
        if grp is not None and grp not in groups:
            groups.append(opts[i][1].group())
    groups.sort()
    for g in groups:
        g_list = []
        for i in range(len(opts)):
            if isinstance(opts[i], tuple):
                if g == str(opts[i][1].group()):
                    g_list.append(opts[i])
        for gs in g_list:
            opts.remove(gs)
        for i in range(len(opts)):
            if g == str(opts[i][0]) and g != 'hidden':
                opts.insert(i + 1, g_list)
                break
    return opts


def _to_dict(name_value: (dict, tuple)) ->dict:
    """Make sure the name_value a dict object"""
    return dict(name_value) if isinstance(name_value, tuple) else name_value


def register_scalable_target(ServiceNamespace=None, ResourceId=None,
    ScalableDimension=None, MinCapacity=None, MaxCapacity=None, RoleARN=None):
    """
    Registers or updates a scalable target. A scalable target is a resource that Application Auto Scaling can scale out or scale in. After you have registered a scalable target, you can use this operation to update the minimum and maximum values for your scalable dimension.
    After you register a scalable target, you can create and apply scaling policies using  PutScalingPolicy . You can view the scaling policies for a service namespace using  DescribeScalableTargets . If you are no longer using a scalable target, you can deregister it using  DeregisterScalableTarget .
    See also: AWS API Documentation

    Examples
    This example registers a scalable target from an Amazon ECS service called web-app that is running on the default cluster, with a minimum desired count of 1 task and a maximum desired count of 10 tasks.
    Expected Output:
    This example registers a scalable target from an Amazon EC2 Spot fleet with a minimum target capacity of 1 and a maximum of 10.
    Expected Output:

    :example: response = client.register_scalable_target(
        ServiceNamespace='ecs'|'elasticmapreduce'|'ec2'|'appstream',
        ResourceId='string',
        ScalableDimension='ecs:service:DesiredCount'|'ec2:spot-fleet-request:TargetCapacity'|'elasticmapreduce:instancegroup:InstanceCount'|'appstream:fleet:DesiredCapacity',
        MinCapacity=123,
        MaxCapacity=123,
        RoleARN='string'
    )

    :type ServiceNamespace: string
    :param ServiceNamespace: [REQUIRED]
            The namespace of the AWS service. For more information, see AWS Service Namespaces in the Amazon Web Services General Reference .

    :type ResourceId: string
    :param ResourceId: [REQUIRED]
            The identifier of the resource associated with the scalable target. This string consists of the resource type and unique identifier.
            ECS service - The resource type is service and the unique identifier is the cluster name and service name. Example: service/default/sample-webapp .
            Spot fleet request - The resource type is spot-fleet-request and the unique identifier is the Spot fleet request ID. Example: spot-fleet-request/sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE .
            EMR cluster - The resource type is instancegroup and the unique identifier is the cluster ID and instance group ID. Example: instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0 .
            AppStream 2.0 fleet - The resource type is fleet and the unique identifier is the fleet name. Example: fleet/sample-fleet .

    :type ScalableDimension: string
    :param ScalableDimension: [REQUIRED]
            The scalable dimension associated with the scalable target. This string consists of the service namespace, resource type, and scaling property.
            ecs:service:DesiredCount - The desired task count of an ECS service.
            ec2:spot-fleet-request:TargetCapacity - The target capacity of a Spot fleet request.
            elasticmapreduce:instancegroup:InstanceCount - The instance count of an EMR Instance Group.
            appstream:fleet:DesiredCapacity - The desired capacity of an AppStream 2.0 fleet.

    :type MinCapacity: integer
    :param MinCapacity: The minimum value to scale to in response to a scale in event. This parameter is required if you are registering a scalable target and optional if you are updating one.

    :type MaxCapacity: integer
    :param MaxCapacity: The maximum value to scale to in response to a scale out event. This parameter is required if you are registering a scalable target and optional if you are updating one.

    :type RoleARN: string
    :param RoleARN: The ARN of an IAM role that allows Application Auto Scaling to modify the scalable target on your behalf. This parameter is required when you register a scalable target and optional when you update one.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


@classmethod
def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):
    """Updates declared fields with fields converted from the SQLAlchemy model
        passed as the `model` class Meta option.
        """
    opts = klass.opts
    Converter = opts.model_converter
    converter = Converter(schema_cls=klass)
    declared_fields = super().get_declared_fields(klass, cls_fields,
        inherited_fields, dict_cls)
    fields = mcs.get_fields(converter, opts, declared_fields, dict_cls)
    fields.update(declared_fields)
    return fields


@classmethod
def get_class_to_create(cls, tagname):
    """Returns the class to create according to the given tagname
        """
    return cls._get_creatable_subclass_by_tagnames().get(tagname)


def split_path(path):
    """
    Splits path into component parts
    :param path: the path (e.g., /v1/AUTH_1234/c/o/sub)
    :return: a tuple containing account, container, obj
    """
    account = container = obj = None
    try:
        _, _, account = path.split('/', 2)
        _, _, account, container = path.split('/', 3)
        if not container:
            container = None
        _, _, account, container, obj = path.split('/', 4)
        if not obj:
            obj = None
    except ValueError:
        pass
    return account, container, obj


def extractResponse(cls, request, is_member_str):
    """Take a C{L{TeamsRequest}} and a list of Launchpad
        team values and create a C{L{TeamsResponse}}
        object containing that data.

        @param request: The Launchpad teams request object
        @type request: TeamsRequest

        @param is_member: The Launchpad teams data for this
            response, as a list of strings.
        @type is_member: {str:str}

        @returns: a Launchpad teams response object
        @rtype: TeamsResponse
        """
    self = cls()
    self.ns_uri = request.ns_uri
    self.is_member = is_member_str.split(',')
    return self


def abort():
    """ called if processing of the queue needs to be aborted """


def user_label(user):
    """Given a user ORM FAB object, returns a label"""
    if user:
        if user.first_name and user.last_name:
            return user.first_name + ' ' + user.last_name
        else:
            return user.username


@classmethod
def parse(cls, name, data_size, reader, parsers):
    """given a 4 byte name, data_size int, BitstreamReader
        and dict of {"atom":handler} sub-parsers,
        returns an atom of this class"""
    assert name == b'mvhd'
    version, flags = reader.parse('8u 24u')
    if version == 0:
        atom_format = '32u 32u 32u 32u 32u 16u 10P'
    else:
        atom_format = '64U 64U 32u 64U 32u 16u 10P'
    (created_utc_date, modified_utc_date, time_scale, duration,
        playback_speed, user_volume) = reader.parse(atom_format)
    geometry_matrices = reader.parse('32u' * 9)
    (qt_preview, qt_still_poster, qt_selection_time, qt_current_time,
        next_track_id) = reader.parse('64U 32u 64U 32u 32u')
    return cls(version=version, flags=flags, created_utc_date=
        created_utc_date, modified_utc_date=modified_utc_date, time_scale=
        time_scale, duration=duration, playback_speed=playback_speed,
        user_volume=user_volume, geometry_matrices=geometry_matrices,
        qt_preview=qt_preview, qt_still_poster=qt_still_poster,
        qt_selection_time=qt_selection_time, qt_current_time=
        qt_current_time, next_track_id=next_track_id)


def download_blob(cursor, oid, tid, filename):
    """Download a blob into a file.

        Returns the size of the blob file in bytes.
        """


def lambd_BOH3_SO4_FW86(T, P):
    """n-a: boric-acid sulfate [FW86]."""
    lambd = 0.018
    valid = T == 298.15
    return lambd, valid


def convert_to_int(m):
    """
    Convert the string m to an int, except if m is 'all' or None
    """
    if m == 'all' or m is None:
        return m
    else:
        return int(m)


@classmethod
def flush_event_listeners(cls):
    """
        Remove all of the event listeners for the model.
        """
    if not cls.__dispatcher__:
        return
    for event in cls.get_observable_events():
        cls.__dispatcher__.forget('%s: %s' % (event, cls.__name__))


def format_arg_spec(metadata):
    """
    Return a string representing the arguments taken by the handler for the
    given event.  This is meant to be used by the docstring formatters.
    """
    if metadata.arg_spec is None:
        return ''
    results = []
    arguments = metadata.arg_spec.args
    defaults = metadata.arg_spec.defaults
    varargs = metadata.arg_spec.varargs
    kwargs = metadata.arg_spec.keywords
    num_arguments = len(arguments)
    num_defaults = len(defaults) if defaults is not None else 0
    for index, argument in enumerate(arguments):
        if index == 0 and argument == 'self':
            continue
        default_index = index - num_arguments + num_defaults
        if default_index >= 0:
            argument += '={}'.format(defaults[default_index])
        results.append(argument)
    if varargs is not None:
        results.append('*' + varargs)
    if kwargs is not None:
        results.append('**' + kwargs)
    if results:
        return ' : ' + ', '.join(results)
    else:
        return ''


def get_graph_solution(x):
    """Get graph solution from binary string.

    Args:
        x (numpy.ndarray) : binary string as numpy array.

    Returns:
        numpy.ndarray: graph solution as binary numpy array.
    """
    return 1 - x


def write(filename, data):
    """ Write data to the file. """
    with open(filename, 'w') as f:
        f.write(data)


def is_staff(request, view, obj=None):
    """
    Checks if the current user is a staff member.
    """
    return request.user.is_staff


@classmethod
def ClearIter(cls):
    """Sets the color iterator to None."""
    cls.color_iter = None
    cls.current_figure = None


def _setup(conn):
    """CacheTable setup function."""
    conn.cursor().execute(
        """
    CREATE TABLE IF NOT EXISTS cache_anime (
        aid INTEGER,
        complete INTEGER NOT NULL CHECK(complete IN (0, 1)),
        watched_episodes INTEGER NOT NULL,
        anime_files TEXT,
        PRIMARY KEY (aid),
        FOREIGN KEY (aid) REFERENCES anime(aid)
            ON DELETE CASCADE ON UPDATE CASCADE
    )"""
        )


def grouper_exact(it, chunk_size):
    """
    Grouper-like func, but returns exactly all elements from it:

    >>> for chunk in grouper_exact(range(10), 3): print(e)
    (0,1,2)
    (3,4,5)
    (6,7,8)
    (9,)

    About 2 times slower than simple zip(*[it] * 3), but does not need to convert iterator to sequence to be sure to
    get exactly all elements in it (i.e. get a last chunk that may be smaller than chunk_size).
    """
    import itertools
    i = itertools.zip_longest(*([iter(it)] * chunk_size), fillvalue=...)
    curr = next(i)
    for nxt in i:
        yield curr
        curr = nxt
    if ... in curr:
        yield curr[:curr.index(...)]
    else:
        yield curr


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

        :param secondary_emails.SecondaryEmail val:
        :rtype: AddSecondaryEmailResult
        """
    return cls('success', val)


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

        :param TeamProfileChangeNameType val:
        :rtype: EventType
        """
    return cls('team_profile_change_name', val)


def Stokes_number(V, Dp, D, rhop, mu):
    """Calculates Stokes Number for a given characteristic velocity `V`,
    particle diameter `Dp`, characteristic diameter `D`, particle density
    `rhop`, and fluid viscosity `mu`.

    .. math::
        \\text{Stk} = \\frac{\\rho_p V D_p^2}{18\\mu_f D}

    Parameters
    ----------
    V : float
        Characteristic velocity (often superficial), [m/s]
    Dp : float
        Particle diameter, [m]
    D : float
        Characteristic diameter (ex demister wire diameter or cyclone
        diameter), [m]
    rhop : float
        Particle density, [kg/m^3]
    mu : float
        Fluid viscosity, [Pa*s]

    Returns
    -------
    Stk : float
        Stokes numer, [-]

    Notes
    -----
    Used in droplet impaction or collection studies.

    Examples
    --------
    >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)
    0.5

    References
    ----------
    .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.
    .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.
       Al-Masry. "Investigating Droplet Separation Efficiency in Wire-Mesh Mist
       Eliminators in Bubble Column." Journal of Saudi Chemical Society 14, no.
       4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.
    """
    return rhop * V * (Dp * Dp) / (18.0 * mu * D)


def inrange(index, v1, v2):
    """Force index to be within the range v1 to v2, and return result.
    """
    if v1 < v2:
        low = v1
        high = v2
    else:
        low = v2
        high = v1
    return min(max(index, low), high)


def concat_iter(*iters):
    """Concatenate iterators"""
    for iterator in iters:
        for value in iterator:
            yield value


def _stable_ids_from_unambig(unambig):
    """Create stable IDs from an unambiguous IDs"""
    assoc = {}
    ri = {}
    for k in unambig:
        tag, untagged = k.split('_', 1)
        stab = '%s.%s' % (untagged, tag)
        assoc[stab] = k
        ri[k] = stab
    return assoc, ri


@staticmethod
def workbench_scenarios():
    """A canned scenario for display in the workbench."""
    return [('ScormXBlock',
        """<vertical_demo>
                <openedxscorm/>
                </vertical_demo>
             """
        )]


def put_object_string(swift, container, object_name, contents):
    """Put the object contents as a string """
    try:
        contents = contents.decode('utf-8')
    except AttributeError:
        pass
    return swift.put_object(container, object_name, contents)


def divide(num1, num2):
    """
    definition: func(arg1, arg2) {...}
    objective : divides the given two elements
    """
    return num1 / num2


def update(x, new_x):
    """Update the value of `x` to `new_x`.

    # Arguments
        x: A `Variable`.
        new_x: A tensor of same shape as `x`.

    # Returns
        The variable `x` updated.
    """
    raise NotImplementedError(
        'MXNet Backend: Update operations are not supported yet.')


@classmethod
def deserialize(cls, serializer, wf_spec, s_state, **kwargs):
    """
        Deserializes the trigger using the provided serializer.
        """
    return serializer.deserialize_trigger(wf_spec, s_state, **kwargs)


@staticmethod
def _get_updated_on_mapping(updated_on):
    """
        Get the Jira value mapping for the modification date field.

        :param updated_on: Issue modification date
        :return: Jira value mapping for the modification date
        """
    return updated_on.isoformat()


@staticmethod
def _n_regions_to_allocate(send_buffering, recording):
    """ Get the number of regions that will be allocated
        """
    if recording and send_buffering:
        return 5
    elif recording or send_buffering:
        return 4
    return 3


@classmethod
def load(cls, params=None, ranges=None):
    """
        Loads data for one class
        """
    cls.load_all(params, ranges)


def format_seconds(seconds: float) ->str:
    """Prepare a number of seconds to be displayed as a string."""
    hours, remainder = divmod(int(round(seconds)), 60 ** 2)
    minutes, seconds = divmod(remainder, 60)
    return f'{hours:02}:{minutes:02}:{seconds:02}'


def calculateContactsVar(deltaR, epsMax):
    """
        Calculate the variation of epsilon according to the contact ratio

        :param deltaR: Change in contact ratio
        :type deltaR: float
        :param epsMax: Maximum value of epsilon
        :type epsMax: float

        :returns: float -- Epsilon variation
    """
    if deltaR < 0.1:
        return 0
    elif deltaR > 1.0:
        return epsMax * 0.09
    else:
        return epsMax * 0.09 * deltaR


def main_sequence_iter(game_tree):
    """Provide the 'leftmost' complete sequence of a Coarse_game_tree.

    game_tree -- Coarse_game_tree

    Returns an iterable of property maps.

    If the game has no variations, this provides the complete game. Otherwise,
    it chooses the first variation each time it has a choice.

    """
    while True:
        for properties in game_tree.sequence:
            yield properties
        if not game_tree.children:
            break
        game_tree = game_tree.children[0]


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

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

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


def enum_chargelst(chargelst_lin):
    """
    Make a list of integers from 0 to 2^nsingle having nesting of chargelst_lin.

    Parameters
    ----------
    chargelst_lin : list of lists
        Constructed by construct_chargelst(nsingle).

    Returns
    -------
    chargelst : list of lists
    """
    ncharge = len(chargelst_lin)
    chargelst = [[] for i in range(ncharge)]
    counter1 = 0
    for j1 in range(ncharge):
        counter2 = counter1 + len(chargelst_lin[j1])
        chargelst[j1] = list(range(counter1, counter2))
        counter1 = counter2
    return chargelst


def _get_filenames(year, industry_scope=None):
    """Return filenames for oes files based on pattern.

    Parameters
    ----------
    year : string
        4 digit year in string format 'YYYY'.

    Returns
    -------
    dict.

    """
    if industry_scope == None:
        prefix = 'natsector'
    elif industry_scope == 5 or industry_scope == 6:
        prefix = 'nat5d_6d'
    else:
        prefix = 'nat{}d'.format(industry_scope)
    return {'national': f'oesm{year[2:]}nat/national_M{year}_dl.xlsx',
        'state': f'oesm{year[2:]}st/state_M{year}_dl.xlsx', 'metros':
        f'oesm{year[2:]}ma/MSA_M{year}_dl.xlsx', 'metros-divisions':
        f'oesm{year[2:]}ma/aMSA_M{year}_dl.xlsx', 'non-metros':
        f'oesm{year[2:]}ma/BOS_M{year}_dl.xlsx', 'industry':
        f'oesm{year[2:]}in4/{prefix}_M{year}_dl.xlsx'}