def _totuple(x):
    """Utility stuff to convert string, int, float, None or anything to a usable tuple."""
    if isinstance(x, str):
        out = x,
    elif isinstance(x, (int, float)):
        out = str(x),
    elif x is None:
        out = None,
    else:
        out = tuple(x)
    return out


def keep(dataset, tag):
    """K - keep (unchanged for non-sequence attributes, cleaned for sequences)"""
    pass


@classmethod
def Id(cls, id):
    """Class method to create the class from an ID

        :param id: A slack ID, e.g. T1NASNDSP
        :return: A class instance of whatever class this is mixed in to
        """
    cls_instance = cls(dict(id=id))
    cls_instance._repr_keys.add('id')
    return cls_instance


def getLogEntryById(id):
    """Return LogEntry by ID"""


def norm3(vec3):
    """
    Quick convenient function to get the norm of a 3-element vector
    norm3: 475 ns | np.linalg.norm: 4.31 us
    """
    a, b, c = vec3
    return (a * a + b * b + c * c) ** 0.5


def get_settings(data):
    """ Load needed settings from an issue report

    Arguments:
    data -- the parsed issue report dictionary

    Output:
    Dictionary of settings
    """
    settings = {}
    model = data.get('insulin_model')
    if not model:
        raise RuntimeError('No insulin model information found')
    if model.lower() == 'humalognovologchild':
        settings['model'] = [data.get('insulin_action_duration') / 60, 65]
    elif model.lower() == 'humalognovologadult':
        settings['model'] = [data.get('insulin_action_duration') / 60, 75]
    elif model.lower() == 'fiasp':
        settings['model'] = [data.get('insulin_action_duration') / 60, 55]
    else:
        settings['model'] = [data.get('insulin_action_duration') / 60 / 60]
    momentum_interval = data.get('glucose_store').get('momentumDataInterval')
    if momentum_interval is not None:
        settings['momentum_data_interval'] = float(momentum_interval) / 60
    else:
        settings['momentum_data_interval'] = 15
    suspend_threshold = data.get('suspend_threshold')
    if suspend_threshold is not None:
        settings['suspend_threshold'] = float(suspend_threshold)
    else:
        settings['suspend_threshold'] = None
    settings['dynamic_carb_absorption_enabled'] = True
    settings['retrospective_correction_integration_interval'] = 30
    settings['recency_interval'] = 15
    settings['retrospective_correction_grouping_interval'] = 30
    settings['rate_rounder'] = 0.05
    settings['insulin_delay'] = 10
    settings['carb_delay'] = 10
    settings['default_absorption_times'] = [float(data.get(
        'carb_default_absorption_times_fast')) / 60, float(data.get(
        'carb_default_absorption_times_medium')) / 60, float(data.get(
        'carb_default_absorption_times_slow')) / 60]
    settings['max_basal_rate'] = data.get('maximum_basal_rate')
    settings['max_bolus'] = data.get('maximum_bolus')
    settings['retrospective_correction_enabled'] = data.get(
        'retrospective_correction_enabled') and data.get(
        'retrospective_correction_enabled').lower() == 'true'
    return settings


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 before_class(cls, bases, dct):
    """Allows to dynamically change how the class will be constructed"""
    return bases, dct


def getInterestedUsers():
    """Return a list of Users who will want to know about the results of
        this build but who did not actually make the Changes that went into it
        (build sheriffs, code-domain owners)."""


def from79(theWord):
    """Returns an integer from Rep code 0x4F, 16bit signed integer."""
    return theWord


@classmethod
def deserialize_field(cls, value, field_type):
    """
        Deserialise the value of a particular field with a type
        :param value: The value
        :param field_type: The field type
        :return: The deserialised value
        """
    if field_type is None:
        return value
    deserializer_method = getattr(cls, '_deserialize_{}'.format(field_type))
    return deserializer_method(value)


@conf
def find_crayftn(conf):
    """Find the Cray fortran compiler (will look in the environment variable 'FC')"""
    fc = conf.find_program(['crayftn'], var='FC')
    conf.get_crayftn_version(fc)
    conf.env.FC_NAME = 'CRAY'
    conf.env.FC_MOD_CAPITALIZATION = 'UPPER.mod'


def getid(obj):
    """Wrapper to get  object's ID.

    Abstracts the common pattern of allowing both an object or an
    object's ID (UUID) as a parameter when dealing with relationships.
    """
    return getattr(obj, 'id', obj)


def get_shared_size(L1_Preferred):
    """
    Returns the size (in number of doubles) of shared memory for sm_20

    Parameters
    ----------
    L1_Preferred : bool
        If true, prefer a larger L1 cache over more shared memory (recommended)
    """
    if not L1_Preferred:
        return 49152 / 8
    else:
        return 16384 / 8


def refl_vgroupi(refl):
    """
        >>> refl_vgroupi([0, 0, 0, 1, 2, 2, 2])
        [[0, 1, 2], [3], [4, 5, 6]]
    """
    rslts = []
    prev_value = refl[0]
    prev_index = 0
    lngth = len(refl)
    for i in range(1, lngth):
        curr_value = refl[i]
        if curr_value == prev_value:
            pass
        else:
            slc = list(range(prev_index, i))
            rslts.append(slc)
            prev_value = curr_value
            prev_index = i
    slc = list(range(prev_index, lngth))
    rslts.append(slc)
    return rslts


@classmethod
def get_kinetic_energy_cutoff_EEX(cls, calc, **kwargs):
    """Return kinetic energy cutoff for exact exchange (EEX) operator in eV.

        .. note :: by default returns ecutrho, as indicated in
            http://www.quantum-espresso.org/wp-content/uploads/Doc/INPUT_PW.html
        """
    from qe_tools.constants import ry_to_ev
    parameters = calc.inputs.parameters
    try:
        return parameters.get_dict()['SYSTEM']['ecutfock'] * ry_to_ev
    except KeyError:
        pass
    return cls.get_kinetic_energy_cutoff_charge_density(calc)


def clear_parent_children_cache(instance):
    """
    Clears the children_cache of the instance-parent if the instance has
    a parent and the parent is not the instance itself (i.e. pointing to
    itself). The latter will cause an unlimited recursion.
    """
    parent = instance.parent
    if parent and parent != instance:
        if parent.children_cache:
            parent.children_cache = ''
            parent.save()


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

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


@classmethod
def from_url(cls, url, **kwargs):
    """
        Creates an instance of the KubeConfig class from a single URL (useful
        for interacting with kubectl proxy).
        """
    doc = {'clusters': [{'name': 'self', 'cluster': {'server': url}}],
        'contexts': [{'name': 'self', 'context': {'cluster': 'self'}}],
        'current-context': 'self'}
    self = cls(doc, **kwargs)
    return self


def softmax_cross_entropy(data=None, label=None, name=None, attr=None, out=
    None, **kwargs):
    """Calculate cross entropy of softmax output and one-hot label.

    - This operator computes the cross entropy in two steps:
      - Applies softmax function on the input array.
      - Computes and returns the cross entropy loss between the softmax output and the labels.

    - The softmax function and cross entropy loss is given by:

      - Softmax Function:

      .. math:: \\text{softmax}(x)_i = \\frac{exp(x_i)}{\\sum_j exp(x_j)}

      - Cross Entropy Function:

      .. math:: \\text{CE(label, output)} = - \\sum_i \\text{label}_i \\log(\\text{output}_i)

    Example::

      x = [[1, 2, 3],
           [11, 7, 5]]

      label = [2, 0]

      softmax(x) = [[0.09003057, 0.24472848, 0.66524094],
                    [0.97962922, 0.01794253, 0.00242826]]

      softmax_cross_entropy(data, label) = - log(0.66524084) - log(0.97962922) = 0.4281871

    Defined in src/operator/loss_binary_op.cc:L59

    Parameters
    ----------
    data : Symbol
        Input data
    label : Symbol
        Input label

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

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


def cut_at_newline(text):
    """ Cut the text at the first newline. """
    i = text.find('\n')
    if i > -1:
        return text[:i]
    return text


def is_mp_obj(obj):
    """
    Helper function to determine if the current object matches the structure
    that the library enforices for MatrixProfiles.

    Parameters
    ----------
    obj : object
        The object to test.

    Returns
    -------
    bool :
        True or false respectively.
    """
    return isinstance(obj, dict) and obj.get('class') == 'MatrixProfile'


@staticmethod
def get_clique(node, join_tree):
    """
        Gets the parent clique associated with the specified BBN node.

        :param node: BBN node.
        :param join_tree: Join tree.
        :return: Parent clique.
        """
    if 'parent.clique' not in node.metadata:
        cliques = sorted(join_tree.find_cliques_with_node_and_parents(node.
            id), key=lambda x: x.id)
        clique = cliques[0]
        node.add_metadata('parent.clique', clique)
        return clique
    else:
        return node.metadata['parent.clique']


@classmethod
def comment(cls, comment, drop_incompat_keys=False):
    """Patch a comment object"""
    comment['created_time'] = str(int(comment.get('created_at')))
    from_user = {'username': comment['user']['username'], 'profile_picture':
        comment['user']['profile_pic_url'], 'id': str(comment['user']['pk']
        ), 'full_name': comment['user']['full_name']}
    comment['from'] = from_user
    comment['id'] = str(comment['pk'])
    if drop_incompat_keys:
        cls._drop_keys(comment, ['bit_flags', 'content_type', 'created_at',
            'created_at_utc', 'media_id', 'pk', 'status', 'type', 'user',
            'user_id'])
    return comment


def underline(line, underline='~'):
    """Return an underline string for ``line``.

    Intended for use with level 3 and lower headings.

    Note that the default for ``underline`` assumes that the level
    1 and 2 underlines are the standard ``=`` and ``-``. You can
    pass a different underline character to this function if needed.
    """
    if line.endswith('\n'):
        line = line[:-1]
    return '{}\n'.format(underline * len(line))


def add(X, varX, Y, varY):
    """Addition with error propagation"""
    Z = X + Y
    varZ = varX + varY
    return Z, varZ


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


def frobenius_monomial_base(poly: object) ->list:
    """
    Generates a list of monomials of x**(i*p) % g for range(poly.degrees()). Used with Frobenius map.

    Parameters:
        poly (Polynomial): Polynomial to generate bases for.

    Returns:
        list: List of monomial bases mod g.

    References:
        https://github.com/sympy/sympy/blob/d1301c58be7ee4cd12fd28f1c5cd0b26322ed277/sympy/polys/galoistools.py
    """
    from samson.math.symbols import oo
    n = poly.degree()
    if n == 0:
        return []
    P = poly.ring
    q = (poly.coeff_ring.order if poly.coeff_ring.order != oo else poly.
        coeff_ring.characteristic)
    bases = [None] * n
    bases[0] = P.one()
    if q < n:
        for i in range(1, n):
            bases[i] = (bases[i - 1] << q) % poly
    elif n > 1:
        R = P / poly
        x = P.symbol
        bases[1] = R(x) ** q
        for i in range(2, n):
            bases[i] = bases[i - 1] * bases[1]
        for i in range(1, n):
            bases[i] = bases[i].val
    return bases


def type_name(value) ->str:
    """
    Возвращает строковое представление названия класса принимаемого объекта

    :param Any value: объект
    :rtype: str
    :Пример работы:
        >>> type_name('abcd')
        'str'
        >>> type_name(4.5)
        'float'
    """
    return value.__class__.__name__


def get_containing_quad(minx, miny, maxx, maxy):
    """Get Quadrangle within image bounds
    """
    minx = minx + abs(minx) % 0.125
    miny = miny - miny % 0.125 + 0.125
    maxx = maxx + abs(maxx) % 0.125 - 0.125
    maxy = maxy - maxy % 0.125
    return [minx, miny, maxx, maxy]


def ifactor(n):
    """
    The same as factor() above, but designed as a generator; this function
    should be better for massive numbers.

    AUTHORS:
    v1.0.4+             --> pydsigner
    """
    ceil = n // 2 + 1
    i = 2
    while i < ceil:
        nn, rem = divmod(n, i)
        if rem:
            i += 1
        else:
            n = nn
            yield i


@classmethod
def SetProfileDict(cls, keyprofile):
    """Set the keyprofile using a dictionary of id => bindings
        @param cls: Class Object
        @param keyprofile: { menu_id : (u'Ctrl', u'C'), }

        """
    cls.keyprofile = keyprofile


def _factors_count(idadf, columnlist, valuelist=None):
    """
    Count non-missing values for all columns in a list (valuelist) over the
    IdaDataFrame grouped by a list of columns(columnlist).

    Parameters
    ----------
    columnlist : list
        List of column names that exist in self.
    valuelist : list
        List of column names that exist in self.

     Notes
     -----
     The function assumes the following:

        * The columns given as parameter exists in the IdaDataframe
        * The parameter columnlist is a optional and is a list
        * Columns are referenced by their own name (character string)

    Returns
    -------
        DataFrame
    """
    column_string = '"' + '", "'.join(columnlist) + '"'
    name = idadf.internal_state.current_state
    if valuelist is None:
        query = (
            'SELECT %s, COUNT(*) as COUNT FROM %s GROUP BY %s ORDER BY %s, COUNT ASC'
             % (column_string, name, column_string, column_string))
    else:
        agg_list = []
        for value in valuelist:
            query = 'COUNT("%s") as "%s"' % (value, value)
            agg_list.append(query)
        agg_string = ', '.join(agg_list)
        value_string = '"' + '", "'.join(valuelist) + '"'
        query = 'SELECT %s,%s FROM %s GROUP BY %s ORDER BY %s,%s ASC' % (
            column_string, agg_string, name, column_string, column_string,
            value_string)
    return idadf.ida_query(query)


@classmethod
def options(cls):
    """Return list of configs.OxMonOption for configure this task.
        """
    raise NotImplementedError


def dupliob_move_down():
    """Move dupli object down in the list

    """
    pass


def _envdir_merge_func(command_args, noxfile_args):
    """Ensure that there is always some envdir.

    Args:
        command_args (_option_set.Namespace): The options specified on the
            command-line.
        noxfile_Args (_option_set.Namespace): The options specified in the
            Noxfile.
    """
    return command_args.envdir or noxfile_args.envdir or '.nox'


@classmethod
def readable_fields(cls):
    """Get all metadata fields: the writable ones from
        :meth:`fields` and also other audio properties.
        """
    for property in cls.fields():
        yield property
    for property in ('length', 'samplerate', 'bitdepth', 'bitrate',
        'channels', 'format'):
        yield property


def update():
    """
        update the item registered in the canonical
        check that there aren't two translations on the same language
        (used for changing the contexts language)
        """


def shared_access_signature_tokens_are_allowed_only_over_https_3_5(
    storage_accounts):
    """
    There is no automation possible for this currently
    Manual
    """
    pass


def psi_Na_HCO3_HSO4_HMW84(T, P):
    """c-a-a': sodium bicarbonate bisulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def conflicting_indices(X):
    """Finds where the indices are in the rest of feature matrix. This assures
    that the correct indices are dropped.

    Parameters
    ----------
    X : 2D array
        The embed indices. This is the same shape as the actual embedded time
        series.

    Returns
    -------
    conf_ind : 1d array
        Conflicting indices to be dropped.
    """
    conf_ind = []
    for i in range(len(X)):
        inds = []
        for j in range(len(X)):
            if len(set(X[i]).intersection(X[j])) > 0:
                inds.append(j)
        conf_ind.append(inds)
    return conf_ind


@staticmethod
def _to_config(field_name):
    """Convert a field name to a config key"""
    return field_name.replace('_', '-')


def fixe_mode_ecran(cls, mode):
    """Fixe le mode de l'écran

        - "logo": angles et orientation géographique (Défaut)
        - "standard": angles et orientation trigonométrique
        """
    cls.ecran.mode(mode)


def atom_degree(atom):
    """Get the degree of an atom.

    Note that the result will be different depending on whether the Hs are
    explicitly modeled in the graph.

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

    Returns
    -------
    list
        List containing one int only.

    See Also
    --------
    atom_total_degree
    """
    return [atom.GetDegree()]


def int_to_le_bytes(value, size=None):
    """Converts an integer to a big-endian sequence of bytes"""
    if size is None:
        size = (value.bit_length() + 7) // 8
    return value.to_bytes(size, 'little')


def rshift(val, n):
    """python port for '>>>'(right shift with padding)
    """
    return val % 4294967296 >> n


def elt_to_dict(el):
    """Convert xml element attributes to a dictionnary

    Parameters
    ----------
    el

    Returns
    -------

    """
    param = dict([])
    param.update(dict(name=el.tag))
    param_type = el.get('type')
    param.update(dict(type=param_type))
    title = el.get('title')
    if title == 'None':
        title = el.tag
    param.update(dict(title=title))
    if 'visible' not in el.attrib.keys():
        visible = True
    else:
        visible = bool(int(el.get('visible')))
    param.update(dict(visible=visible))
    if 'removable' not in el.attrib.keys():
        removable = False
    else:
        removable = bool(int(el.get('removable')))
    param.update(dict(removable=removable))
    if 'readonly' not in el.attrib.keys():
        readonly = False
    else:
        readonly = bool(int(el.get('readonly')))
    param.update(dict(readonly=readonly))
    if 'show_pb' in el.attrib.keys():
        show_pb = bool(int(el.get('show_pb')))
    else:
        show_pb = False
    param.update(dict(show_pb=show_pb))
    if 'filetype' in el.attrib.keys():
        filetype = bool(int(el.get('filetype')))
        param.update(dict(filetype=filetype))
    if 'detlist' in el.attrib.keys():
        detlist = eval(el.get('detlist'))
        param.update(dict(detlist=detlist))
    if 'movelist' in el.attrib.keys():
        movelist = eval(el.get('movelist'))
        param.update(dict(movelist=movelist))
    if 'addList' in el.attrib.keys():
        addList = eval(el.get('addList'))
        param.update(dict(addList=addList))
    if 'values' in el.attrib.keys():
        values = eval(el.get('values'))
        param.update(dict(values=values))
    if 'limits' in el.attrib.keys():
        limits = eval(el.get('limits'))
        param.update(dict(limits=limits))
    return param


def isPoint(pointlist):
    """ Verify is a list is a list of points """
    if len(pointlist) in [2, 3]:
        if isinstance(pointlist[0], (int, float)) and isinstance(pointlist[
            1], (int, float)):
            return True
        else:
            return False
    else:
        return False


def _filename_dataset(dataset, market=None, variant=None, extension=None):
    """
    Compose the filename for a dataset given its name, variant, market,
    and filename extension.

    :param dataset: String with dataset name e.g. 'income'.
    :param market: Optional string with dataset market e.g. 'usa'.
    :param variant: Optional string with dataset variant e.g. 'ttm'.
    :param extension: Optional string with filename extension e.g. 'zip' or 'csv'.
    :return: String with filename for the dataset-file.
    """
    assert dataset is not None
    if market is None:
        filename = dataset
    else:
        filename = '{}-{}'.format(market, dataset)
    if variant is not None:
        filename = '{}-{}'.format(filename, variant)
    if extension is not None:
        filename = '{}.{}'.format(filename, extension)
    return filename


@staticmethod
def _get_test_callable_name(test):
    """
        Base class override.
        """
    _, _, class_and_callable_name = test.address()
    first_dot_index = class_and_callable_name.find('.')
    test_callable_name = class_and_callable_name[first_dot_index + 1:]
    return test_callable_name


@classmethod
def reset_connection_params(cls):
    """Removes all existing connection parameter information."""
    cls._connection_params = {}


def __new__(cls, scope: 'Scope2', *args, **kwargs):
    """Overwrite superclass method to enforce singleton manager per Scope2 object."""
    instance = super().__new__(cls)
    if scope.id in cls.__existing_managers:
        instance = cls.__existing_managers[scope.id]
    else:
        cls.__existing_managers[scope.id] = instance
    return instance


def get_fs_ndf_name(function_space):
    """ Returns a ndf name for this FunctionSpace object. """
    return 'ndf_' + function_space.mangled_name


def set_compat_six_eight(flag_value):
    """Allow backwards compatibility with calculations bug from Thinc 6.8"""
    global REPRODUCE_BUG
    REPRODUCE_BUG = flag_value


def __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max):
    """
    For RGB_to_HSL and RGB_to_HSV, the Hue (H) component is calculated in
    the same way.
    """
    if var_max == var_min:
        return 0.0
    elif var_max == var_R:
        return (60.0 * ((var_G - var_B) / (var_max - var_min)) + 360) % 360.0
    elif var_max == var_G:
        return 60.0 * ((var_B - var_R) / (var_max - var_min)) + 120
    elif var_max == var_B:
        return 60.0 * ((var_R - var_G) / (var_max - var_min)) + 240.0


@classmethod
def from_bytes(cls, bs, offset=0, length=None, **kw):
    """ Return a `CornuCopyBuffer` fed from the supplied bytes `bs`
        starting at `offset` and ending after `length`.

        This is handy for callers parsing using buffers but handed bytes.

        Parameters:
        * `bs`: the bytes
        * `offset`: a starting position for the data; the input
          data will start this far into the bytes
        * `length`: the maximium number of bytes to use; the input
          data will be cropped this far past the starting point;
          default: the number of bytes in `bs` after `offset`
        Other keyword arguments are passed to the buffer constructor.
    """
    if offset < 0:
        raise ValueError('offset(%d) should be >= 0' % (offset,))
    if offset > len(bs):
        raise ValueError('offset(%d) beyond end of bs (%d bytes)' % (offset,
            len(bs)))
    if length is None:
        length = len(bs) - offset
    elif length < 1:
        raise ValueError('length(%d) < 1' % (length,))
    end_offset = offset + length
    if end_offset > len(bs):
        raise ValueError('offset(%d)+length(%d) > len(bs):%d' % (offset,
            length, len(bs)))
    if offset > 0 or end_offset < len(bs):
        bs = memoryview(bs)[offset:end_offset]
    return cls([bs], **kw)


def _old_break_annotation_tie(annotated_lines):
    """Chose an attribution between several possible ones.

    :param annotated_lines: A list of tuples ((file_id, rev_id), line) where
        the lines are identical but the revids different while no parent
        relation exist between them

     :return : The "winning" line. This must be one with a revid that
         guarantees that further criss-cross merges will converge. Failing to
         do so have performance implications.
    """
    return sorted(annotated_lines)[0]


def clean_extra_expose_des_motifs(html):
    """
    the budget related texts have an exposé des motifs per article
    at the depot step, we remove all of them except the last one
    to make the later parsing easier
    """
    before_expose, after_expose = [], []
    last_expose = []
    expose = False
    count = 0
    we_are_inside_an_expose_table = False
    for line in html.split('\n'):
        if '>Exposé des motifs' in line:
            expose = ['']
            count += 1
        elif line and expose:
            if '<table' in line:
                we_are_inside_an_expose_table = True
            if '
' in line or '' in line or
                    '' in line or ' 3:
        return '\n'.join(before_expose + last_expose + after_expose), True
    return html, False


@conf
def find_msgfmt(conf):
    """
	Detects msgfmt and sets the ``MSGFMT`` variable
	"""
    conf.find_program('msgfmt', var='MSGFMT')


def quote_plus(s):
    """
    Convert some URL elements to be HTTP-safe.

    Not the same as in urllib, because, for instance, parentheses and commas
    are passed through.

    Parameters
    ----------
    s: input URL/portion

    Returns
    -------
    corrected URL
    """
    s = s.replace('/', '%2F')
    s = s.replace(' ', '%20')
    return s


def flag(val):
    """Does the value look like an on/off flag?"""
    if val == 1:
        return True
    elif val == 0:
        return False
    val = str(val)
    if len(val) > 5:
        return False
    return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF')


def _CrossDeviceCopy(name=None, attr=None, out=None, **kwargs):
    """Special op to copy data cross device

    Parameters
    ----------

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

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


def unshift_token(text):
    """Remove a token from the front of a string.

    :param str text:
    :returns: {'text': str, 'separator': str, 'remainder': str}
    """
    if len(text) == 0:
        return {'text': text, 'separator': '', 'remainder': ''}
    token = ''
    for i in range(0, len(text)):
        char = text[i]
        if char == ' ' and (len(token) >= 1 and token[i - 1] == ' '):
            token += char
        elif char == ' ' and len(token) == 0:
            token += char
        elif char == ' ':
            return {'text': token, 'separator': ' ', 'remainder': text[i + 1:]}
        elif char == '\n':
            return {'text': token, 'separator': '\n', 'remainder': text[i + 1:]
                }
        elif len(token) >= 1 and token[i - 1] == ' ':
            return {'text': token, 'separator': '', 'remainder': text[len(
                token):]}
        else:
            token += char
    return {'text': token, 'separator': '', 'remainder': ''}


def _overlaps(media_a, media_b):
    """Determines if two TrackMedia overlap."""
    a1 = media_a.start
    a2 = media_a.start + media_a.duration - 1
    b1 = media_b.start
    b2 = media_b.start + media_b.duration - 1
    return a1 <= b2 and b1 <= a2


def update_a_node(base, node_id, profile_id=None, name=None, metadata=None,
    tainted=None, role=None, wait_timeout=None):
    """Utility function that updates a Senlin node.

    Update a node and return it after it is ACTIVE.
    """
    params = {'node': {'profile_id': profile_id, 'metadata': metadata,
        'name': name, 'role': role}}
    if tainted is not None:
        params['node']['tainted'] = tainted
    res = base.client.update_obj('nodes', node_id, params)
    action_id = res['location'].split('/actions/')[1]
    base.client.wait_for_status('actions', action_id, 'SUCCEEDED', wait_timeout
        )
    return res['body']['status_reason']


def vvo2max(vo2max):
    """
    Calculates velocity (kilometers/hour) at a specified VO2Max (mL/(kg*min))

    args:
        vo2max (float): VO2Max, given in mL/(kg * min)

    Returns:
        float: kilometers / hour
    """
    return vo2max / 3.5


def forward(apps, schema_editor):
    """
    Updates default value of context field
    """
    if not schema_editor.connection.alias == 'default':
        return
    Config = apps.get_model('config', 'Config')
    for config in Config.objects.filter(context__isnull=True):
        config.context = {}
        config.save()


def _initialize_global_variables(likelihood, priors, search_parameter_keys,
    use_ratio):
    """
    Store a global copy of the likelihood, priors, and search keys for
    multiprocessing.
    """
    global _likelihood
    global _priors
    global _search_parameter_keys
    global _use_ratio
    _likelihood = likelihood
    _priors = priors
    _search_parameter_keys = search_parameter_keys
    _use_ratio = use_ratio


def next_round_turn(game_state):
    """ Takes the round and turn from the game state dict and returns
    the round and turn of the next step in a dict.

    Returns
    -------
    dict { 'round' , 'turn' }
        The updated round and turn

    Raises
    ------
    ValueError
        If gamestate['gameover'] is True
    """
    if game_state['gameover']:
        raise ValueError('Game is already over')
    turn = game_state['turn']
    round = game_state['round']
    if turn is None and round is None:
        turn = 0
        round = 1
    else:
        turn = turn + 1
        if turn >= 4:
            turn = turn % 4
            round = round + 1
    return {'round': round, 'turn': turn}


def eval_default(expression, default_res=None):
    """Calls eval on expression and returns default_res if it throws
    exceptions
    """
    if default_res is None:
        default_res = expression
    try:
        return eval(expression)
    except:
        pass
    return default_res


def link_annotation(objects, file_ann):
    """Link the File Annotation to each object."""
    for o in objects:
        if o.canAnnotate():
            o.linkAnnotation(file_ann)


def get_termsize():
    """Return terminal size as a tuple (height, width)."""
    try:
        import struct, fcntl, termios
        height, width = struct.unpack('hhhh', fcntl.ioctl(0, termios.
            TIOCGWINSZ, '\x00' * 8))[0:2]
        if not (height and width):
            height, width = 24, 79
    except (ImportError, IOError) as e:
        height, width = 24, 79
    return height, width


def no_constraints():
    """default constraints function for FitProblem"""
    return 0


def driver_variables_paste(replace: bool=False):
    """Add copied driver variables to the active driver

    :param replace: Replace Existing, Replace existing driver variables, instead of just appending to the end of the existing list
    :type replace: bool
    """
    pass


def camel_case(name):
    """Convert words into CamelCase."""
    return ''.join(name.capitalize().split())


def run():
    """
        Fire 'startup' System Events, move the reactor to the 'running'
        state, then run the main loop until it is stopped with C{stop()} or
        C{crash()}.
        """


def _get_template_params(template, param_values):
    """Return all required parameter values for the specified template.
    :param dict template: Template JSON object.
    :param dict param_values: User provided parameter values.
    """
    param_keys = {}
    try:
        for param, values in template['parameters'].items():
            if 'type' not in values:
                raise ValueError('Parameter {} does not have type defined'.
                    format(param))
            try:
                value = param_values[param]
                if isinstance(value, dict) and value.get('value') != None:
                    param_keys[param] = value.get('value')
                else:
                    param_keys[param] = value
            except KeyError:
                param_keys[param] = values.get('defaultValue')
    except KeyError:
        pass
    return param_keys


def flip7(x, y):
    """ fast, slow to dety, detz"""
    return -y, x


def build_url(group_id, artifact_id, version, filename, baseurl=
    'http://repo1.maven.org/maven2'):
    """
    Return a download URL for a Maven artifact built from its coordinates.
    """
    filename = filename or ''
    group_id = group_id.replace('.', '/')
    path = '{group_id}/{artifact_id}/{version}'.format(**locals())
    return '{baseurl}/{path}/{filename}'.format(**locals())


def template3():
    """RDKitFingerprint"""
    script = """
                ## (Enter,datasets)
                    << host = cheml
                    << function = load_cep_homo
                    >> smiles 2

                ## (Represent,molecular descriptors)
                    << host = cheml
                    << function = RDKitFingerprint
                    << molfile = @molfile
                    >> 0 molfile
                    >> df 1

                ## (Store,file)
                    << host = cheml
                    << function = SaveFile
                    << format = smi
                    << header = False
                    << filename = smiles
                    >> filepath 0
                    >> 2 df

                ## (Store,file)
                    << host = cheml
                    << function = SaveFile
                    << filename = Fingerprints
                    >> 1 df
            """
    return script.strip().split('\n')


def disable(fontid: int, option: int):
    """Disable option.

    :param fontid: The id of the typeface as returned by blf.load(), for default font use 0.
    :type fontid: int
    :param option: One of ROTATION, CLIPPING, SHADOW or KERNING_DEFAULT.
    :type option: int
    """
    pass


def upgrade():
    """Update database."""


def get_current_canvas():
    """ Proxy for context.get_current_canvas to avoud circular import.
    This function replaces itself with the real function the first
    time it is called. (Bah)
    """
    from .context import get_current_canvas
    globals()['get_current_canvas'] = get_current_canvas
    return get_current_canvas()


def argparser_to_readme(argparser, template='README-template.md',
    destination='README.md', indentation=0, placeholder='{{ argparse }}'):
    """Add the formatted help output of a command line utility using the
    Python module `argparse` to a README file.

    :param object argparser: The argparse parser object.
    :param str template: The path of a template text file containing the
      placeholder. Default: `README-template.md`
    :param str destination: The path of the destination file. Default:
      `README.me`
    :param int indentation: Indent the formatted help output by X spaces.
      Default: 0
    :param str placeholder: Placeholder string that gets replaced by the
      formatted help output. Default: `{{ argparse }}`
    """
    help_string = argparser().format_help()
    if indentation > 0:
        indent_lines = []
        lines = help_string.split('\n')
        for line in lines:
            indent_lines.append(' ' * indentation + line)
        help_string = '\n'.join(indent_lines)
    with open(template, 'r', encoding='utf-8') as template_file:
        template_string = template_file.read()
        readme = template_string.replace(placeholder, help_string)
    readme_file = open(destination, 'w')
    readme_file.write(readme)
    readme_file.close()


def r(o, t):
    """
    Transform back from the Boltzmann variable into `r`.

    Parameters
    ----------
    o : float or numpy.ndarray
        Value(s) of the Boltzmann variable. If a `numpy.ndarray`, it must have
        a shape broadcastable with `t`.
    t : float or numpy.ndarray
        Time(s). If a `numpy.ndarray`, it must have a shape broadcastable with
        `o`. Values must be positive.

    Returns
    -------
    r : float or numpy.ndarray
        The return is a float if both `o` and `t` are floats. Otherwise it is a
        `numpy.ndarray` of the shape that results from broadcasting `o` and
        `t`.

    See also
    --------
    o
    t
    """
    return o * t ** 0.5


def getTypeInfo(contentType):
    """ Return an ITypeInformation for the given type name / object.

        o If 'contentType' is actually an object, rather than a string,
          attempt to look up the appropriate type info using its 'portal_type'.

        o Permission:  Public
        """


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 squared_pov_index(expenditure, poverty_line):
    """
        This is a weighted sum of poverty gaps, where the weights are the proportionate poverty gaps.
        Hence, by squaring the poverty gap index, the measure implicitly puts more weight on observations that fall well below the poverty line.

        First argument is a list having numerical values of individual's or country's expenditure
        Second argument refers to the minimum income for not being considered as poor.
    """
    index = 0
    for country in expenditure:
        if country < poverty_line:
            index += (poverty_line - country) / poverty_line * ((
                poverty_line - country) / poverty_line)
    if len(expenditure) != 0:
        return index / len(expenditure)
    else:
        print('Check Expenditure data.')
        return


def format_role_order(roles):
    """Given roles, returns them in the format: role_arn,principal_arn.

    The format of the attribute value should be role_arn,principal_arn
    but lots of blogs list it as principal_arn,role_arn so let's reverse
    them if needed.

    Args:
        roles: List of roles.

    Returns:
        List of roles in the format: role_arn,principal_arn
    """
    for role in roles:
        chunks = role.split(',')
        if 'saml-provider' in chunks[0]:
            _role = chunks[1] + ',' + chunks[0]
            index = roles.index(role)
            roles.insert(index, _role)
            roles.remove(role)
    return roles


def ImportRelatedNamespaces():
    """Import modules for related namespaces so they are available to
    create binding instances from the WSDL sources."""
    try:
        import pyxb.bundles.wssplat.soapbind11
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soapbind12
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soap11
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soap12
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soapenv
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.httpbind
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.mimebind
    except ImportError:
        pass


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


def _like_rnncell_(cell):
    """Checks that a given object is an RNNCell by using duck typing."""
    conditions = [hasattr(cell, 'output_size'), hasattr(cell, 'state_size'),
        hasattr(cell, 'zero_state'), callable(cell)]
    return all(conditions)


def manage_workspace(REQUEST):
    """Dispatch to first interface in manage_options
        """


@classmethod
def card_list(cls, *args):
    """Create a list of new cards.

        Each argument should describe one card with rank and suit together.

        :param args: One or more cards.
        :type rank: str
        :returns: List of new cards, one for each input parameter.
        :rtype: list of :class:`pokercards.cards.Card` objects
        :raises: ValueError
        """
    lst = []
    for c in args:
        lst.append(cls(c))
    return lst


@classmethod
def _encode_markdown(cls, message):
    """Make transformations to the message prior to rendering as Markdown.

        The main thing is to convert spaces to non-breaking spaces, so that
        plaintext spacing is preserved.
        """
    md_message = message.replace(' ', ' ')
    return md_message


def make_dhdu(ham, controls, derivative_fn):
    """
    Computes the partial of the hamiltonian w.r.t control variables.

    :param ham: Hamiltonian function.
    :param controls: A list of each control variable.
    :param derivative_fn: Total derivative function.
    :return: :math:`dH/du`
    """
    dHdu = []
    for ctrl in controls:
        dHdu.append(derivative_fn(ham, ctrl['symbol']))
    return dHdu


def neighborCoordinates(particleNum, coordList, neighborList):
    """
    Given a certain particle and the list of coordinates and neighbors, this
    function generates the list of a particle's neighbors' coordinates. The fact
    that the indexing of the neighbor list is off, is taken into account in this
    function.

    Inputs: particleNum - index of desired particle
            coordList - list of all particle coordinates in the packing
            neighborList - list of all particle neighborhoods in the packing

    Returns: numpy array of the neighbor's coordinates
    """
    return list(map(lambda x: coordList[x], neighborList))


@classmethod
def is_digit(cls, user_input):
    """
        Checks if the given input is an integer or a digit string.

        :rtype: bool
        """
    return isinstance(user_input, int) or isinstance(user_input, str
        ) and user_input.isdigit()


@staticmethod
def value_aspect_ratio(data):
    """Returns a string"""
    info = data.get('display_aspect_ratio', None)
    return info, info or 'null'


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

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


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


def set_tl_state(traffic_lights, traffic_light_state):
    """Sets all traffic lights in the `traffic_lights` list to the given state.

    Args:
        traffic_lights (list): List of carla.TrafficLight actors
        traffic_light_state (carla.TrafficLightState):  The state to set the
            lights

    Returns:
        None

    """
    for traffic_light in traffic_lights:
        traffic_light.set_state(traffic_light_state)


def descent_set(perm):
    """Returns descent set of the permutation

    >>> Permutation(42561873).descent_set()
    [1, 4, 6, 7]
    """
    p = list(perm)
    n = perm.__len__()
    descents = []
    for i in range(1, n):
        if p[i - 1] > p[i]:
            descents.append(i)
    return descents


def silent(obj):
    """ Mark view method or class as "silent" so events won't be fired.

    Should be used as decorator on view classes or methods.

    :param obj: Any object that allows attributes assignment. Should be
        either view method or view class.
    """
    obj._silent = True
    return obj


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 interpolate_sequence():
    """Generate ‘in-betweens’ to smoothly interpolate between Grease Pencil frames

    """
    pass


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

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

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


@classmethod
def filter(cls, o):
    """
            Filter object with this class in data
            return
            True when object contains this datablock
            False otherwhise
            usage:
            class_name.filter(object) from outside world
            self.__class__.filter(object) from instance
        """
    try:
        return cls.__name__ in o.data
    except:
        pass
    return False


def monitored(fn):
    """Provides monitoring capabilities for task methods."""
    return fn


def clickselect(extend: bool=False, column: bool=False, curves: bool=False):
    """Select keyframes by clicking on them

    :param extend: Extend Select, Toggle keyframe selection instead of leaving newly selected keyframes only
    :type extend: bool
    :param column: Column Select, Select all keyframes that occur on the same frame as the one under the mouse
    :type column: bool
    :param curves: Only Curves, Select all the keyframes in the curve
    :type curves: bool
    """
    pass


def create_ip_set(Name=None, ChangeToken=None):
    """
    Creates an  IPSet , which you use to specify which web requests you want to allow or block based on the IP addresses that the requests originate from. For example, if you're receiving a lot of requests from one or more individual IP addresses or one or more ranges of IP addresses and you want to block the requests, you can create an IPSet that contains those IP addresses and then configure AWS WAF to block the requests.
    To create and configure an IPSet , perform the following steps:
    For more information about how to use the AWS WAF API to allow or block HTTP requests, see the AWS WAF Developer Guide .
    See also: AWS API Documentation

    Examples
    The following example creates an IP match set named MyIPSetFriendlyName.
    Expected Output:

    :example: response = client.create_ip_set(
        Name='string',
        ChangeToken='string'
    )

    :type Name: string
    :param Name: [REQUIRED]
            A friendly name or description of the IPSet . You can't change Name after you create the IPSet .

    :type ChangeToken: string
    :param ChangeToken: [REQUIRED]
            The value returned by the most recent call to GetChangeToken .

    :rtype: dict
    :return: {
        'IPSet': {
            'IPSetId': 'string',
            'Name': 'string',
            'IPSetDescriptors': [
                {
                    'Type': 'IPV4'|'IPV6',
                    'Value': 'string'
                },
            ]
        },
        'ChangeToken': 'string'
    }

    :returns:
    Name (string) -- [REQUIRED]
    A friendly name or description of the  IPSet . You can't change Name after you create the IPSet .

    ChangeToken (string) -- [REQUIRED]
    The value returned by the most recent call to  GetChangeToken .

    """
    pass


def is_alpha(character):
    """
    Checks if the given character represents an alphabet
    letter. This is a complex operation as many comparison
    operations must be performed.

    :rtype: bool
    :return: If the given character represents an alphabet
    letter.
    """
    return (character >= 'a' and character <= 'z' or character >= '0' and
        character <= '9' or character >= 'A' and character <= 'Z' or
        character == '_' or character == '$' or character == '\\' or
        character is not None and ord(character) > 126)


def operator_defaults():
    """Set the active operator to its default values

    """
    pass


def parse_units(varname, variable):
    """Parses units based on variable input"""
    try:
        units = variable.units
        units = units.replace('-', '**-')
        units = units.replace('mmr', '1').replace('S', 'ohm**-1')
        units = units.replace('cm3', 'cm**3').replace('erg/g/s', 'erg/(g*s)')
        units = units.replace('none', '1')
    except:
        units = ''
        if varname == 'Z':
            units = 'cm'
    return units


def pony_func(func):
    """Decorator to mark expose a method to a PonyDebugger caller."""
    func.is_pony_func = True
    return func


@staticmethod
def get_compatable_state_types():
    """
        This is needed so the service framework knows which
        states this current state is compatable.
        return::['str'] A list of the compatable state, update types.
        """
    return ['full_update_out']


def get_context_keys_for_custom_policy(PolicyInputList=None):
    """
    Gets a list of all of the context keys referenced in the input policies. The policies are supplied as a list of one or more strings. To get the context keys from policies associated with an IAM user, group, or role, use  GetContextKeysForPrincipalPolicy .
    Context keys are variables maintained by AWS and its services that provide details about the context of an API query request, and can be evaluated by testing against a value specified in an IAM policy. Use GetContextKeysForCustomPolicy to understand what key names and values you must supply when you call  SimulateCustomPolicy . Note that all parameters are shown in unencoded form here for clarity, but must be URL encoded to be included as a part of a real HTML request.
    See also: AWS API Documentation

    :example: response = client.get_context_keys_for_custom_policy(
        PolicyInputList=[
            'string',
        ]
    )

    :type PolicyInputList: list
    :param PolicyInputList: [REQUIRED]
            A list of policies for which you want the list of context keys referenced in those policies. Each document is specified as a string containing the complete, valid JSON text of an IAM policy.
            The regex pattern used to validate this parameter is a string of characters consisting of any printable ASCII character ranging from the space character (u0020) through end of the ASCII character range as well as the printable characters in the Basic Latin and Latin-1 Supplement character set (through u00FF). It also includes the special characters tab (u0009), line feed (u000A), and carriage return (u000D).
            (string) --

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

    :returns:
    (string) --

    """
    pass


def sort_column_ui_context():
    """Change sorting to use column under cursor

    """
    pass


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['type']
    if type == 'volume':
        return 'VolumeSourceFromVolumeDetails'
    if type == 'volumeBackup':
        return 'VolumeSourceFromVolumeBackupDetails'
    else:
        return 'VolumeSourceDetails'


def get_rightbottom_from_lefttop(lefttop, res):
    """Compute right bottom corner of a rectangle from its left top."""
    return lefttop[0] + res[0], lefttop[1] + res[1]


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

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

    """
    pass


def parseFilterStr(args):
    """Convert Message-Filter settings in '+<addr> -<addr> ...' format to a dict of the form
    { '<addr>':True, '<addr>':False, ... }
    Returns a list: ['<prefix>', filters]
    """
    out = {}
    if type(args) in str:
        args = [args]
    prefix = None
    for arg in args:
        head = None
        for plus in arg.split('+'):
            minus = plus.split('-')
            plusfs = minus.pop(0).strip()
            if len(plusfs):
                plusfs = '/' + plusfs.strip('/')
            if head == None and plusfs != '/*':
                head = plusfs
            elif len(plusfs):
                if plusfs == '/*':
                    out = {'/*': True}
                else:
                    out[plusfs] = True
            for minusfs in minus:
                minusfs = minusfs.strip()
                if len(minusfs):
                    minusfs = '/' + minusfs.strip('/')
                    if minusfs == '/*':
                        out = {'/*': False}
                    else:
                        out[minusfs] = False
        if prefix == None:
            prefix = head
    return [prefix, out]


def _convert_flatten(builder, node, graph, err):
    """
    convert to CoreML Flatten Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4826
    """
    axis = node.attrs.get('axis', 1)
    builder.add_flatten_to_2d(name=node.name, input_name=node.inputs[0],
        output_name=node.outputs[0], axis=axis)


def sn(ok):
    """converts boolean value to +1 or -1
  """
    if ok:
        return 1
    else:
        return -1


@staticmethod
def untab(g):
    """A token which will decrease the indent depth by the default amount
        if added to the stream"""
    g.indent_depth -= g.default_indent


@classmethod
def _is_expired(cls, ttl_ms, cur_ms):
    """
        Return true if ttl is expired
        :param ttl_ms: Ttl
        :type ttl_ms: float
        :param ttl_ms: Current ms
        :type ttl_ms: float
        :return bool
        """
    return ttl_ms <= cur_ms


def pytest_internalerror(excrepr, excinfo):
    """ called for internal errors. """


def get_preferred_sparse_format():
    """Get the preferred sparse matrix format supported by the backend.

    Different backends have their preferred backend. This info is useful when
    constructing a sparse matrix.

    Returns
    -------
    string
        the name of the preferred sparse matrix format.
    """
    pass


def dissolve_verts(use_face_split: bool=False, use_boundary_tear: bool=False):
    """Dissolve verts, merge edges and faces

    :param use_face_split: Face Split, Split off face corners to maintain surrounding geometry
    :type use_face_split: bool
    :param use_boundary_tear: Tear Boundary, Split off face corners instead of merging faces
    :type use_boundary_tear: bool
    """
    pass


def edit_string_for_tags(tags):
    """
    Given list of ``Tag`` instances, creates a string representation of
    the list suitable for editing by the user, such that submitting the
    given string representation back without changing it will give the
    same list of tags.

    Tag names which contain commas will be double quoted.

    If any tag name which isn't being quoted contains whitespace, the
    resulting string of tag names will be comma-delimited, otherwise
    it will be space-delimited.
    """
    names = []
    use_commas = False
    for tag in tags:
        name = tag.name
        if ',' in name:
            names.append('"%s"' % name)
            continue
        elif ' ' in name:
            if not use_commas:
                use_commas = True
        names.append(name)
    if use_commas:
        glue = ', '
    else:
        glue = ' '
    result = glue.join(names)
    if len(names) == 1 and use_commas:
        result = '"' + result + '"'
    return result


def select(iterable, conditional):
    """
     Looks through each value in the list, returning an array of all the values that pass a truth test (conditional).

    params: conditional, iterable
        iterable -> list, sequenece, set, dictionary, generator etc
        conditional -> a lambda or function that takes one or two inputs, first is element from iterable, second is index (optional)

    Examples:

    >>> list(_.find([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0))
    >>> [2, 4, 6]

    """
    return filter(conditional, iterable)


def colorspace(size):
    """Returns an cycler over a linear color space with 'size' entries.

    Args:
        size (int): the number of colors to define in the space.

    Returns:
        itertools.cycle: iterable cycler with 'size' colors.
    """
    from matplotlib import cm
    from itertools import cycle
    import numpy as np
    rbcolors = cm.rainbow(np.linspace(0, 1, size))
    return cycle(rbcolors)


def sendMessage(title, message, receiver, sender=None, replyTo=None):
    """ Send a IMS message.
        """


@classmethod
def error_resp(cls, text, **kwargs):
    """Ошибка запроса пользователя.

        Args:
            text: [description]
            **kwargs: [description]

        Returns:
            Возвращает себя инициализированного
            Message

        """
    return cls(response=400, error=text, **kwargs)


@classmethod
def _from_dict(cls, _dict):
    """Initialize a RuntimeIntent object from a json dictionary."""
    args = {}
    if 'intent' in _dict:
        args['intent'] = _dict.get('intent')
    else:
        raise ValueError(
            "Required property 'intent' not present in RuntimeIntent JSON")
    if 'confidence' in _dict:
        args['confidence'] = _dict.get('confidence')
    else:
        raise ValueError(
            "Required property 'confidence' not present in RuntimeIntent JSON")
    return cls(**args)


def gravity_wmg(weight, mass):
    """Usage: gravity_wmg(weight of object, mass of object)"""
    return weight / mass


def format_step(step, zero_prefix=False):
    """Return the step value in format suitable for display."""
    if isinstance(step, int):
        return '{:06}'.format(step) if zero_prefix else '{}'.format(step)
    elif isinstance(step, tuple):
        return '{:04}:{:06}'.format(*step) if zero_prefix else '{}:{}'.format(*
            step)


def returning_available(raise_exception=False):
    """
    Tests if returning query is available
    :return: boolean
    """
    try:
        from django_pg_returning import ReturningQuerySet
        return True
    except ImportError:
        if raise_exception:
            raise ImportError(
                'Returning feature requires django-pg-returning library installed. Use pip install django-pg-returning'
                )
        else:
            return False


def gravity_outside(gravitation):
    """ translate gavitation name for adding text outside"""
    dict_return = {}
    if gravitation == 'N':
        dict_return['vertical'] = 'top'
        dict_return['horizontal'] = 'Center'
    if gravitation == 'NW':
        dict_return['vertical'] = 'top'
        dict_return['horizontal'] = 'West'
    if gravitation == 'NE':
        dict_return['vertical'] = 'top'
        dict_return['horizontal'] = 'East'
    if gravitation == 'W':
        dict_return['vertical'] = 'top'
        dict_return['horizontal'] = 'West'
    if gravitation == 'C':
        dict_return['vertical'] = 'top'
        dict_return['horizontal'] = 'Center'
    if gravitation == 'E':
        dict_return['vertical'] = 'top'
        dict_return['horizontal'] = 'East'
    if gravitation == 'SW':
        dict_return['vertical'] = 'bottom'
        dict_return['horizontal'] = 'West'
    if gravitation == 'S':
        dict_return['vertical'] = 'bottom'
        dict_return['horizontal'] = 'Center'
    if gravitation == 'SE':
        dict_return['vertical'] = 'bottom'
        dict_return['horizontal'] = 'East'
    return dict_return


@classmethod
def create_with_netlinks(cls, name, netlinks, **kwargs):
    """
        Create a multilink with a list of StaticNetlinks. To properly create
        the multilink using this method, pass a list of netlinks with the
        following dict structure::

            netlinks = [{'netlink': StaticNetlink,
                         'ip_range': 1.1.1.1-1.1.1.2,
                         'netlink_role': 'active'}]

        The `netlink_role` can be either `active` or `standby`. The remaining
        settings are resolved from the StaticNetlink. The IP range value must
        be an IP range within the StaticNetlink's specified network.
        Use kwargs to pass any additional arguments that are supported by the
        `create` constructor.
        A full example of creating a multilink using predefined netlinks::

            multilink = Multilink.create_with_netlinks(
                name='mynewnetlink',
                netlinks=[{'netlink': StaticNetlink('netlink1'),
                           'ip_range': '1.1.1.2-1.1.1.3',
                           'netlink_role': 'active'},
                          {'netlink': StaticNetlink('netlink2'),
                           'ip_range': '2.1.1.2-2.1.1.3',
                           'netlink_role': 'standby'}])

        :param StaticNetlink,DynamicNetlink netlink: StaticNetlink element
        :param str ip_range: ip range for source NAT on this netlink
        :param str netlink_role: the role for this netlink, `active` or
            `standby`
        :raises CreateElementFailed: failure to create multilink
        :rtype: Multilink
        """
    multilink_members = []
    for member in netlinks:
        m = {'ip_range': member.get('ip_range', '0.0.0.0'), 'netlink_role':
            member.get('netlink_role', 'active')}
        netlink = member.get('netlink')
        m.update(netlink_ref=netlink.href)
        if netlink.typeof == 'netlink':
            m.update(network_ref=netlink.data.get('ref')[0])
        multilink_members.append(m)
    return cls.create(name, multilink_members, **kwargs)


def initialization_VBGMM(n_components, points_data, points_test=None,
    covariance_type='full'):
    """
    This method returns an array of k means and an array of k covariances (dim,dim)
    which will be used in order to initialize an EM algorithm

    Parameters
    ----------
    points : an array (n_points,dim)

    k : int
        the number of clusters

    Returns
    -------
    means : an array (n_components,dim)
        The initial means computed

    cov : an array (n_components,dim,dim)
        The initial covariances computed

    log_weights : an array (n_components,)
        The initial weights (log) computed

    log_assignements : an array (n_points,n_components)
        The log of the soft assignements according to VBGMM

    """
    from .VBGMM import VariationalGaussianMixture
    GM = VariationalGaussianMixture(n_components)
    GM.fit(points_data, points_test, patience=0)
    log_assignements = GM.predict_log_resp(points_data)
    return GM.means, GM.cov, GM.log_weights, log_assignements


def module_file(module):
    """Return the correct original file name of a module."""
    name = module.__file__
    return name[:-1] if name.endswith('.pyc') else name


@classmethod
def _parse(cls, spec, cmdline_type):
    """
        Parse an adapter specification for a non-linked adapter (without '...')

        Allow:
        'back' and ADAPTER
        'back' and ADAPTERX
        'back' and ADAPTER$
        'front' and ADAPTER
        'front' and XADAPTER
        'front' and ^ADAPTER
        'anywhere' and ADAPTER
        """
    if cmdline_type not in ('front', 'back', 'anywhere'):
        raise ValueError('cmdline_type must be front, back or anywhere')
    error = ValueError(
        'You cannot use multiple placement restrictions for an adapter at the same time. Choose one of ^ADAPTER, ADAPTER$, XADAPTER or ADAPTERX'
        )
    spec, middle, parameters_spec = spec.partition(';')
    name, spec = cls._extract_name(spec)
    spec = spec.strip()
    parameters = cls._parse_parameters(parameters_spec)
    spec = cls.expand_braces(spec)
    if len(spec.strip('X')) == 0:
        return name, None, spec, {}
    front_restriction = None
    if spec.startswith('^'):
        front_restriction = 'anchored'
        spec = spec[1:]
    if spec.upper().startswith('X'):
        if front_restriction is not None:
            raise error
        front_restriction = 'noninternal'
        spec = spec.lstrip('xX')
    back_restriction = None
    if spec.endswith('$'):
        back_restriction = 'anchored'
        spec = spec[:-1]
    if spec.upper().endswith('X'):
        if back_restriction is not None:
            raise error
        back_restriction = 'noninternal'
        spec = spec.rstrip('xX')
    n_placement_restrictions = int(bool(front_restriction)) + int(bool(
        back_restriction))
    if n_placement_restrictions > 1:
        raise error
    if cmdline_type == 'front' and back_restriction:
        raise ValueError(
            "Allowed placement restrictions for a 5' adapter are XADAPTER and ^ADAPTER"
            )
    if cmdline_type == 'back' and front_restriction:
        raise ValueError(
            "Allowed placement restrictions for a 3' adapter are ADAPTERX and ADAPTER$"
            )
    assert front_restriction is None or back_restriction is None
    if front_restriction is not None:
        restriction = front_restriction
    else:
        restriction = back_restriction
    if cmdline_type == 'anywhere' and restriction is not None:
        raise ValueError(
            "Placement restrictions (with X, ^, $) not supported for 'anywhere' (-b) adapters"
            )
    return name, restriction, spec, parameters


@staticmethod
def margins_func(widget_item):
    """ Get the margins for the given widget item.

        """
    m = widget_item.widget().contentsMargins()
    return m.top(), m.right(), m.bottom(), m.left()


def _get_complete(node):
    """
    Get flag indicating whether the checklist contains all species seen.

    :param node: the tag for the body of the last section in the checklist.

    :return: True is all species seen were recorded, False if not.

    """
    tag = node.find('div', class_='all-spp-ans').find('h5')
    value = tag.text.strip().lower()
    return value == 'yes'


def add_feather_vertex_slide(MASK_OT_add_feather_vertex=None,
    MASK_OT_slide_point=None):
    """Add new vertex to feather and slide it

    :param MASK_OT_add_feather_vertex: Add Feather Vertex, Add vertex to feather
    :param MASK_OT_slide_point: Slide Point, Slide control points
    """
    pass


def error_response(o):
    """if o is a string then it's an error response
    utility function to return errors from a sub-call to validate/error_handler
    decorated function
    """
    if not isinstance(o, str):
        return False
    return o


def df_equal(df1, df2):
    """
    Compares two dataframe and tells if they are equal.

    @param          df1     first dataframe
    @param          df2     second dataframe
    @return                 boolean

    The function compare column one by one.
    It does not check the order of the columns is the same.
    It reorders the columns before doing the comparison.

    If you need more complex comparison,
    you can look into function :epkg:`assert_frame_equal`_.

    The function does not handle well NaN values because ``numpy.nan != numpy.nan`` is true.
    It also compares types:

    .. faqref::
        :tag: pandas
        :title: Comment comparer deux dataframe?

        Ecrire ``df1 == df2`` ne compare pas deux dataframes entre deux
        car le sens n'est pas forcément le même pour tout le monde.
        Même si les valeurs sont les mêmes, est-ce l'ordre des colonnes
        est important ?
        Il faut le faire soi-même pour une comparaison spécifique à
        vos besoins. Le code ci-dessus
        compare d'abord les dimensions, ensuite compare l'ordre
        des colonnes puis enfin les valeurs ::

            if df1.shape != df2.shape:
                return False
            l1 = list(df1.columns)
            l2 = list(df2.columns)
            l1.sort()
            l2.sort()
            if l1 != l2:
                return False
            df1 = df1[l1]
            df2 = df2[l2]
            t = (df1 == df2).all()
            s = set(t)
            return False not in s

        Autres alternatives :

        * `equals <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.equals.html>`_
        * :epkg:`assert_frame_equal`
    """
    if df1.shape != df2.shape:
        return False
    l1 = list(df1.columns)
    l2 = list(df2.columns)
    l1.sort()
    l2.sort()
    if l1 != l2:
        return False
    df1 = df1[l1]
    df2 = df2[l2]
    s = set(df1.dtypes == df2.dtypes)
    if False in s:
        return False
    s = set((df1 == df2).all())
    return False not in s


def dictadd(*dicts):
    """
    Returns a dictionary consisting of the keys in the argument dictionaries.
    If they share a key, the value from the last argument is used.

        >>> dictadd({1: 0, 2: 0}, {2: 1, 3: 1})
        {1: 0, 2: 1, 3: 1}
    """
    result = {}
    for dct in dicts:
        result.update(dct)
    return result


def readfile(filename, encoding='windows-1251'):
    """
    Reading file and moving it into dictionary

    filename - existing file
    encoding - encoding of given file
    """
    out = dict()
    with open(filename, encoding=encoding) as settings_file:
        for line in settings_file:
            line = line.rstrip()
            if line[:1] != '#' and len(line) > 0:
                key, value = line.split('=', 1)
                out[key] = value.rstrip()
    return out


def _adjust_returns(returns, adjustment_factor):
    """
    Returns the returns series adjusted by adjustment_factor. Optimizes for the
    case of adjustment_factor being 0 by returning returns itself, not a copy!

    Parameters
    ----------
    returns : pd.Series or np.ndarray
    adjustment_factor : pd.Series or np.ndarray or float or int

    Returns
    -------
    adjusted_returns : array-like
    """
    if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:
        return returns
    return returns - adjustment_factor


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 int_to_bytes_8(k: int) ->bytes:
    """Serialize an integer to the corresponding big endian bytes."""
    assert 0 <= k < 2 ** 64
    return k.to_bytes(8, byteorder='big')


def find_flag_groups(h5group, strict=True):
    """Returns all HDF5 Groups under the given group that contain a flag

    The check is just that the sub-group has a ``'name'`` attribute, so its
    not fool-proof by any means.

    Parameters
    ----------
    h5group : `h5py.Group`
        the parent group in which to search

    strict : `bool`, optional, default: `True`
        if `True` raise an exception for any sub-group that doesn't have a
        name, otherwise just return all of those that do

    Raises
    ------
    KeyError
        if a sub-group doesn't have a ``'name'`` attribtue and ``strict=True``
    """
    names = []
    for group in h5group:
        try:
            names.append(h5group[group].attrs['name'])
        except KeyError:
            if strict:
                raise
            continue
    return names


def map_to_num(ser):
    """Replace a columns existing content with frequency rank E.g. replace names with their frequences"""
    mapping = ser.value_counts().reset_index().reset_index().set_index('index'
        )['level_0']
    return ser.apply(mapping.get).astype(str)


@classmethod
def exponential(cls, lam, sam):
    """
        Visualization for an Exponential distribution
        Args:
            lam (float): parameter to an Exponential distribution
        Returns:
            image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
        """
    if lam <= 0:
        raise ValueError(
            'For an Exponential distribution, lambda should be greater than zero.'
            )
    return cls._call_post(dist='exponential', lam=lam, sam=sam)


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

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


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

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

    """
    pass


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

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

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


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

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


def unregister(module_name: str):
    """Unregisters an addon’s UI translations.

    :param module_name: The name identifying the addon.
    :type module_name: str
    """
    pass


def reboot(session):
    """
    Reboot windows machine

    :param session: instance of Windows, which hold session to win machine
    :type session: winremote.Windows
    :returns: True if cmd successfully ran, False otherwise
    :rtype: bool
    """
    return session.run_cmd('shutdown /r /t 1')[0]


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

        :param LookupError val:
        :rtype: GetMetadataError
        """
    return cls('path', val)


def setup_plots(fontsize=8, usetex=True, figsize=None):
    """
    This function adjusts matplotlib settings so that all figures in the
    textbook have a uniform format and look.
    """
    import matplotlib
    if figsize:
        matplotlib.rc('figure', figsize=figsize, dpi=150)
    matplotlib.rc('legend', fontsize=fontsize * 3 // 4, handlelength=3)
    matplotlib.rc('axes', titlesize=fontsize)
    matplotlib.rc('axes', labelsize=fontsize)
    matplotlib.rc('xtick', labelsize=fontsize)
    matplotlib.rc('ytick', labelsize=fontsize)
    matplotlib.rc('text', usetex=usetex)
    matplotlib.rc('font', size=fontsize, family='serif', style='normal',
        variant='normal', stretch='normal', weight='normal')


@classmethod
def _get_sensors_temperatures(cls, chassis):
    """Get temperature sensors reading.

        :param chassis: Redfish `chassis` object
        :returns: returns a dict of sensor data.
        """
    sensors = {}
    for temps in chassis.thermal.temperatures:
        sensor = cls._sensor2dict(temps, 'identity',
            'max_reading_range_temp', 'min_reading_range_temp',
            'reading_celsius', 'physical_context', 'sensor_number')
        sensor.update(cls._sensor2dict(temps.status, 'state', 'health'))
        unique_name = '%s@%s' % (temps.identity, chassis.identity)
        sensors[unique_name] = sensor
    return sensors


def int_one(vals):
    """ Return an integer value of 1
    """
    return int(1)


def get_yesno(parent=None, title='User Input', prompt='Yes or No:'):
    """Opens a simple yes/no message box, returns a bool
    """
    ret = input(prompt + ' (Y/N): ')
    if ret.lower() == 'n':
        return False
    else:
        return True


@staticmethod
def _binary_insert(lst, elem, key, lo=0, hi=None):
    """
        Insert an element into a sorted list, and keep the list sorted.

        The major difference from bisect.bisect_left is that this function supports a key method, so user doesn't have
        to create the key array for each insertion.

        :param list lst: The list. Must be pre-ordered.
        :param object element: An element to insert into the list.
        :param func key: A method to get the key for each element in the list.
        :param int lo: Lower bound of the search.
        :param int hi: Upper bound of the search.
        :return: None
        """
    if lo < 0:
        raise ValueError('lo must be a non-negative number')
    if hi is None:
        hi = len(lst)
    while lo < hi:
        mid = (lo + hi) // 2
        if key(lst[mid]) < key(elem):
            lo = mid + 1
        else:
            hi = mid
    lst.insert(lo, elem)


def point_left_of_line(point, line_start, line_end):
    """Determines whether a point is left of a line

    :param point: Point to be checked (tuple with x any y coordinate)
    :param line_start: Starting point of the line (tuple with x any y coordinate)
    :param line_end: End point of the line (tuple with x any y coordinate)
    :return: True if point is left of line, else False
    """
    return (line_end[0] - line_start[0]) * (point[1] - line_start[1]) - (
        line_end[1] - line_start[1]) * (point[0] - line_start[0]) < 0


def get_hosted_zone(Id=None):
    """
    Gets information about a specified hosted zone including the four name servers assigned to the hosted zone.
    See also: AWS API Documentation

    :example: response = client.get_hosted_zone(
        Id='string'
    )

    :type Id: string
    :param Id: [REQUIRED]
            The ID of the hosted zone that you want to get information about.

    :rtype: dict
    :return: {
        'HostedZone': {
            'Id': 'string',
            'Name': 'string',
            'CallerReference': 'string',
            'Config': {
                'Comment': 'string',
                'PrivateZone': True|False
            },
            'ResourceRecordSetCount': 123
        },
        'DelegationSet': {
            'Id': 'string',
            'CallerReference': 'string',
            'NameServers': [
                'string',
            ]
        },
        'VPCs': [
            {
                'VPCRegion': 'us-east-1'|'us-east-2'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-west-2'|'eu-central-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-south-1'|'ap-northeast-1'|'ap-northeast-2'|'sa-east-1'|'ca-central-1'|'cn-north-1',
                'VPCId': 'string'
            },
        ]
    }

    """
    pass


@classmethod
def _create(cls, doc):
    """Create a db instance on the server."""
    return cls.api.create(cls.__collection_name__, doc)


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


def _helper_reraises_exception(ex):
    """Pickle-able helper function for use by _guarded_task_generation."""
    raise ex


def landscape(pagesize):
    """Use this to get page orientation right"""
    a, b = pagesize
    if a < b:
        return b, a
    else:
        return a, b


def document_collection_object(section, collection_model, include_signature
    =True):
    """Documents a collection resource object

    :param section: The section to write to

    :param collection_model: The model of the collection

    :param include_signature: Whether or not to include the signature.
        It is useful for generating docstrings.
    """
    if include_signature:
        section.style.start_sphinx_py_attr(collection_model.name)
    section.include_doc_string('A collection of %s resources' %
        collection_model.resource.type)


def update2Dlines(iline, x, y):
    """
    provide a common interface to update objects on the plot to a new position (x,y) depending
    on whether they are hlines, vlines, dots etc

    Parameters
    ----------

    iline: :obj:`matplotlib.lines.Line2D` object

    x : float with new position

    y : float with new position

    """
    if not hasattr(iline, 'whatisthis'):
        raise AttributeError(
            "This method will only work if iline has the attribute 'whatsthis'"
            )
    elif iline.whatisthis in ['dot']:
        iline.set_xdata(x)
        iline.set_ydata(y)
    elif iline.whatisthis in ['lineh']:
        iline.set_ydata((y, y))
    elif iline.whatisthis in ['linev']:
        iline.set_xdata((x, x))
    else:
        raise TypeError('what is this type of 2Dline?')


@classmethod
def users_teams(cls, user_id):
    """Gets all the teams a user is part of.

        Args:
            user_id:

        Returns:

        """
    for item in cls.client()._GET_paginated('/user/{0}/team/'.format(user_id)):
        yield item


@classmethod
def apply_state(cls, *bloks):
    """ Call the rigth method is the blok state change

        .. warning::

            for the uninstallation the method called is ``uninstall_all``

        :param bloks: list of the blok name load by the registry
        """
    for blok in bloks:
        b = cls.query().filter(cls.name == blok).first()
        if b.state in ('undefined', 'uninstalled', 'toinstall'):
            b.install()
        elif b.state == 'toupdate':
            b.upgrade()
    uninstalled_bloks = cls.query().filter(cls.state == 'uninstalled').all(
        ).name
    conditional_bloks_to_install = []
    for blok in uninstalled_bloks:
        if cls.check_if_the_conditional_are_installed(blok):
            conditional_bloks_to_install.append(blok)
    if conditional_bloks_to_install:
        for b in conditional_bloks_to_install:
            cls.query().filter(cls.name == b).update({cls.state: 'toinstall'})
        return True
    return False


def view_center_pick():
    """Center the view to the Z-depth position under the mouse cursor

    """
    pass


@staticmethod
def _qargs_int(key, values, default):
    """Return the query arg value as an integer for the specified key or
        return the specified default value.

        :param str key: The key to return the value for
        :param dict values: The query value dict returned by urlparse
        :param int default: The default return value
        :rtype: int

        """
    return int(values.get(key, [default])[0])


@classmethod
def serialize(serializer, fname, corpus, id2word=None, index_fname=None,
    progress_cnt=None, labels=None, metadata=False, **kwargs):
    """
        Iterate through the document stream `corpus`, saving the documents
        as a ShardedCorpus to `fname`.

        Use this method instead of calling `save_corpus` directly.
        You may need to supply some kwargs that are used upon dataset creation
        (namely: `dim`, unless the dataset can infer the dimension from the
        given corpus).

        Ignore the parameters id2word, index_fname, progress_cnt, labels
        and metadata. They currently do nothing and are here only to
        provide a compatible method signature with superclass."""
    serializer.save_corpus(fname, corpus, id2word=id2word, progress_cnt=
        progress_cnt, metadata=metadata, **kwargs)


@staticmethod
def __check_none(instance, missing_str, for_str):
    """if instance is None, raise error """
    if not instance:
        raise ValueError('Missing {} for {}.'.format(missing_str, for_str))


@staticmethod
def interpolate(dq0, dq1, t):
    """Return interpolated dual quaternion

        Parameters
        ----------
        dq0 : skrobot.coordinates.dual_quaternion.DualQuaternion
        dq1 : skrobot.coordinates.dual_quaternion.DualQuaternion
            dual quaternion
        t : float
            ratio of interpolation. Must be 0 <= t <= 1.0.
        """
    if not 0 <= t <= 1:
        raise ValueError(
            'Interpolation step must be between 0 and 1, but gives {}'.
            format(t))
    dqt = dq0 * (1 - t) + dq1 * t
    return dqt.normalized


@classmethod
def from_json(cls, json_obj):
    """Parses the message from a dictionary that has be
        deserialized form json, and returns a new instance of the
        parsed message.

        @param json_obj A dictionary with the json representation.

        @returns A new instance of the message.
        """
    raise NotImplementedError()


def _visibility_clauses(show, hide):
    """
    Given the show/hide clauses of an element's **kwargs,
    construct the angular directives to insert into the template.
    """
    visibility = None
    if hide:
        visibility = 'ng-hide="{0}"'.format(hide)
    if show:
        show = ' ng-show="{0}"'.format(show)
        if visibility:
            visibility += show
        else:
            visibility = show
    return visibility


def psi_Na_BOH4_Cl_FW86(T, P):
    """c-a-a': sodium borate chloride [FW86]."""
    psi = -0.0073
    valid = T == 298.15
    return psi, valid


def time_independent_HMAC_compare(a, b):
    """
    No-one likes timing attacks.

    This function should probably not be part of the public API, and thus will
    be deprecated in a future release to be replaced with a internal function.
    """
    if len(a) != len(b):
        return False
    result = 0
    a, b = a.lower(), b.lower()
    for x, y in zip(a, b):
        result |= ord(x) ^ ord(y)
    return result == 0


def to_list(obj):
    """Convert an object to a list if it is not already one"""
    if not isinstance(obj, (list, tuple)):
        obj = [obj]
    return obj


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

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'User role restriction'
    return 'userrestrictrole'


@classmethod
def get_testing_options(cls):
    """Get testing options for the transform class.

        Returns:
            list: Multiple dictionaries of keywords and messages before/after
                pairs that will result from the transform created by the provided
                keywords.

        """
    return [{'in/out': [(1, NotImplementedError)], 'kwargs': {
        'initial_state': {'test': 1}, 'original_datatype': {'type': 'int'}}}]


@classmethod
def register(cls, resource_body_cls):
    """Register resource."""
    resource_type = resource_body_cls.resource_type
    assert resource_type not in cls._REGISTERED_TYPES
    cls._REGISTERED_TYPES[resource_type] = resource_body_cls
    return resource_body_cls


def set_center_principal():
    """Set optical center to center of footage

    """
    pass


def beforeDaemonize():
    """
        Hook to be called immediately before daemonization. No reactor methods
        may be called until L{afterDaemonize} is called.

        @return: C{None}.
        """


def put_value(json_data, field, value):
    """Put the value for a multiple depth key."""
    data = json_data
    field = field[1:] if field and field.startswith('.') else field
    fields = field.split('.') if field else []
    for idx, fld in enumerate(fields):
        if idx == len(fields) - 1:
            data[fld] = value
        elif fld not in data or not isinstance(data[fld], dict):
            data[fld] = {}
        data = data[fld]


def put_blockhashes(blockhashes):
    """
        @param blockhashes=list
        Add the block hash tree to the share.
        """


@classmethod
def get_or_create(cls, **fields):
    """Return an existing or create a new document.

        This will find and return a single document matching the
        query specified through ``**fields``. If no document is found,
        a new one will be created.

        Along with returning the ``Model`` instance, a boolean value
        will also be returned to indicate whether or not the document
        was created.

        :param safe: (optional) **DEPRECATED** Use ``w`` instead.
        :type safe: bool.
        :param w: (optional) The number of servers that must receive the
                  update for it to be successful.
        :type w: int.
        :param \\*\\*fields: Keyword arguments specifying the query.
        :type \\*\\*fields: \\*\\*kwargs.
        :returns: tuple -- the :class:`~simon.Model` and whether the
                  document was created.
        :raises: :class:`~simon.Model.MultipleDocumentsFound`

        """
    write_concern = {'safe': fields.pop('safe', None), 'w': fields.pop('w',
        None)}
    try:
        return cls.get(**fields), False
    except cls.NoDocumentFound:
        return cls.create(safe=write_concern['safe'], w=write_concern['w'],
            **fields), True


def is_model_managed(model):
    """True if managed is True in Meta class"""
    return model._meta.managed


def get_group_key(request, group, prefix='hacl', suffix=None):
    """
    @Linked to `lru_wrapped`
    :param request:
    :param group:
    :param prefix:
    :param suffix:
    :return:
    """
    if suffix is None:
        suffix = ''
    return '{prefix}:site_{site_id}:group_{group_id}{suffix}'.format(prefix
        =prefix, site_id=request.site.id, group_id=group.id, suffix=suffix)


def is_cython_class(cls):
    """Returns whether a class is a Cython extension class."""
    return '__pyx_vtable__' in cls.__dict__


@staticmethod
def _first_not_none(seq, supplier_func):
    """Applies supplier_func to each element in seq, returns 1st not None

        :param seq: Sequence of object
        :type seq: iterable
        :param supplier_func: Function that extracts the desired value from
            elements in seq
        :type supplier_func: function
        """
    for i in seq:
        obj = supplier_func(i)
        if obj is not None:
            return obj
    return None


def get_nuclear_dipole_moment(qc, component='x'):
    """Computes the nuclear part of the dipole moment.

  **Parameters:**

  qc : class
    QCinfo class. (See :ref:`Central Variables` for details.)
  component : string, {'x','y', 'z'}
    Specifies the compontent of the dipole moment operator which shall be applied.

  **Returns:**

  nuclear_dipole_moment : float
    Contains the nuclear dipole moment.
  """
    if not isinstance(component, int):
        component = 'xyz'.find(component)
    if component == -1:
        raise ValueError('The selection of the component was not valid!' +
            " (component = 'x' or 'y' or 'z')")
    nuclear_dipole_moment = 0.0
    for i_nuc in range(len(qc.geo_spec)):
        nuclear_dipole_moment += float(qc.geo_info[i_nuc, 2]) * qc.geo_spec[
            i_nuc, component]
    return nuclear_dipole_moment


def parse_encoding_header(header):
    """
    Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form,
    {'encoding-name':qvalue}.
    """
    encodings = {'identity': 1.0}
    for encoding in header.split(','):
        if encoding.find(';') > -1:
            encoding, qvalue = encoding.split(';')
            encoding = encoding.strip()
            qvalue = qvalue.split('=', 1)[1]
            if qvalue != '':
                encodings[encoding] = float(qvalue)
            else:
                encodings[encoding] = 1
        else:
            encodings[encoding] = 1
    return encodings


@staticmethod
def run(instance, instances):
    """Enrich instance object with jump hosts."""
    return instance


def motor_lid_3d_construction(c):
    """ construct the 3D-assembly-configurations of the motor_lid
  """
    hr = c['holder_radius']
    eh = c['extrusion_height'] / 2.0
    motor_lid_3dconf1 = []
    motor_lid_3dconf1.append(('holder_A_fig', 0.0, 0.0, 0.0, 0.0, c[
        'extrusion_height'], 'i', 'xy', 0.0, 0.0, 0 * eh))
    motor_lid_3dconf1.append(('middle_lid_0_fig', 0.0, 0.0, 0.0, 0.0, c[
        'extrusion_height'], 'i', 'xy', 0.0, 0.0, 5 * eh))
    motor_lid_3dconf1.append(('middle_lid_1_fig', 0.0, 0.0, 0.0, 0.0, c[
        'extrusion_height'], 'i', 'xy', 0.0, 0.0, 5 * eh))
    motor_lid_3dconf1.append(('holder_B_fig', 0.0, 0.0, 0.0, 0.0, c[
        'extrusion_height'], 'i', 'xy', 0.0, 0.0, 10 * eh))
    if c['fastening_BC_external_radius'] > 0:
        motor_lid_3dconf1.append(('holder_C_fig', 0.0, 0.0, 0.0, 0.0, c[
            'extrusion_height'], 'i', 'xy', 0.0, 0.0, 15 * eh))
    motor_lid_3dconf1.append(('holder_A_with_motor_lid_fig', 0.0, 0.0, 0.0,
        0.0, c['extrusion_height'], 'i', 'xy', 0.0, 0.0, 0 * eh))
    r_assembly = {}
    r_slice = {}
    r_assembly['motor_lid_3dconf1'] = motor_lid_3dconf1
    r_slice['motor_lid_3dconf1'] = 2 * hr, 2 * hr, 6 * eh, -hr, -hr, 0.0, [eh
        ], [], []
    return r_assembly, r_slice


def position(text, pos, vals):
    """A peglet action: always succeed, producing the current position."""
    return pos, pos, vals + (pos,)


def second():
    """
    Return millis for a second
    :return: 1000
    """
    return 1000


def questionnaire_branch():
    """
    Ask about lookup branch.
    """
    while True:
        branch = input('BRANCH (ex. AAD): ')
        if len(branch) != 3 or not branch.isalpha():
            print('BRANCH MUST BE 3 LETTERS, TRY AGAIN')
            continue
        else:
            break
    return branch


def read1Result(selectfile):
    """
    Loads in a bifacial_radiance results file ``.csv`` format,
    and return a :py:class:`~pandas.DataFrame`

    Parameters
    ----------
    selectfile : str
        File name (with path if not in working folder) that has been produced by
        bifacial_radiance.

    Returns
    -------
    resultsDF : :py:class:`~pandas.DataFrame`
        Dataframe with the bifacial_radiance .csv values read.

    """
    import pandas as pd
    resultsDF = pd.read_csv(selectfile)
    return resultsDF


def pdmssp_connect_device(module_version):
    """
    Method collects user inputs for phone's MAC address.
    INPUTS: none
    OUTPUT: Returns macaddr when successful, None when unsuccessful.
    """
    import re
    print(f'Welcome to VVXME CLI Menu version {module_version}\n')
    print('Attempting to connect endpoint on PDMS-SP:\n')
    print('[Step-1]: Collect phone MAC Address.\n')
    macaddr = ''
    loop = True
    while loop:
        macaddr = input(
            'Enter MAC address of the phone(no separators[-:], Eg.64167f12a34b): '
            )
        if re.match('([0-9a-f]{2}){6}$', macaddr.lower()):
            print(f'{macaddr} is a valid MAC address.')
            return macaddr
        else:
            print(
                f"Invalid input '{macaddr}' >> Invalid MAC address format. Do not use separators[-:], Eg.64167f12a34b"
                )