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

        :param DeviceApprovalsAddExceptionDetails val:
        :rtype: EventDetails
        """
    return cls('device_approvals_add_exception_details', val)


def convert_unit(value, ppi=72):
    """
    Function to convert size given in some unit to pixels, following the
    https://www.w3.org/TR/2008/REC-CSS2-20080411/syndata.html#length-units

    Parameters:
    -----------

    value, str or int:
        The given size followed by it's unit. Fixed units are (in, cm,
        mm, pt, pc). Relative units are (em, ex, %)

    ppi, int, optional:
        The number of pixel per inch (Latex use 72)
    """
    value = str(value)
    if 'px' in value:
        value = '%0.1f' % float(value.replace('px', ''))
    if 'mm' in value:
        value = '%fcm' % (float(value.replace('mm', '')) * 10 ** -1)
    if 'cm' in value:
        value = '%fin' % (float(value.replace('cm', '')) * (1 / 2.54))
    if 'pc' in value:
        value = '%fin' % float(value.replace('pc', '') * 12)
    if 'pt' in value:
        value = '%fin' % (float(value.replace('pt', '')) * (1 / 72.0))
    if 'in' in value:
        out = float(value.replace('in', '')) * ppi
    else:
        out = float(value)
    return out


@classmethod
def get_url(cls):
    """
        Gets the URL to the World Overview page in Tibia.com

        Returns
        -------
        :class:`str`
            The URL to the World Overview's page.
        """
    return 'https://www.tibia.com/community/?subtopic=worlds'


def draw_root_fret_markers(draw, instrument, text_top_area,
    text_bottom_area, image_height, palette):
    """Add the fret markers to the root finder image"""
    for fret_pos in instrument.marker_positions:
        x_pos = instrument.margin / 2 + instrument.nut_width / 2 + fret_pos * (
            instrument.fret_spacing / 4) - instrument.fret_spacing / 8
        if fret_pos in instrument.double_markings:
            y_pos = text_top_area + (image_height - text_top_area -
                text_bottom_area) / 3
            draw.ellipse((x_pos - instrument.marker_size / 3, y_pos -
                instrument.marker_size / 3, x_pos + instrument.marker_size /
                3, y_pos + instrument.marker_size / 3), palette.
                fret_marker_colour)
            y_pos = image_height - text_bottom_area - (image_height -
                text_top_area - text_bottom_area) / 3
            draw.ellipse((x_pos - instrument.marker_size / 3, y_pos -
                instrument.marker_size / 3, x_pos + instrument.marker_size /
                3, y_pos + instrument.marker_size / 3), palette.
                fret_marker_colour)
        else:
            y_pos = (image_height - text_top_area - text_bottom_area
                ) / 2 + text_top_area
            draw.ellipse((x_pos - instrument.marker_size / 3, y_pos -
                instrument.marker_size / 3, x_pos + instrument.marker_size /
                3, y_pos + instrument.marker_size / 3), palette.
                fret_marker_colour)
    return draw


@staticmethod
def get_record_caller_info(record):
    """ Make a single-field human-readable combined caller info """
    result = '%s:%s:%s' % (record.pathname, record.lineno, record.funcName)
    return result


@classmethod
def get_current(cls, app, os_image, tag):
    """
        Given an app, OS image, and a tag, look for a build that matches
        all three and was successfully built (or is currently building).
        If not found, return None.
        """
    builds = cls.objects.filter(app=app, os_image=os_image, tag=tag).exclude(
        status='expired').exclude(status='failed').order_by('-id')
    return next(iter(builds), None)


def read_config_file(filename):
    """
    Read a simple ``'='``-delimited config file.
    Raises :const:`IOError` if unable to open file, or :const:`ValueError`
    if an parse error occurs.
    """
    f = open(filename)
    try:
        cfg = {}
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):
                try:
                    key, value = line.split('=', 1)
                    cfg[key] = value
                except ValueError:
                    pass
    finally:
        f.close()
    return cfg


def end_comp(n_current_comp, tmp_components, final_components, cnt_wcc_id):
    """
    Store the component
    :param n_current_comp:
    :param tmp_components:
    :param storage_path:
    :return:
    """
    comp_to_store = tmp_components[n_current_comp]
    comp_to_store.id = cnt_wcc_id
    final_components.append(comp_to_store)
    tmp_components[n_current_comp] = None
    cnt_wcc_id += 1
    return cnt_wcc_id


def _get_responses(link):
    """
    Returns minimally acceptable responses object based
    on action / method type.
    """
    template = {'description': ''}
    if link.action.lower() == 'post':
        return {'201': template}
    if link.action.lower() == 'delete':
        return {'204': template}
    return {'200': template}


def qualify_symbol(symname, ns):
    """Build a fully-qualified symbol name from a name & part of namespace."""
    if ns[0] == '.':
        ns = 'py2neo' + ns
    if ns[-1] == '.':
        ns += symname
    return tuple(ns.rsplit('.', 1))


def dot2(v1, v2):
    """Obtiene el producto escalar de dos vectores"""
    return float(v1.x) * float(v2.x) + float(v1.y) * float(v2.y)


def polynomialFit3(x, b0, b1, b2, b3):
    """
    Taylor polynomial for fit
    b1 = GD
    b2 = GDD / 2
    b3 = TOD / 6

    """
    return b0 + b1 * x + b2 * x ** 2 + b3 * x ** 3


def is_github_url(url):
    """Tell if a given URL matches a Github one.

    Args:
        url (str): The URL to test. It can be None.

    Returns:
        bool: False if the URL is not a string or if it doesn't match a Github URL

    """
    if isinstance(url, str):
        return url.startswith('https://github.com/') or url.startswith(
            'ssh://github.com/')
    else:
        return False


def is_valid_app_config(app_config):
    """
    Checks if provided app_config is valid. Tries to get namespace.
    """
    return getattr(app_config, 'namespace', None)


def get_all_clouds(session, return_type=None, **kwargs):
    """
    Retrieves details for all available storage clouds.

    :type session: zadarapy.session.Session
    :param session: A valid zadarapy.session.Session object.

    :type return_type: str
    :param return_type: If this is set to the string 'json', this function
        will return a JSON string.  Otherwise, it will return a Python
        dictionary.  Optional (will return a Python dictionary by default).

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    path = '/api/providers.json'
    return session.get_api(path=path, return_type=return_type, **kwargs)


@staticmethod
def get_uti_type(flp) ->str:
    """
        Get the Apple conform UTI Type from a flp instance which has been used on the data which should be sent

        :param flp: fleep object
        """
    uti_type = 'public.content'
    if len(flp.mime) == 0 or len(flp.type) == 0:
        return uti_type
    mime = flp.mime[0]
    f_type = flp.type[0]
    if 'image' in mime:
        uti_type = 'public.image'
        if 'jpg' in mime:
            uti_type = 'public.jpeg'
        elif 'jp2' in mime:
            uti_type = 'public.jpeg-2000'
        elif 'gif' in mime:
            uti_type = 'com.compuserve.gif'
        elif 'png' in mime:
            uti_type = 'public.png'
        elif 'raw' in mime or 'raw' in f_type:
            uti_type = 'public.camera-raw-image'
    elif 'audio' in f_type:
        uti_type = 'public.audio'
    elif 'video' in f_type:
        uti_type = 'public.video'
    elif 'archive' in f_type:
        uti_type = 'public.data'
        if 'gzip' in mime:
            uti_type = 'org.gnu.gnu-zip-archive'
        if 'zip' in mime:
            uti_type = 'public.zip-archive'
    return uti_type


def get_last_idx(iterable, func):
    """
    获取最后一个符合条件数据的数组索引
    :param iterable:
    :param func:
    :return:
    """
    count = len(iterable)
    for n in range(count - 1, -1, -1):
        if func(iterable[n]):
            return n
    return None


@classmethod
def from_builtin_corpus(cls, corpus_label):
    """
        Construct Corpus object by loading one of the built-in datasets specified by `corpus_label`. To get a list
        of available built-in datasets, use :meth:`~tmtoolkit.corpus.Corpus.builtin_corpora`.

        :param corpus_label: the corpus to load (one of the labels listed in
                             :meth:`~tmtoolkit.corpus.Corpus.builtin_corpora`
        :return: Corpus instance
        """
    available = cls.builtin_corpora(with_paths=True)
    if corpus_label in available:
        return cls.from_zip(available[corpus_label], **cls.
            _BUILTIN_CORPORA_LOAD_KWARGS.get(corpus_label, {}))
    else:
        raise ValueError('built-in corpus does not exist:', corpus_label)


@classmethod
def create_from_learning_model(cls, model_id, label, description=None,
    default_prediction_server_id=None):
    """Create a deployment from a DataRobot model.

        .. versionadded:: v2.17

        Parameters
        ----------
        model_id : str
            id of the DataRobot model to deploy
        label : str
            a human readable label of the deployment
        description : str, optional
            a human readable description of the deployment
        default_prediction_server_id : str
            an identifier of a prediction server to be used as the default prediction server

        Returns
        -------
        deployment : Deployment
            The created deployment

        Examples
        --------
        .. code-block:: python

            from datarobot import Project, Deployment
            project = Project.get('5506fcd38bd88f5953219da0')
            model = project.get_models()[0]
            deployment = Deployment.create_from_learning_model(model.id, 'New Deployment')
            deployment
            >>> Deployment('New Deployment')
        """
    payload = {'model_id': model_id, 'label': label, 'description': description
        }
    if default_prediction_server_id:
        payload['default_prediction_server_id'] = default_prediction_server_id
    url = '{}fromLearningModel/'.format(cls._path)
    deployment_id = cls._client.post(url, data=payload).json()['id']
    return cls.get(deployment_id)


def get_protocol(path):
    """Given a path, returns the protocol the path uses

    For example,
      's3://a/b/c/'  returns 's3'
      'http://a/b/c' returns 'http'
      'tmp/a/bc/'    returns ''

    """
    pos = path.find('://')
    if pos < 0:
        return ''
    return path[0:pos].lower()


def traverse_using(iterator, obj, visitors):
    """visit the given expression structure using the given iterator of
    objects.

    :func:`.visitors.traverse_using` is usually called internally as the result
    of the :func:`.visitors.traverse` or :func:`.visitors.traverse_depthfirst`
    functions.

    :param iterator: an iterable or sequence which will yield
     :class:`.ClauseElement` structures; the iterator is assumed to be the
     product of the :func:`.visitors.iterate` or
     :func:`.visitors.iterate_depthfirst` functions.

    :param obj: the :class:`.ClauseElement` that was used as the target of the
     :func:`.iterate` or :func:`.iterate_depthfirst` function.

    :param visitors: dictionary of visit functions.  See :func:`.traverse`
     for details on this dictionary.

    .. seealso::

        :func:`.traverse`

        :func:`.traverse_depthfirst`

    """
    for target in iterator:
        meth = visitors.get(target.__visit_name__, None)
        if meth:
            meth(target)
    return obj


def listDictToHtmlTable(listDict):
    """return string containing html code for table"""
    result = '
'
    if len(listDict) > 0:
        result += '

'
        for key in listDict[0]:
            result += '' + str(key) + '	'
        result += '

'
        for item in listDict:
            result += '
'
            for key in item:
                result += '' + str(item[key]) + '	'
            result += '
'
        result += '
'
    result += '
'
    return result


def _get_best_track(tracks, partial, gap, acceptabledist):
    """
    Get the best track minimizing gap
    """
    pt0 = partial[0, 0]
    mindist = float('inf')
    best = None
    for track in tracks:
        t1 = track[-1][-1, 0] + gap
        if t1 < pt0:
            dist = t1 - pt0
            if dist < acceptabledist:
                return track
            if dist < mindist:
                best = track
                mindist = dist
    return best


def make_metadata_path(keys, value, version=None):
    """
    Generate a path to find a given lookup table.
    """
    if isinstance(keys, (list, tuple)):
        keys = '/'.join(keys)
    path = '%s/%s' % (keys, value)
    if version:
        path += '.%s' % version
    path += '.csv.yml'
    return path


@classmethod
def is_list(cls, node, graph):
    """Determine if a given node is plausibly the subject of a list element."""
    return bool(list(graph.match(subject=node, predicate=cls.resolve(
        'rdf:rest'))))


def count(start=0, step=1):
    """Make an iterator that returns evenly spaced values starting with `start`.
  Often used as an argument to :func:`imap` to generate consecutive data points.
  Also, used with :func:`izip` to add sequence numbers.

  When counting with floating point numbers, better accuracy can sometimes be
  achieved by substituting multiplicative code such as: ``(start + step * i for
  i in count())``.

  .. note:: Software and documentation for this function are taken from
            CPython, :ref:`license details <psf-license>`.
  """
    n = start
    while True:
        yield n
        n += step


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


def is_kanji(text, start_block=u'一', end_block=u'\u9fff'):
    """Check if all characters in text are kanji character. [CJK Unified Ideographs 4E00-9FFF Common]"""
    res = True
    for t in text:
        if t < start_block or t > end_block:
            res = False
            break
    return res


@classmethod
def sqlType(cls):
    """
        Underlying SQL storage type for this UDT.
        """
    raise NotImplementedError('UDT must implement sqlType().')


@classmethod
def command_class(cls, command: str):
    """
        Get command class with command name

        :param command: command name
        :return: command class
        """
    return cls.__command_classes.get(command)


def disassociate_product_from_portfolio(AcceptLanguage=None, ProductId=None,
    PortfolioId=None):
    """
    Disassociates the specified product from the specified portfolio.
    See also: AWS API Documentation

    :example: response = client.disassociate_product_from_portfolio(
        AcceptLanguage='string',
        ProductId='string',
        PortfolioId='string'
    )

    :type AcceptLanguage: string
    :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows:
            'en' (English)
            'jp' (Japanese)
            'zh' (Chinese)
            If no code is specified, 'en' is used as the default.

    :type ProductId: string
    :param ProductId: [REQUIRED]
            The product identifier.

    :type PortfolioId: string
    :param PortfolioId: [REQUIRED]
            The portfolio identifier.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def point_idx_to_term(idx):
    """
        Convert point indices to the terms it represent.

        idx| 0 |  1 | 2 |  3 | 4 |
        --------------------------
           | 0 | -1 | 1 | -2 | 2 |
    """
    if idx == 0:
        return 0
    residual = (idx - 1) % 2
    term_abs = (idx + 1) // 2
    term = term_abs * -1 if residual == 0 else term_abs
    return term


@staticmethod
def mm_verb_stem(verb):
    """ Lookup a verb stem for a 'miðmynd' verb,
            i.e. "eignast" for "eigna" (which may have appeared
            as "eignaðist" in the text) """
    return verb if verb.endswith('st') else verb + 'st'


def _append_children(node, clusters_before, clusters_after,
    clusters_reversed, solution_before, solution_after):
    """Append children for the given node.

    Receives a key (representing a node) of one of the dictionaries.
    In order to proceed with building a tree, containing the list of
    nodes required to create a subproblem, the method append the children
    (subnodes) of the given parent. If the node is the key of
    clusters_before or clusters_after dictionary, then the cluster of
    signatures is a part of the currently generating subproblem.

    :param node:
        A key of one of the given dictionaries.

        Example (for example clusters_reversed's key):
            node = A

    :param clusters_before:
        A dictionary containing unique keys and signatures clustered into
        lists (representing the same author), as values.

        Example:
            clusters_before = {1: ['A', 'B'], 2: ['C']}

    :param clusters_after:
        A dictionary containing unique keys and signatures clustered into
        lists (representing the same author), as values.

        Example:
            clusters_after = {3: ['A', 'B'], 4: ['C', D']}

    :param clusters_reversed:
        A dictionary containing values from clusters_before and
        clusters_after dictionaries as the keys and the keys of
        these dictionaries as the values. This dictionary points,
        where the given signatures are stored.

        Example:
            clusters_reversed = {'A': [1, 3], 'B': [1, 3],
                                 'C': [2, 4], 'D': [4]}

    :param solution_before:
        A dictionary of sets containing signatures being selected as the
        part of the currently generating subproblem in the-state-before.

        Example:
            solution_before = {1: set(['A, B'])}

    :param solution_after:
        A dictionary of sets containing signatures being selected as the
        part of the currently generating subproblem in the-state-after.

        Example:
            solution_after = {3: set(['A, B'])}

    :return:
        A list of children of the given node.

        Example:
            [1, 3]
    """
    if node in clusters_before.keys():
        solution_before[node] = clusters_before[node]
        return clusters_before[node]
    if node in clusters_after.keys():
        solution_after[node] = clusters_after[node]
        return clusters_after[node]
    if node in clusters_reversed.keys():
        return clusters_reversed[node]


def get_ignores():
    """
    Return a list of ignore directories.
    """
    ignores = ['/\\.\\w+/*']
    return ignores


@classmethod
def from_dict(cls, pdict):
    """Factory method producing a _Provider based on a dict with
        appropriate keys.

        :param pdict: Dictionary representing a provider, with keys 'name',
                      'uuid', 'generation', 'parent_provider_uuid'.  Of these,
                      only 'name' is mandatory.
        """
    return cls(pdict['name'], uuid=pdict.get('uuid'), generation=pdict.get(
        'generation'), parent_uuid=pdict.get('parent_provider_uuid'))


def select_first(only_selected_strokes: bool=False, extend: bool=False):
    """Select first point in Grease Pencil strokes

    :param only_selected_strokes: Selected Strokes Only, Only select the first point of strokes that already have points selected
    :type only_selected_strokes: bool
    :param extend: Extend, Extend selection instead of deselecting all other selected points
    :type extend: bool
    """
    pass


def get_typecode(dtype):
    """ Get the IDL typecode for a given dtype """
    if dtype.name[:5] == 'bytes':
        return '1'
    if dtype.name == 'int16':
        return '2'
    if dtype.name == 'int32':
        return '3'
    if dtype.name == 'float32':
        return '4'
    if dtype.name == 'float64':
        return '5'
    if dtype.name[:3] == 'str':
        return dtype.name[3:]
    raise ValueError("Don't recognise the datatype")


def resync(hive, hive_names, timeout=2, max_attempts=5):
    """This waits for the shell prompt for each host in an effort to try to get
    them all to the same state. The timeout is set low so that hosts that are
    already at the prompt will not slow things down too much. If a prompt match
    is made for a hosts then keep asking until it stops matching. This is a
    best effort to consume all input if it printed more than one prompt. It's
    kind of kludgy. Note that this will always introduce a delay equal to the
    timeout for each machine. So for 10 machines with a 2 second delay you will
    get AT LEAST a 20 second delay if not more. """
    for hostname in hive_names:
        if hive[hostname] is not None:
            for attempts in range(0, max_attempts):
                if not hive[hostname].prompt(timeout=timeout):
                    break


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

    :return: rst string
    :rtype: str
    """
    return """
    The ``servicegroup`` model is used to group several hosts.

    """


def str_to_span(string):
    """ Return the equivalent interval time in seconds.

    Parameters
    ----------
    string : str
        Time periodicity

    Returns
    -------
    span : int
        Number of seconds in time interval.

    Examples
    --------
    >>> str_to_span('minutely')
    60

    """
    if string.lower() in ['weekly', 'week', '7d', '1w', 'w']:
        return 604800
    elif string.lower() in ['daily', 'day', '24h', '1d', 'd']:
        return 86400
    elif string.lower() in ['bi-hourly', 'bi-hour', '2h']:
        return 7200
    elif string.lower() in ['hourly', 'hour', '1h', '60min', 'h']:
        return 3600
    elif string.lower() in ['half-hourly', 'half-hour', '30min']:
        return 1800
    elif string.lower() in ['5-minute', 'five-minute', '5 minute',
        'five minute', '5min']:
        return 300
    elif string.lower() in ['minutely', 'minute', '1min', 'min']:
        return 60
    else:
        print('Error, string not understood.\nString must be "minutely",',
            '"5 minute", "hourly", "daily" or "weekly".')


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


def PointerProperty(type=None, name: str='', description: str='', options:
    set={'ANIMATABLE'}, update=None):
    """Returns a new pointer property definition.

    :param type: A subclass of bpy.types.PropertyGroup.
    :param name: Name used in the user interface.
    :type name: str
    :param description: Text used for the tooltip and api documentation.
    :type description: str
    :param options: Enumerator in [‘HIDDEN’, ‘SKIP_SAVE’, ‘ANIMATABLE’, ‘LIBRARY_EDITABLE’, ‘PROPORTIONAL’,’TEXTEDIT_UPDATE’].
    :type options: set
    :param update: Function to be called when this value is modified, This function must take 2 values (self, context) and return None. Warning there are no safety checks to avoid infinite recursion.
    """
    pass


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

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


@staticmethod
def parse_transport_fields(header) ->dict:
    """
        Parse Transport request/response
        """
    res = {}
    fields_ = header.split(';')
    for field in fields_:
        if '=' in field:
            k, v = field.split('=', 1)
        else:
            k, v = field, None
        res[k.strip()] = v.strip() if v is not None else None
    return res


@staticmethod
def determine_dicom_zipname(filenames, series_label):
    """Return a filename for the dicom series that is unique to a container

        Args:
            filenames (dict): A map of series uids to filenames
            series_label (str): The base to use for the filename

        Returns:
            str: The filename for the zipped up series
        """
    filename = series_label + '.dicom.zip'
    duplicate = 1
    while filename in filenames.values():
        filename = series_label + f'_dup-{duplicate}.dicom.zip'
        duplicate += 1
    return filename


@classmethod
def _hash_key_attribute(cls):
    """
        Returns the attribute class for the hash key
        """
    for attr_cls in cls._get_attributes().values():
        if attr_cls.is_hash_key:
            return attr_cls


def _set_key_passphrase(db_handle, passphrase):
    """
    Set a passphrase for encryption key derivation.

    The key itself can be a passphrase, which is converted to a key using
    PBKDF2 key derivation. The result is used as the encryption key for
    the database. By using this method, there is no way to alter the KDF;
    if you want to do so you should use a raw key instead and derive the
    key using your own KDF.

    :param db_handle: A handle to the SQLCipher database.
    :type db_handle: pysqlcipher.Connection
    :param passphrase: The passphrase used to derive the encryption key.
    :type passphrase: str
    """
    db_handle.cursor().execute("PRAGMA key = '%s'" % passphrase)


def parse_sample(qc_sample):
    """Parse out relevant information from sample data."""
    data = {}
    for key, value in qc_sample.items():
        if 'lanes' in key:
            hs_metrics = value['CalculateHsMetrics']['Header']['Data']
            mult_metrics = value['CollectMultipleMetrics']['Header']['Pair']
            data['strand_balance'] = mult_metrics['STRAND_BALANCE']
            data['sex_predicted'] = value['ChanjoSexCheck']['gender']
            data['coverage_target'] = hs_metrics['MEAN_TARGET_COVERAGE']
            data['completeness_target_10'] = hs_metrics['PCT_TARGET_BASES_10X']
            data['completeness_target_20'] = hs_metrics['PCT_TARGET_BASES_20X']
            data['completeness_target_50'] = hs_metrics['PCT_TARGET_BASES_50X']
            data['completeness_target_100'] = hs_metrics[
                'PCT_TARGET_BASES_100X']
            comp_overlap = value['VariantEval_All']['CompOverlap_header'][
                'CompOverlap_data_all']
            variant_sum = value['VariantEval_All']['VariantSummary_header'][
                'VariantSummary_data_all']
            variant_count = value['VariantEval_All']['CountVariants_header'][
                'CountVariants_data_all']
            data['variants'] = comp_overlap['nEvalVariants']
            data['indels'] = variant_sum['nIndels']
            data['snps'] = variant_sum['nSNPs']
            data['titv_ratio'] = variant_sum['TiTvRatio']
            data['novel_sites'] = comp_overlap['novelSites']
            data['concordant_rate'] = comp_overlap['concordantRate'] / 100
            data['hethom_ratio'] = variant_count['hetHomRatio']
    data['reads'] = qc_sample['TotalReads']
    data['mapped_percent'] = qc_sample['MappedRate']
    data['duplicates_percent'] = qc_sample['Duplicates']
    return data


def django_cms_is_present():
    """Helper for checking wheather django-cms library is installed.

    (https://github.com/divio/django-cms)

    Returns:
        True if django-cms is installed otherwise False.

    """
    try:
        import cms
        return True
    except ImportError:
        return False


@staticmethod
def name():
    """
        Name of the instrument, e.g. 'nova_seq'

        :returns: name of instrument as string
        """
    raise NotImplementedError


def _compare_set(new_set, old_set, change_list, root):
    """
        a method for list changes made to a set

    :param new_set: set with new values
    :param old_set: set with old values
    :param change_list: list of differences between old and new
    :patam root: string with record of path to the root of the main object
    :return: list of differences between old and new
    """
    from copy import deepcopy
    path = deepcopy(root)
    missing_items = old_set - new_set
    extra_items = new_set - old_set
    for item in missing_items:
        change_list.append({'action': 'REMOVE', 'key': None, 'value': item,
            'path': path})
    for item in extra_items:
        change_list.append({'action': 'ADD', 'key': None, 'value': item,
            'path': path})
    return change_list


def _normalize_states(states):
    """Normalize states by inheriting parameters explicitly.

    The TMHMM file format allows parameters to be tied to the parameters of
    some other state. This basically means that a state inherits the parameters
    from another state.

    The normalization performed by this function consists of copying the
    specified parameters from the parent state to the inheriting state such
    that all states explicitly specify their transition and emission
    probabilities.
    """
    for name, state in states.items():
        if 'tied_trans' in state:
            parent_state = states[state['tied_trans']]
            to_states = state['trans']
            states[name]['trans'] = dict(zip(state['trans'], parent_state[
                'trans'].values()))
        if 'tied_letter' in state:
            parent_state = state['tied_letter']
            states[name]['only'] = dict(states[parent_state]['only'])
    return states


def write_file(filename, contents):
    """Create a file with the specified name and write 'contents' (a
    sequence of strings without line terminators) to it.
    """
    contents = '\n'.join(contents)
    contents = contents.encode('utf-8')
    with open(filename, 'wb') as f:
        f.write(contents)


@staticmethod
def read(reader, _index):
    """
        Reads Zserio string type from the bit stream.

        :param reader: Bit stream from which to read.
        :param _index: Not used.
        """
    return reader.readString()


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

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

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


def mpl_get_cb_bound_below_plot(ax):
    """
    Return the coordinates for a colorbar axes below the provided axes object.
    Take into account the changes of the axes due to aspect ratio settings.

    Parts of this code are taken from the transforms.py file from matplotlib

    Important: Use only AFTER fig.subplots_adjust(...)

    Use as:
    =======
    """
    position = ax.get_position()
    figW, figH = ax.get_figure().get_size_inches()
    fig_aspect = figH / figW
    box_aspect = ax.get_data_ratio()
    pb = position.frozen()
    pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect).bounds
    ax_size = ax.get_position().bounds
    sizes = [ax_size[0], ax_size[1] - 0.14, pb1[2], 0.03]
    return sizes


def is_redirection(status):
    """
    Check if HTTP status code is redirection.

    :param status: http status code
    :returns: True if status is redirection, else False
    """
    return 300 <= status <= 399


def plot_connectivity_matrix(connectivity_matrix, label_names):
    """ Plot the connectivity matrix. """
    import numpy as np
    from matplotlib import pyplot as plt
    plt.figure(figsize=(10, 10))
    np.fill_diagonal(connectivity_matrix, 0)
    fig = plt.imshow(connectivity_matrix, interpolation='nearest', cmap=
        'RdBu_r', vmax=0.8, vmin=-0.8)
    plt.colorbar()
    _ = plt.xticks(range(len(label_names)), label_names, rotation=90)
    _ = plt.yticks(range(len(label_names)), label_names)
    return fig


def REVERSE_ARRAY(expression):
    """
    Accepts an array expression as an argument and returns an array with the elements in reverse order.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/reverseArray/
    for more details
    :param expression: Any valid expression as long as it resolves to an array.
    :return: Aggregation operator
    """
    return {'$reverseArray': expression}


def doc_handle_data(event):
    """Documentation for handlers bound to ``evt.EVT_DATA_RECV`` or
    ``evt.EVT_DATA_SENT``.

    Parameters
    ----------
    event : events.Event
        Represents data being sent to or received from the remote over the
        socket. ``Event`` attributes are:

        * ``assoc`` : the
          :py:class:`association <pynetdicom.association.Association>`
          that is running the service that received the user identity
          negotiation request.
        * ``data`` : the data sent to or received from the remote (as
          ``bytes``).
        * ``event`` : the event that occurred as ``namedtuple``.
        * ``timestamp`` : the
          `date and time <https://docs.python.org/3/library/datetime.html#datetime-objects>`_
          that the negotiation request was processed by the ACSE.
    """
    pass


def p_namespace(t):
    """namespace : NAMESPACE ID LBRACE specification RBRACE"""


@staticmethod
def _questionmark_handler(date_pointer):
    """ Handles Cron Syntax parsing for `?` values. """
    parsed_date = date_pointer
    unit_boundary_reached = True
    return parsed_date, unit_boundary_reached


def lambd_SO2_Cl_MHJZ89(T, P):
    """n-a: sulfur-dioxide chloride [MHJZ89]."""
    lambd = 0
    valid = T == 298.15
    return lambd, valid


def connection_id(hid, lid):
    """ConnectionId is unique within all incoming lightweight connections LocalEndPoint."""
    return hid << 32 | lid


def str_presenter(yaml_dumper, data):
    """Use block style for multiline strings"""
    if len(data.splitlines()) > 1:
        return yaml_dumper.represent_scalar('tag:yaml.org,2002:str', data,
            style='|')
    return yaml_dumper.represent_scalar('tag:yaml.org,2002:str', data)


def filter_ice_border(ice_thick):
    """Sets the ice thickness at the border of the domain to zero."""
    ice_thick[(0), :] = 0
    ice_thick[(-1), :] = 0
    ice_thick[:, (0)] = 0
    ice_thick[:, (-1)] = 0
    return ice_thick


@staticmethod
def get_interesting_elements(element_list):
    """
        Function called upon new trace creation. From a list, takes the interesting elements for animation
        :param element_list:
        :return: new_element_list
        """
    return [element_list]


@staticmethod
def _get_name_from_dn(dn):
    """
        Get the instance name from the dn

        :param dn: string containing the distinguished name URL
        :return: string containing the name
        """
    name = dn.split('/adj-')[1].split('/')[0]
    return name


@classmethod
def find(cls, id, columns=None):
    """
        Find a model by its primary key.

        :param id: The id of the model
        :type id: mixed

        :param columns: The columns to retrieve
        :type columns: list

        :return: Either a Model instance or a Collection
        :rtype: Model
        """
    instance = cls()
    if isinstance(id, list) and not id:
        return instance.new_collection()
    if columns is None:
        columns = ['*']
    return instance.new_query().find(id, columns)


def chained_join(*relationships):
    """
    Return a chained Join object for given relationships.
    """
    property_ = relationships[0].property
    if property_.secondary is not None:
        from_ = property_.secondary.join(property_.mapper.class_.__table__,
            property_.secondaryjoin)
    else:
        from_ = property_.mapper.class_.__table__
    for relationship in relationships[1:]:
        prop = relationship.property
        if prop.secondary is not None:
            from_ = from_.join(prop.secondary, prop.primaryjoin)
            from_ = from_.join(prop.mapper.class_, prop.secondaryjoin)
        else:
            from_ = from_.join(prop.mapper.class_, prop.primaryjoin)
    return from_


def match(needle, haystack):
    """
    Command-T-style string matching.
    """
    score = 1
    j = 0
    last_match = 0
    needle = needle.lower()
    haystack = haystack.lower()
    for c in needle:
        while j < len(haystack) and haystack[j] != c:
            j += 1
        if j >= len(haystack):
            return 0
        score += 1 / (last_match + 1.0)
        last_match = j
        j += 1
    return score


def is_valid_ot_str_ens(ext):
    """ Checks if output type for structure ensemble is correct """
    formats = ['gro', 'g96', 'pdb']
    return ext in formats


def _common_bytes(blocks1, blocks2):
    """Count the number of common bytes in two block count dicts.

    :param block1: The first dict of block hashcode -> total bytes.
    :param block2: The second dict of block hashcode -> total bytes.
    :return: The number of bytes in common between blocks1 and blocks2. This is
        only approximate due to possible hash collisions.
    """
    if len(blocks1) > len(blocks2):
        blocks1, blocks2 = blocks2, blocks1
    score = 0
    for block, count1 in blocks1.items():
        count2 = blocks2.get(block)
        if count2:
            score += min(count1, count2)
    return score


def crop(input_file, output_file, thresh=0.1):
    """Crop away static pixels from an ultrasound

  This function isolates the moving video in the center of an ultrasound clip and
  removes static borders that often contains patient information.

  Examples

  sonocrop crop in.mp4 out.mp4 --thresh=0.05

  Args:
      input_file: Path to input video (must be mp4, mov, or avi)
      output_file: File path for video output
      thresh (float, optional): Defaults to 0.1
  """
    import numpy as np
    import cv2
    from pathlib import Path
    from sonocrop import vid
    import rich
    from rich.progress import Progress
    v, fps, f, height, width = vid.loadvideo(input_file)
    rich.print(f'Auto cropping: [underline]{input_file}[/underline]')
    rich.print(f'  Frames: {f}')
    rich.print(f'  FPS: {fps}')
    rich.print(f'  Width x height: {width} x {height}')
    rich.print(f'  Thresh: {thresh}')
    with Progress() as progress:
        task = progress.add_task('[green] Finding static video pixels...',
            total=height)
        u = np.zeros((height, width), np.uint8)
        for i in range(height):
            u[i] = np.apply_along_axis(vid.countUniquePixels, 0, v[:, (i), :])
            progress.update(task, advance=1)
    u_avg = u / f
    rich.print(' Finding edges')
    maxW = np.max(u_avg, axis=0)
    left, right = vid.findEdges(maxW, thresh=thresh)
    maxH = np.max(u_avg, axis=1)
    top, bottom = vid.findEdges(maxH, thresh=thresh)
    rich.print(f'  Top: {top}')
    rich.print(f'  Bottom: {bottom}')
    rich.print(f'  Left: {left}')
    rich.print(f'  Right: {right}')
    cropped = v[:, top:bottom, left:right]
    rich.print(f' Saving to file: "{output_file}"')
    vid.savevideo(output_file, cropped, fps)
    rich.print(' DONE')


@classmethod
def handle_cursor(cls, cursor, query, session):
    """Handle a live cursor between the execute and fetchall calls

        The flow works without this method doing anything, but it allows
        for handling the cursor and updating progress information in the
        query object"""
    pass


@staticmethod
def __get_dict(target_dict) ->dict:
    """
        target_dict が None なら 空の Dict を
        Noneでなければそのまま返す
        :param target_dict:
        :return:
        """
    if target_dict is None:
        return {}
    else:
        return target_dict


def setvar(storage, variable, value):
    """Stores value inside of variable.

        Note: allways returns true so can be used in require block.

        .. code-block:: xml

            variable = value
            variable -> value
        """
    storage[variable] = value
    return True


def setMethodAliases(aliases):
    """ Assign method aliases for this type.

        o Return True if the operation changed any aliases, else False.

        o 'aliases' is the mapping of aliases to be assigned.

        o ???:  define keys and values of the mapping.

        o Permission:  Manage portal
        """


@classmethod
def from_transpose(cls, transpose_graph):
    """ Generate a graph by transposing another graph (reversing all of its
            edges) """
    g = cls()
    for v in transpose_graph.vertices:
        g.add_vertex(v.val)
    for e in transpose_graph.edges:
        g.add_edge((e.v_to.val, e.v_from.val))
    return g


def list_groups(UserPoolId=None, Limit=None, NextToken=None):
    """
    Lists the groups associated with a user pool.
    Requires developer credentials.
    See also: AWS API Documentation

    :example: response = client.list_groups(
        UserPoolId='string',
        Limit=123,
        NextToken='string'
    )

    :type UserPoolId: string
    :param UserPoolId: [REQUIRED]
            The user pool ID for the user pool.

    :type Limit: integer
    :param Limit: The limit of the request to list groups.

    :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.

    :rtype: dict
    :return: {
        'Groups': [
            {
                'GroupName': 'string',
                'UserPoolId': 'string',
                'Description': 'string',
                'RoleArn': 'string',
                'Precedence': 123,
                'LastModifiedDate': datetime(2015, 1, 1),
                'CreationDate': datetime(2015, 1, 1)
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def midi_to_freq(midi_num):
    """Converts MIDI note number to frequency.

    midi_num: int MIDI note number

    returns: float frequency in Hz
    """
    x = (midi_num - 69) / 12.0
    freq = 440.0 * 2 ** x
    return freq


@classmethod
def DELETE(cls, *n, **kw):
    """
        Perform a DELETE request using `RESTClient.request()`
        """
    return cls.IMPL.DELETE(*n, **kw)


def area(poly):
    """
    calculate the area of polygon

    Keyword arguments:
    poly -- polygon geojson object

    return polygon area
    """
    poly_area = 0
    points = poly['coordinates'][0]
    j = len(points) - 1
    count = len(points)
    for i in range(0, count):
        p1_x = points[i][1]
        p1_y = points[i][0]
        p2_x = points[j][1]
        p2_y = points[j][0]
        poly_area += p1_x * p2_y
        poly_area -= p1_y * p2_x
        j = i
    poly_area /= 2
    return poly_area


def split_field(field):
    """Разбивка на поля."""
    if not isinstance(field, (list, tuple)):
        return field.split('.')
    fields = []
    for f in field:
        if not isinstance(f, (list, tuple)):
            f = f.split('.')
        fields.extend(f)
    return fields


def _intersection(l0, l1, e=1e-06):
    """intersection of lines."""
    a0, b0, c0 = l0
    a1, b1, c1 = l1
    w = a0 * b1 - a1 * b0
    x = b0 * c1 - b1 * c0
    y = c0 * a1 - c1 * a0
    if abs(w) < e:
        raise ZeroDivisionError
    return x / w, y / w


def fill_missing_day(all_loc_rec, k):
    """
    For any location (L) in any day, see the next k days.
    If in these k days, there is >= 1 day when this person appears in L,
    then fill the gaps with L.
    """
    result_dict = {}
    for loc in all_loc_rec.keys():
        loc_date = all_loc_rec[loc]
        loc_date.sort()
        new_loc_date = list(loc_date)
        if len(loc_date) > 1:
            for i, date in enumerate(loc_date[:-1]):
                close_date = loc_date[i + 1]
                date_diff = close_date - date
                if 1 < date_diff <= k:
                    new_loc_date += range(date + 1, close_date)
        new_loc_date.sort()
        result_dict[loc] = new_loc_date
    return result_dict


def atom_num_radical_electrons(atom):
    """Get the number of radical electrons for an atom.

    Parameters
    ----------
    atom : rdkit.Chem.rdchem.Atom
        RDKit atom instance.

    Returns
    -------
    list
        List containing one int only.
    """
    return [atom.GetNumRadicalElectrons()]


def remove_keys(apps, schema_editor):
    """
    We can't import the Post model directly as it may be a newer
    version than this migration expects. We use the historical version.
    """
    Setting = apps.get_model('settings', 'Setting')
    try:
        key = 'USER_REGISTER_GIFT_BON_CREDITS'
        Setting.objects.get(key=key).delete()
    except Exception:
        pass


def floatimg2uint8(image):
    """
    Convert array with floats to 'uint8' and rescale from [0,1] to [0, 256].

    Converts only if image.dtype != uint8.

    >>> import numpy as np
    >>> image = np.eye(10, 20, dtype=float)
    >>> arr = floatimg2uint8(image)
    >>> np.max(arr)
    255

    :param numpy.array image: Numpy array with range [0,1]
    :return: Numpy array with range [0,255] and dtype 'uint8'
    :rtype: numpy array
    """
    return (image * 255).astype('uint8') if image.dtype != 'uint8' else image


def convert_to_float(frac_str):
    """This function converts fractions to float, ex. -1/3 = -0.33333..."""
    try:
        return float(frac_str)
    except ValueError:
        try:
            num, denom = frac_str.split('/')
        except ValueError:
            return None
        try:
            leading, num = num.split(' ')
        except ValueError:
            return float(num) / float(denom)
        if float(leading) < 0:
            sign_mult = -1
        else:
            sign_mult = 1
        return float(leading) + sign_mult * (float(num) / float(denom))


def django_pg_bulk_update_available():
    """
    Tests if django-pb-bulk-update library is installed
    :return: Boolean
    """
    try:
        import django_pg_bulk_update
        return True
    except ImportError:
        return False


def get_ssl_client_options(conf):
    """Format SSL-related requests options.

    :param conf: oslo_config CONF object
    :returns: tuple of 'verify' and 'cert' values to pass to requests
    """
    if conf.insecure:
        verify = False
    else:
        verify = conf.cafile or True
    if conf.certfile and conf.keyfile:
        cert = conf.certfile, conf.keyfile
    else:
        cert = None
    return verify, cert


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


@classmethod
def all(cls, name, hash_key, range_key=None, throughput=None):
    """ Create an index that projects all attributes """
    return cls(cls.ALL, name, hash_key, range_key, throughput=throughput)


def add_headers(width=80, title='Untitled', subtitle='', author='', email=
    '', description='', tunings=None):
    """Create a nice header in the form of a list of strings using the
    information that has been filled in.

    All arguments except 'width' and 'tunings' should be strings. 'width'
    should be an integer and 'tunings' a list of tunings representing the
    instruments.
    """
    if tunings is None:
        tunings = []
    result = ['']
    title = str.upper(title)
    result += [str.center('  '.join(title), width)]
    if subtitle != '':
        result += ['', str.center(str.title(subtitle), width)]
    if author != '' or email != '':
        result += ['', '']
        if email != '':
            result += [str.center('Written by: %s <%s>' % (author, email),
                width)]
        else:
            result += [str.center('Written by: %s' % author, width)]
    if description != '':
        result += ['', '']
        words = description.split()
        lines = []
        line = []
        last = 0
        for word in words:
            if len(word) + last < width - 10:
                line.append(word)
                last += len(word) + 1
            else:
                lines.append(line)
                line = [word]
                last = len(word) + 1
        lines.append(line)
        for line in lines:
            result += [str.center(' '.join(line), width)]
    if tunings != []:
        result += ['', '', str.center('Instruments', width)]
        for i, tuning in enumerate(tunings):
            result += ['', str.center('%d. %s' % (i + 1, tuning.instrument),
                width), str.center(tuning.description, width)]
    result += ['', '']
    return result


@classmethod
def add_command(cls, command):
    """Add commands to class

        :param cls: add command to cls
        :param command: command object
        """
    cls.commands[command.name] = command
    return True


def touch(fp):
    """Touch an empty file"""
    open(fp, 'a').close()


def get_developer_package(path, format=None):
    """Create a developer package.

    Args:
        path (str): Path to dir containing package definition file.
        format (str): Package definition file format, detected if None.

    Returns:
        `DeveloperPackage`.
    """
    from rez.developer_package import DeveloperPackage
    return DeveloperPackage.from_path(path, format=format)


def uniq_g(lst, key=lambda value: value):
    """
    Get unique elements of an iterable preserving its order and optionally
    determining uniqueness by hash of a key.
    """
    known = set()
    for value in lst:
        value_key = key(value)
        if value_key not in known:
            yield value
            known.add(value_key)


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


def ichimoku(dataframe, conversion_line_period=20, base_line_periods=60,
    laggin_span=120, displacement=30):
    """Ichimoku cloud indicator"""
    df = dataframe.copy()
    high_9 = df['high'].rolling(window=conversion_line_period).max()
    low_9 = df['low'].rolling(window=conversion_line_period).min()
    df['tenkan_sen'] = (high_9 + low_9) / 2
    high_26 = df['high'].rolling(window=base_line_periods).max()
    low_26 = df['low'].rolling(window=base_line_periods).min()
    df['kijun_sen'] = (high_26 + low_26) / 2
    last_index = df.iloc[-1:].index[0]
    last_date = df['date'].iloc[-1].date()
    df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)
    high_52 = df['high'].rolling(window=laggin_span).max()
    low_52 = df['low'].rolling(window=laggin_span).min()
    df['senkou_span_b'] = ((high_52 + low_52) / 2).shift(displacement)
    df['chikou_span'] = df['close'].shift(-displacement)
    return {'tenkan_sen': df['tenkan_sen'], 'kijun_sen': df['kijun_sen'],
        'senkou_span_a': df['senkou_span_a'], 'senkou_span_b': df[
        'senkou_span_b'], 'chikou_span': df['chikou_span'], 'cloud_green':
        df['senkou_span_a'] > df['senkou_span_b'], 'cloud_red': df[
        'senkou_span_b'] > df['senkou_span_a']}


def not_found_response(resource='servers'):
    """
    Return a 404 response body, depending on the resource.  Expects
    resource to be one of "images", "flavors", "loadbalancer", or "node".

    If the resource is unrecognized, defaults to
    "The resource culd not be found."
    """
    message = {'images': 'Image not found.', 'flavors':
        'The resource could not be found.', 'loadbalancer':
        'Load balancer not found', 'node': 'Node not found'}
    resp = {'itemNotFound': {'message': message.get(resource,
        'The resource could not be found.'), 'code': 404}}
    if resource == 'loadbalancer' or resource == 'node':
        return resp['itemNotFound']
    return resp


def nb2md(ptn, nb, fp):
    """Notebook to Markdown"""
    for ce in nb.get('cells', []):
        ct = ce.get('cell_type')
        sc = ce.get('source')
        if ct == 'markdown':
            sc = ptn.sub('**\\2**', sc)
            fp.write(f'{sc}\n')
        elif ct == 'code':
            ec = ce.get('execution_count') or ' '
            fp.write(f'In [{ec}]:\n\n')
            for s in sc.splitlines():
                fp.write(f'    {s}\n')
            fp.write('\n')
            ops = []
            for op in ce.get('outputs', []):
                tt = op.get('text')
                if tt:
                    fp.write(f'> {tt}\n')
                dc = op.get('data', {})
                if 'image/png' not in dc:
                    for k, v in dc.items():
                        ops.append(v)
            if ops:
                fp.write(f'Out [{ec}]:\n\n    ')
                fp.write('\n    '.join(ops))
                fp.write('\n\n')


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 register_handler(handler):
    """
    Install application-specific FITS image handler.

    :param handler: Handler object.
    """
    global _handler
    _handler = handler


def attr(obj, *path, **kwargs):
    """Safely get a nested attribute from an dictionary"""
    default = kwargs.get('default')
    if obj is None:
        return default
    res = obj
    for p in path:
        if p not in res:
            return default
        res = res[p]
    return res


def segment_generator(List, segment_size):
    """ Split a list into s segments of size r (segment_size).

        Parameters
        ----------
        List: list
            List of items to be segmented.
        segment_size: int
            Size of each segment.

        Returns
        -------
        Generator
    """
    for i in range(0, len(List), segment_size):
        yield List[i:i + segment_size]


def get_fees(inputs, outputs):
    """
    Blockstore currently does not allow
    the subsidization of namespaces.
    """
    return None, None


def document_repr(docid, default=None):
    """ Return an index-specific string representation for the docid value,
        or the default if no such docid exists in the index."""


@classmethod
def get(cls, **kwargs: dict) ->'Meta.Model':
    """
        Shortcut for get method of model
        return: Model
        """
    return cls.Meta.model.objects.get(**kwargs)


@classmethod
def isparentof(cls, other):
    """
    Determines if an axis object is an instance of a base class (or the same
    class) of another axis.

    Parameters
    ==========
    other : :class:`Axis` object to compare against this one.

    Returns
    =======
    bool : boolean
      True if ``other`` is an instance of this object's class
    """
    return isinstance(other, cls)


@classmethod
def increase(cls, name):
    """Increase counter of ``name`` by one."""
    return cls.change_by(name, 1)


@classmethod
def purge(cls):
    """Clear the expression compilation cache."""
    cls._CACHE.clear()


def impersonator_user_role(id, name):
    """
    Canned response for validate token if the token being validated
    is an impersonated token.
    """
    return {'id': id, 'roles': [{'id': '10000001', 'serviceId':
        'test-eabb70a0e702a4626977c331d5c4', 'description':
        'Service admin role for cloud feeds access. Assign only to service users'
        , 'name': 'cloudfeeds:service-admin'}, {'id': '10000002',
        'serviceId': 'test-eabb70a0e702a4626977c331d5c4', 'description':
        'Checkmate Access role', 'name': 'checkmate'}, {'id': '100000003',
        'serviceId': 'test-eabb70a0e702a4626977c331d5c4', 'description':
        'Service admin role for Monitoring access. Assign only to service users'
        , 'name': 'monitoring:service-admin'}, {'id': '100000004',
        'serviceId': 'test-eabb70a0e702a4626977c331d5c4', 'description':
        'Admin Role.', 'name': 'identity:admin'}, {'id': '10000005',
        'serviceId': 'test-d4614b87411e141fe8109099bc4f', 'description':
        'Role to access Customer service as an Admin', 'name':
        'customer:admin'}, {'id': '10000006', 'serviceId':
        'test-eabb70a0e702a4626977c331d5c4', 'description':
        'Service admin role for Cloud Backup access. Assign only to service users'
        , 'name': 'cloudbackup:service-admin'}], 'name': name}


def __iter__():
    """Iterator of objects providing IRepo"""


def get_factor(operator):
    """get the factor to adjust the volume, bass, treble... with

    Returns the parsed number, but accounts for operator-only input.

    >>> get_factor('+10')
    10

    >>> get_factor('+')
    1

    >>> get_factor('-')
    -1
    """
    if not operator.startswith(('+', '-')):
        raise ValueError('Valid operators are + and -')
    if len(operator) == 1:
        operator += '1'
    try:
        return int(operator)
    except ValueError:
        raise ValueError('"{}" is not a number or +/-'.format(operator))


def longest_string(strings):
    """
    Method returns the longest string from a list of strings
    :param strings: a list of string objects
    :return: the longest string from a `strings`
    """
    return max(strings, key=len)


def whitespace_tokenize(text):
    """Runs basic whitespace cleaning and splitting on a peice of text."""
    text = text.strip()
    if not text:
        return []
    tokens = text.split()
    return tokens


def context_set_value(data_path: str='', value: str=''):
    """Set a context value

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param value: Value, Assignment value (as a string)
    :type value: str
    """
    pass


def _toggle_instance(instance, new_value, old_value):
    """Alter instance upon visually toggling it"""
    instance.data['publish'] = new_value


def stroke_apply_thickness():
    """Apply the thickness change of the layer to its strokes

    """
    pass


@classmethod
def multipleBlocks(cls, p, reply, ciphering):
    """
        Check is all_ data fit to one data block.

        @param p
        LN parameters.
        @param reply
        Generated reply.
        """
    len_ = 0
    if p.data:
        len_ = len(p.data) - p.data.position
    if p.attributeDescriptor:
        len_ += p.attributeDescriptor.size
    if ciphering:
        len_ += cls.__CIPHERING_HEADER_SIZE
    if not p.multipleBlocks:
        p.multipleBlocks = 2 + len(reply) + len_ > p.settings.maxPduSize
    if p.multipleBlocks:
        p.lastBlock = not 8 + len(reply) + len_ > p.settings.maxPduSize
    if p.lastBlock:
        p.lastBlock = not 8 + len(reply) + len_ > p.settings.maxPduSize


@staticmethod
def validate(text):
    """Validate string format for this cipher.

        :param text: The cipher-text
        :type text: str

        :returns: Either the text is in the cipher format or not
        :rtype: bool

        :raise NotImplementedError: If the validate function not set in the decoder
        """
    raise NotImplementedError


def get_physrot_specs(cell_name, model):
    """  Return physrot specifications for cell types

    Parameters:
    -----------
    cell_name : string
        The name of the cell.
    Returns:
    --------
    polarlim : array_like
        lower and upper bound for the polar angle
    pref_orient : array_like
        3-dim vetor of preferred orientation
    """
    if model == 'bbp':
        polarlim = {'BP': [0.0, 15.0], 'AC': None, 'BTC': None, 'ChC': None,
            'DBC': None, 'LBC': None, 'MC': [0.0, 15.0], 'NBC': None, 'NGC':
            None, 'SBC': None, 'PC': [0.0, 15.0], 'SS': [0.0, 15.0], 'SP':
            [0.0, 15.0]}
        pref_orient = {'BP': [0.0, 0.0, 1.0], 'AC': None, 'BTC': None,
            'ChC': None, 'DBC': None, 'LBC': None, 'MC': [0.0, 0.0, 1.0],
            'NBC': None, 'NGC': None, 'SBC': None, 'PC': [0.0, 0.0, 1.0],
            'SS': [0.0, 0.0, 1.0], 'SP': [0.0, 0.0, 1.0]}
        polar = None
        orient = None
        for k in polarlim.keys():
            if k in cell_name.split('_')[1]:
                polar = polarlim[k]
                orient = pref_orient[k]
                break
        return polar, orient
    else:
        raise NotImplementedError('Cell model %s is not implemented' % model)


def load_ipython_extension(ip):
    """
    Special method to automatically make PNG objects display inline.

    MAY 2017: everything happens in converter.subConverters
    """
    try:
        from matplotlib import pyplot as plt
        plt.ion()
        ip.run_line_magic('config', "InlineBackend.figure_format = 'retina'")
    except ImportError:
        pass


def build_endpoint_route_name(cls, method_name, class_name=None):
    """
    Build the route endpoint
    It is recommended to place your views in /views directory, so it can build
    the endpoint from it. If not, it will make the endpoint from the module name
    The main reason for having the views directory, it is explicitly easy
    to see the path of the view

    :param cls: The view class
    :param method_name: The name of the method
    :param class_name: To pass the class name.
    :return: string
    """
    return '%s.%s:%s' % (cls.__module__, class_name or cls.__name__,
        method_name)


def log2(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise Base-2 logarithmic value of the input.

    ``2**log2(x) = x``

    The storage type of ``log2`` output is always dense

    Defined in src/operator/tensor/elemwise_unary_op_logexp.cc:L105

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

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

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


def _applySpecial_VectorOpts_orientFlip(args, overlayList, displayCtx, target):
    """Applies the ``VectorOpts.orientFlip`` option.

    The :attr:`.VectorOpts.orientFlip` property is initialised to ``False``
    for images with a radiological storage order, and ``True`` for images with
    a neurological storage order. So if this argument is specified, we need to
    invert its initial value - apply the flip for radiologically stored
    images, but not for neurologically stored images.
    """
    target.orientFlip = not target.orientFlip


def set_default_user(profile, user):
    """Set the user as the default user for the given profile.

    :param profile: the profile
    :param user: the user
    """
    from aiida.manage.configuration import get_config
    config = get_config()
    profile.default_user = user.email
    config.update_profile(profile)
    config.store()


def can_paginate(operation_name=None):
    """
    Check if an operation can be paginated.

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

    """
    pass


def make_covmatrix(sigma_x, sigma_y, rho=0):
    """ create covariance matrix from given standard deviations and normalised correlation rho, vectorized """
    return (sigma_x ** 2, rho * sigma_x * sigma_y), (rho * sigma_x *
        sigma_y, sigma_y ** 2)


def get_all_param(current_scene_db):
    """returns a list of set parameters in the scene"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(current_scene_db)
    cur = conn.cursor()
    list_param = 'SELECT * FROM "Parameters" ORDER BY Parameter DESC'
    cur.execute(list_param)
    conn.commit()
    rows = cur.fetchall()
    conn.close()
    return rows


def _digestpw_plaintext(password, salt=None):
    """ No password digest, just store the passwords in plain text. """
    if not salt:
        salt = 'none'
    return salt, password


def revision_before(latest_revision: int, revisions: list) ->dict:
    """Finds the revision before the current revision"""
    for revision in reversed(revisions):
        if revision['revision'] < latest_revision:
            return revision
    raise ValueError('No earlier revision found')


def delPage(pageIndex, retJson=True):
    """ Delete specific page.
        Note: If there is only one page left, can not delete the page.

        @param pageIndex
        index of the page to be deleted

        @retJson
        format return value to json format or not( default True )

        @return
        a dict contains state of process, format like:
        {
            'success': True,
            'msg': 'Delete page success.'
        }

        """


def consonants_between_vowels(name1):
    """Vowels between consonants find the vowels mapping between consonant
       example: pradeeip-----> {pr,d,p}
    """
    list_vowels = ['a', 'e', 'i', 'o', 'u']
    index_list = []
    ans_list = []
    for index, item in enumerate(name1):
        if item in list_vowels:
            index_list.append(index)
    if index_list[0] not in list_vowels:
        ans_list.append(name1[:index_list[0]])
    for i in range(len(index_list) - 1):
        ans_list.append(name1[index_list[i] + 1:index_list[i + 1]])
    if index_list[-1] < len(name1) - 1:
        ans_list.append(name1[index_list[-1] + 1:])
    ans_list = list(filter(None, ans_list))
    return ans_list


def stepText2Changed(build, step, text2):
    """The text2 for a step has been updated.

        This is called when calling setText2() on the step status, and
        hands in text2 list."""


def encode(headers, sequences):
    """
    This creates the contents of a non-interleaved phylip sequence file.
    @param headers: some header strings
    @param sequences: some sequence strings
    """
    nrows = len(headers)
    ncols = len(sequences[0])
    out_lines = ['%d %d' % (nrows, ncols)]
    for h, seq in zip(headers, sequences):
        out_h = h[:10].ljust(10)
        out_lines.append(out_h + seq)
    return '\n'.join(out_lines)


@classmethod
def from_int(cls, roman_as_int):
    """ Create a RomanNumeral object from an int

        """
    cls(roman_as_int)


def nextpow2(n):
    """Find :math:`p` that satisfies :math:`2^p \\ge |n|`.

    Parameters
    ----------
    n : int or float

    Returns
    -------
    p : int
        the power of 2 satisfying :math:`2^p \\ge |n|`.

    """
    p = 0
    pow2 = 2 ** p
    while pow2 < abs(n):
        p = p + 1
        pow2 = 2 ** p
    return p


@staticmethod
def _set_config_section(config, section, **kwargs):
    """
        Set the configuration section in the file with the properties given. The section
        must exist before calling this method.

        :param config: the configuration object
        :param section: the name of the section
        :param kwargs: the key value pairs to put into the section
        :return: Nothing
        """
    for name, value in kwargs.items():
        config.set(section, name, value)


@staticmethod
def _duration_to_secs(duration):
    """Convert all duration specifications into seconds."""
    secs = int(duration[:-1])
    if duration[-1] == 's':
        pass
    elif duration[-1] == 'm':
        secs *= 60
    elif duration[-1] == 'h':
        secs *= 60 * 60
    elif duration[-1] == 'd':
        secs *= 60 * 60 * 24
    else:
        raise ValueError('Invalid duration: %r' % duration)
    return secs


@staticmethod
def p_supplier(p):
    """supplier : SUPPLIER STRING"""
    p[0] = p[2]


@staticmethod
def _get_reduced_dataframe(df):
    """
        Exclude empty column "Tabellhuvud:"
        :param df: pd.DataFrame
        :return: Reduced pd.DataFrame
        """
    if 'Tabellhuvud:' in df:
        df.pop('Tabellhuvud:')
    return df


def update_table_args_2_dict(args):
    """
    change update_table_args to dict

    :param args: update table args
    :type args: UpdateTableArgs

    :return:
    :rtype dict
    """
    return {'tableVersion': args.table_version, 'compressType': args.
        compress_type, 'ttl': args.ttl, 'maxVersions': args.max_versions}


def warning(dirname, msg):
    """warning(dirname, msg) -> None

    Print a warning.
    """
    print('Warning: ' + msg)


def inset_rect(rect, amount):
    """ Return rectangle inset by given amount. """
    return (rect[0][0] + amount, rect[0][1] + amount), (rect[1][0] - 2 *
        amount, rect[1][1] - 2 * amount)


def vert_connect_path():
    """Connect vertices by their selection order, creating edges, splitting faces

    """
    pass


@classmethod
def start_next_scene(cls):
    """
        Start next scene
        """
    cls.current_running_scene.start()
    cls.current_running_scene.scene_loop()


def get_caption(etype, cell_meta, resources):
    """return an ipypublish caption or False

    captions can either be located at cell_meta.ipub.<type>.caption,
    or at resources.caption[cell_meta.ipub.<type>.label]

    the resources version is proritised
    """
    try:
        caption = cell_meta['ipub'][etype]['caption']
    except (KeyError, TypeError):
        caption = False
    try:
        label = cell_meta['ipub'][etype]['label']
    except (KeyError, TypeError):
        label = False
    rcaption = False
    if label:
        try:
            rcaption = resources['caption'][label]
        except (KeyError, TypeError):
            pass
    if rcaption:
        return rcaption
    return caption


def sort_by_onset(sounding_notes):
    """
    Sort a list of notes by pitch

    Parameters
    ----------
    sounding_notes : list
        List of `VSNote` instances

    Returns
    -------
    list
        List of sounding notes sorted by onset
    """
    return sorted(sounding_notes, key=lambda x: x.onset)


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


def psi_K_Cl_SO4_HMW84(T, P):
    """c-a-a': potassium chloride sulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def _set_global(env, func_name, func):
    """Set a template environment global function."""
    env.globals[func_name] = func
    return env


@classmethod
def _merge_options(cls, old_opts, new_opts):
    """
        Update the old_opts option dictionary with the options defined in
        new_opts. Instead of a shallow update as would be performed by calling
        old_opts.update(new_opts), this updates the dictionaries of all option
        types separately.

        Given two dictionaries
            old_opts = {'a': {'x': 'old', 'y': 'old'}}
        and
            new_opts = {'a': {'y': 'new', 'z': 'new'}, 'b': {'k': 'new'}}
        this returns a dictionary
            {'a': {'x': 'old', 'y': 'new', 'z': 'new'}, 'b': {'k': 'new'}}
        """
    merged = dict(old_opts)
    for option_type, options in new_opts.items():
        if option_type not in merged:
            merged[option_type] = {}
        merged[option_type].update(options)
    return merged


def is_publicly_trusted(domain):
    """
    A domain has a "Publicly Trusted" certificate if its canonical
    endpoint has a publicly trusted certificate.
    """
    canonical, https, httpswww = (domain.canonical, domain.https, domain.
        httpswww)
    if canonical.host == 'root':
        evaluate = https
    else:
        evaluate = httpswww
    return evaluate.live and evaluate.https_public_trusted


@classmethod
def get_verbose_name_plural(cls):
    """
        A convenience method to get the base model verbose name, needed in templates
        :return:
        """
    return cls._meta.verbose_name_plural


def __get_vm_attr_variable_value(var_config_values, vm_dict):
    """
    Returns the associated value contained on a VM instance
    :param var_config_values: the configuration dictionary
    :param vm_dict: the dictionary containing all VMs where the key is the VM's
                    name
    :return: the value
    """
    vm = vm_dict.get(var_config_values['vm_name'])
    if vm:
        if var_config_values['value'] == 'floating_ip':
            return vm.get_floating_ip().ip
        if var_config_values['value'] == 'image_user':
            return vm.get_image_user()


def to_two_bytes(integer):
    """
    Breaks an integer into two 7 bit bytes.
    """
    if integer > 32767:
        raise ValueError(
            "Can't handle values bigger than 32767 (max for 2 bits)")
    return bytearray([integer % 128, integer >> 7])


def runfcgi(func, addr=('0.0.0.0', 8000)):
    """Runs a WSGI function as a FastCGI server."""
    import flup.server.fcgi as flups
    return flups.WSGIServer(func, multiplexed=True, bindAddress=addr, debug
        =False).run()


def delete_trust(TrustId=None, DeleteAssociatedConditionalForwarder=None):
    """
    Deletes an existing trust relationship between your Microsoft AD in the AWS cloud and an external domain.
    See also: AWS API Documentation

    :example: response = client.delete_trust(
        TrustId='string',
        DeleteAssociatedConditionalForwarder=True|False
    )

    :type TrustId: string
    :param TrustId: [REQUIRED]
            The Trust ID of the trust relationship to be deleted.

    :type DeleteAssociatedConditionalForwarder: boolean
    :param DeleteAssociatedConditionalForwarder: Delete a conditional forwarder as part of a DeleteTrustRequest.

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

    """
    pass


def _load():
    """Read prime entries from file system into list."""
    ps = []
    for digits in range(1, 7):
        ps.extend(map(int, open('data/' + str(digits)).read().split('\n')))
    return ps


def p_element_list(p):
    """element_list : element_list element """
    if not p[2] is None:
        p[0] = p[1] + [p[2]]
    else:
        p[0] = p[1]


def source_header(filename, target_name, ltag):
    """Returns lines that begin a source file"""
    return ['// Generated by the lua-protobuf compiler',
        "// You shouldn't edit this file manually", '//',
        '// source proto file: %s' % filename, '', '#include "%s.pb-lua.h"' %
        target_name, '', '#ifdef __cplusplus',
        'extern "C" { // make sure functions treated with C naming',
        '#endif', '', '#include <lauxlib.h>', '', '#ifdef __cplusplus', '}',
        '#endif', '', '#include <string>', '',
        '// this represents Lua udata for a protocol buffer message',
        '// we record where a message came from so we can GC it properly',
        'typedef struct msg_udata { // confuse over-simplified pretty-printer',
        '    ::google::protobuf::Message%s * msg;' % ltag,
        '    bool lua_owns;', '    lua_protobuf_gc_callback gc_callback;',
        '    void * callback_data;', '} msg_udata;', '']


def add_scheme_if_missing(url):
    """
    >>> add_scheme_if_missing("example.org")
    'http://example.org'
    >>> add_scheme_if_missing("https://example.org")
    'https://example.org'
    """
    if '//' not in url:
        url = 'http://%s' % url
    return url


def persist_sequence(run, sequence, fitness_val):
    """
    Persist the sequence and its fitness value in the database.

    Args:
        run: The current run we are attached to, with all its information.
        sequence: The fittest sequence generated by an algorithm.
        fitness_val: The fittest algorithm generated by an algorithm.
    """
    from benchbuild.utils import schema as s
    session = run.session
    session.commit()


def create(object_id, data):
    """
        Create an object within the collection and return the new ``object_id``
        and object data. May return a deferred.

        If ``object_id`` is ``None``, an identifier will be generated. Some
        collections may insist on generating their own ``object_id`` and raise
        a :class:`CollectionUsageError` if an ``object_id`` is given.

        Should raise :class:`CollectionObjectAlreadyExists` if ``object_id`` is
        not ``None`` and already exists.
        """


def queryDefaultViewName(object, request, default=None, context=None):
    """Look for the name of the default view for the object and request.

        If a matching default view name cannot be found, returns the default.

        If context is not specified, attempts to use object to specify
        a context.
        """


def _buildParams(userInput):
    """ Takes a dictionary of user-inputted paramaters, where the keys are the names
	of the parameters in the URL and the values are either None or the value of the parameters
	in the URL."""
    params = '?'
    for key, value in userInput.items():
        if value != None:
            params += '%s=%s&' % (key, value)
    return params


@classmethod
def attach_barcodes(cls, args=None):
    """command line entrypoint for attaching barcodes to a bamfile."""
    raise NotImplementedError


def _check_for_too_many_exclusions(exclude_instances, available_instances,
    delta, groups_members):
    """
        Check whether the amount of exluded instances will make it possible to
        scale down by the given delta.

        :param exclude_instances: A list of node instance IDs to exclude.
        :param available_instances: A list of all available instance IDs. For
                                    groups this should include both the group
                                    instance IDs and the member node instance
                                    IDs.
        :param delta: How much to scale by. This is expected to be negative.
        :param groups_members: A dict of group instances with their members,
                               e.g. produced by get_groups_with_members
        :return: A string detailing problems if there are any, or an empty
                 string if there are no problems.
    """
    if groups_members:
        excluded_groups = set()
        for inst in exclude_instances:
            for group, members in groups_members.items():
                if inst in members or inst == group:
                    excluded_groups.add(group)
        planned_group_instances = len(groups_members) + delta
        if planned_group_instances < len(excluded_groups):
            return (
                'Instances from too many different groups were excluded. Target number of group instances was {group_count}, but {excluded_count} excluded groups.'
                .format(group_count=planned_group_instances, excluded_count
                =len(excluded_groups)))
    else:
        planned_num_instances = len(available_instances) + delta
        if planned_num_instances < len(exclude_instances):
            return (
                'Target number of instances is less than excluded instance count. Target number of instances was {target}. Excluded instances were: {instances}. '
                .format(target=planned_num_instances, instances=', '.join(
                exclude_instances)))
    return ''


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a GitHub item."""
    if 'forks_count' in item:
        return str(item['fetched_on'])
    else:
        return str(item['id'])


def get(propagate=True):
    """Wait until the task is ready and return its result."""


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

    The ".dev0" means dirty.

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


def _basename_in_blacklist_re(base_name, black_list_re):
    """Determines if the basename is matched in a regex blacklist

    :param str base_name: The basename of the file
    :param list black_list_re: A collection of regex patterns to match against.
        Successful matches are blacklisted.

    :returns: `True` if the basename is blacklisted, `False` otherwise.
    :rtype: bool
    """
    for file_pattern in black_list_re:
        if file_pattern.match(base_name):
            return True
    return False


def focal_rf(radius):
    """Usage: focal point with radius for concave and convex mirrors"""
    return radius / 2


def get_json_content(window, simple_mode=True):
    """
    Extract information from json to a dict

    :param window:
    :return:
    """
    info = {'left_index': window.left, 'right_index': window.right,
        'center_index': window.center, 'channel_id': window.channel_id,
        'time_of_first_sample': window.time_of_first_sample, 'max_cc_value':
        window.max_cc_value, 'cc_shift_in_samples': window.cc_shift,
        'cc_shift_in_seconds': window.cc_shift_in_seconds, 'dlnA': window.
        dlnA, 'dt': window.dt, 'min_period': window.min_period,
        'absolute_starttime': window.absolute_starttime, 'absolute_endtime':
        window.absolute_endtime, 'relative_starttime': window.
        relative_starttime, 'relative_endtime': window.relative_endtime,
        'window_weight': window.weight}
    if not simple_mode:
        info['phase_arrivals'] = window.phase_arrivals
    if 'channel_id_2' in dir(window):
        info['channel_id_2'] = window.channel_id_2
    return info


def _table_columns(first_table_row):
    """Find column ranges in output line.

    Return list of tuples (start,end) for each column
    detected by plus (+) characters in delimiter line.
    """
    positions = []
    start = 1
    while start < len(first_table_row):
        end = first_table_row.find('+', start)
        if end == -1:
            break
        positions.append((start, end))
        start = end + 1
    return positions


def isiterable(obj):
    """
    Tests if the argument is an iterable

    :param obj: Object
    :type  obj: any

    :rtype: boolean
    """
    try:
        iter(obj)
    except TypeError:
        return False
    else:
        return True


def scale_action(action_space, action):
    """
    Rescale the action from [low, high] to [-1, 1]
    (no need for symmetric action space)

    :param action_space: (gym.spaces.box.Box)
    :param action: (np.ndarray)
    :return: (np.ndarray)
    """
    low, high = action_space.low, action_space.high
    return 2.0 * ((action - low) / (high - low)) - 1.0


def invert(image):
    """
    Invert an image (channel).

    .. code-block:: python

        out = MAX - image

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image.load()
    return image._new(image.im.chop_invert())


def get_pt2262_deviceid(device_id, nb_data_bits):
    """Extract and return the address bits from a Lighting4/PT2262 packet."""
    if nb_data_bits is None:
        return
    import binascii
    try:
        data = bytearray.fromhex(device_id)
    except ValueError:
        return None
    mask = 255 & ~((1 << nb_data_bits) - 1)
    data[len(data) - 1] &= mask
    return binascii.hexlify(data)


def cMultiplyScalar():
    """
    Return the kernel source for cMultiplyScalar.
    """
    code_text = """
        KERNEL void cMultiplyScalar(
                     const float2 CA,
                GLOBAL_MEM float2 *CX)
        {
        // Scale CX by CA: CX=CA*CX
        //  CA: scaling factor(float2)
        //*CX: input, output array(float2)
        unsigned long gid = get_global_id(0);
        CX[gid].x=CA.x*CX[gid].x-CA.y*CX[gid].y;
        CX[gid].y=CA.x*CX[gid].y+CA.y*CX[gid].x;
        };
        """
    return code_text


@classmethod
def speedDial(cls):
    """
        Class method to get a reference to the speed dial.

        @return reference to the speed dial (SpeedDial)
        """
    if cls._speedDial is None:
        from .SpeedDial.SpeedDial import SpeedDial
        cls._speedDial = SpeedDial()
    return cls._speedDial


def unserialize(cls, s):
    """ classmethod to create an item from its serialized version """


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

        :param LegalHoldsExportRemovedType val:
        :rtype: EventType
        """
    return cls('legal_holds_export_removed', val)


def create_route_short_name(relation):
    """Create a meaningful route short name."""
    return relation.tags.get('ref') or ''


def get_tlv(tlvs, cls):
    """Find the instance of a class in a list"""
    for tlv in tlvs:
        if isinstance(tlv, cls):
            return tlv


@staticmethod
def __format_rowname(stru):
    """
        Private method to format the name of the rows in the stats table
        :param stru:
        :return:
        """
    total_length = 35
    return ' ' * (total_length - len(stru) - 1) + '{}:'.format(stru.rstrip(':')
        )


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

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

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


def get_or_create_user_by_crsid(crsid):
    """ Returns the django user corresponding to the crsid parameter.
        :param crsid: the crsid of the retrieved user
    """
    from django.contrib.auth.models import User
    user = User.objects.filter(username=crsid)
    if user.exists():
        user = user.first()
    else:
        user = User.objects.create_user(username=crsid)
    return user


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


def ordinal(value):
    """
    Converts zero or a *postive* integer (or their string
    representations) to an ordinal value.

    >>> for i in range(1,13):
    ...     ordinal(i)
    ...
    '1st'
    '2nd'
    '3rd'
    '4th'
    '5th'
    '6th'
    '7th'
    '8th'
    '9th'
    '10th'
    '11th'
    '12th'

    >>> for i in (100, '111', '112',1011):
    ...     ordinal(i)
    ...
    '100th'
    '111th'
    '112th'
    '1011th'

    Notes
    -----
    Author:  Serdar Tumgoren
    http://code.activestate.com/recipes/576888-format-a-number-as-an-ordinal/
    MIT license
    """
    try:
        value = int(value)
    except ValueError:
        return value
    if value % 100 // 10 != 1:
        if value % 10 == 1:
            ordval = '%d%s' % (value, 'st')
        elif value % 10 == 2:
            ordval = '%d%s' % (value, 'nd')
        elif value % 10 == 3:
            ordval = '%d%s' % (value, 'rd')
        else:
            ordval = '%d%s' % (value, 'th')
    else:
        ordval = '%d%s' % (value, 'th')
    return ordval


def ones_comp_sum16(num1: int, num2: int) ->int:
    """Calculates the 1's complement sum for 16-bit numbers.

    Args:
        num1: 16-bit number.
        num2: 16-bit number.

    Returns:
        The calculated result.
    """
    carry = 1 << 16
    result = num1 + num2
    return result if result < carry else result + 1 - carry


def add_species_aliases(registry, ftype, alias_species, species):
    """
    This takes a field registry, a fluid type, and two species names.
    The first species name is one you wish to alias to an existing species
    name.  For instance you might alias all "H_p0" fields to "H\\_" fields
    to indicate that "H\\_" fields are really just neutral hydrogen fields.
    This function registers field aliases for the density, number_density,
    mass, and fraction fields between the two species given in the arguments.
    """
    registry.alias((ftype, '%s_density' % alias_species), (ftype,
        '%s_density' % species))
    registry.alias((ftype, '%s_fraction' % alias_species), (ftype,
        '%s_fraction' % species))
    registry.alias((ftype, '%s_number_density' % alias_species), (ftype,
        '%s_number_density' % species))
    registry.alias((ftype, '%s_mass' % alias_species), (ftype, '%s_mass' %
        species))


def read():
    """Obtain the parsed manifest data structure.

        The returned object conforms to the ``imanifestdict`` interface.
        """


def nd(fsm, group, phi):
    """
    Return the set of states of fsm satisfying nD<group> phi

    fsm -- a MAS representing the system
    group -- a non-empty list of (str) names of agents of fsm
    phi -- a BDD representing the set of states of fsm satisfying phi
    """
    return fsm.equivalent_states(phi & fsm.reachable_states, frozenset(group)
        ) & fsm.reachable_states


def normalize_weekly(data):
    """Normalization for dining menu data"""
    if 'tblMenu' not in data['result_data']['Document']:
        data['result_data']['Document']['tblMenu'] = []
    if isinstance(data['result_data']['Document']['tblMenu'], dict):
        data['result_data']['Document']['tblMenu'] = [data['result_data'][
            'Document']['tblMenu']]
    for day in data['result_data']['Document']['tblMenu']:
        if 'tblDayPart' not in day:
            continue
        if isinstance(day['tblDayPart'], dict):
            day['tblDayPart'] = [day['tblDayPart']]
        for meal in day['tblDayPart']:
            if isinstance(meal['tblStation'], dict):
                meal['tblStation'] = [meal['tblStation']]
            for station in meal['tblStation']:
                if isinstance(station['tblItem'], dict):
                    station['tblItem'] = [station['tblItem']]
    return data


def find_open_and_close_braces(line_index, start, brace, lines):
    """
    Take the line where we want to start and the index where we want to start
    and find the first instance of matched open and close braces of the same
    type as brace in file file.

    :param: line (int): the index of the line we want to start searching at
    :param: start (int): the index in the line we want to start searching at
    :param: brace (string): one of the type of brace we are looking for ({, },
        [, or ])
    :param lines ([string, string, ...]): the array of lines in the file we
        are looking in.

    :return: (start, start_line, end, end_line): (int, int, int): the index
        of the start and end of whatever braces we are looking for, and the
        line number that the end is on (since it may be different than the line
        we started on)
    """
    if brace in ['[', ']']:
        open_brace = '['
        close_brace = ']'
    elif brace in ['{', '}']:
        open_brace = '{'
        close_brace = '}'
    elif brace in ['(', ')']:
        open_brace = '('
        close_brace = ')'
    else:
        return -1, -1, -1, -1
    open_braces = []
    line = lines[line_index]
    ret_open_index = line.find(open_brace, start)
    line_index_cpy = line_index
    while ret_open_index == -1:
        line_index = line_index + 1
        if line_index >= len(lines):
            return 0, line_index_cpy, 0, line_index_cpy
        line = lines[line_index]
        ret_open_index = line.find(open_brace)
    open_braces.append(open_brace)
    ret_open_line = line_index
    open_index = ret_open_index
    close_index = ret_open_index
    while len(open_braces) > 0:
        if open_index == -1 and close_index == -1:
            line_index = line_index + 1
            if line_index >= len(lines):
                return (ret_open_index, ret_open_line, ret_open_index,
                    ret_open_line)
            line = lines[line_index]
            close_index = line.find(close_brace)
            open_index = line.find(open_brace)
        else:
            if close_index != -1:
                close_index = line.find(close_brace, close_index + 1)
            if open_index != -1:
                open_index = line.find(open_brace, open_index + 1)
        if close_index != -1:
            open_braces.pop()
            if len(open_braces) == 0 and (open_index > close_index or
                open_index == -1):
                break
        if open_index != -1:
            open_braces.append(open_brace)
    ret_close_index = close_index
    return ret_open_index, ret_open_line, ret_close_index, line_index


def load_glib(finder, module):
    """Ignore globals that are imported."""
    module.AddGlobalName('GError')
    module.AddGlobalName('IOChannel')
    module.AddGlobalName('IO_ERR')
    module.AddGlobalName('IO_FLAG_APPEND')
    module.AddGlobalName('IO_FLAG_GET_MASK')
    module.AddGlobalName('IO_FLAG_IS_READABLE')
    module.AddGlobalName('IO_FLAG_IS_SEEKABLE')
    module.AddGlobalName('IO_FLAG_IS_WRITEABLE')
    module.AddGlobalName('IO_FLAG_MASK')
    module.AddGlobalName('IO_FLAG_NONBLOCK')
    module.AddGlobalName('IO_FLAG_SET_MASK')
    module.AddGlobalName('IO_HUP')
    module.AddGlobalName('IO_IN')
    module.AddGlobalName('IO_NVAL')
    module.AddGlobalName('IO_OUT')
    module.AddGlobalName('IO_PRI')
    module.AddGlobalName('IO_STATUS_AGAIN')
    module.AddGlobalName('IO_STATUS_EOF')
    module.AddGlobalName('IO_STATUS_ERROR')
    module.AddGlobalName('IO_STATUS_NORMAL')
    module.AddGlobalName('Idle')
    module.AddGlobalName('MainContext')
    module.AddGlobalName('MainLoop')
    module.AddGlobalName('OPTION_ERROR')
    module.AddGlobalName('OPTION_ERROR_BAD_VALUE')
    module.AddGlobalName('OPTION_ERROR_FAILED')
    module.AddGlobalName('OPTION_ERROR_UNKNOWN_OPTION')
    module.AddGlobalName('OPTION_FLAG_FILENAME')
    module.AddGlobalName('OPTION_FLAG_HIDDEN')
    module.AddGlobalName('OPTION_FLAG_IN_MAIN')
    module.AddGlobalName('OPTION_FLAG_NOALIAS')
    module.AddGlobalName('OPTION_FLAG_NO_ARG')
    module.AddGlobalName('OPTION_FLAG_OPTIONAL_ARG')
    module.AddGlobalName('OPTION_FLAG_REVERSE')
    module.AddGlobalName('OPTION_REMAINING')
    module.AddGlobalName('OptionContext')
    module.AddGlobalName('OptionGroup')
    module.AddGlobalName('PRIORITY_DEFAULT')
    module.AddGlobalName('PRIORITY_DEFAULT_IDLE')
    module.AddGlobalName('PRIORITY_HIGH')
    module.AddGlobalName('PRIORITY_HIGH_IDLE')
    module.AddGlobalName('PRIORITY_LOW')
    module.AddGlobalName('Pid')
    module.AddGlobalName('PollFD')
    module.AddGlobalName('SPAWN_CHILD_INHERITS_STDIN')
    module.AddGlobalName('SPAWN_DO_NOT_REAP_CHILD')
    module.AddGlobalName('SPAWN_FILE_AND_ARGV_ZERO')
    module.AddGlobalName('SPAWN_LEAVE_DESCRIPTORS_OPEN')
    module.AddGlobalName('SPAWN_SEARCH_PATH')
    module.AddGlobalName('SPAWN_STDERR_TO_DEV_NULL')
    module.AddGlobalName('SPAWN_STDOUT_TO_DEV_NULL')
    module.AddGlobalName('Source')
    module.AddGlobalName('Timeout')
    module.AddGlobalName('child_watch_add')
    module.AddGlobalName('filename_display_basename')
    module.AddGlobalName('filename_display_name')
    module.AddGlobalName('filename_from_utf8')
    module.AddGlobalName('get_application_name')
    module.AddGlobalName('get_current_time')
    module.AddGlobalName('get_prgname')
    module.AddGlobalName('glib_version')
    module.AddGlobalName('idle_add')
    module.AddGlobalName('io_add_watch')
    module.AddGlobalName('main_context_default')
    module.AddGlobalName('main_depth')
    module.AddGlobalName('markup_escape_text')
    module.AddGlobalName('set_application_name')
    module.AddGlobalName('set_prgname')
    module.AddGlobalName('source_remove')
    module.AddGlobalName('spawn_async')
    module.AddGlobalName('timeout_add')
    module.AddGlobalName('timeout_add_seconds')


def clear_url(url):
    """ Remove domain and protocol from url """
    if url.startswith('http'):
        return '/' + url.split('/', 3)[-1]
    return url


def _pad_sequence_fix(attr, kernel_dim=None):
    """Changing onnx's pads sequence to match with mxnet's pad_width
    mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)
    onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)"""
    new_attr = ()
    if len(attr) % 2 == 0:
        for index in range(int(len(attr) / 2)):
            new_attr = new_attr + attr[index::int(len(attr) / 2)]
        if kernel_dim is not None:
            while len(new_attr) < kernel_dim * 2:
                new_attr = new_attr + (0, 0)
    return new_attr


@staticmethod
def __check_response(status_code):
    """Raises an assertion error if the status code is not a success"""
    first_digit = status_code // 100
    assert first_digit in (2, 3)


@staticmethod
def _source_kafka():
    """Method to as kafka as source."""
    pass


def get_compliance_summary_by_resource_type(ResourceTypes=None):
    """
    Returns the number of resources that are compliant and the number that are noncompliant. You can specify one or more resource types to get these numbers for each resource type. The maximum number returned is 100.
    See also: AWS API Documentation

    :example: response = client.get_compliance_summary_by_resource_type(
        ResourceTypes=[
            'string',
        ]
    )

    :type ResourceTypes: list
    :param ResourceTypes: Specify one or more resource types to get the number of resources that are compliant and the number that are noncompliant for each resource type.
            For this request, you can specify an AWS resource type such as AWS::EC2::Instance , and you can specify that the resource type is an AWS account by specifying AWS::::Account .
            (string) --

    :rtype: dict
    :return: {
        'ComplianceSummariesByResourceType': [
            {
                'ResourceType': 'string',
                'ComplianceSummary': {
                    'CompliantResourceCount': {
                        'CappedCount': 123,
                        'CapExceeded': True|False
                    },
                    'NonCompliantResourceCount': {
                        'CappedCount': 123,
                        'CapExceeded': True|False
                    },
                    'ComplianceSummaryTimestamp': datetime(2015, 1, 1)
                }
            },
        ]
    }

    """
    pass


def translate_attach(TRANSFORM_OT_translate=None, NODE_OT_attach=None,
    NODE_OT_insert_offset=None):
    """Move nodes and attach to frame

    :param TRANSFORM_OT_translate: Move, Move selected items
    :param NODE_OT_attach: Attach Nodes, Attach active node to a frame
    :param NODE_OT_insert_offset: Insert Offset, Automatically offset nodes on insertion
    """
    pass