def describe_policies(AutoScalingGroupName=None, PolicyNames=None,
    PolicyTypes=None, NextToken=None, MaxRecords=None):
    """
    Describes the policies for the specified Auto Scaling group.
    See also: AWS API Documentation

    Examples
    This example describes the policies for the specified Auto Scaling group.
    Expected Output:

    :example: response = client.describe_policies(
        AutoScalingGroupName='string',
        PolicyNames=[
            'string',
        ],
        PolicyTypes=[
            'string',
        ],
        NextToken='string',
        MaxRecords=123
    )

    :type AutoScalingGroupName: string
    :param AutoScalingGroupName: The name of the group.

    :type PolicyNames: list
    :param PolicyNames: One or more policy names or policy ARNs to be described. If you omit this parameter, all policy names are described. If an group name is provided, the results are limited to that group. This list is limited to 50 items. If you specify an unknown policy name, it is ignored with no error.
            (string) --

    :type PolicyTypes: list
    :param PolicyTypes: One or more policy types. Valid values are SimpleScaling and StepScaling .
            (string) --

    :type NextToken: string
    :param NextToken: The token for the next set of items to return. (You received this token from a previous call.)

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of items to be returned with each call. The default value is 50 and the maximum value is 100.

    :rtype: dict
    :return: {
        'ScalingPolicies': [
            {
                'AutoScalingGroupName': 'string',
                'PolicyName': 'string',
                'PolicyARN': 'string',
                'PolicyType': 'string',
                'AdjustmentType': 'string',
                'MinAdjustmentStep': 123,
                'MinAdjustmentMagnitude': 123,
                'ScalingAdjustment': 123,
                'Cooldown': 123,
                'StepAdjustments': [
                    {
                        'MetricIntervalLowerBound': 123.0,
                        'MetricIntervalUpperBound': 123.0,
                        'ScalingAdjustment': 123
                    },
                ],
                'MetricAggregationType': 'string',
                'EstimatedInstanceWarmup': 123,
                'Alarms': [
                    {
                        'AlarmName': 'string',
                        'AlarmARN': 'string'
                    },
                ]
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    If you want the adjustment to be triggered when the metric is greater than or equal to 50 and less than 60, specify a lower bound of 0 and an upper bound of 10.
    If you want the adjustment to be triggered when the metric is greater than 40 and less than or equal to 50, specify a lower bound of -10 and an upper bound of 0.

    """
    pass


def entries(ol):
    """
        from elist.elist import *
        ol = ['a','b','c']
        rslt = entries(ol)
        rslt
    """
    rslt = []
    length = ol.__len__()
    for i in range(0, length):
        entry = [i, ol[i]]
        rslt.append(entry)
    return rslt


def line_break(length=10, symbol='-'):
    """Insert a line break"""
    return '\n{}\n\n'.format(symbol * length)


def find_litho_markers(tokens, regex):
    """Find lithology lithology terms that match a regular expression

    Args:
        tokens (iterable of str): the list of tokenised sentences.
        regex (regex): compiles regular expression  e.g. re.compile('sand|clay')

    Returns:
        (list of str): tokens found to be matching the expression
    """
    return list(filter(regex.search, tokens))


def get_github_website():
    """Get the URL for the GitHub project."""
    return 'https://github.com/cloudsmith-io/cloudsmith-cli'


def linalg_slogdet(A=None, out=None, name=None, **kwargs):
    """Compute the sign and log of the determinant of a matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* is a square matrix. We compute:

      *sign* = *sign(det(A))*
      *logabsdet* = *log(abs(det(A)))*

    If *n>2*, *slogdet* is performed separately on the trailing two dimensions
    for all inputs (batch mode).

    .. note:: The operator supports float32 and float64 data types only.
    .. note:: The gradient is not properly defined on sign, so the gradient of
              it is not backwarded.
    .. note:: No gradient is backwarded when A is non-invertible. Please see
              the docs of operator det for detail.

    Examples::

       Single matrix signed log determinant
       A = [[2., 3.], [1., 4.]]
       sign, logabsdet = slogdet(A)
       sign = [1.]
       logabsdet = [1.609438]

       Batch matrix signed log determinant
       A = [[[2., 3.], [1., 4.]],
            [[1., 2.], [2., 4.]],
            [[1., 2.], [4., 3.]]]
       sign, logabsdet = slogdet(A)
       sign = [1., 0., -1.]
       logabsdet = [1.609438, -inf, 1.609438]

    Defined in src/operator/tensor/la_op.cc:L1031

    Parameters
    ----------
    A : NDArray
        Tensor of square matrix

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def convertFilterTypeToOperator(filterType):
    """
        convertFilterTypeToOperator - Converts a filter type to a SQL operator

          @param filterType <str> - A filter type ( likely following "__" such as "fieldName__eq" would be "eq" )

          @reurn <str> - Matching SQL operator
    """
    ft = filterType.lower()
    if not ft or ft in ('eq', '='):
        return '='
    elif ft in ('ne', '!=', '<>'):
        return '<>'
    elif ft in 'gt>':
        return '>'
    elif ft in ('gte', 'ge', '>='):
        return '>='
    elif ft in ('lt', '<'):
        return '<'
    elif ft in ('lte', 'le', '<='):
        return '<='
    elif ft in ('in', 'isin', 'is in', 'is_in'):
        return 'in'
    elif ft in ('notin', 'not_in', 'not in'):
        return 'not in'
    elif ft in ('like',):
        return 'like'
    elif ft in ('notlike', 'not_like', 'not like'):
        return 'not like'
    elif ft in ('is',):
        return 'is'
    elif ft in ('isnot', 'is_not', 'is not'):
        return 'is not'
    elif ft == 'between':
        return 'between'
    raise ValueError('Unknown filter type: %s' % (repr(filterType),))


@classmethod
def fetch(cls, client, _id):
    """
        fetch by instrument id
        """
    return cls.fetch_list(client, [_id])[0]


def __check_integer(items):
    """Checks a list of strings whether items are valid integers.

    Args:
        items (list of [str,]): The list of items to test.

    Returns:
        list of [int,]: The list of items converted to integers. Returns None
            if any one test fails.
    """
    for i, item in enumerate(items):
        if '.' in item:
            print('Failed on item: "{}"'.format(item))
            return None
        try:
            items[i] = int(item)
        except ValueError:
            print('Failed on item: "{}"'.format(item))
            return None
    return items


@classmethod
def raise_if_needed(cls, response):
    """Raise exception if response contains error."""
    if response.status_code >= 400:
        raise cls(response)


def load_properties(file_path):
    """
    Read properties file into map.
    """
    props = {}
    with open(file_path, 'rt') as f:
        for line in f:
            line = line.strip()
            if not line.startswith('#'):
                pair = line.split('=', 1)
                if len(pair) > 1:
                    key = pair[0].strip()
                    props[key] = pair[1].strip()
    return props


@classmethod
def pull(cls, src=None):
    """
        hace pull a un repositorio

        Parameters
        ==========
        src: string
            ruta del repositorio que se quiere hacer pull
        """
    repo = cls.repo(src)
    repo.remote().pull()


def slogdet(A=None, name=None, attr=None, out=None, **kwargs):
    """Compute the sign and log of the determinant of a matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* is a square matrix. We compute:

      *sign* = *sign(det(A))*
      *logabsdet* = *log(abs(det(A)))*

    If *n>2*, *slogdet* is performed separately on the trailing two dimensions
    for all inputs (batch mode).

    .. note:: The operator supports float32 and float64 data types only.
    .. note:: The gradient is not properly defined on sign, so the gradient of
              it is not backwarded.
    .. note:: No gradient is backwarded when A is non-invertible. Please see
              the docs of operator det for detail.

    Examples::

       Single matrix signed log determinant
       A = [[2., 3.], [1., 4.]]
       sign, logabsdet = slogdet(A)
       sign = [1.]
       logabsdet = [1.609438]

       Batch matrix signed log determinant
       A = [[[2., 3.], [1., 4.]],
            [[1., 2.], [2., 4.]],
            [[1., 2.], [4., 3.]]]
       sign, logabsdet = slogdet(A)
       sign = [1., 0., -1.]
       logabsdet = [1.609438, -inf, 1.609438]

    Defined in src/operator/tensor/la_op.cc:L1031

    Parameters
    ----------
    A : Symbol
        Tensor of square matrix

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

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


def view_selected():
    """Zoom the sequencer on the selected strips

    """
    pass


@classmethod
def get_fields(cls):
    """
        Get table fields

        :return: fields
        :rtype list|tuple|set
        """
    return {}


def vaccine(y, x, N, beta, gamma, nu):
    """
    Defines the SIR vaccine model.

    :param array y: Individuals at time step x
    :param array x: Time step
    :param int N: Population
    :param float beta: The parameter controlling how often a susceptible-infected contact results in a new infection.
    :param float gamma: The rate an infected recovers and moves into the resistant phase.
    :param float nu: The rate at which susceptible become vaccinated.

    :returns: S, I, R at time step n
    :rtype: tuple(int/float, int/float, int/float)
    """
    S = -beta * y[0] * y[1] / N - nu * y[0]
    I = beta * y[0] * y[1] / N - gamma * y[1]
    R = gamma * y[1] + nu * y[2]
    return S, I, R


def get(name, context=None, **kws):
    """Find the named template for the given context.

        This search for a named template using a stacked strategy.  If the
        template has been registered for the given context in the template
        manager, that template is used.  If not, a file system based template
        is used as a fallback.  If nothing can be found, the empty string is
        returned.

        Use the ``ITemplateManager`` to set specific template locations.  The
        fallbacks all use the ``mailman:`` scheme to use in-tree defaults.

        :param name: The name of the template to find.
        :type name: str
        :param context: The context in which to find the template.  This can
            be either an IMailingList, an IDomain, or None for the global/site
            context.  The template will be searched in order from most
            specific to least specific, i.e. from list-id, to domain, to
            global.
        :type context: IMailingList, IDomain, None
        :param kws: Additional URL substitution variables.  Once a URL for the
            given name and context is identified, these are used to fill in
            placeholders in the URL before the template is retrieved.
            `list_id`, `list_name`, and `mail_host` will automatically be
            filled in if available depending on the `context`.  This
            dictionary is passed directly to the underlying
            ``ITemplatemanager.get()`` call.
        :type kws: dict
        :return: The found template or its fallback.
        :rtype: str
        """


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


def is_client_error(code):
    """Checks if response code has client error."""
    return 400 <= code <= 499


def show_warning(message):
    """Show warning using Tkinter if available"""
    try:
        import Tkinter, tkMessageBox
        root = Tkinter.Tk()
        root.withdraw()
        tkMessageBox.showerror('Spyder', message)
    except ImportError:
        pass
    raise RuntimeError(message)


def color_delete():
    """Remove active color from palette

    """
    pass


def __setitem__(name, object):
    """ add imapperattributeitem object """


def reindex(report):
    """Reindex report so that 'TOTAL' is the last row"""
    index = list(report.index)
    i = index.index('TOTAL')
    return report.reindex(index[:i] + index[i + 1:] + ['TOTAL'])


def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule
    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        try:
            import_module('%s.models_init' % app)
        except:
            if module_has_submodule(mod, 'models_init'):
                raise


@classmethod
def black(cls, string, auto=False):
    """Color-code entire string.

        :param str string: String to colorize.
        :param bool auto: Enable auto-color (dark/light terminal).

        :return: Class instance for colorized string.
        :rtype: Color
        """
    return cls.colorize('black', string, auto=auto)


def reform_uid(uid):
    """
    Convert a uid with underscores to the original format
    """
    return uid[:3] + '://' + '/'.join(uid[6:].split('_'))


def render():
    """Return the template with the option 'menus'"""


def view_ndof():
    """Use a 3D mouse device to pan/zoom the view

    """
    pass


def convertbits(data, frombits, tobits, pad=True):
    """General power-of-2 base conversion."""
    acc = 0
    bits = 0
    ret = []
    maxv = (1 << tobits) - 1
    max_acc = (1 << frombits + tobits - 1) - 1
    for value in data:
        if value < 0 or value >> frombits:
            return None
        acc = (acc << frombits | value) & max_acc
        bits += frombits
        while bits >= tobits:
            bits -= tobits
            ret.append(acc >> bits & maxv)
    if pad:
        if bits:
            ret.append(acc << tobits - bits & maxv)
    elif bits >= frombits or acc << tobits - bits & maxv:
        return None
    return ret


@staticmethod
def mimetype():
    """Return most common media type for format."""
    return 'text/csv'


@classmethod
def put(cls, obj):
    """A factory classmethod to format a given object.

        Args:
            obj: An object.

        Returns:
            A `RemotePartitions` object.
        """
    return cls(obj)


def lesser(attrs, inputs, proto_obj):
    """Logical Lesser operator with broadcasting."""
    return 'broadcast_lesser', attrs, inputs


@classmethod
def RegisterDecoders(cls, decoders):
    """Registers decoders.

    The decoders are identified based on their lower case encoding method.

    Args:
      decoders (list[type]): decoder classes.

    Raises:
      KeyError: if decoders is already set for the corresponding
          encoding method.
    """
    for decoder in decoders:
        cls.RegisterDecoder(decoder)


@classmethod
def exactly_half_floor(cls, variables):
    """Clauses encoding a "exactly half" constraint (rounded down)

        Parameters
        ----------
        variables : list of variables
           variables in the constraint

        Returns
        -------
            a list of clauses
        """
    threshold = int(len(variables) / 2)
    return cls.equal_to_constraint(variables, threshold)


@classmethod
def via_tcpip(cls, hostname, port, name=None, **kwargs):
    """Return a Driver with an underlying TCP Instrument resource.

        Parameters
        ----------
        hostname :
            The ip address or hostname of the instrument.
        port :
            the port of the instrument.
        name :
            Unique name given within Lantz to the instrument for logging purposes.
            Defaults to one generated based on the class name if not provided.
        kwargs :
            keyword arguments passed to the Resource constructor on initialize.
        **kwargs :

        Returns
        -------

        """
    resource_name = 'TCPIP::%s::%s::INSTR' % (hostname, port)
    return cls(resource_name, name, **kwargs)


def broadcast_logical_and(lhs=None, rhs=None, name=None, attr=None, out=
    None, **kwargs):
    """Returns the result of element-wise **logical and** with broadcasting.

    Example::

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

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

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

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L154

    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 toggle_bit(vector, position, value):
    """
    Set value of a bit in a proper position.

    >>> toggle_bit(0, 0, False)
    0
    >>> toggle_bit(0, 0, True)
    1
    >>> toggle_bit(1, 0, False)
    0
    >>> toggle_bit(1, 0, True)
    1
    >>> toggle_bit(5, 2, False)
    1
    """
    mask = 1 << position
    if value:
        vector |= mask
    else:
        vector &= ~mask
    return vector


@staticmethod
def scope(goal_name, task_name):
    """Returns options scope for specified task in specified goal.

        :API: public
        """
    return goal_name if goal_name == task_name else '{0}.{1}'.format(goal_name,
        task_name)


def provider_parser(subparser):
    """Configure provider parser for internetbs"""
    subparser.add_argument('--auth-key', help=
        'specify API key for authentication')
    subparser.add_argument('--auth-password', help=
        'specify password for authentication')


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

        :param DeviceApprovalsRemoveExceptionDetails val:
        :rtype: EventDetails
        """
    return cls('device_approvals_remove_exception_details', val)


def write_findings(method, lead_space, address, pc, at_init=''):
    """
    Writes contract address and EVM program counter indicating whether counter was read at constructor
    :param method: pointer to the object with the write method
    :param lead_space: leading white space
    :param address: contract address
    :param pc: program counter
    :param at_init: Boolean
    :return: pass
    """
    method.write(f'{lead_space}Contract: {address:#x}')
    method.write(
        f"""{lead_space}EVM Program counter: {pc:#x}{' (at constructor)' if at_init else ''}
"""
        )


def _truncate_seq_pair(tokens_a, tokens_b, max_length):
    """Truncates a sequence pair in place to the maximum length."""
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_length:
            break
        if len(tokens_a) > len(tokens_b):
            tokens_a.pop()
        else:
            tokens_b.pop()


@classmethod
def drop(cls, db):
    """
        Drop table in database.

        :param obj db: DatabaseManager.
        :return: cls object.
        """
    cls.__table__.drop(db.engine)
    return cls


@staticmethod
def _cleaned(line):
    """Remove 'forbidden' characters from the line"""
    if set(line) == set("'"):
        line = ''
    return line.replace('"', '').replace('(', '').replace(')', '').strip()


def __init__(model, name, parent):
    """Name and parent are used to hook the correct application hierarchy.
        """


def psi_H_CO3_HSO4_HMW84(T, P):
    """c-a-a': hydrogen carbonate bisulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def __sub__(other):
    """Either a DateTime or a number may be subtracted from a
        DateTime, however, a DateTime may not be subtracted from a
        number."""


def backimage_move():
    """Move Node backdrop

    """
    pass


def expandPrefix(prefix):
    """Expand prefix string by adding a trailing period if needed.

    expandPrefix(p) should be used instead of p+'.' in most contexts.
    """
    if prefix and not prefix.endswith('.'):
        return prefix + '.'
    return prefix


@classmethod
def registeredConverters(cls):
    """Return an iterator over the converters registered in 'cls', in
        reversed order of registration."""
    return reversed(cls._converters)


def build_relabel_dict(x):
    """Relabel the input ids to continuous ids that starts from zero.

    The new id follows the order of the given node id list.

    Parameters
    ----------
    x : list
      The input ids.

    Returns
    -------
    relabel_dict : dict
      Dict from old id to new id.
    """
    relabel_dict = {}
    for i, v in enumerate(x):
        relabel_dict[v] = i
    return relabel_dict


@classmethod
def _timedelta_to_seconds(cls, td):
    """
        Converts a 'datetime.timedelta' object `td` into seconds contained in
        the duration.
        Note: We cannot use `timedelta.total_seconds()` because this is not
        supported by Python 2.6.
        """
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6
        ) / 10 ** 6


@staticmethod
def _calc_cost(distance, line_cost=3667, tie_in_cost=0,
    transmission_multiplier=1):
    """
        Compute transmission cost in $/MW

        Parameters
        ----------
        distance : float
            Distance to feature in miles
        line_cost : float
            Cost of tranmission lines in $/MW-mile
        tie_in_cost : float
            Cost to connect to feature in $/MW
        line_multiplier : float
            Multiplier for region specific line cost increases

        Returns
        -------
        cost : float
            Cost of transmission in $/MW
        """
    cost = distance * line_cost * transmission_multiplier + tie_in_cost
    return cost


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


def models_dict_to_list(models):
    """
    Given a models dict containing subapp names as keys and models as a list of values
    return an aggregated list of all models
    """
    all_models = []
    if isinstance(models, dict):
        for _, app_models in list(models.items()):
            all_models.extend(app_models)
    else:
        all_models = models
    return all_models


@staticmethod
def _construct_values_list(values):
    """
        This values_list is a strange construction, because of ini format.
        We need to extract the values with the following supported format:

            >>> key = value0
            ...     value1
            ...
            ...     # Comment line here
            ...     value2

        given that normally, either value0 is supplied, or (value1, value2),
        but still allowing for all three at once.

        Furthermore, with the configparser, we will get a list of values,
        and intermediate blank lines, but no comments. This means that we can't
        merely use the count of values' items to heuristically "skip ahead" lines,
        because we still have to manually parse through this.

        Therefore, we construct the values_list in the following fashion:
            1. Keep the first value (in the example, this is `value0`)
            2. For all other values, ignore blank lines.
        Then, we can parse through, and look for values only.
        """
    lines = values.splitlines()
    values_list = lines[:1]
    values_list.extend(filter(None, lines[1:]))
    return values_list


def strip_log(string):
    """Strips string from slack marks and leading/trailing spaces"""
    if string.endswith('**'):
        string = string[:-2]
    return string.strip()


def tokenizer(fmt):
    """
    Split a format into a series of tokens, adding parens for optional values.

    For example,
      '%(%H:%)%?%M %!Z%?'
    will become
      '%(', '%H', ':', '%)', '%?', '%M', ' ', '%(', '%!Z', '%)', '%?'
    """
    i = 0
    n = len(fmt)
    while i < n:
        j = i + 1
        if fmt[i] == '%':
            j += 1
            if j > n:
                raise ValueError('Incomplete token - nothing follows %')
            if fmt[j - 1] == '!':
                j += 1
                if j > n:
                    raise ValueError('Incomplete token - nothing follows %!')
        optional = j + 1 < n and fmt[j:j + 2] == '%?'
        single = fmt[i:j] != '%)'
        if optional and single:
            yield '%('
        yield fmt[i:j]
        if optional:
            if single:
                yield '%)'
            yield '%?'
            j += 2
        i = j


def largest_quantity(q1, q2):
    """
    This function finds the maximum of two quantities of any class.
    This is done by trying it's level best compare them and if it fails it
    returns the string "Some"
    """
    if q1 is None:
        return q2
    if q2 is None:
        return q1
    try:
        return max(q1, q2)
    except BaseException:
        pass
    try:
        return max(q2, q1)
    except BaseException:
        pass
    try:
        return max(q1, type(q1)(q2))
    except BaseException:
        pass
    try:
        return max(q2, type(q2)(q1))
    except BaseException:
        return 'Some'


@classmethod
def _read_txt(cls, input_file):
    """Reads a tab separated value file."""
    with open(input_file, 'r') as f:
        reader = f.readlines()
        lines = []
        for line in reader:
            lines.append(line.strip().split('_!_'))
        return lines


def item(data, feed=None, service=None):
    """
    Format an text section page for a feed subscription using data found in
    its Opml feed entry and in its Rss file.

    @param data: Opml data
    @type data: dict
    @param feed: Rss data. Default dict.
    @type feed: dict
    @param service: Intialized soovee.regex object. Default None.
    @type service: obj
    @return:
    @rtype: basestring
    @raise TypeError: data or feed passed was not a dict
    """
    if not isinstance(data, dict) and not isinstance(feed, dict):
        raise TypeError('FormsItem missing dictionaries.')
    from soovee_lib.txtwrap import wraptext
    page = ['=' * 80, '\n'.join(wraptext('FEED TITLE: %s' % service.
        PRETITLE.sub('', data['title']))), '\n'.join(wraptext(
        'FEED PAGE: %s ' % data['htmlUrl'])), '\n'.join(wraptext(service.
        DELHTML.sub('', data['description'])))]
    for episode in feed['eps']:
        audiofile = '%s (%.2f MB)' % (episode['enclosure']['url'], service.
            TOMB(episode['enclosure']['length']))
        subpage = ['-' * 80, '\n'.join(wraptext('EPISODE TITLE: %s' %
            episode['title'], 4)), '\n'.join(wraptext('EPISODE AUTHOR: %s' %
            episode['itunes:author'], 4)), '\n'.join(wraptext(
            'EPISODE CATEGORY: %s' % episode['category'], 4)), '\n'.join(
            wraptext('EPISODE AUDIOFILE: %s' % audiofile, 4)), '\n'.join(
            wraptext(service.PREEPISODE.sub('', episode['description']), 4))]
        page.append('\n'.join(subpage))
    return '\n'.join(page)


def get_parent_projects_df(project_details_df):
    """
    Get details for projects that have an associated child project.
    :param DataFrame project_details_df: the details for all projects
    :return DataFrame: parent_projects_df
    """
    parent_projects_df = project_details_df[project_details_df[
        'source_project_parent_id'].isna()]
    return parent_projects_df


def section_break(qty: int=2) ->str:
    """Return multiple line break characters.

    :param int qty: number of line break characters (default: 2)
    :returns: multiple new line characters
    :rtype: str
    """
    return '\n' * int(qty)


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


@classmethod
def clear_instance(cls):
    """unset _instance for this class and singleton parents.
        """
    if not cls.initialized():
        return
    for subclass in cls._walk_mro():
        if isinstance(subclass._instance, cls):
            subclass._instance = None


def dumps(obj):
    """
    Dump an nginx configuration to a string.

    :param obj obj: nginx object (Conf, Server, Container)
    :returns: nginx configuration as string
    """
    return ''.join(obj.as_strings)


def unmap(widget):
    """Unmap a mapped WIDGET."""
    result = False
    if widget and widget.winfo_exists() and widget.winfo_ismapped():
        result = True
        geom_mgr = widget.winfo_manager()
        if geom_mgr == 'grid':
            widget.grid_forget()
        elif geom_mgr == 'pack':
            widget.pack_forget()
        elif geom_mgr == 'place':
            widget.place_forget()
        else:
            result = False
    return result


def assert_variable_type(variable, expected_type, raise_exception=True):
    """Return True if a variable is of a certain type or types.
    Otherwise raise a ValueError exception.

    Positional arguments:
    variable -- the variable to be checked
    expected_type -- the expected type or types of the variable
    raise_exception -- whether to raise an exception or just return
                        False on failure, with error message
    """
    if not isinstance(expected_type, list):
        expected_type = [expected_type]
    for t in expected_type:
        if not isinstance(t, type):
            raise ValueError('expected_type argument "%s" is not a type' %
                str(t))
    if not isinstance(raise_exception, bool):
        raise ValueError('raise_exception argument "%s" is not a bool' %
            str(raise_exception))
    if not len([t for t in expected_type if isinstance(variable, t)]):
        error_message = (
            '"%s" is not an instance of type %s. It is of type %s' % (str(
            variable), ' or '.join([str(t) for t in expected_type]), str(
            type(variable))))
        if raise_exception:
            raise ValueError(error_message)
        else:
            return False, error_message
    return True, None


def majority(*args):
    """
    Evaluate majority function on arbitrary number of inputs.

    :param args: tuple of Boolean inputs
    :return: [bool] value of majority function
    """
    return sum(args) > len(args) / 2


def drop_zero(n):
    """
    Drop trailing 0s
    For example:
    10.100 -> 10.1
    """
    n = str(n)
    return n.rstrip('0').rstrip('.') if '.' in n else n


def create_address(email, display_name=None):
    """Create and return an address unlinked to any user.

        :param email: The text email address for the address being created.
        :type email: str
        :param display_name: The display name associated with the address.
        :type display_name: str
        :return: The newly created address object, with the given email
            address and display name, if given.
        :rtype: `IAddress`
        :raises ExistingAddressError: when the email address is already
            registered.
        """


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 _is_scan_complete(hdr):
    """ Checks if the scan is complete ('stop' document exists)

    Parameters
    ----------

    hdr : databroker.core.Header
        header of the run
        hdr = db[scan_id]
        The header must be reloaded each time before the function is called.

    Returns
    -------

    True: scan is complete
    False: scan is incomplete (still running)
    """
    return bool(hdr.stop)


@classmethod
def all(klass):
    """
        Get all instances of the given class in the database.  Note that this is the
        equivalent of calling L{find} with no arguments.

        @return: A C{Deferred} which returns the following to a callback:
        A C{list} containing all of the instances in the database.
        """
    return klass.find()


@staticmethod
def merge_nodes(G, nodes, new_node, **attr):
    """
        Merges the selected `nodes` of the graph G into one `new_node`,
        meaning that all the edges that pointed to or from one of these
        `nodes` will point to or from the `new_node`.
        attr_dict and `**attr` are defined as in `G.add_node`.
        """
    G.add_node(new_node, **attr)
    newG = G.copy()
    for n1, n2, data in newG.edges(data=True):
        if n1 in nodes:
            G.add_edge(new_node, n2, **data)
        elif n2 in nodes:
            G.add_edge(n1, new_node, **data)
    for n in nodes:
        G.remove_node(n)


def plural(length, label, suffix='s'):
    """Return a label with an optional plural suffix"""
    return '%d %s%s' % (length, label, suffix if length != 1 else '')


@classmethod
def sort(cls, tokens):
    """
        Return a new sorted sequence of tokens given a sequence of tokens. The
        primary sort is on start and the secondary sort is on longer lengths.
        Therefore if two tokens have the same start, the longer token will sort
        first.

        For example:
        >>> tokens = [Token(0, 0), Token(5, 5), Token(1, 1), Token(2, 4), Token(2, 5)]
        >>> expected = [Token(0, 0), Token(1, 1), Token(2, 5), Token(2, 4), Token(5, 5)]
        >>> expected == Token.sort(tokens)
        True
        """
    key = lambda s: (s.start, -len(s))
    return sorted(tokens, key=key)


@staticmethod
def turn_to_time(time):
    """ Takes miliseconds
        and returns "hours:minutes:seconds.centiseconds"
        with padding (:02 means pad with 0s if it's less than 2 digits)"""
    time = time // 10
    b = time // 100 // 60
    return f'{b // 60}:{b % 60:02}:{time // 100 % 60:02}.{time % 100:02}'


def Assert_Intesection():
    """
    Check that there is an intersection between pairs of lists in Series raise exception if not all row has intersection
    """
    pass


def list_identity_pool_usage(NextToken=None, MaxResults=None):
    """
    Gets a list of identity pools registered with Cognito.
    ListIdentityPool can only be called with developer credentials. You cannot make this API call with the temporary user credentials provided by Cognito Identity.
    See also: AWS API Documentation

    :example: response = client.list_identity_pool_usage(
        NextToken='string',
        MaxResults=123
    )

    :type NextToken: string
    :param NextToken: A pagination token for obtaining the next page of results.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to be returned.

    :rtype: dict
    :return: {
        'IdentityPoolUsages': [
            {
                'IdentityPoolId': 'string',
                'SyncSessionsCount': 123,
                'DataStorage': 123,
                'LastModifiedDate': datetime(2015, 1, 1)
            },
        ],
        'MaxResults': 123,
        'Count': 123,
        'NextToken': 'string'
    }

    :returns:
    (dict) -- Returned for a successful ListIdentityPoolUsage request.
    IdentityPoolUsages (list) -- Usage information for the identity pools.
    (dict) -- Usage information for the identity pool.
    IdentityPoolId (string) -- A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
    SyncSessionsCount (integer) -- Number of sync sessions for the identity pool.
    DataStorage (integer) -- Data storage information for the identity pool.
    LastModifiedDate (datetime) -- Date on which the identity pool was last modified.

    MaxResults (integer) -- The maximum number of results to be returned.
    Count (integer) -- Total number of identities for the identity pool.
    NextToken (string) -- A pagination token for obtaining the next page of results.

    """
    pass


def paste():
    """Paste text from clipboard

    """
    pass


def standard_param_name(name):
    """Convert parameter name to namespace format"""
    return name.lstrip('/').lstrip('-').replace('-', '_')


def get_invalidation(DistributionId=None, Id=None):
    """
    Get the information about an invalidation.
    See also: AWS API Documentation

    :example: response = client.get_invalidation(
        DistributionId='string',
        Id='string'
    )

    :type DistributionId: string
    :param DistributionId: [REQUIRED]
            The distribution's ID.

    :type Id: string
    :param Id: [REQUIRED]
            The identifier for the invalidation request, for example, IDFDVBD632BHDS5 .

    :rtype: dict
    :return: {
        'Invalidation': {
            'Id': 'string',
            'Status': 'string',
            'CreateTime': datetime(2015, 1, 1),
            'InvalidationBatch': {
                'Paths': {
                    'Quantity': 123,
                    'Items': [
                        'string',
                    ]
                },
                'CallerReference': 'string'
            }
        }
    }

    :returns:
    (string) --

    """
    pass


def maybe_unwrap_results(results):
    """
    Gets raw results back from wrapped results.

    Can be used in plotting functions or other post-estimation type
    routines.
    """
    return getattr(results, '_results', results)


@classmethod
def increase(cls):
    """Increase indentation level by one."""
    cls.level += 1
    cls.set_format()


def filter_absent(record_stream):
    """Adapt a record stream to remove absent records."""
    for record in record_stream:
        if record.storage_kind != 'absent':
            yield record


def moses(pred, seq):
    """
    return two iterators: filter(pred, seq), filter(not pred, seq)

    Example
    ~~~~~~~

    >>> moses(lambda x:x > 5, range(10))
    ([6, 7, 8, 9], [0, 1, 2, 3, 4, 5])
    """
    trueitems = []
    falseitems = []
    for x in seq:
        if pred(x):
            trueitems.append(x)
        else:
            falseitems.append(x)
    return trueitems, falseitems


def mean(iterable):
    """Returns the arithmetic mean of the given list of values.

    For example: mean([1,2,3,4]) = 10/4 = 2.5.

    """
    a = iterable if isinstance(iterable, list) else list(iterable)
    return float(sum(a)) / (len(a) or 1)


@staticmethod
def is_not_certain(fragment, certainty_threshold):
    """State if a fragment has been assigned with sufficient certainty

        Parameters
        ----------
        fragment : Fragment object
            Collection of images related to the same individual
        certainty_threshold : float
            Lower boundary in [0,1] for the certainty of a fragment

        Returns
        -------
        is_not_certain_flag : bool
            True if the fragment is assigned with high enough certainty

        """
    return fragment.certainty < certainty_threshold


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

        :param DeviceApprovalsChangeMobilePolicyType val:
        :rtype: EventType
        """
    return cls('device_approvals_change_mobile_policy', val)


def entries(daterange=None, ticket=None, milestone=None, project=None,
    client=None):
    """ Returns a list of non repeating time entries to cover the provided date range,
            optionally only for a given ticket, milestone, project or client
        """


@staticmethod
def wb_error_log(*params):
    """
        接受不定个数的参数, 并print出来
        """
    print('\x1b[1;31;40m')
    print('*' * 50)
    print('\x1b[7;31m{}\x1b[1;31;40m'.format('###wb-error-log: '))
    print('', end='')
    for param in params:
        print('\x1b[7;31m{}\x1b[1;31;40m'.format(param), end='')
    print()
    print('*' * 50)
    print('\x1b[0m')


def outline_int(text):
    """parses text value from outline to an int value.

    Args:
        text:
    """
    return int(text)


def set_config(config):
    """Set ISparcAppConfiguration for current runtime configuration settings

        Args:
            config: ISparcAppConfiguration provider
        """


def bisect_left(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e < x, and all e in
    a[i:] have e >= x.  So if x already appears in the list, a.insert(x) will
    insert just before the leftmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo


@classmethod
def get_language_code(cls, code, language_format=None):
    """Do any possible formatting needed for language code."""
    if not language_format:
        language_format = cls.language_format
    return getattr(cls, 'get_language_{}'.format(language_format))(code)


@staticmethod
def write_file(data, path):
    """
        Save the output data to the file system at the specified path.

        :param data: a byte string of data to write to disk
        :param path: the path to write the file to
        """
    with open(path, 'wb+') as out_file:
        out_file.write(data)


@classmethod
def get_cache(cls):
    """Get a reference to the class-global results cache"""
    return cls._dCache


def check_categories(lines):
    """
  find out how many row and col categories are available
  """
    rcat_line = lines[0].split('\t')
    num_rc = 0
    found_end = False
    for inst_string in rcat_line[1:]:
        if inst_string == '':
            if found_end is False:
                num_rc = num_rc + 1
        else:
            found_end = True
    max_rcat = 15
    if max_rcat > len(lines):
        max_rcat = len(lines) - 1
    num_cc = 0
    for i in range(max_rcat):
        ccat_line = lines[i + 1].split('\t')
        if ccat_line[0] == '' and len(ccat_line) > 1:
            num_cc = num_cc + 1
    num_labels = {}
    num_labels['row'] = num_rc + 1
    num_labels['col'] = num_cc + 1
    return num_labels


@classmethod
def controlName(cls):
    """Returns control name, needs to be implemented by subclasses."""
    raise NotImplementedError('Method not implemented for class %s', (cls.
        __name__,))


def hasMultValuesPerItem(listOfD):
    """returns true if the dictionary has a list with more than one element"""
    if len(listOfD) > 1:
        return True
    for d in listOfD:
        for value in d.values():
            if len(value) > 1:
                return True
    return False


def dosage_from_probs(homo_probs, hetero_probs, scale=2):
    """Computes dosage from probability matrix (for the minor allele).

    Args:
        homo_probs (numpy.array): the probabilities for the homozygous genotype
        hetero_probs (numpy.array): the probabilities for the heterozygous
                                    genotype
        scale (int): the scale value

    Returns:
        numpy.array: the dosage computed from the probabilities

    """
    return (homo_probs + hetero_probs / 2) * scale


def iter_high(hub, high):
    """
    Take a highstate strucutre and iterate over it yielding the elements down to the
    execution args
    Yields (id_, body, state, run, arg)
    """
    for id_, body in high.items():
        if not isinstance(body, dict):
            continue
        for state, run in body.items():
            if state.startswith('__'):
                continue
            for arg in run:
                yield id_, body, state, run, arg


@classmethod
def get_key_fully_qualified_name(cls, schema_fully_qualified_name: str) ->str:
    """
        Get the key name given the schema name.

        :param schema_fully_qualified_name: Fully qualified name of the schema
        :return: The key fully qualified name
        """
    return '.'.join(schema_fully_qualified_name.split('.')[:-1] + ['Key'])


def fireSystemEvent(eventType):
    """
        Fire a system-wide event.

        System-wide events are things like 'startup', 'shutdown', and
        'persist'.
        """


def prepare(obj, app_metadata=None, sys_metadata={}):
    """Prepares saving and registering of versionable aspects.

        The archivist decides which aspects of the objects are prepared
        to be saved and which not.

        Doesn't do any save operation, just returns information
        to allow recursively save the object.

        Returns an 'IPreparedObject' object.
        """


def clean_fullname(val):
    """Remove special characters from user full name."""
    if not val:
        return val
    val = val.strip()
    for i in range(32):
        val = val.replace(chr(i), '')
    return val


def _format_jid(local=None, domain=None, resource=None):
    """Format the given JID components into a full or bare JID.

    :param string local: Optional. The local portion of the JID.
    :param string domain: Required. The domain name portion of the JID.
    :param strin resource: Optional. The resource portion of the JID.

    :return: A full or bare JID string.
    """
    result = []
    if local:
        result.append(local)
        result.append('@')
    if domain:
        result.append(domain)
    if resource:
        result.append('/')
        result.append(resource)
    return ''.join(result)


def world_remove():
    """Remove Rigid Body simulation world from the current scene

    """
    pass


def readLink(segments):
    """
        Return the value of link at `segments'.
        """


def tar_entry_size(filesize):
    """Get the space a file of the given size will actually require in a TAR.

    The entry has a 512-byte header followd by the actual file data,
    padded to a multiple of 512 bytes if necessary.

    Args:
      filesize (int): File size in bytes

    Returns:
      int: Bytes consumed in a TAR archive by this file.

    Examples:
      ::

        >>> tar_entry_size(1)
        1024
        >>> tar_entry_size(511)
        1024
        >>> tar_entry_size(512)
        1024
        >>> tar_entry_size(513)
        1536
    """
    return 512 + filesize + (512 - filesize) % 512


def close_parallel_region():
    """Closes a parallel region

    This is a clean solution without having to explicitely invoke Manager
    and DistributedConfiguration class

    """
    from .managers import Manager
    dc = Manager().get_DistributedConfiguration()
    if dc.rank != 0:
        Manager().log_conf.verbosity += 2
        Manager().log_conf.fverbosity += 2


def add():
    """ Returns an integer to be added to the sorting
        """


def provides(varmap):
    """Return a minimal ``provides`` list from the setup vars.
    """
    try:
        return ['{} ({})'.format(varmap['name'], varmap['version'])]
    except KeyError:
        return [varmap['name']]


def _are_bounds_contained_by_dataset(dataset, bounds):
    """Check if a Dataset fully contains a bounds.

    :param bounds: The Bounds object to check.
    :type bounds: Bounds
    :param dataset: The Dataset that should be fully contain the
        Bounds
    :type dataset: Dataset

    :returns: True if the Bounds are contained by the Dataset, Raises
        a ValueError otherwise
    """
    lat_min, lat_max, lon_min, lon_max = dataset.spatial_boundaries()
    start, end = dataset.temporal_boundaries()
    errors = []
    if lat_min > bounds.lat_max:
        error = (
            'bounds.lat_max: %s is not between lat_min: %s and lat_max: %s' %
            (bounds.lat_max, lat_min, lat_max))
        errors.append(error)
    if lon_min > bounds.lon_max:
        error = (
            'bounds.lon_max: %s is not between lon_min: %s and lon_max: %s' %
            (bounds.lon_max, lon_min, lon_max))
        errors.append(error)
    if not bounds.start is None:
        if not start <= bounds.start <= end:
            error = 'bounds.start: %s is not between start: %s and end: %s' % (
                bounds.start, start, end)
            errors.append(error)
    if not bounds.end is None:
        if not start <= bounds.end <= end:
            error = 'bounds.end: %s is not between start: %s and end: %s' % (
                bounds.end, start, end)
            errors.append(error)
    if len(errors) == 0:
        return True
    else:
        error_message = '\n'.join(errors)
        raise ValueError(error_message)


def dicttotext(d, sort=False, max=0):
    """Function for converting dictionary to plaintext output, optionally with some (reverse) sorting"""
    if sort:
        f = lambda x: sorted(x, key=lambda y: -1 * y[1])
    else:
        f = lambda x: x
    output = ''
    for i, (key, value) in enumerate(f(d.items())):
        output += key + '\t' + str(value) + '\n'
        if max != 0 and i >= max:
            break
    return output


def _fragmentation(data_size, disk_size):
    """Think of the fragmentation metric is that it's
    a measure of the % of the database or view that's used
    to store old documents and their associated metadata.

    See
    https://wiki.apache.org/couchdb/Compaction
    and
    http://docs.couchdb.org/en/latest/config/compaction.html#compaction-daemon-rules
    for details on fragmentation calculation.
    """
    if data_size is None or disk_size is None:
        return None
    fragmentation = (disk_size - float(data_size)) / disk_size * 100.0
    return int(round(fragmentation, 0))


def get_ngram_pos(toks, key_indx):
    """
        Given ngram: 'convention center'

            found at index: 13
            in this sentence: at the brown convention center
            sentence toks: ['at', the', 'brown', 'convention', 'center']

        The purpose of this function is to return sentence toks index: 3
    """
    offset = 0
    for i in range(len(toks)):
        if offset == key_indx:
            return i
        offset += len(toks[i]) + 1
    return -1


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

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


def find_subsequence(iterable, predicate):
    """
    find the subsequence in iterable which predicted return true

    for example:
    >>> find_subsequence([1, 10, 2, 3, 5, 8, 9],  lambda x: x in [1, 0, 2, 3, 4, 5, 8, 9])
    [[1], [2, 3, 5, 8, 9]]

    >>> find_subsequence([1, 10, 2, 3, 5, 8, 9],  lambda x: x not in [1, 0, 2, 3, 4, 5, 8, 9])
    [[10]]

    """
    seqs = []
    seq = []
    continuous = False
    for i in iterable:
        if predicate(i):
            if continuous:
                seq.append(i)
            else:
                seq = [i]
                continuous = True
        elif continuous:
            seqs.append(seq)
            seq = []
            continuous = False
    if len(seq):
        seqs.append(seq)
    return seqs


def add(message):
    """ Add message to context. """


@staticmethod
def can_flash(target):
    """
        Check if target should be flashed using this flasher.
        :param target: target board
        :return: boolean
        """
    raise NotImplementedError


def chunks(l, n):
    """ split successive n-sized chunks from a list."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def _band_shortname(long_name):
    """Get short band name, e.g. `Near Infrared (NIR)` becomes `nir` and
    `Red` becomes `red`.
    """
    if '(' in long_name:
        start = long_name.find('(') + 1
        end = long_name.find(')')
        short_name = long_name[start:end]
    else:
        short_name = long_name.replace(' ', '_').replace('-', '_')
    return short_name.lower()


def p_class_name_constant(p):
    """class_name_constant : class_name DOUBLE_COLON CLASS"""
    p[0] = p[1]


@staticmethod
def size():
    """Return network size."""
    return 1


def _n_action_handler(event):
    """Default handler for when an N-ACTION request is received.

    See _handlers.doc_handle_action for detailed documentation.
    """
    raise NotImplementedError("No handler has been bound to 'evt.EVT_N_ACTION'"
        )


def version(cls):
    """Retourne la version de la classe"""
    return cls._version


def check_shape(tensors, shapes):
    """
    Verifies the tensors match the given shape, will raise an error if the shapes do not match

    :param tensors: ([TensorFlow Tensor]) The tensors that should be checked
    :param shapes: ([list]) The list of shapes for each tensor
    """
    i = 0
    for tensor, shape in zip(tensors, shapes):
        assert tensor.get_shape().as_list() == shape, 'id ' + str(i
            ) + ' shape ' + str(tensor.get_shape()) + str(shape)
        i += 1


def de_select_first():
    """(De)select first of visible part of each NURBS

    """
    pass


def map_vector(x, raster, **kvars):
    """
    Create new GeoRaster, which has its data replaced by x
    Useful to map output of PySal analyses, e.g. spatial autocorrelation values, etc.

    Usage: raster2 = map_vector(x, raster)
    where
        raster: GeoRaster
        x: Numpy array of data with same length as non-missing values in raster,
           i.e., len(x) == np.sum(raster.mask==False)
    """
    y = raster.copy()
    y.raster[y.raster.mask == False] = x
    return y


def get_raw_data_from_file(imageset, i):
    """Use cbflib_adaptbx directly to access the raw data array rather than
    through the imageset, in order to work for multi-panel detectors and other
    situations where the format class modifies the raw array"""
    from cbflib_adaptbx import uncompress
    import binascii
    file_name = imageset.get_image_identifier(i)
    with open(file_name, 'rb') as cbf:
        data = cbf.read()
    start_tag = binascii.unhexlify('0c1a04d5')
    data_offset = data.find(start_tag) + 4
    cbf_header = data[:data_offset - 4]
    fast = slow = length = 0
    for record in cbf_header.split('\n'):
        if 'X-Binary-Size-Fastest-Dimension' in record:
            fast = int(record.split()[-1])
        elif 'X-Binary-Size-Second-Dimension' in record:
            slow = int(record.split()[-1])
        elif 'X-Binary-Size:' in record:
            xbsize_record = record
            length = int(record.split()[-1])
    values = uncompress(packed=data[data_offset:data_offset + length], fast
        =fast, slow=slow)
    return values,


def sample(size: int=1):
    """Use mouse to sample a color in current image

    :param size: Sample Size
    :type size: int
    """
    pass


def merge_featurecollection(*jsons):
    """
    merge features into one featurecollection

    Keyword arguments:
    jsons   -- jsons object list

    return geojson featurecollection
    """
    features = []
    for json in jsons:
        if json['type'] == 'FeatureCollection':
            for feature in json['features']:
                features.append(feature)
    return {'type': 'FeatureCollection', 'features': features}


def _get_tests():
    """Enables ``python setup.py test``."""
    import doctest
    return doctest.DocTestSuite(optionflags=doctest.ELLIPSIS)


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 libsolv_formatted_evr(epoch, version, release):
    """Create an epoch-version-release string from the separate values.

    Pulp stores epoch-version-release separately, libsolv uses them together.
    Convert from Pulp separate values to a combined EVR formatted as libsolv expects.
    """
    if version is None:
        return None
    return '{}{}{}'.format('{}:'.format(epoch) if epoch else '', version,
        '-{}'.format(release) if release else '')


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 connect_segmentation(connect, list_connections):
    """
    connect label like:
    connect = {             connect = {
        1: {2,3,4}              1 : {2,3,4,5,6,7,8,9}
        2: {5,6}        =>  }
        3: {7,8,9}
    }
    @param connect : dict contain all pixels label and sprite's label that key belong to
    @param list_key_connect : list contain all key label in dict connect
    """
    for x in reversed(list_connections):
        count = 0
        try:
            connect[x] = list(set(connect[x]))
            while count < len(connect[x]):
                connect[x] += connect[connect[x][count]]
                connect[x] = list(set(connect[x]))
                count += 1
        except IndexError:
            continue


def basis_function_ders(degree, knot_vector, span, knot, order):
    """ Computes derivatives of the basis functions for a single parameter.

    Implementation of Algorithm A2.3 from The NURBS Book by Piegl & Tiller.

    :param degree: degree, :math:`p`
    :type degree: int
    :param knot_vector: knot vector, :math:`U`
    :type knot_vector: list, tuple
    :param span: knot span, :math:`i`
    :type span: int
    :param knot: knot or parameter, :math:`u`
    :type knot: float
    :param order: order of the derivative
    :type order: int
    :return: derivatives of the basis functions
    :rtype: list
    """
    left = [(1.0) for _ in range(degree + 1)]
    right = [(1.0) for _ in range(degree + 1)]
    ndu = [[(1.0) for _ in range(degree + 1)] for _ in range(degree + 1)]
    for j in range(1, degree + 1):
        left[j] = knot - knot_vector[span + 1 - j]
        right[j] = knot_vector[span + j] - knot
        saved = 0.0
        r = 0
        for r in range(r, j):
            ndu[j][r] = right[r + 1] + left[j - r]
            temp = ndu[r][j - 1] / ndu[j][r]
            ndu[r][j] = saved + right[r + 1] * temp
            saved = left[j - r] * temp
        ndu[j][j] = saved
    ders = [[(0.0) for _ in range(degree + 1)] for _ in range(min(degree,
        order) + 1)]
    for j in range(0, degree + 1):
        ders[0][j] = ndu[j][degree]
    a = [[(1.0) for _ in range(degree + 1)] for _ in range(2)]
    for r in range(0, degree + 1):
        s1 = 0
        s2 = 1
        a[0][0] = 1.0
        for k in range(1, order + 1):
            d = 0.0
            rk = r - k
            pk = degree - k
            if r >= k:
                a[s2][0] = a[s1][0] / ndu[pk + 1][rk]
                d = a[s2][0] * ndu[rk][pk]
            if rk >= -1:
                j1 = 1
            else:
                j1 = -rk
            if r - 1 <= pk:
                j2 = k - 1
            else:
                j2 = degree - r
            for j in range(j1, j2 + 1):
                a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j]
                d += a[s2][j] * ndu[rk + j][pk]
            if r <= pk:
                a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r]
                d += a[s2][k] * ndu[r][pk]
            ders[k][r] = d
            j = s1
            s1 = s2
            s2 = j
    r = float(degree)
    for k in range(1, order + 1):
        for j in range(0, degree + 1):
            ders[k][j] *= r
        r *= degree - k
    return ders


def greyOut(checkBox, items, checked=True):
    """
    greyOut makes items unavailable for the user by greying them out
    """
    if type(checkBox).__name__ == 'QCheckBox':
        if checkBox.isChecked():
            for item in items:
                item.setDisabled(not checked)
        else:
            for item in items:
                item.setDisabled(checked)
    elif type(checkBox).__name__ == 'QPushButton':
        for item in items:
            item.setDisabled(not checked)


def p_argument_list(p):
    """argument_list : func_arg
                     | argument_list "," func_arg """
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1] + [p[3]]


def validate_page_nbr(arg: str) ->int:
    """
    Validates a page number, returns as int. Raises ValueError if bad.
    """
    try:
        num = int(arg)
    except ValueError:
        raise ValueError('txtv <PAGE>\nexample: txtv 130')
    if num < 100 or num > 999:
        raise ValueError('Text tv pages range from 100 to 999')
    return num


@staticmethod
def get_url(fmt='json'):
    """
        Get the URLs used to push the configuration to the APIC
        if no format parameter is specified, the format will be 'json'
        otherwise it will return '/api/mo/uni.' with the format string
        appended.

        :param fmt: optional format string, default is 'json'
        :returns: URL string
        """
    return '/api/mo/uni/fabric.' + fmt, '/api/mo/uni.' + fmt


def normalize(points):
    """ Normalize a collection of points in
	homogeneous coordinates so that last row = 1. """
    for row in points:
        row /= points[-1]
    return points


def dsndate_fmt(datetime):
    """ Converts a datetime object to a DSN time format.
    Given the following time object time(2017, 11, 3, 9) will return the
    following string: D171103 """
    return f"D{datetime.strftime('%y%m%d')}"


def isfloat(x):
    """Is the input a float or a string that can be converted to float?"""
    try:
        float(x)
        return True
    except ValueError:
        return False


def _get_old_package_revision_license_ids(migrate_engine):
    """Returns a dict of old license ids, keyed by package_revision id."""
    old_ids = {}
    select_licenses = 'SELECT id, license_id FROM package_revision;'
    q = migrate_engine.execute(select_licenses)
    for id, license_id in q:
        old_ids[id] = license_id
    return old_ids


@classmethod
def from_edges(cls, edges, **kwargs):
    """Generate an axis object from a sequence of bin edges.

        This method should be used to construct an axis where the bin
        edges should lie at specific values (e.g. a histogram).  The
        number of bins will be one less than the number of edges.

        Parameters
        ----------
        edges : `~numpy.ndarray`
            Axis bin edges.
        interp : {'lin', 'log', 'sqrt'}
            Interpolation method used to transform between axis and pixel
            coordinates.  Default: 'lin'.
        """
    if len(edges) < 2:
        raise ValueError('Edges array must have at least two elements.')
    return cls(edges, node_type='edges', **kwargs)


def multiply():
    """
    Example code, multiplying two numbers.

    This is expected to be run from the command line, as it reads
    ``sys.argv``.

    Usage::

      ./code.py in_file out_file

    Reads input from ``in_file`` (``sys.argv[1]``) (e.g.: {"x1": 2, "x2": 4})
    Writes product to ``out_file`` (``sys.argv[2]``) (e.g.: {"product": 8})

    Note for developers:

    * This would be replaced by a python wrapper around your code.
    * This code will be executed on the computer you specify.
    """
    import json
    import sys
    in_file = sys.argv[1]
    out_file = sys.argv[2]
    with open(in_file) as f:
        in_dict = json.load(f)
    out_dict = {'product': in_dict['x1'] * in_dict['x2']}
    with open(out_file, 'w') as f:
        json.dump(out_dict, f)
    print('Exiting multiply code.')


def new():
    """Add new particle settings

    """
    pass


def tagref(row, args):
    """A single tag pattern standing alone.
    @param row: the HXL data row
    @param args: the arguments parsed
    """
    return row.get(args[0])


def increase_time_resolution_of_regular_cumulative_data(dict_info, start_lo,
    end_lo, time_delta_lo, time_delta_hi):
    """ Use the low resolution to create the high resolution """
    my_dt_lo = start_lo
    divisor, remainder = divmod(int(time_delta_lo.total_seconds()), int(
        time_delta_hi.total_seconds()))
    if remainder != 0:
        raise Exception(
            'Increase Resolution: Time Deltas are not multiples of each other.'
            )
    elif divisor < 1:
        raise Exception(
            'Increase Resolution: Low resolution lower than higher resolution {} < {}.'
            .format(time_delta_lo, time_delta_hi))
    new_dict_info = dict()
    while start_lo <= my_dt_lo and my_dt_lo <= end_lo:
        my_value = dict_info[my_dt_lo]
        my_portion = my_value / divisor
        for my_sub_step in range(0, -divisor, -1):
            new_dict_info[my_dt_lo + my_sub_step * time_delta_hi] = my_portion
        my_dt_lo += time_delta_lo
    return new_dict_info


@classmethod
def autoconfigure(cls, conf, autoconfigure_prefix):
    """
        Called with a :class:`.ConfigRegistry`, the result of this method must
        be either a new instance of this class, or :any:`None`. This method
        is automatically called during the autoconfigure phase.
        """
    raise NotImplementedError('This method must be implemented')


def get_p2p(type_, data):
    """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n1306

    Positional arguments:
    type_ -- corresponding `ieprinters` dictionary key for the instance.
    data -- bytearray data to read.
    """
    raise NotImplementedError


def get_by_list_id(list_id):
    """Return the mailing list with the given list id, if it exists.

        :param list_id: The List-ID
        :type list_id: str
        :return: the matching mailing list or None if no matching list is
            found.
        :rtype: IMailingList
        """


def get_member_hp(checks, member_uuid, pool_uuid):
    """Helper function to find a members health in a given pool

    :param checks list: https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Pool/#healthMonitor
    :param member_uuid: server UUID we are looking for
    :param pool_uuid: Connection pool uuid to search for
    """
    status = '---'
    for check in checks:
        if check.get('poolUuid') == pool_uuid:
            for hp_member in check.get('membersHealth'):
                if hp_member.get('uuid') == member_uuid:
                    status = hp_member.get('status')
    return status


def linprog_terse_callback(res):
    """
    A sample callback function demonstrating the linprog callback interface.
    This callback produces brief output to sys.stdout before each iteration
    and after the final iteration of the simplex algorithm.

    Parameters
    ----------
    res : A `scipy.optimize.OptimizeResult` consisting of the following fields:

        x : 1D array
            The independent variable vector which optimizes the linear
            programming problem.
        fun : float
            Value of the objective function.
        success : bool
            True if the algorithm succeeded in finding an optimal solution.
        slack : 1D array
            The values of the slack variables. Each slack variable corresponds
            to an inequality constraint. If the slack is zero, then the
            corresponding constraint is active.
        con : 1D array
            The (nominally zero) residuals of the equality constraints, that is,
            ``b - A_eq @ x``.
        phase : int
            The phase of the optimization being executed. In phase 1 a basic
            feasible solution is sought and the T has an additional row
            representing an alternate objective function.
        status : int
            An integer representing the exit status of the optimization::

                 0 : Optimization terminated successfully
                 1 : Iteration limit reached
                 2 : Problem appears to be infeasible
                 3 : Problem appears to be unbounded
                 4 : Serious numerical difficulties encountered

        nit : int
            The number of iterations performed.
        message : str
            A string descriptor of the exit status of the optimization.
    """
    nit = res['nit']
    x = res['x']
    if nit == 0:
        print('Iter:   X:')
    print('{0: <5d}   '.format(nit), end='')
    print(x)


@classmethod
def from_line(cls, line, user=None, cron=None):
    """Generate CronItem from a cron-line and parse out command and comment"""
    obj = cls(user=user, cron=cron)
    obj.parse(line.strip())
    return obj


def reductions(seq, func, start=0):
    """
    return an iterator of the partial values of the reduction.
    the last value is always equal to reduce(func, seq, start)
    """
    out = start
    it = iter(seq)
    while True:
        try:
            yield out
            out = func(out, next(it))
        except StopIteration:
            raise StopIteration


def substraction(first, second):
    """Substraction operation

    :param first: first operator
    :param second: second operator

    Returns:
        The result of a substraction operation
    """
    return first - second


@staticmethod
def set_next(next_node):
    """Set the next node"""
    raise ValueError('Cannot declare nodes after a scanner!')


def rebase(prices, base=100.0):
    """
    Rebase all series to a given intial base.
    This makes comparing/plotting different series together easier.
    Args:
        * prices: Expects a price series/dataframe
        * base (number): starting value for all series.
    """
    return prices.dropna() / prices.dropna().iloc[0] * base


@classmethod
def delete(cls, param=None, **kwargs):
    """Bind middleware's method as DELETE endpoint.
        """
    return cls.bind(param, methods=['DELETE'], **kwargs)


def record_responses_for_decorator(function_return, function_args, store=store
    ):
    """ Create and store mock function responses from real responses and store them by function argument tuples.

        To be called from inside decorator
    """
    print('Recording response function "%s"' % function_args[0])
    store_key = store.hash_args(function_args)
    store.update(store_key, function_return)
    return function_return


def match_movie_length():
    """Set image’s user’s length to the one of this video

    """
    pass


@classmethod
def disable_dynamic_config(cls):
    """
        Disables dynamic log level configuration in the running system.
        """
    cls._enabled = False


@staticmethod
def remove(layer, select):
    """Delete selection (list of ids) of units from parameter arrays. """
    layer['bias'] = layer['bias'][0, [select]]
    layer['lvar'] = layer['lvar'][0, [select]]
    return True


def ErlangB(Rho, m):
    """ErlangB calculates the blocking probability for a M/G/m/m loss system.
    The probability returned is in range [0-1].
    It is easy to prove the correctness of the value.

    Source1: https://en.wikipedia.org/wiki/Erlang_%28unit%29#Erlang_B_formula

    Source2: https://stackoverflow.com/questions/23528145/how-to-wtite-erlang-b-and-erlang-c-formulas-in-python

    :param Rho: Rho = lambda/mu
    :type Rho: double
    :param m: The number of servers.
    :type m: int
    :return: The blocking probability for incoming requests.
    :rtype: double
    """
    InvB = 1.0
    for j in range(1, m + 1):
        InvB = 1.0 + InvB * (j / Rho)
    return 1.0 / InvB


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


@classmethod
def load_tunables(cls, data):
    """
        Sets the tunables.

        :param data: set of tunables to load
        :type data: dict
        :rtype: None

        >>> TunableManager.load_tunables({'foo': 'bar'})
        >>> tunable('foo', 'not bar')
        'bar'
        """
    cls.current = data


def add_resize(vstruct, sfraction=1.0):
    """resize data array
    for example array of shape (16,16,16) with sfraction 0.5
    -> shape (8,8,8)

    sfraction : float
        resize data by fraction
    """
    vstruct['transforms'].append({'type': 'resize', 'sfraction': sfraction})


@staticmethod
def p_multiplexor_switch_name(p):
    """multiplexor_switch_name : IDENT"""
    p[0] = p[1]


def C_func(*, η_O, η_A, η_H, b_θ, b_r, b_φ):
    """
    Compute the value of the variable C
    """
    return (η_H * b_θ - η_A * b_r * b_φ) / (η_O + η_A * (1 - b_φ ** 2))


def weight_to_float(w):
    """Take a parsed weight list and return a float. e.g.:
        ["86", "%"] -> 0.86
    """
    r = float(w[0])
    if w[-1] == '%':
        r /= 100.0
    return r


def annotate_map(ax, gdf, annot, row_slice=slice(None), **kwargs):
    """
	Add annotations to a map.

	Parameters
	----------
	ax : Axes
	gdf : GeoDataFrame
	annot : str
		This is a format string, which will be populated
		using each row of `gdf`.
	row_slice : Slice, optional
		The slice of rows from `gdf` to use for annotation.
		This slice is passed to the `.loc` indexer.
	**kwargs
		Other keyword arguments are passed through to the
		`ax.annotate` command.
	"""
    gdf.loc[row_slice].apply(lambda x: ax.annotate(s=annot.format(**x), xy=
        x.geometry.centroid.coords[0], horizontalalignment='center', **
        kwargs), axis=1)


def camel_case_to_title(text):
    """
    Split string by upper case letters and return a nice name
    :param text: str, string to convert
    :return: str
    """
    words = list()
    char_pos = 0
    for curr_char_pos, char in enumerate(text):
        if char.isupper() and char_pos < curr_char_pos:
            words.append(text[char_pos:curr_char_pos].title())
            char_pos = curr_char_pos
    words.append(text[char_pos:].title())
    return ' '.join(words)


@classmethod
def _cross_match(cls, container, items_to_match):
    """Find all possible matches as sets of positions.

        Look through each item and list every position in the `container` that
        they match.
        :yields: Sets of positions which match a particular item
        """
    for item in items_to_match:
        constraint_set = set()
        for other_pos, other_item in enumerate(container):
            if item == other_item:
                constraint_set.add(other_pos)
        yield constraint_set


def read_long(fo):
    """variable-length, zig-zag encoding."""
    c = fo.read(1)
    b = ord(c)
    n = b & 127
    shift = 7
    while b & 128 != 0:
        b = ord(fo.read(1))
        n |= (b & 127) << shift
        shift += 7
    return n >> 1 ^ -(n & 1)


@classmethod
def __on_create__(cls):
    """ Called after class is constructed but before meta_ is set """
    pass


def single_point_hist_update(hist, x, fout, ifail):
    """
  Update the complete_history structure after a single call to f.

  single_point_hist_update(hist, x, fout, ifail)"""
    if ifail == 1:
        hist.failed_points.append(x)
    else:
        hist.good_points.append(x)
        hist.good_values.append(fout)


def parse_gender(gender_codeName_str):
    """
    parse user gender
    :param gender_codeName_str:
    :return:
    """
    dict_gender_mapping = {'0': 'male', '1': 'female', '2': 'unknown'}
    if isinstance(gender_codeName_str, str):
        return dict_gender_mapping[gender_codeName_str]


def nearest_index(n, ns, nt):
    """ Returns nearest possible index `n`

    Parameters
    ----------
    n: int
        Index to look for
    ns: int
        Subdivision of `nt`
    nt: int
        Total number of iterations
    """
    if n > nt:
        return nt
    if n % ns == n:
        return ns
    if n % ns > ns / 2:
        return (n // ns + 1) * ns
    if n % ns <= ns / 2:
        return n // ns * ns
    return ns


@staticmethod
def _build_from_input_dict(model_class, input_dict, data=None):
    """
        This method is used by the public method from_dict to build an object
        of class model_class using the information contained in input_dict.
        Note: This method is often overrided in the derived class to deal with
        any pre-processing of the parameters in input_dict before calling the
        constructor of the object.

        :param str model_class: Class of the object to build.
        :param dict input_dict: Extra information needed by the constructor of model_class.
        """
    return model_class(**input_dict)


def supplements(parms, countrate=None):
    u"""Supplementary parameters:
        [12]  n₁ = n*F₁     Particle number of species 1
        [13]  n₂ = n*F₂     Particle number of species 2
        [14]  n₃ = n*F₃     Particle number of species 3 (F₃ = 1-F₁-F₂)
    """
    n = parms[0]
    F1 = parms[4]
    F2 = parms[5]
    Info = list()
    Info.append([u'n₁', n * F1])
    Info.append([u'n₂', n * F2])
    Info.append([u'n₃', n * (1 - F1 - F2)])
    if countrate is not None:
        cpp = countrate / n
        Info.append(['cpp [kHz]', cpp])
    return Info


@staticmethod
def decode(buff):
    """
		Transforms the raw buffer data read in into a list of bytes
		"""
    pp = list(map(ord, buff))
    if 0 == len(pp) == 1:
        pp = []
    return pp


def red_yellow_colourmap(original_col, shade=10):
    """Red colour specification is input and returns
    a red to yellow colour map"""
    col_list = []
    col_list.append(original_col)
    curr_col = original_col
    z = max(original_col) / float(shade)
    for i in range(0, shade - 1):
        new_col = curr_col[0], curr_col[1] + z, curr_col[2]
        col_list.append(new_col)
        curr_col = new_col
    return col_list


def type_or_none(typerefs, value):
    """
    Provides a helper function to check that a value is of the types passed or
    None.
    """
    return isinstance(value, typerefs) or value is None


def isClique(cnds, node, tb, te, as_link, times):
    """ returns True if X(c) union node is a clique over tb;te, False otherwise"""
    for i in cnds:
        if as_link(i, node) not in times:
            return False
        else:
            link = as_link(i, node)
            tlist = times[link]
            first, last = 0, len(tlist) - 1
            middle = (first + last) // 2
            while first <= last:
                if tlist[middle][0] > tb:
                    last = middle - 1
                elif tlist[middle][1] < tb:
                    first = middle + 1
                else:
                    assert tlist[middle][0] <= tb and tlist[middle][1] >= tb
                    if tlist[middle][1] < te:
                        return False
                    break
                middle = (first + last) // 2
            if first > last:
                return False
    return True


def expand_NONE(nsw):
    """For nsws tagged 'NONE', return 'and' if nsw is '&', otherwise return
       nothing."""
    if nsw == '&':
        return 'and'
    else:
        return ''


def select_linked(extend: bool=False):
    """Select bones related to selected ones by parent/child relationships

    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


@staticmethod
def exit_app(_model, gui):
    """Exit GUI application."""
    gui.exit_app()


def compute_completion_metadata(shell, matches, inspect_magics=True):
    """Computes completion item metadata.

  Args:
    shell: IPython shell
    matches: List of string completion matches.
    inspect_magics: (optional, default: True) If unset, don't call
        object_inspect on any symbols starting with %.

  Returns:
    Metadata for each of the matches.
  """
    old_str_detail_level = shell.inspector.str_detail_level
    shell.inspector.str_detail_level = 1
    try:
        infos = []
        for match in matches:
            info = {}
            if '#' in match:
                info['type_name'] = match.split('#')[1]
            elif match.startswith('%') and not inspect_magics:
                info['type_name'] = 'Magic function'
            else:
                inspect_results = shell.object_inspect(match)
                info['type_name'] = inspect_results['type_name']
                if inspect_results.get('definition', ''):
                    info['definition'] = inspect_results['definition']
                elif inspect_results.get('init_definition', ''):
                    info['definition'] = inspect_results['init_definition']
            infos.append(info)
        return infos
    finally:
        shell.inspector.str_detail_level = old_str_detail_level


def get_lemma_from_mor(mor):
    """Extract lemma from ``mor``.

    Parameters
    ----------
    mor : tuple(str, str, str)

    Returns
    -------
    str
    """
    lemma, _, _ = mor.partition('-')
    lemma, _, _ = lemma.partition('&')
    return lemma


def _get_local_explanation_row(explainer, evaluation_examples, i, batch_size):
    """Return the local explanation for the sliced evaluation_examples.

    :param explainer: The explainer used to create local explanations.
    :type explainer: BaseExplainer
    :param evaluation_examples: The evaluation examples.
    :type evaluation_examples: DatasetWrapper
    :param i: The index to slice from.
    :type i: int
    :param batch_size: If include_local is True, specifies the batch size for aggregating
        local explanations to global.
    :type batch_size: int
    :return: The local explanation for the slice of rows.
    :rtype DynamicLocalExplanation
    """
    rows = evaluation_examples.dataset[i:i + batch_size]
    return explainer.explain_local(rows)


def convert_string(*args, **kwargs):
    """
    Handle converter type "string"

    :param args:
    :param kwargs:
    :return: return schema dict
    """
    schema = {'type': 'string'}
    for prop in ['length', 'maxLength', 'minLength']:
        if prop in kwargs:
            schema[prop] = kwargs[prop]
    return schema


def is_current_session(session, request):
    """
    Checks if a given session object is the same as the on used by the request.

    :type session: :class:`django.contrib.sessions.backends.base.SessionBase`
    :type request: :class:`django.http.HttpRequest` or None
    """
    if request is not None:
        return session.session_key == request.session.session_key
    return False


def get_max_delta_mags(model):
    """Largest value minus second largest value of fitted Lomb Scargle model."""
    return model['max_delta_mags']


def getBaseCurrency():
    """returns the base currency-id"""


def download_structure(pdbid, save_name):
    """This class helps user to download the 3D structure of the protein and save it on a disk.

    Example:

        To Download the file
        >>>from packman import molecule
        >>>molecule.download_structure('1prw','1prw.pdb')

    Args:
        pdbid (str)    : A Unique 4 Letter PDB ID (eg.. 1PRW)
        save_name (str): Save name of the downloaded file (Don't forget the extension). (eg... 1PRW.pdb)
    """
    import urllib.request as ur
    response = ur.urlopen('https://files.rcsb.org/view/' + pdbid + '.pdb')
    try:
        open(save_name, 'wb').write(response.read())
    except IOError:
        None
    return True


def get_write_uri():
    """Return the URI string that can be used by others to get write
        access to this node, if it is writeable. If this is a read-only node,
        return None."""


def in_unassigned(cp, category, ucd):
    """Code points that are not (yet) assigned in Unicode.

    Args:
        cp (int): Code point.
        category (str): Unicode general category for `cp`.
        ucd (UnicodeData): Unicode character database.

    Returns:
        bool: True if `cp` is in set.
    """
    return category == 'Cn' and not ucd.noncharacter(cp)


def check_topic_moderate(user, forum):
    """
    Check if one topic is mark like moderate
    """
    if user.is_superuser:
        return True
    elif not forum.is_moderate:
        return True
    elif user in forum.moderators.all():
        return True
    else:
        return False


@staticmethod
def _count_lane_invasion(weak_self, event):
    """
        Callback to update lane invasion count
        """
    self = weak_self()
    if not self:
        return
    self.actual_value += 1


def pvmodule_output_power(irrad, tdry, pvmod_Pnom, pvmod_Tcoeff, pvmod_noct):
    """
    calculate the output power of a solar module depending on its
    parameters, solar irradiation, ambient temperature. At the beginning
    is calculated the cell operation temperature, from the temperature
    follows the power gain/loss with respect to STC nominal and the
    actual power output as function of the irradiation

    input
    - irrad: solar irradiation (W/m2), integer/float
    - tdry: ambient temperature (degrees C), float
    - pvmod_Pnom: max power output at STC (W), float
    - pvmod_Tcoeff: temperature coefficient gamma (gamma), power change%
    at STC Treference =25 C compared to Pmax (x%/C), float
    - pvmod_noct: NOCT reference temperature, to estimate cell work
    temperature at given irradiation, ambient temperature, float

    returns
    - power_out, actual power generated by the module (W), float
    - cell_temp, cell estimated work temperature (degrees C), float

    """
    Tref_stc = 25
    Tref_noct = 20
    cell_temp = tdry + round((pvmod_noct - Tref_noct) * irrad / 800, 1)
    power_nom = pvmod_Pnom + pvmod_Tcoeff * (cell_temp - Tref_stc)
    power_out = power_nom * irrad / 1000
    return power_out, cell_temp


def hexa_to_rgb(color):
    """Convert hexadecimal color to RGB."""
    r = int(color[1:3], 16)
    g = int(color[3:5], 16)
    b = int(color[5:7], 16)
    if len(color) == 7:
        return r, g, b
    elif len(color) == 9:
        return r, g, b, int(color[7:9], 16)
    else:
        raise ValueError('Invalid hexadecimal notation.')


def _set_label_text(obj, text, tooltip=None, replace_all=False):
    """
    Keep text before first colon and replace the rest with new text.

    If there is no colon in the
    :param obj:
    :param text:
    :param tooltip:
    :param replace_all: No colon is searched and whole text is replaced
    :return:
    """
    dlab = str(obj.text())
    index_of_colon = dlab.find(': ')
    if index_of_colon == -1:
        index_of_colon = 0
    else:
        index_of_colon += 2
    if replace_all:
        index_of_colon = 0
    obj.setText(dlab[:index_of_colon] + '%s' % text)
    if tooltip is not None:
        obj.setToolTip(tooltip)


def get_choice_by_name(choices, name):
    """
    Find choices by name (with spaces or without spaces) or by raw_name.
    """
    try:
        return choices.from_name(name.replace(' ', '_').lower())
    except ValueError:
        for choice_id, choice_name in choices():
            choice = choices.from_id(choice_id)
            if choice.raw == name:
                return choice
        raise


def is_iterable(obj):
    """
    Are we being asked to look up a list of things, instead of a single thing?
    We check for the `__iter__` attribute so that this can cover types that
    don't have to be known by this module, such as NumPy arrays.

    Strings, however, should be considered as atomic values to look up, not
    iterables. The same goes for tuples, since they are immutable and therefore
    valid entries.

    We don't need to check for the Python 2 `unicode` type, because it doesn't
    have an `__iter__` attribute anyway.
    """
    return hasattr(obj, '__iter__') and not isinstance(obj, str
        ) and not isinstance(obj, tuple)


taqdir-2.1.3//تقدیر/کوائف.pyclass:کوائف/روزانہ

def روزانہ(خود):
    """
        روزانہ کی ظرز پر کوائف ۔

        Returns
        -------
        pd.DataFrame
        """
    return خود.اعداد


def get_closest_index(i1, i2, T, t0):
    """ Returns the index i such that abs(T[i]-t0) is minimum for i1,i2 """
    if abs(T[i1] - t0) <= abs(T[i2] - t0):
        return i1
    else:
        return i2


def is_same_class(class1, class2):
    """
    Check if 2 class are the same
    :param class1:
    :param class2:
    :return:
    """
    return class1 == class2


def update_validated_flags(validated_df, column_name, check):
    """
    Check if the previous_df which is being sent is empty or not.
    If empty set check flag and return the updated raw_df
    :param validated_df: The df containing validated columns and previous flag values.
    :param column_name: The column for which the flag has to be updated.
    :param check: The type of check being performed.
    :return: validation flags updated dataframe
    """
    cond = validated_df[column_name + '_' + check + '_flag'] == 1
    validated_df.loc[cond, column_name + '_' + check + '_flag'
        ] = validated_df.loc[cond, column_name + '_' + check + '_flag'
        ] + validated_df.loc[cond, column_name + '_' + check + '_flag_previous'
        ]
    validated_df.loc[cond, column_name] = validated_df.loc[cond,
        column_name + '_previous']
    return validated_df


def copy_as_script():
    """Copy the console contents for use in a script

    """
    pass


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

        :param PaperDocMentionType val:
        :rtype: EventType
        """
    return cls('paper_doc_mention', val)


@classmethod
def from_df(cls, df):
    """Creates an OrbitPopulation from a DataFrame.

        :param df:
            :class:`pandas.DataFrame` object.  Must contain the following
            columns: ``['M1','M2','P','ecc','mean_anomaly','obsx','obsy','obsz']``,
            i.e., as what is accessed via :attr:`OrbitPopulation.dataframe`.

        :return:
            :class:`OrbitPopulation`.
        """
    return cls(df['M1'], df['M2'], df['P'], ecc=df['ecc'], mean_anomaly=df[
        'mean_anomaly'], obsx=df['obsx'], obsy=df['obsy'], obsz=df['obsz'])


@classmethod
def default_options(cls):
    """Default configuration options

        Parameters
        ----------
        None

        Returns
        -------
        dict
        """
    return {'CHECK_WITH_INVERT_PROJ': True, 'GTIFF_IMPLICIT_JPEG_OVR':
        False, 'RASTERIO_ENV': True}


def ntToPosixSlashes(filepath):
    """
    Replaces all occurrences of NT backslashes in provided
    filepath with Posix slashes

    >>> ntToPosixSlashes('C:\\Windows')
    'C:/Windows'
    """
    return filepath.replace('\\', '/') if filepath else filepath


def auto_docstring(cls):
    """ generate a docstring for the new class in which the Attrs are documented """
    header = 'Traited class [{}.{}]'.format(cls.__module__, cls.__name__)
    doc = [header, len(header) * '^', '']
    if cls.__doc__ is not None:
        doc.extend([cls.__doc__, ''])
    doc.extend(['Attributes declared', '"""""""""""""""""""', ''])
    for attr_name in cls.declarative_attrs:
        attr = getattr(cls, attr_name)
        doc.append('{} : {}'.format(attr_name, str(attr)))
        for line in attr.doc.splitlines():
            doc.append('    ' + line.lstrip())
        doc.append('')
    if cls.declarative_props:
        doc.extend(['', 'Properties declared', '"""""""""""""""""""', ''])
    for prop_name in cls.declarative_props:
        prop = getattr(cls, prop_name)
        doc.append('  {} : {}'.format(prop_name, str(prop)))
        for line in prop.attr.doc.splitlines():
            doc.append('    ' + line.lstrip())
        if prop.fget.__doc__ is not None:
            for line in prop.fget.__doc__.splitlines():
                doc.append('    ' + line.lstrip())
    doc = '\n'.join(doc)
    return doc


def _get_dict_char_count(txt):
    """
    reads the characters in txt and returns a dictionary
    of all letters
    """
    dct = {}
    for letter in txt:
        if letter in dct:
            dct[letter] += 1
        else:
            dct[letter] = 1
    return dct


def cmp(x, y):
    """Compare the two objects x and y and return an integer according to the outcome.

    Args:
        x: The first number to compare.
        y: The second number to compare.

    Returns:
        A negative value if x < y, zero if x == y and  positive if x > y.
    """
    return (x > y) - (x < y)


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


def hasChildren():
    """Returns True if this mmeber has children False otherwise."""


@classmethod
def _construct_create_form_data(cls, project_name):
    """
        Constructs the payload to be POSTed with the request to create a new project.

        Note that this private method is relied upon for extensibility so that subclasses can
        inject additional payload data when creating new projects.

        Parameters
        ----------
        project_name : str
            Name of the project.
        Returns
        -------
        dict
        """
    return {'project_name': project_name}


def col_strip(df, col_name, dest=False):
    """ Performs str.strip() a column of a DataFrame
    Parameters:
    df - DataFrame
        DataFrame to operate on
    col_name - string
        Name of column to strip
    dest - bool, default False
        Whether to apply the result to the DataFrame or return it.
        True is apply, False is return.
    """
    if dest:
        df[col_name] = df[col_name].str.strip()
    else:
        return df[col_name].str.strip()


def cursor_set(location: float=(0.0, 0.0)):
    """Set 2D cursor location

    :param location: Location, Cursor location in normalized clip coordinates
    :type location: float
    """
    pass


def code_from_builtin(shader_name: str) ->dict:
    """Exposes the internal shader code for query.

    :param shader_name: One of these builtin shader names: { ‘2D_UNIFORM_COLOR’, ‘2D_FLAT_COLOR’, ‘2D_SMOOTH_COLOR’, ‘2D_IMAGE’, ‘3D_UNIFORM_COLOR’, ‘3D_FLAT_COLOR’, ‘3D_SMOOTH_COLOR’}
    :type shader_name: str
    :return:  Vertex, fragment and geometry shader codes.
    """
    pass


def iterate(delay=0):
    """
        Run the main loop's I/O polling function for a period of time.

        This is most useful in applications where the UI is being drawn "as
        fast as possible", such as games. All pending L{IDelayedCall}s will
        be called.

        The reactor must have been started (via the C{run()} method) prior to
        any invocations of this method.  It must also be stopped manually
        after the last call to this method (via the C{stop()} method).  This
        method is not re-entrant: you must not call it recursively; in
        particular, you must not call it while the reactor is running.
        """


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True):
    """Toggle border selection

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


def is_accessible(path, mode='r'):
    """
    Check if the file or directory at `path` can
    be accessed by the program using `mode` open flags.
    """
    try:
        f = open(path, mode)
        f.close()
    except IOError:
        return False
    return True


def get_number_to_show_archive():
    """Number of items per page to show in the archive.
        """


def typestring(obj):
    """Make a string for the object's type

    Parameters
    ----------
    obj : obj
        Python object.

    Returns
    -------
    `str`
        String representation of the object's type. This is the type's
        importable namespace.

    Examples
    --------
    >>> import docutils.nodes
    >>> para = docutils.nodes.paragraph()
    >>> typestring(para)
    'docutils.nodes.paragraph'
    """
    obj_type = type(obj)
    return '.'.join((obj_type.__module__, obj_type.__name__))


@classmethod
def get_value_from_choices(cls, value, choices):
    """ Returns the key for the choices tuple of tuples

        Note if you are using classes, they must implement the __in__ and __eq__ for the logical comparison.

        :param value: The raw value to test if it exists in the valid choices. Could be the key or the value in the dict
        :type value: Object
        :rtype: Object
        """
    if not choices:
        return None
    for key, val in choices:
        if value in (key, val):
            return key
    return None


def palette_remove():
    """Remove active Grease Pencil palette

    """
    pass