def make_plots(inputs):
    """Make all available plots

    Parameters
    ----------
    inputs: pesummary.cli.summarypageslw.LWInputs
        Namespace object containing all command line arguments
    """
    from pesummary.core.plots.main import _PlotGeneration
    plotting_object = _PlotGeneration(webdir=inputs.webdir, labels=inputs.
        labels, samples=inputs.samples, kde_plot=False, existing_labels=
        None, existing_injection_data=None, existing_samples=None,
        same_parameters=inputs.same_parameters, injection_data=inputs.
        injection_data, colors=inputs.colors, custom_plotting=None,
        add_to_existing=False, priors=None, disable_comparison=False,
        linestyles=None, disable_interactive=False)
    plotting_object.generate_plots()


def are_conserved_aas(aa1, aa2):
    """Determines if two amino acids are conserved based on the paper
    'Structural Determinants in the Sequences of Immunoglobulin Variable
    Domain'"""
    groups = ['WFILMVC', 'PYTHSAG', 'KEQNRD']
    for g in groups:
        if aa1.upper() in g and aa2.upper() in g:
            return True
    return False


@classmethod
def int_safe(cls, s):
    """
        Only allow safe str and valid int to be coerced to destination IntType
        """
    if isinstance(s, bool):
        raise TypeError(f'{s} is not a integer')
    if isinstance(s, int):
        cls.check_value(s)
        return s
    if not isinstance(s, str):
        raise TypeError(f'{s} is not instance of <str>.')
    if len(s) < 1:
        raise TypeError(f"'{s}' is empty.")
    len_min = len(str(cls.min_value))
    len_max = len(str(cls.max_value))
    if len(s) > max(len_min, len_max):
        raise TypeError(
            f'Length of {s} is larger than max:{max(len_min, len_max)}.')
    ret = int(s)
    cls.check_value(ret)
    return ret


def lambd_NH3_Ca_CB89(T, P):
    """n-c: ammonia calcium [CB89]."""
    lambd = -0.081
    valid = T == 298.15
    return lambd, valid


def first(resolve=True):
    """ Return the first element in the sequence.  If ``resolve`` is True,
        and the result set has a valid resolver, return the resolved
        document, otherwise return the document id of the first document. """


def channels_group(name: str='NewGroup'):
    """Add selected F-Curves to a new group

    :param name: Name, Name of newly created group
    :type name: str
    """
    pass


def _if(parent, arg):
    """Return the value only if condition is met."""
    if parent is None:
        return arg if arg else ''
    return parent if parent == arg else ''


def mailPassword(forgotten_userid, REQUEST):
    """ Email a forgotten password to a member.

        o Raise ValueError if user ID is not found.

        o ???: should probably *not* raise, in order to prevent cracking.

        o Permission:  Mail forgotten password
        """


def string_to_num(s):
    """Converts a string to an int/float

    Returns ``None`` if it can't be converted

    >>> string_to_num('5')
    5
    >>> string_to_num('5.2')
    5.2
    >>> string_to_num(10)
    10
    >>> string_to_num(10.1)
    10.1
    >>> string_to_num('this is not a string') is None
    True
    """
    if isinstance(s, (int, float)):
        return s
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return None


def raise_error(error, info=''):
    """Raise the given error"""
    raise error(info)


def uniq(lst):
    """return lst with unique elements."""
    seen = []
    for _ in lst:
        if _ not in seen:
            seen.append(_)
            yield _


def pytest_assertrepr_compare(config, op, left, right):
    """return explanation for comparisons in failing assert expressions.

    Return None for no custom explanation, otherwise return a list
    of strings.  The strings will be joined by newlines but any newlines
    *in* a string will be escaped.  Note that all but the first line will
    be indented slightly, the intention is for the first line to be a summary.

    :param _pytest.config.Config config: pytest config object
    """


def assignValue(cfg, playerValue, otherValue):
    """artificially determine match results given match circumstances.
    WARNING: cheating will be detected and your player will be banned from server"""
    player = cfg.whoAmI()
    result = {}
    for p in cfg.players:
        if p.name == player.name:
            val = playerValue
        else:
            val = otherValue
        result[p.name] = val
    return result


def has_change_path_cmd(sql):
    """Determines if the search_path should be refreshed by checking if the
    sql has 'set search_path'."""
    return 'set search_path' in sql.lower()


def event(me, email, ip, event, additional={}, timeout=0, backfill=False,
    url='', testmode=False):
    """
        When something interesting happens on your site, tell Deduce.

        Parameters
        ----------
        email : str
          The user's email address.
          It will be processed and hashed, not used directly.
        ip : str
          The user's IP address (v4 or v6)
        event : str
          The evnt type
          Consult with Deduce support to determine the event types.
        additional : dict
          Event data.
          Consult with Deduce support to determine data to send.
          if you pass in 'email_prev' or 'cc' fields, they will be automatically
          processed and hashed, not send directly.

        Return
        ------
        on success : Nothing
        on fail    : an error string

        """
    if not me.__email_valid(email):
        return 'invalid email'
    d = additional.copy()
    d['email'] = email
    d['ip'] = ip
    d['event'] = event
    return me.events([d], timeout, backfill, url, testmode)


def get_doc():
    """Get documentation of this resource

    :return: rst string
    :rtype: str
    """
    return """
    The ``history`` model is used to maintain a log of the received checks results.

    The Alignak backend stores all the checks results it receives to keep a full log of the system
    checks results.
    """


@staticmethod
def inline_code(text):
    """Inline code text converter.

        :param text: a text string.
        :type text: str
        :return: a string like this example: ``'``text``'``
        :rtype: str"""
    return '``' + text + '``'


@classmethod
def scalar(cls, value):
    """Create an ArgumentType with a single scalar in range(value)."""
    return lambda i, name: cls(i, name, (value,), lambda a: a[0], None, None)


def _seconds_to_time(seconds: int) ->str:
    """Converts seconds to a SLURM allocation duration.

    Args:
        seconds: The number of seconds to reserve.

    Returns:
        A string of the form DD:HH:MM:SS.
    """
    seconds_per_day = 60 * 60 * 24
    seconds_per_hour = 60 * 60
    seconds_per_minute = 60
    days = seconds // seconds_per_day
    seconds -= days * seconds_per_day
    hours = seconds // seconds_per_hour
    seconds -= hours * seconds_per_hour
    minutes = seconds // seconds_per_minute
    seconds -= minutes * seconds_per_minute
    return '{:02d}-{:02d}:{:02d}:{:02d}'.format(days, hours, minutes, seconds)


def parse_host_port(address, default_port=None):
    """Interpret a string as a host:port pair.

    An IPv6 address MUST be escaped if accompanied by a port,
    because otherwise ambiguity ensues: 2001:db8:85a3::8a2e:370:7334
    means both [2001:db8:85a3::8a2e:370:7334] and
    [2001:db8:85a3::8a2e:370]:7334.

    >>> parse_host_port('server01:80')
    ('server01', 80)
    >>> parse_host_port('server01')
    ('server01', None)
    >>> parse_host_port('server01', default_port=1234)
    ('server01', 1234)
    >>> parse_host_port('[::1]:80')
    ('::1', 80)
    >>> parse_host_port('[::1]')
    ('::1', None)
    >>> parse_host_port('[::1]', default_port=1234)
    ('::1', 1234)
    >>> parse_host_port('2001:db8:85a3::8a2e:370:7334', default_port=1234)
    ('2001:db8:85a3::8a2e:370:7334', 1234)

    """
    if address[0] == '[':
        _host, _port = address[1:].split(']')
        host = _host
        if ':' in _port:
            port = _port.split(':')[1]
        else:
            port = default_port
    elif address.count(':') == 1:
        host, port = address.split(':')
    else:
        host = address
        port = default_port
    return host, None if port is None else int(port)


def get_analysis_code(sol):
    """
    Maps the solution number to the OP2 analysis code.

     * 8 - post-buckling (maybe 7 depending on NLPARM???)

    # not important
     * 3/4 - differential stiffness (obsolete)
     * 11  - old geometric nonlinear statics
     * 12  - contran (???)

    .. todo:: verify
    """
    codes = {(101): 1, (103): 2, (105): 7, (106): 10, (107): 9, (108): 5, (
        111): 5, (112): 6, (114): 1, (115): 2, (116): 7, (118): 5, (129): 6,
        (144): 1, (145): 1, (146): 1, (153): 10, (159): 6}
    approach_code = codes[sol]
    return approach_code


def thermal_time_constant_as_considered_load(TauR, dTOr, dTOi, dTOu, n):
    """ Returns the average oil time constant in minutes (for a given load)
    As per IEEE C57.91-2011
    TauR = Thermal time constant at rated load
    dTOr = Top oil rise at rated load
    dTOi = Top oil rise initial
    dTOu = Top oil rise ultimate (at load considered)
    n = Temperature cooling exponent (From IEEE C57.91-2011 Table 4)
    """
    a = dTOu / dTOr
    b = dTOi / dTOr
    if a - b == 0 or n == 0:
        STTTC = TauR
    else:
        try:
            STTTC = TauR * (a - b) / (a ** (1 / n) - b ** (1 / n))
        except ZeroDivisionError:
            STTTC = TauR
    return STTTC


def __setitem__(path, node):
    """Define the node value for a path in the manifest.

        If the path is already in the manifest, its flags will be copied to
        the new entry.
        """


def time_diff_in_ms(start, end):
    """ Returns the time difference end-start in ms.
    """
    return (end - start) * 1000


def _is_descriptor(obj):
    """Returns True if obj is a descriptor, False otherwise."""
    return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj,
        '__delete__')


def mem():
    """Returns memory usage tuple of ints: (rss, vsz).

    :rtype: tuple
    """
    return 0, 0


@classmethod
def is_datasource_for(cls, **kwargs):
    """
        Determines if the file corresponds to a GBM summary lightcurve
        `~sunpy.timeseries.TimeSeries`.
        """
    if 'source' in kwargs.keys():
        if kwargs.get('source', ''):
            return kwargs.get('source', '').lower().startswith(cls._source)
    if 'meta' in kwargs.keys():
        return kwargs['meta'].get('INSTRUME', '').startswith('GBM')


def populate():
    """Populate the styles from the configuration files.

        This clears the current set of styles and resets them from those
        defined in the configuration files.
        """


def rename_edge_attribute(topology, old_attr, new_attr):
    """Rename all edges attributes with a specific name to a new name

    Parameters
    ----------
    topology : Topology
        The topology object
    old_attr : any hashable type
        Old attribute name
    new_attr : any hashable type
        New attribute name

    Example
    -------
    >>> import fnss
    >>> topo = fnss.Topology()
    >>> topo.add_edge(1, 2, cost=1)
    >>> topo.add_edge(2, 3, cost=2)
    >>> topo.edges(data=True)
    [(1, 2, {'cost': 1}), (2, 3, {'cost': 2})]
    >>> fnss.rename_edge_attribute(topo, 'cost', 'weight')
    >>> topo.edges(data=True)
    [(1, 2, {'weight': 1}), (2, 3, {'weight': 2})]
    """
    for u, v in topology.edges():
        if old_attr in topology.adj[u][v]:
            topology.adj[u][v][new_attr] = topology.edge[u][v][old_attr]
            del topology.adj[u][v][old_attr]


def hasSortCriterion():
    """Tells if a sort criterai is already setup.
        """


def clear_render_border():
    """Clear the boundaries of the border render and disable border render

    """
    pass


@classmethod
def component_type(cls, node):
    """Return the type.group.label dotted information"""
    if node is None:
        return ''
    return cls.type_formatter.format(type=str(type(node).__name__))


def checksize():
    """Obtain the expected sizes of backing files.

        TODO this is used by verify and it should not be part of the interface.
        """


def meta(str1, str2, ratios, weights):
    """A meta ratio function. Returns a weighted meta ratio.

    The Wiesendahl ratio is a meta ratio which combines a weighted
    ratio of given ratio functions.

    Args:

        str1   (str): first string
        str2   (str): second string
        ratios (list(function(str, str) -> float)): ratio functions
            This parameter is a list of ratio functions.
        weights (list(float)): list of weights
            Each weight gets applied to its corresponding function.

    Returns:
        float: the combined and weighted meta ratio

    """
    c = 0
    r = 0.0
    for i, fn in enumerate(ratios):
        r += fn(str1, str2) * weights[i]
        c += weights[i]
    return r / float(c)


@staticmethod
def _regr_test():
    """
>>> from eyap.core import redis_comments
>>> rc = redis_comments.RedisCommentThread(
...     'test-owner', 'test-realm', 'test-topic', 'test-owner')
>>> rc.delete_thread(really=True)
>>> status = rc.add_comment('test_comment', allow_create=True)
>>> print(', '.join(['%s: %s' % (k, status[k]) for k in sorted(status)]))
lpush: 1, ltrim: None, status: OK
>>> sec = rc.lookup_comments('test-topic')
>>> print(sec.show())  # doctest: +ELLIPSIS
========================================
Subject: test_comment ...
Timestamp: ...
----------
test_comment
        """


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

        :param FileEditCommentDetails val:
        :rtype: EventDetails
        """
    return cls('file_edit_comment_details', val)


@staticmethod
def julian_ephemeris_day(jd, deltat):
    """Calculate the Julian Ephemeris Day from the Julian Day and delta-time = (terrestrial time - universal time) in seconds"""
    return jd + deltat / 86400.0


def get(isamAppliance, check_mode=False, force=False):
    """
    Retrieving a list of all server connections
    """
    return isamAppliance.invoke_get(
        'Retrieving a list of all server connections',
        '/mga/server_connections/v1')


def _send_n_create_rsp(event):
    """Logging handler when an N-CREATE-RSP is sent.

    Parameters
    ----------
    event : events.Event
        The evt.EVT_DIMSE_SENT event that occurred.
    """
    pass


@classmethod
def from_simple_str(cls, s):
    """ Accepts only the output of to_simple_str(). The output of __str__() is invalid as input. """
    if not isinstance(s, str):
        raise TypeError('Expected an str instance, received %r' % (s,))
    return cls(cls.bits_from_simple_str(s))


@staticmethod
def enter(connection, command):
    """
        Enter a command to the channel (with '
' appended)

        @param connection: Connection to the host
        @type connection: L{Connection}

        @param command: command to execute
        @type command: str

        @return: number of bytes actually sent
        @rtype: int
        """
    return connection.channel.send(command + '\n')


def general_commands() ->dict:
    """Lists the available general sub-commands of the 'chado' command with corresponding descriptions"""
    return {'connect':
        'connect to a CHADO database for an interactive session', 'query':
        'query a CHADO database and export the result to a text file'}


def construct_set_string(phage_id_set):
    """Convert set of phage_ids to string formatted for MySQL.

    e.g. set: {'Trixie', 'L5', 'D29'}
    returns: "('Trixie', 'L5', 'D29')""
    """
    string = "('" + "', '".join(phage_id_set) + "')"
    return string


def assert_lrp_epsilon_param(epsilon, caller):
    """
        Function for asserting epsilon parameter choice
        passed to constructors inheriting from EpsilonRule
        and LRPEpsilon.
        The following conditions can not be met:

        epsilon > 1

        :param epsilon: the epsilon parameter.
        :param caller: the class instance calling this assertion function
    """
    if epsilon <= 0:
        err_head = 'Constructor call to {} : '.format(caller.__class__.__name__
            )
        err_msg = err_head + 'Parameter epsilon must be > 0 but was {}'.format(
            epsilon)
        raise ValueError(err_msg)
    return epsilon


def finalize(name, msg, session_id=''):
    """Finalize dict message before sending"""
    msg_dict = {'session': session_id, 'name': name, 'data': msg}
    return msg_dict


def to_root_latex(s):
    """
    Converts latex expressions in a string *s* to ROOT-compatible latex.
    """
    return s.replace('$', '').replace('\\', '#')


def myobj(y, z, v, w):
    """Return value of the objective function with the derivative w.r.t. all variables passed
    """
    return y ** 2 + z - v + w ** 2, 2 * y, 1, -1, 2 * w


def knife_project(cut_through: bool=False):
    """Use other objects outlines & boundaries to project knife cuts

    :param cut_through: Cut through, Cut through all faces, not just visible ones
    :type cut_through: bool
    """
    pass


@classmethod
def pre_create_app(cls, **settings):
    """Run any logic that needs to be done strictly before the app has been
        made.

        The Pre Create Hook will be run immediately before :meth:`create_app`
        is run. It will be given the kwargs that were passed to
        :meth:`create_app` as it's kwargs. It is expected to return
        a dictionary of kwargs that will be passed to the actual App
        ``__init__`` call and to the :meth:`post_create_app` hook.

        Basically, this lets you hook in and parse or change settings
        dynamically. That's it's only goal and what it can do is up to you!

        .. admonition:: Make Sure You Call ``super``!

            A failure to call `super` in a hook method, such as the Pre Create
            Hook, is likely to break your **entire Fleaker App chain**! Make
            sure the very first, or very last, thing that your hook does is
            call `super`!
        """
    return settings


def values(d):
    """Try to return `dict.itervalues()`, else `dict.values()`."""
    try:
        return d.itervalues()
    except AttributeError:
        return d.values()


def CSS_FILE():
    """
    Hardcoded CSS file
    """
    return """
button span {
    font-family: 'Montserrat', sans-serif;
}
button:hover {
    box-shadow: 0px 1px 5px 0px #0000003a;
    transition: all 0.3s ease 0s;
}
a:hover {
    transition: all 0.5s ease 0s !important;
}
#main {
    font-family: 'Roboto Condensed', sans-serif;
}
.hero-head {
    font-family: 'Montserrat', sans-serif;
}
.help {
    font-family: 'Merriweather', serif;
}
.gen-box {
    display: block;
    padding: 1.25rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.25;
    border-bottom: 0.5px solid rgb(228, 228, 228);
}
.gen-box:hover {
    background-color: #ecf0f1;
    transition: all 0.5s ease 0s;
}
.gen-box.warning {
    color: #e74c3c;
    font-weight: 700;
}
"""


@classmethod
def from_header(cls, hdr, pixstep, field=0):
    """Read FSF parameters from a FITS header"""
    raise NotImplementedError


def make_range_string(start, stop=None):
    """Create a byte range specifier in accordance with RFC-2616.

    Parameters
    ----------
    start: int
        The start of the byte range

    stop: int, optional
        The end of the byte range.  If unspecified, indicates EOF.

    Returns
    -------
    str
        A byte range specifier.

    """
    if stop is None:
        return 'bytes=%d-' % start
    return 'bytes=%d-%d' % (start, stop)


@staticmethod
def help():
    """
        This is a function for less experienced python-users. It will print some tipps for working with this Radar
        class. If possible use the documentation, it will be much more likely up to date and contains more information!

        Returns:
            Just prints some help messages into the console
        """
    print(
        """This class provides acces to the radar data from the Max-Planck-Institute owned radars on Barbados.
"""
        )
    print(
        """Input for start and end: can either be a datetime-object or a string.
   If it is a string the it needs to have the format YYYYMMDDhhmmss, where
   Y:Year, M:Month, D:Day, h:Hour, m:Minute, s:Second.
   Missing steps will be appended automatically with the lowest possible value. Example:
   input='2017' -> '20170101000000'.
"""
        )
    print(
        'Be careful with the timeframe as 1 month of data takes about 1GB of ram.\n'
        )
    print('Input for Version: Can be one of 1,[2],3\n')
    print(
        """reflectivity: can be called with parameter 'postprocessing'.
   This can be one of [Zf],Ze,Zg,Zu.
     Zf: Filtered and Mie corrected Radar Reflectivity of all Hydrometeors
     Ze: Unfiltered Equivalent Radar Reflectivity of all Hydrometeors
     Zu: Unfiltered and Mie corrected Radar Reflectivity of all Hydrometeors
     Zg: Unfiltered Equivalent Radar Reflectivity of all Targets (global)
   Note: not all parameters might be available for every data_version"""
        )
    print(
        """Please have a look at the documentation. It contains examples for many usecases.
www.hereWillBeTheDocumentationAtSomePoint.de
at the moment: docs/_build/html/index.html"""
        )


def merge_dicts(*dicts):
    """Merge multiple dicts into one."""
    context = {}
    for d in dicts:
        context.update(d)
    return context


def amortization_iof(amortization, num_days, daily_iof_aliquot=8.2e-05):
    """IOF tax over amortization.

    If :math:`A` is the amortization, :math:`I^*` is the daily IOF fee and
    :math:`n` is the number of days since taxable event, then the due IOF tax
    over the amortization is

    .. math::

        A\\ \\min(nI^*, 0.015).

    Parameters
    ----------
    amortization: float, required
        The amortization, i.e., principal payment, which is the basis for the
        amortization IOF tax.
    daily_iof_aliquot: float, required
        Aliquot applied over the amortization with its value define by law.
    num_days: int, required
        Number of days since the taxable event.
    """
    return float(amortization * min(daily_iof_aliquot * num_days, 0.015))


def run_probabilistic(mfts, partitioner, train_data, test_data, window_key=
    None, **kwargs):
    """
    Run the probabilistic forecasting benchmarks

    :param mfts: FTS model
    :param partitioner: Universe of Discourse partitioner
    :param train_data: data used to train the model
    :param test_data: ata used to test the model
    :param steps:
    :param resolution:
    :param window_key: id of the sliding window
    :param transformation: data transformation
    :param indexer: seasonal indexer
    :return: a dictionary with the benchmark results
    """
    import time
    import numpy as np
    from pyFTS.models import hofts, ifts, pwfts
    from pyFTS.models.ensemble import ensemble
    from pyFTS.partitioners import Grid, Entropy, FCM
    from pyFTS.benchmarks import Measures, arima, quantreg, knn
    from pyFTS.models.seasonal import SeasonalIndexer
    tmp = [hofts.HighOrderFTS, ifts.IntervalFTS, pwfts.
        ProbabilisticWeightedFTS, arima.ARIMA, ensemble.
        AllMethodEnsembleFTS, knn.KNearestNeighbors]
    tmp2 = [Grid.GridPartitioner, Entropy.EntropyPartitioner, FCM.
        FCMPartitioner]
    tmp3 = [Measures.get_distribution_statistics, SeasonalIndexer.
        SeasonalIndexer, SeasonalIndexer.LinearSeasonalIndexer]
    indexer = kwargs.get('indexer', None)
    steps_ahead = kwargs.get('steps_ahead', 1)
    method = kwargs.get('method', None)
    if mfts.benchmark_only:
        _key = mfts.shortname + str(mfts.order if mfts.order is not None else
            '') + str(mfts.alpha)
    else:
        pttr = str(partitioner.__module__).split('.')[-1]
        _key = mfts.shortname + ' n = ' + str(mfts.order
            ) + ' ' + pttr + ' q = ' + str(partitioner.partitions)
        mfts.partitioner = partitioner
        mfts.append_transformation(partitioner.transformation)
    _key += str(steps_ahead)
    _key += str(method) if method is not None else ''
    if mfts.has_seasonality:
        mfts.indexer = indexer
    _start = time.time()
    mfts.fit(train_data, **kwargs)
    _end = time.time()
    times = _end - _start
    _crps1, _t1, _brier = Measures.get_distribution_statistics(test_data,
        mfts, **kwargs)
    _t1 += times
    ret = {'key': _key, 'obj': mfts, 'CRPS': _crps1, 'time': _t1, 'brier':
        _brier, 'window': window_key, 'steps': steps_ahead, 'method': method}
    return ret


def layer_duplicate():
    """Make a copy of the active Grease Pencil layer

    """
    pass


def create_cluster_subnet_group(ClusterSubnetGroupName=None, Description=
    None, SubnetIds=None, Tags=None):
    """
    Creates a new Amazon Redshift subnet group. You must provide a list of one or more subnets in your existing Amazon Virtual Private Cloud (Amazon VPC) when creating Amazon Redshift subnet group.
    For information about subnet groups, go to Amazon Redshift Cluster Subnet Groups in the Amazon Redshift Cluster Management Guide .
    See also: AWS API Documentation

    :example: response = client.create_cluster_subnet_group(
        ClusterSubnetGroupName='string',
        Description='string',
        SubnetIds=[
            'string',
        ],
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type ClusterSubnetGroupName: string
    :param ClusterSubnetGroupName: [REQUIRED]
            The name for the subnet group. Amazon Redshift stores the value as a lowercase string.
            Constraints:
            Must contain no more than 255 alphanumeric characters or hyphens.
            Must not be 'Default'.
            Must be unique for all subnet groups that are created by your AWS account.
            Example: examplesubnetgroup

    :type Description: string
    :param Description: [REQUIRED]
            A description for the subnet group.

    :type SubnetIds: list
    :param SubnetIds: [REQUIRED]
            An array of VPC subnet IDs. A maximum of 20 subnets can be modified in a single request.
            (string) --

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

    :rtype: dict
    :return: {
        'ClusterSubnetGroup': {
            'ClusterSubnetGroupName': 'string',
            'Description': 'string',
            'VpcId': 'string',
            'SubnetGroupStatus': 'string',
            'Subnets': [
                {
                    'SubnetIdentifier': 'string',
                    'SubnetAvailabilityZone': {
                        'Name': 'string'
                    },
                    'SubnetStatus': 'string'
                },
            ],
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ]
        }
    }

    """
    pass


def get_role(RoleName=None):
    """
    Retrieves information about the specified role, including the role's path, GUID, ARN, and the role's trust policy that grants permission to assume the role. For more information about roles, see Working with Roles .
    See also: AWS API Documentation

    Examples
    The following command gets information about the role named Test-Role.
    Expected Output:

    :example: response = client.get_role(
        RoleName='string'
    )

    :type RoleName: string
    :param RoleName: [REQUIRED]
            The name of the IAM role to get information about.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: _+=,.@-

    :rtype: dict
    :return: {
        'Role': {
            'Path': 'string',
            'RoleName': 'string',
            'RoleId': 'string',
            'Arn': 'string',
            'CreateDate': datetime(2015, 1, 1),
            'AssumeRolePolicyDocument': 'string',
            'Description': 'string'
        }
    }

    """
    pass


def first_true(iterable, key=lambda x: x, default=None):
    """
        Return the first item of any iterable for which the key is True.

        By default the key is the entire element.

        If the iterable is empty, return the default value.
    """
    for x in iterable:
        if key(x):
            return x
    return default


@staticmethod
def create_replication(src_lun, max_time_out_of_sync, dst_pool_id,
    remote_system):
    """Creates a new lun on remote system and sets up replication to it."""
    return src_lun.replicate_with_dst_resource_provisioning(
        max_time_out_of_sync, dst_pool_id, remote_system=remote_system,
        dst_lun_name=src_lun.name)


def load_scipy_special__cephes(finder, module):
    """the scipy.special._cephes is an extension module and the scipy module
       imports * from it in places; advertise the global names that are used
       in order to avoid spurious errors about missing modules."""
    module.AddGlobalName('gammaln')


def single_phase_options(printout=True):
    """Retrieve all the options for direct radation"""
    if printout:
        print(
            "Can also set functional form of forward/back scattering in approx['TTHG_params']"
            )
    return ['cahoy', 'OTHG', 'TTHG', 'TTHG_ray']


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


def pre_ce_moves(mas, agents, target, moves):
    """
    Return the set of moves of mas such that there exists a move for agents
    in moves such that all reached states have a move in target.

    mas -- a multi-agent system;
    agents -- a subset of agents of mas;
    target -- a subset of moves for agents;
    moves -- a set of moves for agents.
    """
    agents_cube = mas.inputs_cube_for_agents(agents)
    others_cube = mas.bddEnc.inputsCube - agents_cube
    states = target.forsome(mas.bddEnc.inputsCube)
    moves = moves.forsome(others_cube)
    states = states & mas.bddEnc.statesMask
    nstates = ~states & mas.bddEnc.statesMask
    moves = moves & mas.bddEnc.statesInputsMask
    return ((~mas.weak_pre(nstates).forsome(others_cube) & mas.weak_pre(
        states)).forsome(others_cube) & moves).forsome(others_cube)


@classmethod
def write_mode(cls, format):
    """
        Return the correct write mode for this type of format.
        """
    if format == cls.PICKLE:
        return 'wb'
    else:
        return 'w'


def has_meta_cmd(query):
    """Determines if the completion needs a refresh by checking if the sql
    statement is an alter, create, drop, commit or rollback."""
    try:
        first_token = query.split()[0]
        if first_token.lower() in ('alter', 'create', 'drop', 'commit',
            'rollback'):
            return True
    except Exception:
        return False
    return False


@classmethod
def clone(cls, *mixins, **attributes):
    """Return a subclass with the given attributes.

        If a model is found, it will prefix the class name with the model.
        """
    name = cls.__name__
    model = attributes.get('model', getattr(cls, 'model', None))
    if model is None:
        model = getattr(cls, 'model', None)
    if model and model.__name__ not in cls.__name__:
        name = '{}{}'.format(model.__name__, cls.__name__)
    return type(name, (cls,) + mixins, attributes)


def lorentzian(x, amp, freq, HWHM):
    """compute a Lorentzian peak

    Inputs
    ------
    x : ndarray
        the positions at which the signal should be sampled
    amp : float or ndarray with size equal to x.shape
        amplitude
    freq : float or ndarray with size equal to x.shape
        frequency/position of the Gaussian component
    HWHM : float or ndarray with size equal to x.shape
        half-width at half-maximum

    Returns
    -------
    out : ndarray
        the signal

    Remarks
    -------
    Formula is amp/(1+((x-freq)/HWHM)**2)
    """
    return amp / (1 + ((x - freq) / HWHM) ** 2)


def ncol(records):
    """Return the number of columns in the records

    :param records: a list of dictionaries
    :returns: an integer

    >>> movies = [
    ... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
    ... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
    ... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
    ... ]
    >>> ncol(movies)
    4

    """
    return len(records[0])


def setTracebackClearing(clear=True):
    """
    Enable or disable traceback clearing.
    By default, clearing is disabled and Python will indefinitely store unhandled exception stack traces.
    This function is provided since Python's default behavior can cause unexpected retention of
    large memory-consuming objects.
    """
    global clear_tracebacks
    clear_tracebacks = clear


def discretize_N(x, N=4):
    """
    transform float `x` from [0.,1.] to int [0,N]
    """
    return int((max(x, 0.0) + 1.0 / (2.0 * N)) * N)


@staticmethod
def validate_mime_type(mimetype):
    """Validate the mimetype string."""
    valid_prefixes = ['application', 'audio', 'font', 'example', 'image',
        'message', 'model', 'mulitpart', 'text', 'video']
    validated = False
    for prefix in valid_prefixes:
        if prefix + '/' == mimetype[:len(prefix) + 1]:
            validated = True
    return validated


def flagged(flag):
    """
    Return special character denoting concretization happened.
    """
    return '(*)' if flag else ''


def _after(date):
    """
    Returns a query item matching messages sent after a given date.

    Args:
        date (str): The date messages must be sent after.

    Returns:
        The query string.

    """
    return f'after:{date}'


def find_members(subscriber=None, list_id=None, role=None):
    """Search for members matching some criteria.

        The members are sorted first by list-id, then by subscribed
        email address, then by role.  Because the user may be a member
        of the list under multiple roles (e.g. as an owner and as a
        digest member), the member can appear multiple times in this
        list.

        :param subscriber: The email address or user id of the user getting
            subscribed.  This argument may contain asterisks, which will be
            interpreted as wildcards in the search pattern.
        :type subscriber: string or int
        :param list_id: The list id of the mailing list to search for the
            subscriber's memberships on.
        :type list_id: string
        :param role: The member role.
        :type role: `MemberRole`
        :return: A sequence of all memberships, which may be empty.
        :rtype: A `QuerySequence` of `IMember`
        """


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


def snr_two_image(image, ref):
    """
    Two image signal to noise ratio after [1].

    Parameters
    ----------
    image : 2-D array
        Input image used to calculate SNR.
    ref : 2-D array
        Reference image used to calculate SNR.

    Returns
    -------
    snr : float
        The signal to noise ratio.

    Notes
    -----
    This implementation assumes the images are aligned.

    References
    ----------
    1. J. Frank, The Role of Correlation Techniques in Computer Image Processing. In Computer Processing of Electron Microscope Images (Ed. Peter W. Hawkes), Springer Heidelberg, Berlin (1980).
    https://link.springer.com/chapter/10.1007/978-3-642-81381-8_5

    """
    cc = (image * ref).sum() / image.size
    im, iv = image.mean(), image.std()
    rm, rv = ref.mean(), ref.std()
    rho = (cc - im * rm) / (iv * rv)
    snr = rho / (1 - rho)
    return snr


def read_utf8(fh, byteorder, dtype, count, offsetsize):
    """Read tag data from file and return as unicode string."""
    return fh.read(count).decode('utf-8')


def smaller_or_equal(old_value, value):
    """Checks if a value is an improvement. Smaller values are improvements.

    Parameters
    ----------
    old_value : int or float
        The old value.
    value : int or float
        The new value that is checked.

    Returns
    -------
    bool
        Returns true if the new value is smaller or equal to the old value,
        else returns false.

    Examples
    --------
    Some simple tests:

    .. doctest::

        >>> from lclpy.aidfunc.is_improvement_func import smaller_or_equal
        >>> smaller_or_equal(2, 5)
        False
        >>> smaller_or_equal(5, 2)
        True
        >>> smaller_or_equal(3,3)
        True

    """
    return value <= old_value


@staticmethod
def join_path(prefix, path):
    """
        Policy to merge a prefix and a path in this protocol.

        :param prefix: prefix to add to the current path.
        :type prefix: str
        :param path: path to the file in the remote.
        :type path: str
        :returns: result of joining the prefix and the path for this protocol.
        :rtype: str
        """
    while prefix.endswith('/'):
        prefix = prefix[:-1]
    while path.startswith('/'):
        path = path[1:]
    return prefix + '//' + path


@classmethod
def by_json(cls, data, read_only=False, **kw):
    """ Creates a new instance and calls from_json on the instance.

            Will take kwargs and pass to the underlying instance
            initializer.

            :param class cls: Class method is running on
            :param str data: JSON string to create object from
            :param bool read_only: Set object read-only
            :param dict **kw: Object initializer options
            :rtype: cls
            :returns: new BrineObject subclass instance
        """
    inst = cls(**kw)
    inst.from_json(data)
    if read_only:
        inst.read_only()
    return inst


def unique(s):
    """Return a list of the elements in s, but without duplicates.

    For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
    unique("abcabc") some permutation of ["a", "b", "c"], and
    unique(([1, 2], [2, 3], [1, 2])) some permutation of
    [[2, 3], [1, 2]].

    For best speed, all sequence elements should be hashable.  Then
    unique() will usually work in linear time.

    If not possible, the sequence elements should enjoy a total
    ordering, and if list(s).sort() doesn't raise TypeError it's
    assumed that they do enjoy a total ordering.  Then unique() will
    usually work in O(N*log2(N)) time.

    If that's not possible either, the sequence elements must support
    equality-testing.  Then unique() will usually work in quadratic
    time.
    """
    n = len(s)
    if n == 0:
        return []
    u = {}
    try:
        for x in s:
            u[x] = 1
    except TypeError:
        pass
    else:
        return list(u.keys())
    del u
    try:
        t = sorted(s)
    except TypeError:
        pass
    else:
        assert n > 0
        last = t[0]
        lasti = i = 1
        while i < n:
            if t[i] != last:
                t[lasti] = last = t[i]
                lasti = lasti + 1
            i = i + 1
        return t[:lasti]
    del t
    u = []
    for x in s:
        if x not in u:
            u.append(x)
    return u


def const_positive(x):
    """A constraint function that :math:`x > 0`."""
    return x > 0


@classmethod
def fromData(cls, type, data, startOffset):
    """
        Create an instrument from raw file data.

        This method must be implemented in subclasses; this
        abstract-base-class implementation simply raises
        NotImplementedError.
        """
    raise NotImplementedError('Override fromData() in Instrument subclasses!')


def __call__(context, request, args):
    """Returns a dictionary of query arguments which are used by
       the catalog in 'searchResults'.

         - `context` is the context in which the request was made.

         - `request` is the REQUEST as passed to
           `CatalogTool.searchResults`.

         - `args` is a dictionary that holds all search request info.
           It contains arguments from request and kwargs passed to
           `CatalogTool.searchResults`.
       """


@classmethod
def get_uri(cls, search_string, search_spec='ip'):
    """Get the URI for an item

            :param company: The name of the company you need the URI for

            :return: returns servers response to the GET request
        """
    return super().get_uri(uri=cls.uri, search_spec=search_spec,
        search_string=search_string)


@staticmethod
def drop_leap(resource):
    """Drop Feb 29th from resource df with time index.

        Parameters
        ----------
        resource : pd.DataFrame
            Resource dataframe with an index containing a pandas
            time index object with month and day attributes.

        Returns
        -------
        resource : pd.DataFrame
            Resource dataframe with all February 29th timesteps removed.
        """
    if hasattr(resource, 'index'):
        if hasattr(resource.index, 'month') and hasattr(resource.index, 'day'):
            leap_day = (resource.index.month == 2) & (resource.index.day == 29)
            resource = resource.drop(resource.index[leap_day])
    return resource


def select_linked():
    """Select all points in same strokes as already selected points

    """
    pass


def looks_like_partition(dir_name):
    """
    True if the directory name is a valid partition number, False otherwise.
    """
    try:
        part = int(dir_name)
        return part >= 0
    except ValueError:
        return False


def split():
    """Split selected strips at their midpoints

    """
    pass


def calc_strike_temp(WaterVolInQuarts, GrainMassInPounds, GrainTemp, MashTemp):
    """
    Calculates the proper strike water temperature for mashing. All arguments should be floats or ints
    """
    WaterToGrainRatio = WaterVolInQuarts / GrainMassInPounds
    StrikeWaterTemp = 0.2 / WaterToGrainRatio * (MashTemp - GrainTemp
        ) + MashTemp
    return round(StrikeWaterTemp, 1)


def reduce_to_unit(divider):
    """
    Reduce a repeating divider to the smallest repeating unit possible.

    This function is used by :meth:`make_div`.

    :param divider: The divider.
    :type divider: str
    :return: Smallest repeating unit possible.
    :rtype: str

    :Example: 'XxXxXxX' -> 'Xx'
    """
    for unit_size in range(1, len(divider) // 2 + 1):
        length = len(divider)
        unit = divider[:unit_size]
        divider_item = divider[:unit_size * (length // unit_size)]
        if unit * (length // unit_size) == divider_item:
            return unit
    return divider


def clean_hex(d):
    """Convert decimal to hex and remove the "L" suffix that is appended to
    large numbers.

    :param d:
    :return:
    """
    return hex(d).rstrip('L')


def get_resource_filename(path):
    """A uniform interface for internal/open-source filenames."""
    return path


def list_tags_for_resource(ResourceARN=None, Marker=None, Limit=None):
    """
    Lists the tags that have been added to the specified resource. This operation is only supported in the cached volume, stored volume and tape gateway architecture.
    See also: AWS API Documentation

    Examples
    Lists the tags that have been added to the specified resource.
    Expected Output:

    :example: response = client.list_tags_for_resource(
        ResourceARN='string',
        Marker='string',
        Limit=123
    )

    :type ResourceARN: string
    :param ResourceARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the resource for which you want to list tags.

    :type Marker: string
    :param Marker: An opaque string that indicates the position at which to begin returning the list of tags.

    :type Limit: integer
    :param Limit: Specifies that the list of tags returned be limited to the specified number of items.

    :rtype: dict
    :return: {
        'ResourceARN': 'string',
        'Marker': 'string',
        'Tags': [
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    }

    :returns:
    (dict) --
    Key (string) --
    Value (string) --

    """
    pass


def tup_sum(tuple):
    """
    definition: name(tuple) {...}
    objective : returns the sum of all elements in the given tuple
    """
    sum = 0
    for element in tuple:
        sum += element
    return sum


def is_response_to_head(response):
    """
    Checks whether the request of a response has been a HEAD-request.
    Handles the quirks of AppEngine.

    :param conn:
    :type conn: :class:`httplib.HTTPResponse`
    """
    method = response._method
    if isinstance(method, int):
        return method == 3
    return method.upper() == 'HEAD'


@classmethod
def to_int(cls, bound_str):
    """
        Encode a string as an int for serialization.
        """
    return cls._bound_str_to_int_map[bound_str.upper()]


def encode_key(value):
    """Encode an S3Key, this is just a link to
	the S3 URL, with a special __s3key__ type"""
    ret = {'__type__': '__s3key__'}
    ret['__href__'] = value.generate_url(3600)
    return ret


def add_matrix(X, Y):
    """Adds two matrices"""
    result = [[(0.0) for x in range(len(X))] for y in range(len(X))]
    for i in range(len(X)):
        for j in range(len(X)):
            result[i][j] = X[i][j] + Y[i][j]
    return result


def create_repeated_indexes(data):
    """
    Convenience function. Given an array-like with length N,
    returns a generator that yields N indexes [0, 1, ..., N].
    """
    from numpy import arange
    index_range = arange(0, len(data))
    return (index_range for i in index_range)


def obfuscate_API_key(API_key):
    """
    Return a mostly obfuscated version of the API Key

    :param API_key: input string
    :return: str
    """
    if API_key is not None:
        return (len(API_key) - 8) * '*' + API_key[-8:]


@classmethod
def MultimodalLogNormalDistribution(cls, rmin, rmax):
    """Set 6S to use a Multimodal Log-Normal distribution.

        Arguments:

        * ``rmin`` -- The minimum aerosol radius
        * ``rmax`` -- The maximum aerosol radius

        This returns an :class:`.AerosolDistribution` object. Components can then be added to this distribution using the :meth:`.add_component`
        method of the returned class.

        Example usage::

          s.aeroprofile = AeroProfile.MultimodalLogNormalDistribution(0.3, 0.1)
          s.aeroprofile.add_component(...)

        """
    return cls.AerosolDistribution(rmin, rmax, 8)


def _GenerateCRCTable():
    """Generate a CRC-32 table.

        ZIP encryption uses the CRC32 one-byte primitive for scrambling some
        internal keys. We noticed that a direct implementation is faster than
        relying on binascii.crc32().
        """
    poly = 3988292384
    table = [0] * 256
    for i in range(256):
        crc = i
        for j in range(8):
            if crc & 1:
                crc = crc >> 1 & 2147483647 ^ poly
            else:
                crc = crc >> 1 & 2147483647
        table[i] = crc
    return table


@staticmethod
def getLinesSuffix(lineRange):
    """Provides the proper suffix for the selected item tooltips"""
    if lineRange[0] == lineRange[1]:
        return 'line ' + str(lineRange[0])
    return 'lines ' + str(lineRange[0]) + '-' + str(lineRange[1])


def get_mod_mappings(mappings):
    """
    Returns a dict of all known modification mappings.

    Parameters
    ----------
    mappings: collections.abc.Iterable[vermouth.map_parser.Mapping]
        All known mappings.

    Returns
    -------
    dict[tuple[str], vermouth.map_parser.Mapping]
        All mappings that describe a modification mapping.
    """
    out = {}
    for mapping in mappings:
        if mapping.type == 'modification':
            out[mapping.names] = mapping
    return out


def Custom(*data, **kwargs):
    """Apply a custom operator implemented in a frontend language (like Python).

    Custom operators should override required methods like `forward` and `backward`.
    The custom operator must be registered before it can be used.
    Please check the tutorial here: https://mxnet.incubator.apache.org/api/faq/new_op

    Defined in src/operator/custom/custom.cc:L546

    Parameters
    ----------
    data : Symbol[]
        Input data for the custom operator.
    op_type : string
        Name of the custom operator. This is the name that is passed to `mx.operator.register` to register the operator.

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

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


def rf_duration(rf_event, dt):
    """Return the duration of the rf event (array) based on the number of the points and  dt.

    Args:
        rf_event (np.array): An array of event.
        dt (float [s]): Value of time resolution.

    Returns:
        float [s]: duration of the event.

    Todo:
        Regard the dimensions of the array.

    """
    size = rf_event.size
    return size * dt


def set_verbosity(level):
    """Sets the modules message verbosity level for *all* messages printed.

    :arg level: a positive integer (>0); higher levels including more detail.
    """
    global verbosity
    verbosity = level


def _call_constructed(class_reference, instance):
    """Check if a property is allowed to be unhandled."""
    if not hasattr(class_reference, '__deserialize_constructed__'):
        return
    class_reference.__deserialize_constructed__(instance)


def upper_transform(mean, bound, logbase):
    """ Log transformation scaling.

    Examples
    --------
    Untransformed data looks as so:

        Yupper = Ymean + bound
        Ylower = Ymean - bound

    We want log(bounds)
        ie.
            log(Yupper) - log(Ymean)
            log(Ylower) + log(Ymean)

    so log(bound) = log(1 + bound/Ymean)
       log(bound) = log(1 - bound/Ymean)
    """
    return abs(logbase((mean + bound) / mean))


def byte2bit_string(data):
    """
    >>> byte2bit_string(0x1b)
    '00011011'
    """
    return '{0:08b}'.format(data)


def full_3x3_to_Voigt_6_index(i, j):
    """
    Conversion of tensor to Voigt notation for indices

    """
    if i == j:
        return i
    return 6 - i - j


def valuate_position(position, tdate):
    """Valuate the position for the given date.

    Parameters
    ----------
    position : alphapy.Position
        The position to be valued.
    tdate : timedate
        Date to value the position.

    Returns
    -------
    position : alphapy.Position
        New value of the position.

    Notes
    -----

    An Example of Cost Basis

    ======== ====== ====== ======
    Date     Shares Price  Amount
    ======== ====== ====== ======
    11/09/16  +100   10.0   1,000
    12/14/16  +200   15.0   3,000
    04/05/17  -500   20.0  10,000
    -------- ------ ------ ------
    All        800         14,000
    ======== ====== ====== ======

    The cost basis is calculated as the total value of all
    trades (14,000) divided by the total number of shares
    traded (800), so 14,000 / 800 = 17.5, and the net position
    is -200.

    """
    pdata = position.pdata
    if tdate in pdata.index:
        cp = float(pdata.loc[tdate]['close'])
        multiplier = position.multiplier
        netpos = 0
        tts = 0
        ttv = 0
        totalprofit = 0.0
        for trade in position.trades:
            tq = trade.quantity
            netpos = netpos + tq
            tts = tts + abs(tq)
            tp = trade.price
            pfactor = tq * multiplier
            cv = pfactor * cp
            cvabs = abs(cv)
            ttv = ttv + cvabs
            ev = pfactor * tp
            totalprofit = totalprofit + cv - ev
        position.quantity = netpos
        position.price = cp
        position.value = abs(netpos) * multiplier * cp
        position.profit = totalprofit
        position.costbasis = ttv / tts
        position.netreturn = totalprofit / cvabs - 1.0
    return position


@classmethod
def translate_str(cls, val):
    """Default behavior for translation"""
    return cls.translate_escaped_str(val)


def verify_indices_all_unique(obj):
    """
    Check that all axes of a pandas object are unique.

    Parameters
    ----------
    obj : pd.Series / pd.DataFrame / pd.Panel
        The object to validate.

    Returns
    -------
    obj : pd.Series / pd.DataFrame / pd.Panel
        The validated object, unchanged.

    Raises
    ------
    ValueError
        If any axis has duplicate entries.
    """
    axis_names = [('index',), ('index', 'columns'), ('items', 'major_axis',
        'minor_axis')][obj.ndim - 1]
    for axis_name, index in zip(axis_names, obj.axes):
        if index.is_unique:
            continue
        raise ValueError('Duplicate entries in {type}.{axis}: {dupes}.'.
            format(type=type(obj).__name__, axis=axis_name, dupes=sorted(
            index[index.duplicated()])))
    return obj


def convert_by_vocab(vocab, items):
    """Converts a sequence of [tokens|ids] using the vocab."""
    output = []
    for item in items:
        output.append(vocab[item])
    return output


def all_methods(obj):
    """
    Return a list of names of methods of `obj`
    """
    temp = []
    for name in dir(obj):
        func = getattr(obj, name)
        if callable(func):
            temp.append(name)
    return temp


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


def RelsRiskAdj(t):
    """Release of Risk Adjustment to Revenue

    Warning:
        To be implemented.
    """
    return 0


def timestamp_to_unix(timestamp):
    """Convert a NILM timestamp (integer microseconds since epoch)
    into a Unix timestamp (floating point seconds since epoch)"""
    return timestamp / 1000000.0


def _repeat_stream(stream, n_devices):
    """Repeat a stream indefinitely."""
    while True:
        for example in stream(n_devices):
            yield example


def convert_rgb_to_rgba(row, result):
    """Convert an RGB image to RGBA. This method assumes the
        alpha channel in result is already correctly initialized.
        """
    for i in range(3):
        result[i::4] = row[i::3]


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


def degrees(data=None, name=None, attr=None, out=None, **kwargs):
    """Converts each element of the input array from radians to degrees.

    .. math::
       degrees([0, \\pi/2, \\pi, 3\\pi/2, 2\\pi]) = [0, 90, 180, 270, 360]

    The storage type of ``degrees`` output depends upon the input storage type:

       - degrees(default) = default
       - degrees(row_sparse) = row_sparse
       - degrees(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L274

    Parameters
    ----------
    data : Symbol
        The input array.

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

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


def _get_approx_string_width(text, font_width, fixed_width=False):
    """
    Get the approximate width of a string using a specific average font width.

    Args:
        text(str): Text string to calculate width of.
        font_width(int): Average width of font characters.
        fixed_width(bool): Indicates that the font is fixed width.

    Returns:
        int: Width of string in pixels.

    Examples:

        Call the function with a string and the maximum character width of the font you are using:

            >>> int(_get_approx_string_width('hello', 10))
            29

        This example shows the comparison of simplistic calculation based on a fixed width.
        Given a test string and a fixed font width of 10, we can calculate the width
        by multiplying the length and the font character with:

            >>> test_string = 'GOOGLE|ijkl'
            >>> _get_approx_string_width(test_string, 10, fixed_width=True)
            110

        Since some characters in the string are thinner than others we expect that the
        apporximate text width will be narrower than the fixed width calculation:

            >>> _get_approx_string_width(test_string, 10)
            77

    """
    if fixed_width:
        return len(text) * font_width
    size = 0.0
    char_width_percentages = {"lij|' ": 40.0, '![]fI.,:;/\\t': 50.0,
        '`-(){}r"': 60.0, '*^zcsJkvxy': 70.0,
        'aebdhnopqug#$L+<>=?_~FZT0123456789': 70.0, 'BSPEAKVXY&UwNRCHD':
        70.0, 'QGOMm%W@': 100.0}
    for s in text:
        percentage = 100.0
        for k in char_width_percentages.keys():
            if s in k:
                percentage = char_width_percentages[k]
                break
        size += percentage / 100.0 * float(font_width)
    return int(size)


def is_tree(obj):
    """Determine if the object is a tree-like."""
    return hasattr(obj, 'documents')


def create_dt_url(dt, root, fname, subdirs=[]):
    """
    Create URLs from root + fname and a list of subdirectories.
    fname and subdirs will be put through dt.strftime.

    Parameters
    ----------
    dt: datetime.datetime
        date as basis for the URL
    root: string
        root of the url
    fname: string
        filename to use
    subdirs: list, optional
        list of strings.
        Each element represents a subdirectory.
        For example the list ['%Y', '%m'] would lead to a URL of
        ``root/YYYY/MM/fname`` or for a dt of datetime(2000,12,31)
        ``root/2000/12/fname``

    Returns
    -------
    url: string
    """
    dt_subdirs = []
    for subdir in subdirs:
        dt_subdirs.append(dt.strftime(subdir))
    dt_fname = dt.strftime(fname)
    url = '/'.join([root] + dt_subdirs + [dt_fname])
    return url


def get_elk_command(line):
    """Return the 2 character command in the message."""
    if len(line) < 4:
        return ''
    return line[2:4]


@classmethod
def _get_attribute_for_field(cls, field):
    """
        Get the model class attribute/descriptor from property instance
        (e.g. ``ColumnProperty`` class or related)
        """
    return field.class_attribute


def getHost():
    """
        Similar to getPeer, but returns an address describing this side of the
        connection.

        @return: An L{IAddress} provider.
        """


def __delitem__(name):
    """Delete a file or directory inside this directory
        """


def create_coordinate_clusters(coordinates, cluster_labels):
    """
    Create cluster arrays of the input coordinate data from cluster labels.
    """
    clusters = []
    last_label, cluster = None, None
    for idx, label in enumerate(cluster_labels):
        is_new_cluster = label != -1 and last_label != label
        if is_new_cluster:
            if cluster:
                clusters.append(cluster)
            cluster = []
            last_label = label
        if label != -1:
            cluster.append(coordinates[idx])
    return clusters


def interpolate(shift: float=0.0):
    """Interpolate grease pencil strokes between frames

    :param shift: Shift, Bias factor for which frame has more influence on the interpolated strokes
    :type shift: float
    """
    pass


def clone_vm_spec(client_factory, location, power_on=False, snapshot=None,
    template=False, config=None):
    """Builds the VM clone spec."""
    clone_spec = client_factory.create('ns0:VirtualMachineCloneSpec')
    clone_spec.location = location
    clone_spec.powerOn = power_on
    if snapshot:
        clone_spec.snapshot = snapshot
    if config is not None:
        clone_spec.config = config
    clone_spec.template = template
    return clone_spec


def feature_stats(features, q=2.0):
    """ Compute quartiles, inter-quartile range and min/max acceptable values for every
    column in 'features' based on Tukey's rule for outliers.

    Parameters
    ----------
    features: pandas.DataFrame
        Output of the featurize() function.
    q: float, optional (default: 2.0)
        Parameter that controls the min and max values that define the 'inlier' or
        'normality' range. For every feature, the first and third quartiles (Q1 and Q3)
        are calculated, and R = Q3 - Q1 is the interquartile range. The min and max
        acceptable values are then defined as:

        vmin = Q1 - q x R
        vmax = Q3 + q x R

        The original recommendation of Tukey is q = 1.5.

    Returns
    -------
    stats: pandas.DataFrame
        DataFrame containing the results. Columns are individual features, and rows are
        individual statistics (quartiles, iqr, min and max values).

    Examples
    --------

    An example output would look like:

               std       ptp     lfamp
    q1    0.025949  0.130252  0.173604
    q3    0.028379  0.152941  0.387956
    iqr   0.002430  0.022689  0.214352
    vmin  0.021090  0.084874 -0.255099
    vmax  0.033238  0.198319  0.816660
    """
    stats = features.quantile([0.25, 0.5, 0.75])
    stats = stats.rename({(0.25): 'q1', (0.5): 'med', (0.75): 'q3'})
    stats.loc['iqr'] = stats.loc['q3'] - stats.loc['q1']
    stats.loc['vmin'] = stats.loc['q1'] - q * stats.loc['iqr']
    stats.loc['vmax'] = stats.loc['q3'] + q * stats.loc['iqr']
    return stats


def categorical_excess_cardinality_flagger_and_reducer(df, useful_cols,
    cardinality_fraction_threshold=0.1,
    cardinality_max_categories_threshold=50, **kwargs):
    """
    Function inspects categorical features in the input dataframe where there is excess cardinality (too many unique     values), and returns a list of features which exceed these thresholds, as well as Series detailing the cardinality     (in absolute terms as well as as a fraction of the total number of samples).

    Parameters
    ----------
    df : pandas.DataFrame
        The input dataframe
    useful_cols : pandas.DataFrame
        Look-up dataframe, which contains information about the dtypes of desired features, and how to deal with
        missing values for each feature
    cardinality_fraction_threshold : int or None
        Cardinality fraction is the ratio of unique values for a given feature to the total number of samples in the dataset
        - If None, no threshold applied
        - If int, this is the threshold beyond which a feature is deemed to have excessive cardinality
    cardinality_max_categories_threshold : int or None
        Cardinality max categories is the absolute number of unique values for a given feature
        - If None, no threshold applied
        - If int, this is the threshold beyond which a feature is deemed to have excessive cardinality

    Returns
    -------
    df_cardinality : pandas.Series
        Cardinality (number of unique elements) of the categorical features in the input dataset
    df_cardinality_fraction : pandas.Series
        Cardinality fractions of the categorical features in the input dataset
    excess_cardinality : list
        List of features which exceed one or more of the thresholds

    """
    categorical_features = list(useful_cols.loc[useful_cols.dtype ==
        'nominal', 'feature'])
    categorical_data = df[categorical_features]
    m_samples = categorical_data.shape[0]
    df_cardinality = categorical_data.nunique()
    df_cardinality_fraction = df_cardinality / m_samples
    excess_cardinality_fraction = set(df_cardinality_fraction[
        df_cardinality_fraction > cardinality_fraction_threshold].index)
    print(
        f'Following features exceed cardiality fraction threshold of {cardinality_fraction_threshold}: {excess_cardinality_fraction}'
        )
    excess_cardinality_absolute = set(df_cardinality[df_cardinality >
        cardinality_max_categories_threshold].index)
    print(
        f'Following features exceed cardiality absolute number threshold of {cardinality_max_categories_threshold}: {excess_cardinality_absolute}'
        )
    excess_cardinality = list(set.union(excess_cardinality_fraction,
        excess_cardinality_absolute))
    if kwargs['reducer'] == True:
        n_max_categories = kwargs['reducer_max_categories']
        for feature in excess_cardinality:
            value_counts = df[feature].value_counts()
            small_categories = list(value_counts[n_max_categories:].index)
            df.loc[df[feature].isin(small_categories), feature
                ] = 'SMALL_CATEGORY'
        print(
            f'Features {excess_cardinality} exceeded thresholds and have each been reduced down to a maximum {n_max_categories} categories per feature'
            )
    return df_cardinality, df_cardinality_fraction, excess_cardinality


def valid_gameweek(gameweek):
    """Returns True if the gameweek is valid."""
    if not isinstance(gameweek, int) and (gameweek < 1 or gameweek > 38):
        raise 'Gameweek must be a number between 1 and 38.'
    return True


def winner(sprites, n):
    """Check if player n occupies 3 squares in a row"""
    for sq in [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5,
        8), (0, 4, 8), (2, 4, 6)]:
        if sum(1 for s in sq if sprites[s].costumeNumber == n) == 3:
            return True


def id_generator():
    """TODO: id_generator docstring."""
    index = 0
    while True:
        index += 1
        yield index


def get_parameter_default(parameter, ctx):
    """
    Get the value for a specific parameter from the computer_builder or the default value of that option

    :param parameter: parameter name
    :param ctx: click context of the command
    :return: parameter default value, or None
    """
    default = None
    for param in ctx.command.get_params(ctx):
        if param.name == parameter:
            default = param.default
    try:
        value = getattr(ctx.computer_builder, parameter)
        if value == '' or value is None:
            value = default
    except KeyError:
        value = default
    return value


def display_score(review):
    """
    This function is called when a score is displayed to the user - `review.display_score()`.
    Since `review.score` holds "data without context", points that will be displayed to the user are expected to be
    calculated from `review.score` e.g. score may be a percentual value for a specific type of submit and absolute
    value for other type ...
    """
    return str(review.score)


def _breadth_first_iter(loc):
    """
    Given a loctation node (from a zipper) walk it's children in breadth first
    order.

    >>> from .dependencies import targets

    >>> tree = _make_tree(targets)

    >>> result = [loc.node().name for loc in _breadth_first_iter(tree)]
    >>> result  # doctest: +NORMALIZE_WHITESPACE
    [None, 'shipwright_test/1', 'shipwright_test/independent',
    'shipwright_test/2', 'shipwright_test/3']

    """
    tocheck = [loc]
    while tocheck:
        l = tocheck.pop(0)
        yield l
        child = l.down()
        while child:
            tocheck.append(child)
            child = child.right()


def abort():
    """Abort the current transaction."""


@classmethod
def add_dimension(cls, columns, dimension, dim_pos, values, vdim):
    """
        Adding value dimensions not currently supported by iris interface.
        Adding key dimensions not possible on dense interfaces.
        """
    if not vdim:
        raise Exception('Cannot add key dimension to a dense representation.')
    raise NotImplementedError


def freestyle_module_add():
    """Add a style module into the list of modules

    """
    pass


def _stack_concatenated_datasets(concat_dataset):
    """Extract and stack indices of different data sets from `concat_dataset`.

    Each data set is represented by a complete range of indices
    starting from 0...len(data set) for the first data set.
    The ranges of the following data sets build on
    the range of the corresponding previous data set so that
    the indices of the lists are cumulative::

        datasets = [[0 ... len(data_1) - 1],
                    [len(data_1) ... len(data_1) - 1], ... ]

    Args:
        concat_dataset (ConcatDataset): data set to sample from

    Returns:
        list: list of lists of data set indices

    Example:
        >>> import torch
        >>> from torch.utils.data import (TensorDataset, ConcatDataset)
        >>> data_1 = TensorDataset(torch.Tensor([0, 1, 2, 3]))
        >>> data_2 = TensorDataset(torch.Tensor([0, 1, 2]))
        >>> concat_dataset = ConcatDataset((data_1, data_2))
        >>> concat_dataset.cumulative_sizes
        [4, 7]
        >>> _stack_concatenated_datasets(concat_dataset)
        [[0, 1, 2, 3], [4, 5, 6]]

    """
    datasets = []
    start_idx = 0
    for upper_edge in concat_dataset.cumulative_sizes:
        datasets += [list(range(start_idx, upper_edge))]
        start_idx = upper_edge
    return datasets


def initial(sys, T=None, X0=0.0, input=None, output=None, return_x=False):
    """
    Initial condition response of a linear system

    If the system has multiple outputs (?IMO), optionally, one output
    may be selected. If no selection is made for the output, all
    outputs are given.

    Parameters
    ----------
    sys: StateSpace, or TransferFunction
        LTI system to simulate

    T: array-like object, optional
        Time vector (argument is autocomputed if not given)

    X0: array-like object or number, optional
        Initial condition (default = 0)

        Numbers are converted to constant arrays with the correct shape.

    input: int
        This input is ignored, but present for compatibility with step
        and impulse.

    output: int
        If given, index of the output that is returned by this simulation.

    Returns
    -------
    yout: array
        Response of the system

    T: array
        Time values of the output

    xout: array (if selected)
        Individual response of each x variable

    See Also
    --------
    lsim, step, impulse

    Examples
    --------
    >>> yout, T = initial(sys, T, X0)

    """
    from ..timeresp import initial_response
    T, yout, xout = initial_response(sys, T, X0, output=output, transpose=
        True, return_x=True)
    if return_x:
        return yout, T, xout
    return yout, T


def threeindicesfamily(n):
    """
    #TODO to be OPTIMIZED
    remove harmonics
    """
    listhkl = []
    for hh in list(range(n + 1)):
        for kk in list(range(n + 1)):
            for ll in list(range(n + 1)):
                if hh >= kk and kk >= ll:
                    listhkl.append([hh, kk, ll])
    return listhkl[1:]


@classmethod
def args_from_string(cls, s):
    """Extract init-arguments from string representation of range."""
    pat = cls.range_pattern
    result = ()
    if pat.match(s):
        if bool(pat.LB) != bool(pat.UB):
            raise ValueError('Need both bounds or none')
        btype = pat.LB + pat.UB if pat.LB and pat.UB else None
        lower = cls.bound_from_string(pat.lower.strip())
        upper = cls.bound_from_string(pat.upper.strip())
        result = lower, upper, btype
    return result


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def planInvalidInMap(map, state):
    """
    Just checks to be sure the first two cells are occupiable.  In low
    noise conditions, it's good to check the whole plan, so failures
    are discovered earlier;  but in high noise, we often have to get
    close to a location before we decide that it is really not safe to
    traverse.
    """
    end = min(2, len(state))
    for s in state[:end]:
        if not map.robotCanOccupy(s):
            return True
    return False


@staticmethod
def _set_default_configuration_options(app):
    """Sets the default configuration options used by this extension."""
    app.config.setdefault('JWT_USE_COOKIE', False)
    app.config.setdefault('JWT_HEADER_NAME', 'Authorization')
    app.config.setdefault('JWT_HEADER_TYPE', 'Bearer')
    app.config.setdefault('JWT_ALGORITHM', 'RS256')
    app.config.setdefault('JWT_IDENTITY', None)
    app.config.setdefault('VERIFY_AUD', True)
    app.config.setdefault('JWT_AUTHORIZED_KEYS', None)


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


def build_entry(etype, entity, permissions=None, use_nfsv4_acls=False):
    """Builds and returns an entry string. Does not include the permissions bit if they are not provided."""
    if use_nfsv4_acls:
        return ':'.join([etype, entity, permissions, 'allow'])
    if permissions:
        return etype + ':' + entity + ':' + permissions
    return etype + ':' + entity


@staticmethod
def preprocess_sample(sample, api_schema):
    """Modify a sample to set default or missing fields.

        Args:
           sample (Any): A definition for a single sample generated from parsed yaml.
           api_schema (api.API): The schema that defines the API to which the sample belongs.
        """
    sample['package_name'] = api_schema.naming.warehouse_package_name
    sample.setdefault('response', [{'print': ['%s', '$resp']}])


def format_exception(etype, evalue, tb):
    """Format an exception."""
    import traceback
    s = ''.join(traceback.format_tb(tb))
    return '%s: %s\n%s' % (etype.__name__, evalue, s)


def select_stream_by_typed_index(ffprobe_streams, index, codec_type=None):
    """will return the mixed position of a stream by codec type"""
    assert codec_type in ('audio', 'video')
    current_type_index = -1
    for stream in ffprobe_streams:
        if stream['codec_type'] == codec_type:
            current_type_index += 1
        if current_type_index == index:
            return int(stream['index'])


def _hashable_bytes(data):
    """
    Coerce strings to hashable bytes.
    """
    if isinstance(data, bytes):
        return data
    elif isinstance(data, str):
        return data.encode('ascii')
    else:
        raise TypeError(data)


def is_int(str_val):
    """
    Check if str_val is int type
    :param str_val: str
    :return: bool
    """
    if str_val.startswith('-') and str_val[1:].isdigit():
        return True
    elif str_val.isdigit():
        return True
    else:
        return False


def find_indels(ref_aln, qry_aln):
    """
    Identify the positions of indels in the alignment of 2 sequences

    :param ref_aln: An aligned sequence representing the reference
    :param qry_aln: An aligned sequence representing the query
    :yields:        The position of each gap character in the alignment
    """
    assert len(ref_aln) == len(qry_aln
        ), 'Error - Aligned sequence lengths do not match'
    for pos, pair in enumerate(zip(ref_aln, qry_aln)):
        if '-' in pair:
            yield pos


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


def _normalized_indent(text):
    """Returns `text` with normalized indentation."""
    lines = text.strip().split('\n')
    head = lines[0]
    rest = lines[1:]
    if rest:
        indent = 0
        for line in rest:
            contents = line.lstrip()
            if contents:
                indent = len(line) - len(contents)
                break
        if indent:
            lines = [head] + [line[indent:] for line in rest]
    return '\n'.join(lines)


def _check_flag(elems, value):
    """
    Checks that a value is a member of a set of flags.

    Note that we use a top-level function and `partial`. The trouble with lambdas or local
    defs is that they can't be pickled because they're inaccessible to the unpickler.

    If you don't intend to pickle your encoders, though, they're completely fine to use in
    rules.
    """
    return isinstance(value, str) and value in elems


def transform(gr, transform, vertex_or_edge='vertex'):
    """transformes values and creates new for a graph

    :param transform: iterable of dict. Each tripel contains "name" name of vertex attribute to be transformed,
    "func" a callable which can be called with the values of "name". "default" a value which should be used if the
    function call doesn't work. (e.g. {"name" : year, "func" : int, "default": 0})
    """
    assert vertex_or_edge in ['vertex', 'edge'
        ], "vertex_or_edge has to be either 'vertex' or 'edge'"
    for t in transform:
        new_val = []
        if vertex_or_edge == 'vertex':
            iterate = gr.vs[t['name']]
        else:
            iterate = gr.es[t['name']]
        for val in gr.vs[t['name']]:
            try:
                new_val.append(t['func'](val))
            except TypeError:
                new_val.append(t['default'])
            except ValueError:
                new_val.append(t['default'])
        gr.vs[t['name']] = new_val


def listSortFields():
    """Return a list of available fields for sorting."""


@classmethod
def josephus(cls, m, n, s=1):
    """Return as a permutation the shuffling of range(n) using the Josephus
        scheme in which every m-th item is selected until all have been chosen.
        The returned permutation has elements listed by the order in which they
        were selected.

        The parameter ``s`` stops the selection process when there are ``s``
        items remaining and these are selected by continuing the selection,
        counting by 1 rather than by ``m``.

        Consider selecting every 3rd item from 6 until only 2 remain::

            choices    chosen
            ========   ======
              012345
              01 345   2
              01 34    25
              01  4    253
              0   4    2531
              0        25314
                       253140

        Examples
        ========

        >>> from sympy.combinatorics import Permutation
        >>> Permutation.josephus(3, 6, 2).array_form
        [2, 5, 3, 1, 4, 0]

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Flavius_Josephus
        .. [2] https://en.wikipedia.org/wiki/Josephus_problem
        .. [3] http://www.wou.edu/~burtonl/josephus.html

        """
    from collections import deque
    m -= 1
    Q = deque(list(range(n)))
    perm = []
    while len(Q) > max(s, 1):
        for dp in range(m):
            Q.append(Q.popleft())
        perm.append(Q.popleft())
    perm.extend(list(Q))
    return cls(perm)


@classmethod
def _postprocess_root(cls, root, radicals):
    """Return the root if it is trivial or a ``RootOf`` object."""
    poly, index = root
    roots = cls._roots_trivial(poly, radicals)
    if roots is not None:
        return roots[index]
    else:
        return cls._new(poly, index)


@staticmethod
def _filter_categories(d, filters_to_keep, filters_to_remove):
    """
        Filters a dictionary based on certain keywords.
        :param d: dictionary
        :param filters_to_keep: list or string
        :param filters_to_remove: list or string
        :return: filtered dictionary
        """
    filtered_dict = dict(d)
    if filters_to_keep is not None:
        if isinstance(filters_to_keep, str):
            filters_to_keep = filters_to_keep.split()
        for word in filters_to_keep:
            for key, values in d.items():
                if str(key).lower().find(word.lower()) == -1 and str(values
                    ).lower().find(word.lower()) == -1:
                    try:
                        del filtered_dict[key]
                    except KeyError:
                        continue
                else:
                    continue
    if filters_to_remove is not None:
        if isinstance(filters_to_remove, str):
            filters_to_remove = filters_to_remove.split()
        for word in filters_to_remove:
            for key, values in d.items():
                if str(key).lower().find(word.lower()) != -1 or str(values
                    ).lower().find(word.lower()) != -1:
                    try:
                        del filtered_dict[key]
                    except KeyError:
                        continue
                else:
                    continue
    return filtered_dict


def count(log):
    """''Count the number of the same record
      Return a list like [['4.3', 'Iris-setosa', 1], ['4.4', 'Iris-setosa', 3],...]"""
    log_cnt = []
    log.sort(key=lambda log: log[0])
    i = 0
    while i < len(log):
        cnt = log.count(log[i])
        record = log[i][:]
        record.append(cnt)
        log_cnt.append(record)
        i += cnt
    return log_cnt


def _compile_jq(jq_expr):
    """Compile JQ expression, returning a JQ program object
    See: https://pypi.python.org/pypi/jq
    """
    import jq
    return jq.jq(jq_expr)


def profile(code):
    """
        dummy = profile('print("sss")')
    """
    import cProfile
    import pstats
    from io import StringIO
    cProfile.run(code, 'info')
    s = StringIO()
    sortby = 'cumulative'
    ps = pstats.Stats('info', stream=s).sort_stats(sortby)
    ps.print_stats()
    info = s.getvalue()
    print(info)
    return info


def getUsers():
    """ Return all user objects. Since the number of user records in
        an LDAP database is potentially very large this method will
        only return those user objects that are in the internal cache
        of the LDAPUserFolder and not expired.

        Permission - *Manage users*
        """


def star_auth(cluster, logdir, cmd, *args):
    """Attempt another auth to any unauthenticated nodes"""
    if len(args) == 0:
        user = None
    else:
        user = args[0]
    cluster.reauth(user)


def _func_star(args):
    """
    A function and argument expanding helper function.

    The first item in args is callable, and the remainder of the items are
    used as expanded arguments. This is to make the function header for reduce
    the same for the normal and parallel versions. Otherwise, the functions
    would have to do their own unpacking of arguments.
    """
    f = args[0]
    args = args[1:]
    return f(*args)


def uvs_reverse():
    """Flip direction of UV coordinates inside faces

    """
    pass


def print_order_monitor(monitor):
    """
    This is just print test, but its likely to be a Queue of some sort.
    """
    trade_id = monitor._order.getTradeID()
    print('TradeID {}'.format(trade_id))


def uptime(start_time):
    """Calculate the difference between now() and the given create_time.

    @param start_time: milliseconds passed since 'event' (not since epoc)
    @type float
    """
    from datetime import datetime
    return datetime.now() - datetime.fromtimestamp(start_time)


def update_scaling_parameters(DomainName=None, ScalingParameters=None):
    """
    Configures scaling parameters for a domain. A domain's scaling parameters specify the desired search instance type and replication count. Amazon CloudSearch will still automatically scale your domain based on the volume of data and traffic, but not below the desired instance type and replication count. If the Multi-AZ option is enabled, these values control the resources used per Availability Zone. For more information, see Configuring Scaling Options in the Amazon CloudSearch Developer Guide .
    See also: AWS API Documentation

    :example: response = client.update_scaling_parameters(
        DomainName='string',
        ScalingParameters={
            'DesiredInstanceType': 'search.m1.small'|'search.m1.large'|'search.m2.xlarge'|'search.m2.2xlarge'|'search.m3.medium'|'search.m3.large'|'search.m3.xlarge'|'search.m3.2xlarge',
            'DesiredReplicationCount': 123,
            'DesiredPartitionCount': 123
        }
    )

    :type DomainName: string
    :param DomainName: [REQUIRED]
            A string that represents the name of a domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen).

    :type ScalingParameters: dict
    :param ScalingParameters: [REQUIRED]
            The desired instance type and desired number of replicas of each index partition.
            DesiredInstanceType (string) --The instance type that you want to preconfigure for your domain. For example, search.m1.small .
            DesiredReplicationCount (integer) --The number of replicas you want to preconfigure for each index partition.
            DesiredPartitionCount (integer) --The number of partitions you want to preconfigure for your domain. Only valid when you select m2.2xlarge as the desired instance type.

    :rtype: dict
    :return: {
        'ScalingParameters': {
            'Options': {
                'DesiredInstanceType': 'search.m1.small'|'search.m1.large'|'search.m2.xlarge'|'search.m2.2xlarge'|'search.m3.medium'|'search.m3.large'|'search.m3.xlarge'|'search.m3.2xlarge',
                'DesiredReplicationCount': 123,
                'DesiredPartitionCount': 123
            },
            'Status': {
                'CreationDate': datetime(2015, 1, 1),
                'UpdateDate': datetime(2015, 1, 1),
                'UpdateVersion': 123,
                'State': 'RequiresIndexDocuments'|'Processing'|'Active'|'FailedToValidate',
                'PendingDeletion': True|False
            }
        }
    }

    :returns:
    RequiresIndexDocuments : the option's latest value will not be deployed until  IndexDocuments has been called and indexing is complete.
    Processing : the option's latest value is in the process of being activated.
    Active : the option's latest value is completely deployed.
    FailedToValidate : the option value is not compatible with the domain's data and cannot be used to index the data. You must either modify the option value or update or remove the incompatible documents.

    """
    pass


@classmethod
def with_params(cls, xid, zxid, error, data, offset, client, server):
    """Build a ServerMessage (a reply or event) with the given params, possibly parsing some more.

    This must be overridden by ServerMessage subclasses to offer extra parsing of
    parameters specific to the ServerMessage subclass.

    :param xid: the transaction id associated with this ServerMessage
    :param zxid: the ZooKeeper txn id associated with this ServerMessage
    :param error: if the response has an error
    :param data: the remaining data of the associated data packet
    :param offset: the offset from which the data should be read
    :param client: the ip:port to which this ServerMessage is directed to

    :returns: Returns an instance of the specific ServerMessage subclass.
    :raises DeserializationError: if parsing the ServerMessage fails.
    """
    return cls(xid, zxid, error, '', client, server)


def calculate_iou(confusion_matrix):
    """
    https://github.com/ternaus/robot-surgery-segmentation/blob/master/validation.py
    """
    confusion_matrix = confusion_matrix.astype(float)
    ious = []
    for index in range(confusion_matrix.shape[0]):
        true_positives = confusion_matrix[index, index]
        false_positives = confusion_matrix[:, (index)].sum() - true_positives
        false_negatives = confusion_matrix[(index), :].sum() - true_positives
        denom = true_positives + false_positives + false_negatives
        if denom == 0:
            iou = 0
        else:
            iou = float(true_positives) / denom
        ious.append(iou)
    return ious


@classmethod
def export_entry(cls, entry):
    """Returns a string representation of a single entry."""
    return str(entry)


def get_nodes_from(component_set):
    """
    Get the list of nodes specified in the given component set
    """
    index = component_set.find('#')
    if index == -1:
        return component_set
    return component_set[0:index]


def _get_surfaces(idf):
    """Get the surfaces from the IDF.
    """
    surfaces = idf.getsurfaces() + idf.getshadingsurfaces(
        ) + idf.getsubsurfaces()
    return surfaces


def unpack_arg(v):
    """Use for local methods."""
    if isinstance(v, tuple):
        return v[0], v[1]
    else:
        return v, {}


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

        :param str val:
        :rtype: FileErrorResult
        """
    return cls('invalid_file_action_error', val)


def scientificNotation(num, pr=True):
    """Abbreviation: scin"""
    result = '%e' % num
    if pr:
        print(result)
    else:
        return result


def path_open(filepath: str=''):
    """Open a path in a file browser

    :param filepath: filepath
    :type filepath: str
    """
    pass


@classmethod
def for_new_file(cls, path, disk_format, **kwargs):
    """Create a new disk file and return a DiskRepresentation.

        Args:
          path (str): Path to create file at.
          disk_format (str): Disk format to create, such as 'iso' or 'vmdk'.
          **kwargs: Arguments to pass through to appropriate DiskRepresentation
            subclass for this format.

        Returns:
          DiskRepresentation: representation of the created file.

        Raises:
          NotImplementedError: if ``disk_format`` is not supported.
        """
    if cls.disk_format != disk_format:
        cls = cls.class_for_format(disk_format)
        if cls is None:
            raise NotImplementedError("No support for files of type '{0}'".
                format(disk_format))
    cls.create_file(path, **kwargs)
    return cls(path)


@classmethod
def coerce(cls, val):
    """
        Return the desired enum object or throw an error, the enum object will
        be searched based on its name or value.

        :param val: the value or name of the desired enum
        :return: the enum object
        """
    try:
        return cls[val]
    except KeyError:
        try:
            return cls(val)
        except ValueError:
            msg = (
                '"{0}" not a valid enum value or name of {1}, possible names are {2} and possible values are {3}.'
                )
            raise ValueError(msg.format(val, cls.__name__, ','.join(cls.
                get_names()), str(cls.get_values())))


def p_lexical_vars(p):
    """lexical_vars : USE LPAREN lexical_var_list RPAREN
                    | empty"""
    if len(p) == 5:
        p[0] = p[3]
    else:
        p[0] = []


def get_hash160_from_outscript_p2sh(outscript):
    """ Extract the hash160 data from a P2SH raw outscript. """
    outscript = outscript[1:]
    n = outscript[0]
    return outscript[1:n + 1]


def requestedFormat(request, acceptedFormat):
    """Return the response format requested by client

        Client could specify requested format using:
        (options are processed in this order)
            - `format` field in http request
            - `Accept` header in http request
        Example:
            chooseFormat(request, ['text/html','application/json'])
        Args:
            acceptedFormat: list containing all the accepted format
        Returns:
            string: the user requested mime-type (if supported)
        Raises:
            ValueError: if user request a mime-type not supported
        """
    if 'format' in request.args:
        fieldFormat = request.args.get('format')
        if fieldFormat not in acceptedFormat:
            raise ValueError('requested format not supported: ' + fieldFormat)
        return fieldFormat
    else:
        return request.accept_mimetypes.best_match(acceptedFormat)


def _chunk_write(chunk, local_file, progress):
    """Write a chunk to file and update the progress bar."""
    local_file.write(chunk)
    progress.update_with_increment_value(len(chunk))


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


def lineStartingWith(string, lines):
    """ Searches through the specified list of strings and returns the
    first line starting with the specified search string, or None if not found
    """
    for line in lines:
        if line.startswith(string):
            return line
    else:
        return None


def decode_cipher(cipher_spec, key_size):
    """Decode a dm-crypt style cipher specification string

       The assumed format being cipher[:keycount]-chainmode-ivmode[:ivopts] as
       documented under linux/Documentation/device-mapper/dm-crypt.txt in the
       kernel source tree.
    """
    cipher_alg, cipher_mode, ivgen_alg = cipher_spec.split('-')
    cipher_alg = cipher_alg + '-' + str(key_size)
    return {'cipher_alg': cipher_alg, 'cipher_mode': cipher_mode,
        'ivgen_alg': ivgen_alg}


def retrieve_permission(pid: str, **filters):
    """

    DynamoDB Integration:
    ---

    if not all(required_fields):
        raise KeyError("NAMESPACE & ACTION fields are required")

    try:
        if pid == '__all__':

            return permission_table.query(
                    Key=Key('namespace').between('A', 'Z')
                    ProjectionExpression="namespace, action"
                )
            .

        return permission_table.get_item(Key={"pid": {"S": pid}})

    except Exception as e:
        print(e)

        return []
    """
    if pid == '__all__':
        pid = 'some-pid'
    return [{'pid': pid, 'namespace': 'test_namespace', 'action':
        'test_action', 'permission': 'test_namespace:test_action'}]


def get_subset(values, lower=None, upper=None):
    """Returns subset of values greater or equal `lower` and smaller `upper`.

    Args:
        values (iterable): Iterable of numeric values.
        lower (number, default None): Lower bound (including) to filter values.
        upper (number, default None): Upper bound (excluding) to filter values.
    """
    if lower is None and upper is not None:
        subset = filter(lambda v: v < upper, values)
    elif lower is not None and upper is None:
        subset = filter(lambda v: v >= lower, values)
    elif lower is not None and upper is not None:
        subset = filter(lambda v: v >= lower and v < upper, values)
    else:
        subset = values
    return list(subset)


@staticmethod
def _get_name(line, dictionary, proper_name):
    """Default function for finding object name.

        Splits the line by ':' and checks if it exists in the object's
        dictionary (heropediadata).

        Note
        ----
        ``Illusions attack damage reduced against buildings`` returns ``None``

        Parameters
        ----------
        line : str
            The phrase to be checked

        dictionary : dict
            Object's main dictionary (heropediadata)

        proper_name : dict
            Object's secondary dictionary

        Returns
        -------
        name : str or None
            Proper object name
        """
    name = line.split(':')[0]
    name = name.lower().replace(' ', '_')
    found = dictionary.get(name, None)
    if not found:
        name = proper_name.get(name, None)
    return name


def GetInterface(setting):
    """Get the class, subclass, and protocol for the given USB setting."""
    return setting.getClass(), setting.getSubClass(), setting.getProtocol()


def remove_version_from_guid(guid):
    """
    Removes version from toolshed-derived tool_id(=guid).
    """
    if '/' not in guid:
        return None
    last_slash = guid.rfind('/')
    return guid[:last_slash]


@classmethod
def make_request(cls, memory_location, dfi=None):
    """
        Generates a request for RequestDownload

        :param memory_location: The address and the size of the memory block to be written.
        :type memory_location: :ref:`MemoryLocation <MemoryLocation>`

        :param dfi: Optional :ref:`DataFormatIdentifier <DataFormatIdentifier>` defining the compression and encryption scheme of the data.
                If not specified, the default value of 00 will be used, specifying no encryption and no compression
        :type dfi: :ref:`DataFormatIdentifier <DataFormatIdentifier>`

        :raises ValueError: If parameters are out of range, missing or wrong type
        """
    from udsoncan import Request, MemoryLocation
    dfi = cls.normalize_data_format_identifier(dfi)
    if not isinstance(memory_location, MemoryLocation):
        raise ValueError(
            'memory_location must be an instance of MemoryLocation')
    request = Request(service=cls)
    request.data = b''
    request.data += dfi.get_byte()
    request.data += memory_location.alfid.get_byte()
    request.data += memory_location.get_address_bytes()
    request.data += memory_location.get_memorysize_bytes()
    return request


def get_tz_suffix(tz_input):
    """Return the suffix to be added for time zone information."""
    if tz_input == '':
        return ''
    elif tz_input == '+0000':
        return 'Z'
    return '{}:{}'.format(tz_input[:3], tz_input[3:])


def _clean_onerror(func, path, excinfo):
    """
    Error handler for cleaner
    """
    print('%s encountered error when processing %s: %s' % (func, path, excinfo)
        )