def __len__():
    """Return the number of objects indexed.
        """


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

        :param TeamMergeRequestCanceledShownToPrimaryTeamDetails val:
        :rtype: EventDetails
        """
    return cls('team_merge_request_canceled_shown_to_primary_team_details', val
        )


@classmethod
def from_transformation(cls, transformation):
    """Constructs a frame from a ``Transformation``.

        Parameters
        ----------
        transformation : :class:`compas.geometry.Transformation`
            The transformation defines the orientation of the frame through the
            rotation and the origin through the translation.

        Returns
        -------
        :class:`compas.geometry.Frame`
            The constructed frame.

        Examples
        --------
        >>> from compas.geometry import Transformation
        >>> f1 = Frame([1, 1, 1], [0.68, 0.68, 0.27], [-0.67, 0.73, -0.15])
        >>> T = Transformation.from_frame(f1)
        >>> f2 = Frame.from_transformation(T)
        >>> f1 == f2
        True
        """
    xaxis, yaxis = transformation.basis_vectors
    point = transformation.translation
    return cls(point, xaxis, yaxis)


def preprocess_input(x):
    """Preprocesses a tensor encoding a batch of images.

    # Arguments
        x: input Numpy tensor, 4D.
        data_format: data format of the image tensor.

    # Returns
        Preprocessed tensor.
    """
    x = x[(...), ::-1]
    x[..., 0] -= 103.939
    x[..., 1] -= 116.779
    x[..., 2] -= 123.68
    return x


def _whctrs(anchor):
    """Return width, height, x center, and y center for an anchor (window)."""
    w = anchor[2] - anchor[0] + 1
    h = anchor[3] - anchor[1] + 1
    x_ctr = anchor[0] + 0.5 * (w - 1)
    y_ctr = anchor[1] + 0.5 * (h - 1)
    return w, h, x_ctr, y_ctr


def calc_commission_hk(trade_cnt, price):
    """
    h股计算交易费用：印花税＋佣金： 佣金千分之二，印花税千分之一
    :param trade_cnt: 交易的股数（int）
    :param price: 每股的价格（人民币）
    :return: 计算结果手续费
    """
    cost = trade_cnt * price
    tax = cost * 0.001
    commission = cost * 0.002
    commission += tax
    return commission


def eccentricity_earth_orbit(julian_century):
    """Returns the Eccentricity or Earth Orbit with Julian Century, julian_century."""
    ecc_earth_orb = 0.016708634 - julian_century * (4.2037e-05 + 1.267e-07 *
        julian_century)
    return ecc_earth_orb


def valid_ids(nb_a, nb_b):
    """
    Ensure each notebook we are comparing has a full set of unique cell ids

    nb_a: (dict) one notebook to compare
    nb_b: (dict) the other notebook to compare
    """
    prior_a_ids = []
    prior_b_ids = []
    for c in nb_a:
        if 'comet_cell_id' not in c['metadata']:
            return False
        elif c['metadata']['comet_cell_id'] in prior_a_ids:
            return False
        else:
            prior_a_ids.append(c['metadata']['comet_cell_id'])
    for c in nb_b:
        if 'comet_cell_id' not in c['metadata']:
            return False
        elif c['metadata']['comet_cell_id'] in prior_b_ids:
            return False
        else:
            prior_b_ids.append(c['metadata']['comet_cell_id'])
    return True


def nba_season(x):
    """Takes in 4-digit year for first half of season and returns API appropriate formatted code

    Input Values: YYYY

    Used in: _Draft.Anthro(), _Draft.Agility(), _Draft.NonStationaryShooting(),
    _Draft.SpotUpShooting(), _Draft.Combine()

    """
    if len(str(x)) == 4:
        try:
            return '{0}-{1}'.format(x, str(int(x) % 100 + 1)[-2:].zfill(2))
        except ValueError:
            raise ValueError(
                'Enter the four digit year for the first half of the desired season'
                )
    else:
        raise ValueError(
            'Enter the four digit year for the first half of the desired season'
            )


def resolve_arrange_item_class_name(cls):
    """
    Returns an ArrangeItem class name for provided class.
    """
    return '%sArrangeItem' % cls._meta.object_name


@classmethod
def is_mine(cls):
    """Check if it can handle the report file.

        :raises: :class:`NotImplementedError` because this is an abstract method.

        """
    raise NotImplementedError(
        '`is_mine` function MUST be defined for each parser.')


def insertlast(newnode):
    """Insert newnode as last node.
        """


def compute_average_unit_cell(unit_cell_list):
    """Compute the weighted average unit cell based on a list of

    ((unit cell), nref)

    tuples."""
    w_tot = 0.0
    a_tot = 0.0
    b_tot = 0.0
    c_tot = 0.0
    alpha_tot = 0.0
    beta_tot = 0.0
    gamma_tot = 0.0
    for cell, n_ref in unit_cell_list:
        w_tot += n_ref
        a_tot += cell[0] * n_ref
        b_tot += cell[1] * n_ref
        c_tot += cell[2] * n_ref
        alpha_tot += cell[3] * n_ref
        beta_tot += cell[4] * n_ref
        gamma_tot += cell[5] * n_ref
    return (a_tot / w_tot, b_tot / w_tot, c_tot / w_tot, alpha_tot / w_tot,
        beta_tot / w_tot, gamma_tot / w_tot)


@classmethod
def register_variable_provider(cls, provider):
    """Plugin point to allow functions to manipulate the context
        passed to *all* templates for *all* widgets.

        def provider(context): ...

        TemplateEngine.register_variable_provider(provider)
        """
    cls.variable_providers.append(provider)


def toStringDuration(duration):
    """Returns a description of the given duration in the most appropriate
    units (e.g. seconds, ms, us, or ns).
    """
    table = ('%dms', 0.001, 1000.0), (u'%dμs', 1e-06, 1000000.0), ('%dns',
        1e-09, 1000000000.0)
    if duration > 1:
        return '%fs' % duration
    for format, threshold, factor in table:
        if duration > threshold:
            return format % int(duration * factor)
    return '%fs' % duration


@classmethod
def get_object(cls, api_token, ip):
    """
            Class method that will return a FloatingIP object by its IP.

            Args:
                api_token: str - token
                ip: str - floating ip address
        """
    floating_ip = cls(token=api_token, ip=ip)
    floating_ip.load()
    return floating_ip


def write_file(file_path, text, echo=False, append=False, mode=None,
    encoding='utf8'):
    """Write text to a file"""
    if echo:
        print('Saving to ' + file_path)
    mode = mode if mode else 'a' if append else 'w'
    f = open(file_path, mode, encoding=encoding)
    f.write(text)
    f.close()


@classmethod
def commit(cls, client=None):
    """Commit everything from datapoints via the client.

        :param client: InfluxDBClient instance for writing points to InfluxDB.
        :attention: any provided client will supersede the class client.
        :return: result of client.write_points.
        """
    if not client:
        client = cls._client
    rtn = client.write_points(cls._json_body_())
    cls._reset_()
    return rtn


def _boolean_or_list(config_name, args, configs, alternative_names=[],
    default=[]):
    """Get a boolean or list of regexes from args and configs."""
    for key in (alternative_names + [config_name]):
        if hasattr(args, key) and getattr(args, key):
            setattr(args, config_name, ['.*'])
            return
    setattr(args, config_name, default)
    option = None
    alternative_names.insert(0, config_name)
    for key in alternative_names:
        if configs.has_option('settings', key):
            option = configs.get('settings', key)
            break
    if option is not None:
        if option.strip().lower() == 'true':
            setattr(args, config_name, ['.*'])
        elif option.strip().lower() == 'false':
            setattr(args, config_name, [])
        else:
            for pattern in option.split('\n'):
                if pattern.strip() != '':
                    if not getattr(args, config_name):
                        setattr(args, config_name, [])
                    getattr(args, config_name).append(pattern)


@staticmethod
def point_from_cols_vals(cols, vals):
    """Create a dict from columns and values lists.

        :param cols: List of columns
        :param vals: List of values
        :return: Dict where keys are columns.
        """
    point = {}
    for col_index, col_name in enumerate(cols):
        point[col_name] = vals[col_index]
    return point


def openbabelConvert(input_file, input_format, output_format):
    """
    Converts the file from the input format to the output format specified. It uses the openbabel features

    Parameters
    ----------
    input_file: str
        The path of the input file to convert
    input_format: str
        The input file format
    output_format: str
        The output file format

    Returns
    -------
    outfile: str
        The output file generated
    """
    import openbabel
    import tempfile
    input_format = input_format[1:] if input_format.startswith('.'
        ) else input_format
    file = tempfile.NamedTemporaryFile(delete=True, suffix='.' + output_format)
    file.close()
    outfile = file.name
    _ = openbabel.OBConversion()
    _.SetInAndOutFormats(input_format, output_format)
    _mol = openbabel.OBMol()
    _.ReadFile(_mol, input_file)
    _.WriteFile(_mol, outfile)
    return outfile


def handle_read_callback(notifier):
    """
    Just stop receiving IO read events after the first
    iteration (unrealistic example).
    """
    print('handle_read callback')
    notifier.loop.stop()


def positive_int(string):
    """Type checker for positive integers
    """
    value = int(string)
    if value <= 0:
        raise ValueError('integer is not positive: {}'.format(value))
    return value


def avanzar_modelo(símismo, n_ciclos):
    """
        Avanzar el modelo por un número determinado de ciclos.

        Parameters
        ----------
        n_ciclos: int
            El número de ciclos que hay que avanzar.

        """
    raise NotImplementedError


def getBaseURL(req):
    """
    Given a Django web request object, returns the OpenID 'trust root'
    for that request; namely, the absolute URL to the site root which
    is serving the Django request.  The trust root will include the
    proper scheme and authority.  It will lack a port if the port is
    standard (80, 443).
    """
    name = req.META['HTTP_HOST']
    try:
        name = name[:name.index(':')]
    except:
        pass
    try:
        port = int(req.META['SERVER_PORT'])
    except:
        port = 80
    proto = req.META['SERVER_PROTOCOL']
    if 'HTTPS' in proto:
        proto = 'https'
    else:
        proto = 'http'
    if port in [80, 443] or not port:
        port = ''
    else:
        port = ':%s' % (port,)
    url = '%s://%s%s/' % (proto, name, port)
    return url


@classmethod
def add_quick_search_filter(cls, qs, search_text):
    """Add a filter to the given queryset `qs` in order to apply a quick
        search for the given `search_text`.

        """
    flt = qs.model.quick_search_filter(search_text)
    if len(flt) == 0:
        return qs.model.objects.none()
    return qs.filter(flt)


@classmethod
def normalize_field_names(cls, torrent_info):
    """Translates from torrent fields names in terms of RPC to field names in term of torrt.
        Updates accordingly a given torrent_info.

        :param torrent_info: dict
        :return:
        """
    for old_name, new_name in cls.torrent_fields_map.items():
        if old_name in torrent_info:
            torrent_info[new_name] = torrent_info[old_name]


@classmethod
def delete(cls, options=None):
    """Delete parameter from config
        Usage::

            hammer defaults delete [OPTIONS]

        Options::

            --param-name OPTION_NAME      The name of the default option
        """
    cls.command_sub = 'delete'
    return cls.execute(cls._construct_command(options))


def cache_key(key, *args, **kwargs):
    """ Modifies the cache key if needed and returns it
        """


def h_12():
    """Return the 12-hour clock representation of the hour"""


@staticmethod
def _subscribe(sub_id, channel, callback, **kwargs):
    """Listen to a queue, notify via callback function.
        :param sub_id: ID for this subscription in the transport layer
        :param channel: Queue name to subscribe to
        :param callback: Function to be called when messages are received
        :param **kwargs: Further parameters for the transport layer. For example
               exclusive: Attempt to become exclusive subscriber to the queue.
               acknowledgement: If true receipt of each message needs to be
                                acknowledged.
        """
    raise NotImplementedError('Transport interface not implemented')


@staticmethod
def __remove_duplicates(results):
    """
        Removes each result which has a span contained in a
        result's span with a higher score
        :param results: List[RecognizerResult]
        :return: List[RecognizerResult]
        """
    results = sorted(results, key=lambda x: (-x.score, x.start, x.end - x.
        start))
    filtered_results = []
    for result in results:
        if result.score == 0:
            continue
        valid_result = True
        if result not in filtered_results:
            for filtered in filtered_results:
                if result.contained_in(filtered
                    ) and result.entity_type == filtered.entity_type:
                    valid_result = False
                    break
        if valid_result:
            filtered_results.append(result)
    return filtered_results


@staticmethod
def _get_message_from_stream(stream):
    """
        make the request and return the body

        :param stream: the stream
        :type method: request
        :returns: the message
        :rtype: dictionary
        """
    message = b''
    for char in stream.iter_content():
        if char == b'\n':
            yield message.decode('unicode_escape')
            message = b''
        else:
            message += char


def _check_invalid_udfs(udf_columns):
    """
    Checks if given udf columns are valid. Raises ValueError if they are not.

    :param udf_columns: A list of udf columns.
    """
    for col in udf_columns:
        for index in col.column_indices:
            if index is None:
                raise ValueError(
                    'Column passed to the udf function must be a column in the DataFrame, i.e, df[col] or df[[col1, col2]]. Other types of Column are not supported.'
                    )


def paste(selection: bool=False):
    """Paste text from clipboard

    :param selection: Selection, Paste text selected elsewhere rather than copied (X11 only)
    :type selection: bool
    """
    pass


def _est_regularized_naive(mod, pnum, partitions, fit_kwds=None):
    """estimates the regularized fitted parameters.

    Parameters
    ----------
    mod : statsmodels model class instance
        The model for the current partition.
    pnum : scalar
        Index of current partition
    partitions : scalar
        Total number of partitions
    fit_kwds : dict-like or None
        Keyword arguments to be given to fit_regularized

    Returns
    -------
    An array of the parameters for the regularized fit
    """
    if fit_kwds is None:
        raise ValueError('_est_regularized_naive currently ' +
            'requires that fit_kwds not be None.')
    return mod.fit_regularized(**fit_kwds).params


def prettyTime(diffInSecs):
    """Returns a human-readable string from time-difference (in seconds).
    Uses absolute value of time-diff, and thus does not care about before/after.

    Args:
        diffInSecs (int): Timedifference in seconds.
    """
    intervals = [('minute', 60), ('hour', 60), ('day', 24), ('week', 7), (
        'month', 4.34811904762), ('year', 12)]
    unit, number = 'second', abs(diffInSecs)
    for new_unit, ratio in intervals:
        new_number = float(number) / ratio
        if new_number < 2:
            break
        unit, number = new_unit, new_number
    shown_num = int(number)
    return '{} {}'.format(shown_num, unit + ('' if shown_num == 1 else 's'))


@staticmethod
def md5(msg: str) ->str:
    """Calculates MD5 hashs for string argument.
        """
    import hashlib
    if str is None:
        raise ValueError('Data do hash cannot be None')
    name_hash = hashlib.md5()
    name_hash.update(msg.encode('UTF-8'))
    return name_hash.hexdigest()


def unrestrictedTraverse(path, default=None, restricted=0):
    """Lookup an object by path.

        path -- The path to the object. May be a sequence of strings or a
        slash separated string. If the path begins with an empty path element
        (i.e., an empty string or a slash) then the lookup is performed
        from the application root. Otherwise, the lookup is relative to
        self. Two dots (..) as a path element indicates an upward traversal
        to the acquisition parent.

        default -- If provided, this is the value returned if the path cannot
        be traversed for any reason (i.e., no object exists at that path or
        the object is inaccessible).

        restricted -- If false (default) then no security checking is
        performed. If true, then all of the objects along the path are
        validated with the security machinery. Usually invoked using
        restrictedTraverse().
        """


def join_strings(input_list, delimiter=' '):
    """Open file and retrieve a dictionary of data.

    :param input_list: List of values to join.
    :type input_list: list
    :param delimiter: Delimiter used between values.
    :type delimiter: str
    :returns: Concatenated values, excluding all None and '' values.
    :rtype: str
    """
    concat_list = []
    for value in input_list:
        if value is not None and value != '':
            concat_list.append(value)
    if len(concat_list) > 0:
        string = delimiter.join(concat_list)
    else:
        string = ''
    return string


def gwrap(some_string):
    """
    Returns green text
    """
    return '\x1b[92m%s\x1b[0m' % some_string


def popcorn(t=120, T=None):
    """
    Simulation of stovetop popcorn cooking.

    A fixed number of popcorn kernels are cooked are heated at the same
    temperature. This simulation returns the number of kernels that are edible
    when the pot is left on the stove for a given number of `t` seconds.

    Parameters
    ----------

    `t` is the number of seconds that the pot is left on the stove. The
    default amount, if not provided, is 120 seconds.

    Time durations less than 77 seconds are not supported. A vector (list) of
    time values is not permitted, since the goal is to perform sequential
    experimentation to determine the optimum time, with the fewest number of
    function calls.

    Returns
    -------
    The number of edible popcorn kernels. Random noise is added for realism.

    Source
    ------
    Kevin Dunn, Process Improvement using Data, Chapter 5, 2010 to 2019,
    https://learnche.org/pid

    Examples
    --------
    >>> popcorn(t=55)    # will fail
    >>> popcorn(t=120)
    >>> popcorn(t=152.2)

    >>> # What happens if we leave the pot on the stove for too long?
    >>> popcorn(t=500)

    Also see
    grocery
    manufacter

    """
    pass


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

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

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


@staticmethod
def never_trigger(dt):
    """
        A should_trigger implementation that will never trigger.
        """
    return False


def links_sortkey(link):
    """key function for sorting a list of link description object."""
    return link['href'], link['rel']


def keymap_restore(all: bool=False):
    """Restore key map(s)

    :param all: All Keymaps, Restore all keymaps to default
    :type all: bool
    """
    pass


def clean_string(s: str) ->str:
    """
    a DNS-1123 subdomain must consist of lower case alphanumeric characters, '-' or '.',
    and must start and end with an alphanumeric character (
    e.g. 'example.com', regex used for validation is
    '[a-z0-9]( [-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*'

    'must be no more than 63 characters'
    """
    return s.replace('/', '-').replace(':', '-').replace('_', '-').replace('.',
        '-').replace('--', '-')[-63:]


def _import_module(name, package=None, warn=True, prefix='_py_', ignore='_'):
    """Try import all public attributes from module into global namespace.

    Existing attributes with name clashes are renamed with prefix.
    Attributes starting with underscore are ignored by default.

    Return True on successful import.

    """
    import warnings
    from importlib import import_module
    try:
        if not package:
            module = import_module(name)
        else:
            module = import_module('.' + name, package=package)
    except ImportError:
        if warn:
            warnings.warn('failed to import module %s' % name)
    else:
        for attr in dir(module):
            if ignore and attr.startswith(ignore):
                continue
            if prefix:
                if attr in globals():
                    globals()[prefix + attr] = globals()[attr]
                elif warn:
                    warnings.warn('no Python implementation of ' + attr)
            globals()[attr] = getattr(module, attr)
        return True


@classmethod
def from_terms(cls, terms, name, description, refgen):
    """
            Convenience function to create a Ontology from an iterable
            terms object.

            Parameters
            ----------
            terms : iterable of camoco.GOTerm objects
                Items to add to the ontology. The key being the name
                of the term and the items being the loci.
            name : str
                The name of the camoco object to be stored in the database.
            description : str
                A short message describing the dataset.
            refgen : camoco.RefGen
                A RefGen object describing the genes in the dataset
        """
    self = cls.create(name, description, refgen)
    self.log('Adding {} terms to the database.', len(terms))
    self.add_terms(terms, overwrite=True)
    self.log('Building the indices.')
    self._build_indices()
    self.log('Your gene ontology is built.')
    return self


def is_valid_key(key):
    """Return if a key can be used in the SHA-256 signature."""
    return key not in ['merchantSig', 'sig'] and not key.startswith('ignore.')


@staticmethod
def p_var_measurement(p):
    """var_measurement : VAR_MEASUREMENT IDENT"""
    p[0] = p[2]


def reverse_dict_partial(dict_obj):
    """Reverse a dict, so each value in it maps to one of its keys.

    Parameters
    ----------
    dict_obj : dict
        A key-value dict.

    Returns
    -------
    dict
        A dict where each value maps to the key that mapped to it.

    Example
    -------
    >>> dicti = {'a': 1, 'b': 3}
    >>> reverse_dict_partial(dicti)
    {1: 'a', 3: 'b'}
    """
    new_dict = {}
    for key in dict_obj:
        new_dict[dict_obj[key]] = key
    return new_dict


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

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


def read_config(line: str) ->dict:
    """
    Read the config line of a file.

    Config lines start with #! and declare configuration item like name:value.
    Items need to be separated by whitespace.

    :param line: Config line as str
    :return: parsed config as dict
    """
    config: dict = {}
    config_list: list = line.split(' ')
    for element in config_list:
        if ':' in element:
            item = element.split(':')
            config.update({item[0]: item[1].replace('\n', '')})
    return config


def add_nodes_from(graph, node_list):
    """Add nodes from a node list.

    Parameters
    ----------
    graph : regraph.Graph
    node_list : iterable
        Iterable containing a collection of nodes, optionally,
        with their attributes

    Examples
    --------
    >>> import networkx as nx
    >>> from regraph.primitives import add_nodes_from
    >>> G = nx.Graph()
    >>> add_nodes_from(G, [1, (2, {"a": 1}), 3])
    """
    graph.add_nodes_from(node_list)


def geojson2json(content, destiny='plot'):
    """
    content is a GeoJson object must be converted to a RethinkDB JSON object....
    """
    try:
        time = content['properties']['time']
        dt0 = content['properties']['dt']
        c_datetime = dt0.isoformat()
        dt = dt0.isoformat()
        if destiny == 'plot':
            dt_gen = content['properties']['DT_GEN'].isoformat()
        else:
            dt_gen = content['properties']['DT_GEN']
    except Exception as exec:
        print('Error en calcular fecha tiempo %s' % exec)
        raise exec
    new_value = dict(source='DataWork', station_name=content['properties'][
        'station'], DT_GEN=dt_gen, timestamp=time, data={'N': {'value':
        content['features'][0]['geometry']['coordinates'][0], 'error':
        content['properties']['NError'], 'min': content['features'][0][
        'geometry']['coordinates'][0] - content['properties']['NError'],
        'max': content['features'][0]['geometry']['coordinates'][0] +
        content['properties']['NError']}, 'E': {'value': content['features'
        ][0]['geometry']['coordinates'][1], 'error': content['properties'][
        'EError'], 'min': content['features'][0]['geometry']['coordinates']
        [1] - content['properties']['EError'], 'max': content['features'][0
        ]['geometry']['coordinates'][1] + content['properties']['EError']},
        'U': {'value': content['features'][0]['geometry']['coordinates'][2],
        'error': content['properties']['UError'], 'min': content['features'
        ][0]['geometry']['coordinates'][2] - content['properties']['UError'
        ], 'max': content['features'][0]['geometry']['coordinates'][2] +
        content['properties']['UError']}})
    return new_value


def parse_header_links(value):
    """Return a dict of parsed link headers proxies.

    i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"

    """
    links = []
    replace_chars = ' \'"'
    for val in value.split(','):
        try:
            url, params = val.split(';', 1)
        except ValueError:
            url, params = val, ''
        link = {}
        link['url'] = url.strip('<> \'"')
        for param in params.split(';'):
            try:
                key, value = param.split('=')
            except ValueError:
                break
            link[key.strip(replace_chars)] = value.strip(replace_chars)
        links.append(link)
    return links


def create_single_event(data):
    """ Creates an event dictionary that will be used to collect data and then
    packed into the the master data dictionary.

    Args:
	**data** (dict): Data dictionary that will hold all the data from the events.

    Returns:
	**event** (dict): The new event dictionary with keys and no event information

    """
    event = {}
    for k in data.keys():
        if k[-5:] == 'index':
            event[k] = data[k]
        elif k in data['groups']['_SINGLETON_']:
            event[k] = None
        elif k in data['list_of_counters']:
            event[k] = 0
        else:
            event[k] = data[k].copy()
    return event


@classmethod
def write_str(cls, opc_sync: bool, total_size: int, context: str
    ) ->'IoTransferEventArgs':
    """Creates new IoTransferEventArgs of write string

		:param opc_sync: defines if the command is OPC-synchronised
		:param total_size: size of the data to write
		:param context: SCPI command write. It is truncated to maximum of 100 characters.
		:return: IoTransferEventArgs object of a write string operation."""
    obj = cls(False, opc_sync, total_size, context)
    obj.binary = False
    return obj


def install(args=None):
    """Check if LPy language will be supported based on if the lpy package
    can be imported from openalea.

    Args:
        args (argparse.Namespace, optional): Arguments parsed from the
            command line. Default to None and is created from sys.argv.

    Returns:
        bool: True if install succeded, False otherwise.

    """
    try:
        from openalea import lpy
        del lpy
        return True
    except ImportError:
        return False


def analog_l3_released(controller):
    """
    Callback function that is triggered, when the left stick button was released

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('ACTION:' + str(controller.number) + ':' + controller.name +
        ':Analog L3 released')


@classmethod
def make_class(cls, name, bases, objectProperties=False, datatypeProperties
    =False):
    """
        Intended to be used for setting up a class from the RDF graph, for
        instance.
        """
    if not datatypeProperties:
        datatypeProperties = []
    if not objectProperties:
        objectProperties = []
    cls(name, bases, dict(objectProperties=objectProperties,
        datatypeProperties=datatypeProperties))


def levelize_path(path):
    """Splits given path to list of paths removing latest level in each step.

    >>> path = '/application/item/new'
    >>> levelize_path(path)
    ['/application/item/new', '/application/item', '/application']
    """
    parts = path.rstrip('/').split('/')
    paths = []
    for i in range(len(parts), 0, -1):
        sub_path = '/'.join(parts[:i])
        if sub_path:
            paths.append(sub_path)
    return paths


def int_to_roman(input):
    """ Convert an integer to a Roman numeral. """
    if not isinstance(input, type(1)):
        raise TypeError('expected integer, got %s' % type(input))
    if not 0 < input < 4000:
        raise ValueError('Argument must be between 1 and 3999')
    ints = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
    nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V',
        'IV', 'I')
    result = []
    for i in range(len(ints)):
        count = int(input / ints[i])
        result.append(nums[i] * count)
        input -= ints[i] * count
    return ''.join(result)


def get_string(stream):
    'Use this to grab a "string" from a bytearray() stream.\n\n    C\'s printf() prints until it encounters a null byte (b\'\x00\'). This function behaves the same.\n\n    Positional arguments:\n    stream -- bytearray stream of data.\n\n    Returns:\n    bytes() instance of any characters from the start of the stream until before the first null byte.\n    '
    ba = bytearray()
    for c in stream:
        if not c:
            break
        ba.append(c)
    return bytes(ba)


def gen_window_makefile(file_path):
    """
    Genera windows make.bat

    :param str file_path: ruta para guardar el fichero
    """
    template = """
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
    set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build

if "%1" == "" goto help

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
    echo.
    echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
    echo.installed, then set the SPHINXBUILD environment variable to point
    echo.to the full path of the 'sphinx-build' executable. Alternatively you
    echo.may add the Sphinx directory to PATH.
    echo.
    echo.If you don't have Sphinx installed, grab it from
    echo.http://sphinx-doc.org/
    exit /b 1
)

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%

:end
popd
"""
    with open(file_path, 'w') as f:
        f.write(template)


@classmethod
def _get_namespace_url(cls) ->str:
    """Get the URL to use as the reference BEL namespace."""
    return cls.identifiers_url or f'_{cls.module_name.upper()}'


def use_psyco():
    """Use Psyco (if available) to speed things up."""
    try:
        import psyco
        psyco.full()
    except ImportError:
        pass


def removed(object, oldParent=None, oldName=None):
    """Send an :class:`~.IObjectRemovedEvent` for ``object``.

        ``oldParent`` is the container ``object`` was removed from.
        ``oldName`` was the name used to store ``object`` in `oldParent`.

        If either of these is not provided or is ``None``, they will
        be taken from the values of ``object.__parent__`` or
        ``object.__name__``, respectively.
        """


@classmethod
def from_idx_branch_revision(cls, idx, branch=None, revision=None):
    """Factory method from idx, (branch and revision)."""
    if idx is None:
        return None
    id_ = cls(id_text=idx)
    if not branch:
        branch = cls.BRANCH_TRUNK
    if not revision:
        revision = cls.REV_HEAD
    id_.branch = branch
    id_.revision = revision
    if id_.revision == cls.REV_HEAD:
        id_.to_string_with_version()
    return id_


def get_file_list(resource, datum_kwarg_gen, get_spec_handler):
    """
    Given a resource and an iterable of datum kwargs, get a list of
    associated files.

    DO NOT USE FOR COPYING OR MOVING. This is for debugging only.
    See the methods for moving and copying on the Registry object.
    """
    handler = get_spec_handler(resource['uid'])
    return handler.get_file_list(datum_kwarg_gen)


@classmethod
def global_config(cls, key, *args):
    """ This reads or sets the global settings stored in class.settings. """
    if args:
        cls.settings = cls.settings.copy()
        cls.settings[key] = args[0]
    else:
        return cls.settings[key]


@classmethod
def maptag(cls, tag, fn):
    """
        Map (override) tag => I{class} mapping.
        @param tag: An xsd tag name.
        @type tag: str
        @param fn: A function or class.
        @type fn: fn|class.
        """
    cls.tags[tag] = fn


def is_frame_magic(data):
    """Unpacks an int and checks whether it matches the EDR frame magic number

    Does not roll the reading position back.
    """
    magic = data.unpack_int()
    return magic == -7777777


def _get_label_values(func, use_apply, name_and_group):
    """
    Returns a tuple of a name, func(group) for this name_and_group.
    Used since .groupby() returns an iterator over the pairs (name, group).

    Parameters
    ----------
    func : Function
        Must be picklable:  A lambda function will not work!
    name_and_group : Tuple
        name, group
    use_apply : Boolean
        If True, use group.apply(func)
        If False, use func(group)

    Returns
    -------
    name : the group name/label
        Same as the 'name' passed in
    value : Either group.apply(func) or func(group)
    """
    name, group = name_and_group
    value = group.apply(func) if use_apply else func(group)
    return name, value


def z_score(x):
    """
    Takes input array x and converts each element in the array to a z_score
    """
    import scipy.stats as stats
    return stats.zscore(x)


def object_to_dict(xmp):
    """
    Extracts all XMP data from a given XMPMeta instance organizing it into a
    standard Python dictionary.
    """
    dxmp = dict()
    if not xmp:
        return {}
    for item in xmp:
        if item[-1]['IS_SCHEMA']:
            dxmp[item[0]] = []
        else:
            dxmp[item[0]].append(item[1:])
    return dxmp


def add_arguments(parser):
    """
        Adds arguments to overall program's parser.
    """
    parser.add_argument('--bound', default=None, type=float, help=
        '[Default is None] Decision boundary for belief.')
    parser.add_argument('--orthotrustfactor', default=0.85, type=float,
        help=
        '[Default is 0.85] Trust factor (decay) in belief for orthologue nodes.'
        )
    parser.add_argument('--paratrustfactor', default=0.7225, type=float,
        help=
        '[Default is 0.7225] Trust factor (decay) in belief for paralogue nodes.'
        )


@classmethod
def apply_query_gte(cls, queryset, options, value):
    """Apply `gte` functional query.

        Syntax:

            /endpoint/?field_name__gte={value}__{boost}
            /endpoint/?field_name__gte={value}

        Example:

            http://localhost:8000/api/articles/?id__gte=1__2.0
            http://localhost:8000/api/articles/?id__gte=1

        :param queryset: Original queryset.
        :param options: Filter options.
        :param value: value to filter on.
        :type queryset: elasticsearch_dsl.search.Search
        :type options: dict
        :type value: str
        :return: Modified queryset.
        :rtype: elasticsearch_dsl.search.Search
        """
    return cls.apply_filter(queryset=queryset, options=options, args=[
        'range'], kwargs={options['field']: cls.get_gte_lte_params(value,
        'gte')})


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

        :param TfaRemoveSecurityKeyType val:
        :rtype: EventType
        """
    return cls('tfa_remove_security_key', val)


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 __bin_base_interval(mod, ii):
    """Ensures that base bounds are opened to either positive real axis
    or negative real axes"""
    return mod.binbaselower[ii] + mod.binbaseupper[ii] <= 1


def register(module_name: str, translations_dict: dict):
    """Registers an addon’s UI translations.

    :param module_name: The name identifying the addon.
    :type module_name: str
    :param translations_dict: A dictionary built like that: {locale: {msg_key: msg_translation, ...}, ...}
    :type translations_dict: dict
    """
    pass


def get_cpu_tempfunc():
    """ Return CPU temperature """
    result = 0
    mypath = '/sys/class/thermal/thermal_zone0/temp'
    with open(mypath, 'r') as mytmpfile:
        for line in mytmpfile:
            result = line
    result = float(result) / 1000
    result = round(result, 1)
    return str(result)


def default_idtoken_processing_hook(id_token, user, token, request, **kwargs):
    """
    Hook to perform some additional actions to `id_token` dictionary just before serialization.

    :param id_token: dictionary contains values that going to be serialized into `id_token`
    :type id_token: dict

    :param user: user for whom id_token is generated
    :type user: User

    :param token: the Token object created for the authentication request
    :type token: oidc_provider.models.Token

    :param request: the request initiating this ID token processing
    :type request: django.http.HttpRequest

    :return: custom modified dictionary of values for `id_token`
    :rtype: dict
    """
    return id_token


def get_logvar(name):
    """Return user-defined log variable contents.

    * http://uwsgi.readthedocs.io/en/latest/LogFormat.html#user-defined-logvars

    .. warning:: Bytes are returned for Python 3.

    :param str|unicode name:

    :rtype: bytes|str
    """


def lambd_NH3_Br_CB89(T, P):
    """n-a: ammonia bromide [CB89]."""
    lambd = -0.022
    valid = T == 298.15
    return lambd, valid


def _int(v):
    """Convert to int for excel, but default to original value."""
    try:
        if v is None or v == '':
            return ''
        if type(v) is str:
            return int(float(v.replace(',', '')))
        return int(v)
    except ValueError:
        return v


@staticmethod
def _transform_image(image):
    """
        override this method to apply image transformations in order to increase OCR accuracy.
        good starting point is cv2.threshold(image, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] but be sure to
            transform PIL images to numpy array first (np.array(image))
        """
    return image


def useOrRaise(thing, errmsg=''):
    """Raise 'thing' if it's a subclass of Exception.  Otherwise return it.

    Called by: Cheetah.Servlet.cgiImport()
    """
    if isinstance(thing, type) and issubclass(thing, Exception):
        raise thing(errmsg)
    return thing


@staticmethod
def is_list_arg(arg=None, types=None):
    """
        Returns True if the given arg is a list and all items in that list are instances of given types ele returns False
        If types is None (default), the type of each item is not tested
        :param arg: variant, value to validate as a list
        :param types: class or list of types and/or classes
        :return: bool
        """
    result = isinstance(arg, (tuple, list))
    if result and types is not None:
        for a in arg:
            if not isinstance(a, types):
                result = False
                break
    return result


def unsubscribe(subscriber, type_name=None):
    """
        Unsubscribes 'subscriber.'  'subscriber' can any of the supported
        subscription types.
        """


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

        :returns: list of strings containing APIC class names
        """
    resp = ['actrlRule']
    return resp


def refine(string, variables=[]):
    """refine(...) --> str

	Return a parsed math term mostly readable by python
	eg.  .25 -> 0.25 ,  2x(54/3) -> 2*x*(54/3) ,
	 | 1-x^3 \\|/{10-4} -> (abs (1-x**3) )/(10-4)  etc.
	second parameter is a list of single character
	reserved as unknown values
	Not fully reliable
	Will be changed in future versions"""
    string = string.replace(' ', '')
    string = string.replace('^', '**')
    string = string.replace('[', '(')
    string = string.replace(']', ')')
    string = string.replace('{', '(')
    string = string.replace('}', ')')
    string = string.replace('\\|', ') )')
    string = string.replace('|', '(abs (')
    last_index = -1
    for _ in range(string.count('.')):
        index = string.index('.', last_index + 1)
        if index != 0:
            if not string[index - 1].isdigit():
                string = string[:index] + '0.' + string[index + 1:]
        else:
            string = '0' + string
        last_index = index
    last_index = -1
    for _ in range(string.count('(')):
        index = string.index('(', last_index + 1)
        if index != 0 and (string[index - 1].isdigit() or string[index - 1] in
            variables):
            string = string[:index] + '*(' + string[index + 1:]
        last_index = index
    last_index = -1
    for _ in range(string.count(')')):
        length = len(string)
        index = string.index(')', last_index + 1)
        if index + 1 < length:
            if string[index + 1].isdigit() or string[index + 1
                ] in variables + ['(']:
                string = string[:index] + ')*' + string[index + 1:]
        last_index = index
    for v in variables:
        last_index = -1
        for _ in range(string.count(v)):
            index = string.index(v, last_index + 1)
            if index != 0 and string[index - 1] not in '+-*/%()':
                string = string[:index] + '*' + v + string[index + 1:]
            if index + 1 < len(string):
                if string[index + 1] not in '+-*/%()' + v:
                    string = string[:index] + v + '*' + string[index + 1:]
    return string


def save_repeat_treks(tandem_repeats, file):
    """ Save multiple `tandem_repeats` in T-REKS format in specified `file`

        At current, only one TR per sequence can be defined, as the identifiers
        in the dict <tandem_repeats> must be unique.

        Parameters: Dict of tandem repeats and identifiers.
            e.g. {'ENSP00012': [msa1, begin1], 'ENSP00013': [msa2, begin2]}

            T-REKS format example:

            >a
            Length: 3 residues - nb: 3  from  1 to 10 - Psim:0.8076923076923077 region Length:42
            GHKI
            GHKI
            GH--
            **********************

            Length: 3 residues - nb: 2  from  21 to 27 - Psim:0.7857142857142857 region Length:22
            GHKI
            GH--
            **********************

            >b
            Length: 3 residues - nb: 3  from  1 to 10 - Psim:0.8095238095238095 region Length:20
            UIR
            UIR
            UIR
    """
    with open(file, 'w', newline='\n') as fh:
        for identifier, info in tandem_repeats.items():
            fh.write('>{0}\n'.format(identifier))
            fh.write('Length: from {0} to\n'.format(str(info[1])))
            fh.write('\n'.join(info[0]) + '\n' + '*' * 22 + '\n\n')


@classmethod
def poisson_gt(cls, tau_1, tau_2, symbolic=False):
    """Asymptotic development of ``P(X_1 > X_2)``, where ``X_i ~ Poison(tau_i * n)``.

        Parameters
        ----------
        tau_1,tau_2 : Number
            The parameter of the Poisson distribution of ``X_i`` is ``tau_i * n``, where `n` tends to infinity.
        symbolic : bool
            Whether the computations are symbolic or numeric.

        Returns
        -------
        Asymptotic
            The asymptotic development of ``P(X_1 > X_2)``, where ``X_i ~ Poison(tau_i * n)``.

        Examples
        --------
            >>> from math import log
            >>> print(Asymptotic.poisson_gt(tau_1=0, tau_2=0))
            exp(- inf)
            >>> print(Asymptotic.poisson_gt(tau_1=0, tau_2=1/10))
            exp(- inf)
            >>> print(Asymptotic.poisson_gt(tau_1=1/10, tau_2=0))
            exp(o(1))
            >>> Asymptotic.poisson_gt(tau_1=9/10, tau_2=1/10).look_equal(
            ...     Asymptotic(mu=0, nu=0, xi=0))
            True
            >>> Asymptotic.poisson_gt(tau_1=3/10, tau_2=3/10).look_equal(
            ...     Asymptotic(mu=0, nu=0, xi=-log(2)))
            True
            >>> asymptotic = Asymptotic.poisson_gt(tau_1=1/10, tau_2=9/10)
            >>> asymptotic_eq = Asymptotic.poisson_eq(tau_1=1/10, tau_2=9/10)
            >>> asymptotic.look_equal(
            ...     Asymptotic(mu=asymptotic_eq.mu, nu=asymptotic_eq.nu, xi=asymptotic_eq.xi - log(2)))
            True
        """
    return cls.poisson_x1_ge_x2_plus_k(tau_1, tau_2, 1, symbolic=symbolic)


def select_labeled_events(t, key='type'):
    """Returns rows from a table where the column `key` is not masked."""
    return t[~t.mask[key]] if t.has_masked_values else t.copy()


def chown(*unused_args, **unused_kwargs):
    """Method os.chown() is forbidden"""
    raise RuntimeError(
        'Usage of os.chown() is forbidden.Use certbot.compat.filesystem.copy_ownership_and_apply_mode() instead.'
        )


@classmethod
def bills_since(cls, date_cutoff):
    """
        grabs all bills that have had activity since a given date
        """
    return cls.objects.filter(last_action_date_dt__gte=date_cutoff)


def inverse_mod(a, m):
    """Inverse of a mod m."""
    if a < 0 or m <= a:
        a = a % m
    c, d = a, m
    uc, vc, ud, vd = 1, 0, 0, 1
    while c != 0:
        q, c, d = divmod(d, c) + (c,)
        uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc
    assert d == 1
    if ud > 0:
        return ud
    else:
        return ud + m


def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
    """Truncates a pair of sequences to a maximum sequence length."""
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_num_tokens:
            break
        trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
        assert len(trunc_tokens) >= 1
        if rng.random() < 0.5:
            del trunc_tokens[0]
        else:
            trunc_tokens.pop()


def _json_view_params(shape, affine, vmin, vmax, cut_slices, black_bg=False,
    opacity=1, draw_cross=True, annotate=True, title=None, colorbar=True,
    value=True):
    """ Create a dictionary with all the brainsprite parameters.
        Returns: params
    """
    if black_bg:
        cfont = '#FFFFFF'
        cbg = '#000000'
    else:
        cfont = '#000000'
        cbg = '#FFFFFF'
    if type(vmin).__module__ == 'numpy':
        vmin = vmin.tolist()
    if type(vmax).__module__ == 'numpy':
        vmax = vmax.tolist()
    params = {'canvas': '3Dviewer', 'sprite': 'spriteImg', 'nbSlice': {'X':
        shape[0], 'Y': shape[1], 'Z': shape[2]}, 'overlay': {'sprite':
        'overlayImg', 'nbSlice': {'X': shape[0], 'Y': shape[1], 'Z': shape[
        2]}, 'opacity': opacity}, 'colorBackground': cbg, 'colorFont':
        cfont, 'crosshair': draw_cross, 'affine': affine.tolist(),
        'flagCoordinates': annotate, 'title': title, 'flagValue': value,
        'numSlice': {'X': cut_slices[0] - 1, 'Y': cut_slices[1] - 1, 'Z':
        cut_slices[2] - 1}}
    if colorbar:
        params['colorMap'] = {'img': 'colorMap', 'min': vmin, 'max': vmax}
    return params


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

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

    Returns
    -------
    bool
        Returns true if the new value is bigger than the old value, else
        returns false.

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

    .. doctest::

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

    """
    return value > old_value


@classmethod
def _parse_item(cls, item):
    """
        PArse item into parts. Currently we use just split with some type conversions.
        :param item:
        :return: list of parts
        """
    result = []
    for part in item.split('.'):
        try:
            result.append(int(part))
        except:
            result.append(part)
    return result


def add_intercept_to_dataframe(specification, dataframe):
    """
    Checks whether `intercept` is in `specification` but not in `dataframe` and
    adds the required column to dataframe. Note this function is not
    idempotent--it alters the original argument, `dataframe`.

    Parameters
    ----------
    specification : an iterable that has a `__contains__` method.
    dataframe : pandas DataFrame.
        Dataframe containing the data for the choice model to be estimated.

    Returns
    -------
    None.
    """
    if 'intercept' in specification and 'intercept' not in dataframe.columns:
        dataframe['intercept'] = 1.0
    return None


def doctests():
    """
    >>> d = Database()
    >>> d.execute("create table table1 (name varchar primary key, email varchar not null unique);")
    >>> d.execute("insert into table1 (name, email) values ('sah', 'sah@blackearthgroup.com')")
    >>> d.execute("insert into table1 (name, email) values ('sah', 'sah.harrison@gmail.com')")
    Traceback (most recent call last):
      ...
    sqlite3.IntegrityError: UNIQUE constraint failed: table1.name
    """


def clear(fig):
    """Clear all plugins from the figure, including defaults"""
    fig.mpld3_plugins = []


@classmethod
def get_as_var(cls, tokens):
    """Returns context variable from `as` template tag clause if any.

         Modifies tokens inplace.

        :param tokens:
        :rtype: None|str
        """
    as_var = None
    if tokens[-2] == 'as':
        as_var = tokens[-1]
        tokens[-2:] = []
    return as_var


def brightness_from_percentage(percent):
    """Convert percentage to absolute value 0..255."""
    return round(percent * 255.0 / 100.0)


@staticmethod
def init_user_filter(user):
    """This method is used to check if the user has access"""
    return True


def init(root_helper=None):
    """Initialise oslo.privsep library.

    This function should be called at the top of main(), after the
    command line is parsed, oslo.config is initialised and logging is
    set up, but before calling any privileged entrypoint, changing
    user id, forking, or anything else "odd".

    :param root_helper: List of command and arguments to prefix
        privsep-helper with, in order to run helper as root.  Note,
        ignored if context's helper_command config option is set.
    """
    if root_helper:
        global _HELPER_COMMAND_PREFIX
        _HELPER_COMMAND_PREFIX = root_helper


@classmethod
def from_file(cls, fn, plain=False):
    """
        Constrant an instance from the file
        """
    out = cls()
    out.load_file(fn, plain)
    return out


def p_and_expr_1(p):
    """AndExpr : EqualityExpr"""
    p[0] = p[1]


def _get_size_for_dev(device):
    """
    @param device: the device
    @type device: pyudev.Device
    @return: the size in logical blocks, 0 if none found
    @rtype: int
    """
    attributes = device.attributes
    try:
        sect_size = attributes.asint('size')
    except (KeyError, UnicodeDecodeError, ValueError):
        return 0
    if device['DEVTYPE'] == 'partition':
        attributes = device.parent.attributes
    try:
        logical_block_size = attributes.asint('queue/logical_block_size')
    except (KeyError, UnicodeDecodeError, ValueError):
        return 0
    return sect_size * 512 // logical_block_size


@classmethod
def origin_index(cls, index):
    """Return the equivalent index when the supershape is at the origin."""
    row, col = index
    origin_row = 0
    origin_col = col % 3
    return origin_row, origin_col


def uniquify(md):
    """
    makes unique and preserves list order
    """
    res = []
    for m in md:
        if m not in res:
            res.append(m)
    return res


def get_manifold_version():
    """Easy function to get the current Manifold version
    :return: str of version
    """
    import manifold
    return manifold.__version__


def marker_jump(next: bool=True):
    """Jump to previous/next marker

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


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

        :param SsoChangeLogoutUrlType val:
        :rtype: EventType
        """
    return cls('sso_change_logout_url', val)


def checkConfig(otherStatusReceivers):
    """Verify that there are no other status receivers which conflict with
        the current one.

        @type  otherStatusReceivers: A list of L{IStatusReceiver} objects which
        will contain self.
        """


@classmethod
def from_dict(cls, d) ->'OASRequest':
    """Create the request domain model from a dict.

        This also validates the dict's schema and raises a :code:`ValidationError`
        if any required keys are missing or the data is malformed.

        :param d: The dict to deserialize from
        :return: The domain model with the data from :code:`d` filled in
        """
    return cls()


@staticmethod
def xor_strings(subject, modifier, shift=0):
    """
        Операция XOR для двух строк
        """
    subject, modifier = list(subject), list(modifier)
    i, j = shift, 0
    while len(subject) > i:
        subject[i] = subject[i] ^ modifier[j]
        i += 1
        j += 1
        if j >= len(modifier):
            j = 0
    return bytearray(subject)


def is_query(client, command_input, service_id=None, timeout=60):
    """Invokes a read-only query on the given infrastructure service instance.
    """
    client.invoke_infrastructure_query(command_input, service_id, timeout)


@staticmethod
def _calc_total_recording_time(epochlength_in_min, lights_on, lights_off):
    """
        returns the recording time in minutes, excluding lights on at begin and end
        :param epochlength_in_min:
        :param lights_on:
        :param lights_off:
        :return: RTR [min]
        """
    return (lights_on - lights_off) * epochlength_in_min


def is_integer(obj):
    """Test if input object is an integer.

    > *Input arguments*

    * `obj`: Input variable.

    > *Returns*

    `True`, if `obj` is a integer.
    """
    import numpy as np
    return isinstance(obj, int) or isinstance(obj, np.int64)


@staticmethod
def _from_db_object(magnum_service, db_magnum_service):
    """Converts a database entity to a formal object."""
    for field in magnum_service.fields:
        magnum_service[field] = db_magnum_service[field]
    magnum_service.obj_reset_changes()
    return magnum_service


@classmethod
def header_hash(cls, header):
    """Given a header return the hash."""
    import x11_hash
    return x11_hash.getPoWHash(header)


def list_user_pools(NextToken=None, MaxResults=None):
    """
    Lists the user pools associated with an AWS account.
    See also: AWS API Documentation

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

    :type NextToken: string
    :param NextToken: An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

    :type MaxResults: integer
    :param MaxResults: [REQUIRED]
            The maximum number of results you want the request to return when listing the user pools.

    :rtype: dict
    :return: {
        'UserPools': [
            {
                'Id': 'string',
                'Name': 'string',
                'LambdaConfig': {
                    'PreSignUp': 'string',
                    'CustomMessage': 'string',
                    'PostConfirmation': 'string',
                    'PreAuthentication': 'string',
                    'PostAuthentication': 'string',
                    'DefineAuthChallenge': 'string',
                    'CreateAuthChallenge': 'string',
                    'VerifyAuthChallengeResponse': 'string'
                },
                'Status': 'Enabled'|'Disabled',
                'LastModifiedDate': datetime(2015, 1, 1),
                'CreationDate': datetime(2015, 1, 1)
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


@staticmethod
def _convert(x):
    """Helper conversion function: if rgb[0]>0 then (0x80 * rgb[0])+0x20000000 else 0x00"""
    if x > 0:
        x = 128 * x + 536870912
    return x


@staticmethod
def zoom_factor(width: int, height: int, x_right: float, x_left: float,
    y_top: float, y_bottom: float) ->float:
    """Calculate the zoom factor."""
    x_diff = x_left - x_right
    y_diff = y_top - y_bottom
    x_diff = x_diff if x_diff else 1.0
    y_diff = y_diff if y_diff else 1.0
    if width / x_diff < height / y_diff:
        return width / x_diff
    else:
        return height / y_diff


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Nest thermostat.

    No longer in use.
    """


def list_thing_principals(thingName=None):
    """
    Lists the principals associated with the specified thing.
    See also: AWS API Documentation

    :example: response = client.list_thing_principals(
        thingName='string'
    )

    :type thingName: string
    :param thingName: [REQUIRED]
            The name of the thing.

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

    """
    pass


@classmethod
def from_evt(cls, evt):
    """
        Initializes a new instance of given class by copying all data.

        Args:
            evt: pero.MouseEvt
                Source event from which to copy the data.

        Returns:
            cls instance
                New instance of requested class.
        """
    return cls(native=evt.native, view=evt.view, control=evt.control, x_pos
        =evt.x_pos, y_pos=evt.y_pos, x_rot=evt.x_rot, y_rot=evt.y_rot,
        left_down=evt.left_down, middle_down=evt.middle_down, right_down=
        evt.right_down, alt_down=evt.alt_down, cmd_down=evt.cmd_down,
        ctrl_down=evt.ctrl_down, shift_down=evt.shift_down)


def index_of_dict_in_list(l, value, key=None):
    """Get index of item (a dict) in list

    # Example:
    ```python
    l = [
        {'a': 1},
        {'a': 2},
        {'a': 3}
    ]
    index_of_dict_in_list(l, 2) # returns 1
    ```
    """
    if key is None:
        for i, d in enumerate(l):
            v, = d.values()
            if v == value:
                return i
    else:
        for i, d in enumerate(l):
            if d[key] == value:
                return i
    raise ValueError('No value matched')


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

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


def fetch_reads(samfile, chrom, start, end, rm_duplicate=True, inner_only=
    True, mapq_min=0, mismatch_max=10 ** 5, rlen_min=1, is_mated=True):
    """To fetch the reads in a given region from a pysam AlignmentFile.

    Args:
        samfile: A Samfile object in pysam.
        chrom: A string of chromosome, e.g., "IV", "chr10".
        start: An integer of the start position for mapped reads.
        end: An integer of the end position for mapped reads.
        rm_duplicate: A bool for only keeping the first one of duplicates.
        inner_only: A bool for only keeping fully region matched reads.
        mapq_min: An integer of the minimum of map quality.
        mismatch_min: An integer of the minimum of mismatched bases.
        rlen_min: An integer of the minimum of read length.
        is_paired: A bool for mating paired-end reads.

    Returns:
        A dict containing lists of mated reads1 and reads2, and unmated reads1u
        and reads2u, i.e.,
        {'reads1': [r11, r21, ...]
         'reads2': [r12, r22, ...]
         'reads1u': [r*1, r*1, ...]
         'reads2u': [r*2, r*2, ...]}
        reads1 is the 5-end of the fragment, and reads2 is the 3-end of the
        fragment.

    Raises:
        ValueError: An error occurred when fetching reads.
        AssertionError: An error occurred when fetching reads.
    """
    chrom = str(chrom)
    if chrom in samfile.references:
        pass
    else:
        chrom_parts = chrom.split('chr')
        if len(chrom_parts) <= 1:
            chrom = chrom_parts[0]
        else:
            chrom = chrom_parts[1]
    try:
        reads = samfile.fetch(chrom, start, end)
    except ValueError:
        reads = []
        print('Cannot fetch reads in region: %s:%d-%d' % (chrom, start, end))
    except AssertionError:
        reads = []
        print('AssertionError in region: %s:%d-%d' % (chrom, start, end))
        print(' - Check that your BAM file is indexed!')
    qname1, qname2 = [], []
    reads1, reads2 = [], []
    r_prev = None
    for r in reads:
        if (rm_duplicate and r_prev is not None and r_prev.qname == r.qname and
            r_prev.positions == r.positions):
            r_prev = r
            continue
        r_prev = r
        if inner_only == True and (r.pos < start or r.aend > end):
            continue
        if r.mapq < mapq_min:
            continue
        if r.rlen - len(r.positions) > mismatch_max:
            continue
        if r.rlen < rlen_min:
            continue
        if r.is_read2:
            reads2.append(r)
            qname2.append(r.qname)
        else:
            reads1.append(r)
            qname1.append(r.qname)
    FLAG = True
    if len(qname1) > 0:
        for i in range(len(qname1) - 1):
            if qname1[i][-1] != qname1[i + 1][-1]:
                FLAG = False
                break
    if FLAG and len(qname2) > 0:
        for i in range(len(qname1) - 1):
            if qname1[i][-1] != qname1[i + 1][-1]:
                FLAG = False
                break
    if FLAG:
        for i in range(len(qname1)):
            qname1[i] = qname1[i][:-1]
        for i in range(len(qname2)):
            qname2[i] = qname2[i][:-1]
    rv_reads1, rv_reads2 = [], []
    rv_reads1u, rv_reads2u = [], []
    if is_mated == True:
        idx1 = sorted(range(len(qname1)), key=qname1.__getitem__)
        idx2 = sorted(range(len(qname2)), key=qname2.__getitem__)
        i1, i2 = 0, 0
        while i1 < len(idx1) and i2 < len(idx2):
            if qname1[idx1[i1]] == qname2[idx2[i2]]:
                rv_reads1.append(reads1[idx1[i1]])
                rv_reads2.append(reads2[idx2[i2]])
                i1, i2 = i1 + 1, i2 + 1
            elif qname1[idx1[i1]] < qname2[idx2[i2]]:
                rv_reads1u.append(reads1[idx1[i1]])
                i1 += 1
            elif qname1[idx1[i1]] > qname2[idx2[i2]]:
                rv_reads2u.append(reads2[idx2[i2]])
                i2 += 1
        for i in range(i1, len(idx1)):
            rv_reads1u.append(reads1[idx1[i]])
        for i in range(i2, len(idx2)):
            rv_reads2u.append(reads2[idx2[i]])
    else:
        rv_reads1u, rv_reads2u = reads1, reads2
    RV = {}
    RV['reads1'] = rv_reads1
    RV['reads2'] = rv_reads2
    RV['reads1u'] = rv_reads1u
    RV['reads2u'] = rv_reads2u
    return RV


@classmethod
def update_source_instance_status(cls, source_instance, status_ok, oldnew_check
    ):
    """ Updates state on given source_instance
            Returns True if source_instance have triggered a value change
        """
    value = source_instance.get
    stime = source_instance.source_time
    return cls.update_source_instance_value(source_instance, value, stime,
        status_ok, oldnew_check)


def object_image_guess(obj, bm=None):
    """
    Return a single image used by the object,
    first checking the texture-faces, then the material.
    """
    me = obj.data
    if bm is None:
        if obj.mode == 'EDIT':
            import bmesh
            bm = bmesh.from_edit_mesh(me)
    if bm is not None:
        tex_layer = bm.faces.layers.tex.active
        if tex_layer is not None:
            for f in bm.faces:
                image = f[tex_layer].image
                if image is not None:
                    return image
    else:
        tex_layer = me.uv_textures.active
        if tex_layer is not None:
            for tf in tex_layer.data:
                image = tf.image
                if image is not None:
                    return image
    for m in obj.data.materials:
        if m is not None:
            for mtex in reversed(m.texture_slots):
                if mtex and mtex.use_map_color_diffuse:
                    texture = mtex.texture
                    if texture and texture.type == 'IMAGE':
                        image = texture.image
                        if image is not None:
                            return image
    return None


def invoke_async(FunctionName=None, InvokeArgs=None):
    """
    Submits an invocation request to AWS Lambda. Upon receiving the request, Lambda executes the specified function asynchronously. To see the logs generated by the Lambda function execution, see the CloudWatch Logs console.
    This operation requires permission for the lambda:InvokeFunction action.
    See also: AWS API Documentation

    Examples
    This operation invokes a Lambda function asynchronously
    Expected Output:

    :example: response = client.invoke_async(
        FunctionName='string',
        InvokeArgs=b'bytes'|file
    )

    :type FunctionName: string
    :param FunctionName: [REQUIRED]
            The Lambda function name. Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 characters in length.

    :type InvokeArgs: bytes or seekable file-like object
    :param InvokeArgs: [REQUIRED]
            JSON that you want to provide to your Lambda function as input.

    :rtype: dict
    :return: {
        'Status': 123
    }

    """
    pass


@classmethod
def get_by_auth_password(cls, auth_id, password):
    """Returns a user object, validating password.

        :param auth_id:
            Authentication id.
        :param password:
            Password to be checked.
        :returns:
            A user object, if found and password matches.
        :raises:
            ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
        """


def build_absolute_uri(host_url, path=None):
    """Build absolute URI with given (optional) path"""
    path = path or ''
    if path.startswith('http://') or path.startswith('https://'):
        return path
    if host_url.endswith('/') and path.startswith('/'):
        path = path[1:]
    return host_url + path


@classmethod
def reset(cls):
    """Reset the registry to the standard codecs."""
    cls._codecs = {}
    c = cls._codec
    for name, encode, decode in cls._common_codec_data:
        cls._codecs[name] = c(encode, decode)


@staticmethod
def from_affine(affine_point):
    """ A no-op since the point is already affine.

        Args:
            affine_point (ECPointAffine): A Affine point

        Returns:
            ECPointAffine: Returns the input arg.
        """
    return affine_point


def is_task_stub_mutable(context, task_stub):
    """Return True if the task stub is mutable in this context."""
    if context.is_admin:
        return True
    if context.owner is None:
        return False
    return task_stub.owner == context.owner


def _deg(f):
    """
    Compute the degree of a multivariate polynomial
    `f \\in K[x_0, \\ldots, x_{k-2}, y] \\cong K[y][x_0, \\ldots, x_{k-2}]`.

    Parameters
    ==========

    f : PolyElement
        polynomial in `K[x_0, \\ldots, x_{k-2}, y]`

    Returns
    =======

    degf : Integer tuple
        degree of `f` in `x_0, \\ldots, x_{k-2}`

    Examples
    ========

    >>> R, x, y = ring('x, y', ZZ)

    >>> f = x**2*y**2 + x**2*y - 1
    >>> _deg(f)
    (2,)

    >>> R, x, y, z = ring('x, y, z', ZZ)

    >>> f = x**2*y**2 + x**2*y - 1
    >>> _deg(f)
    (2, 2)

    >>> f = x*y*z - y**2*z**2
    >>> _deg(f)
    (1, 1)

    """
    k = f.ring.ngens
    degf = (0,) * (k - 1)
    for monom in f:
        if monom[:-1] > degf:
            degf = monom[:-1]
    return degf


def variational_distance_pmf(p, q):
    """
    Compute the variational distance.

    Parameters
    ----------
    p : np.ndarray
        The first pmf.
    q : np.ndarray
        The second pmf.

    Returns
    -------
    vd : float
        The variational distance.

    Notes
    -----
    `p` and `q` are assumed to be 1-to-1 with regards to events.
    """
    return abs(p - q).sum() / 2


def _set_global_detection_thresh(params, name: str, index: int, value: float):
    """Adjust the Parameters.global_detection_thresh parameter"""
    if index is not None:
        raise IndexError(
            'You cannot index the global_detection_thresh parameter')
    params.global_detection_thresh = value


def clear_memoized_methods(obj, *method_names):
    """
    Clear the memoized method or @memoizeproperty results for the given
    method names from the given object.

    >>> v = [0]
    >>> def inc():
    ...     v[0] += 1
    ...     return v[0]
    ...
    >>> class Foo(object):
    ...    @memoizemethod
    ...    def foo(self):
    ...        return inc()
    ...    @memoizeproperty
    ...    def g(self):
    ...       return inc()
    ...
    >>> f = Foo()
    >>> f.foo(), f.foo()
    (1, 1)
    >>> clear_memoized_methods(f, 'foo')
    >>> (f.foo(), f.foo(), f.g, f.g)
    (2, 2, 3, 3)
    >>> (f.foo(), f.foo(), f.g, f.g)
    (2, 2, 3, 3)
    >>> clear_memoized_methods(f, 'g', 'no_problem_if_undefined')
    >>> f.g, f.foo(), f.g
    (4, 2, 4)
    >>> f.foo()
    2
    """
    for key in list(getattr(obj, '_memoized_results', {}).keys()):
        if key[0] in method_names:
            del obj._memoized_results[key]
    property_dict = obj._cache_
    for prop in method_names:
        inner_attname = '__%s' % prop
        if inner_attname in property_dict:
            del property_dict[inner_attname]


def create_thing(thingName=None, thingTypeName=None, attributePayload=None):
    """
    Creates a thing record in the thing registry.
    See also: AWS API Documentation

    :example: response = client.create_thing(
        thingName='string',
        thingTypeName='string',
        attributePayload={
            'attributes': {
                'string': 'string'
            },
            'merge': True|False
        }
    )

    :type thingName: string
    :param thingName: [REQUIRED]
            The name of the thing to create.

    :type thingTypeName: string
    :param thingTypeName: The name of the thing type associated with the new thing.

    :type attributePayload: dict
    :param attributePayload: The attribute payload, which consists of up to three name/value pairs in a JSON document. For example:
            {'attributes':{'string1':'string2'}})
            attributes (dict) --A JSON string containing up to three key-value pair in JSON format. For example:
            {'attributes':{'string1':'string2'}})
            (string) --
            (string) -- An attribute value for an Thing. An empty or null value in Update means that existing value for that attribute should be deleted. Empty and null values in create are ignored.

            merge (boolean) --Specifies whether the list of attributes provided in the AttributePayload is merged with the attributes stored in the registry, instead of overwriting them.
            To remove an attribute, call UpdateThing with an empty attribute value.
            Note
            The merge attribute is only valid when calling UpdateThing .

    :rtype: dict
    :return: {
        'thingName': 'string',
        'thingArn': 'string'
    }

    """
    pass


def ingredients(count):
    """Prints ingredients for making `count` arepas."""
    print('{:.2} cups arepa flour'.format(0.1 * count))
    print('{:.2} cups cheese'.format(0.1 * count))
    print('{:.2} cups water'.format(0.025 * count))


def concat(funcname, args):
    """Return args spliced by sql concat operator."""
    return ' || '.join(args)


def _warning_on_one_line(message, category, filename, lineno, file=None,
    line=None):
    """Formats warning messages to appear on one line."""
    return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)


@staticmethod
def deduce_id(deduce_from: str) ->str:
    """
        Try and return a deduced identifier.

        An identifier must be a lowercase version of the given data with only
        letters.  Spaces in the data are replaced with the
        underscore (_).  A tabulation will break parsing.  Letters are
        copied as-is.  Non-letter symbols are just ignored.

        Args:
            deduce_from (str): the origin or the identifier to deduce.

        Examples:
            >>> Component.deduce_id("click me!")
            `click_me`
            >>> Component.deduce_id("Quit	CTRL + Q")
            'quit'

        """
    identifier = ''
    for char in deduce_from:
        if char.isalpha():
            identifier += char.lower()
        elif char == ' ' and not identifier.endswith('_'):
            identifier += '_'
        elif char == '\t':
            break
    return identifier.strip('_')


@classmethod
def clear_cache(cls):
    """Remove all items from the cache."""
    with cls.ca_lock:
        cls.cache = {}
        cls.timeouts = {}


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


def is_detritus(subp):
    """Return True if the supplied path is detritus, False otherwise"""
    return subp.endswith('.THIS') or subp.endswith('.BASE') or subp.endswith(
        '.OTHER') or subp.endswith('~') or subp.endswith('.tmp')


def save_as(snd, filename):
    """Save sound snd to filename."""
    snd.save_as(filename)


@classmethod
def from_file(cls, filepath, features='lxml', builder=None, parse_only=None,
    from_encoding=None, exclude_encodings=None, **kwargs):
    """Alternate constructor to init soup from filepath.

        Args:
            filepath (str): Path to file holding HTML.

        Returns:
            Sauce: A soup object with added functionality.
        """
    with open(filepath, 'r') as f:
        return cls(f, features, builder, parse_only, from_encoding,
            exclude_encodings, **kwargs)


def empty_when_none(_string=None):
    """If _string if None, return an empty string, otherwise return string.
    """
    if _string is None:
        return ''
    else:
        return str(_string)


def mk_graph(cnf):
    """
    Generates a variable relationship graph.

    In this graph there is one vertex per VARIABLE (thus we do not
    distinguish between the two possible literals for a var) and there is
    one edge between two variables iff their literals belong to one same
    clause.

    .. note::
        The dimacs CNF format declares way more variables than are actually
        used. This is a waste of resources and it makes the output cluttered
        and hardly analyzable.
    """
    import igraph
    counter = 0
    canonical = {}
    edgelist = []
    lit_attr = []
    for clause in cnf.clauses_list:
        for i in range(len(clause)):
            for j in range(i + 1, len(clause)):
                source = abs(clause[i])
                dest = abs(clause[j])
                if source not in canonical:
                    canonical[source] = counter
                    lit_attr.append(source)
                    counter += 1
                if dest not in canonical:
                    canonical[dest] = counter
                    lit_attr.append(dest)
                    counter += 1
                c_src = canonical[source]
                c_dst = canonical[dest]
                edgelist.append((c_src, c_dst))
    return igraph.Graph(n=counter, edges=edgelist, vertex_attrs={'lit':
        lit_attr})


def PSMessage(action, options):
    """Builds a message
    """
    return 'PSMessage', action, options


def styleNoDisplay(style: dict) ->bool:
    """ check whether the style defines not to display the element """
    return style.get('display', 'inline') == 'none' or style.get('visibility',
        'visible') == 'hidden' or style.get('visibility', 'visible'
        ) == 'collapse'


def _chunks(l, n):
    """
	Yield successive chunks from list  l with a minimum size  n
	"""
    for i in range(0, len(l), n):
        yield l[i:i + n]


@staticmethod
def minMaxDistance(obj1, obj2):
    """Computes the min max distance used for feature grouping"""
    commonTimeInterval = obj1.commonTimeInterval(obj2)
    if not commonTimeInterval.empty():
        minDistance = (obj1.getPositionAtInstant(commonTimeInterval.first) -
            obj2.getPositionAtInstant(commonTimeInterval.first)).norm2()
        maxDistance = minDistance
        for t in list(commonTimeInterval)[1:]:
            d = (obj1.getPositionAtInstant(t) - obj2.getPositionAtInstant(t)
                ).norm2()
            if d < minDistance:
                minDistance = d
            elif d > maxDistance:
                maxDistance = d
        return int(commonTimeInterval.length()), minDistance, maxDistance
    else:
        return int(commonTimeInterval.length()), None, None


def make_body(resource, parameters):
    """Creates body request using the parameters.

    :param resource: kind of resource
    :param parameters: list of parameters
    """
    content = {}
    for key in parameters.keys():
        content[key] = parameters[key]
    if resource:
        body = {resource: content}
    else:
        body = content
    return body


@classmethod
def global_config(cls, key, *args):
    """ This reads or sets the global settings stored in class.settings. """
    if args:
        cls.settings = cls.settings.copy()
        cls.settings[key] = args[0]
    else:
        return cls.settings[key]


def scattering(eigenvalues):
    """Compute the scattering of the local dataset

    See (Weinmann et al, 2015)

    Parameters
    ----------
    eigenvalues : numpy.array
        Set of normalized eigenvalues; must be (1, 3)-shaped

    Returns
    -------
    float
        Scattering
    """
    return eigenvalues[2] / eigenvalues[0]


def epicyclic_gearing_self_test():
    """
  This is the non-regression test of epicyclic_gearing.
  Look at the Tk window to check errors.
  """
    r_tests = [['simplest test',
        '--sun_gear_tooth_nb 20 --planet_gear_tooth_nb 31 --gear_module 1.0 --planet_nb 3'
        ], ['sun crenel',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --sun_axle_x_width 6 --sun_crenel_nb 2'
        ], ['planet crenel',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --planet_axle_diameter 8 --planet_crenel_nb 5'
        ], ['gearring crenel',
        '--sun_gear_tooth_nb 23 --planet_gear_tooth_nb 31 --gear_module 1.0 --holder_crenel_number 4'
        ], ['carrier with peripheral and crenel',
        '--sun_gear_tooth_nb 20 --planet_gear_tooth_nb 31 --gear_module 1.0 --planet_nb 3'
        ], ['carrier with peripheral and without crenel',
        '--sun_gear_tooth_nb 20 --planet_gear_tooth_nb 31 --gear_module 1.0 --planet_nb 3 --carrier_crenel_height 0'
        ], ['carrier without peripheral and with crenel',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --carrier_peripheral_disable --carrier_central_diameter 30.0'
        ], ['carrier without peripheral and crenel',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --carrier_peripheral_disable --carrier_crenel_height 0 --carrier_central_diameter 30.0'
        ], ['carrier without peripheral and small central circle',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --carrier_peripheral_disable --carrier_central_diameter 20.0'
        ], ['sun crenel circle',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --sun_axle_x_width 8 --sun_crenel_nb 6 --sun_crenel_type circle --sun_crenel_width 1.9 --sun_crenel_diameter 12'
        ], ['sun crenel circle marked',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --sun_axle_x_width 8 --sun_crenel_nb 6 --sun_crenel_type circle --sun_crenel_width 1.9 --sun_crenel_diameter 12 --sun_crenel_mark_nb 1'
        ], ['carrier crenel hole',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0 --carrier_hole_diameter 1.9'
        ], ['carrier crenel double hole',
        '--sun_gear_tooth_nb 17 --planet_gear_tooth_nb 31 --gear_module 1.0 --carrier_hole_diameter 1.0 --carrier_double_hole_length 2.0'
        ], ['holder crenel double hole',
        '--sun_gear_tooth_nb 17 --planet_gear_tooth_nb 31 --gear_module 1.0 --holder_hole_diameter 5.0 --holder_double_hole_diameter 3.0 --holder_double_hole_length 10.0 --holder_crenel_skin_width 2.0 --holder_crenel_position 3.0 --holder_crenel_height 2.0'
        ], ['gear simulation',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 33 --gear_module 1.0 --gear_addendum_dedendum_parity_slack 1.5 --simulate_2d eg_sim_annulus_planet'
        ], ['output file',
        '--sun_gear_tooth_nb 21 --planet_gear_tooth_nb 31 --gear_module 1.0 --input_gearwheel_tooth_nb 29 --output_file_basename test_output/epicyclic_self_test.dxf'
        ], ['output file2',
        '--sun_gear_tooth_nb 13 --planet_gear_tooth_nb 19 --gear_module 1.0 --holder_hole_diameter 1.0 --holder_crenel_position 2.0 --holder_crenel_height 2.0 --holder_crenel_width 6.0 --holder_crenel_skin_width 4.0 --input_gearwheel_tooth_nb 29 --input_gearwheel_module 1.0 --input_gearwheel_axle_diameter 19.0 --input_gearwheel_crenel_number 6 --input_gearwheel_crenel_position_diameter 24.0 --input_gearwheel_crenel_diameter 1.0 --input_cover_extra_space 0.5 --output_gearwheel_tooth_nb 13 --output_gearwheel_module 3.0 --output_gearwheel_axle_diameter 22.0 --output_gearwheel_crenel_number 6 --output_gearwheel_crenel_position_diameter 28.0 --output_gearwheel_crenel_diameter 3.0 --output_gearwheel_crenel_angle 0.3 --output_cover_extra_space 0.5 --output_file_basename test_output/epicyclic_self_test2.dxf'
        ], ['output file3',
        '--sun_gear_tooth_nb 13 --planet_gear_tooth_nb 19 --gear_module 1.0 --holder_hole_diameter 1.0 --holder_crenel_position 2.0 --holder_crenel_height 2.0 --holder_crenel_width 6.0 --holder_crenel_skin_width 4.0 --input_gearwheel_tooth_nb 45 --input_gearwheel_module 1.0 --input_gearwheel_axle_diameter 22.0 --input_gearwheel_crenel_number 6 --input_gearwheel_crenel_position_diameter 26.0 --input_gearwheel_crenel_diameter 1.0 --input_cover_extra_space 0.5 --output_gearwheel_tooth_nb 13 --output_gearwheel_module 3.0 --sun_crenel_nb 5 --sun_crenel_type circle --sun_crenel_mark_nb 2 --sun_crenel_diameter 8.0 --sun_crenel_width 1.0 --carrier_hole_position_diameter 38.0 --carrier_hole_diameter 1.0 --carrier_double_hole_length 3.0 --carrier_leg_hole_diameter 3.0 --output_file_basename test_output/epicyclic_self_test3.dxf'
        ], ['last test',
        '--sun_gear_tooth_nb 19 --planet_gear_tooth_nb 31 --gear_module 1.0']]
    return r_tests


def _a_decode_tuple(stream, offset, count, mapping):
    """
    'a1t3i123',3,1 --> 8,[123]
    'a2t1i41i2',3,1 --> 8,[4,2]
    """
    container = []
    for _ in range(count):
        index = offset
        while 48 <= ord(stream[index:index + 1]) <= 57:
            index += 1
        offset, value = mapping[stream[index:index + 1]](stream, index + 1,
            int(stream[offset:index]), mapping)
        container.append(value)
    return offset, tuple(container)


def get_language_settings(language_code, site_id=None):
    """
    Return the language settings for the current site
    """
    from parler import appsettings
    return appsettings.PARLER_LANGUAGES.get_language(language_code, site_id)


def _int_arg(s):
    """Convert a string argument to an integer for use in a template
    function.  May raise a ValueError.
    """
    return int(s.strip())


def get_silva_object():
    """Used by acquisition to get the nearest containing
        SilvaObject.
        """


def equal_attributes(obj1, obj2, attributes):
    """Compare two objects attributes"""
    if not attributes:
        return False
    temp1, temp2 = object(), object()
    for attr in attributes:
        if callable(attr):
            if attr(obj1) != attr(obj2):
                return False
        elif getattr(obj1, attr, temp1) != getattr(obj2, attr, temp2):
            return False
    return True


def process(proc_data):
    """
    Final processing to conform to the schema.

    Parameters:

        proc_data:   (dictionary) raw structured data to process

    Returns:

        Dictionary. Structured data with the following schema:

        {
          "variables": [
            "name":               string,
            "value":              string
          ],
          "schedule": [
            {
              "occurrence"        string,
              "minute": [
                                  string
              ],
              "hour": [
                                  string
              ],
              "day_of_month": [
                                  string
              ],
              "month": [
                                  string
              ],
              "day_of_week": [
                                  string
              ],
              "occurrence":       string,
              "command":          string
            }
          ]
        }

    """
    try:
        for entry in proc_data['schedule']:
            entry['minute'] = entry['minute'].split(',')
            entry['hour'] = entry['hour'].split(',')
            entry['day_of_month'] = entry['day_of_month'].split(',')
            entry['month'] = entry['month'].split(',')
            entry['day_of_week'] = entry['day_of_week'].split(',')
    except KeyError:
        pass
    return proc_data


def __delattr__(cls, name):
    """
        Remove an attribute from the class, clearing `_unbound_fields` if
        needed.
        """
    if not name.startswith('_'):
        cls._unbound_fields = None
    type.__delattr__(cls, name)


def ask_user(msg, bypass=False):
    """
    Asks the user yes no questions

    Args:
        msg: question to display
        bypass: Handle passing yes always
    Returns:
        response: boolean indicating whether to proceed or not.
    """
    acceptable = False
    while not acceptable:
        if bypass:
            ans = 'yes'
        else:
            ans = input(msg + ' (y/n)\n')
        if ans.lower() in ['y', 'yes']:
            acceptable = True
            response = True
        elif ans.lower() in ['n', 'no']:
            acceptable = True
            response = False
        else:
            print('Unrecognized answer, please use (y, yes, n, no)')
    return response


def get_stream_enc(stream, default=None):
    """Return the given stream's encoding or a default.

    There are cases where ``sys.std*`` might not actually be a stream, so
    check for the encoding attribute prior to returning it, and return
    a default if it doesn't exist or evaluates as False. ``default``
    is None if not provided.
    """
    if not hasattr(stream, 'encoding') or not stream.encoding:
        return default
    else:
        return stream.encoding


def get_item_properties(item, fields, mixed_case_fields=(), formatters=None):
    """Return a tuple containing the item properties.

    :param item: a single item resource (e.g. Server, Tenant, etc)
    :param fields: tuple of strings with the desired field names
    :param mixed_case_fields: tuple of field names to preserve case
    :param formatters: dictionary mapping field names to callables
       to format the values
    """
    if formatters is None:
        formatters = {}
    row = []
    for field in fields:
        if field in formatters:
            row.append(formatters[field](item))
        else:
            if field in mixed_case_fields:
                field_name = field.replace(' ', '_')
            else:
                field_name = field.lower().replace(' ', '_')
            if not hasattr(item, field_name) and isinstance(item, dict):
                data = item[field_name]
            else:
                data = getattr(item, field_name, '')
            if data is None:
                data = ''
            row.append(data)
    return tuple(row)


def fix_team_tricode(tricode):
    """
    Some of the tricodes are different than how I want them

    :param tricode: 3 letter team name - ex: NYR

    :return: fixed tricode
    """
    fixed_tricodes = {'TBL': 'T.B', 'LAK': 'L.A', 'NJD': 'N.J', 'SJS': 'S.J'}
    if tricode.upper() in list(fixed_tricodes.keys()):
        return fixed_tricodes[tricode.upper()]
    else:
        return tricode


def _decode_slice(s, size):
    """Find (start, stop, step, length) information that an extended slice
    represents in terms of indexes into a collection of the given size.
    Note that this function exists because slice.indices doesn't correctly decode these
    in some cases.

    :s: slice object
    :size: the size of the collection
    """
    if not isinstance(s, slice):
        raise TypeError('s must be a slice object')
    if not isinstance(size, int):
        raise TypeError('size must be an integer')
    if size < 0:
        raise ValueError('size must not be negative')
    if s.step is None:
        step = 1
    elif not isinstance(s.step, int):
        raise TypeError('step must be an integer')
    else:
        step = s.step
    if step == 0:
        raise ValueError('step must not be zero')
    if step < 0:
        if s.start is None:
            start = size - 1
        elif not isinstance(s.start, int):
            raise TypeError('start must be an integer')
        else:
            start = s.start
            if start >= size:
                start = size - 1
            elif start < 0:
                start += size
                if start < 0:
                    start = step
        if s.stop is None:
            stop = -1
        elif not isinstance(s.stop, int):
            raise TypeError('stop must be an integer')
        else:
            stop = s.stop
            if stop < 0:
                stop += size
                if stop < 0:
                    stop = -1
        if stop > start:
            stop = start
        else:
            stop += (start - stop) % step
        assert size > start >= stop >= step
    else:
        if s.start is None:
            start = 0
        elif not isinstance(s.start, int):
            raise TypeError('start must be an integer')
        else:
            start = s.start
            if start >= size:
                start = size
            elif start < 0:
                start += size
                if start < 0:
                    start = 0
        if s.stop is None:
            stop = size
        elif not isinstance(s.stop, int):
            raise TypeError('stop must be an integer')
        else:
            stop = s.stop
            if stop > size:
                stop = size
            elif stop < 0:
                stop += size
                if stop < 0:
                    stop = start
        if stop <= start:
            stop = start
        else:
            stop += (start - stop) % step
        assert 0 <= start <= stop <= size + step
    length, modulus = divmod(stop - start, step)
    assert length >= 0
    assert modulus == 0
    return start, stop, step, length


def start_child_span(parent_span, operation_name, tags=None, start_time=None):
    """A shorthand method that starts a child_of span for a given parent span.

    Equivalent to calling

        parent_span.tracer().start_span(
            operation_name,
            references=opentracing.child_of(parent_span.context),
            tags=tags,
            start_time=start_time)

    :param parent_span: the Span which will act as the parent in the returned
        Span's child_of reference.
    :param operation_name: the operation name for the child Span instance
    :param tags: optional dict of Span Tags. The caller gives up ownership of
        that dict, because the Tracer may use it as-is to avoid extra data
        copying.
    :param start_time: an explicit Span start time as a unix timestamp per
        time.time().

    :return: Returns an already-started Span instance.
    """
    return parent_span.tracer.start_span(operation_name=operation_name,
        child_of=parent_span, tags=tags, start_time=start_time)


@staticmethod
def func_substitute(header, lines):
    """Returns modified lines and whether string changed.

        Keyword arguments:
        header -- Header object
        lines -- file contents string

        Returns modified file contents string
        """
    pos = 0
    while pos < len(lines):
        old_length = len(lines)
        match = header.func_regex.search(lines, pos)
        if not match:
            break
        pos = match.start(1) + len(header.prefix) + len(match.group(1))
        if match.group(1) in header.func_names:
            lines = lines[0:match.start(1)] + header.prefix + match.group(1
                ) + lines[match.end(1):]
    return lines


def get_version_v2(base_uri):
    """
    Canned response for keystone v2 version.

    Cf: http://developer.openstack.org/api-ref-identity-v2.html#listVersions-v2
    """
    return {'version': {'status': 'stable', 'updated':
        '2014-04-17T00:00:00Z', 'media-types': [{'base': 'application/json',
        'type': 'application/vnd.openstack.identity-v2.0+json'}], 'id':
        'v2.0', 'links': [{'href': base_uri.rstrip('/') + '/identity/v2.0',
        'rel': 'self'}, {'href': 'http://docs.openstack.org/', 'type':
        'text/html', 'rel': 'describedby'}]}}


def disable_endpoint_for_tenant(tenant_id, template_id):
    """
        Disable an endpoint for a specific tenant.

        :param six.text_type tenant_id: tenant id to operate on
        :param six.text_type template_id: endpoint template id to disable
        :raises: ValueError if template is not enabled for the tenant
        """


def calc_target_joint_dimension(joint_list):
    """Calculate Total Degrees of Freedom from joint list

    Parameters
    ----------
    joint_list : list[skrobot.model.Joint]

    Returns
    -------
    n : int
        total Degrees of Freedom
    """
    n = 0
    for j in joint_list:
        n += j.joint_dof
    return n


def _get_default_world(default_world=None, num_agents=None):
    """
    Get default world if a world is not already specified by the task.

    If a default world is provided, return this. Otherwise, return
    DialogPartnerWorld if there are 2 agents and MultiAgentDialogWorld if
    there are more.

    :param default_world:
        default world to return
    :param num_agents:
        number of agents in the environment
    """
    if default_world is not None:
        world_class = default_world
    elif num_agents is not None:
        import parlai.core.worlds as core_worlds
        world_name = ('DialogPartnerWorld' if num_agents == 2 else
            'MultiAgentDialogWorld')
        world_class = getattr(core_worlds, world_name)
    else:
        return None
    return world_class


def get_code(module):
    """
    Compile and return a Module's code object.
    """
    fp = open(module.path)
    try:
        return compile(fp.read(), str(module.name), 'exec')
    finally:
        fp.close()


def is_lock(lock):
    """
    Tests if the given lock is an instance of a lock class
    """
    if lock is None:
        return False
    for attr in ('acquire', 'release', '__enter__', '__exit__'):
        if not hasattr(lock, attr):
            return False
    return True