def strip_type(t):
    """Return type name from type declaration"""
    t = t.replace(' ', '')
    if t.startswith('type('):
        t = t[t.index('(') + 1:t.index(')')]
    if t.startswith('class('):
        t = t[t.index('(') + 1:t.index(')')]
    return t.lower()


@classmethod
def validate(cls, change_type):
    """Validate change type and raise ValueError if invalid"""
    if change_type not in cls.types:
        raise ValueError(
            "Invalid script's config change type '%s'. Should be one of %s" %
            (change_type, str(cls.types)))


def intersect_line_sphere(line_a, line_b, sphere_co, sphere_radius, clip=True):
    """Takes a line (as 2 points) and a sphere (as a point and a radius) and returns the intersection

	Parameters:
	line_a (mathutils.Vector) – First point of the line
	line_b (mathutils.Vector) – Second point of the line
	sphere_co (mathutils.Vector) – The center of the sphere
	sphere_radius (sphere_radius) – Radius of the sphere

	Returns: The intersection points as a pair of vectors or None when there is no intersection

	Return type: A tuple pair containing mathutils.Vector or None"""
    from . import Vector
    return Vector, Vector


@staticmethod
def get_amr_line(input_f):
    """
        Read the file containing AMRs. AMRs are separated by a blank line.
        Each call of get_amr_line() returns the next available AMR (in one-line form).
        Note: this function does not verify if the AMR is valid

        """
    cur_amr = []
    has_content = False
    for line in input_f:
        line = line.strip()
        if line == '':
            if not has_content:
                continue
            else:
                break
        if line.strip().startswith('#'):
            continue
        else:
            has_content = True
            cur_amr.append(line.strip())
    return ''.join(cur_amr)


@classmethod
def CreateDerived(cls, category_to_unit_and_exps, resulting_class=None,
    unknown_unit_caption=None):
    """
        Same as _CreateDerived, but always validating the category and units.

        .. see:: _CreateDerived for parameters.
        """
    return cls._CreateDerived(category_to_unit_and_exps, resulting_class,
        unknown_unit_caption=unknown_unit_caption)


@staticmethod
def dotDrawTransition(st1, label, st2, sep='\n'):
    """ Draw a transition in Dot Format

        :param str st1: starting state
        :param str st2: ending state
        :param str label: symbol
        :param str sep: separator
        :rtype: str"""
    return '"{0:s}" -> "{1:s}" [label = "{2:s}"];{3:s} '.format(st1, st2,
        label, sep)


def _get_win_folder_from_registry(csidl_name):
    """This is a fallback technique at best. I'm not sure if using the
    registry for this guarantees us the correct answer for all CSIDL_*
    names.
    """
    import winreg
    shell_folder_name = {'CSIDL_APPDATA': 'AppData', 'CSIDL_COMMON_APPDATA':
        'Common AppData', 'CSIDL_LOCAL_APPDATA': 'Local AppData'}[csidl_name]
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
        'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'
        )
    dir, _ = winreg.QueryValueEx(key, shell_folder_name)
    return dir


def remove(src, rel, dst):
    """
    Returns an SQL statement that removes edges from
    the SQL backing store. Either `src` or `dst` may
    be specified, even both.

    :param src: The source node.
    :param rel: The relation.
    :param dst: The destination node.
    """
    smt = 'DELETE FROM %s' % rel
    queries = []
    params = []
    if src is not None:
        queries.append('src = ?')
        params.append(src)
    if dst is not None:
        queries.append('dst = ?')
        params.append(dst)
    if not queries:
        return smt, params
    smt = '%s WHERE %s' % (smt, ' AND '.join(queries))
    return smt, params


def conserve_mpmath_dps(func):
    """After the function finishes, resets the value of mpmath.mp.dps to
    the value it had before the function was run.
    """
    import functools
    import mpmath

    def func_wrapper():
        dps = mpmath.mp.dps
        try:
            func()
        finally:
            mpmath.mp.dps = dps
    func_wrapper = functools.update_wrapper(func_wrapper, func)
    return func_wrapper


def isPortalOrDefaultChild():
    """Determine if the context is the portal or a default-document"""


def api_get_xy(source, obj=None, keys_method=None, values_method=None):
    """
    get x: y data from an api endpoint

    :returns: `obj`, `obj` tuple
    :param source: either a `str` url or a django view
    :param obj: object to use for x and y vectors
    :param x_method: `list` of `str` method(s) to call on x object
    :param y_method: `list` of `str` method(s) to call on y object
    """
    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 collapse_polytomies(phylobuddy, threshold, mode='support'):
    """
    Remove nodes if their support value or branch length are below the given threshold
    :param phylobuddy: PhyloBuddy objecct
    :param threshold: Value below which the node will be removed
    :type threshold: float
    :param mode: Choose which value to apply threshold to (either 'support' or 'length')
    :return: The modified PhyloBuddy object
    """
    if mode not in ['support', 'length']:
        raise NameError("Mode must be 'support' or 'length'")
    for tree in phylobuddy.trees:
        tree.encode_bipartitions()
        for node in tree.postorder_node_iter():
            try:
                value = node.label if mode == 'support' else node.edge_length
                if float(value) < threshold:
                    for child in node.child_nodes():
                        child.parent_node = node.parent_node
                    if node.parent_node:
                        node.parent_node.remove_child(node)
                        tree.encode_bipartitions()
            except TypeError:
                continue
    return phylobuddy


def is_pangram(sentence):
    """Determines if a sentence is a pangram."""
    from string import ascii_lowercase
    sentence = sentence.lower()
    for letter in ascii_lowercase:
        if letter not in sentence:
            return False
    return True


def split_after(iterable, pred):
    """Yield lists of items from *iterable*, where each list ends with an
    item where callable *pred* returns ``True``:

        >>> list(split_after('one1two2', lambda s: s.isdigit()))
        [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']]

        >>> list(split_after(range(10), lambda n: n % 3 == 0))
        [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

    """
    buf = []
    for item in iterable:
        buf.append(item)
        if pred(item) and buf:
            yield buf
            buf = []
    if buf:
        yield buf


def get_colmin(data):
    """
    Get rowwise column names with minimum values

    :param data: pandas dataframe
    """
    data = data.T
    colmins = []
    for col in data:
        colmins.append(data[col].idxmin())
    return colmins


def make_list(thing_that_should_be_a_list):
    """If it is not a list.  Make it one. Return a list."""
    if thing_that_should_be_a_list is None:
        thing_that_should_be_a_list = []
    if not isinstance(thing_that_should_be_a_list, list):
        thing_that_should_be_a_list = [thing_that_should_be_a_list]
    return thing_that_should_be_a_list


def flipDict(d):
    """Flips dict p_d: keys become values, values become keys. p_d is left
       untouched: a new, flipped, dict is returned."""
    res = {}
    for k, v in d.items():
        res[v] = k
    return res


def logical_not(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns the result of logical NOT (!) function

    Example:
      logical_not([-2., 0., 1.]) = [0., 1., 0.]

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

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

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


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

        :param DeviceApprovalsChangeOverageActionDetails val:
        :rtype: EventDetails
        """
    return cls('device_approvals_change_overage_action_details', val)


def is_derivatized(monosaccharide):
    """Tests whether any of the substituents attached to `monosaccharide` were
    added by derivatization.

    Parameters
    ----------
    monosaccharide : Monosaccharide
        The object to test

    Returns
    -------
    bool
    """
    for pos, sub in monosaccharide.substituents():
        if sub._derivatize:
            return True
    return False


def correctangle(angle):
    """
    shift angle in between 0 and 360
    TODO: useful for zone axis recognition ?
    """
    res = angle
    if angle < 0.0:
        res = 180.0 + angle
    return res


def is_kernelspec_model(spec_dict):
    """Returns True if spec_dict is already in proper form.  This will occur when using a gateway."""
    return (isinstance(spec_dict, dict) and 'name' in spec_dict and 'spec' in
        spec_dict and 'resources' in spec_dict)


def add_simple_jar(parser):
    """ Add --simple_jar option to parser. """
    parser.add_argument('-s', '--simple_jar', action='store_true', help=
        'Instead of creating an Uber-JAR for the topology, which contains all of its JVM dependencies, create a simple JAR with just the code for the project.  This is useful when your project is pure Python and has no JVM dependencies.'
        )


def theta_CO3_Cl_PP82(T, P):
    """a-a': carbonate chloride [PP82]."""
    theta = -0.053
    valid = T == 298.15
    return theta, valid


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

        :param ShowcaseFileDownloadType val:
        :rtype: EventType
        """
    return cls('showcase_file_download', val)


@classmethod
def error_payload(cls, message, code, id_):
    """JSON v2 error payload.  result is not present."""
    return {'jsonrpc': '2.0', 'id': id_, 'error': {'message': message,
        'code': code}}


def color_mode(mode, max_1=255, max_2=None, max_3=None, max_alpha=255):
    """Set the color mode of the renderer.

    :param mode: One of {'RGB', 'HSB'} corresponding to Red/Green/Blue
        or Hue/Saturation/Brightness
    :type mode: str

    :param max_1: Maximum value for the first color channel (default:
        255)
    :type max_1: int

    :param max_2: Maximum value for the second color channel (default:
        max_1)
    :type max_2: int

    :param max_3: Maximum value for the third color channel (default:
        max_1)
    :type max_3: int

    :param max_alpha: Maximum valu for the alpha channel (default:
        255)
    :type max_alpha: int

    """
    global color_parse_mode
    global color_range
    if max_2 is None:
        max_2 = max_1
    if max_3 is None:
        max_3 = max_1
    color_range = max_1, max_2, max_3, max_alpha
    color_parse_mode = mode


def CurrentAmplifierTwoPort(G, Zi, Zo, Z0=50.0):
    """CurrentAmplifierTwoPort
    Two port current amplifier
    @param G float current gain
    @param Zi float or complex input impedance
    @param Zo float or complex output impedance
    @param Z0 (optional) float reference impedance (defaults to 50 ohms)
    @return list of list s-parameter matrix for a current amplifier
    The two port current amplifier is the same as the three port current amplifier with
    port 3 grounded.

    The current sense element senses the current entering port 1
    with a series resistance in the current sense path of Zi.

    The current generated by the amplifier exits port 2 and is
    shunted with Zo.
    """
    return [[(Zi - Z0) / (Zi + Z0), 0.0], [2.0 * G * Zo * Z0 / ((Zi + Z0) *
        (Zo + Z0)), (Zo - Z0) / (Zo + Z0)]]


def ndim(x):
    """Returns the number of axes in a tensor, as an integer.

    # Arguments
        x: Tensor or variable.

    # Returns
        Integer (scalar), number of axes.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> inputs = K.placeholder(shape=(2, 4, 5))
        >>> val = np.array([[1, 2], [3, 4]])
        >>> kvar = K.variable(value=val)
        >>> K.ndim(inputs)
        3
        >>> K.ndim(kvar)
        2
    ```
    """
    shape = x.shape
    if shape is not None:
        return len(shape)
    return None


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 _on_message_callback(c, userdata, message):
    """Internal callback"""
    userdata['callback'](c, userdata['userdata'], message)


def check_cas_number(cas_no):
    """
	Checks the CAS number to ensure the check digit is valid
	with respect to the rest of the number.

	If the CAS number is valid 0 is returned. If there is a problem the difference
	between the computed check digit and that given as part of the CAS number
	is returned.

	:param cas_no:
	:type cas_no: int
	:return:
	:rtype: int
	"""
    cas_no = abs(int(cas_no))
    check_digit = cas_no % 10
    main_value = (cas_no - check_digit) // 10
    block_2 = main_value % 100
    block_1 = (main_value - block_2) // 100
    last_digit = block_2 % 10
    check_total = last_digit + (block_2 - last_digit) // 10 * 2
    for position, digit in enumerate(str(block_1)[::-1]):
        check_total += int(digit) * (position + 3)
    if check_digit == check_total % 10:
        return 0
    else:
        return check_total % 10 - check_digit


@classmethod
def embedding(cls, inputs, name='embedding', **kwargs):
    """ Create embedding from inputs tensor.

        Parameters
        ----------
        inputs : tf.Tensor
            Input tensor.

        name : str
            Scope name.

        base : callable
            Tensor processing function. Default is :func:`~.layers.conv_block`.

        kwargs : dict
            Parameters for `base` block.

        Returns
        -------
        tf.Tensor
        """
    base_block = kwargs.get('base', cls.block)
    return base_block(inputs, name=name, **kwargs)


@classmethod
def from_dict(cls, config, defaults=None):
    """
        Creates a configuration using a dictionary.
        The dictionary should hold the appropriate _private and _namespace values.
        The _private value specifies which configurations should not be passed on
        to configuration that use this configuration as a base.
        The _namespace value specifies which prefix should be used to search default configurations,
        when a key can not be found in the configuration.

        :param config: (dict) the configuration keys and values to create a configuration with
        :param defaults: (dict) the configuration keys and values that act as a fallback
            or None to load defaults from settings at runtime
        :return: a configuration instance
        """
    assert isinstance(config, dict
        ), 'Config should be a dict which values are the configurations.'
    assert '_namespace' in config, '_namespace needs to be specified in the configuration.'
    assert '_private' in config, '_private needs to be specified in the configuration.'
    assert isinstance(defaults, dict
        ) or defaults is None, 'Defaults should be a dict which values are the configuration defaults.'
    instance = cls(defaults=defaults, namespace=config['_namespace'],
        private=config['_private'])
    instance.update(config)
    return instance


def set_terminal_size(size):
    """
    Can't get this to work....
    """
    rows, cols = size
    return


def singlyfy_parameters(parameters):
    """
    Makes a cgi-parsed parameter dictionary into a dict where the values that
    are just a list of a single value, are converted to just that single value.
    """
    for key, value in parameters.items():
        if isinstance(value, (list, tuple)) and len(value) == 1:
            parameters[key] = value[0]
    return parameters


def other():
    """
    Note to contributors:
        Other signal-to-noise masks must be named with the author or method
        name. If already published, the full citation must be provided. Please,
        add "unpub." otherwise. E.g: Smith et al. (unpub.)

        Please, check /DESIGN.md to adhere to our coding style.
    """


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


def isSameDay(first, second):
    """detects if two dates are the same day. bool."""
    return (first.day == second.day and first.month == second.month and
        first.year == second.year)


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 x_for_tau(tau, beta):
    """Rescales xaxis to tau in 0 ... beta"""
    if tau.min() < 0 or tau.max() > beta:
        raise ValueError('domain of tau')
    return 2 / beta * (tau - beta / 2)


def retrieve_tape_archive(TapeARN=None, GatewayARN=None):
    """
    Retrieves an archived virtual tape from the virtual tape shelf (VTS) to a tape gateway. Virtual tapes archived in the VTS are not associated with any gateway. However after a tape is retrieved, it is associated with a gateway, even though it is also listed in the VTS, that is, archive. This operation is only supported in the tape gateway architecture.
    Once a tape is successfully retrieved to a gateway, it cannot be retrieved again to another gateway. You must archive the tape again before you can retrieve it to another gateway. This operation is only supported in the tape gateway architecture.
    See also: AWS API Documentation

    Examples
    Retrieves an archived virtual tape from the virtual tape shelf (VTS) to a gateway-VTL. Virtual tapes archived in the VTS are not associated with any gateway.
    Expected Output:

    :example: response = client.retrieve_tape_archive(
        TapeARN='string',
        GatewayARN='string'
    )

    :type TapeARN: string
    :param TapeARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the virtual tape you want to retrieve from the virtual tape shelf (VTS).

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway you want to retrieve the virtual tape to. Use the ListGateways operation to return a list of gateways for your account and region.
            You retrieve archived virtual tapes to only one gateway and the gateway must be a tape gateway.

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

    """
    pass


def date(value, format_string):
    """Convert date into python format
    """
    return value.strftime(format_string)


@staticmethod
def var_set(session, **kwargs):
    """
        Sets the given variables or prints the current ones. "set answer=42"
        """
    if not kwargs:
        for name, value in session.variables.items():
            session.write_line('{0}={1}'.format(name, value))
    else:
        for name, value in kwargs.items():
            name = name.strip()
            session.set(name, value)
            session.write_line('{0}={1}', name, value)


@staticmethod
def bool_to_string(value):
    """Hilfsmethode zur Speicherung von boolschen Datentypen. In Konfigurationsdateien
        sind die Werte True und False in true und false zu konvertieren."""
    if value:
        string = 'true'
    else:
        string = 'false'
    return string


def vertex_group_normalize_all(lock_active: bool=True):
    """Normalize all weights of all vertex groups, so that for each vertex, the sum of all weights is 1.0

    :param lock_active: Lock Active, Keep the values of the active group while normalizing others
    :type lock_active: bool
    """
    pass


def expand_dotdict(dotdict):
    """
    Expand a dictionary containing keys in dot notation.

    For example::

    .. code-block:: python3

        dotdict = {
            'key1.key2.key3': 'string1',
            'key1.key2.key4': 1000,
            'key4.key5': 'string2',
        }

        expanded = expand_dotdict(dotdict)

    Will produce:

    .. code-block:: python3

        {
            'key1': {
                'key2': {
                    'key3': 'string1',
                    'key4': 1000,
                },
            },
            'key4': {
                'key5': 'string2',
            },
        }

    :param dict dotdict: Original dictionary containing string keys in dot
     notation.

    :return: The expanded dictionary.
    :rtype: dict
    """
    dtype = type(dotdict)
    result = dtype()
    for key, value in dotdict.items():
        path = key.split('.')
        assert path, 'Invalid dot-notation path'
        node = result
        for part in path[:-1]:
            node = node.setdefault(part, dtype())
            assert isinstance(node, dtype), 'Incompatible paths to {}'.format(
                key)
        node[path[-1]] = value
    return result


def check_shape(a, b):
    """Check if the shapes of given values match.

    Args:
        a (array_like, tuple): An object with shape attribute or a tuple representing shape.
        b (array_like, tuple): An object with shape attribute or a tuple representing shape.

    Raises:
        Exception: When shapes don't match.
    """
    if hasattr(a, 'shape'):
        a = a.shape
    if hasattr(b, 'shape'):
        b = b.shape
    assert a == b, f"Shapes {a} and {b} don't match"


def get_buttons_from_dialog(dialog, channel):
    """ Gets buttons from the `Followers` or `Following` dialog boxes"""
    if channel == 'Follow':
        buttons = dialog.find_elements_by_xpath("//button[text()='Follow']")
    elif channel == 'Unfollow':
        buttons = dialog.find_elements_by_xpath(
            "//button[text() = 'Following']")
    return buttons


def main():
    """This main is a place holder

    """
    pass


def p_varargslist_10(p):
    """varargslist : fpdef varargslist_star COMMA"""
    p[2].args.insert(0, p[1])
    p[0] = p[2]


def intersection(fake_title, unit):
    """对两个list求交集，并返回相同元素的个数

    Keyword arguments:
    fake_title, unit            -- 列表类型
    Return:
        相同元素的个数
    """
    same = 0
    for i in fake_title:
        if i in unit:
            same += 1
    return same


@staticmethod
def enable_logging(path):
    """Enables logging of SSH events to a file.

        :param str path: Path to the file the log is written to.

        :returns: `True`, if logging was successfully enabled. False otherwise.
        """
    raise NotImplementedError


def total_ordering(cls):
    """Class decorator that fills in missing ordering methods"""
    convert = {'__lt__': [('__gt__', lambda self, other: not (self < other or
        self == other)), ('__le__', lambda self, other: self < other or
        self == other), ('__ge__', lambda self, other: not self < other)],
        '__le__': [('__ge__', lambda self, other: not self <= other or self ==
        other), ('__lt__', lambda self, other: self <= other and not self ==
        other), ('__gt__', lambda self, other: not self <= other)],
        '__gt__': [('__lt__', lambda self, other: not (self > other or self ==
        other)), ('__ge__', lambda self, other: self > other or self ==
        other), ('__le__', lambda self, other: not self > other)], '__ge__':
        [('__le__', lambda self, other: not self >= other or self == other),
        ('__gt__', lambda self, other: self >= other and not self == other),
        ('__lt__', lambda self, other: not self >= other)]}
    roots = set(dir(cls)) & set(convert)
    if not roots:
        raise ValueError(
            'must define at least one ordering operation: < > <= >=')
    root = max(roots)
    for opname, opfunc in convert[root]:
        if opname not in roots:
            opfunc.__name__ = opname
            try:
                op = getattr(int, opname)
            except AttributeError:
                pass
            else:
                opfunc.__doc__ = op.__doc__
            setattr(cls, opname, opfunc)
    return cls


def thumbnails(html):
    """
    Given a HTML string, converts paths in img tags to thumbnail
    paths, using Mezzanine's ``thumbnail`` template tag. Used as
    one of the default values in the ``RICHTEXT_FILTERS`` setting.
    """
    from django.conf import settings
    from bs4 import BeautifulSoup
    from mezzanine.core.templatetags.mezzanine_tags import thumbnail
    if settings.MEDIA_URL.lower() not in html.lower():
        return html
    dom = BeautifulSoup(html, 'html.parser')
    for img in dom.findAll('img'):
        src = img.get('src', '')
        src_in_media = src.lower().startswith(settings.MEDIA_URL.lower())
        width = img.get('width')
        height = img.get('height')
        if src_in_media and width and height:
            img['src'] = settings.MEDIA_URL + thumbnail(src, width, height)
    return str(dom)


def _get_uncertainty(errors):
    """ Strip uncertainty info for an extractor """
    return {'uncertainty': errors.uncertainty, 'lower_uncertainty': errors.
        lower_uncertainty, 'upper_uncertainty': errors.upper_uncertainty,
        'confidence_level': errors.confidence_level}


def job_prepare(job_backend):
    """
    Setups all necessary folder structure so the network can run with datasets code and model_provider.py.
    :type job_model: JobModel
    """
    pass


def encode_html(text, quotes=True):
    """Return text that's safe for an HTML attribute."""
    a = ('&', '&'), ('<', '<'), ('>', '>')
    if quotes:
        a = a + (("'", '''), ('"', '"'))
    for k, v in a:
        text = text.replace(k, v)
    return text


def get_comment(path):
    """Return the string minus the comment symbol."""
    return path.lstrip().lstrip('#').strip()


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 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 Integer(value, default=None):
    """Get integer value from the provided value.
    If None, default is returned
    """
    if value is None:
        return default
    value = value.lower()
    if value.startswith('0x'):
        return int(value[2:], 16)
    elif value.startswith('0b'):
        value = value.replace('x', '0')[2:]
        return int(value, 2)
    elif value.startswith('#'):
        value = value.replace('x', '0')[1:]
        return int(value, 2)
    else:
        return int(value)


def set_prefs(prefs):
    """This function is called before opening the project"""
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg',
        '.svn', '_svn', '.git', '.tox', '.env', 'node_modules',
        'bower_components']
    prefs['save_objectdb'] = True
    prefs['compress_objectdb'] = False
    prefs['automatic_soa'] = True
    prefs['soa_followed_calls'] = 0
    prefs['perform_doa'] = True
    prefs['validate_objectdb'] = True
    prefs['max_history_items'] = 32
    prefs['save_history'] = True
    prefs['compress_history'] = False
    prefs['indent_size'] = 4
    prefs['extension_modules'] = []
    prefs['import_dynload_stdmods'] = True
    prefs['ignore_syntax_errors'] = False
    prefs['ignore_bad_imports'] = False
    prefs['split_imports'] = False
    prefs['sort_imports_alphabetically'] = False


def readinto_direct(f, out):
    """
    read from `f` into numpy array `out`, returning a view
    for the read data
    """
    ret = f.readinto(out)
    if ret is None:
        raise IOError('could not readinto()')
    return out[:ret]


def xyz2zxy(vol):
    """
    Swaps axes to ELEKTRONN convention ([X, Y, Z] -> [Z, X, Y]). If additional
    channel axis is provided: [X, Y, Z, CH] -> [Z, X, Y, CH]

    Parameters
    ----------
    vol : np.array [X, Y, Z]

    Returns
    -------
    np.array [Z, X, Y]
    """
    assert vol.ndim >= 3
    vol = vol.swapaxes(1, 0)
    vol = vol.swapaxes(0, 2)
    return vol


def __new__(cls, s, *args):
    """
        Create a new instance.

        :param fmt: A format string explaining the reason for denial.
        :param args: Arguments are stored and used with the format string
                      to generate the ``msg``.

        """
    inst = int.__new__(cls, cls.boolval)
    inst.s = s
    inst.args = args
    return inst


def get_canvas_height() ->int:
    """Returns the canvas height.

    :return:  The canvas height.
    """
    pass


def validate_process_subtype(supertype_name, supertype, subtype_name, subtype):
    """Perform process subtype validation.

    :param supertype_name: Supertype name
    :param supertype: Supertype schema
    :param subtype_name: Subtype name
    :param subtype: Subtype schema
    :return: A list of validation error strings
    """
    errors = []
    for item in supertype:
        for subitem in subtype:
            if item['name'] != subitem['name']:
                continue
            for key in (set(item.keys()) | set(subitem.keys())):
                if key in ('label', 'description'):
                    continue
                elif key == 'required':
                    item_required = item.get('required', True)
                    subitem_required = subitem.get('required', False)
                    if item_required and not subitem_required:
                        errors.append(
                            "Field '{}' is marked as required in '{}' and optional in '{}'."
                            .format(item['name'], supertype_name, subtype_name)
                            )
                elif item.get(key, None) != subitem.get(key, None):
                    errors.append(
                        "Schema for field '{}' in type '{}' does not match supertype '{}'."
                        .format(item['name'], subtype_name, supertype_name))
            break
        else:
            errors.append(
                "Schema for type '{}' is missing supertype '{}' field '{}'."
                .format(subtype_name, supertype_name, item['name']))
    return errors


def ensure_sphinx_astropy_installed():
    """
    Make sure that sphinx-astropy is available.

    This returns the available version of sphinx-astropy as well as any
    paths that should be added to sys.path for sphinx-astropy to be available.
    """
    sys_path_inserts = []
    sphinx_astropy_version = None
    try:
        from sphinx_astropy import __version__ as sphinx_astropy_version
    except ImportError:
        raise ImportError(
            'sphinx-astropy needs to be installed to buildthe documentation.')
    return sphinx_astropy_version, sys_path_inserts


@staticmethod
def rho(rhos, x):
    """
		The NFW density as a function of :math:`x = r/r_{\\rm s}`.

		This routine can be called without instantiating an NFWProfile object. In most cases, the
		:func:`~halo.profile_base.HaloDensityProfile.density` function should be used instead.

		Parameters
		-------------------------------------------------------------------------------------------
		rhos: float
			The central density in physical :math:`M_{\\odot} h^2 / {\\rm kpc}^3`.
		x: array_like
			The radius in units of the scale radius, :math:`x=r/r_{\\rm s}`; can be a number or a
			numpy array.

		Returns
		-------------------------------------------------------------------------------------------
		rho: array_like
			Density in physical :math:`M_{\\odot} h^2 / {\\rm kpc}^3`; has the same dimensions
			as ``x``.

		See also
		-------------------------------------------------------------------------------------------
		halo.profile_base.HaloDensityProfile.density: Density as a function of radius.
		"""
    return rhos / x / (1.0 + x) ** 2


def to_brackets(field_name, format_spec):
    """Return PEP 3101 format string with field name and format specification.
    """
    if format_spec:
        format_spec = ':' + format_spec
        return '{' + field_name + format_spec + '}'
    return '{' + field_name + '}'


def describe_event_details(eventArns=None, locale=None):
    """
    Returns detailed information about one or more specified events. Information includes standard event data (region, service, etc., as returned by  DescribeEvents ), a detailed event description, and possible additional metadata that depends upon the nature of the event. Affected entities are not included; to retrieve those, use the  DescribeAffectedEntities operation.
    If a specified event cannot be retrieved, an error message is returned for that event.
    See also: AWS API Documentation

    :example: response = client.describe_event_details(
        eventArns=[
            'string',
        ],
        locale='string'
    )

    :type eventArns: list
    :param eventArns: [REQUIRED]
            A list of event ARNs (unique identifiers). For example: 'arn:aws:health:us-east-1::event/AWS_EC2_MAINTENANCE_5331', 'arn:aws:health:us-west-1::event/AWS_EBS_LOST_VOLUME_xyz'
            (string) --

    :type locale: string
    :param locale: The locale (language) to return information in. English (en) is the default and the only supported value at this time.

    :rtype: dict
    :return: {
        'successfulSet': [
            {
                'event': {
                    'arn': 'string',
                    'service': 'string',
                    'eventTypeCode': 'string',
                    'eventTypeCategory': 'issue'|'accountNotification'|'scheduledChange',
                    'region': 'string',
                    'availabilityZone': 'string',
                    'startTime': datetime(2015, 1, 1),
                    'endTime': datetime(2015, 1, 1),
                    'lastUpdatedTime': datetime(2015, 1, 1),
                    'statusCode': 'open'|'closed'|'upcoming'
                },
                'eventDescription': {
                    'latestDescription': 'string'
                },
                'eventMetadata': {
                    'string': 'string'
                }
            },
        ],
        'failedSet': [
            {
                'eventArn': 'string',
                'errorName': 'string',
                'errorMessage': 'string'
            },
        ]
    }

    :returns:
    (string) --
    (string) --

    """
    pass


def get_slot_type_versions(name=None, nextToken=None, maxResults=None):
    """
    Gets information about all versions of a slot type.
    The GetSlotTypeVersions operation returns a SlotTypeMetadata object for each version of a slot type. For example, if a slot type has three numbered versions, the GetSlotTypeVersions operation returns four SlotTypeMetadata objects in the response, one for each numbered version and one for the $LATEST version.
    The GetSlotTypeVersions operation always returns at least one version, the $LATEST version.
    This operation requires permissions for the lex:GetSlotTypeVersions action.
    See also: AWS API Documentation

    :example: response = client.get_slot_type_versions(
        name='string',
        nextToken='string',
        maxResults=123
    )

    :type name: string
    :param name: [REQUIRED]
            The name of the slot type for which versions should be returned.

    :type nextToken: string
    :param nextToken: A pagination token for fetching the next page of slot type versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of versions, specify the pagination token in the next request.

    :type maxResults: integer
    :param maxResults: The maximum number of slot type versions to return in the response. The default is 10.

    :rtype: dict
    :return: {
        'slotTypes': [
            {
                'name': 'string',
                'description': 'string',
                'lastUpdatedDate': datetime(2015, 1, 1),
                'createdDate': datetime(2015, 1, 1),
                'version': 'string'
            },
        ],
        'nextToken': 'string'
    }

    """
    pass


def get_bbq_patterns(pattern):
    """
    Return union and exception patterns
    """
    tokens = pattern.split(' ')
    bbq_patterns = []
    last_token = '+'
    in_range = True
    for idx, token in enumerate(tokens):
        if token == '+' or token == '-':
            last_token = token
            in_range = False
        else:
            if not in_range or idx == 0:
                bbq_patterns.append(last_token + token)
            else:
                bbq_patterns[-1] = bbq_patterns[-1] + ' ' + token
            in_range = True
    return bbq_patterns


def config_to_settings(args):
    """Merge configuration file settings with any command-line provided settings."""
    if 'config' in args:
        if args['config'] != None:
            if 'settings' in args and args['settings'] != None:
                args['settings'].update(args['config']['serviceSettings'])
            else:
                args['settings'] = args['config']['serviceSettings']
        args.pop('config', None)
    return args


def convert(num):
    """
    This function convert number
    :param num: input numger
    :type num:int
    :return: output string
    """
    for x in ['wh', 'Kwh', 'Mwh', 'Gwh']:
        if num < 1000:
            return '%3.1f %s' % (num, x)
        num /= 1000


def _get_manifest_coords(manifest: dict) ->tuple:
    """Create a tuple with the manifest (kind, namespace, name)"""
    kind = manifest.get('kind')
    namespace = manifest.get('metadata').get('namespace')
    name = manifest.get('metadata').get('name')
    return kind, namespace, name


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 view_all(fit_view: bool=False):
    """View whole image with markers

    :param fit_view: Fit View, Fit frame to the viewport
    :type fit_view: bool
    """
    pass


def deltafmt(delta, decimals=None):
    """
Returns a human readable representation of a time with the format:

    [[[Ih]Jm]K[.L]s

For example: 6h5m23s

If "decimals" is specified, the seconds will be output with that many decimal places.
If not, there will be two places for times less than 1 minute, one place for times
less than 10 minutes, and zero places otherwise
"""
    try:
        delta = float(delta)
    except:
        return '(bad delta: %s)' % (str(delta),)
    if delta < 60:
        if decimals is None:
            decimals = 2
        return ('{0:.' + str(decimals) + 'f}s').format(delta)
    mins = int(delta / 60)
    secs = delta - mins * 60
    if delta < 600:
        if decimals is None:
            decimals = 1
        return ('{0:d}m{1:.' + str(decimals) + 'f}s').format(mins, secs)
    if decimals is None:
        decimals = 0
    hours = int(mins / 60)
    mins -= hours * 60
    if delta < 3600:
        return '{0:d}m{1:.0f}s'.format(mins, secs)
    else:
        return ('{0:d}h{1:d}m{2:.' + str(decimals) + 'f}s').format(hours,
            mins, secs)


def from_bool_to_int(boolean):
    """Convert a bool to a int representation

    :param boolean: bool to convert
    :type boolean: bool
    :return: if boolean 1 ,else 0
    :rtype: int
    """
    if boolean:
        return 1
    return 0


def rgb2hex(r, g, b):
    """
    Convert rgb color to hex format.

    >>> rgb2hex(129, 154, 70)
    '#819a46'
    >>> rgb2hex(-10, 256, -1)
    Traceback (most recent call last):
    ...
    AssertionError: (r, g, b) value must within range 0 ~ 255.
    """
    assert (0, 0, 0) <= (r, g, b) <= (255, 255, 255
        ), '(r, g, b) value must within range 0 ~ 255.'
    hex = '#{:02x}{:02x}{:02x}'.format(r, g, b)
    return hex


def color(requestContext, seriesList, theColor):
    """
    Assigns the given color to the seriesList

    Example::

        &target=color(collectd.hostname.cpu.0.user, 'green')
        &target=color(collectd.hostname.cpu.0.system, 'ff0000')
        &target=color(collectd.hostname.cpu.0.idle, 'gray')
        &target=color(collectd.hostname.cpu.0.idle, '6464ffaa')

    """
    for series in seriesList:
        series.color = theColor
    return seriesList


def rewrite_elife_funding_awards(json_content, doi):
    """ rewrite elife funding awards """
    if doi == '10.7554/eLife.00801':
        for i, award in enumerate(json_content):
            if 'id' in award and award['id'] == 'par-2':
                del json_content[i]
    if doi == '10.7554/eLife.04250':
        recipients_for_04250 = [{'type': 'person', 'name': {'preferred':
            'Eric Jonas', 'index': 'Jonas, Eric'}}]
        for i, award in enumerate(json_content):
            if 'id' in award and award['id'] in ['par-2', 'par-3', 'par-4']:
                if 'recipients' not in award:
                    json_content[i]['recipients'] = recipients_for_04250
    if doi == '10.7554/eLife.06412':
        recipients_for_06412 = [{'type': 'person', 'name': {'preferred':
            'Adam J Granger', 'index': 'Granger, Adam J'}}]
        for i, award in enumerate(json_content):
            if 'id' in award and award['id'] == 'par-1':
                if 'recipients' not in award:
                    json_content[i]['recipients'] = recipients_for_06412
    return json_content


def multi_set_data_frame(data, arrays, set_value):
    """
    Change multiple values on a pandas data frame in one line.
    :param data: pandas DataFrame. Note: must be of the same type as set_value.
            e.g.: DataFrame of "float" type and set_value=2.1.
    :param arrays: arrays of (row, col) directing to the cell to change the value.
    :param set_value: value to change to.
    """
    for i in arrays:
        data.at[i[0], i[1]] = set_value


def get_html_schema(_, __):
    """We don't need to keep a schema of html files - these are outputs anyway"""
    return None


def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text('Hola! This is Incubot for the CLAN lab.')
    update.message.reply_text(
        'Before changing volumes make sure your ID is registered.')
    update.message.reply_text('Send /help for help. Enjoy!')


def inside(head):
    """Return True if head inside screen."""
    return -200 < head.x < 200 and -200 < head.y < 200


def get_record_type(rawdata=None, **kwargs):
    """Returns the type of upcoming wmf record."""
    try:
        return rawdata.peek(6)[4:]
    except Exception:
        return


def output_F(results, contrast):
    """
    This convenience function outputs the results of an Fcontrast
    from a regression

    Parameters
    ----------
    results : object
        implementing Tcontrast method
    contrast : array
        contrast matrix

    Returns
    -------
    F : array
        array of F values
    """
    return results.Fcontrast(contrast).F


def stem(word):
    """The main entry point in the old version of the API."""
    raise DeprecationWarning('stem() is deprecated starting with v1.0.0')


def getTransition(source, transition_id):
    """Get transition with transition_id given source state.

        If the transition is invalid from this source state,
        an InvalidTransitionError is raised.
        """


@classmethod
def _create(cls, model_class, *args, **kwargs):
    """Create an instance of the model, and save it to the database."""
    if cls._meta.django_get_or_create:
        return cls._get_or_create(model_class, *args, **kwargs)
    manager = cls._get_manager(model_class)
    return manager.create(*args, **kwargs)


def gpib_send_ifc(library, session):
    """Pulse the interface clear line (IFC) for at least 100 microseconds.

    Corresponds to viGpibSendIFC function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viGpibSendIFC(session)


@classmethod
def create(cls, service, uri, new_graph):
    """I implement :meth:`ILocalCore.create`.

        I store `new_graph` in the obsel collection of the obsel's trace.
        """
    trace = cls._get_trace_from_uri(service, uri)
    trace.obsel_collection.add_obsel_graph(new_graph, True)


def add_prefix(prefix: str, tag: str) ->str:
    """
    Simple function to account for optional BIDS tags in the bids file names, i.e. it prefixes 'prefix' only when tag is not empty

    :param prefix:  The prefix (e.g. '_sub-')
    :param tag:     The tag (e.g. 'control01')
    :return:        The tag with the leading prefix (e.g. '_sub-control01') or just the empty tag ''
    """
    if tag:
        tag = prefix + str(tag)
    else:
        tag = ''
    return tag


def cancel():
    """Cancel loading of selected file

    """
    pass


def reset():
    """reset previously accessed `lazybase` attributes"""


def create_ib_tuple(instrument):
    """ create ib contract tuple """
    from qtpylib import futures
    if isinstance(instrument, str):
        instrument = instrument.upper()
        if 'FUT.' not in instrument:
            instrument = instrument, 'STK', 'SMART', 'USD', '', 0.0, ''
        else:
            try:
                symdata = instrument.split('.')
                if symdata[1] not in futures.futures_contracts.keys():
                    raise ValueError(
                        'Un-supported symbol. Please use full contract tuple.')
                spec = futures.get_ib_futures(symdata[1])
                if not isinstance(spec, dict):
                    raise ValueError('Un-parsable contract tuple')
                if len(symdata) == 3 and symdata[2] != '':
                    expiry = symdata[2]
                else:
                    expiry = futures.get_active_contract(symdata[1])
                instrument = spec['symbol'].upper(), 'FUT', spec['exchange'
                    ].upper(), spec['currency'].upper(), int(expiry), 0.0, ''
            except Exception as e:
                raise ValueError('Un-parsable contract tuple')
    elif len(instrument) <= 7:
        instrument_list = list(instrument)
        if len(instrument_list) < 3:
            instrument_list.append('SMART')
        if len(instrument_list) < 4:
            instrument_list.append('USD')
        if len(instrument_list) < 5:
            instrument_list.append('')
        if len(instrument_list) < 6:
            instrument_list.append(0.0)
        if len(instrument_list) < 7:
            instrument_list.append('')
        try:
            instrument_list[4] = int(instrument_list[4])
        except Exception as e:
            pass
        instrument_list[5] = 0.0 if isinstance(instrument_list[5], str
            ) else float(instrument_list[5])
        instrument = tuple(instrument_list)
    return instrument


def table_has_row(connection, table, rowname):
    """Check whether actual table has row."""
    with connection.cursor() as cursor:
        table_description = connection.introspection.get_table_description(
            cursor, table)
        for row in table_description:
            if row.name == rowname:
                return True
    return False


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 transformed_potential_energy(potential_energy, inv_transform, z):
    """
    Given a potential energy `p(x)`, compute potential energy of `p(z)`
    with `z = transform(x)` (i.e. `x = inv_transform(z)`).

    :param potential_energy: a callable to compute potential energy of original
        variable `x`.
    :param ~numpyro.distributions.constraints.Transform inv_transform: a
        transform from the new variable `z` to `x`.
    :param z: new variable to compute potential energy
    :return: potential energy of `z`.
    """
    x, intermediates = inv_transform.call_with_intermediates(z)
    logdet = inv_transform.log_abs_det_jacobian(z, x, intermediates=
        intermediates)
    return potential_energy(x) - logdet


def c_array(ctype, values):
    """Create ctypes array from a python array

    Parameters
    ----------
    ctype : ctypes data type
        data type of the array we want to convert to

    values : tuple or list
        data content

    Returns
    -------
    out : ctypes array
        Created ctypes array
    """
    return (ctype * len(values))(*values)


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

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


def GetTime():
    """
    returns timestamp of most recent block

    """
    pass


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


@classmethod
def build_route_name(cls, method_name):
    """Creates a unique route name based on the combination of the class
        name with the method name.

        :param method_name: the method name to use when building a route name
        """
    return cls.__name__ + ':%s' % method_name


def equalize_axes(left, right):
    """Takes two dataframes, combines their columns and indexes
    and sets combined index and columns for each
    Args:
        left: (pd.DataFrame)
        right: (pd.DataFrame)
    """
    new_cols = left.columns.union(right.columns)
    new_idx = left.index.union(right.index)
    return left.loc[new_idx, new_cols], right.loc[new_idx, new_cols]


def can_generate_custom_crop_from_original(width, height, crop):
    """Checks whether custom crop can be generated or not

    :param int width: width of original
    :param int height: height of original
    :param dict crop: custom crop data
    :return bool: True if custom crop is within original image dimensions
    """
    if not crop:
        crop = {}
    if crop.get('ratio'):
        return True
    try:
        crop_width = int(crop['width'])
    except (KeyError, TypeError, ValueError):
        crop_width = None
    try:
        crop_height = int(crop['height'])
    except (KeyError, TypeError, ValueError):
        crop_height = None
    if crop_width is None and crop_height is None:
        return False
    if (crop_width is not None and crop_height is None or crop_width is
        None and crop_height is not None):
        return True
    return width >= crop_width and height >= crop_height


def exception_string(exception):
    """Return the string value of an exception, valid for both python 2 and
    python 3.
    """
    return exception.args[0].decode('utf-8')


@classmethod
def new(cls, client, *a, type='mixing', **kw):
    """
        Create a new bridge with this state machine.

        Always use as `async with …`.

        Arguments other than "client" and "type" are passed to the constructor.
        """
    s = object.__new__(cls)
    s.client = client
    s._bridge_args = dict(type=type, bridgeId=client.generate_id('B'))
    s._bridge_kw = kw
    return s


def onStart():
    """
        Called after forking the process.
        """


def do_OP_2DROP(stack):
    """
    >>> s = [1, 2, 3]
    >>> do_OP_2DROP(s)
    >>> print(s)
    [1]
    """
    stack.pop()
    stack.pop()


def import_rest_api(failOnWarnings=None, parameters=None, body=None):
    """
    A feature of the Amazon API Gateway control service for creating a new API from an external API definition file.
    See also: AWS API Documentation

    :example: response = client.import_rest_api(
        failOnWarnings=True|False,
        parameters={
            'string': 'string'
        },
        body=b'bytes'|file
    )

    :type failOnWarnings: boolean
    :param failOnWarnings: A query parameter to indicate whether to rollback the API creation (true ) or not (false ) when a warning is encountered. The default value is false .

    :type parameters: dict
    :param parameters: Custom header parameters as part of the request.
            (string) --
            (string) --

    :type body: bytes or seekable file-like object
    :param body: [REQUIRED]
            The POST request body containing external API definitions. Currently, only Swagger definition JSON files are supported.

    :rtype: dict
    :return: {
        'id': 'string',
        'name': 'string',
        'description': 'string',
        'createdDate': datetime(2015, 1, 1),
        'version': 'string',
        'warnings': [
            'string',
        ],
        'binaryMediaTypes': [
            'string',
        ]
    }

    :returns:
    (string) --

    """
    pass


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


def validate_0_rtype(instruction) ->bool:
    """Validates R-Type instructions with 0 registers

    Parameters
    ----------
    instruction : R-Type
        R-types with 0 registers

    Returns
    -------
    bool
        [Syntax correct or not]
    """
    rd = instruction.destination_register
    rs = instruction.source_register
    rt = instruction.target_register
    check1 = rd is None
    check2 = rs is None
    check3 = rt is None
    return check1 and check2 and check3


def check_bounds(x, bounds):
    """Input validation for .
    Checks kappa and nu for consistent values and shapes.
    """
    if not isinstance(bounds, dict):
        raise TypeError('bounds should be a dictionary')
    assert x.shape[1] == len(bounds), 'bounds is of inconsistent size.'
    for key_value in bounds.items():
        values = key_value[1]
        if not (isinstance(values, tuple) or isinstance(values, list)):
            raise TypeError('bounds values should be stored in list or tuple')
        assert len(values) == 2, 'bounds is of inconsistent size.'
        inf, sup = values
        if isinstance(inf, str) or isinstance(sup, str):
            raise ValueError('bounds values should be numeric.')
        assert inf < sup, 'inf bound cannot be superior to sup bound.'


@classmethod
def __parse_pretty_field_def(cls, field_def):
    """Parses a single field definition

        Testing badly formatted field names

        >>> class MyObject(PrettyObject):
        ...     __pretty_fields__ = [
        ...         "a:<asdf",
        ...     ]
        ...     def __init__(self, a): self.a = a
        >>> obj = MyObject('test')
        >>> print(obj)
        Traceback (most recent call last):
        ...
        ValueError: Invalid format specifier
        """
    if '!' in field_def:
        field_def = field_def.split('!', 1)
        field_def[1] = '!' + field_def[1]
        return field_def
    if ':' in field_def:
        field_def = field_def.split(':', 1)
        field_def[1] = ':' + field_def[1]
        return field_def
    return field_def, '!r'


def convert_to_undirected(G):
    """Return a new undirected representation of the graph G."""
    return G.to_undirected()


def b(n, alpha, beta, x):
    """The second term of the recurrence relation from Wikipedia, * P_n-1^(a,b)."""
    term1 = 2 * n + alpha + beta - 1
    iterm1 = 2 * n + alpha + beta
    iterm2 = 2 * n + alpha + beta - 2
    iterm3 = alpha ** 2 - beta ** 2
    temp_product = iterm1 * iterm2 * x + iterm3
    return term1 * temp_product


@conf
def scc_common_flags(conf):
    """
	Flags required for executing the sun C compiler
	"""
    v = conf.env
    v.CC_SRC_F = []
    v.CC_TGT_F = ['-c', '-o', '']
    if not v.LINK_CC:
        v.LINK_CC = v.CC
    v.CCLNK_SRC_F = ''
    v.CCLNK_TGT_F = ['-o', '']
    v.CPPPATH_ST = '-I%s'
    v.DEFINES_ST = '-D%s'
    v.LIB_ST = '-l%s'
    v.LIBPATH_ST = '-L%s'
    v.STLIB_ST = '-l%s'
    v.STLIBPATH_ST = '-L%s'
    v.SONAME_ST = '-Wl,-h,%s'
    v.SHLIB_MARKER = '-Bdynamic'
    v.STLIB_MARKER = '-Bstatic'
    v.cprogram_PATTERN = '%s'
    v.CFLAGS_cshlib = ['-xcode=pic32', '-DPIC']
    v.LINKFLAGS_cshlib = ['-G']
    v.cshlib_PATTERN = 'lib%s.so'
    v.LINKFLAGS_cstlib = ['-Bstatic']
    v.cstlib_PATTERN = 'lib%s.a'


def partial_timerange(partial):
    """
    Return begin and endtime of partial
    """
    return partial[0, 0], partial[-1, 0]


@conf
def gxx_modifier_darwin(conf):
    """Configuration flags for executing g++ on MacOS"""
    v = conf.env
    v.CXXFLAGS_cxxshlib = ['-fPIC']
    v.LINKFLAGS_cxxshlib = ['-dynamiclib']
    v.cxxshlib_PATTERN = 'lib%s.dylib'
    v.FRAMEWORKPATH_ST = '-F%s'
    v.FRAMEWORK_ST = ['-framework']
    v.ARCH_ST = ['-arch']
    v.LINKFLAGS_cxxstlib = []
    v.SHLIB_MARKER = []
    v.STLIB_MARKER = []
    v.SONAME_ST = []


def freestyle_module_add():
    """Add a style module into the list of modules

    """
    pass


def virtual_url_path():
    """Return a URL for the object, relative to the site root.

        If a virtual host is configured, the URL is a path relative to
        the virtual host's root object.  Otherwise, it is the physical
        path.  In either case, the URL does not begin with a slash.
        """


def voidage_Benyahia_Oneil_spherical(Dp, Dt):
    """Calculates voidage of a bed of spheres
    packed into a bed or tube of diameter `Dt`, with sphere diameters
    `Dp`. Shown in [1]_, and cited by various authors. Correlations exist
    also for solid cylinders, hollow cylinders, and 4-hole cylinders.
    Based on a series of physical measurements.

    .. math::
        \\epsilon = 0.390+\\frac{1.740}{\\left(\\frac{d_{cyl}}{d_p}+1.140\\right)^2}

    Parameters
    ----------
    Dp : float
        Spherical particle diameter, [m]
    Dt : float
        Diameter of the tube, [m]

    Returns
    -------
    voidage : float
        Void fraction of bed packing []

    Notes
    -----
    Average error 1.5%, 1.5 < ratio < 50.

    Examples
    --------
    >>> voidage_Benyahia_Oneil_spherical(Dp=.001, Dt=.05)
    0.3906653157443224

    References
    ----------
    .. [1] Benyahia, F., and K. E. O’Neill. "Enhanced Voidage Correlations for
       Packed Beds of Various Particle Shapes and Sizes." Particulate Science
       and Technology 23, no. 2 (April 1, 2005): 169-77.
       doi:10.1080/02726350590922242.
    """
    return 0.39 + 1.74 / (Dt / Dp + 1.14) ** 2


def storageObject(uid, entity, url, storage_type):
    """image returns an image object. entity is the parent
    """
    fields = [{'key': 'uid', 'required': True, 'value': uid}, {'key': 'url',
        'required': True, 'value': url}]
    collection = entity.collection.get_name()
    entity = entity.get_name()
    storage_type = storage_type.replace(' ', '-').lower().capitalize()
    model = {'fields': fields, 'exclude_from_indexes': ['url'], 'key': [
        'Collection', collection, 'Entity', entity, storage_type, uid]}
    return model


def _long_opt(name_or_flags):
    """Find the long option name."""
    for opt in name_or_flags:
        if opt.startswith('--'):
            return opt.lstrip('--')
    return None


def xj(xp):
    """
  Split xpath/jpath expr in -> xpath,jpath
  ex:   "//b[@v='.'].-1.size" ---> ( "//b[@v='.']" , '-1.size' )
  """
    ll = xp.split('.')
    if len(ll) > 1:
        ends = []
        while 1:
            if 'size' in ll[-1]:
                ends.append(ll.pop())
            elif ll[-1].lstrip('-+').isdigit():
                ends.append(ll.pop())
            else:
                break
        return '.'.join(ll), '.'.join(reversed(ends))
    else:
        return xp, ''


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def _repl_args(args, key, replacement):
    """Replaces occurrences of key in args with replacement."""
    ret = []
    for arg in args:
        if arg == key:
            ret.extend(replacement)
        else:
            ret.append(arg)
    return ret


def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

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

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


@staticmethod
def _has_trips(data):
    """
        Returns True if the data contains trips
        :param dict data: The response data as provided by self.__request
        :return bool:
        """
    return len(data.get('payload', {}).get('data', {}).get('trips', [])) > 0


@staticmethod
def count_in_out_topic(topic, lst):
    """Count the number of incoming and outgoing links."""
    in_cnt = 0
    out_cnt = 0
    for element in lst:
        if element.get_value('Topic') == topic:
            in_cnt += 1
        else:
            out_cnt += 1
    return in_cnt, out_cnt


def negative(data=None, out=None, name=None, **kwargs):
    """Numerical negative of the argument, element-wise.

    The storage type of ``negative`` output depends upon the input storage type:

       - negative(default) = default
       - negative(row_sparse) = row_sparse
       - negative(csr) = csr

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

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

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


def byte_to_zwave_brightness(value):
    """Convert brightness in 0-255 scale to 0-99 scale.

    `value` -- (int) Brightness byte value from 0-255.
    """
    if value > 0:
        return max(1, round(value / 255 * 99))
    return 0


@classmethod
def get_compo_name(cls):
    """
        Get current component name.
        :return str
        :rtype str
        """
    return cls._compo_name


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


@staticmethod
def provider_network_attribute_updates_supported():
    """Returns the provider network attributes that can be updated

        Possible values: neutron_lib.api.definitions.provider_net.ATTRIBUTES

        :returns: (list) provider network attributes that can be updated in a
                         live network using this driver.
        """
    return []


@classmethod
def merge(cls, edge1, edge2):
    """ Merges multi-color information from two supplied :class:`BGEdge` instances into a new :class:`BGEdge`

        Since :class:`BGEdge` represents an undirected edge, created edge's vertices are assign according to the order in first supplied edge.

        Accounts for subclassing.

        :param edge1: first out of two edge information from which is to be merged into a new one
        :param edge2: second out of two edge information from which is to be merged into a new one
        :return: a new undirected with multi-color information merged from two supplied :class:`BGEdge` objects
        :raises: ``ValueError``
        """
    if edge1.vertex1 != edge2.vertex1 and edge1.vertex1 != edge2.vertex2:
        raise ValueError('Edges to be merged do not connect same vertices')
    forward = edge1.vertex1 == edge2.vertex1
    if forward and edge1.vertex2 != edge2.vertex2:
        raise ValueError('Edges to be merged do not connect same vertices')
    elif not forward and edge1.vertex2 != edge2.vertex1:
        raise ValueError('Edges to be merged do not connect same vertices')
    return cls(vertex1=edge1.vertex1, vertex2=edge1.vertex2, multicolor=
        edge1.multicolor + edge2.multicolor)


@classmethod
def list_indices(cls):
    """List all the indices in the elasticsearch cluster."""
    return cls.config.connection.indices.get('*').keys()


def translate_version_str2int(version_str):
    """Translates a version string in format x[.y[.z[...]]] into a 000000 number.
    Each part of version number can have up to 99 possibilities."""
    import math
    parts = version_str.split('.')
    i, v, l = 0, 0, len(parts)
    if not l:
        return v
    while i < 3:
        try:
            v += int(parts[i]) * int(math.pow(10, (2 - i) * 2))
            l -= 1
            i += 1
        except ValueError:
            return v
        if not l:
            return v
    return v
    try:
        v += 10000 * int(parts[0])
        l -= 1
    except ValueError:
        return v
    if not l:
        return v
    try:
        v += 100 * int(parts[1])
        l -= 1
    except ValueError:
        return v
    if not l:
        return v
    try:
        v += int(parts[0])
        l -= 1
    except ValueError:
        return v
    if not l:
        return v


def part_realpath(part_name: str, source_part_name: str) ->str:
    """ Get an absolute part name from a relative part name (e.g. from a relationship)

    @:param part_name: A relative or absolute part name to be transformed
    @:param source_part_name: Base part (source of the relationship etc.) to use as starting point of part_name if it
        is a relative path
    """
    if part_name[0] == '/':
        return part_name
    path_segments = part_name.split('/')
    result = source_part_name.split('/')[:-1]
    for segment in path_segments:
        if segment in ('.', ''):
            pass
        elif segment == '..':
            result.pop()
        else:
            result.append(segment)
    return '/'.join(result)


def lineincustcols(inlist, colsizes):
    """
Returns a string composed of elements in inlist, with each element
right-aligned in a column of width specified by a sequence colsizes.  The
length of colsizes must be greater than or equal to the number of columns
in inlist.

Usage:   lineincustcols (inlist,colsizes)
Returns: formatted string created from inlist
"""
    outstr = ''
    for i in range(len(inlist)):
        if not isinstance(inlist[i], str):
            item = str(inlist[i])
        else:
            item = inlist[i]
        size = len(item)
        if size <= colsizes[i]:
            for j in range(colsizes[i] - size):
                outstr = outstr + ' '
            outstr = outstr + item
        else:
            outstr = outstr + item[0:colsizes[i] + 1]
    return outstr


@classmethod
def deserialize(cls, raw_bytes):
    """
        Deserializes the given raw bytes into an instance.

        Since this is a subclass of ``Part`` but a top-level one (i.e. no other
        subclass of ``Part`` would have a ``Response`` as a part) this merely
        has to parse the raw bytes and discard the resulting offset.
        """
    instance, _ = cls.parse(raw_bytes, offset=0)
    return instance


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``EditTransformPanel`` is only intended to be added to
        :class:`.OrthoPanel` views.
        """
    from fsleyes.views.orthopanel import OrthoPanel
    return [OrthoPanel]


@staticmethod
def fromQml(path: str):
    """
        Reads a ClassificationScheme from a QML file.
        :param path: str, path to QML file
        :return: ClassificationScheme
        """
    raise NotImplementedError()


def read_radolan_header(fid):
    """Reads radolan ASCII header and returns it as string

    Parameters
    ----------
    fid : object
        file handle

    Returns
    -------
    header : string
    """
    header = ''
    while True:
        mychar = fid.read(1)
        if not mychar:
            raise EOFError(
                'Unexpected EOF detected while reading RADOLAN header')
        if mychar == b'\x03':
            break
        header += str(mychar.decode())
    return header


@staticmethod
def get_decorator_mapping():
    """
        Get label mapping for display in test listing.

        :return: Dict {TestClass: decorator function}
        """
    raise NotImplementedError


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


def merge_m(rec1, rec2):
    """
    Merge M records.

    Parameters
    ----------
    rec1 : sdt.seisan_M
        Seisan M record.
    rec2 : sdt.seisan_M
        Seisan M record.

    Returns
    -------
    rec1 : sdt.seisan_M
        Seisan M record.

    """
    rec1.mrr_mzz = rec2.mrr_mzz
    rec1.mtt_mxx = rec2.mtt_mxx
    rec1.mpp_myy = rec2.mpp_myy
    rec1.mrt_mzx = rec2.mrt_mzx
    rec1.mrp_mzy = rec2.mrp_mzy
    rec1.mtp_mxy = rec2.mtp_mxy
    rec1.reporting_agency2 = rec2.reporting_agency2
    rec1.mt_coordinate_system = rec2.mt_coordinate_system
    rec1.exponential = rec2.exponential
    rec1.scalar_moment = rec2.scalar_moment
    rec1.method_used_2 = rec2.method_used_2
    rec1.quality_2 = rec2.quality_2
    return rec1


@staticmethod
def _create_html_checkbox(input_key, input_value, checked=False):
    """ Return the html of the checkboxes

        Args:
            input_key:
            input_value:
            checked:

        Returns:

        """
    input_tag = '<input type="checkbox" '
    if checked:
        input_tag += 'checked '
    input_tag += 'value="' + input_key + '"/> ' + input_value
    return '<span>' + input_tag + '</span>'


@classmethod
def scoped_function_for_session(cls):
    """ Save the value of the key in the environment """
    return cls.environment.scoped_function_for_session


def get_pinned_version(ireq):
    """Get the pinned version of an InstallRequirement.

    An InstallRequirement is considered pinned if:

    - Is not editable
    - It has exactly one specifier
    - That specifier is "=="
    - The version does not contain a wildcard

    Examples:
        django==1.8   # pinned
        django>1.8    # NOT pinned
        django~=1.8   # NOT pinned
        django==1.*   # NOT pinned

    Raises `TypeError` if the input is not a valid InstallRequirement, or
    `ValueError` if the InstallRequirement is not pinned.
    """
    try:
        specifier = ireq.specifier
    except AttributeError:
        raise TypeError('Expected InstallRequirement, not {}'.format(type(
            ireq).__name__))
    if ireq.editable:
        raise ValueError('InstallRequirement is editable')
    if not specifier:
        raise ValueError('InstallRequirement has no version specification')
    if len(specifier._specs) != 1:
        raise ValueError('InstallRequirement has multiple specifications')
    op, version = next(iter(specifier._specs))._spec
    if op not in ('==', '===') or version.endswith('.*'):
        raise ValueError('InstallRequirement not pinned (is {0!r})'.format(
            op + version))
    return version


def is_truthy(data):
    """
    Returns True if the data is a truthy value, False otherwise.
    """
    string = str(data).lower()
    return string in ['true', '1', 'f']


@classmethod
def get_exchange_name(cls):
    """
        Get exchange name
        :return: Exchange name string
        """
    return 'Gatecoin'


def _pipe_segment_with_colons(align, colwidth):
    """Return a segment of a horizontal line with optional colons which
    indicate column's alignment (as in `pipe` output format)."""
    w = colwidth
    if align in ['right', 'decimal']:
        return '-' * (w - 1) + ':'
    elif align == 'center':
        return ':' + '-' * (w - 2) + ':'
    elif align == 'left':
        return ':' + '-' * (w - 1)
    else:
        return '-' * w


@staticmethod
def _construct_branch_name(package_name: str, new_package_version: str) ->str:
    """Construct branch name for the updated dependency."""
    return f'kebechet-{package_name}-{new_package_version}'


def _trim_data(ref_data, fields):
    """Trim only fields in dict and return errors."""
    data = {}
    for key in fields:
        data[key] = ref_data[key]
    return data


def setPyFlakesFilter(func):
    """
	Set a filter for PyFlake warning messages. This filter should be a function
	that takes a single message, and returns False if the message should be
	ignored (True otherwise.)

	Argument:
	func	--	The filter function.
	"""
    global _filter
    _filter = func


def ctx_exit(obj, path, access):
    """
    Called on context exit. if ``access='w'`` dumps ``obj`` into
    file specified by ``path``.

    :param obj: object to be dumped
    :param path: file path
    :param access: access permission ('r' - read, 'w' - write, 'rw' - edit)
    """
    if 'w' in access:
        obj.dump(path)


def tuplize(dlist, d, name):
    """
    Convert a list into a list of tuples.
    """
    if len(dlist) % d != 0:
        raise ValueError('Cannot tuplize data for set ' + str(name) +
            ' because its length ' + str(len(dlist)) +
            ' is not a multiple of dimen ' + str(d))
    j = 0
    t = []
    rv = []
    for i in dlist:
        t.append(i)
        j += 1
        if j == d:
            rv.append(tuple(t))
            t = []
            j = 0
    return rv


def _remove_capsule_name(capsule_name, fullname):
    """Remove "capsule_name" from capsule_name.some_module.some_module2
    Since the files in the zip file won't have "capsule_name" in the paths
    """
    parts = fullname.split('.')
    return '.'.join(parts[1:])


def comma_separated_arg(string):
    """ Split a comma separated string """
    return string.split(',')


def p_contents(p):
    """contents : header_section type_section sweep_section trace_section value_section end"""
    p[0] = p[1], p[2], p[3], p[4], p[5]


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


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
         {
            "dynamic":true,
                "properties": {
                    "data": {
                        "properties": {
                            "long_desc": {
                                "dynamic": false,
                                "properties": {}
                            },
                            "short_desc": {
                                "dynamic": false,
                                "properties": {
                                    "__text__": {
                                        "type": "text",
                                        "index": true
                                    }
                                }
                            },
                            "activity": {
                                "dynamic": false,
                                "properties": {}
                            }
                        }
                    }
                }
        }
        """
    return {'items': mapping}


def doc_locate(doc, path):
    """Walk a path down a document.

    The path is a list of bytestring segments.
    Starting from the root node, a cursor points at the first segment.

    At each node, the segment under the cursor is used
    to access the node to go deeper.

    As the cursor moves from the begining towards the end of the segment list,
    the list is logically split into two parts.

    The first part, the trail, is the prefix of segments
    that have already been used in descending through the document hierarchy
    and corresponds to the current path.

    The second part of the path, the feed, is the suffix of segments
    that have not yet been accessed to descend to the full path.

    There are two outcomes:
        1. feed is empty, meaning that the given path was found
        2. feed is non-empty, meaning that the first segment in the feed was
           not found in the document at the path formed by the trail.

    Args:
        doc (dict):
            A recursive object-document
        path (tuple):
            A sequence of path segments as in ('path', 'to', 'somewhere')

    Returns:
        tuple of lists:
            feed (list):
                List of path segments left that have not yet been accessed
            trail (list):
                List of path segments already accessed. It corresponds to the
                current path of the node where no further descent was possible
                and thus doc_locate() was terminated.
            nodes (list):
                List of nodes already accessed, in order.
    """
    feed = list(reversed(path))
    trail = []
    nodes = [doc]
    while feed:
        segment = feed.pop()
        if not segment:
            continue
        if not isinstance(doc, dict) or segment not in doc:
            feed.append(segment)
            break
        trail.append(segment)
        doc = doc[segment]
        nodes.append(doc)
    return feed, trail, nodes


def extrude_forked(ARMATURE_OT_extrude=None, TRANSFORM_OT_translate=None):
    """Create new bones from the selected joints and move them

    :param ARMATURE_OT_extrude: Extrude, Create new bones from the selected joints
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


@staticmethod
def _graph_indices(T, changepoints):
    """Describes which graphs are active for each time
        by returning a list with the graphs indices

        Parameters
        ----------
        T : int
            number of total timesteps
        changepoints : list[int]
            list of changepoint indices

        Yields
        ------
        Graph indices for all t < T
        """
    graph = count = 0
    for cp in changepoints:
        while count < cp:
            count += 1
            yield graph
        graph += 1
    while count < T:
        count += 1
        yield graph


def assignIfExists(opts, default=None, **kwargs):
    """
	Helper for assigning object attributes from API responses.
	"""
    for opt in opts:
        if opt in kwargs:
            return kwargs[opt]
    return default


def supportsOutcastAffiliation():
    """ Reports if the backend supports the publisher affiliation.

        @rtype: C{bool}
        """


def _rdf2dot_simple(g, stream):
    """Create a simple graph of processes and artifacts."""
    from itertools import chain
    import re
    path_re = re.compile(
        '(?P<prefix>https://\\w+/|https://\\w+/\\w+/){0,1}(?P<type>[a-zA-Z]+)/(?P<commit>\\w+)(?P<path>.+)?'
        )
    inputs = g.query(
        """
        SELECT ?input ?role ?activity ?comment
        WHERE {
            ?activity (prov:qualifiedUsage/prov:entity) ?input .
            ?activity prov:qualifiedUsage ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:entity ?input .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun .
            ?activity rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
        )
    outputs = g.query(
        """
        SELECT ?activity ?role ?output ?comment
        WHERE {
            ?output (prov:qualifiedGeneration/prov:activity) ?activity .
            ?output prov:qualifiedGeneration ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:activity ?activity .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun ;
                      rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
        )
    activity_nodes = {}
    artifact_nodes = {}
    for source, role, target, comment in chain(inputs, outputs):
        src_path = path_re.match(source).groupdict()
        tgt_path = path_re.match(target).groupdict()
        stream.write(
            '\t"{src_commit}:{src_path}" -> "{tgt_commit}:{tgt_path}" [label={role}] \n'
            .format(src_commit=src_path['commit'][:5], src_path=src_path.
            get('path') or '', tgt_commit=tgt_path['commit'][:5], tgt_path=
            tgt_path.get('path') or '', role=role))
        if src_path.get('type') == 'commit':
            activity_nodes.setdefault(source, {'comment': comment})
            artifact_nodes.setdefault(target, {})
        if tgt_path.get('type') == 'commit':
            activity_nodes.setdefault(target, {'comment': comment})
            artifact_nodes.setdefault(source, {})
    for node, content in activity_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" [shape=box label="#{commit}:{path}:{comment}"] \n'
            .format(comment=content['comment'], commit=node_path['commit'][
            :5], path=node_path.get('path') or ''))
    for node, content in artifact_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write('\t"{commit}:{path}" [label="#{commit}:{path}"] \n'.
            format(commit=node_path['commit'][:5], path=node_path.get(
            'path') or ''))
    stream.write('}\n')


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


def path2fname(path):
    """
    extracts file name from path
  """
    return path.split('/')[-1]


@staticmethod
def query_str(query_dict):
    """ Takes a RequestQuery object and returns a proper Aeris API url query

            Params:
                - query_dict: A dictionary containing a single RequestQuery and its value

            Returns:
                - str: a correctly formatted query attribute ready to be inserted into an API request url
        """
    out_query = ''
    if query_dict is not None:
        for q, value in query_dict.items():
            out_query += '&' + q.value + '=' + value
    else:
        out_query = None
    return out_query


@staticmethod
def save_gmt(response, *, path):
    """Save the GMT file."""
    with open(path, 'wb') as f:
        f.write(response.body)


@classmethod
def validate_dependency_registration(cls, params, name):
    """
        Validate required parameters for dependency file

        :param params: parameters related to the dependency file
        :param name: name of the dependency file
        :raises ValueError: if some of the required parameters are missing,
                            or some of the parameters are invalid
        """
    mandatory = ['Dependency-Version']
    cls._check_mandatory_params(params, mandatory)
    perm = params.get('Dependency-Permissions')
    if perm is not None:
        try:
            perm_int = int(perm, 8)
        except ValueError:
            raise ValueError('Dependency permission is incorrect')
        if perm_int & int('600', 8) != int('600', 8):
            raise ValueError('The owner should have rw permission')


def cAnisoShrink():
    """
    Return the kernel source of cAnisoShrink
    """
    R = """
    KERNEL void cAnisoShrink(const  float2 threshold,
                                    GLOBAL_MEM const float2 *indata,
                                    GLOBAL_MEM  float2 *outdata)
    {
    const unsigned int gid =  get_global_id(0);
    float2 tmp; // temporay register
    tmp = indata[gid];
    //float zero = 0.0;
    //tmp.x=sign(tmp.x)*max(fabs(tmp.x)-threshold.x, zero);
    //tmp.y=sign(tmp.y)*max(fabs(tmp.y)-threshold.y, zero);
    tmp.x =  (tmp.x > threshold.x)*(tmp.x - threshold.x) ;//+ (tmp.x < - threshold.x)*(tmp.x + threshold.x);
    tmp.y =  (tmp.y > threshold.x)*(tmp.y - threshold.x) ;//+ (tmp.y < - threshold.x)*(tmp.y + threshold.x);
    outdata[gid]=tmp;
    };
    """
    return R


def argument(*name_or_flags, **kwargs):
    """Convenience function to properly format arguments to pass to the
    subcommand decorator.

    """
    return list(name_or_flags), kwargs


def was_killed_by_user(info):
    """
        Process 'crew member was killed by user' event.

        Input:
        `info`  # An object with information about event's time, user's
                # callsign and aircraft, seat number, attacker's callsign,
                # aircraft and position on map.
        """


def _unpack_parameters(parameters, key):
    """Unpacks the values from a dictionary containing various parameters for
    pymaws

    Parameters
    ----------
    parameters : dict
        planetary parameters dict with keys:
            angular_frequency: float, (rad/sec)
            gravitational_acceleration: float, (m/sec^2)
            mean_radius: float, (m)
            layer_mean_depth: float, (m)
    key : String
        key with the one of the names of the above keys.
    Returns
    -------
    value : Float, scalar
            one of the above values
    """
    if not isinstance(key, str):
        raise TypeError(str(key) + ' should be string...')
    if not isinstance(parameters, dict):
        raise TypeError('parameters should be dictionary...')
    if key not in parameters:
        raise KeyError(str(key) + ' not in parameters!')
    value = parameters[key]
    return value


@classmethod
def get(cls, id, using=None, index=None, **kwargs):
    """
        Retrieve a single document from elasticsearch using its ``id``.

        :arg id: ``id`` of the document to be retrieved
        :arg index: elasticsearch index to use, if the ``Document`` is
            associated with an index this can be omitted.
        :arg using: connection alias to use, defaults to ``'default'``

        Any additional keyword arguments will be passed to
        ``Elasticsearch.get`` unchanged.
        """
    es = cls._get_connection(using)
    doc = es.get(index=cls._default_index(index), id=id, **kwargs)
    if not doc.get('found', False):
        return None
    return cls.from_es(doc)


def sizeof_fmt(num, suffix='B'):
    """Return human readable version of in-memory size.
    Code from Fred Cirera from Stack Overflow:
    https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
    """
    for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
        if abs(num) < 1024.0:
            return '%3.1f%s%s' % (num, unit, suffix)
        num /= 1024.0
    return '%.1f%s%s' % (num, 'Yi', suffix)


@classmethod
def _camel_case(cls, text, first_upper=False):
    """
        Transform text to camelCase or CamelCase

        :param text:
        :param first_upper: first symbol must be upper?
        :return:
        """
    result = ''
    need_upper = False
    for pos, symbol in enumerate(text):
        if symbol == '_' and pos > 0:
            need_upper = True
        else:
            if need_upper:
                result += symbol.upper()
            else:
                result += symbol.lower()
            need_upper = False
    if first_upper:
        result = result[0].upper() + result[1:]
    return result


def left_screen_edge(desktop, rect):
    """ Get the x-coordinate of the effective left screen edge.

    Parameters
    ----------
    desktop : QDesktopWidget
        The desktop widget for the application.

    rect : QRect
        The rect of interest.

    Returns
    -------
    result : int
        the x-coordinate of the effective left screen edge.

    """
    p1 = rect.topLeft()
    p2 = rect.bottomLeft()
    g1 = desktop.availableGeometry(p1)
    g2 = desktop.availableGeometry(p2)
    return max(p1.x(), g1.left(), g2.left())


def cmd_stor(args):
    """Store a file. Write access required.
        """


def shield_split(shield_string):
    """

    Parse the electron configuration string, dividing up into the different orbital
    shells.

    *args*:

        - **shield_string**: string, electron configuration

    *return*:

        - **parsed_shield**: list of separated orbital components

    ***
    """
    alphas = []
    for s in range(len(shield_string)):
        if shield_string[s].isalpha():
            alphas.append(s)
    parsed_shield = []
    for s in range(len(alphas) - 1):
        parsed_shield.append(shield_string[alphas[s] - 1:alphas[s + 1] - 1])
    parsed_shield.append(shield_string[alphas[-1] - 1:])
    return parsed_shield


def _fit_IC_table(res, ictable):
    """
    Determines cartesian coordinates from an internal coordinate table stored in
    CHARMM residue topology files

    Parameters
    ----------
    res : ResidueTemplate
        The residue template for which coordinates are being determined
    ictable : list[tuple(atoms, measurements)]
        The internal coordinate table

    Notes
    -----
    This method assigns an xx, xy, and xz attribute to ``res``. For the time
    being, this is just a placeholder, as its functionality has not yet been
    implemented (CHARMM does not use a 'traditional' Z-matrix, and I don't know
    of any existing code that will compute the proper cartesian coordinates from
    the form used by CHARMM)
    """
    for atom in res:
        atom.xx = atom.xy = atom.xz = 0.0


def PolsAccHosp(t):
    """Number of policies: Accidental Hospitalization"""
    return 0


def item_openclose(all: bool=True):
    """Toggle whether item under cursor is enabled or closed

    :param all: All, Close or open all items
    :type all: bool
    """
    pass


def pileup_acgt(pileup, quality, depth, reference, qlimit=53, noend=False,
    nostart=False):
    """
    Yet another version of the pileup parser. Used as a template
    for the C implementation, the old function still runs slightly
    faster, to my surprise...
    """
    characters = {'A': 0, 'C': 1, 'G': 2, 'T': 3, 'a': 4, 'c': 5, 'g': 6,
        't': 7, '$': 8, '*': 9, '-': 10, '+': 11}
    nucleot_list = [0, 0, 0, 0]
    strand_list = [0, 0, 0, 0]
    last_base = None
    index = len(pileup)
    n = 0
    q = 0
    while n < index:
        base = pileup[n]
        if base == '^':
            if not nostart:
                n += 2
                base = pileup[n]
            else:
                n += 3
                q += 1
                continue
        if base == '.':
            base = reference
        elif base == ',':
            base = reference.lower()
        base_index = characters[base]
        if base_index < 4:
            if ord(quality[q]) >= qlimit:
                last_base = base_index
                nucleot_list[base_index] += 1
                strand_list[base_index] += 1
            else:
                last_base = None
            n += 1
            q += 1
        elif base_index < 8:
            if ord(quality[q]) >= qlimit:
                last_base = base_index
                nucleot_list[base_index - 4] += 1
            else:
                last_base = None
            n += 1
            q += 1
        elif base_index == 8:
            if not noend:
                pass
            elif last_base:
                if last_base < 4:
                    nucleot_list[last_base] -= 1
                    strand_list[last_base] -= 1
                else:
                    nucleot_list[last_base - 4] -= 1
            last_base = None
            n += 1
        elif base_index == 9:
            last_base = None
            n += 1
            q += 1
        elif base_index > 9:
            offset = n + 1
            while True:
                if pileup[offset].isdigit():
                    offset += 1
                else:
                    break
            step = int(pileup[n + 1:offset])
            n = step + offset
    nucleot_dict = {'A': nucleot_list[0], 'C': nucleot_list[1], 'G':
        nucleot_list[2], 'T': nucleot_list[3]}
    nucleot_dict['Z'] = [strand_list[0], strand_list[1], strand_list[2],
        strand_list[3]]
    return nucleot_dict


def parse_entry_point(entry_point):
    """
    Parses a Python entry point and returns the module and function.
    The two allowed formats are 'path.to.module', and 'path.to.module:function'.
    In the former case, ('path.to.module', None) is returned.
    In the latter case, ('path.to.module', 'function') is returned.
    """
    module, sep, function = entry_point.partition(':')
    if function and sep and module:
        return module, function
    else:
        return module, None


def is_package(fullname):
    """ Return True if the module specified by 'fullname' is a package.
        """


def __new__(cls, *args, **kwargs):
    """Mainly checks to ensure all subclasses have a PK_FIELDS attribute."""
    if not hasattr(cls, 'PK_FIELDS'):
        raise AttributeError('{} is missing PK_FIELDS'.format(cls.__name__))
    return super().__new__(cls)


def _expand_minus_str(minus_nodes_str):
    """ Expand a '1-5' or '6' string to a list on integer
    :raises: ValueError on invalid values
    """
    minus_node = minus_nodes_str.split('-')
    res = None
    if len(minus_node) == 1:
        res = [int(minus_node[0])]
    else:
        first, last = minus_node
        nodes_range = range(int(first), int(last) + 1)
        if len(nodes_range) <= 1:
            raise ValueError
        res = nodes_range
    return res


@staticmethod
def _image_name(image):
    """Strips image name from image URI"""
    return image.split('/')[1].split(':')[0]


def navigation_root_path():
    """ path of the navigation root
        """


def default_claims_verification_callback(user_claims):
    """
    By default, we do not do any verification of the user claims.
    """
    return True


def chunk(lst, chunk_len):
    """
    Yield successive {chunk_len}-sized chunks from {lst}.
    Reference: https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks
    """
    for index in range(0, len(lst), chunk_len):
        yield lst[index:index + chunk_len]


def hp2kw(power_hp):
    """Convert power from HP to kW"""
    return power_hp / 1.34102


@classmethod
def create_zap_package(cls, package_name, recursive=True):
    """Convenience constructor for a package zap rule.

        Essentially equivalent to just using ``shading_zap('package_name.**')``.

        :param string package_name: Package name to remove (eg, ``org.pantsbuild.example``).
        :param bool recursive: Whether to remove everything under any subpackage of ``package_name``,
          or just direct children of the package. (Defaults to True).
        """
    return cls.create_zap(cls._format_package_glob(package_name, recursive))


@classmethod
def get_schema(cls):
    """Get mapping of table name to column names.

        Returns a dictionary mapping tablenames to the list of
        column names for that table.  Both tablenames and columnnames
        are strings.
        """
    all_schemas = {}
    for trans in cls.TRANSLATORS:
        cls._get_schema(trans, all_schemas)
    return all_schemas