def get_user_input(message):
    """
    A method to ask question. The answer needs to be yes or no.

    Parameters
    ----------
    :param message  string, the question

    Returns
    -------

    Return a boolean: True for Yes, False for No
    """
    while True:
        answer = input(message)
        if answer in ('y', 'Y', 'yes', 'YES'):
            return True
        elif answer in ('n', 'N', 'no', 'No'):
            return False
        else:
            print('Unkown command. Please state yes or no')


def get_Union_params(un):
    """Python version independent function to obtain the parameters
    of a typing.Union object.
    Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
    """
    try:
        return un.__union_params__
    except AttributeError:
        return un.__args__


def IntbitsetCmp(x, y):
    """Compare two intbitsets."""
    if x is None or y is None:
        return False
    else:
        return x == y


def workcost():
    """ The estimated work cost
        """


@staticmethod
def _variable_attributes(varname):
    """Get dict of netCDF4 variable attributes for a given NcdcRecord Data column name"""
    proxy_map = {'d13c': ('d13C', 'per mil'), 'd18o': ('d18O', 'per mil'),
        'mgca': ('Mg/Ca', 'per mil'), 'percent': ('Percent foraminifera',
        '%'), 'tex86': ('TEX86', 'index'), 'uk37': ("UK'37", 'index')}
    foraminifera_map = {'bulloides': 'Globigerina bulloides',
        'crassaformis': 'Globorotalia crassaformis', 'dutertrei':
        'Neogloboquadrina dutertrei', 'inflata': 'Globoconella inflata',
        'mabahethi': 'Cibicides mabahethi', 'marginata':
        'Bulimina marginata', 'menardii': 'Globorotalia menardii',
        'obliquiloculata': 'Pulleniatina obliquiloculata', 'pachyderma':
        'Neogloboquadrina pachyderma sinistral', 'pachysin':
        'Neogloboquadrina pachyderma sinistral', 'pachyderma_d':
        'Neogloboquadrina incompta', 'peregrina': 'Uvigerina peregrina',
        'quinqueloba': 'Turborotalita quinqueloba', 'ruber':
        'Globigerinoides ruber white', 'ruber_lato':
        'Globigerinoides ruber white', 'ruber_pink':
        'Globigerinoides ruber pink', 'ruber_stricto':
        'Globigerinoides ruber white', 'sacculifer':
        'Trilobatus sacculifer', 'truncatulinoides':
        'Globorotalia pachytheca', 'tumida': 'Globorotalia tumida',
        'acicula': 'Creseis acicula'}
    varname = varname.lower()
    try:
        if '_' not in varname:
            out = {'long_name': proxy_map[varname][0], 'units': proxy_map[
                varname][1]}
        else:
            proxy, foram = varname.split('_', 1)
            out = {'long_name': proxy_map[proxy][0], 'units': proxy_map[
                proxy][1], 'foraminifera_type': foraminifera_map[foram]}
    except KeyError:
        out = {}
    return out


def _reencrypt_key(path, gpg, gpg_recipients):
    """Reencrypt a single key.

    Gets called from :func:`passpy.gpg._reencrypt_path`.

    :param str path: The path to a gpg encrypted file.

    :param gpg: The gpg object.
    :type gpg: :class:`gnupg.GPG`

    :param list gpg_recipients: The list of GPG Ids to encrypt the key
        with.

    """
    with open(path, 'rb') as key_file:
        key_data = gpg.decrypt_file(key_file).data
    key_data_enc = gpg.encrypt(key_data, gpg_recipients).data
    with open(path, 'wb') as key_file:
        key_file.write(key_data_enc)


@staticmethod
def metadata_id(item):
    """Extracts the identifier from an entry item."""
    return str(item['link'])


def stop():
    """
        Stops the process.

        Stopping the process will end product execution.
        """


def get_queue_url(QueueName=None, QueueOwnerAWSAccountId=None):
    """
    Returns the URL of an existing queue. This action provides a simple way to retrieve the URL of an Amazon SQS queue.
    To access a queue that belongs to another AWS account, use the QueueOwnerAWSAccountId parameter to specify the account ID of the queue's owner. The queue's owner must grant you permission to access the queue. For more information about shared queue access, see ``  AddPermission `` or see Shared Queues in the Amazon SQS Developer Guide .
    See also: AWS API Documentation

    Examples
    The following example retrieves the queue ARN.
    Expected Output:

    :example: response = client.get_queue_url(
        QueueName='string',
        QueueOwnerAWSAccountId='string'
    )

    :type QueueName: string
    :param QueueName: [REQUIRED]
            The name of the queue whose URL must be fetched. Maximum 80 characters. Valid values: alphanumeric characters, hyphens (- ), and underscores (_ ).
            Queue names are case-sensitive.

    :type QueueOwnerAWSAccountId: string
    :param QueueOwnerAWSAccountId: The AWS account ID of the account that created the queue.

    :rtype: dict
    :return: {
        'QueueUrl': 'string'
    }

    """
    pass


@classmethod
def get_percent_required_fields(cls):
    """
        get ``set`` of ``required fields`` for ``Percent`` ``type``.

        Returns:
            ``set`` of fields
        """
    fields = cls.get_required_fields()
    return fields.union({'percentage'})


def fact(x):
    """ fact(x)    factorial    {x} int x > 0

            (x can be int)
    """
    for n in range(1, x, 1):
        x *= n
    return x


def handle_record_not_found(error):
    """Response to when the view was not found."""
    return "Record for key '%s' and stage '%s' not found" % (error.key,
        error.stage), 400


def reduceWith(reducer, seed, iterable):
    """
    reduceWith takes reducer as first argument, computes a reduction over iterable.
    Think foldl from Haskell.
    reducer is (b -> a -> b)
    Seed is b
    iterable is [a]
    reduceWith is (b -> a -> b) -> b -> [a] -> b
    """
    accumulation = seed
    for value in iterable:
        accumulation = reducer(accumulation, value)
    return accumulation


def set_user_harakiri(timeout=0):
    """Sets user level harakiri.

    :param int timeout: Seconds. ``0`` disable timer.

    :rtype: None
    """


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

        :param FileDeleteCommentDetails val:
        :rtype: EventDetails
        """
    return cls('file_delete_comment_details', val)


def get_permitted_algorithm_names():
    """ returns permitted algorithm names. """
    return ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'PS256',
        'PS384', 'PS512']


@staticmethod
def make_key(observer):
    """Construct a unique, hashable, immutable key for an observer."""
    if hasattr(observer, '__self__'):
        inst = observer.__self__
        method_name = observer.__name__
        key = id(inst), method_name
    else:
        key = id(observer)
    return key


def _yield_overlaps(x1, x2):
    """yield common hash values while iterating over two sorted lists of hashes
    To properly compute the estimate, I need this to only process min(len(x1), len(x2)) elements
    Returns an iterable object
    """
    i = 0
    j = 0
    processed = 0
    try:
        while processed <= min(len(x1), len(x2)):
            while x1[i] < x2[j]:
                i += 1
                processed += 1
            while x1[i] > x2[j]:
                j += 1
                processed += 1
            if x1[i] == x2[j]:
                yield x1[i]
                i += 1
                j += 1
                processed += 1
    except IndexError:
        return


@classmethod
def _value_to_status_less(cls, value, check_config, modifier=None):
    """Return an error when the value should be less than threshold."""
    critical, warning = cls.get_thresholds(check_config, modifier)
    if value >= critical:
        return cls.STATUS_CRIT
    elif value >= warning:
        return cls.STATUS_WARN
    else:
        return cls.STATUS_OK


@classmethod
def generate_custom_ridge(cls, r_args):
    """Generates a custom Ridge wrapper.
        :param r_args: parameters to pass into the Ridge regression
        :type r_args: dict
        :rtype: cls
        """
    return type('Custom' + cls.__name__, (cls,), dict(r_args=r_args))


def get_messages(request):
    """
    Return the message storage on the request if it exists, otherwise return
    an empty list.
    """
    return getattr(request, '_messages', [])


def record_param_count(parent=None, new_value=None, **kwargs):
    """Size getter/setter for the record parameters array element count."""
    if parent is None:
        raise KeyError('Cannot get/set the size of record parameter ' +
            'array without a supplied parent.')
    if new_value is None:
        return (parent.size - 3) * 2
    assert not new_value % 2, 'record byte sizes must be a multiple of 2.'
    parent.size = 3 + new_value // 2


def material_slot_copy():
    """Copies materials to other selected objects

    """
    pass


def user_deactivation_handler(sender, **kwargs):
    """Ensures that an administratively deactivated user does not have any
    lingering unverified email addresses."""
    created = kwargs['created']
    user = kwargs['instance']
    if not created and not user.is_active:
        for email in user.emailaddress_set.all():
            if not email.is_verified():
                email.delete()


def delimitProtobuf(src):
    """Python protobuf bindings are missing writeDelimited, this is a workaround to add a delimiter"""
    from google.protobuf.internal import encoder
    serializedMessage = src.SerializeToString()
    delimiter = encoder._VarintBytes(len(serializedMessage))
    return delimiter + serializedMessage


def _escape_ffarg(arg):
    """
    Escape FFmpeg filter argument. See ffmpeg-filters(1), "Notes on
    filtergraph escaping".
    """
    arg = arg.replace('\\', '\\\\')
    arg = arg.replace("'", "'\\\\\\''")
    arg = arg.replace(':', '\\:')
    return "'{}'".format(arg)


def multi_char_literal(chars):
    """Emulates character integer literals in C. Given a string "abc",
    returns the value of the C single-quoted literal 'abc'.
    """
    num = 0
    for index, char in enumerate(chars):
        shift = (len(chars) - index - 1) * 8
        num |= ord(char) << shift
    return num


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

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Alignak users groups'
    return 'usergroup'


def getitem_via_sibseqs(ol, *sibseqs):
    """
        from elist.elist import *
        y = ['a',['b',["bb"]],'c']
        y[1][1]
        getitem_via_sibseqs(y,1,1)
    """
    pathlist = list(sibseqs)
    this = ol
    for i in range(0, pathlist.__len__()):
        key = pathlist[i]
        this = this.__getitem__(key)
    return this


def releases_key(release, countries, original_year):
    """Used as a key to sort releases by date then preferred country
    """
    date = release.get('date')
    if date and original_year:
        year = date.get('year', 9999)
        month = date.get('month', 99)
        day = date.get('day', 99)
    else:
        year = 9999
        month = 99
        day = 99
    country_key = 99
    if release.get('country'):
        for i, country in enumerate(countries):
            if country.match(release['country']):
                country_key = i
                break
    return year, month, day, country_key


@staticmethod
def dumpMemory(MEMORY):
    """ Returns a sequence of Quads
        """
    for x in MEMORY:
        yield str(x)


def get_network_boundaries(network):
    """
    Determines the first and last IPs given an ipaddress network object
    Returns: First IP, Last IP
    https://stackoverflow.com/a/9717242
    https://stackoverflow.com/a/1942848
    """
    count = 0
    for ip in network:
        count += 1
    return network[0], network[count - 1]


@staticmethod
def supportedViews():
    """Return the views that this control supports.

        This method may be overridden by sub-classes to return a list of
        the view types that are supported by this control. For example, the
        :class:`.OrthoToolBar` control is intended to be used solely with the
        :class:`.OrthoPanel` view.

        The default implementation returns ``None``, which is interpreted
        as being compatible with all views.
        """
    return None


@classmethod
def read_csv_with_errors(cls, url, delimiter=',', header=True, comment_char
    ='', escape_char='\\', double_quote=True, quote_char='"',
    skip_initial_space=True, column_type_hints=None, na_values=['NA'],
    line_terminator='\n', usecols=[], nrows=None, skiprows=0, verbose=True,
    nrows_to_infer=100, **kwargs):
    """
        Constructs an SFrame from a CSV file or a path to multiple CSVs, and
        returns a pair containing the SFrame and a dict of filenames to SArrays
        indicating for each file, what are the incorrectly parsed lines
        encountered.

        Parameters
        ----------
        url : string
            Location of the CSV file or directory to load. If URL is a directory
            or a "glob" pattern, all matching files will be loaded.

        delimiter : string, optional
            This describes the delimiter used for parsing csv files.

        header : bool, optional
            If true, uses the first row as the column names. Otherwise use the
            default column names: 'X1, X2, ...'.

        comment_char : string, optional
            The character which denotes that the
            remainder of the line is a comment.

        escape_char : string, optional
            Character which begins a C escape sequence

        double_quote : bool, optional
            If True, two consecutive quotes in a string are parsed to a single
            quote.

        quote_char : string, optional
            Character sequence that indicates a quote.

        skip_initial_space : bool, optional
            Ignore extra spaces at the start of a field

        column_type_hints : None, type, list[type], dict[string, type], optional
            This provides type hints for each column. By default, this method
            attempts to detect the type of each column automatically.

            Supported types are int, float, str, list, dict, and array.array.

            * If a single type is provided, the type will be
              applied to all columns. For instance, column_type_hints=float
              will force all columns to be parsed as float.
            * If a list of types is provided, the types applies
              to each column in order, e.g.[int, float, str]
              will parse the first column as int, second as float and third as
              string.
            * If a dictionary of column name to type is provided,
              each type value in the dictionary is applied to the key it
              belongs to.
              For instance {'user':int} will hint that the column called "user"
              should be parsed as an integer, and the rest will be type inferred.

        na_values : str | list of str, optional
            A string or list of strings to be interpreted as missing values.

        line_terminator : str, optional
            A string to be interpreted as the line terminator. Defaults to "\\n"
            which will also correctly match Mac, Linux and Windows line endings
            ("\\r", "\\n" and "\\r\\n" respectively)

        usecols : list of str, optional
            A subset of column names to output. If unspecified (default),
            all columns will be read. This can provide performance gains if the
            number of columns are large. If the input file has no headers,
            usecols=['X1','X3'] will read columns 1 and 3.

        nrows : int, optional
            If set, only this many rows will be read from the file.

        skiprows : int, optional
            If set, this number of rows at the start of the file are skipped.

        verbose : bool, optional
            If True, print the progress.

        Returns
        -------
        out : tuple
            The first element is the SFrame with good data. The second element
            is a dictionary of filenames to SArrays indicating for each file,
            what are the incorrectly parsed lines encountered.

        See Also
        --------
        read_csv, SFrame

        Examples
        --------
        >>> bad_url = 'https://static.turi.com/datasets/bad_csv_example.csv'
        >>> (sf, bad_lines) = graphlab.SFrame.read_csv_with_errors(bad_url)
        >>> sf
        +---------+----------+--------+
        | user_id | movie_id | rating |
        +---------+----------+--------+
        |  25904  |   1663   |   3    |
        |  25907  |   1663   |   3    |
        |  25923  |   1663   |   3    |
        |  25924  |   1663   |   3    |
        |  25928  |   1663   |   2    |
        |   ...   |   ...    |  ...   |
        +---------+----------+--------+
        [98 rows x 3 columns]

        >>> bad_lines
        {'https://static.turi.com/datasets/bad_csv_example.csv': dtype: str
         Rows: 1
         ['x,y,z,a,b,c']}
       """
    return cls._read_csv_impl(url, delimiter=delimiter, header=header,
        error_bad_lines=False, comment_char=comment_char, escape_char=
        escape_char, double_quote=double_quote, quote_char=quote_char,
        skip_initial_space=skip_initial_space, column_type_hints=
        column_type_hints, na_values=na_values, line_terminator=
        line_terminator, usecols=usecols, nrows=nrows, verbose=verbose,
        skiprows=skiprows, store_errors=True, nrows_to_infer=nrows_to_infer,
        **kwargs)


def Ht_est(Ht_p_est, Hs_est, harm_mean, n):
    """Basic Equation: Ht+Hs_est/(2*N_harmonic*n)"""
    n = float(n)
    Ht = Ht_p_est
    Ht_est = Ht + Hs_est / (2.0 * harm_mean * n)
    return Ht_est


@classmethod
def process(cls, *, context=None, parameter=None):
    """ Evaluate the DISCARD command. """
    context.stack.pop()


def dbamp(db):
    """Convert db to amplitude"""
    return 10 ** (db / 20.0)


@classmethod
def new(cls, message, content, grouping_value=None, error_message=None):
    """
        Creates a new message, based on an existing message. This has the consequence that it will be tracked together
            and the tap will not be notified until every message in the chain is properly ack'ed.

        :param message: Message instance, as received by the intersection
        :param content: Any value that can be serialized into json
        :param grouping_value: String that can be used for routing messages consistently to the same receiver
        """
    return cls(ramp_unique_id=message.ramp_unique_id, content=content,
        grouping_value=grouping_value, error_message=error_message,
        producer_uuid=message.producer_uuid)


def writeArray(fp, a, delim=' ', nl=1):
    """
    Writes a sequence a of floats to file pointed to by file pointer.
    """
    for i in a:
        fp.write('%f%s' % (i, delim))
    if nl:
        fp.write('\n')


def read_table(data, coerce_type, transpose=False):
    """
    Reads in data from a simple table and forces it to be a particular type

    This is a helper function that allows data to be easily constained in a
    simple script
    ::return: a dictionary of with the keys being a tuple of the strings
       in the first row and colum of the table
    ::param data: the multiline string containing the table data
    ::param coerce_type: the type that the table data is converted to
    ::param transpose: reverses the data if needed

    Example:
    >>> table_data = ""\"
    ...         L1      L2      L3      L4      L5      L6
    ... C1      6736    42658   70414   45170   184679  111569
    ... C2      217266  227190  249640  203029  153531  117487
    ... C3      35936   28768   126316  2498    130317  74034
    ... C4      73446   52077   108368  75011   49827   62850
    ... C5      174664  177461  151589  153300  59916   135162
    ... C6      186302  189099  147026  164938  149836  286307
    ... ""\"
    >>> table = read_table(table_data, int)
    >>> table[("C1","L1")]
    6736
    >>> table[("C6","L5")]
    149836
    """
    lines = data.splitlines()
    headings = lines[1].split()
    result = {}
    for row in lines[2:]:
        items = row.split()
        for i, item in enumerate(items[1:]):
            if transpose:
                key = headings[i], items[0]
            else:
                key = items[0], headings[i]
            result[key] = coerce_type(item)
    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 p_specification(t):
    """specification : definition_list"""


def yubikey_public_id(otp):
    """ Returns the yubikey identity given a token. """
    return otp[:12]


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

        :param SecondaryTeamRequestExpiredDetails val:
        :rtype: TeamMergeRequestExpiredExtraDetails
        """
    return cls('secondary_team', val)


def colordiff(rgb1, rgb2):
    """ Computes the Euclidean difference between two RGB color tuples.

    Parameters
    ----------
    rgb1 : numpy.array
        First RGB color
    rgb2 : numpy.array
        Second RGB color

    Returns
    -------
    float
        The Euclidean distance between the two colors.
    """
    r1, g1, b1 = rgb1
    r2, g2, b2 = rgb2
    return (float(r1) - float(r2)) ** 2 + (float(g1) - float(g2)) ** 2 + (float
        (b1) - float(b2)) ** 2


def get_weekly_report_subject(week_day, person):
    """
    Returns subject string for weekly report email

    `week_day:datetime.date` - any date for the week we are reporting for
    `person:str` - reporting person's name, e.g. 'Jon Doe'
    """
    calendar_time = 'week {:02}'.format(week_day.isocalendar()[1])
    subject = 'Weekly report for {person} ({calendar_time})'.format(person=
        person, calendar_time=calendar_time)
    return subject


def _sim_fill(r1, r2, imsize):
    """
        calculate the fill similarity over the image
    """
    bbsize = (max(r1['max_x'], r2['max_x']) - min(r1['min_x'], r2['min_x'])
        ) * (max(r1['max_y'], r2['max_y']) - min(r1['min_y'], r2['min_y']))
    return 1.0 - (bbsize - r1['size'] - r2['size']) / imsize


def separate():
    """Separate selected points from connected unselected points into a new object

    """
    pass


def filter_score(rules, minimum_score=0):
    """
    Filter the rules object for rules that have a certain score or higher
    :param rules: YARA rules JSON object
    :param minimum_score: minimum score
    :return: list of filtered rules
    """
    filtered_rules = []
    for rule in rules:
        if int(rule['score']) >= minimum_score:
            filtered_rules.append(rule)
    return filtered_rules


def _build_simple_row(padded_cells, rowfmt):
    """Format row according to DataRow format without padding."""
    begin, sep, end = rowfmt
    return (begin + sep.join(padded_cells) + end).rstrip()


def read_varint(readfn):
    """
    Reads a variable-length encoded integer.

    :param readfn: a callable that reads a given number of bytes,
        like file.read().
    """
    b = ord(readfn(1))
    i = b & 127
    shift = 7
    while b & 128 != 0:
        b = ord(readfn(1))
        i |= (b & 127) << shift
        shift += 7
    return i


def _insert_newlines(text: str, n=40):
    """
    Inserts a newline into the given text every n characters.
    :param text: the text to break
    :param n:
    :return:
    """
    if not text:
        return ''
    lines = []
    for i in range(0, len(text), n):
        lines.append(text[i:i + n])
    return '\n'.join(lines)


def reveal():
    """Show again hidden control points

    """
    pass


def get_input(prompt, default=None, choices=None, option_value=None):
    """
    If option_value is not None, then return it. Otherwise get the result from
    input.
    """
    if option_value is not None:
        return option_value
    choices = choices or []
    while 1:
        r = input(prompt + ' ').strip()
        if not r and default is not None:
            return default
        if choices:
            if r not in choices:
                r = None
            else:
                break
        else:
            break
    return r


def is_16bytes(instance, attribute, value):
    """
    validator for a 16 byte value
    """
    if not isinstance(value, bytes) or len(value) != 16:
        raise ValueError('must be 16 byte value')


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

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

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


def t_INITIAL_bin_LineContinue(t):
    """[_\\\\][ \\t]*('.*|[Rr][Ee][Mm]\\b.*|[Rr][Ee][Mm])?\\r?\\n"""
    global LABELS_ALLOWED
    t.lexer.lineno += 1
    LABELS_ALLOWED = False


def _get_index_range(start, stop, length, step=1):
    """Given start, stop, step and array length, return
    absolute values of start, stop, and step for generating index range.
    The returned values have been compensated by adding length if they
    are less than zero for all the cases but slice(None, None, -1).
    Note that the returned value of stop is not necessarily >= 0, since
    absolute stop is -1 in the case of slice(None, None, -1)."""
    if step == 0:
        raise ValueError('step size cannot be zero')
    if length < 0:
        raise ValueError('array length cannot be less than zero')
    if step is None:
        step = 1
    if start is None:
        if step > 0:
            start = 0
        else:
            start = length - 1
    elif start < 0:
        start += length
        if start < 0:
            raise IndexError('Slicing start %d exceeds limit of %d' % (
                start - length, length))
    elif start >= length:
        raise IndexError('Slicing start %d exceeds limit of %d' % (start,
            length))
    if stop is None:
        if step > 0:
            stop = length
        else:
            stop = -1
    elif stop < 0:
        stop += length
        if stop < 0:
            raise IndexError('Slicing stop %d exceeds limit of %d' % (stop -
                length, length))
    elif stop > length:
        raise IndexError('Slicing stop %d exceeds limit of %d' % (stop, length)
            )
    return start, stop, step


def team_and_division(o):
    """For use on Model.team_clashes as label_from_instance argument."""
    return '%s (%s)' % (o.title, o.division.title)


def renderHeader(column):
    """Render a header for the given column.

        Uses getHeader."""


@classmethod
def get_commissions(cls, contract_values, turnover, nlvs=None):
    """
        Returns a DataFrame of commissions.

        Parameters
        ----------
        contract_values : DataFrame, required
            a DataFrame of contract values (price * multipler / price_magnifier)

        turnover : DataFrame of floats, required
            a DataFrame of turnover, expressing the percentage of account equity that
            is turning over

        nlvs : DataFrame of nlvs, optional
            a DataFrame of NLVs (account balance), which is used to calculate and
            enforce min commissions. NLVs should be expressed in the currency of the
            contract, which should also be the currency of the commission class. If
            not provided, min commissions won't be calculated or enforced.

        Returns
        -------
        DataFrame
            a DataFrame of commissions, expressed as percentages of account equity
        """
    taker_ratio = 1 - cls.MAKER_RATIO
    exchange_fee_per_share = (cls.EXCHANGE_FEE_PER_SHARE + cls.MAKER_RATIO *
        cls.MAKER_FEE_PER_SHARE + taker_ratio * cls.TAKER_FEE_PER_SHARE)
    if cls.TIER_2_RATIO:
        broker_commission_per_share = ((1 - cls.TIER_2_RATIO) * cls.
            BROKER_COMMISSION_PER_SHARE + cls.TIER_2_RATIO * cls.
            BROKER_COMMISSION_PER_SHARE_TIER_2)
    else:
        broker_commission_per_share = cls.BROKER_COMMISSION_PER_SHARE
    commission_per_share_with_fees = broker_commission_per_share * (1 + cls
        .COMMISSION_PERCENTAGE_FEE_RATE)
    broker_commission_rates = float(broker_commission_per_share
        ) / contract_values.where(contract_values != 0).abs()
    broker_commissions = broker_commission_rates * turnover
    if nlvs is not None and cls.MIN_COMMISSION:
        broker_commissions = cls._enforce_min_commissions(broker_commissions,
            nlvs=nlvs)
    share_based_exchange_fee_rates = (exchange_fee_per_share /
        contract_values.where(contract_values != 0).abs())
    share_based_exchange_fees = share_based_exchange_fee_rates * turnover
    value_based_fees = cls.PERCENTAGE_FEE_RATE * turnover
    commission_based_fees = (cls.COMMISSION_PERCENTAGE_FEE_RATE *
        broker_commissions)
    commissions = (broker_commissions + share_based_exchange_fees +
        value_based_fees + commission_based_fees)
    return commissions


def openbaar_domein_adapter(obj, request=None):
    """
    Adapter for rendering
    :class:`oe_geoutils.data.models.OpenbaarDomein` to json.

    Add the adapter to `jsonpublish`
    from jsonpublish import register_adapter
    register_adapter(OpenbaarDomein, openbaar_domein_adapter)

    Add the adapter to your :class:`pyramid.renderers.JSON` json_renderer
    from pyramid.renderers import JSON
    json_renderer = JSON()
    json_renderer.add_adapter(OpenbaarDomein, openbaar_domein_adapter)
    """
    openbaar_domein = {'id': obj.id, 'type': obj.type, 'provincie': {
        'niscode': obj.provincie_niscode, 'naam': obj.provincie_naam},
        'gemeente': {'niscode': obj.gemeente_niscode, 'naam': obj.
        gemeente_naam, 'id': obj.gemeente_crab_id}, 'deelgemeente': {
        'niscode': obj.deelgemeente_niscode, 'naam': obj.deelgemeente_naam},
        'omschrijving': obj.omschrijving}
    return openbaar_domein


def _score(estimator, x, y, scorers):
    """Return a dict of scores"""
    scores = {}
    for name, scorer in scorers.items():
        score = scorer(estimator, x, y)
        scores[name] = score
    return scores


def build_toc_line(toc_line_no_indent: str, no_of_indentation_spaces: int=0
    ) ->str:
    """Build the TOC line.

    :parameter toc_line_no_indent: the TOC line without indentation.
    :parameter no_of_indentation_spaces: the number of indentation spaces.
         Defaults to ``0``.
    :type toc_line_no_indent: str
    :type no_of_indentation_spaces: int
    :returns: toc_line, a single line of the table of contents.
    :rtype: str
    :raises: a built-in exception.
    """
    assert no_of_indentation_spaces >= 0
    indentation = no_of_indentation_spaces * ' '
    toc_line = indentation + toc_line_no_indent
    return toc_line


def cleanup_test_name(name, strip_tags=True, strip_scenarios=False):
    """Clean up the test name for display.

    By default we strip out the tags in the test because they don't help us
    in identifying the test that is run to its result.

    Make it possible to strip out the testscenarios information (not to
    be confused with tempest scenarios) however that's often needed to
    identify generated negative tests.
    """
    if strip_tags:
        tags_start = name.find('[')
        tags_end = name.find(']')
        if tags_start > 0 and tags_end > tags_start:
            newname = name[:tags_start]
            newname += name[tags_end + 1:]
            name = newname
    if strip_scenarios:
        tags_start = name.find('(')
        tags_end = name.find(')')
        if tags_start > 0 and tags_end > tags_start:
            newname = name[:tags_start]
            newname += name[tags_end + 1:]
            name = newname
    return name


def get_logger(name):
    """Get a logging instance we can use."""
    import logging
    import sys
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    shandler = logging.StreamHandler(sys.stdout)
    fmt = ''
    fmt += '\x1b[1;32m%(levelname)-5s %(module)s:%(funcName)s():'
    fmt += '%(lineno)d %(asctime)s\x1b[0m| %(message)s'
    fmtr = logging.Formatter(fmt)
    shandler.setFormatter(fmtr)
    logger.addHandler(shandler)
    return logger


def p_exprlist(p):
    """ exprlist : a_expr
                 | exprlist "," a_expr """
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1] + [p[3]]


@classmethod
def get(cls, *args, **filters):
    """
        Get single item using filter_by query.
        """
    if len(args) == 1 and len(filters) == 0:
        filters['id'] = args[0]
    return cls.query.filter_by(**filters).first()


def text_cut():
    """Cut selected text to clipboard

    """
    pass


def GetVendorName():
    """Software vendor's name."""
    return 'Silverglass Technical'


def bC_Ca_HCO3_POS85(T, P):
    """c-a: calcium bicarbonate [POS85]."""
    b0 = 0.28
    b1 = 0.3
    b2 = 0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def wrap_span(text: str, col: str=None, font: str=None, weight: str=None
    ) ->str:
    """
    This wraps a span element around an input text.

    :param weight: string, the weight of the element, numerical or  'ultralight', 'light', 'normal', 'bold',
        'ultrabold', 'heavy'
    :param font: string, the font to use for the span element
    :type text: string, the text that should be wrapped in the span
    :type col: string, a html color string
    """
    color_text = " color='%s'" % col if col else ''
    font_text = " font='%s'" % font if font else ''
    weight_text = " weight='%s'" % weight if weight else ''
    return '<span%s%s%s>%s</span>' % (font_text, color_text, weight_text, text)


def asindices(iterable, lst):
    """Replace items in iterable with their corresponding indices in list, or
    convert them to integers. E.g. asindices(['o', '22'], 'foobar') => 1, 22.
    """
    for item in iterable:
        try:
            yield lst.index(item)
        except ValueError:
            yield int(item)


@classmethod
def parseKwargs(cls, config_stats, logger=None):
    """Parse the stats field of a configuration dict and return the kwargs to use for
        initializing an instance of the class.

        The base class implementation just returns the kwargs as they are, but derived classes
        might want to override this if they need to do something more sophisticated with them.

        :param config_stats:    The stats field of the configuration dict, config['stats']
        :param logger:          A logger object for logging debug info. [default: None]

        :returns: a kwargs dict to pass to the initializer
        """
    kwargs = {}
    kwargs.update(config_stats)
    kwargs.pop('type', None)
    return kwargs


def untranslateName(s):
    """Undo Python conversion of CL parameter or variable name"""
    s = s.replace('DOT', '.')
    s = s.replace('DOLLAR', '$')
    if s[:2] == 'PY':
        s = s[2:]
    s = s.replace('.PY', '.')
    return s


def reverse_lists(lists):
    """
    >>> reverse_lists([[1,2,3], [4,5,6]])
    [[3, 2, 1], [6, 5, 4]]
    """
    return list(map(list, map(reversed, lists)))


def valid_sample(sample):
    """Check whether a sample is valid.

        sample: sample to be checked

    """
    return sample is not None and isinstance(sample, dict) and len(list(
        sample.keys())) > 0 and not sample.get('__bad__', False)


def count_distinct(df, *cols):
    """Count distinct values across the given columns of a Spark DF.

    This triggers a job to run the count.

    Parameters
    ----------
    df : DataFrame
        A Spark DataFrame.
    cols : str, Column or list-like
        Zero or more string column names or Columns, or a list thereof.

    Returns
    -------
    int
        The number of distinct values in a single column, or the number of
        distinct rows across multiple columns. If no columns are given, returns
        the number of distinct rows in the DataFrame.
    """
    if len(cols) > 0:
        df = df.select(*cols)
    return df.distinct().count()


@staticmethod
def APPLYSORT(arr, func):
    """Algorithm to sort a list if func is applied to the elements of the list"""
    data = arr
    return sorted(data, key=func)


def get_alignment_size(alignment_tuple):
    """Get alignment length from alignment tuple.

    Given tuple (aln_name, aln_dict) get len of random sequence in {taxon: sequence} alignment dict."""
    alignment_name, alignment_dict = alignment_tuple
    seq_length = len(next(iter(alignment_dict.values())))
    total_alignment_size = seq_length * len(alignment_dict.values())
    return total_alignment_size


def human_filesize(bytes):
    """Human-readable file size.
    """
    for x in ['bytes', 'KB', 'MB', 'GB']:
        if bytes < 1024.0:
            return '%3.1f %s' % (bytes, x)
        bytes /= 1024.0
    return '%3.1f %s' % (bytes, 'TB')


def start_game_session_placement(PlacementId=None, GameSessionQueueName=
    None, GameProperties=None, MaximumPlayerSessionCount=None,
    GameSessionName=None, PlayerLatencies=None, DesiredPlayerSessions=None):
    """
    Places a request for a new game session in a queue (see  CreateGameSessionQueue ). When processing a placement request, Amazon GameLift searches for available resources on the queue's destinations, scanning each until it finds resources or the placement request times out.
    A game session placement request can also request player sessions. When a new game session is successfully created, Amazon GameLift creates a player session for each player included in the request.
    When placing a game session, by default Amazon GameLift tries each fleet in the order they are listed in the queue configuration. Ideally, a queue's destinations are listed in preference order.
    Alternatively, when requesting a game session with players, you can also provide latency data for each player in relevant regions. Latency data indicates the performance lag a player experiences when connected to a fleet in the region. Amazon GameLift uses latency data to reorder the list of destinations to place the game session in a region with minimal lag. If latency data is provided for multiple players, Amazon GameLift calculates each region's average lag for all players and reorders to get the best game play across all players.
    To place a new game session request, specify the following:
    If successful, a new game session placement is created.
    To track the status of a placement request, call  DescribeGameSessionPlacement and check the request's status. If the status is Fulfilled , a new game session has been created and a game session ARN and region are referenced. If the placement request times out, you can resubmit the request or retry it with a different queue.
    See also: AWS API Documentation

    :example: response = client.start_game_session_placement(
        PlacementId='string',
        GameSessionQueueName='string',
        GameProperties=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ],
        MaximumPlayerSessionCount=123,
        GameSessionName='string',
        PlayerLatencies=[
            {
                'PlayerId': 'string',
                'RegionIdentifier': 'string',
                'LatencyInMilliseconds': ...
            },
        ],
        DesiredPlayerSessions=[
            {
                'PlayerId': 'string',
                'PlayerData': 'string'
            },
        ]
    )

    :type PlacementId: string
    :param PlacementId: [REQUIRED]
            Unique identifier to assign to the new game session placement. This value is developer-defined. The value must be unique across all regions and cannot be reused unless you are resubmitting a canceled or timed-out placement request.

    :type GameSessionQueueName: string
    :param GameSessionQueueName: [REQUIRED]
            Name of the queue to use to place the new game session.

    :type GameProperties: list
    :param GameProperties: Set of developer-defined properties for a game session. These properties are passed to the server process hosting the game session.
            (dict) --Set of key-value pairs containing information a server process requires to set up a game session. This object allows you to pass in any set of data needed for your game. For more information, see the Amazon GameLift Developer Guide .
            Key (string) -- [REQUIRED]TBD
            Value (string) -- [REQUIRED]TBD

    :type MaximumPlayerSessionCount: integer
    :param MaximumPlayerSessionCount: [REQUIRED]
            Maximum number of players that can be connected simultaneously to the game session.

    :type GameSessionName: string
    :param GameSessionName: Descriptive label that is associated with a game session. Session names do not need to be unique.

    :type PlayerLatencies: list
    :param PlayerLatencies: Set of values, expressed in milliseconds, indicating the amount of latency that players are experiencing when connected to AWS regions. This information is used to try to place the new game session where it can offer the best possible gameplay experience for the players.
            (dict) --Regional latency information for a player, used when requesting a new game session with StartGameSessionPlacement . This value indicates the amount of time lag that exists when the player is connected to a fleet in the specified region. The relative difference between a player's latency values for multiple regions are used to determine which fleets are best suited to place a new game session for the player.
            PlayerId (string) --Unique identifier for a player associated with the latency data.
            RegionIdentifier (string) --Name of the region that is associated with the latency value.
            LatencyInMilliseconds (float) --Amount of time that represents the time lag experienced by the player when connected to the specified region.

    :type DesiredPlayerSessions: list
    :param DesiredPlayerSessions: Set of information on each player to create a player session for.
            (dict) --Player information for use when creating player sessions using a game session placement request with StartGameSessionPlacement .
            PlayerId (string) --Unique identifier for a player to associate with the player session.
            PlayerData (string) --Developer-defined information related to a player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game.

    :rtype: dict
    :return: {
        'GameSessionPlacement': {
            'PlacementId': 'string',
            'GameSessionQueueName': 'string',
            'Status': 'PENDING'|'FULFILLED'|'CANCELLED'|'TIMED_OUT',
            'GameProperties': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ],
            'MaximumPlayerSessionCount': 123,
            'GameSessionName': 'string',
            'GameSessionId': 'string',
            'GameSessionArn': 'string',
            'GameSessionRegion': 'string',
            'PlayerLatencies': [
                {
                    'PlayerId': 'string',
                    'RegionIdentifier': 'string',
                    'LatencyInMilliseconds': ...
                },
            ],
            'StartTime': datetime(2015, 1, 1),
            'EndTime': datetime(2015, 1, 1),
            'IpAddress': 'string',
            'Port': 123,
            'PlacedPlayerSessions': [
                {
                    'PlayerId': 'string',
                    'PlayerSessionId': 'string'
                },
            ]
        }
    }

    :returns:
    PlacementId (string) -- [REQUIRED]
    Unique identifier to assign to the new game session placement. This value is developer-defined. The value must be unique across all regions and cannot be reused unless you are resubmitting a canceled or timed-out placement request.

    GameSessionQueueName (string) -- [REQUIRED]
    Name of the queue to use to place the new game session.

    GameProperties (list) -- Set of developer-defined properties for a game session. These properties are passed to the server process hosting the game session.

    (dict) --Set of key-value pairs containing information a server process requires to set up a game session. This object allows you to pass in any set of data needed for your game. For more information, see the Amazon GameLift Developer Guide .

    Key (string) -- [REQUIRED]TBD

    Value (string) -- [REQUIRED]TBD

    MaximumPlayerSessionCount (integer) -- [REQUIRED]
    Maximum number of players that can be connected simultaneously to the game session.

    GameSessionName (string) -- Descriptive label that is associated with a game session. Session names do not need to be unique.
    PlayerLatencies (list) -- Set of values, expressed in milliseconds, indicating the amount of latency that players are experiencing when connected to AWS regions. This information is used to try to place the new game session where it can offer the best possible gameplay experience for the players.

    (dict) --Regional latency information for a player, used when requesting a new game session with  StartGameSessionPlacement . This value indicates the amount of time lag that exists when the player is connected to a fleet in the specified region. The relative difference between a player's latency values for multiple regions are used to determine which fleets are best suited to place a new game session for the player.

    PlayerId (string) --Unique identifier for a player associated with the latency data.

    RegionIdentifier (string) --Name of the region that is associated with the latency value.

    LatencyInMilliseconds (float) --Amount of time that represents the time lag experienced by the player when connected to the specified region.

    DesiredPlayerSessions (list) -- Set of information on each player to create a player session for.

    (dict) --Player information for use when creating player sessions using a game session placement request with  StartGameSessionPlacement .

    PlayerId (string) --Unique identifier for a player to associate with the player session.

    PlayerData (string) --Developer-defined information related to a player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game.

    """
    pass


def __getitem__(key):
    """
        Get db or resource
        """


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


@classmethod
def check_version(cls, target, logger):
    """
        Check the target and see if its kernel version matches our view of the world
        """
    parts = target.kernel_version.parts
    ref_parts = 4, 4, 0
    if parts < ref_parts:
        logger.warn(
            'Sched domain flags are defined for kernels v{} and up, but target is running v{}'
            .format(ref_parts, parts))


@staticmethod
def _set_migration_status(migration, status):
    """Set the status, and guard against a None being passed in.

        This is useful as some of the compute RPC calls will not pass
        a migration object in older versions. The check can be removed when
        we move past 4.x major version of the RPC API.
        """
    if migration:
        migration.status = status
        migration.save()


def _get_default_service_trust_document():
    """
    Just a string representing the service role policy.
    Includes newlines for pretty printing :)
    """
    return """{
    "Version": "2012-10-17",
    "Statement": [{
        "Sid": "",
        "Effect": "Allow",
        "Principal": {
            "Service": "elasticbeanstalk.amazonaws.com"
        },
        "Action": "sts:AssumeRole",
        "Condition": {
            "StringEquals": {
                "sts:ExternalId": "elasticbeanstalk"
            }
        }
    }]
}"""


def dirac_str_to_int(dirac_str):
    """Converts a string in Dirac notation to an integer

    This will work for the computational basis only.
    Example: |1001> = 9

    Args:
        dirac_str: something like "|1001>"
    """
    return int(dirac_str[1:-1], 2)


@classmethod
def get_object_info(cls, where_clause=None):
    """Get model and field information about the model class."""
    related_model_info = {}
    for fkf in cls._meta.refs:
        rel_mod = fkf.rel_model
        if rel_mod.__class__.__name__ != cls.__name__:
            table = rel_mod._meta.table_name
            pkey = rel_mod._meta.primary_key.name
            related_model_info[fkf.name] = {'db_column': fkf.column_name,
                'db_table': table, 'primary_key': pkey}
    where_clause = where_clause if where_clause else {}
    field_types = {}
    for field_name, field in cls._meta.fields.items():
        field_types[field_name] = str(field.field_type)
    js_object = {'callable_name': cls.__module__.split('.').pop().lower(),
        'last_changed_date': cls.last_change_date(), 'primary_keys': cls.
        get_primary_keys(), 'field_list': cls._meta.sorted_field_names,
        'field_types': field_types, 'foreign_keys': cls.cls_foreignkeys(),
        'related_models': related_model_info, 'related_names': cls.
        cls_revforeignkeys(), 'record_count': cls.select().where(cls.
        where_clause(where_clause)).count()}
    return js_object


def section_header(section_name: str) ->str:
    """
    Constructs a Phase Header given a Phase Name
    :param section_name:
    """
    return '[' + section_name + ']'


@staticmethod
def _validate_key(key):
    """Emit a warning or raise an exception if key is invalid. Returns key."""
    if '.' in key:
        from ..errors import InvalidKeyError
        raise InvalidKeyError("Keys may not contain dots ('.').")
    return key


def ising_energy(sample, h, J, offset=0.0):
    """Calculate the energy for the specified sample of an Ising model.

    Energy of a sample for a binary quadratic model is defined as a sum, offset
    by the constant energy offset associated with the model, of
    the sample multipled by the linear bias of the variable and
    all its interactions. For an Ising model,

    .. math::

        E(\\mathbf{s}) = \\sum_v h_v s_v + \\sum_{u,v} J_{u,v} s_u s_v + c

    where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}`
    the quadratic bias (interactions), and :math:`c` the energy offset.

    Args:
        sample (dict[variable, spin]):
            Sample for a binary quadratic model as a dict of form {v: spin, ...},
            where keys are variables of the model and values are spins (either -1 or 1).
        h (dict[variable, bias]):
            Linear biases as a dict of the form {v: bias, ...}, where keys are variables of
            the model and values are biases.
        J (dict[(variable, variable), bias]):
           Quadratic biases as a dict of the form {(u, v): bias, ...}, where keys
           are 2-tuples of variables of the model and values are quadratic biases
           associated with the pair of variables (the interaction).
        offset (numeric, optional, default=0):
            Constant offset to be applied to the energy. Default 0.

    Returns:
        float: The induced energy.

    Notes:
        No input checking is performed.

    Examples:
        This example calculates the energy of a sample representing two down spins for
        an Ising model of two variables that have positive biases of value 1 and
        are positively coupled with an interaction of value 1.

        >>> import dimod
        >>> sample = {1: -1, 2: -1}
        >>> h = {1: 1, 2: 1}
        >>> J = {(1, 2): 1}
        >>> dimod.ising_energy(sample, h, J, 0.5)
        -0.5

    References
    ----------

    `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_

    """
    for v in h:
        offset += h[v] * sample[v]
    for v0, v1 in J:
        offset += J[v0, v1] * sample[v0] * sample[v1]
    return offset


def _get_center(c):
    """Compute center of ellipse from implicit function coefficients.

    Parameters
    ----------
    c : array_like
        Coefficients of general quadratic polynomial function for
        conic funs.

    Returns
    -------
    xc : float
        x coordinate of center.
    yc : float
        y coordinate of center.
    """
    A, B, C, D, E, _F = c[:]
    den = B ** 2 - 4 * A * C
    xc = (2 * C * D - B * E) / den
    yc = (2 * A * E - B * D) / den
    return xc, yc


def enableFaulthandler():
    """ Enable faulthandler for all threads.

    If the faulthandler package is available, this function disables and then
    re-enables fault handling for all threads (this is necessary to ensure any
    new threads are handled correctly), and returns True.

    If faulthandler is not available, then returns False.
    """
    try:
        import faulthandler
        faulthandler.disable()
        faulthandler.enable(all_threads=True)
        return True
    except ImportError:
        return False


@classmethod
def disable(cls):
    """Disables headless events for the target.
        """
    return cls.build_send_payload('disable', {}), None


def normalise_tabular_labelling(row, marker_item):
    """Removes duplicate column labels"""
    for item in row:
        if item == marker_item:
            row.remove(item)
    return row


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def open_instance_public_ports(portInfo=None, instanceName=None):
    """
    Adds public ports to an Amazon Lightsail instance.
    See also: AWS API Documentation

    :example: response = client.open_instance_public_ports(
        portInfo={
            'fromPort': 123,
            'toPort': 123,
            'protocol': 'tcp'|'all'|'udp'
        },
        instanceName='string'
    )

    :type portInfo: dict
    :param portInfo: [REQUIRED]
            An array of key-value pairs containing information about the port mappings.
            fromPort (integer) --The first port in the range.
            toPort (integer) --The last port in the range.
            protocol (string) --The protocol.

    :type instanceName: string
    :param instanceName: [REQUIRED]
            The name of the instance for which you want to open the public ports.

    :rtype: dict
    :return: {
        'operation': {
            'id': 'string',
            'resourceName': 'string',
            'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
            'createdAt': datetime(2015, 1, 1),
            'location': {
                'availabilityZone': 'string',
                'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
            },
            'isTerminal': True|False,
            'operationDetails': 'string',
            'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
            'status': 'NotStarted'|'Started'|'Failed'|'Completed',
            'statusChangedAt': datetime(2015, 1, 1),
            'errorCode': 'string',
            'errorDetails': 'string'
        }
    }

    """
    pass


def present_params(paramlist, spacing=0, maxchars=90, linecont=', &'):
    """Creates the (paramlist) for a method call formatted nicely for calls
    with lots of parameters."""
    line = []
    length = 0
    result = []
    for param in paramlist:
        extra = len(list(param))
        if length + extra + 2 + spacing > maxchars:
            result.append(', '.join(line) + linecont)
            line = [param]
            length = extra + 2
        else:
            line.append(param)
            length += extra + 2
    result.append(', '.join(line))
    return '\n{}'.format(' '.join(['' for i in range(spacing + 3)])).join(
        result)


def get(isamAppliance, check_mode=False, force=False):
    """
    Retrieving the administrator settings
    """
    return isamAppliance.invoke_get('Retrieving the administrator settings',
        '/admin_cfg')


def min(cube1, cube2):
    """Return min value between two cubes
    """
    return (cube1 > cube2) * cube2 + (cube1 <= cube2) * cube1


def imapUTF7Encode(ust):
    """Returns imap utf-7 encoded version of string"""
    return ust.encode('imap4-utf-7')


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

        :param PaperFolderChangeSubscriptionDetails val:
        :rtype: EventDetails
        """
    return cls('paper_folder_change_subscription_details', val)


def distance(vec1, vec2):
    """Returns the distance between two Vectors"""
    vec3 = vec2 - vec1
    return vec3.length()


def allnot(it):
    """Returns True iff all elements in the iterable ``it`` evaluate to ``False``, and ``False`` otherwise."""
    return not [(1) for e in it if bool(e) is True]


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


def field_points_to_compare(side_length, penumbra_width, rotation,
    num_points_across_penumbra=11, num_points_across_field_edge=51):
    """Points for comparison for field centre finding.

    Creates two sets of points centred around the origin designed
    so that by shifting the points by the centre to be tested and then
    comparing a function looked up at one set, to that at the other set
    a profile centre can be found.
    """


def filter_date_suffix(date):
    """Returns a date suffix for a given date"""
    day = int(date[-2:])
    if 4 <= day <= 20 or 24 <= day <= 30:
        suffix = 'th'
    else:
        suffix = ['st', 'nd', 'rd'][day % 10 - 1]
    return date + suffix


@classmethod
def _get_classname(cls):
    """Get name of the class."""
    return cls.__name__


def mass_setattr(obj, **attrs):
    """Set all given attributes and return the same object."""
    for attr in attrs:
        setattr(obj, attr, attrs[attr])
    return obj


def is_private():
    """Returns true if the item is private.

        Private items are picked up only by news filters in the same
        container as the source.
        """


@staticmethod
def get_iterations(args) ->int:
    """Return number of iterations performed, based on lower level function arguments."""
    return args[0]


def create_table(conn, table_sql):
    """ create a table from the table_sql statement
    :param conn: Connection object
    :param table_sql: a CREATE TABLE statement
    :return:
    """
    c = conn.cursor()
    c.execute(table_sql)
    conn.commit()


def select_ungrouped(extend: bool=False):
    """Select vertices without a group

    :param extend: Extend, Extend the selection
    :type extend: bool
    """
    pass


def get_dbattr(basemodel, attrstring):
    """
    get a database attribute for a string which may have multiple levels

    :param basemodel: top level model under which attrstring should be found
    :param attrstring: dotted notation attribute; dots allow traversal of multiple levels
    :return: bottom level attribute value
    """
    attrs = attrstring.split('.')
    thismodel = basemodel
    while len(attrs) > 1:
        thisattr = attrs.pop(0)
        thismodel = type(getattr(thismodel, thisattr))
    attr = attrs.pop(0)
    return getattr(thismodel, attr)


def get_route_doc_string(routes, route, method):
    """Returns doc string for embedded route functions."""
    try:
        doc = routes[route][0].handlers[method].__doc__
    except AttributeError:
        doc = routes[route][0].__doc__
    return doc


def vapor_pressure(T, formula='Tetens1930'):
    """
    Calculate vapor pressure according to
    given formula
    """
    if formula == 'Tetens1930':
        e = 6.11 * 10 ** (7.5 * T / (237.3 + T))
    return e


def _tag_depth(path, depth=None):
    """Add depth tag to path."""
    if not path or path[0] != '/':
        raise ValueError('Path must start with /!')
    if depth is None:
        depth = path.count('/')
    return '{}{}'.format(depth, path).encode('utf-8')


def proto_to_bytes(proto):
    """ Converts a proto object to a bytes array """
    return proto.SerializeToString()


def valid_BIC(bic):
    """Check validity of BIC"""
    bic = bic.strip()
    if len(bic) != 8 and len(bic) != 11:
        return False
    if not bic[:6].isalpha():
        return False
    if not bic[6:8].isalnum():
        return False
    return True


def execute_preset(filepath: str='', menu_idname: str=''):
    """Execute a preset

    :param filepath: filepath
    :type filepath: str
    :param menu_idname: Menu ID Name, ID name of the menu this was called from
    :type menu_idname: str
    """
    pass


def delete_edgeloop(use_face_split: bool=True):
    """Delete an edge loop by merging the faces on each side

    :param use_face_split: Face Split, Split off face corners to maintain surrounding geometry
    :type use_face_split: bool
    """
    pass


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)


@classmethod
def get_args(cls, dist, header=None):
    """
    Yield write_script() argument tuples for a distribution's
    console_scripts and gui_scripts entry points.
    """
    template = 'import sys\nfrom {0} import {1}\nsys.exit({1}())'
    if header is None:
        header = cls.get_header()
    spec = str(dist.as_requirement())
    for type_ in ('console', 'gui'):
        group = type_ + '_scripts'
        for name, ep in dist.get_entry_map(group).items():
            cls._ensure_safe_name(name)
            script_text = template.format(ep.module_name, ep.attrs[0])
            args = cls._get_script_args(type_, name, header, script_text)
            for res in args:
                yield res


def convert_short_channel_id_to_channel_id(blockheight, transaction, output):
    """
    Converts short channel id (blockheight:transaction:output) to a long integer channel id.

    :param blockheight:
    :param transaction: Number of transaction in the block.
    :param output: Number of output in the transaction.
    :return: channel id: Encoded integer number representing the channel,
     can be decoded by :func:`lib.conversion.extract_short_channel_id_from_string`.
    """
    return blockheight << 40 | transaction << 16 | output


def _isviewer(target):
    """Return true if target is a viewer"""
    return target.__class__.__name__ == 'Viewer'


@classmethod
def was_any_device_deleted(cls):
    """
        Checks if any device was deleted.
        :return: True if any device was deleted, False otherwise
        """
    return cls._was_any_device_deleted


def _eq(field, value, document):
    """
    Returns True if the value of a document field is equal to a given value
    """
    try:
        return document.get(field, None) == value
    except TypeError:
        return False


def isnumber(x):
    """Is x a number? We say it is if it has a __int__ method."""
    return hasattr(x, '__int__')


def p_chain_dot_disconnect(p):
    """chain : chain DOT connected_atom"""
    p[0] = p[1] + [('DOT',)] + p[3]


def setup_cmd():
    """
    Try to install activate-global-python-argcomplete to enable auto-completion
    for bash command line
    """
    pass


def repeat(input, repeats, dim):
    """Repeats elements of an array.

    Parameters
    ----------
    input : Tensor
        Input data array
    repeats : int
        The number of repetitions for each element
    dim : int
        The dim along which to repeat values.

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


def error_msg_from_exception(e):
    """Translate exception into error message

    Database have different ways to handle exception. This function attempts
    to make sense of the exception object and construct a human readable
    sentence.

    TODO(bkyryliuk): parse the Presto error message from the connection
                     created via create_engine.
    engine = create_engine('presto://localhost:3506/silver') -
      gives an e.message as the str(dict)
    presto.connect('localhost', port=3506, catalog='silver') - as a dict.
    The latter version is parsed correctly by this function.
    """
    msg = ''
    if hasattr(e, 'message'):
        if isinstance(e.message, dict):
            msg = e.message.get('message')
        elif e.message:
            msg = '{}'.format(e.message)
    return msg or '{}'.format(e)


def JulianDay():
    """Return the Julian day according to
        http://www.tondering.dk/claus/cal/node3.html#sec-calcjd
        """


def getData(func, key, force_reload=False, args=[], kwargs={}):
    """Convenience to read and cache results at once.

        * Tries to read result from cache.
        * If no result, call given functions with *args ang **kwargs
        * If function called, store returned value to cache
        * Return result
        """


@classmethod
def kwargs(cls, model=None, **kwargs):
    """
        Create KwargDict

        Parameters
        ----------
        model
            model to be operated on

        Returns
        -------
        'KwargDict'
            KwargDict class instance containing dict of layer's kwargs
        """
    return super().kwargs(**kwargs)


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

        :param PaperContentRemoveFromFolderDetails val:
        :rtype: EventDetails
        """
    return cls('paper_content_remove_from_folder_details', val)


@classmethod
def home(cls):
    """Return a new path pointing to the user's home directory (as
        returned by os.path.expanduser('~')).

        :rtype: Path
        """
    return cls(cls()._flavour.gethomedir(None))


def getMeasure(unique_name):
    """Returns a IMeasure in the cube with the given unique name."""


def childDataReceived(childFD, data):
    """
        Called when data arrives from the child process.

        @type childFD: C{int}
        @param childFD: The file descriptor from which the data was
            received.

        @type data: C{str}
        @param data: The data read from the child's file descriptor.
        """


def register(name, title, install_module=None, module_path=None, depends_on
    =(u'Silva',)):
    """Register a new extension.
        """


def _get_is_direct(stmt):
    """Returns true if there is evidence that the statement is a direct
    interaction. If any of the evidences associated with the statement
    indicates a direct interatcion then we assume the interaction
    is direct. If there is no evidence for the interaction being indirect
    then we default to direct."""
    any_indirect = False
    for ev in stmt.evidence:
        if ev.epistemics.get('direct') is True:
            return True
        elif ev.epistemics.get('direct') is False:
            any_indirect = True
    if any_indirect:
        return False
    return True


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

    The ".dev0" means dirty.

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


def async_connect(socket):
    """Issues socket connection. And returns a file descriptor.

    * http://uwsgi.readthedocs.io/en/latest/Async.html

    :param str|unicode socket:

    :rtype: int
    """


def mxnlist(m, n):
    """creates a blank nested list of size mxn
    (m rows and n columns)"""
    A = [[[] for _ in range(n)] for __ in range(m)]
    return A


def months_to_seconds(months):
    """Convert months to seconds"""
    return int(months * 2592000.0)


def export_mealy_io(variables, values):
    """
    @rtype: list of dict
    """
    var_list = []
    for ind, variable in enumerate(variables):
        var_dict = {}
        var_dict['name'] = variable
        var_dict['values'] = list(values[ind])
        var_list.append(var_dict)
    return var_list


@classmethod
def new(cls, expression=None, **kwargs):
    """
        Create a :class:`~crython.expression.CronExpression` instance from the given expression string or field values.

        :param expression: (Optional) A string that can be converted to a cron expression.
        :param kwargs: (Optional) A dict that maps field names to values.
        :return: A :class:`~crython.expression.CronExpression` that represents the given string or field values.
        """
    return cls.from_str(expression) if expression else cls.from_kwargs(**kwargs
        )


@staticmethod
def _add_boolean_param_by_name(req_dict, param_name, param_value):
    """
        Adds the specified boolean parameter to the dictionary

        :param req_dict: The dictionary
        :param param_name: The name of the parameter
        :param param_value: The value for the parameter
        :raises ValueError: if the param_value cannot be coerced into a boolean
        """
    if param_value is not None:
        param_value_as_lowercase_string = str(param_value).lower()
        if param_value_as_lowercase_string not in ('true', 'false'):
            raise ValueError('%s must be true or false, found: %s' % (
                param_name, param_value))
        req_dict[param_name] = param_value_as_lowercase_string


def wrap(start: str, string: str, end: str='') ->str:
    """Wrap string inside other strings at start and end.

    If the string is not None or empty, then wrap with start and end, otherwise return
    an empty string.
    """
    return f'{start}{string}{end}' if string else ''


@staticmethod
def transform_category_nans(df):
    """ONLY TRANSFORM: Convert np.NaNs to a category 'NaN'"""
    for column in df.select_dtypes(include=['category']).columns:
        if 'NaN' in df[column].cat.categories:
            df[column].fillna('NaN', inplace=True)


def whitening_zca_cor(array):
    """ Maximizes the average cross-correlation between each dimension of the whitened and original data, and uniquely
    produces a symmetric cross-correlation matrix.
    """
    pass


def abs(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise absolute value of the input.

    Example::

       abs([-2, 0, 3]) = [2, 0, 3]

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

       - abs(default) = default
       - abs(row_sparse) = row_sparse
       - abs(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L721

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

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

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


@classmethod
def _standard_pathway_identifier_filter(cls, pathway_id: str):
    """Get a SQLAlchemy filter for the standard pathway identifier."""
    return cls.pathway_model_identifier_column == pathway_id


def get_supported_projections():
    """
    Get a list of supported projections for creating a Geomap

    ### Returns

    - *list of strings*: list of supported projections
    """
    return ['equal-area', 'lcc', 'mercator', 'stereo']


def application(environ, start_response):
    """Basic WSGI Application"""
    start_response('200 OK', [('Content-type', 'text/plain')])
    return ['Hello World!']


@classmethod
def count(cls, database, bibliography_eid):
    """
        Different to the usual count, it counts the number of documents in a given bibliography.
        """
    query = database.query(cls).filter(cls.bibliography_eid == bibliography_eid
        )
    return query.count()


def solar_geometric_mean_anomaly(julian_century):
    """Returns the Anomaly of Solar Geometric Mean with Julian Century, julian_century."""
    solar_geometric_mean_anomaly = 357.52911 + julian_century * (
        35999.05029 - 0.0001537 * julian_century)
    return solar_geometric_mean_anomaly


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


def __delitem__(key):
    """delete the corresponding key"""


def error_msg_from_exception(e):
    """Translate exception into error message

    Database have different ways to handle exception. This function attempts
    to make sense of the exception object and construct a human readable
    sentence.

    TODO(bkyryliuk): parse the Presto error message from the connection
                     created via create_engine.
    engine = create_engine('presto://localhost:3506/silver') -
      gives an e.message as the str(dict)
    presto.connect('localhost', port=3506, catalog='silver') - as a dict.
    The latter version is parsed correctly by this function.
    """
    msg = ''
    if hasattr(e, 'message'):
        if isinstance(e.message, dict):
            msg = e.message.get('message')
        elif e.message:
            msg = '{}'.format(e.message)
    return msg or '{}'.format(e)


def modified_files(old_tree, new_tree):
    """Return a list of paths in the new tree with modified contents."""
    for f, (op, path), c, v, p, n, (ok, k), e in new_tree.iter_changes(old_tree
        ):
        if c and k == 'file':
            yield str(path)


def walk_line(p0, p1):
    """Returns a generator of points in the line from p0 to p1 such
       that they are connected (in the way they would do to draw a
       line. Order of points is not guaranteed: points may go p0->p1
       or p1->p0. See walk_line_ordered if points must go from p0 to
       p1."""
    x0, y0 = p0
    x1, y1 = p1
    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1
    if x0 > x1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0
    deltax = x1 - x0
    deltay = abs(y1 - y0)
    error = deltax / 2
    y = y0
    ystep = 1 if y0 < y1 else -1
    for x in range(x0, x1 + 1):
        yield (x, y) if not steep else (y, x)
        error = error - deltay
        if error < 0:
            y = y + ystep
            error = error + deltax


def load_handlers(name):
    """Load the (URL pattern, handler) tuples for each component."""
    mod = __import__(name, fromlist=['default_handlers'])
    return mod.default_handlers


def is_blank(text):
    """
    Returns ``True`` if string contains only whitespace characters
    or is empty. Otherwise ``False`` is returned.
    """
    return not text or text.isspace()


def sorted_tuple(m, s):
    """Used as a key for the matches."""
    return tuple(sorted(((s.key, s.Name), (m.key, m.Name))))


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

        :param ShowcaseUntrashedType val:
        :rtype: EventType
        """
    return cls('showcase_untrashed', val)


def hypergeometric_expval(n, m, N):
    """
    Expected value of hypergeometric distribution.
    """
    return 1.0 * n * m / N


@classmethod
def register_handler(cls, handler, method='GET', headers=None):
    """
        Register a handler within a given method, the default method is get.
        The data structure used to store the handler is a dictionary of arrays, each array
        entry contains the handler tuple (path, callable). It looks like this:
            {"GET": ("/profile", profileHandler), ("/settings", settingsHandler)}
        The registered handler should return 2 values, the response body and status code.
        """
    if not hasattr(cls, 'handlers'):
        cls.handlers = {method: [{'handler': handler, 'headers': headers}]}
    elif method in cls.handlers.keys():
        cls.handlers[method].append({'handler': handler, 'headers': headers})
    else:
        cls.handlers[method] = [{'handler': handler, 'headers': headers}]


@classmethod
def _get_attribute_mapper_attr_names(cls):
    """
        get the attr names defined by the attribute mappers
        """
    names = []
    for mapper in cls._get_attribute_mappers():
        names.append(mapper.get_attr_name())
    return names


def kebab_to_underscore(s):
    """
    Convert kebab-styled-string to underscore_styled_string
    :param s:
    :return:
    """
    return s.replace('-', '_')


def isoformat(dt):
    """Return iso-formatted timestamp

    Like .isoformat(), but uses Z for UTC instead of +00:00
    """
    return dt.isoformat().replace('+00:00', 'Z')


def getImages():
    """ All Images inside of the Product
        """


def _point(p):
    """Default B{C{point}} callable for function L{hausdorff_}.

       @arg p: The original C{model} or C{target} point (C{any}).

       @return: The point, suitable for the L{hausdorff_}
                B{C{distance}} callable.
    """
    return p


def add_dependencies(targets, deps, order=None):
    """ Add dependent formats and optionally put into right build order. """
    for target, deps in deps.items():
        if target in targets:
            targets = list(set(targets).union(deps))
    if order:
        return list(filter(targets.__contains__, order))
    return targets


def get_labels_ablog(l, a, b):
    """Get all combinations ij, where i,j are feature labels.

    Parameters
    ----------
    a : float
    b : float

    Returns
    -------
    new_features : list
        List of new feature names.
    """
    L = len(l)
    new_features = []
    for f1 in range(L):
        for f2 in range(f1, L):
            new_features.append('log' + str(a) + '_' + l[f1] + 'log' + str(
                b) + '_' + l[f2])
    return new_features


def identity(x):
    """
    Helper function which returns its argument unchanged.
    That is, `identity(x)` returns `x` for any input `x`.
    """
    return x


def t_HEXA(t):
    """([0-9][0-9a-fA-F]*[hH])|(\\$[0-9a-fA-F]+)|(0x[0-9a-fA-F]+)"""
    if t.value[0] == '$':
        t.value = t.value[1:]
    elif t.value[:2] == '0x':
        t.value = t.value[2:]
    else:
        t.value = t.value[:-1]
    t.value = int(t.value, 16)
    t.type = 'NUMBER'
    return t


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

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

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


def sorted_by_field(issues, field='closed_at', reverse=False):
    """Return a list of issues sorted by closing date date."""
    return sorted(issues, key=lambda i: i[field], reverse=reverse)


def is_ipv6(address_string):
    """Checks if a string is an IPv6 address or prefix"""
    return ':' in address_string


def getDefaultTraversal(request, ob):
    """Get the default published object for the request

        Allows a default view to be added to traversal.
        Returns (ob, steps_reversed).
        """


def is_reply(tweet):
    """ Assume a tweet is a reply if in_reply_to_screen_name
    or in_reply_to_status_id are not None

    """
    return tweet.get('in_reply_to_screen_name') or tweet.get(
        'in_reply_to_status_id')


def _Mul(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
    """Multiplies arguments element-wise.

    The storage type of ``elemwise_mul`` output depends on storage types of inputs

       - elemwise_mul(default, default) = default
       - elemwise_mul(row_sparse, row_sparse) = row_sparse
       - elemwise_mul(default, row_sparse) = row_sparse
       - elemwise_mul(row_sparse, default) = row_sparse
       - elemwise_mul(csr, csr) = csr
       - otherwise, ``elemwise_mul`` generates output with default storage

    Parameters
    ----------
    lhs : Symbol
        first input
    rhs : Symbol
        second input

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

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


def select(extend: bool=False, deselect: bool=False, toggle: bool=False,
    location: float=(0.0, 0.0)):
    """Select spline points

    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    :param deselect: Deselect, Remove from selection
    :type deselect: bool
    :param toggle: Toggle Selection, Toggle the selection
    :type toggle: bool
    :param location: Location, Location of vertex in normalized space
    :type location: float
    """
    pass


def asunicode(s):
    """Turns bytes into unicode, if needed.

    Uses UTF-8.
    """
    if isinstance(s, bytes):
        return s.decode('utf-8', 'replace')
    else:
        return s


def rho(flag, S, K, t, r, sigma, b, pricing_function):
    """Calculate option rho using numerical integration.

    :param S: underlying asset price
    :type S: float
    :param K: strike price
    :type K: float
    :param sigma: annualized standard deviation, or volatility
    :type sigma: float
    :param t: time to expiration in years
    :type t: float
    :param r: risk-free interest rate
    :type r: float
    :param b: see above
    :type b: float
    :param flag: 'c' or 'p' for call or put.
    :type flag: str
    :param pricing_function: any function returning the price of an option
    :type pricing_function: python function object
    """
    return (pricing_function(flag, S, K, t, r + 0.01, sigma, b + 0.01) -
        pricing_function(flag, S, K, t, r - 0.01, sigma, b - 0.01)) / 2.0


def parseServerPort():
    """
    Bring a server port number from pylatte_config.xml
    """
    from xml.dom.minidom import parse
    doc = parse('pylatte_config.xml')
    tags = doc.getElementsByTagName('pylatte-server')
    for item in tags:
        for item1 in item.childNodes:
            if item1.nodeName == 'port':
                return int(item1.firstChild.nodeValue)
    pass


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


def uround(value):
    """Returns a string representation of a value with an uncertainity which
    has been rounded to significant digits based on the uncertainty value.

    Parameters
    ----------
    value : ufloat
        A single ufloat.

    Returns
    -------
    s : string
        A rounded string representation of `value`.

    2.4563752289999+/-0.0003797273827

    becomes

    2.4564+/-0.0004

    This probably doesn't work for weird cases like large uncertainties.

    """
    try:
        nom = value.nominal_value
    except AttributeError:
        s = str(value)
    else:
        uncert = value.std_dev
        if abs(nom) < 1e-15:
            s = '0.0+/-0.0'
        else:
            s = '%.14f' % uncert
            for j, number in enumerate(s):
                if number == '0' or number == '.':
                    pass
                else:
                    digit = j
                    break
            newUncert = round(uncert, digit - 1)
            newUncertStr = ('%.' + str(digit - 1) + 'f') % newUncert
            newNom = round(nom, len(newUncertStr) - 2)
            newNomStr = ('%.' + str(digit - 1) + 'f') % newNom
            diff = len(newUncertStr) - len(newNomStr)
            if diff > 0:
                s = newNomStr + int(diff) * '0' + '+/-' + newUncertStr
            else:
                s = newNomStr + '+/-' + newUncertStr
    return s


def siteswap_char_to_int(char):
    """ Converts a siteswap character to a digit """
    if not isinstance(char, str):
        raise ValueError("Invalid SiteSwap character: '{}'".format(char))
    if len(char) != 1:
        raise ValueError('Invalid SiteSwap character, too many characters')
    try:
        return int(char.lower(), 36)
    except ValueError:
        raise ValueError("Invalid SiteSwap character: '{}'".format(char))


def define_attrs(required, extra=[]):
    """Create __slots__ by adding extra attributes to required ones"""
    slots = tuple(required + extra)
    attributes = tuple(required)
    return slots, attributes


def direct_children(obj):
    """Returns direct subcategory objects of obj."""


def openForWriting():
    """
        Return a file object for writing.
        """


def thumbnails(html):
    """
    Given a HTML string, converts paths in img tags to thumbnail
    paths, using wenlincms's ``thumbnail`` template tag. Used as
    one of the default values in the ``RICHTEXT_FILTERS`` setting.
    """
    from django.conf import settings
    from bs4 import BeautifulSoup
    from wenlincms.core.templatetags.wenlincms_tags import thumbnail
    if settings.MEDIA_URL.lower() not in html.lower():
        return html
    dom = BeautifulSoup(html, 'html.parser')
    for img in dom.findAll('img'):
        src = img.get('src', '')
        src_in_media = src.lower().startswith(settings.MEDIA_URL.lower())
        width = img.get('width')
        height = img.get('height')
        if src_in_media and width and height:
            img['src'] = settings.MEDIA_URL + thumbnail(src, width, height)
    return str(dom)


def htrc_load_metadata_86():
    """
    Loads hathitrust metadata for the 86 volumes.
    """
    import os
    import json
    filename = 'vsm-data/htrc-anthropomorphism-86-metadata.json'
    with open(filename) as f:
        metadata = json.load(f)
    return metadata


@classmethod
def mount_action(cls, drive: 'Drive', daemon_controller: 'Controller') ->None:
    """
        Perform the mount action.

        In this case, do absolutely nothing.
        """
    pass


def image_statistics(image, calibration, result=None):
    """
    Adds some numeric image parameters (i.e. size) to the results.

    :param image:
    :param calibration:
    :param result:
    :return:

    >>> sorted(image_statistics(np.array([[0, 0, 0],
    ...                                   [0, 0, 0],
    ...                                   [0, 0, 0]]), calibration=15.0).items())
    [('area', 2025.0), ('area_pixel', 9), ('input_height', 45.0), ('input_height_pixel', 3), ('input_width', 45.0), ('input_width_pixel', 3)]
    """
    return {'input_width': image.shape[1] * calibration, 'input_height':
        image.shape[0] * calibration, 'input_width_pixel': image.shape[1],
        'input_height_pixel': image.shape[0], 'area': image.shape[1] *
        calibration * image.shape[0] * calibration, 'area_pixel': image.
        shape[1] * image.shape[0]}


def almost_equal_floats(value_1: float, value_2: float, *, delta: float=1e-08
    ) ->bool:
    """
    Return True if two floats are almost equal
    """
    return abs(value_1 - value_2) <= delta


def guide_rotate(increment: bool=True, angle: float=0.0):
    """Rotate guide angle

    :param increment: Increment, Increment angle
    :type increment: bool
    :param angle: Angle, Guide angle
    :type angle: float
    """
    pass


def feet_to_meters(feet: float) ->float:
    """ Convert feet to meters.

    :param feet: a measurement in feet.
    :returns: measurement in meters
    """
    return feet / 0.3048


@classmethod
def metadata(cls, sobject):
    """
        Extract the metadata from a suds object.
        @param sobject: A suds object
        @type sobject: L{Object}
        @return: The object's metadata
        @rtype: L{sudsobject.Metadata}
        """
    return sobject.__metadata__


@classmethod
def create_explorer(cls, *args, **kwargs):
    """
        Creates and shows and ObjectExplorer window.

        The *args and **kwargs will be passed to the ObjectExplorer constructor

        A (class attribute) reference to the browser window is kept to prevent
        it from being garbage-collected.
        """
    object_explorer = cls(*args, **kwargs)
    object_explorer.exec_()
    return object_explorer


def binary_column_as_bytes(db_column_data):
    """
        Turn *db_column_data* into a `bytes` object.

        Use this when the specific type must be known,
        for example to prefix or suffix additional byte values
        like that produced by `p64`.
        """


def get_bases_composition(seq):
    """
    Proportion of A,T,G,C bases in a sequence
    """
    seq = seq.lower()
    n_A = seq.count('a')
    n_T = seq.count('t')
    n_G = seq.count('g')
    n_C = seq.count('c')
    return {'A': n_A, 'T': n_T, 'G': n_G, 'C': n_C}


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

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

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


def string_like(s):
    """
    Return True if s operates like a string.
    """
    try:
        s + ''
    except Exception:
        return False
    return True


def F_calc(TP, FP, FN, beta):
    """
    Calculate F-score.

    :param TP: true positive
    :type TP : int
    :param FP: false positive
    :type FP : int
    :param FN: false negative
    :type FN : int
    :param beta : beta coefficient
    :type beta : float
    :return: F score as float
    """
    try:
        result = (1 + beta ** 2) * TP / ((1 + beta ** 2) * TP + FP + beta **
            2 * FN)
        return result
    except (ZeroDivisionError, TypeError):
        return 'None'


def broadcast_minus(lhs=None, rhs=None, name=None, attr=None, out=None, **
    kwargs):
    """Returns element-wise difference of the input arrays with broadcasting.

    `broadcast_minus` is an alias to the function `broadcast_sub`.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_sub(x, y) = [[ 1.,  1.,  1.],
                              [ 0.,  0.,  0.]]

       broadcast_minus(x, y) = [[ 1.,  1.,  1.],
                                [ 0.,  0.,  0.]]

    Supported sparse operations:

       broadcast_sub/minus(csr, dense(1D)) = dense
       broadcast_sub/minus(dense(1D), csr) = dense

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L106

    Parameters
    ----------
    lhs : Symbol
        First input to the function
    rhs : Symbol
        Second input to the function

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

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


def get_request_meta(request, key):
    """
    Given a key, it returns a cleaned up version of the value from request.META, or None
    """
    value = request.META.get(key, request.META.get(key.replace('_', '-'), '')
        ).strip()
    if value == '':
        return None
    return value


@staticmethod
def convert(obj, unit, axis):
    """
        convert obj using unit for the specified axis.  If obj is a sequence,
        return the converted sequence.  The output must be a sequence of scalars
        that can be used by the numpy array layer
        """
    return obj


@classmethod
def from_json(cls, json):
    """Builds a QuickReplyPayload object from JSON provided by the API.

        Args:
            json: A dict containing the JSON representation that is converted
                  into the QuickAttachment object.

        Returns:
            A QuickReplyPayload object.

        """
    return cls(json['payload'])


def postprocessor(path, key, value):
    """Convert key names to something bigquery-compatible, so it is
    possible to import the JSON into bigquery tables.

    """
    if key.startswith('#') or key.startswith('@'):
        key = key[1:]
    if key == 'clinical_results':
        value = {'truncated_by_postprocessor': True}
    return key, value


def unhat(A):
    """Inverts the hat-map """
    import numpy as np
    return np.array([-A[1, 2], A[0, 2], -A[0, 1]])


def time_info(cli):
    """Return time/timezone info by running 'date' command"""
    return cli.exec_command('date\n')


def describe_hosts(HostIds=None, NextToken=None, MaxResults=None, Filters=None
    ):
    """
    Describes one or more of your Dedicated Hosts.
    The results describe only the Dedicated Hosts in the region you're currently using. All listed instances consume capacity on your Dedicated Host. Dedicated Hosts that have recently been released will be listed with the state released .
    See also: AWS API Documentation

    :example: response = client.describe_hosts(
        HostIds=[
            'string',
        ],
        NextToken='string',
        MaxResults=123,
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ]
    )

    :type HostIds: list
    :param HostIds: The IDs of the Dedicated Hosts. The IDs are used for targeted instance launches.
            (string) --

    :type NextToken: string
    :param NextToken: The token to retrieve the next page of results.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500; if maxResults is given a larger value than 500, you will receive an error. You cannot specify this parameter and the host IDs parameter in the same request.

    :type Filters: list
    :param Filters: One or more filters.
            instance-type - The instance type size that the Dedicated Host is configured to support.
            auto-placement - Whether auto-placement is enabled or disabled (on | off ).
            host-reservation-id - The ID of the reservation assigned to this host.
            client-token - The idempotency token you provided when you launched the instance
            state - The allocation state of the Dedicated Host (available | under-assessment | permanent-failure | released | released-permanent-failure ).
            availability-zone - The Availability Zone of the host.
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :rtype: dict
    :return: {
        'Hosts': [
            {
                'HostId': 'string',
                'AutoPlacement': 'on'|'off',
                'HostReservationId': 'string',
                'ClientToken': 'string',
                'HostProperties': {
                    'Sockets': 123,
                    'Cores': 123,
                    'TotalVCpus': 123,
                    'InstanceType': 'string'
                },
                'State': 'available'|'under-assessment'|'permanent-failure'|'released'|'released-permanent-failure',
                'AvailabilityZone': 'string',
                'Instances': [
                    {
                        'InstanceId': 'string',
                        'InstanceType': 'string'
                    },
                ],
                'AvailableCapacity': {
                    'AvailableInstanceCapacity': [
                        {
                            'InstanceType': 'string',
                            'AvailableCapacity': 123,
                            'TotalCapacity': 123
                        },
                    ],
                    'AvailableVCpus': 123
                }
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def print_setup_instructions():
    """
    Prints the setup instructions for the .pgpass file required to access wrds via python.
    """
    print(
        """To build a connection to the wrds server via python, a .pgpass file is required in the user's home
directory, with access limited to the user.
To create this file, follow the instructions here:
https://wrds-www.wharton.upenn.edu/pages/support/programming-wrds/programming-python/python-from-your-computer/
After creating the file, don't forget to run "chmod 0600 ~/.pgpass" in the console to limit access.
Access issue also described here:
https://www.postgresql.org/docs/9.5/libpq-pgpass.html"""
        )


def delete_marker():
    """Delete marker for current frame from selected tracks

    """
    pass


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


def _get_plot_breaks(granularity, only_last):
    """
    Generates the breaks used in plotting

      granularity : string
        the supported granularity value
      only_last : True | False
        indicates whether only the last day or hour is returned and to be plotted
    """
    if granularity == 'day':
        breaks = 3 * 12
    elif only_last == 'day':
        breaks = 12
    else:
        breaks = 3
    return breaks