def hash_password(plaintext_password=''):
    """
    Create a password hash from a given string for protecting a worksheet
    only. This will not work for encrypting a workbook.

    This method is based on the algorithm provided by
    Daniel Rentz of OpenOffice and the PEAR package
    Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>.
    See also http://blogs.msdn.com/b/ericwhite/archive/2008/02/23/the-legacy-hashing-algorithm-in-open-xml.aspx
    """
    password = 0
    for idx, char in enumerate(plaintext_password, 1):
        value = ord(char) << idx
        rotated_bits = value >> 15
        value &= 32767
        password ^= value | rotated_bits
    password ^= len(plaintext_password)
    password ^= 52811
    return str(hex(password)).upper()[2:]


def add_dictval_to_list(adict, key, alist):
    """add a value from a dictionary to a list

    :param adict: dictionary
    :param key: key of value
    :param list: list where value should be added
    """
    if key in adict.keys():
        if type(adict[key]) == str:
            alist.append(adict[key])
        else:
            alist.extend(adict[key])


def rename_app_parameters(app, model):
    """Rename all parameters for a given app."""
    qset = model.objects.filter(name__startswith=app[0])
    for param in qset:
        param.name = param.name.replace('{}.'.format(app[0]), '{}.'.format(
            app[1]))
        param.save()


def mean(seq):
    """Return the mean of all values from seq."""
    try:
        N = float(len(seq))
        return sum(seq) / N
    except TypeError:
        N = S = 0.0
        for x in seq:
            N += 1
            S += x
        return S / N


@classmethod
def true(cls, key):
    """True if the specified key is present in the job document and
        evaluates to True."""
    return cls(lambda job: job.document.get(key, False), 'true_' + key)


def linear(x):
    """
    Convert a dB value in linear.
    """
    return 10 ** (x / 10)


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

        :param FileLockingPolicyChangedDetails val:
        :rtype: EventDetails
        """
    return cls('file_locking_policy_changed_details', val)


def get_url_csl_item_zotero(url):
    """
    Use Zotero's translation-server to generate a CSL Item for the specified URL.
    """
    from manubot.cite.zotero import export_as_csl, web_query
    zotero_data = web_query(url)
    csl_data = export_as_csl(zotero_data)
    csl_item, = csl_data
    return csl_item


@classmethod
def loadf_all(cls, file_handle):
    """create objects of Model class from a file containing an array of JSON-encoded objects"""
    cls.loads_all(file_handle.read())


def ceiling_from_str(src):
    """A simply restriction on integer:

    <xs:simpleType name="Ceiling">
            <xs:restriction base="xs:integer">
                    <xs:maxInclusive value="32767"/>
                    <xs:minInclusive value="-1"/>
            </xs:restriction>
    </xs:simpleType>
    """
    value = int(src)
    if value < -1 or value > 32767:
        raise ValueError('Value exceeds bounds for CEILING: %i' % value)
    return value


@classmethod
def exists(cls, team_name):
    """Determines if a team exists, by name.

        Returns:
            bool: True if team_name exists for a valid team, false otherwise
        """
    return team_name in cls.team_names()


def _fill_journal(r, entry):
    """
    Make a "journal" dict
    :param r: BibJSON record dict that will be filled
    :param entry: bibtexparser entry that will be used to fill the BibJSON record
    :return None
    """
    if 'journal' not in entry.keys():
        return
    r['journal'] = {'name': entry['journal']}
    opt_keys = 'number', 'pages', 'month', 'volume'
    for k in opt_keys:
        if k in entry:
            r['journal'][k] = entry[k]


def rule_del():
    """Delete current boid rule

    """
    pass


@classmethod
def get_last_id(cls):
    """ Return the last primary key ``id`` value
        """
    res = cls.query('id').order_by(cls.id.desc()).limit(1).first()
    if res:
        return res[0]
    return 0


def get_or_create_spark_session(spark_config=None, log_level='ERROR',
    enableHiveSupport=True):
    """
    Gets or initiates an Spark session.

    :param dict spark_config: the parameters based on which the Spark session is to be initiated
    :param log_level: The log level of the Spark session
    :param bool enableHiveSupport: If set to true Hive support will be enabled
    :return: A spark session object
    """
    from pyspark.sql import SparkSession
    builder = SparkSession.builder
    if spark_config:
        for key, value in spark_config.items():
            builder = SparkSession.builder.config(key, value)
    if enableHiveSupport:
        builder = builder.enableHiveSupport()
    spark = builder.getOrCreate()
    spark.sparkContext.setLogLevel(log_level)
    return spark


def p_arglist_star3_1(p):
    """arglist_star3 : COMMA argument"""
    p[0] = [p[2]]


def fetch_process(job, key):
    """ complete fetch requests in parallel for fetch_handler
        job:
            job queue containing (callable, kwargs)
        key:
            multiprocessing lock (database access key)
    """
    while not job.empty():
        req = job.get()
        if not req[0](lock=key, **req[1]):
            pass
    return


def _posargs_to_provides(posargspec, posargs):
    """Automatically unwrap injectable posargs into a more intuitive
    format, similar to an API a human might design. For instance, a
    function which takes exactly one argument would not take a list of
    exactly one argument.

    Cases as follows:

    1. min_count > 1 or max_count > 1, pass through posargs as a list
    2. max_count == 1 -> single argument or None

    Even if min_count == 1, you can get a None back. This compromise
    was made necessary to keep "to_cmd_scope" robust enough to pass to
    help/error handler funcs when validation fails.
    """
    pas = posargspec
    if pas.max_count is None or pas.min_count > 1 or pas.max_count > 1:
        return posargs
    if pas.max_count == 1:
        return posargs[0] if posargs else None
    raise RuntimeError('invalid posargspec/posargs configuration %r -- %r' %
        (posargspec, posargs))


def normalize_time(time_format, time_duration):
    """
        Takes a 'time_format' tuple and a 'time_duration' list and calculates the proper duration of time_duration so it respects time_format specifications
    """
    if not time_format or not time_duration:
        raise RuntimeError("Mising or 'None' arguments")
    if len(time_duration) != len(time_format):
        raise RuntimeError(
            'Time format and duration must have the same number of components')
    for i in range(len(time_duration)):
        if time_duration[i] > time_format[i]:
            if i == len(time_duration) - 1:
                continue
            time_duration[i + 1] += time_duration[i] // time_format[i]
            time_duration[i] = time_duration[i] % time_format[i]
    return time_duration, time_format


def params(f):
    """
    Read header parameters like ## key=value into a dictionary
    :param f: file handler
    :return: {key: value}
    """
    params = {}
    pos = f.tell()
    line = f.readline()
    while line.startswith('#') or line == '\n':
        if line.startswith('##'):
            line = line[2:].rstrip('\n')
            try:
                idx = line.index('=')
                key = line[0:idx].lstrip()
                value = line[idx + 1:]
                params[key] = value
            except:
                pass
        pos = f.tell()
        line = f.readline()
    f.seek(pos)
    return params


def set_max_size_of_cache(connection: 'Connection', cache_size_limit: int
    ) ->None:
    """
    Set the upper limit set in FlowDB for the cache size, in bytes.

    Parameters
    ----------
    connection : "Connection"
    cache_size_limit : int
        Size in bytes to set as the cache limit

    """
    sql = (
        f"UPDATE cache.cache_config SET value='{int(cache_size_limit)}' WHERE key='cache_size'"
        )
    with connection.engine.begin() as trans:
        trans.execute(sql)


def set_property_if_in_dict(_dest_obj, _property_name, _dict,
    _default_value=None, _error_msg=None):
    """Set an object property is the same attribute exists in the dict. If _error is set, raise exception if missing."""
    if _property_name in _dict:
        _dest_obj.__dict__[_property_name] = _dict[_property_name]
    elif _default_value is not None:
        _dest_obj.__dict__[_property_name] = _default_value
    elif _error_msg is not None:
        raise Exception(_error_msg + ' Attribute missing: ' + _property_name)


def _annotation_writer(gff_row):
    """
    Establish a set of rules to annotate Uniprot GFF.

    :param pd.Series gff_row: each line in the GFF file.
    :return str: template filled with type-specific fields.
    """
    if not gff_row.ID and not gff_row.Note:
        return gff_row.TYPE
    elif not gff_row.ID:
        return '{0.TYPE}: {0.Note}'.format(gff_row)
    elif not gff_row.Note:
        return '{0.TYPE} ({0.ID})'.format(gff_row)
    else:
        return '{0.TYPE}: {0.Note} ({0.ID})'.format(gff_row)


def _get_isoweekday_difference(date1, date2):
    """Difference of isoweekdays between days."""
    days = 7 - (date1.isoweekday() - date2.isoweekday())
    if days >= 7:
        days -= 7
    return days


def context_set_id(data_path: str='', value: str=''):
    """Set a context value to an ID data-block

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param value: Value, Assign value
    :type value: str
    """
    pass


@classmethod
def func_to_name(cls, func):
    """
        Returns a standard name for a task function.
        """
    return '.'.join([func.__module__, func.__name__])


def toPyModel(model_ptr):
    """
	toPyModel(model_ptr) -> svm_model

	Convert a ctypes POINTER(svm_model) to a Python svm_model
	"""
    if bool(model_ptr) == False:
        raise ValueError('Null pointer')
    m = model_ptr.contents
    m.__createfrom__ = 'C'
    return m


def somme(l):
    """Takes an array l and returns the array made of the sums of all subarrays
    over the first dimension along."""
    res = l[0]
    for k in l[1:]:
        res += k
    return res


def format_number(number, number_of_digits):
    """
    The function format_number() return a string-representation of a number
    with a number of digits after the decimal separator.
    If the number has more digits, it is rounded.
    If the number has less digits, zeros are added.

    @param number: the number to format
    @param digits: the number of digits
    """
    if number is None:
        return ''
    return '%.{0}f'.format(number_of_digits) % number


def li(items):
    """
    generate list items

        >>> li(['this','that'])
        '
this

that
'

    """
    return ''.join(map('
{}
'.format, items))


@classmethod
def removeMine(class_, o, user, page):
    """If p_user has set a lock on p_page, this method removes it. This
           method is called when the user that locked a page consults PX "view"
           for this page. In this case, we consider that the user has left the
           edit page in an unexpected way and we remove the lock."""
    if hasattr(o, 'locks') and page in o.locks and user.login == o.locks[page][
        0]:
        del o.locks[page]


def nlines_back(n):
    """
    return escape sequences to move character up `n` lines
    and to the beginning of the line
    """
    return '\x1b[{0}A\r'.format(n + 1)


def _c_string_literal(s):
    """
    Convert a python string into a literal suitable for inclusion into C code
    """
    s = s.replace('\\', '\\\\')
    s = s.replace('"', '\\"')
    s = s.replace('\n', '\\n')
    return '"{}"'.format(s)


def scan_invited_accounts(log, org_client):
    """Return a list of handshake IDs"""
    response = org_client.list_handshakes_for_organization(Filter={
        'ActionType': 'INVITE'})
    handshakes = response['Handshakes']
    while 'NextToken' in response:
        response = org_client.list_handshakes_for_organization(Filter={
            'ActionType': 'INVITE'}, NextToken=response['NextToken'])
        handshakes += response['Handshakes']
    log.debug(handshakes)
    return handshakes


@classmethod
def parse_message_tags(cls, data):
    """
        Parses IRCv3.2 message tags from a message, as described at http://ircv3.net/specs/core/message-tags-3.2.html

        data is a list of command arguments, split by spaces.
        """
    if data[0].startswith('@'):
        tagdata = data[0].lstrip('@').split(';')
        for idx, tag in enumerate(tagdata):
            tag = tag.replace('\\s', ' ')
            tag = tag.replace('\\r', '\r')
            tag = tag.replace('\\n', '\n')
            tag = tag.replace('\\:', ';')
            tag = tag.replace('\\\\', '\x00')
            tag = tag.replace('\\', '')
            tag = tag.replace('\x00', '\\')
            tagdata[idx] = tag
        results = cls.parse_isupport(tagdata, fallback='')
        return results
    return {}


def _getargspec_from_signature(function):
    """
    Reproduce getargspec() interface using newer signature protocol
    """
    from inspect import signature
    args, vararg, varkwd, defaults = [], None, None, []
    sig = signature(function)
    for p in sig.parameters.values():
        args.append(p.name)
        if p.default is not p.empty:
            defaults.append(p.default)
        if p.kind is p.VAR_POSITIONAL:
            vararg = p.name
        elif p.kind is p.VAR_KEYWORD:
            varkwd = p.name
    return args, vararg, varkwd, defaults


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

        :param ShowcaseUntrashedDeprecatedDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_untrashed_deprecated_details', val)


def extract_quartic_couplings(path, memmap, coupling_terms, frequencies):
    """ not implemented at this time """
    return


def label_nodes(tree):
    """
    Label the internal nodes in the tree.
    :param tree: an ETE tree.
    :return: None
    """
    i = len(tree.get_leaves()) + 1
    t = 1
    for node in tree.traverse('preorder'):
        if not node.is_leaf():
            node.name = 'n' + str(i)
            i += 1
        else:
            node.name = 't' + str(t)
            t += 1


@staticmethod
def apply_options(target_configuration, options):
    """ Apply the package specific command line options to the target
        configuration.  target_configuration is the target configuration.
        options are the parsed options.
        """
    if options.qtwebengine_sip_dir is not None:
        target_configuration.qtwebengine_sip_dir = options.qtwebengine_sip_dir
    else:
        target_configuration.qtwebengine_sip_dir = (target_configuration.
            pyqt_sip_dir)
    if options.qtwebengine_no_sip_files:
        target_configuration.qtwebengine_sip_dir = ''


def ReadPowerForm(*args, **kwargs):
    """ Stub Anduin function."""
    print('ReadPowerForm', args, kwargs)


@classmethod
def with_context(cls, *args, **kwargs):
    """Return a model (or recordset) equivalent to the current model
        (or recordset) attached to an environment with another context.
        The context is taken from the current environment or from the
        positional arguments `args` if given, and modified by `kwargs`.

        Thus, the following two examples are equivalent:

        .. doctest::

            >>> Product = odoo.env['product.product']
            >>> Product.with_context(lang='fr_FR')
            Model('product.product')

        .. doctest::

            >>> context = Product.env.context
            >>> Product.with_context(context, lang='fr_FR')
            Model('product.product')

        This method is very convenient for example to search records
        whatever their active status are (active/inactive):

        .. doctest::

            >>> all_product_ids = Product.with_context(active_test=False).search([])

        Or to update translations of a recordset:

        .. doctest::

            >>> product_en = Product.browse(1)
            >>> product_en.env.lang
            'en_US'
            >>> product_en.name = "My product"  # Update the english translation
            >>> product_fr = product_en.with_context(lang='fr_FR')
            >>> product_fr.env.lang
            'fr_FR'
            >>> product_fr.name = "Mon produit" # Update the french translation
        """
    context = dict(args[0] if args else cls.env.context, **kwargs)
    return cls.with_env(cls.env(context=context))


def check_cigar_seq(cigar, read_seq, ref_seq):
    """
    The function is used to check whether the cigar is corresponded to read_seq and ref_seq
    """
    pos = 0
    rdp = 0
    for n, c in cigar.list:
        if c in {'M', 'X', '='}:
            pos += n
            rdp += n
        elif c in {'S', 'I'}:
            rdp += n
        elif c in {'D', 'N'}:
            pos += n
    if rdp != len(read_seq) or pos != len(ref_seq):
        raise Exception(
            'Error: input cigar not correspond to read_seq or ref_seq!',
            '\n', cigar.list, '\n', read_seq, '\n', ref_seq)
    return 0


@staticmethod
def _between_(x1s, y1s, x2s, y2s, x, y):
    """
        checks if (x,y) in rectangle of (x1s,y1s)-(x2s,y2s)
        """
    f1 = 1.0 - 1e-12
    f2 = 1.0 + 1e-12
    f3 = 1e-06
    xs_min = min(x1s, x2s)
    if xs_min > 0:
        xs_min *= f1
    else:
        xs_min *= f2
    xs_max = max(x1s, x2s)
    if xs_max > 0:
        xs_max *= f2
    else:
        xs_max *= f1
    ys_min = min(y1s, y2s)
    if ys_min > 0:
        ys_min *= f1
    else:
        ys_min *= f2
    ys_max = max(y1s, y2s)
    if ys_max > 0:
        ys_max *= f2
    else:
        ys_max *= f1
    if xs_min == 0:
        xs_min = -xs_max * f3
    if xs_max == 0:
        xs_max = -xs_min * f3
    if ys_min == 0:
        ys_min = -ys_max * f3
    if ys_max == 0:
        ys_max = -ys_min * f3
    if xs_min <= x <= xs_max and ys_min <= y <= ys_max:
        return True
    else:
        return False


def display_new_scene(name):
    """display function for creating a new scene"""
    print('Created new scene "%s"' % name)


def make_figure_disagg(extractors, what):
    """
    $ oq plot 'disagg?kind=Mag&imt=PGA&rlz=0'
    """
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    oq = extractors[0].oqparam
    disagg = extractors[0].get(what)
    [sid] = disagg.site_id
    [imt] = disagg.imt
    [poe_id] = disagg.poe_id
    [rlz] = disagg.rlz
    ax.set_xlabel('Disagg%s on site %s, imt=%s, poe_id=%d, inv_time=%dy' %
        (disagg.kind, sid, imt, poe_id, oq.investigation_time))
    x, y = disagg.array.T
    print(y)
    ax.plot(x, y, label='rlz-%s' % rlz)
    ax.legend()
    return plt


@classmethod
def broadcast_tx(cls, tx_hex):
    """Broadcasts a transaction to the blockchain.

        :param tx_hex: A signed transaction in hex form.
        :type tx_hex: ``str``
        :raises ConnectionError: If all API services fail.
        """
    success = None
    for api_call in cls.BROADCAST_TX_MAIN:
        try:
            c = api_call(tx_hex)
            if not c:
                continue
            return c
        except cls.IGNORED_ERRORS:
            pass
    if success is False:
        raise ConnectionError(
            'Transaction broadcast failed, or Unspents were already used.')
    raise ConnectionError('All APIs are unreachable.')


def sloppify(n):
    """ Removes the ones place from the integer provided. """
    return int(n / 10) * 10


def bC_Mg_H2PO4_HFM89(T, P):
    """c-a: magnesium dihydrogen-phosphate [HFM89]."""
    b0 = -3.55
    b1 = 16.9
    b2 = 0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def _get_model_form_field(model, name, formfield_callback=None, **kwargs):
    """
    Utility to create the formfield from a model field.
    When a field is not editable, a ``None`` will be returned.
    """
    field = model._meta.get_field(name)
    if not field.editable:
        return None
    if formfield_callback is None:
        formfield = field.formfield(**kwargs)
    elif not callable(formfield_callback):
        raise TypeError('formfield_callback must be a function or callable')
    else:
        formfield = formfield_callback(field, **kwargs)
    return formfield


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.
    """
    Page = apps.get_model('pages', 'Page')
    keys = ['home', 'library', 'category', 'contact_us', 'about_us',
        'my_products', 'download_manager', 'file_manager', 'user_invitation']
    for key in keys:
        try:
            Page.objects.get(english_title=key).delete()
        except Exception:
            pass


@classmethod
def dark_teal(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x11806a``."""
    return cls(1146986)


@classmethod
def findNode(class_, hot_map, targetNode, parentNode=None):
    """ Find the target node in the hot_map. """
    for index, (rect, node, children) in enumerate(hot_map):
        if node == targetNode:
            return parentNode, hot_map, index
        result = class_.findNode(children, targetNode, node)
        if result:
            return result
    return None


def select_or_deselect_all(extend: bool=False, toggle: bool=False, deselect:
    bool=False, center: bool=False, enumerate: bool=False, object: bool=False):
    """Select element under the mouse, deselect everything is there’s nothing under the mouse

    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    :param toggle: Toggle, Toggle the selection
    :type toggle: bool
    :param deselect: Deselect, Remove from selection
    :type deselect: bool
    :param center: Center, Use the object center when selecting, in editmode used to extend object selection
    :type center: bool
    :param enumerate: Enumerate, List objects under the mouse (object mode only)
    :type enumerate: bool
    :param object: Object, Use object selection (editmode only)
    :type object: bool
    """
    pass


def lower(f, c, o=1):
    """Determine whether or not a series value is lower than
    the value ``o`` periods back.

    Parameters
    ----------
    f : pandas.DataFrame
        Dataframe containing the column ``c``.
    c : str
        Name of the column in the dataframe ``f``.
    o : int, optional
        Offset value for shifting the series.

    Returns
    -------
    new_column : pandas.Series (bool)
        The array containing the new feature.

    """
    new_column = f[c] < f[c].shift(o)
    return new_column


def ensure_final_value(packageName, arsc, value):
    """Ensure incoming value is always the value, not the resid

    androguard will sometimes return the Android "resId" aka
    Resource ID instead of the actual value.  This checks whether
    the value is actually a resId, then performs the Android
    Resource lookup as needed.

    """
    if value:
        returnValue = value
        if value[0] == '@':
            try:
                res_id = int('0x' + value[1:], 16)
                res_id = arsc.get_id(packageName, res_id)[1]
                returnValue = arsc.get_string(packageName, res_id)[1]
            except (ValueError, TypeError):
                pass
        return returnValue
    return ''


def _iterordered(ascending, iter1, iter2):
    """produce an ordered iteration from two iterators with the same order

    The ascending is used to indicated the iteration direction.
    """
    choice = max
    if ascending:
        choice = min
    val1 = None
    val2 = None
    try:
        while True:
            if val1 is None:
                val1 = next(iter1)
            if val2 is None:
                val2 = next(iter2)
            n = choice(val1, val2)
            yield n
            if val1 == n:
                val1 = None
            if val2 == n:
                val2 = None
    except StopIteration:
        it = iter2
        if val1 is not None:
            yield val1
            it = iter1
        elif val2 is not None:
            yield val2
        for val in it:
            yield val


@classmethod
def clearLang(cls, env, lang='C'):
    """Reset the language settings of an environment dict
		to some expected value and return the result.
		"""
    env = dict(env)
    env['LANG'] = lang
    for i in {'LANGUAGE', 'LC_CTYPE', 'LC_NUMERIC', 'LC_TIME', 'LC_COLLATE',
        'LC_MONETARY', 'LC_MESSAGES', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
        'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'}:
        env.pop(i, None)
    return env


def setLastModified():
    """
        Cause the last modified time to be set to now.
        """


def isFirstLevelAnalysis(settings):
    """Returns ``True`` if the FEAT analysis described by ``settings``
    is a first level analysis, ``False`` otherwise.

    :arg settings: A FEAT settings dictionary (see :func:`loadSettings`).
    """
    return settings['level'] == '1'


def _draw_rectangle(data, obj, draw_options):
    """Return the PGFPlots code for rectangles.
    """
    label = obj.get_label()
    if label == '':
        return data, []
    handles, labels = obj.axes.get_legend_handles_labels()
    labelsFound = [label for h, label in zip(handles, labels) if obj in h.
        get_children()]
    if len(labelsFound) == 1:
        label = labelsFound[0]
    left_lower_x = obj.get_x()
    left_lower_y = obj.get_y()
    ff = data['float format']
    cont = ('\\draw[{}] (axis cs:' + ff + ',' + ff +
        ') rectangle (axis cs:' + ff + ',' + ff + ');\n').format(','.join(
        draw_options), left_lower_x, left_lower_y, left_lower_x + obj.
        get_width(), left_lower_y + obj.get_height())
    if label != '_nolegend_' and label not in data['rectangle_legends']:
        data['rectangle_legends'].add(label)
        cont += '\\addlegendimage{{ybar,ybar legend,{}}};\n'.format(','.
            join(draw_options))
        cont += '\\addlegendentry{{{}}}\n\n'.format(label)
    return data, cont


def plugin_factory():
    """ A factory function which returns a plain Plugin instance.

    """
    from .plugin import Plugin
    return Plugin()


def cmd_syst(args):
    """Show operating system type of server system.

           No read access required.

           Replying to this command is of questionable utility,
           because this server does not behave in a predictable way
           w.r.t. the output of the LIST command.  We emulate Unix ls
           output, but on win32 the pathname can contain drive
           information at the front Currently, the combination of
           ensuring that os.sep == '/' and removing the leading slash
           when necessary seems to work.  [cd'ing to another drive
           also works]

           This is how wuftpd responds, and is probably the most
           expected.  The main purpose of this reply is so that the
           client knows to expect Unix ls-style LIST output.

           one disadvantage to this is that some client programs
           assume they can pass args to /bin/ls.  a few typical
           responses:

           215 UNIX Type: L8 (wuftpd)
           215 Windows_NT version 3.51
           215 VMS MultiNet V3.3
           500 'SYST': command not understood. (SVR4)
        """


def _cached_call(cache, estimator, method, *args, **kwargs):
    """Call estimator with method and args and kwargs."""
    if cache is None:
        return getattr(estimator, method)(*args, **kwargs)
    try:
        return cache[method]
    except KeyError:
        result = getattr(estimator, method)(*args, **kwargs)
        cache[method] = result
        return result


@classmethod
def resolve_dependencies(cls, job_list, visit_list=None):
    """
        Solve the dependency graph expressed as a list of job definitions.

        :param list job_list: list of known jobs
        :param list visit_list: (optional) list of jobs to solve

        The visit_list, if specified, allows to consider only a part of the
        graph while still having access and knowledge of all jobs.

        :returns list: the solution (a list of jobs to execute in order)
        :raises DependencyDuplicateError:
            if a duplicate job definition is present
        :raises DependencyCycleError:
            if a cyclic dependency is present.
        :raises DependencyMissingErorr:
            if a required job does not exist.
        """
    return cls(job_list)._solve(visit_list)


def convertToIntOrNegativeOneIfUnset(val=None):
    """
        convertToIntOrNegativeOneIfUnset - Converts value to an integer, or -1 if unset

        @param val <int/str/None> - Value

        Takes a value, if not set returns -1. If not an integer, returns 0
    """
    if val in (None, ''):
        return -1
    try:
        return int(val)
    except:
        return 0


@classmethod
def get_pll_mhz(mcs, pll_reg):
    """The getter method for PLL output clocks.

        Parameters
        ----------
        pll_reg : Register
            The control register for a PLL

        Returns
        -------
        float
            The PLL output clock rate measured in MHz.

        """
    pll_fbdiv = pll_reg[mcs.SRC_PLL_FBDIV_FIELD]
    clk_mhz = mcs.DEFAULT_SRC_CLK_MHZ * pll_fbdiv
    return round(clk_mhz, 6)


def get_form_choices_display(choices, value):
    """
    Same functionality as django's get_foo_display() but this will work with form 'choices' not just models
    """
    return dict(choices)[int(value)]


def email(author):
    """get email of author."""
    r = author.find(b'>')
    if r == -1:
        r = None
    return author[author.find(b'<') + 1:r]


@staticmethod
def le_bytes_to_num(data):
    """Convert a number from little endian byte format"""
    ret = 0
    for i in range(len(data) - 1, -1, -1):
        ret <<= 8
        ret += data[i]
    return ret


def __binary__(cls, op):
    """
    This method should be overridden to return the dunder for the given
    operator function.

    """
    return NotImplemented


def startTLS(contextFactory):
    """
        Initiate TLS negotiation.

        @param contextFactory: A context factory (see L{ssl.py<twisted.internet.ssl>})
        """


def zerotime(acqu):
    """get digital filter parameters, if any
    """
    try:
        zerotimeposition = float(acqu['DIGITAL_FILTER_SHIFT'])
    except:
        zerotimeposition = 0.0
    return zerotimeposition


def format_float(arg):
    """Formats a float value to be as short as possible.

    Truncates float to 8 decimal places and trims extraneous
    trailing zeros and period to give API args the best
    possible chance of fitting within 2000 char URL length
    restrictions.

    For example:

    format_float(40) -> "40"
    format_float(40.0) -> "40"
    format_float(40.1) -> "40.1"
    format_float(40.001) -> "40.001"
    format_float(40.0010) -> "40.001"
    format_float(40.000000001) -> "40"
    format_float(40.000000009) -> "40.00000001"

    :param arg: The lat or lng float.
    :type arg: float

    :rtype: string
    """
    return ('%.8f' % float(arg)).rstrip('0').rstrip('.')


def __get_unique_permission_fields(_permissions_dict_list):
    """This function gets the unique fields from a space permissions list from the ``get_space_permissions`` function.

    :param _permissions_dict_list: A list of dictionaries containing space permissions
    :type _permissions_dict_list: list
    :returns: List of unique field names
    """
    _unique_fields = []
    for _permissions_dict in _permissions_dict_list:
        for _permission_field in _permissions_dict.keys():
            if _permission_field not in _unique_fields:
                _unique_fields.append(_permission_field)
    return _unique_fields


def get_external_catalog(phot, filter_file=
    '/usr/local/share/eazy-photoz/filters/FILTER.RES.latest', ZP=23.9,
    sys_err=0.3, verbose=True, external_limits=3, timeout=300):
    """
    Fetch photometry from vizier
    """
    import numpy as np
    import astropy.units as u
    try:
        from .. import utils
    except:
        from grizli import utils
    from eazy.filters import FilterFile
    res = FilterFile(filter_file)
    vizier_catalog = list(utils.VIZIER_VEGA.keys())
    ra = np.median(phot['ra'])
    dec = np.median(phot['dec'])
    dr = np.sqrt((phot['ra'] - ra) ** 2 * np.cos(phot['dec'] / 180 * np.pi) **
        2 + (phot['dec'] - dec) ** 2) * 60
    radius = 1.5 * dr.max()
    tabs = utils.get_Vizier_photometry(ra, dec, templates=None, radius=
        radius * 60, vizier_catalog=vizier_catalog, filter_file=filter_file,
        MW_EBV=0, convert_vega=False, raw_query=True, verbose=True, timeout
        =timeout)
    extern_phot = utils.GTable()
    N = len(phot)
    for t_i in tabs:
        if 'RAJ2000' in t_i.colnames:
            other_radec = 'RAJ2000', 'DEJ2000'
        elif 'RA_ICRS' in t_i.colnames:
            other_radec = 'RA_ICRS', 'DE_ICRS'
        else:
            other_radec = 'ra', 'dec'
        idx, dr = phot.match_to_catalog_sky(t_i, other_radec=other_radec)
        if (dr < 2 * u.arcsec).sum() == 0:
            continue
        tab = t_i[dr < 2 * u.arcsec]
        idx = idx[dr < 2 * u.arcsec]
        err_scale = 1
        if tab.meta['name'] == utils.UKIDSS_LAS_VIZIER:
            flux_scale = 1.33
        else:
            flux_scale = 1.0
        convert_vega = utils.VIZIER_VEGA[tab.meta['name']]
        bands = utils.VIZIER_BANDS[tab.meta['name']]
        to_flam = 10 ** (-0.4 * 48.6) * 3e+18
        for ib, b in enumerate(bands):
            f_number = res.search(b, verbose=False)[0] + 1
            filt = res.filters[f_number - 1]
            if convert_vega:
                to_ab = filt.ABVega()
            else:
                to_ab = 0.0
            fcol, ecol = bands[b]
            fnu = 10 ** (-0.4 * (tab[fcol] + to_ab - ZP))
            efnu = tab[ecol] * np.log(10) / 2.5 * fnu * err_scale
            efnu = np.sqrt(efnu ** 2 + (sys_err * fnu) ** 2)
            fnu.fill_value = -99
            efnu.fill_value = -99
            comment = 'Filter {0} from {1} (N={2})'.format(bands[b][0], t_i
                .meta['name'], len(idx))
            if verbose:
                print(comment)
            if ((~efnu.mask).sum() > 4) & (external_limits > 0):
                fill = np.percentile(efnu.data[~efnu.mask], [90])
                efill = external_limits * fill
            else:
                fill = -99
                efill = -99
            extern_phot.meta['F{0}'.format(f_number)] = b, comment
            extern_phot['F{0}'.format(f_number)] = fill * np.ones(N)
            extern_phot['F{0}'.format(f_number)][idx] = fnu.filled()
            extern_phot['E{0}'.format(f_number)] = efill * np.ones(N)
            extern_phot['E{0}'.format(f_number)][idx] = efnu.filled()
    return extern_phot


@classmethod
def from_range(cls, data: range, name=None, dtype=None) ->'RangeIndex':
    """
        Create RangeIndex from a range object.

        Returns
        -------
        RangeIndex
        """
    if not isinstance(data, range):
        raise TypeError(
            f'{cls.__name__}(...) must be called with object coercible to a range, {repr(data)} was passed'
            )
    cls._validate_dtype(dtype)
    return cls._simple_new(data, name=name)


def get_molec_uc_to_mg_g(isot_dict):
    """Fix the discrepancy coming from old Raspa calculations, having a typo in the conversion label."""
    if 'conversion_factor_molec_uc_to_gr_gr' in isot_dict.get_dict():
        molec_uc_to_mg_g = isot_dict['conversion_factor_molec_uc_to_gr_gr']
    elif 'conversion_factor_molec_uc_to_mg_g' in isot_dict.get_dict():
        molec_uc_to_mg_g = isot_dict['conversion_factor_molec_uc_to_mg_g']
    return molec_uc_to_mg_g


def _calc_num_density_conversion():
    """Calculate conversion factor from PWV * cross section to optical depth

    Returns:
        The conversion factor in units of 1 / (mm * cm^2)
    """
    n_a = 6.02214129e+23
    h2o_molar_mass = 18.0152
    h2o_density = 0.99997
    one_mm_in_cm = 10
    mm_to_num_dens = n_a * h2o_density / (h2o_molar_mass * one_mm_in_cm)
    return mm_to_num_dens


def base_url(root):
    """Determine the base url for a root element."""
    for attr, value in root.attrib.iteritems():
        if attr.endswith('base') and 'http' in value:
            return value
    return None


def no_log_warn(logical_line):
    """Disallow 'LOG.warn('

    https://bugs.launchpad.net/tempest/+bug/1508442

    C301
    """
    if logical_line.startswith('LOG.warn('):
        yield 0, 'C301 Use LOG.warning() rather than LOG.warn()'


def messege(commnad):
    """Base command for adding messeges to git commands."""
    pass


def plugin():
    """ Return html render method """


def docstring_to_title_descr(string):
    """When given a classically formatted docstring, returns a tuple
    (title, description).

    >>> class Foo:
    ...     '''
    ...     Title of foo
    ...
    ...     Description of foo starts here.  It may
    ...     spill onto multiple lines.  It may also have
    ...     indented examples:
    ...
    ...       Foo
    ...       Bar
    ...
    ...     like the above.
    ...     '''
    ...
    >>> title, descr = docstring_to_title_descr(Foo.__doc__)
    >>> print(title)
    Title of foo
    >>> for num, line in enumerate(descr.splitlines()):
    ...    print("%d.%s" % (num, line))
    ...
    0.Description of foo starts here.  It may
    1.spill onto multiple lines.  It may also have
    2.indented examples:
    3.
    4.  Foo
    5.  Bar
    6.
    7.like the above.

    """
    lines = string.splitlines()
    for num, line in enumerate(lines):
        line = line.strip()
        if line:
            title = line
            break
    else:
        raise ValueError
    assert not lines[num + 1].strip()
    descrlines = lines[num + 2:]
    descr1 = descrlines[0]
    indent = len(descr1) - len(descr1.lstrip())
    descr = '\n'.join([line[indent:] for line in descrlines])
    return title, descr


def hide(unselected: bool=False):
    """Hide selected/unselected Grease Pencil layers

    :param unselected: Unselected, Hide unselected rather than selected layers
    :type unselected: bool
    """
    pass


def services_to_strings(services, service_to_string):
    """Convert SUPPORT_* service bitmask to list of service strings."""
    strings = []
    for service in service_to_string:
        if service & services:
            strings.append(service_to_string[service])
    return strings


@classmethod
def is_code_capture_enabled(cls):
    """Used to check whether we should capture the complete python code/file or not"""
    if cls._internal_config is not None:
        return cls._internal_config.is_code_capture_enabled()
    else:
        return False


def register_device(IdentityPoolId=None, IdentityId=None, Platform=None,
    Token=None):
    """
    Registers a device to receive push sync notifications.
    This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.
    See also: AWS API Documentation

    :example: response = client.register_device(
        IdentityPoolId='string',
        IdentityId='string',
        Platform='APNS'|'APNS_SANDBOX'|'GCM'|'ADM',
        Token='string'
    )

    :type IdentityPoolId: string
    :param IdentityPoolId: [REQUIRED]
            A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. Here, the ID of the pool that the identity belongs to.

    :type IdentityId: string
    :param IdentityId: [REQUIRED]
            The unique ID for this identity.

    :type Platform: string
    :param Platform: [REQUIRED]
            The SNS platform type (e.g. GCM, SDM, APNS, APNS_SANDBOX).

    :type Token: string
    :param Token: [REQUIRED]
            The push token.

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

    """
    pass


def get_schema():
    """Schema structure of this resource

    :return: schema dictionary
    :rtype: dict
    """
    return {'schema': {'schema_version': {'type': 'integer', 'default': 1},
        'name': {'schema_version': 1, 'title': 'Daemon name', 'comment':
        'Unique daemon name', 'type': 'string', 'required': True, 'empty':
        False}, 'address': {'schema_version': 1, 'title': 'Address', 'type':
        'string', 'required': True, 'empty': False}, 'port': {
        'schema_version': 1, 'title': 'Port', 'type': 'integer', 'required':
        True, 'empty': False}, 'last_check': {'schema_version': 1, 'title':
        'Last check', 'comment': 'Last time the daemon was checked', 'type':
        'integer', 'required': True, 'empty': False}, 'alive': {
        'schema_version': 1, 'title': 'Alive', 'comment':
        'The daemon is alive', 'type': 'boolean', 'required': True,
        'default': False}, 'reachable': {'schema_version': 1, 'title':
        'Reachable', 'comment': 'The daemon is reachable', 'type':
        'boolean', 'required': True, 'default': False}, 'passive': {
        'schema_version': 1, 'title': 'Passive', 'comment':
        'The daemon is a passive daemon', 'type': 'boolean', 'required':
        True, 'default': False}, 'spare': {'schema_version': 1, 'title':
        'Spare', 'comment': 'The daemon is a spare daemon', 'type':
        'boolean', 'required': True, 'default': False}, 'type': {
        'schema_version': 1, 'title': 'Type', 'comment':
        'Daemon type: "arbiter", "scheduler", "poller", "broker", "reactionner", "receiver"'
        , 'type': 'string', 'required': True, 'allowed': ['arbiter',
        'scheduler', 'poller', 'broker', 'reactionner', 'receiver']},
        '_realm': {'schema_version': 1, 'title': 'Realm', 'comment':
        'Realm this element belongs to.', 'type': 'objectid',
        'data_relation': {'resource': 'realm', 'embeddable': True},
        'required': True}, '_sub_realm': {'schema_version': 1, 'title':
        'Sub-realms', 'comment':
        'Is this element visible in the sub-realms of its realm?', 'type':
        'boolean', 'default': True}, '_users_read': {'schema_version': 1,
        'type': 'list', 'schema': {'type': 'objectid', 'data_relation': {
        'resource': 'user', 'embeddable': True}}}, '_users_update': {
        'schema_version': 1, 'type': 'list', 'schema': {'type': 'objectid',
        'data_relation': {'resource': 'user', 'embeddable': True}}},
        '_users_delete': {'schema_version': 1, 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'user',
        'embeddable': True}}}}, 'schema_deleted': {}}


def append(a, vancestors):
    """
    Append ``a`` to the list of the virtual ancestors, unless it is already
    included.
    """
    add = True
    for j, va in enumerate(vancestors):
        if issubclass(va, a):
            add = False
            break
        if issubclass(a, va):
            vancestors[j] = a
            add = False
    if add:
        vancestors.append(a)


def getlist(cls):
    """Return all the subclasses registered for a given class.
        """
    return filter(lambda k: issubclass(k, cls), cls._registry.values())


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Bus` from a :code:`bus` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Bus`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


@classmethod
def get_by_id(cls, context, port_id):
    """Find a port based on its integer ID and return a Port object.

        :param cls: the :class:`Port`
        :param context: Security context
        :param port_id: the ID of a port.
        :returns: a :class:`Port` object.
        :raises: PortNotFound

        """
    db_port = cls.dbapi.get_port_by_id(port_id)
    port = cls._from_db_object(context, cls(), db_port)
    return port


def intersperse_l(delimiter, iterable):
    """put the delimiter on the left of every element of iterable"""
    it = iter(iterable)
    for x in it:
        yield delimiter
        yield x


def update_package_data(distribution):
    """update build_py options to get package_data changes"""
    build_py = distribution.get_command_obj('build_py')
    build_py.finalize_options()


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


@classmethod
def pdf(this, x, *params, **kwargs):
    """Probability density function at x.

        Parameters
        ----------
        x : array_like
           points where to evaluate the pdf
        param1, param2, ... : array_like
           parameters of the model

        Returns
        -------
        pdf : ndarray
           Probability density function evaluated at x

        """
    raise NotImplementedError


def strip_annotations(ev):
    """Strip all annotations from event."""
    if '_humilis' in ev:
        del ev['_humilis']
    return ev


@staticmethod
def check_required_params(params: dict, payload: dict):
    """
			Vérifie que la paramètres requis soient bien présents dans la charge utile.
			Lance une erreur spécifique le cas contraire.
		"""
    for par in params:
        if 'required' in params[par]:
            if params[par]['required']:
                if par not in payload:
                    raise ValueError('Required argument not provided : ' + par)


@classmethod
def _is_content_digest(cls):
    """Test if content digest was defined."""
    return bool(cls.operation_digest is not None)


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

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


def f_to_d(f, s):
    """
    Converts frequency bins to distance bins based on ADC settings.

    :param f: Frequency bins
    :param s: Settings dictionary
    :return: Distance bins
    """
    return s['c'] * f / (2 * (s['bw'] / s['t_sweep']))


def breast_cancer(round_limit=2, random_method='uniform_mersenne'):
    """Performs a Scan with Iris dataset and simple dense net"""
    import talos as ta
    scan_object = ta.Scan(ta.templates.datasets.breast_cancer()[0], ta.
        templates.datasets.breast_cancer()[1], ta.templates.params.
        breast_cancer(), ta.templates.models.breast_cancer, 'test',
        round_limit=round_limit)
    return scan_object


def trunc_time(time, freq):
    """
    Truncates values in provided time array to provided frequency. E.g. 2018-01-15T12:00 with
    freq = 'M' becomes 2018-01-01.
    """
    return time.astype('<M8[' + freq + ']')


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

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

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

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

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

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


def to77(theVal):
    """Converts theVal to Rep code 0x4D, 8bit mask from theVal."""
    return int(theVal) & 255


def new_thread(function, *args, daemon=True, **kwargs):
    """
    launches the input 'function' in a separate thread with daemon == True.

    Explanation: Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.

    Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.
    @Chris Jester-Young https://stackoverflow.com/a/190017/8436767

    Parameters
    ----------
    function:
        function object
    *args:
        iterable of arguments
    daemon:
        flag, if the thread is daemon(True) or not(False).
    **kwargs:
        dictionary of keywords

    Returns
    -------
    thread:
        thread object

    Examples
    --------
    the example of usage

    >>> def func(*args,**kwargs):
            from time import time,sleep
            t1 = time()
            sleep(N)
            t2 = time()
            print('this thread slept for {} seconds'.format(t2-t1))
            print('input parameters: args = {}, kwargs = {!r}'.format(args[0],kwargs['keyword']))
    >>> start_new_safe_thread(func, 1, keyword = 'this is key 1 value')
    this thread slept for 1.002244234085083 seconds
    input parameters: args = 1, kwargs = 'keywords argument'

    """
    from threading import Thread
    thread = Thread(target=function, args=args, kwargs=kwargs)
    thread.daemon = daemon
    thread.start()
    return thread


def reverse(sequence, keep_nterm=False, keep_cterm=False):
    """
    Create a decoy sequence by reversing the original one.

    Parameters
    ----------
    sequence : str
        The initial sequence string.
    keep_nterm : bool, optional
        If :py:const:`True`, then the N-terminal residue will be kept.
        Default is :py:const:`False`.
    keep_cterm : bool, optional
        If :py:const:`True`, then the C-terminal residue will be kept.
        Default is :py:const:`False`.

    Returns
    -------
    decoy_sequence : str
        The decoy sequence.
    """
    start = 1 if keep_nterm else 0
    end = len(sequence) - 1 if keep_cterm else len(sequence)
    if start == end:
        return sequence
    return sequence[:start] + sequence[start:end][::-1] + sequence[end:]


def p_repo_details(t):
    """
    repo_details : dictionary acl_list hooks
    """
    t[0] = t[1], t[2], t[3]


def _ctypes_dtype(parameter):
    """Determines the ISO_C data type to use for describing the specified parameter.
    """
    ctype = parameter.ctype
    if ctype is None:
        if parameter.kind is not None:
            return '{}({})'.format(parameter.dtype, parameter.kind)
        else:
            return parameter.dtype
    else:
        return '{}({})'.format(parameter.dtype, ctype)


def unique_filepath(path):
    """Get a unique, absolute filepath from path by appending _%d, where %d is
    a unique digit starting at 1.

    Args:
        path (str): A not necessarily absolute filepath.

    Returns:
        str: A unique, absolute filepath.
    """
    import os
    attempt = 0
    file_path = os.path.splitext(os.path.abspath(path))
    file_name = file_path[0]
    file_ext = file_path[1]
    while True:
        suffix = '_' + str(attempt) if attempt > 0 else ''
        attempt_file_path = file_name + suffix + file_ext
        if not os.path.exists(attempt_file_path):
            return attempt_file_path
        attempt += 1


def blank(n=1):
    """Prints a blank line to the terminal."""
    for i in range(n):
        print('')


def collapse_whitespace(message):
    """Collapses consecutive whitespace into a single space"""
    return u' '.join(map(lambda s: s.strip(), filter(None, message.strip().
        splitlines())))


def mdlist(m, n):
    """Preallocate 2D list of size MxN"""
    return [([None] * n) for i in range(m)]


def SizeBenefitLiving(t):
    """Living benefit per policy"""
    return 0


def to_interpolation_method(im):
    """
    to_interpolation_method(x) yields either 'linear' or 'nearest' or raises an exception, depending
      on x; if x is None or a string resembling 'nearest', then 'nearest' is returned, while a
      string resembling 'linear' results in 'linear' being returned.
    """
    if im is None:
        return 'nearest'
    im = im.lower()
    if im in ['linear', 'lin', 'trilinear', 'trilin']:
        return 'linear'
    elif im in ['nearest', 'near', 'nn', 'nearest-neighbor', 'nearest_neighbor'
        ]:
        return 'nearest'
    else:
        raise ValueError(
            'given interpolation_method (%s) is not recognized' % (im,))


def match_all_columns(_left, _right):
    """Match all columns in two arrays, return false if they differ anywhere.

    :param array _left: The left array
    :param array _right: The right array

    .. note::
        This function is a *little bit* tailored to QAL needs.
        The left column *has* to be used for column iteration, since _right might have extra columns for references
        to underlying structures that should not be compared.
    """
    for _curr_column in range(0, len(_left)):
        if _left[_curr_column] != _right[_curr_column]:
            return False
    return True


def _get_query_params_list(older_than, change_type):
    """
    Create a formatted params list.
    """
    return [older_than.strftime('%Y-%m-%d %H:%M:%S'), int(change_type)]


def pct_to_kelvin(pct, max_k=6500, min_k=2700):
    """Convert percent to kelvin."""
    kelvin = (max_k - min_k) * pct / 100 + min_k
    return kelvin


def listAllowedLanguages(content=None, content_type=None):
    """ List the allowed values of the 'Language' DCMI element.

        o 'Language' element values should be suitable for generating
          HTTP headers.

        o Return only values appropriate for content's type, or all values if
          both 'content' and 'content_type' are None.
        """


def s2n(s):
    """
    String to number.
    """
    if not len(s):
        return 0
    return int(s.encode('utf-8').hex(), 16)


def get_ip(container):
    """ Returns the IP adress of a specific container. """
    state = container.state()
    if state.network is None:
        return ''
    eth0 = state.network['eth0']
    for addr in eth0['addresses']:
        if addr['family'] == 'inet':
            return addr['address']
    return ''


def constant(f):
    """
    decorator to mark methods as constant
    """
    f.is_constant = True
    return f


@staticmethod
def equal_lines(line0, line1):
    """ Returns True if line0 and line1 are equivalent, else False.

        'line0' and 'line1' are line segments of form [x0,y0,x1,y1].

        Edge.equal_lines(np.arr[float(x4)], np.arr[float(x4)]) -> bool

        """
    p0, p1 = line0.reshape((2, 2))
    p0 = list(p0)
    p1 = list(p1)
    p2, p3 = line1.reshape((2, 2))
    p2 = list(p2)
    p3 = list(p3)
    return p0 == p2 and p1 == p3 or p0 == p3 and p1 == p2


def process_results(graph, vec):
    """Get `graph` nodes and corresponding absolute values of provided eigenvector.
    This function is helper for :func:`~gensim.summarization.pagerank_weighted.pagerank_weighted`

    Parameters
    ----------
    graph : :class:`~gensim.summarization.graph.Graph`
        Given graph.
    vec : numpy.ndarray, shape = [n, ]
        Given eigenvector, n is number of nodes of `graph`.

    Returns
    -------
    dict
        Graph nodes as keys, corresponding elements of eigenvector as values.

    """
    scores = {}
    for i, node in enumerate(graph.nodes()):
        scores[node] = abs(vec[i])
    return scores


def _attr_key(attr):
    """Return an appropriate key for an attribute for sorting

    Attributes have a namespace that can be either ``None`` or a string. We
    can't compare the two because they're different types, so we convert
    ``None`` to an empty string first.

    """
    return attr[0][0] or '', attr[0][1]


def set_unix_slash(win_path):
    """
    Set windows path to unix style path

    :param win_path: windows style path
    :type win_path: str
    :return: unix style path
    :rtype: str
    """
    unix_path = win_path.strip().replace('\\', '/')
    return unix_path


def dispatch_hook(key, hooks, hook_data, **kwargs):
    """Dispatches a hook dictionary on a given piece of data."""
    hooks = hooks or {}
    hooks = hooks.get(key)
    if hooks:
        if hasattr(hooks, '__call__'):
            hooks = [hooks]
        for hook in hooks:
            _hook_data = hook(hook_data, **kwargs)
            if _hook_data is not None:
                hook_data = _hook_data
    return hook_data


def _format_usage_without_prefix(parser):
    """
    Use private argparse APIs to get the usage string without
    the 'usage: ' prefix.
    """
    fmt = parser._get_formatter()
    fmt.add_usage(parser.usage, parser._actions, parser.
        _mutually_exclusive_groups, prefix='')
    return fmt.format_help().strip()


def point_on_cubic_bezier(p1, p2, c1, c2, t):
    """Find a point on a cubic bezier curve, i.e. a bezier curve with two control points.

	@type p1: Vector
	@param p1: Start point of the curve

	@type p2: Vector
	@param p2: Stop point of the curve

	@type c1: Vector
	@param c1: Control point for point A

	@type c2: Vector
	@param c2: Control point for point B

	@type t: float
	@param t: Relative position on the bezier curve between 0 and 1
	"""
    one_minus_t = 1.0 - t
    one_minus_t_2 = one_minus_t * one_minus_t
    one_minus_t_3 = one_minus_t_2 * one_minus_t
    t_2 = t * t
    t_3 = t_2 * t
    return p1 * one_minus_t_3 + c1 * (3 * one_minus_t_2 * t) + c2 * (3 *
        one_minus_t * t_2) + p2 * t_3


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 getDescription():
    """Gives the description of this result field.
        """


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


def safe_string_equals(a, b):
    """ Near-constant time string comparison.

    Used in order to avoid timing attacks on sensitive information such
    as secret keys during request verification (`rootLabs`_).

    .. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/

    """
    if len(a) != len(b):
        return False
    result = 0
    for x, y in zip(a, b):
        result |= ord(x) ^ ord(y)
    return result == 0


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


@classmethod
def body(cls, inputs, **kwargs):
    """ Create encoder, embedding and decoder

        Parameters
        ----------
        inputs
            input tensor
        filters : tuple of int
            number of filters in decoder blocks

        Returns
        -------
        nn.Module
        """
    kwargs = cls.fill_params('body', **kwargs)
    encoder = kwargs.pop('encoder')
    decoder = kwargs.pop('decoder')
    embedding = kwargs.pop('embedding')
    encoder_outputs = cls.encoder(inputs, **encoder, **kwargs)
    x = cls.embedding(encoder_outputs[-1], **embedding, **kwargs)
    if x != encoder_outputs[-1]:
        encoder_outputs += [x]
    x = cls.decoder(encoder_outputs, **decoder, **kwargs)
    return x


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

        :param ViewerInfoPolicyChangedDetails val:
        :rtype: EventDetails
        """
    return cls('viewer_info_policy_changed_details', val)


def remove_www(hostname):
    """
    Removes www. from the beginning of the address. Only for
    routing purposes. www.test.com/login/ and test.com/login/ should
    find the same tenant.
    """
    if hostname.startswith('www.'):
        return hostname[4:]
    return hostname


@classmethod
def getTimezone(cls):
    """Returns the pytz timezone for the market session."""
    return cls.timezone


def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,
    choice_col, availability_vars, wide_data):
    """
    Checks whether or not each observation with a restricted choice set chose
    an alternative that was personally available to him or her. Will raise a
    helpful ValueError if this is not the case.

    Parameters
    ----------
    obs_id_col : str.
        Denotes the column in `wide_data` that contains the observation ID
        values for each row.
    choice_col : str.
        Denotes the column in `wide_data` that contains a one if the
        alternative pertaining to the given row was the observed outcome for
        the observation pertaining to the given row and a zero otherwise.
    availability_vars : dict.
        There should be one key value pair for each alternative that is
        observed in the dataset. Each key should be the alternative id for the
        alternative, and the value should be the column heading in `wide_data`
        that denotes (using ones and zeros) whether an alternative is
        available/unavailable, respectively, for a given observation.
        Alternative id's, i.e. the keys, must be integers.
    wide_data : pandas dataframe.
        Contains one row for each observation. Should have the specified
        `[obs_id_col, choice_col] + availability_vars.values()` columns.

    Returns
    -------
    None
    """
    wide_availability_values = wide_data[list(availability_vars.values())
        ].values
    unavailable_condition = (wide_availability_values == 0).sum(axis=1).astype(
        bool)
    problem_obs = []
    for idx, row in wide_data.loc[unavailable_condition].iterrows():
        if row.at[availability_vars[row.at[choice_col]]] != 1:
            problem_obs.append(row.at[obs_id_col])
    if problem_obs != []:
        msg = 'The following observations chose unavailable alternatives:\n{}'
        raise ValueError(msg.format(problem_obs))
    return None


@classmethod
def _clip_to_desired_rounds(cls, rounds):
    """
        helper for :meth:`_generate_rounds` --
        clips rounds value to desired min/max set by class (if any)
        """
    mnd = cls.min_desired_rounds or 0
    if rounds < mnd:
        return mnd
    mxd = cls.max_desired_rounds
    if mxd and rounds > mxd:
        return mxd
    return rounds


def set_acl(**kwargs):
    """Set ACL of object or object."""
    resource = kwargs.get('resource')
    bucket_name = kwargs.get('bucket_name')
    object_name = kwargs.get('object_name')
    if kwargs.get('acl_type') == 'object':
        obj = resource.Object(bucket_name=bucket_name, key=object_name)
    if kwargs.get('acl_type') == 'bucket':
        obj = resource.Bucket(bucket_name)
    response = obj.Acl().put(ACL=kwargs.get('acl'))
    return response


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

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


def is_url(url):
    """boolean check for whether a string is a zmq url"""
    if '://' not in url:
        return False
    proto, addr = url.split('://', 1)
    if proto.lower() not in ['tcp', 'pgm', 'epgm', 'ipc', 'inproc']:
        return False
    return True


def p_OptionalIdentifier_empty(p):
    """OptionalIdentifier : """
    p[0] = None


def enfunc(x):
    """
    So-called K combinator. Given any value `x`, returns a function, that for any
    input value returns `x`
    :param x: value to be returned
    :return: function that returns `x` for any input
    """
    return lambda _: x


def strip_nonalpha(s, default=''):
    """Strip non alphabetic characters at the beginning of the string
  and return the result."""
    ss = s.strip()
    i = 0
    for c in ss:
        if c.isalpha():
            return ss[i:]
        i += 1
    return default


def copy_to_center(dest, img):
    """
    Copy img to the center of dest.

    * dest must be at least as big as img
    * img and dest should both be numpy arrays
    """
    dest_height, dest_width = dest.shape
    src_height, src_width = img.shape
    if src_height > dest_height or src_width > dest_width:
        raise Exception('img %s is larger than dest %s' % (img.shape, dest.
            shape))
    d_half = dest_height / 2, dest_width / 2
    (half_h, half_exh), (half_w, half_exw) = divmod(src_height, 2), divmod(
        src_width, 2)
    dest[d_half[0] - half_h:d_half[0] + half_h + half_exh, d_half[1] -
        half_w:d_half[1] + half_w + half_exw] = img


def get_assign_name(element):
    """
    Get name assignment associated with the element. The element might be the
    value or the target or something but we just want to identify the closest
    Assign ancestor and get its Name.

    If Assign appears more than once in the ancestral chain e.g.
    body-Assign-spam-eggs-Assign-targets-Name then we get a list like this:
    [body-Assign, body-Assign-spam-eggs-Assign] and we want the closest one to
    the element i.e. assign_els[-1]

    Ordered set of nodes, from parent to ancestor?
    https://stackoverflow.com/a/15645846
    """
    assign_els = element.xpath('ancestor::Assign')
    assign_el = assign_els[-1]
    name_els = assign_el.xpath('targets/Name')
    if len(name_els) == 1:
        name = name_els[0].get('id')
    else:
        name = None
    return name


def _recv_c_move_rq(event):
    """Logging handler when a C-MOVE-RQ is received.

    **C-MOVE Request Parameters**

    | (M) Message ID
    | (M) Affected SOP Class UID
    | (M) Priority
    | (M) Move Destination
    | (M) Identifier

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


def unindex_doc(relation):
    """unindexes relation for given token"""


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


@classmethod
def _create_from_stripe_object(cls, data, current_ids=None,
    pending_relations=None, save=True, stripe_account=None):
    """
        Instantiates a model instance using the provided data object received
        from Stripe, and saves it to the database if specified.

        :param data: The data dictionary received from the Stripe API.
        :type data: dict
        :param current_ids: stripe ids of objects that are currently being processed
        :type current_ids: set
        :param pending_relations: list of tuples of relations to be attached post-save
        :type pending_relations: list
        :param save: If True, the object is saved after instantiation.
        :type save: bool
        :param stripe_account: The optional connected account             for which this request is being made.
        :type stripe_account: string
        :returns: The instantiated object.
        """
    instance = cls(**cls._stripe_object_to_record(data, current_ids=
        current_ids, pending_relations=pending_relations, stripe_account=
        stripe_account))
    instance._attach_objects_hook(cls, data)
    if save:
        instance.save(force_insert=True)
    instance._attach_objects_post_save_hook(cls, data, pending_relations=
        pending_relations)
    return instance


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

        :param EmmCreateUsageReportType val:
        :rtype: EventType
        """
    return cls('emm_create_usage_report', val)


def extract_res(fname):
    """
    Extract information from res file.
    Returns a dictionary.
    The structure of he res file is not extracted
    """
    rems = []
    with open(fname) as fh:
        for line in fh:
            if 'TITL' in line:
                title = line.strip()
            if 'REM' in line:
                rems.append(line.replace('REM', '').strip())
            if 'cell' in line:
                break
    entries = title.split()
    res = {}
    res['rem'] = rems
    res['uid'] = entries[1]
    res['P'] = float(entries[2])
    res['V'] = float(entries[3])
    res['H'] = float(entries[4])
    res['nat'] = int(entries[7])
    res['sym'] = entries[8]
    res['fname'] = fname
    return res


@staticmethod
def _compare_hist_using_probability_distribution(inferring_hist_cats,
    contender_hist_cats):
    """
        calculate overlap score for given dict of bin and edges
        :param inferring_hist_cats: inference dict of bin to edges.
        :param contender_hist_cats: contender dict of bin to edges.
        """
    if not isinstance(inferring_hist_cats, dict):
        raise Exception(
            'two objects cannot be compared as inferring_hist_cats is not dict type'
            )
    if not isinstance(contender_hist_cats, dict):
        raise Exception(
            'two objects cannot be compared as contender_hist_cats is not dict type'
            )
    score = 0.0
    sum_of_mult_of_both_hist_count = 0.0
    sum_of_square_of_contender_hist_count = 0.0
    sum_of_contender_hist_count = 0.0
    sum_of_inferenced_hist_count = 0.0
    total_categories = list(set(inferring_hist_cats.keys()) | set(
        contender_hist_cats.keys()))
    for each_cat in total_categories:
        contender_hist_count = contender_hist_cats.get(each_cat, 0.0)
        inf_hist_count = inferring_hist_cats.get(each_cat, 0.0)
        sum_of_contender_hist_count += contender_hist_count
        sum_of_inferenced_hist_count += inf_hist_count
        sum_of_mult_of_both_hist_count += contender_hist_count * inf_hist_count
        sum_of_square_of_contender_hist_count += (contender_hist_count *
            contender_hist_count)
    if (sum_of_contender_hist_count <= 1.0 and sum_of_inferenced_hist_count <=
        1.0):
        max_normalized_categories_count = 1.0
        remaining_contender_hist_count = (max_normalized_categories_count -
            sum_of_contender_hist_count)
        remaining_inferenced_hist_count = (max_normalized_categories_count -
            sum_of_inferenced_hist_count)
        sum_of_contender_hist_count = max_normalized_categories_count
        sum_of_inferenced_hist_count = max_normalized_categories_count
        sum_of_mult_of_both_hist_count += (remaining_contender_hist_count *
            remaining_inferenced_hist_count)
        sum_of_square_of_contender_hist_count += (
            remaining_contender_hist_count * remaining_contender_hist_count)
    if (sum_of_square_of_contender_hist_count != 0 and
        sum_of_contender_hist_count != 0 and sum_of_inferenced_hist_count != 0
        ):
        contender_hist_reference_value = (sum_of_contender_hist_count *
            sum_of_contender_hist_count / sum_of_square_of_contender_hist_count
            )
        inference_hist_reference_value = sum_of_mult_of_both_hist_count / (
            sum_of_contender_hist_count * sum_of_inferenced_hist_count)
        score = contender_hist_reference_value * inference_hist_reference_value
    if score > 1.0:
        score = 1.0
    return score


@classmethod
def get_basis_group_map(cls, group_name):
    """
        Return an {element: basis} map for the BasisFamily group with the given name.
        """
    from aiida.common.exceptions import MultipleObjectsError
    family_bases = {}
    family = cls.get_basis_group(group_name)
    for node in family.nodes:
        if isinstance(node, cls):
            if node.element in family_bases:
                raise MultipleObjectsError(
                    'More than one BasisSetData for element {} found in family {}'
                    .format(node.element, group_name))
            family_bases[node.element] = node
    return family_bases


def deserialize_date(string):
    """
    Deserializes string to date.

    :param string: str.
    :type string: str
    :return: date.
    :rtype: date
    """
    try:
        from dateutil.parser import parse
        return parse(string).date()
    except ImportError:
        return string


@classmethod
def access(cls, parent, placeholder):
    """Resolve the deferred field attribute access.

        :param cls: the FieldAccessor class
        :param parent: owning structure of the field being accessed
        :param placeholder: FieldPlaceholder object which holds our info
        :returns: FieldAccessor instance for that field's attribute
        """
    try:
        return parent.lookup_field_by_placeholder(placeholder)
    except KeyError:
        field_placeholder, name = placeholder.args
        field = parent.lookup_field_by_placeholder(field_placeholder)
        accessor = cls(field, name, parent=parent, instantiate=True)
        parent._placeholder_to_field[placeholder] = accessor
        return accessor


def show_df_mem_usage(df):
    """Check dataframe `df` memory use"""
    print('Shape: ', df.shape)
    print('Total Mem usage: ', df.memory_usage().sum())
    df.memory_usage()


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

        :param IntegrationDisconnectedType val:
        :rtype: EventType
        """
    return cls('integration_disconnected', val)


def generic_find_fk_constraint_names(table, columns, referenced, insp):
    """Utility to find foreign-key constraint names in alembic migrations"""
    names = set()
    for fk in insp.get_foreign_keys(table):
        if fk['referred_table'] == referenced and set(fk['referred_columns']
            ) == columns:
            names.add(fk['name'])
    return names


def check_json(node, key):
    """
    check whether the node contains key
    """
    return node and key in node


def is_list(s):
    """
    Returns True if the given object has list type or False otherwise
    :param s: object
    :return: bool
    """
    return type(s) in [list, tuple]


def selector(zelf, *args, **kwargs):
    """ see if this things has the desired attributes. """
    wanted = args[0]
    if not wanted:
        return False
    go = False
    for arg in wanted:
        if arg in zelf and zelf[arg]:
            go = True
            break
    return go


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

        :param SfFbInviteChangeRoleType val:
        :rtype: EventType
        """
    return cls('sf_fb_invite_change_role', val)


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

        :param AppLogInfo val:
        :rtype: ActorLogInfo
        """
    return cls('app', val)


def _get_op_name(op, special):
    """
    Find the name to attach to this method according to conventions
    for special and non-special methods.

    Parameters
    ----------
    op : binary operator
    special : bool

    Returns
    -------
    op_name : str
    """
    opname = op.__name__.strip('_')
    if special:
        opname = '__{opname}__'.format(opname=opname)
    return opname


@staticmethod
def is_configured(func, args, kwargs):
    """Check if func has been configured (with `parameters`) to run with args/kwargs."""
    flag_arg = True
    flag_kwarg = True
    if args not in func.__fargs__:
        flag_arg = False
    if kwargs:
        for key, value in kwargs.items():
            if value not in func.__fkwargs__.get(key, ['__none__']):
                flag_kwarg = False
    elif not kwargs and func.__fkwargs__:
        flag_kwarg = False
    if args == func.__fargs__:
        flag_arg = True
    return True if flag_arg and flag_kwarg else False


def _array_length(type_str: str) ->int:
    """Returns the length of a fixed array, or 0"""
    if '[' not in type_str:
        return 0
    num = type_str[type_str.rindex('[') + 1:type_str.rindex(']')]
    if num == '':
        return 0
    length = int(num)
    if length == 1:
        raise NotImplementedError('1-length arrays? Really?')
    return length


def _mesh_plot(x, y, element_table, kwargs=None):
    """ Triplot of the mesh """
    if kwargs is None:
        kwargs = {}
    import matplotlib.pyplot as plt
    import matplotlib.tri as tri
    t = tri.Triangulation(x, y, element_table - 1)
    fig, ax = plt.subplots()
    ax.triplot(t, **kwargs)
    return fig, ax


def decode_ed25519(limbs):
    """
    Decodes hexcoded limbs with 25.5 radix to Zmod(2^255-19) integer

    :param n:
    :return:
    """
    n = 0
    c = 0
    shift = 0
    bits = [26, 25, 26, 25, 26, 25, 26, 25, 26, 25]
    for i in range(10):
        n += (limbs[i] & (1 << bits[i]) - 1) + c << shift
        c = limbs[i] >> bits[i]
        shift += bits[i]
    return n


def p_string_lprp(p):
    """ string : string LP RP
    """
    p[0] = p[1]


def get_cma_indirection_map_name(function_space):
    """ Returns the name of a CMA indirection dofmap for the supplied
    FunctionSpace. """
    return 'cma_indirection_map_' + function_space.mangled_name


def compress_fastr(sequence):
    """Eliminates repeats in a sequence and returns a string"""
    compressed_sequence = []
    if type(sequence) == str:
        sequence = sequence.split('-')
    last_read = None
    read_repeats = 0
    for read in enumerate(sequence):
        if read[1] == last_read:
            read_repeats += 1
        else:
            if read_repeats != 0:
                compressed_sequence.append('{0}x{1}'.format(str(
                    read_repeats + 1), str(last_read)))
                read_repeats = 0
            elif read[0] != 0:
                compressed_sequence.append(str(last_read))
            last_read = read[1]
        if read[0] + 1 == len(sequence):
            if read_repeats != 0:
                compressed_sequence.append('{0}x{1}'.format(str(
                    read_repeats + 1), str(last_read)))
            else:
                compressed_sequence.append(str(last_read))
            compressed_sequence = '-'.join(compressed_sequence)
    return compressed_sequence


def is_feature_overweighted_towards_class(feature_size_by_class_df,
    threshold=0.99, feature_level=True):
    """
    The intended use case is for seeing whether a categorical feature very
    strongly points towards a particular class value, as, if this is true,
    the feature is either highly predictive or leaking data.

    Parameters
    ----------

    feature_size_by_class_df : pandas.DataFrame
        DataFrame on which this function will operate. This is presumed to
        be a result from the function `get_feature_size_by_class`. Additionally,
        the feature represented in `feature_size_by_class_df` should be discrete,
        i.e. comes from a finite set of values.

    threshold : float, with value between 0 and 1 (default=.99)
        Proportion of rows allowed that are allowed to be taken up by single
        `class_col` & `feature` value grouping.

    feature_level : bool (default=True)
        Whether to perform at the feature level, or feature-value level.

    Return
    ------

    `bool` indicating whether all class values see all feature values.
    """
    ratios = feature_size_by_class_df.unstack(0).ratio
    if feature_level:
        booleans = ratios.sum() >= threshold
    else:
        booleans = (ratios >= threshold).any()
    return booleans.any()


def rectangle(start, end):
    """Draw rectangle from start to end."""
    pass


@classmethod
def get_sites(cls):
    """ Get testbed sites description
        May be run unauthicated

        :returns JSONObject
        """
    return cls._get_with_cache('sites')


@staticmethod
def get_service_request():
    """
        Get a transaction getservice :class:`paynlsdk.api.transaction.getservice.Request` instance

        :return: Transaction getservice request instance
        :rtype: paynlsdk.api.transaction.getservice.Request
        """
    from paynlsdk.api.transaction.getservice import Request
    return Request()


@staticmethod
def prime_product_from_hand(card_ints):
    """
        Expects a list of cards in integer form.
        """
    product = 1
    for c in card_ints:
        product *= c & 255
    return product


def R_from_r(r):
    """
    Calculate reflected power R, starting with reflection amplitude r.
    """
    return abs(r) ** 2


def base92_ord(val):
    """
    Map a char to an integer

    >>> base92_ord('!')
    0
    >>> base92_ord('#')
    1
    >>> base92_ord('_')
    61
    >>> base92_ord('a')
    62
    >>> base92_ord('}')
    90
    >>> base92_ord(' ')
    Traceback (most recent call last):
        ...
    ValueError: val is not a base92 character
    """
    num = ord(val)
    if val == '!':
        return 0
    elif ord('#') <= num and num <= ord('_'):
        return num - ord('#') + 1
    elif ord('a') <= num and num <= ord('}'):
        return num - ord('a') + 62
    else:
        raise ValueError('val is not a base92 character')


def md5sum(filename):
    """ Calculate the MD5 sum of file at filename """
    import hashlib
    hash_md5 = hashlib.md5()
    with open(filename, 'rb') as f:
        for buff in iter(lambda : f.read(4096), b''):
            hash_md5.update(buff)
    return hash_md5.hexdigest()


def remove_comment(string_entry):
    """
    Takes a single line and removes and .ini type comments.
    Also remove any spaces at the begining or end of a commented line
    """
    result = string_entry
    for c in '#;':
        if c in result:
            result = result.split(c)[0]
    return result


def union_in_2orders(orders_pd, other_orders_pd):
    """
    并集：分析因子或者参数问题时使用，debug策略问题时筛选出两个orders_pd中所有不同的交易，
    注意这里不认为在相同的交易日买入相同的股票，两笔交易就一样，这里只是两个orders_pd合并
    后使用drop_duplicates做了去除完全一样的order，即结果为并集：
    orders_pd | cmp_orders_pd或orders_pd.union(cmp_orders_pd)
    :param orders_pd: 回测结果生成的交易订单构成的pd.DataFrame对象
    :param other_orders_pd: 回测结果生成的交易订单构成的pd.DataFrame对象
    :return: orders_pd | cmp_orders_pd
    """
    orders_pd = orders_pd.append(other_orders_pd)
    orders_pd = orders_pd.drop_duplicates()
    return orders_pd


def extract_git_dch_cmds(lines, options):
    """Return a dictionary of all Git-Dch: commands found in lines.
    The command keys will be lowercased, i.e. {'ignore' : True,
    'short': True}.  For now, all the options are binary.  Also return
    all of the lines that do not contain Git-Dch: commands."""
    commands = {}
    other_lines = []
    for line in lines:
        if line.startswith('Git-Dch: ') or line.startswith('Gbp-Dch: '):
            cmd = line.split(' ', 1)[1].strip().lower()
            commands[cmd] = True
        else:
            other_lines.append(line)
    return commands, other_lines


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


@classmethod
def _get_url_for_timerange(cls, timerange, **kwargs):
    """
        Method which generates URL results from a timerange and the `map\\_`
        dictionary.

        Parameters
        ----------
        timerange: `sunpy.time.TimeRange`
             The timerange to extract the URLs for.

        \\*\\*kwargs: `dict`
             Any extra keywords to refine the search. Generated from the
             attributes passed to
             `~sunpy.net.dataretriever.client.GenericClient.search`.
        """
    raise NotImplementedError


def h2d(h):
    """Convert hours into degrees."""
    return h * 15.0


def _color_is_white(color):
    """    Returns if the provided color represents "black".

    :param color: A web color name (i.e. ``darkblue``) or a hexadecimal value
            (``#RGB`` or ``#RRGGBB``) or a RGB(A) tuple (i.e. ``(R, G, B)`` or
            ``(R, G, B, A)``)
    :return: ``True`` if color is represents white, otherwise ``False``.
    """
    try:
        color = color.lower()
    except AttributeError:
        pass
    return color in ('#fff', '#ffffff', 'white', (255, 255, 255), (255, 255,
        255, 255), (255, 255, 255, 1.0))


@classmethod
def _scale_height(cls, r):
    """An effective scale height inherited from the locally-isothermal model.

        It is only meant for comparison with other models, and is not
        used anywhere in AMRVAC.
        """
    return cls._sound_speed(r) / cls._keplerian_angular_velocity(r)


def p_second(p):
    """
    simple_primary : '(' expr ')'
    simple_type : '(' type ')'
    const_expr : '(' const_expr ')'
    returning_opt : RETURNING parameter_types
    taking_opt : TAKING parameter_types
    from_opt : FROM primary
    label_decl : FUNCTION fn_name parameters set_returning_opt newlines
               | SUBROUTINE sub_name parameters newlines
               | LABEL label_name parameters newlines
    """
    p[0] = p[2]


@staticmethod
def _define_module_argument_spec():
    """
        Define the argument spec for the ansible module
        :return: argument spec dictionary
        """
    argument_spec = dict(id=dict(required=False), name=dict(required=False),
        location=dict(required=True), description=dict(required=False),
        wait=dict(default=True, type='bool'), state=dict(default='present',
        choices=['present', 'absent']))
    return argument_spec


def _plugin_initialize():
    """
  optional initialization method of this module, will be called once
  :return:
  """
    pass


@classmethod
def export_set(cls, dataset):
    """Formats the dataset according to the Jira table syntax:

        ||heading 1||heading 2||heading 3||
        |col A1|col A2|col A3|
        |col B1|col B2|col B3|

        :param dataset: dataset to serialize
        :type dataset: tablib.core.Dataset
        """
    header = cls._get_header(dataset.headers) if dataset.headers else ''
    body = cls._get_body(dataset)
    return '{}\n{}'.format(header, body) if header else body


def lighten(color, ratio=0.5):
    """Creates a lighter version of a color given by an RGB triplet.

    This is done by mixing the original color with white using the given
    ratio. A ratio of 1.0 will yield a completely white color, a ratio
    of 0.0 will yield the original color.
    """
    red, green, blue, alpha = color
    return red + (1.0 - red) * ratio, green + (1.0 - green) * ratio, blue + (
        1.0 - blue) * ratio, alpha


def get_prepopulated_value(field, instance):
    """Returns preliminary value based on `populate_from`.

    Args:
        field (:obj:`strawberry.fields.md5.MD5Field`): `MD5Field` instance.
        instance (:obj:`django.db.models.Model`): Django model instance.

    Returns:
        str: Prepopulated value.
    """
    if callable(field.populate_from):
        return field.populate_from(instance)
    else:
        attr = getattr(instance, field.populate_from)
        return callable(attr) and attr() or attr


@classmethod
def from_code(cls, status_code, **kwargs):
    """ Instantiate one of subclasses by code

            :rtype: type
        """
    for C in cls.__subclasses__():
        if C.status_code == status_code:
            return C(**kwargs)
    return cls(**kwargs)


def cut_version(id_str):
    """Remove the version ensembl gene/transcript ids
    """
    index_version = id_str.find('.')
    if index_version != -1:
        id_str = id_str[0:index_version]
    return id_str


def _mergeProList(A, B):
    """Return merged proList os A and B."""
    for item in B:
        A.append(item)
    return A


def install_to_remote_access_session(remoteAccessSessionArn=None, appArn=None):
    """
    Installs an application to the device in a remote access session. For Android applications, the file must be in .apk format. For iOS applications, the file must be in .ipa format.
    See also: AWS API Documentation

    Examples
    The following example installs a specific app to a device in a specific remote access session.
    Expected Output:

    :example: response = client.install_to_remote_access_session(
        remoteAccessSessionArn='string',
        appArn='string'
    )

    :type remoteAccessSessionArn: string
    :param remoteAccessSessionArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the remote access session about which you are requesting information.

    :type appArn: string
    :param appArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the app about which you are requesting information.

    :rtype: dict
    :return: {
        'appUpload': {
            'arn': 'string',
            'name': 'string',
            'created': datetime(2015, 1, 1),
            'type': 'ANDROID_APP'|'IOS_APP'|'WEB_APP'|'EXTERNAL_DATA'|'APPIUM_JAVA_JUNIT_TEST_PACKAGE'|'APPIUM_JAVA_TESTNG_TEST_PACKAGE'|'APPIUM_PYTHON_TEST_PACKAGE'|'APPIUM_WEB_JAVA_JUNIT_TEST_PACKAGE'|'APPIUM_WEB_JAVA_TESTNG_TEST_PACKAGE'|'APPIUM_WEB_PYTHON_TEST_PACKAGE'|'CALABASH_TEST_PACKAGE'|'INSTRUMENTATION_TEST_PACKAGE'|'UIAUTOMATION_TEST_PACKAGE'|'UIAUTOMATOR_TEST_PACKAGE'|'XCTEST_TEST_PACKAGE'|'XCTEST_UI_TEST_PACKAGE',
            'status': 'INITIALIZED'|'PROCESSING'|'SUCCEEDED'|'FAILED',
            'url': 'string',
            'metadata': 'string',
            'contentType': 'string',
            'message': 'string'
        }
    }

    :returns:
    ANDROID_APP: An Android upload.
    IOS_APP: An iOS upload.
    WEB_APP: A web appliction upload.
    EXTERNAL_DATA: An external data upload.
    APPIUM_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package upload.
    APPIUM_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package upload.
    APPIUM_PYTHON_TEST_PACKAGE: An Appium Python test package upload.
    APPIUM_WEB_JAVA_JUNIT_TEST_PACKAGE: An Appium Java JUnit test package upload.
    APPIUM_WEB_JAVA_TESTNG_TEST_PACKAGE: An Appium Java TestNG test package upload.
    APPIUM_WEB_PYTHON_TEST_PACKAGE: An Appium Python test package upload.
    CALABASH_TEST_PACKAGE: A Calabash test package upload.
    INSTRUMENTATION_TEST_PACKAGE: An instrumentation upload.
    UIAUTOMATION_TEST_PACKAGE: A uiautomation test package upload.
    UIAUTOMATOR_TEST_PACKAGE: A uiautomator test package upload.
    XCTEST_TEST_PACKAGE: An XCode test package upload.
    XCTEST_UI_TEST_PACKAGE: An XCode UI test package upload.

    """
    pass


def aa_1(provider):
    """Send A-ABORT PDU (service-user source) and start (or restart)
    ARTIM timer.
    """
    provider.dul_socket.send(provider.primitive.encode())
    provider.timer.restart()
    return 'Sta13'


@classmethod
def available(cls):
    """returns True if ALSA is available and running on the system"""
    try:
        from audiotools.output import ALSAAudio
        return True
    except ImportError:
        return False


def keyframe_jump(next: bool=True):
    """Jump to previous/next keyframe

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


def Hexrgb(dec):
    """
    hex to rgb converter
    Arguments: dec = hexadecimal color to convert
    retuns a string of rgb color.
    """
    assert dec == str(dec)
    if dec.startswith('#'):
        dec = dec[1:]
    r = int(dec[0:2], base=16)
    g = int(dec[2:4], base=16)
    b = int(dec[4:6], base=16)
    color = r, g, b
    return color


def theta_H_NH4_PK74(T, P):
    """c-c': hydrogen ammonium [PK74]."""
    theta = -0.016
    valid = T == 298.15
    return theta, valid


@classmethod
def from_label(cls, uniformly_sampled_xml):
    """ Initializes the meta data from an XML description of the Uniformly_Sampled.

        Parameters
        ----------
        uniformly_sampled_xml : Label or ElementTree Element
            Portion of the label describing this Uniformly Sampled field.

        Returns
        -------
        Meta_FieldUniformlySampled
            Contains meta data for a Uniformly_Sampled field.
        """
    obj = cls()
    obj._load_keys_from_xml(uniformly_sampled_xml, tag_modify=(
        'sampling_parameter_', ''))
    obj.full_location = [{'field': obj['name']}]
    keys_must_exist = ['name', 'interval', 'first_value', 'last_value']
    obj._check_keys_exist(keys_must_exist)
    return obj


@staticmethod
def _format_capture(kind, state, details):
    """Tweak what is saved according to your desire(s)."""
    return kind, state, details


@classmethod
def is_intersecting(cls, first, second):
    """
        :param first: first exon to check
        :type first: tuple([int, int])

        :param second: second exon to check
        :type second: tuple([int, int])

        :rtype bool

        Implementation of the is_intersecting method.
        It checks overlaps between exons.
        """
    if first == second or cls.overlap(first, second) < 0:
        return False
    return True


@classmethod
def register_prober(klass, prober):
    """Register a prober that can look for a control dir.

        """
    klass._probers.append(prober)


def __instancecheck__(cls, other):
    """Determine if an instance is of the sliced type and within bounds.

        Args:
            other: The instance to test.

        Returns:
            True if the object is both of the same type as sliced by the
            created class as well as within the bounds defined by the class.
        """
    try:
        return bool(isinstance(other, cls.__type__) and cls(other))
    except ValueError:
        return False


def available_help(mod, ending='_command'):
    """Returns the dochelp from all functions in this module that have _command
    at the end."""
    help_text = []
    for key in mod.__dict__:
        if key.endswith(ending):
            name = key.split(ending)[0]
            docstring = mod.__dict__[key].__doc__
            if docstring:
                help_text.append(name + ':\n' + docstring)
    return help_text


@classmethod
def _from_dict(cls, _dict):
    """Initialize a CategoriesOptions object from a json dictionary."""
    args = {}
    if 'limit' in _dict:
        args['limit'] = _dict.get('limit')
    return cls(**args)


def valid_gameweek(gameweek):
    """Returns True if the gameweek is valid.

    :param gameweek: The gameweek.
    :type gameweek: int or string
    :raises ValueError: if gameweek is not a number between 1 and 38
    """
    gameweek = int(gameweek)
    if gameweek < 1 or gameweek > 38:
        raise ValueError('Gameweek must be a number between 1 and 38.')
    return True


@staticmethod
def _sanitize_response(response):
    """
        Hook to allow subclasses to clean up response data
        """
    return response.content


@classmethod
def from_name(cls, name, frame='icrs', parse=False):
    """
        Given a name, query the CDS name resolver to attempt to retrieve
        coordinate information for that object. The search database, sesame
        url, and  query timeout can be set through configuration items in
        ``astropy.coordinates.name_resolve`` -- see docstring for
        `~astropy.coordinates.get_icrs_coordinates` for more
        information.

        Parameters
        ----------
        name : str
            The name of the object to get coordinates for, e.g. ``'M42'``.
        frame : str or `BaseCoordinateFrame` class or instance
            The frame to transform the object to.
        parse: bool
            Whether to attempt extracting the coordinates from the name by
            parsing with a regex. For objects catalog names that have
            J-coordinates embedded in their names eg:
            'CRTS SSS100805 J194428-420209', this may be much faster than a
            sesame query for the same object name. The coordinates extracted
            in this way may differ from the database coordinates by a few
            deci-arcseconds, so only use this option if you do not need
            sub-arcsecond accuracy for coordinates.

        Returns
        -------
        coord : SkyCoord
            Instance of the SkyCoord class.
        """
    from .name_resolve import get_icrs_coordinates
    icrs_coord = get_icrs_coordinates(name, parse)
    icrs_sky_coord = cls(icrs_coord)
    if frame in ('icrs', icrs_coord.__class__):
        return icrs_sky_coord
    else:
        return icrs_sky_coord.transform_to(frame)


def complex2float(array):
    """Sums real and imaginary parts of an array together element-
    wise. This is used for finding the power of negative numbers
    which are calcuable but not in numpy which returns a nan.

    This is a workaround routine and is typically using as follows:

    complex2float(np.array(array, dtype=complex)**power)

    """
    return array.real + array.imag