def check_priors(options):
    """Checks whether priors provided by user, and default
    values assigned by extract_metrics function are valid
    assignments.

    Keyword arguments:
    options -- contains all options used to fit model (dictionary)
    """
    for keys in options['priors_definitions']:
        if options['priors_definitions'][keys] not in ('Unif', 'Norm',
            'Log-Norm', 'Beta', 'Gamma'):
            raise Exception(
                """One of the prior distributions defined is not
                            a valid argument from options available!"""
                )
    for values in options['priors_params']:
        for i in range(0, len(options['priors_params'][values])):
            if options['priors_params'][values][i] > 10000 or options[
                'priors_params'][values][i] < -10000:
                raise Exception(
                    """One of the parameters that define a prior
                    distribution is greater than 10000 or less than -10000!"""
                    )


def vertices_smooth_laplacian(repeat: int=1, lambda_factor: float=5e-05,
    lambda_border: float=5e-05, use_x: bool=True, use_y: bool=True, use_z:
    bool=True, preserve_volume: bool=True):
    """Laplacian smooth of selected vertices

    :param repeat: Number of iterations to smooth the mesh
    :type repeat: int
    :param lambda_factor: Lambda factor
    :type lambda_factor: float
    :param lambda_border: Lambda factor in border
    :type lambda_border: float
    :param use_x: Smooth X Axis, Smooth object along X axis
    :type use_x: bool
    :param use_y: Smooth Y Axis, Smooth object along Y axis
    :type use_y: bool
    :param use_z: Smooth Z Axis, Smooth object along Z axis
    :type use_z: bool
    :param preserve_volume: Preserve Volume, Apply volume preservation after smooth
    :type preserve_volume: bool
    """
    pass


@classmethod
def int_keywords(cls):
    """Will return the current set of integer keywords."""
    return cls.int_kw_set


def zerocopy_from_numpy(np_array):
    """Create a tensor that shares the numpy array.

    Parameters
    ----------
    np_array : numpy.ndarray
        The numpy ndarray.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


def argtopk(input, k, dim, descending=True):
    """Return the indices of the k largest elements of the given input tensor
    along the given dimension.

    If descending is False then the k smallest elements are returned.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    k : int
        The number of elements.
    dim : int
        The dimension to sort along.
    descending : bool
        Controls whether to return largest/smallest elements.
    """
    pass


@staticmethod
def p_comment_list_optional(p):
    """comment_list_optional : empty
                                 | comment_list"""
    p[0] = p[1]


def only_keys(d, *keys):
    """Returns a new dictionary containing only the given keys.

    Parameters
    ----------
    d : dict
        The original dictionary.
    keys: list of keys
        The keys to keep.  If a key is not found in the dictionary, it is
        ignored.
    """
    result = dict()
    for key in keys:
        if key in d:
            result[key] = d[key]
    return result


def with_metaclass(meta, base=object):
    """Create a base class with a metaclass."""
    return meta('NewBase', (base,), {})


def sam_list_paired(sam):
    """
	get a list of mapped reads
	require that both pairs are mapped in the sam file in order to remove the reads
	"""
    list = []
    pair = ['1', '2']
    prev = ''
    for file in sam:
        for line in file:
            if line.startswith('@') is False:
                line = line.strip().split()
                id, map = line[0], int(line[1])
                if map != 4 and map != 8:
                    read = id.rsplit('/')[0]
                    if read == prev:
                        list.append(read)
                    prev = read
    return set(list)


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 __nonzero__(me):
    """this is called with something like 3 <= me <= 20."""
    if me.m.replace_last(None) != id(me):
        me.m.replace_last(me)
    return True


@staticmethod
def _get_unique_key(obj):
    """Returns a unique key for passed object for data model building."""
    if obj.__class__.__name__ in ['Member', 'Pool', 'LoadBalancer',
        'Listener', 'Amphora', 'L7Policy', 'L7Rule', 'VThunder']:
        return obj.__class__.__name__ + str(obj.id)
    elif obj.__class__.__name__ in ['SessionPersistence', 'HealthMonitor']:
        return obj.__class__.__name__ + obj.pool_id
    elif obj.__class__.__name__ in ['ListenerStatistics']:
        return obj.__class__.__name__ + obj.listener_id + obj.amphora_id
    elif obj.__class__.__name__ in ['VRRPGroup', 'Vip']:
        return obj.__class__.__name__ + obj.load_balancer_id
    elif obj.__class__.__name__ in ['AmphoraHealth']:
        return obj.__class__.__name__ + obj.amphora_id
    elif obj.__class__.__name__ in ['SNI']:
        return obj.__class__.__name__ + obj.listener_id + obj.tls_container_id
    elif obj.__class__.__name__ in ['Quotas']:
        return obj.__class__.__name__ + obj.project_id
    else:
        raise NotImplementedError


@classmethod
def plot_options(cls, obj, percent_size):
    """
        Given an object and a percentage size (as supplied by the
        %output magic) return all the appropriate plot options that
        would be used to instantiate a plot class for that element.

        Default plot sizes at the plotting class level should be taken
        into account.
        """
    raise NotImplementedError


def algorithms():
    """Get a list of the names of the available stemming algorithms.

    The only algorithm currently supported is the "english", or porter2,
    algorithm.
    """
    return ['english']


def writeToDataFile(filename, values):
    """
    Very simple Function to write (append) some values to a file
    """
    f = open(filename, 'a')
    f.write(values)
    f.close()


def cuboid(target, throat_diameter='throat.diameter'):
    """
    Calculate throat cross-sectional area for a cuboid throat

    Parameters
    ----------
    target : OpenPNM Object
        The object which this model is associated with. This controls the
        length of the calculated array, and also provides access to other
        necessary properties.

    throat_diameter : string
        Dictionary key of the throat diameter values

    Returns
    -------
    value : NumPy ndarray
        Array containing throat cross-sectional area values.

    """
    diams = target[throat_diameter]
    value = diams ** 2
    return value


def wavelength(frequency, speed=343.2):
    """Calculate the wavelength l of frequency f given the speed (of sound)"""
    l = speed / frequency
    return l


def remove_sets(bigset: list, subset: list):
    """
    remove items of subset B from big set
    """
    setC = []
    setC.extend(bigset)
    for item in subset:
        if item in bigset:
            setC.remove(item)
    return setC


def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0, maxiter=1000):
    """Given a function and distinct initial points, search in the
    downhill direction (as defined by the initital points) and return
    new points xa, xb, xc that bracket the minimum of the function
    f(xa) > f(xb) < f(xc). It doesn't always mean that obtained
    solution will satisfy xa<=x<=xb

    :Parameters:

        func : callable f(x,*args)
            Objective function to minimize.
        xa, xb : float
            Bracketing interval.
        args : tuple
            Additional arguments (if present), passed to `func`.
        grow_limit : float
            Maximum grow limit.
        maxiter : int
            Maximum number of iterations to perform.

    :Returns: xa, xb, xc, fa, fb, fc, funcalls

        xa, xb, xc : float
            Bracket.
        fa, fb, fc : float
            Objective function values in bracket.
        funcalls : int
            Number of function evaluations made.

    """
    _gold = 1.618034
    _verysmall_num = 1e-21
    fa = func(*((xa,) + args))
    fb = func(*((xb,) + args))
    if fa < fb:
        dum = xa
        xa = xb
        xb = dum
        dum = fa
        fa = fb
        fb = dum
    xc = xb + _gold * (xb - xa)
    fc = func(*((xc,) + args))
    funcalls = 3
    iter = 0
    while fc < fb:
        tmp1 = (xb - xa) * (fb - fc)
        tmp2 = (xb - xc) * (fb - fa)
        val = tmp2 - tmp1
        if abs(val) < _verysmall_num:
            denom = 2.0 * _verysmall_num
        else:
            denom = 2.0 * val
        w = xb - ((xb - xc) * tmp2 - (xb - xa) * tmp1) / denom
        wlim = xb + grow_limit * (xc - xb)
        if iter > maxiter:
            raise RuntimeError('Too many iterations.')
        iter += 1
        if (w - xc) * (xb - w) > 0.0:
            fw = func(*((w,) + args))
            funcalls += 1
            if fw < fc:
                xa = xb
                xb = w
                fa = fb
                fb = fw
                return xa, xb, xc, fa, fb, fc, funcalls
            elif fw > fb:
                xc = w
                fc = fw
                return xa, xb, xc, fa, fb, fc, funcalls
            w = xc + _gold * (xc - xb)
            fw = func(*((w,) + args))
            funcalls += 1
        elif (w - wlim) * (wlim - xc) >= 0.0:
            w = wlim
            fw = func(*((w,) + args))
            funcalls += 1
        elif (w - wlim) * (xc - w) > 0.0:
            fw = func(*((w,) + args))
            funcalls += 1
            if fw < fc:
                xb = xc
                xc = w
                w = xc + _gold * (xc - xb)
                fb = fc
                fc = fw
                fw = func(*((w,) + args))
                funcalls += 1
        else:
            w = xc + _gold * (xc - xb)
            fw = func(*((w,) + args))
            funcalls += 1
        xa = xb
        xb = xc
        xc = w
        fa = fb
        fb = fc
        fc = fw
    return xa, xb, xc, fa, fb, fc, funcalls


def kappa_analysis_altman(kappa):
    """
    Analysis kappa number with Altman benchmark.

    :param kappa: kappa number
    :type kappa : float
    :return: strength of agreement as str
    """
    try:
        if kappa < 0.2:
            return 'Poor'
        if kappa >= 0.2 and kappa < 0.4:
            return 'Fair'
        if kappa >= 0.4 and kappa < 0.6:
            return 'Moderate'
        if kappa >= 0.6 and kappa < 0.8:
            return 'Good'
        if kappa >= 0.8 and kappa <= 1:
            return 'Very Good'
        return 'None'
    except Exception:
        return 'None'


def _svm_apply(SVM, q):
    """
    f_i = _svm_apply(SVM, q)

    @internal: This is mostly used for testing
    """
    X, Y, Alphas, b, C, kernel = SVM
    N = len(X)
    s = 0.0
    for i in range(N):
        s += Alphas[i] * Y[i] * kernel(q, X[i])
    return s - b


def ascii_lower(string):
    """Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.

    :param string: An Unicode string.
    :returns: A new Unicode string.

    This is used for `ASCII case-insensitive
    <http://whatwg.org/C#ascii-case-insensitive>`_ matching.

    This is different from the :meth:`~py:str.lower` method of Unicode strings
    which also affect non-ASCII characters,
    sometimes mapping them into the ASCII range:

    >>> keyword = u'Bac\\N{KELVIN SIGN}ground'
    >>> assert keyword.lower() == u'background'
    >>> assert ascii_lower(keyword) != keyword.lower()
    >>> assert ascii_lower(keyword) == u'bac\\N{KELVIN SIGN}ground'

    """
    return string.encode('utf8').lower().decode('utf8')


def registerProducer(producer, streaming):
    """
        Register to receive data from a producer.

        This sets self to be a consumer for a producer.  When this object runs
        out of data (as when a send(2) call on a socket succeeds in moving the
        last data from a userspace buffer into a kernelspace buffer), it will
        ask the producer to resumeProducing().

        For L{IPullProducer} providers, C{resumeProducing} will be called once
        each time data is required.

        For L{IPushProducer} providers, C{pauseProducing} will be called
        whenever the write buffer fills up and C{resumeProducing} will only be
        called when it empties.  The consumer will only call C{resumeProducing}
        to balance a previous C{pauseProducing} call; the producer is assumed
        to start in an un-paused state.

        @type producer: L{IProducer} provider

        @type streaming: C{bool}
        @param streaming: C{True} if C{producer} provides L{IPushProducer},
        C{False} if C{producer} provides L{IPullProducer}.

        @raise RuntimeError: If a producer is already registered.

        @return: L{None}
        """


def _remove_volumes(bold_file, skip_vols):
    """Remove skip_vols from bold_file."""
    import nibabel as nb
    from nipype.utils.filemanip import fname_presuffix
    if skip_vols == 0:
        return bold_file
    out = fname_presuffix(bold_file, suffix='_cut')
    bold_img = nb.load(bold_file)
    bold_img.__class__(bold_img.dataobj[(...), skip_vols:], bold_img.affine,
        bold_img.header).to_filename(out)
    return out


def __clean_path(path):
    """ensures path is Django-friendly"""
    if path.startswith('/'):
        path = path[1:]
    if not path.endswith('/'):
        path = '{}/'.format(path)
    return path


def freestyle_add_edge_marks_to_keying_set():
    """Add the data paths to the Freestyle Edge Mark property of selected edges to the active keying set

    """
    pass


def match_node(var_name, node_id, node_label):
    """Query to match a node into the variable.

    Parameters
    ----------
    var_name
        Variable name to use for the matched node
    node_id
        Id of the node to match
    label
        Label of the node to match, default is 'node'
    """
    return "MATCH ({}:{} {{ id : '{}' }})\n".format(var_name, node_label,
        node_id)


@classmethod
def get_available_releases(cls, public=None):
    """ Get the available releases

        Parameters:
            public (bool):
                If True, only return public data releases
        """
    cfgs = cls.list_available_configs()
    releases = []
    for i in cfgs:
        if public and not i.startswith('dr'):
            continue
        b = i.split('.cfg', 1)[0]
        if 'dr' in b or 'mpl' in b:
            releases.append(b.upper())
        elif 'work' in b and 'WORK' not in releases:
            releases.append('WORK')
    return releases


@classmethod
def patch(cls, param=None, **kwargs):
    """Bind middleware's method as PATCH endpoint.
        """
    return cls.bind(param, methods=['PATCH'], **kwargs)


def build_matrix_for_eigendecomposition(lagged_covariances):
    """Build the matrix to use for the eigendecomposition."""
    return lagged_covariances[:, :, (0)]


def coolwarm_transparent(max_alpha=0.7, opaque_perc=30, transparent_perc=8):
    """Modify the coolwarm color scale to have full transparency around the middle."""
    import numpy as np
    import matplotlib.pylab as pl
    from matplotlib.colors import ListedColormap
    cmap = pl.cm.coolwarm
    my_cmap = cmap(np.arange(cmap.N))
    _20perc = cmap.N * opaque_perc // 100
    midpoint = cmap.N // 2 + 1
    _10perc = cmap.N * transparent_perc // 100
    alpha = np.ones(cmap.N) * max_alpha
    alpha[midpoint - _10perc:midpoint + _10perc] = 0
    alpha[_20perc:midpoint - _10perc - 1] = np.linspace(max_alpha, 0, len(
        alpha[_20perc:midpoint - _10perc - 1]))
    alpha[midpoint + _10perc:-_20perc] = np.linspace(0, max_alpha, len(
        alpha[midpoint + _10perc:-_20perc]))
    my_cmap[:, (-1)] = alpha
    return ListedColormap(my_cmap)


def _coeff_isneg(a):
    """Return True if the leading Number is negative.

    Examples
    ========

    >>> from sympy.core.function import _coeff_isneg
    >>> from sympy import S, Symbol, oo, pi
    >>> _coeff_isneg(-3*pi)
    True
    >>> _coeff_isneg(S(3))
    False
    >>> _coeff_isneg(-oo)
    True
    >>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1
    False

    """
    if a.is_Mul:
        a = a.args[0]
    return a.is_Number and a.is_negative


def removeAll():
    """
        Remove all readers and writers.

        Should not remove reactor internal reactor connections (like a waker).

        @return: A list of L{IReadDescriptor} and L{IWriteDescriptor} providers
                 which were removed.
        """


def nop():
    """ Function which does absolutely nothing (aka pass, noop). """
    pass


def get_input_multiplicity(structure, protocol_settings):
    """ Compute the total multiplicity of the structure,
    by summing the atomic magnetizations:
    multiplicity = 1 + sum_i ( natoms_i * magnetization_i ), for each atom_type i
    """
    multiplicity = 1
    all_atoms = structure.get_ase().get_chemical_symbols()
    for key, value in protocol_settings['initial_magnetization'].items():
        multiplicity += all_atoms.count(key) * value
    multiplicity = int(round(multiplicity))
    multiplicity_dict = {'FORCE_EVAL': {'DFT': {'MULTIPLICITY': multiplicity}}}
    if multiplicity != 1:
        multiplicity_dict['FORCE_EVAL']['DFT']['UKS'] = True
    return multiplicity_dict


def keep_q(start_a, stop_a, start_b, stop_b):
    """
    Determines whether or not to keep the second range for labeling the first
    i.e. whether or not the range indicated by [start_b, stop_b] overlaps with
    the range designated by [start_a, stop_a]

    Notes:
        assumes start < stop

    Arguments:
        start_a (int): start of range to test against
        stop_a (int): stop of range to test against
        start_b (int): start of range in question
        stop_b (int): stop of range in question

    Returns:
        (bool): whether or not the second range overlaps the first
    """
    if stop_b < start_a:
        return False
    if start_b > stop_a:
        return False
    return True


def vert_separate(vert: 'bmesh.types.BMVert', edges: 'bmesh.types.BMEdge'
    ) ->'bmesh.types.BMVert':
    """Separate this vertex at every edge.

    :param vert: The vert to be separated.
    :type vert: 'bmesh.types.BMVert'
    :param edges: The edges to separated.
    :type edges: 'bmesh.types.BMEdge'
    :return:  The newly separated verts (including the vertex passed).
    """
    pass


def dtype(x):
    """Returns the dtype of a Keras tensor or variable, as a string.

    # Arguments
        x: Tensor or variable.

    # Returns
        String, dtype of `x`.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> K.dtype(K.placeholder(shape=(2,4,5)))
        'float32'
        >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float32'))
        'float32'
        >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float64'))
        'float64'
        # Keras variable
        >>> kvar = K.variable(np.array([[1, 2], [3, 4]]))
        >>> K.dtype(kvar)
        'float32_ref'
        >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
        >>> K.dtype(kvar)
        'float32_ref'
    ```
    """
    return x.dtype.base_dtype.name


def __call__(environ):
    """ Return an instance of ``pyramid.request.Request``"""


def prefix(it, count):
    """Truncate an iterable to at most `count` items.
    """
    for i, v in enumerate(it):
        if i >= count:
            break
        yield v


def write_boot(boot, triple, outfile):
    """
    Write the current dictionary of bootstrapping output from bootstrap_triple()
    to the file passed as an argument to the function.
    """
    print(
        """P1	Hybrid	P2	Zscore	Pvalue	Gamma	AAAA	AAAB	AABA	AABB	AABC	ABAA	ABAB	ABAC	ABBA	BAAA	ABBC	CABC	BACA	BCAA	ABCD
"""
        , end='', file=outfile)
    for v in boot.values():
        print(triple[0], '\t', triple[1], '\t', triple[2], '\t', sep='',
            end='', file=outfile)
        print(v['Zscore'], '\t', sep='', end='', file=outfile)
        print(v['Pvalue'], '\t', sep='', end='', file=outfile)
        print(v['Gamma'], '\t', sep='', end='', file=outfile)
        print(v['AAAA'], '\t', sep='', end='', file=outfile)
        print(v['AAAB'], '\t', sep='', end='', file=outfile)
        print(v['AABA'], '\t', sep='', end='', file=outfile)
        print(v['AABB'], '\t', sep='', end='', file=outfile)
        print(v['AABC'], '\t', sep='', end='', file=outfile)
        print(v['ABAA'], '\t', sep='', end='', file=outfile)
        print(v['ABAB'], '\t', sep='', end='', file=outfile)
        print(v['ABAC'], '\t', sep='', end='', file=outfile)
        print(v['ABBA'], '\t', sep='', end='', file=outfile)
        print(v['BAAA'], '\t', sep='', end='', file=outfile)
        print(v['ABBC'], '\t', sep='', end='', file=outfile)
        print(v['CABC'], '\t', sep='', end='', file=outfile)
        print(v['BACA'], '\t', sep='', end='', file=outfile)
        print(v['BCAA'], '\t', sep='', end='', file=outfile)
        print(v['ABCD'], '\n', sep='', end='', file=outfile)


def _transform_master_key_providers(key_id, regions, profile):
    """Transform master key provider information to raw aws-encryption-cli arguments.

    :param str key_id: Key ID to use for all regions
    :param list regions: List of region names (may be empty)
    :param str profile: Named profile to use (may be None)
    :returns: Raw aws-encryption-cli master key provider configuration arguments
    :rtype: list of str
    """
    base_config = ['--master-keys', 'key={}'.format(key_id)]
    if profile is not None:
        base_config.append('profile={}'.format(profile))
    if not regions:
        return base_config
    configs = []
    for region in regions:
        configs.extend(base_config + ['region={}'.format(region)])
    return configs


@classmethod
def get_time_series_field_verbose_name(cls, date_period):
    """
        Sent the column data to construct a verbose name.
        Default implemenetation is column name + the end date %Y%m%d
        :param column_name: the computation field_name
        :param date_period: a tuple of (start_date, end_date)
        :return: a verbose string
        """
    return f"{cls.verbose_name} {date_period[1].strftime('%Y%m%d')}"


def get_item(parent=None, title='User Input', prompt='Choose One:', items=[
    ], current=0, editable=False):
    """Opens a simple prompt to choose an item from a list, returns a string
    """
    for ind, item in enumerate(items):
        print(' ', ind + 1, '. ', item)
    ret = input(prompt)
    if ret != '':
        ind = int(ret) - 1
        if ind < len(items):
            return items[ind]
        else:
            return ''
    else:
        return ''


def convert_coordinates(q, conversion, axisorder):
    """
    Convert a 3-tuple in data coordinates into to simplex data
    coordinates for plotting.

    Parameters
    ----------
    q: 3-tuple
       the point to be plotted in data coordinates

    conversion: dict
        keys = ['b','l','r']
        values = lambda function giving the conversion
    axisorder: String giving the order of the axes for the coordinate tuple
        e.g. 'blr' for bottom, left, right coordinates.

    Returns
    -------
    p: 3-tuple
       The point converted to simplex coordinates.
    """
    p = []
    for k in range(3):
        p.append(conversion[axisorder[k]](q[k]))
    return tuple(p)


@staticmethod
def disconnect(controller_widget, control_name, control_instance):
    """ Disconnect a 'Str' or 'String' controller trait and a
        'StrControlWidget' controller widget control.

        Parameters
        ----------
        controller_widget: ControllerWidget (mandatory)
            a controller widget that contains the controller we want to update
        control_name: str(mandatory)
            the name of the controller widget control we want to synchronize
            with the controller
        control_instance: QLineEdit (mandatory)
            the instance of the controller widget control we want to
            synchronize with the controller
        """
    if control_instance.connected:
        widget_hook, widget_hook2, controller_hook = (control_instance.
            _controller_connections)
        controller_widget.controller.on_trait_change(controller_hook, name=
            control_name, remove=True)
        control_instance.userModification.disconnect(widget_hook)
        control_instance.editingFinished.disconnect(widget_hook2)
        del control_instance._controller_connections
        control_instance.connected = False


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

    The ".dev0" means dirty.

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


def please_reset_handler(spawn, session):
    """ Handles the router asking to be reset before booting. """
    if not session.get('please_reset_seen'):
        spawn.log.debug('The device has asked to be reset.')
        session['please_reset_seen'] = True
        if session.get('rommon_count'):
            _ = session.pop('rommon_count')


def read_bytes(fh, byteorder, dtype, count):
    """Read tag data from file and return as byte string."""
    dtype = 'b' if dtype[-1] == 's' else byteorder + dtype[-1]
    return fh.read_array(dtype, count).tostring()


@staticmethod
def get_max_url_file_name_length(savepath):
    """
        Determines the max length for any max... parts.

        :param str savepath: absolute savepath to work on
        :return: max. allowed number of chars for any of the max... parts
        """
    number_occurrences = savepath.count('%max_url_file_name')
    number_occurrences += savepath.count('%appendmd5_max_url_file_name')
    savepath_copy = savepath
    size_without_max_url_file_name = len(savepath_copy.replace(
        '%max_url_file_name', '').replace('%appendmd5_max_url_file_name', ''))
    max_size = 260 - 1 - size_without_max_url_file_name
    max_size_per_occurrence = max_size / number_occurrences
    return max_size_per_occurrence


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


def AVG(src_column):
    """
    Builtin average aggregator for groupby. Synonym for tc.aggregate.MEAN. If
    src_column is of array type, and if array's do not match in length a NoneType is
    returned in the destination column.

    Example: Get the average rating of each user.

    >>> sf.groupby("user",
    ...            {'rating_avg':tc.aggregate.AVG('rating')})
    """
    return '__builtin__avg__', [src_column]


def p_track_file(t):
    """track_flag : FILE STRING start
                  | AUDIOFILE STRING start
                  | FILE STRING start length
                  | AUDIOFILE STRING start length"""
    from audiotools.toc import TOCFlag_FILE
    if len(t) == 4:
        t[0] = TOCFlag_FILE(type=t[1], filename=t[2], start=t[3])
    else:
        t[0] = TOCFlag_FILE(type=t[1], filename=t[2], start=t[3], length=t[4])


def eval_unary_op(tokens):
    """Unary Op Evaluation

    :param tokens: The grammar tokens
    :type tokens: list
    """
    params = tokens[0]
    if params[0] == '-':
        return -1 * params[1]
    else:
        return params[1]


def _verify_token_binding_id(client_data):
    """The tokenBinding member contains information about the state of the
    Token Binding protocol used when communicating with the Relying Party.
    The status member is one of:

        not-supported: when the client does not support token binding.

            supported: the client supports token binding, but it was not
                       negotiated when communicating with the Relying
                       Party.

              present: token binding was used when communicating with the
                       Relying Party. In this case, the id member MUST be
                       present and MUST be a base64url encoding of the
                       Token Binding ID that was used.
    """
    token_binding_status = client_data['tokenBinding']['status']
    token_binding_id = client_data['tokenBinding'].get('id', '')
    if token_binding_status in ('supported', 'not-supported'):
        return True
    return False


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

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

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

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


@staticmethod
def plugin_name():
    """ Short name for the plugin. """
    raise NotImplementedError


def _paths_from_ls(recs):
    """The xenstore-ls command returns a listing that isn't terribly useful.

    This method cleans that up into a dict with each path
    as the key, and the associated string as the value.
    """
    last_nm = ''
    level = 0
    path = []
    ret = []
    for ln in recs.splitlines():
        nm, val = ln.rstrip().split(' = ')
        barename = nm.lstrip()
        this_level = len(nm) - len(barename)
        if this_level == 0:
            ret.append(barename)
            level = 0
            path = []
        elif this_level == level:
            ret.append('%s/%s' % ('/'.join(path), barename))
        elif this_level > level:
            path.append(last_nm)
            ret.append('%s/%s' % ('/'.join(path), barename))
            level = this_level
        elif this_level < level:
            path = path[:this_level]
            ret.append('%s/%s' % ('/'.join(path), barename))
            level = this_level
        last_nm = barename
    return ret


def psi_Ca_MgOH_SO4_HMW84(T, P):
    """c-c'-a: calcium magnesium-hydroxide sulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def calculate_gain_loss(market, book):
    """Calculates the gain or loss of our holdings in both a
    dollar value and percentage"""
    gain_loss = []
    change = []
    length = len(market)
    for index in range(length):
        gain_loss.append('{:.2f}'.format(round(float(market[index]) - float
            (book[index]), 2)))
        change.append('{:.3f}'.format(round(float(gain_loss[index]) / float
            (book[index]), 3)))
    return gain_loss, change


def hhmmss(seconds, rounded=False):
    """formats a time in seconds as hh:mm:ss"""
    if rounded:
        seconds = int(seconds + 0.5)
    sign = ''
    if seconds < 0:
        seconds, sign = -seconds, '-'
    m = int(seconds // 60)
    return '{3}{0:02d}:{1:02d}:{2:02d}'.format(int(m // 60), m % 60, int(
        seconds - 60 * m), sign)


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

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

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


@classmethod
def remove_user_group(cls, options=None):
    """Disassociate an user group.

        Usage:
            hammer user-group remove-user-group [OPTIONS]

        Options:
            --id ID
            --name NAME                                   Name to search by
            --user-group USER_GROUP_NAME                  Name to search by
            --user-group-id USER_GROUP_ID
        """
    cls.command_sub = 'remove-user-group'
    return cls.execute(cls._construct_command(options), output_format='csv')


def shape_for_storage(array, field_size=None):
    """The shape an array will be stored as.

    Parameters
    ----------
    array : ndarray
        The array to be stored.
    field_size : int, optional
        The size of the field.

    Returns
    -------
    tuple of int
        The shape the array will be stored as.

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.field.graph_field import shape_for_storage

    The shape will be such that the first dimension in the field size.

    >>> data = np.arange(6)
    >>> shape_for_storage(data, 3) == (3, 2)
    True
    >>> shape_for_storage(data, 2) == (2, 3)
    True
    >>> shape_for_storage(data, 6) == (6, )
    True

    If a field size is not given, the array will be stored as a
    flattened array.

    >>> shape_for_storage(data) == (6, )
    True
    >>> data = np.arange(6).reshape((3, 2))
    >>> shape_for_storage(data) == (6, )
    True

    For field sizes of 1, the array is always flattened.

    >>> shape_for_storage(data, 1) == (1, 6)
    True

    For scalar arrays, the field size must be 1.

    >>> data = np.array(1.)
    >>> shape_for_storage(data) == (1, )
    True
    >>> shape_for_storage(data, field_size=1) == (1, )
    True

    If the array cannot be shaped into a storage shape, a `ValueError`
    is raised.

    >>> data = np.array(1.)
    >>> shape_for_storage(data, field_size=4) # DOCTEST: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    ValueError: unable to reshape array to field size
    >>> data = np.arange(6.)
    >>> shape_for_storage(data, field_size=4) # DOCTEST: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    ValueError: unable to reshape array to field size
    """
    if field_size is None:
        field_size = array.size
    if array.size % field_size != 0:
        raise ValueError('unable to reshape array to field size ({0} != {1})'
            .format(array.size, field_size))
    if field_size == array.size:
        shape = array.size,
    else:
        shape = field_size, array.size // field_size
    return shape


def memory_free(library, session, offset, extended=False):
    """Frees memory previously allocated using the memory_allocation() operation.

    Corresponds to viMemFree* function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param offset: Offset of the memory to free.
    :param extended: Use 64 bits offset independent of the platform.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    if extended:
        return library.viMemFreeEx(session, offset)
    else:
        return library.viMemFree(session, offset)


def search_mergedcell_value(xl_sheet, merged_range):
    """
    Search for a value in merged_range cells.
    """
    for search_row_idx in range(merged_range[0], merged_range[1]):
        for search_col_idx in range(merged_range[2], merged_range[3]):
            if xl_sheet.cell(search_row_idx, search_col_idx).value:
                return xl_sheet.cell(search_row_idx, search_col_idx)
    return False


def _element_iterable(el):
    """
    Test if a element is iterable

    Parameters
    ----------
    el: object

    Returns
    -------
    iterable: boolean
       if True then then el is iterable
       if Fales then not
    """
    try:
        el[0]
        iterable = True
    except (TypeError, IndexError):
        iterable = False
    return iterable


def complete_strlist_with_capitals(src):
    """
            src := ('k', 'kl', 'klo')  -> ('k', 'kl', 'klo', 'K', 'Kl', 'Klo')
    """
    res = []
    for elem in src:
        res.append(elem)
        res.append(elem.capitalize())
    return res


def _isNotSearchCondition(arg):
    """
	Check whether supplied argument looks like search condition.
	If it is a scalar, or a list of scalars - it is definitely not a condition.
	"""
    if not isinstance(arg, list):
        return True
    for elem in arg:
        if isinstance(elem, list):
            return False
    return True


def clear(cls):
    """
        Empty the cache.
        """
    cls._widgets = {}
    cls._refs = {}
    cls._deps = {}


@classmethod
def get_uuid_names(cls):
    """Returns a tuple of all known Bluetooth Service Class UUID names.

        """
    return tuple(cls.bluetooth_uuid_list.values())


def _passthrough_zotero_data(zotero_data):
    """
    Address known issues with Zotero metadata.
    Assumes zotero data should contain a single bibliographic record.
    """
    if not isinstance(zotero_data, list):
        raise ValueError(
            '_passthrough_zotero_data: zotero_data should be a list')
    if len(zotero_data) > 1:
        zotero_data = zotero_data[:1]
    return zotero_data


@classmethod
def clean_key(cls, key):
    """
        Replace things that look like variables with a '#' so tests aren't
        affected by random variables
        """
    for var_re in cls.VARIABLE_RES:
        key = var_re.sub('#', key)
    return key


def create_row(model, **kw):
    """Instantiate, full_clean, save and return a database object.

    """
    o = model(**kw)
    o.full_clean()
    o.save()
    return o


def check_length_of_shape_or_intercept_names(name_list, num_alts,
    constrained_param, list_title):
    """
    Ensures that the length of the parameter names matches the number of
    parameters that will be estimated. Will raise a ValueError otherwise.

    Parameters
    ----------
    name_list : list of strings.
        Each element should be the name of a parameter that is to be estimated.
    num_alts : int.
        Should be the total number of alternatives in the universal choice set
        for this dataset.
    constrainted_param : {0, 1, True, False}
        Indicates whether (1 or True) or not (0 or False) one of the type of
        parameters being estimated will be constrained. For instance,
        constraining one of the intercepts.
    list_title : str.
        Should specify the type of parameters whose names are being checked.
        Examples include 'intercept_params' or 'shape_params'.

    Returns
    -------
    None.
    """
    if len(name_list) != num_alts - constrained_param:
        msg_1 = '{} is of the wrong length:'.format(list_title)
        msg_2 = 'len({}) == {}'.format(list_title, len(name_list))
        correct_length = num_alts - constrained_param
        msg_3 = 'The correct length is: {}'.format(correct_length)
        total_msg = '\n'.join([msg_1, msg_2, msg_3])
        raise ValueError(total_msg)
    return None


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

    The ".dev0" means dirty.

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


def fixtag(tag, namespaces):
    """ returns the tag name seperated from the namespace uri
    as givein in {some.namespace}tag in elementtree"""
    namespace_uri, tag = tag[1:].split('}', 1)
    ns = namespaces.get(namespace_uri)
    return tag, ns


def _filter_0distance(segment, issues):
    """
    filter issues to drop 0-distance edits
    :param issues: issues to filter
    :return: filter issues
    """
    filtered_issues = []
    for issue in issues:
        if issue['suggestions']:
            suggestions = []
            for suggestion in issue['suggestions']:
                if segment[issue['from']:issue['until']] == suggestion:
                    continue
                suggestions.append(suggestion)
            if suggestions:
                issue['suggestions'] = suggestions
                filtered_issues.append(issue)
        else:
            filtered_issues.append(issue)
    return filtered_issues


@staticmethod
def fromrepo(repo):
    """current value of the variant in the repository"""
    raise NotImplementedError()


def add_cli_addon_drive(subparsers):
    """Create subparser for `addon-drive`.
    """
    desc = 'send motion commands via add-on `drive`'
    addon_drive_parser = subparsers.add_parser('addon-drive', description=
        desc, help=desc, add_help=False)
    addon_drive_parser.add_argument('ID', nargs='?', default=None, help=
        'instance ID')
    addon_drive_parser.add_argument('-r', dest='motion_command', metavar=
        'STRING', default=None, help='raw command (JSON)')
    addon_drive_parser.add_argument('-h', '--help', dest=
        'print_addon_drive_help', action='store_true', default=False, help=
        'print this help message and exit')


def wx_color_to_html_color(wx_color):
    """Convert a wxPython color to an HTML color string."""
    rgb = wx_color.GetRGB()
    green_blue, red = divmod(rgb, 256)
    blue, green = divmod(green_blue, 256)
    return '#%02x%02x%02x' % (red, green, blue)


def get_local_session(env={'LC_ALL': 'C'}, pty=False, shared=None):
    """A shortcut to get a local session"""
    from niceman.resource.shell import Shell
    session = Shell('localshell').get_session(pty=pty, shared=shared)
    if env:
        session.set_envvar(env)
    return session


def rcbrt(data=None, out=None, name=None, **kwargs):
    """Returns element-wise inverse cube-root value of the input.

    .. math::
       rcbrt(x) = 1/\\sqrt[3]{x}

    Example::

       rcbrt([1,8,-125]) = [1.0, 0.5, -0.2]

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L269

    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 get_mod_func(callback):
    """
    Converts 'django.views.news.stories.story_detail' to
    ('django.views.news.stories', 'story_detail')
    """
    try:
        dot = callback.rindex('.')
    except ValueError:
        return callback, ''
    return callback[:dot], callback[dot + 1:]


def size(collection):
    """Gets the size of the `collection` by returning `len(collection)` for
    iterable objects.

    Args:
        collection (list|dict): Collection to iterate over.

    Returns:
        int: Collection length.

    Example:

        >>> size([1, 2, 3, 4])
        4

    .. versionadded:: 1.0.0
    """
    return len(collection)


def __len__():
    """Return the number of (item, score) pairs currently known.

        This is N (the value passed to the constructor), unless .add()
        has been called fewer than N times.
        """


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 param_undefined_info(param_name, default_value):
    """
    Returns info warning an undefined parameter.
    """
    return ('Parameter warning: the hyper-parameter ' +
        "'{}' is not specified, will use default value '{}'".format(
        param_name, default_value))


def SizeReserveUernPremAftMat(t):
    """Unearned premium: After maturity"""
    return 0


def isValidAttributeName(attrName):
    """
        isValidAttributeName - Validate that an attribute name is valid.

          AdvancedHTMLParser will silently drop invalid attributes,
            ValidatingHTMLParser will raise exception

            @param attrName <str> - The attribute name to test

            @return <bool> - True if is valid name, otherwise False
    """
    if not attrName or not attrName[0].isalpha() and attrName[0] != '_':
        return False
    for thisCh in attrName:
        if thisCh.isalnum():
            continue
        elif thisCh in ('-', '_'):
            continue
        return False
    return True


def get_listOfReactions(model):
    """Get list of reactions of a SBML model

    Args:
        model (xml.etree.ElementTree.Element): SBML model

    Returns:
        xml.etree.ElementTree.Element: list of reactions
    """
    listOfReactions = None
    for e in model:
        if e.tag[0] == '{':
            uri, tag = e.tag[1:].split('}')
        else:
            tag = e.tag
        if tag == 'listOfReactions':
            listOfReactions = e
            break
    return listOfReactions


def chunked_read_nb():
    """Reads chunked input without blocking.

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

    * http://uwsgi.readthedocs.io/en/latest/Chunked.html
    * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.13.html#chunked-input-api

    :rtype: bytes|str

    :raises IOError: If unable to receive chunked part.
    """


@classmethod
def setup_xsrf(cls, xsrf_cookies):
    """
        Sample configuration::

            xsrf_cookies: false         # Disables xsrf_cookies
            xsrf_cookies: true          # or anything other than false keeps it enabled
        """
    cls.check_xsrf_cookie = (cls.noop if xsrf_cookies is False else cls.
        xsrf_ajax)


def __call__(context):
    """The context provides a location that the vocabulary can make use of.
        """


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

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

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


def new_instance():
    """
        Create an object sharing the same underlying data, but
        capable of operating independently, such as in a new thread.

        This may return the same object.
        """


def format_lines(var_name, seq, raw=False, indent_level=0):
    """Formats a sequence of strings for output."""
    lines = []
    base_indent = ' ' * indent_level * 4
    inner_indent = ' ' * (indent_level + 1) * 4
    lines.append(base_indent + var_name + ' = (')
    if raw:
        for i in seq:
            lines.append(inner_indent + i + ',')
    else:
        for i in seq:
            r = repr(i + '"')
            lines.append(inner_indent + r[:-2] + r[-1] + ',')
    lines.append(base_indent + ')')
    return '\n'.join(lines)


@classmethod
def isnum(cls, nextchar):
    """ Whether the next character is part of a number """
    return nextchar.isdigit()


@classmethod
def get_parameter_names(cls):
    """Return the names of the parameters of this model."""
    return list(cls.default_parameters.keys())


@classmethod
def copy(cls, other):
    """ Returns a copy of a Node instance """
    node = cls(other._start, other._end)
    node._nonterminal = other._nonterminal
    node._terminal = other._terminal
    node._token = other._token
    node._completed = other._completed
    node._highest_prio = other._highest_prio
    if other._families:
        node._families = other._families[:]
    return node


def collection_drop():
    """Drag to move to collection in Outliner

    """
    pass


@staticmethod
def _select_all_spinbox(event):
    """Select all entry content."""
    event.widget.selection('range', 0, 'end')
    return 'break'


@classmethod
def _from_dict(cls, _dict):
    """Initialize a MetricsMonitoring object from a json dictionary."""
    args = {}
    validKeys = ['usage_metrics_enabled', 'metrics_monitoring_crn']
    badKeys = set(_dict.keys()) - set(validKeys)
    if badKeys:
        raise ValueError(
            'Unrecognized keys detected in dictionary for class MetricsMonitoring: '
             + ', '.join(badKeys))
    if 'usage_metrics_enabled' in _dict:
        args['usage_metrics_enabled'] = _dict.get('usage_metrics_enabled')
    if 'metrics_monitoring_crn' in _dict:
        args['metrics_monitoring_crn'] = _dict.get('metrics_monitoring_crn')
    return cls(**args)


@staticmethod
def write_date(value, file):
    """
        Writes a date as a field to a CSV file.

        :param datetime.date value: The date.
        :param T file: The file.
        """
    file.write(value.isoformat())


def fixture_api(func):
    """ Decorator to mark the method as a fixture-only object.
    """
    """ Decorator to automatically mark the object as the normal thing.
    """
    func.__is_fixture__ = True
    return func


def update_job(JobId=None, Manifest=None, JobType=None, ValidateOnly=None,
    APIVersion=None):
    """
    You use this operation to change the parameters specified in the original manifest file by supplying a new manifest file. The manifest file attached to this request replaces the original manifest file. You can only use the operation after a CreateJob request but before the data transfer starts and you can only use it on jobs you own.
    See also: AWS API Documentation

    :example: response = client.update_job(
        JobId='string',
        Manifest='string',
        JobType='Import'|'Export',
        ValidateOnly=True|False,
        APIVersion='string'
    )

    :type JobId: string
    :param JobId: [REQUIRED] A unique identifier which refers to a particular job.

    :type Manifest: string
    :param Manifest: [REQUIRED] The UTF-8 encoded text of the manifest file.

    :type JobType: string
    :param JobType: [REQUIRED] Specifies whether the job to initiate is an import or export job.

    :type ValidateOnly: boolean
    :param ValidateOnly: [REQUIRED] Validate the manifest and parameter values in the request but do not actually create a job.

    :type APIVersion: string
    :param APIVersion: Specifies the version of the client tool.

    :rtype: dict
    :return: {
        'Success': True|False,
        'WarningMessage': 'string',
        'ArtifactList': [
            {
                'Description': 'string',
                'URL': 'string'
            },
        ]
    }

    :returns:
    (dict) -- Output structure for the UpateJob operation.
    Success (boolean) -- Specifies whether (true) or not (false) AWS Import/Export updated your job.
    WarningMessage (string) -- An optional message notifying you of non-fatal issues with the job, such as use of an incompatible Amazon S3 bucket name.
    ArtifactList (list) -- A collection of artifacts.
    (dict) -- A discrete item that contains the description and URL of an artifact (such as a PDF).
    Description (string) -- The associated description for this object.
    URL (string) -- The URL for a given Artifact.

    """
    pass


def p_exprgt(p):
    """ expr : expr GT expr
    """
    a = int(p[1]) if p[1].isdigit() else 0
    b = int(p[3]) if p[3].isdigit() else 0
    p[0] = '1' if a > b else '0'


def apply_daily_results_by_month_to_mast_data(mast_data, corr_results,
    ref_ws_col='ref', site_ws_col='site', splice=True):
    """Applies the slopes and offsets from a daily correaltion, binned by month, to a DataFrame of wind speed data.

    :Parameters:

    mast_data: DataFrame
        timeseries of wind speed data

    corr_results: DataFrame
        slope, offset, R2, uncert, points for each month

    ref_ws_col: string, default 'ref'
        Reference anemometer data to use. Extracted from mast_data DataFrame.

    site_ws_col: string, default 'site'
        Site anemometer data to use. Extracted from mast_data DataFrame

    splice: Boolean, default True
        Returns site data where available and gap-fills any missing periods between the site mast
        and the reference mast's measurement period. Otherwise, returns purely sythesized data without
        taking into account the measured wind speeds.

    :Returns:

    out: time series DataFrame
        predicted wind speeds at the site

    """
    if corr_results.index.nlevels > 1:
        corr_results = corr_results.loc[(ref_ws_col), :]
    corr_data = mast_data.loc[:, ([ref_ws_col, site_ws_col])].dropna(how='all')
    corr_data['month'] = corr_data.index.month
    corr_data['slope'] = corr_data.month.map(corr_results.slope)
    corr_data['offset'] = corr_data.month.map(corr_results.offset)
    corr_data['syn'] = corr_data[ref_ws_col
        ] * corr_data.slope + corr_data.offset
    corr_data['syn_splice'] = corr_data[site_ws_col]
    corr_data.loc[corr_data.syn_splice.isnull(), 'syn_splice'] = corr_data.loc[
        corr_data.syn_splice.isnull(), 'syn']
    if splice:
        syn_data = corr_data.syn_splice.to_frame('syn')
    else:
        syn_data = corr_data.syn.to_frame('syn')
    return syn_data


def can_search(key):
    """Returns if the user has permission to search the given feature"""


def get_last_ter_line(model_lines):
    """Gets the index of the last TER record in a list of records. 0 will be
    returned if there are none.

    :param list model_lines: the lines to search.
    :rtype: ``int``"""
    last_ter = 0
    for index, line in enumerate(model_lines[::-1]):
        if line[:3] == 'TER':
            last_ter = len(model_lines) - index - 1
            break
    return last_ter


def copy_driver_button():
    """Copy the driver for the highlighted button

    """
    pass


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 _str(_bytes):
    """
    Attempt to decode bytes object back to ordinary Python string (utf-8).

    Decoding cannot be guaranteed, so be careful.

    @rtype:   str, but will return the original data if it can't be interpreted as utf-8
    """
    try:
        return _bytes.decode('utf-8')
    except UnicodeDecodeError:
        return _bytes


@staticmethod
def tree_remains_unsure_and_best_upstream_router_reelected(interface:
    'TreeInterfaceDownstream'):
    """
        Tree remains in Unsure state AND
        BestUpstream neighbor changes

        OR

        Tree remains in Unsure state AND
        BestUpstream neighbor transmitted IamUpstream message that doesnt cause a change of the BestUpstream neighbor
        """
    interface.logger.debug(
        'tree_remains_unsure_and_best_upstream_router_reelected')
    interface.send_no_interest()


def nif_nie_validation(doi, number_by_letter, special_cases):
    """
    Validate if the doi is a NIF or a NIE.
    :param doi: DOI to validate.
    :return: boolean if it's valid.
    """
    doi = doi.upper()
    if doi in special_cases:
        return False
    table = 'TRWAGMYFPDXBNJZSQVHLCKE'
    if len(doi) != 9:
        return False
    control = doi[8]
    numbers = number_by_letter.get(doi[0], doi[0]) + doi[1:8]
    return numbers.isdigit() and control == table[int(numbers) % 23]


def get_det_prefix(pv_info):
    """
    Determines which prefix will be passed into the detector init.

    Parameters
    ----------
    pv_info: ``str``
        The second element in a camview cfg line.

    Returns
    -------
    detector_prefix: ``str``
        The prefix to use in the detector init.
    """
    pv_info = pv_info.split(';')
    try:
        detector_prefix = pv_info[1]
    except IndexError:
        detector_prefix = ':'.join(pv_info[0].split(':')[:-1])
    return detector_prefix


def list_fleets(BuildId=None, Limit=None, NextToken=None):
    """
    Retrieves a collection of fleet records for this AWS account. You can filter the result set by build ID. Use the pagination parameters to retrieve results in sequential pages.
    See also: AWS API Documentation

    :example: response = client.list_fleets(
        BuildId='string',
        Limit=123,
        NextToken='string'
    )

    :type BuildId: string
    :param BuildId: Unique identifier for a build to return fleets for. Use this parameter to return only fleets using the specified build. To retrieve all fleets, leave this parameter empty.

    :type Limit: integer
    :param Limit: Maximum number of results to return. Use this parameter with NextToken to get results as a set of sequential pages.

    :type NextToken: string
    :param NextToken: Token that indicates the start of the next sequential page of results. Use the token that is returned with a previous call to this action. To specify the start of the result set, do not specify a value.

    :rtype: dict
    :return: {
        'FleetIds': [
            'string',
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def ValidateSizeQuota(value):
    """
    Validate a quota value.  This may be blank or a non-negative integer.

    :param value: The proposed value.
    :type value: int
    :returns: The validated value or None,
              and a recommended error message or None.
    :rtype: (int or None, str or None)
    """
    if value is None or value == '':
        return None, None
    error = False
    try:
        value = int(value)
        if value < 0:
            error = True
    except ValueError:
        error = True
    if error:
        return (value,
            'Invalid quota.  Must be blank or a non-negative integer representing the limit in bytes.'
            )
    return value, None


@classmethod
def _create_class_proxy(cls, the_class):
    """Create a proxy for the given class.

        Args:
            the_class (class): Class type in which we want to use the proxy.

        Returns:
            object: New proxy instance referencing the `the_class` class.
        """
    namespace = {}
    for name in cls._special_names:
        if hasattr(the_class, name):
            namespace[name] = cls.make_method(name)
    return type(f'{cls.__name__}({the_class.__name__})', (cls,), namespace)


def name_of(obj):
    """Return the name of *obj*.

    :param obj: any object

    .. note::
       This function will return ``obj.__qualname__`` if :pep:`3155` is
       supported in the runtime Python implementation; otherwise
       ``obj.__name__`` is returned.

    """
    return getattr(obj, '__qualname__', obj.__name__)


def create_job(JobType=None, Manifest=None, ManifestAddendum=None,
    ValidateOnly=None, APIVersion=None):
    """
    This operation initiates the process of scheduling an upload or download of your data. You include in the request a manifest that describes the data transfer specifics. The response to the request includes a job ID, which you can use in other operations, a signature that you use to identify your storage device, and the address where you should ship your storage device.
    See also: AWS API Documentation

    :example: response = client.create_job(
        JobType='Import'|'Export',
        Manifest='string',
        ManifestAddendum='string',
        ValidateOnly=True|False,
        APIVersion='string'
    )

    :type JobType: string
    :param JobType: [REQUIRED] Specifies whether the job to initiate is an import or export job.

    :type Manifest: string
    :param Manifest: [REQUIRED] The UTF-8 encoded text of the manifest file.

    :type ManifestAddendum: string
    :param ManifestAddendum: For internal use only.

    :type ValidateOnly: boolean
    :param ValidateOnly: [REQUIRED] Validate the manifest and parameter values in the request but do not actually create a job.

    :type APIVersion: string
    :param APIVersion: Specifies the version of the client tool.

    :rtype: dict
    :return: {
        'JobId': 'string',
        'JobType': 'Import'|'Export',
        'Signature': 'string',
        'SignatureFileContents': 'string',
        'WarningMessage': 'string',
        'ArtifactList': [
            {
                'Description': 'string',
                'URL': 'string'
            },
        ]
    }

    :returns:
    (dict) -- Output structure for the CreateJob operation.
    JobId (string) -- A unique identifier which refers to a particular job.
    JobType (string) -- Specifies whether the job to initiate is an import or export job.
    Signature (string) -- An encrypted code used to authenticate the request and response, for example, "DV+TpDfx1/TdSE9ktyK9k/bDTVI=". Only use this value is you want to create the signature file yourself. Generally you should use the SignatureFileContents value.
    SignatureFileContents (string) -- The actual text of the SIGNATURE file to be written to disk.
    WarningMessage (string) -- An optional message notifying you of non-fatal issues with the job, such as use of an incompatible Amazon S3 bucket name.
    ArtifactList (list) -- A collection of artifacts.
    (dict) -- A discrete item that contains the description and URL of an artifact (such as a PDF).
    Description (string) -- The associated description for this object.
    URL (string) -- The URL for a given Artifact.

    """
    pass


def is_optimized(solc_arguments: str) ->bool:
    """
    Check if optimization are used

    :param solc_arguments:
    :return:
    """
    if solc_arguments:
        return '--optimize' in solc_arguments
    return False


@classmethod
def _preallocate_query(cls, event, stamp):
    """
        Return the query and update for preallocating a document.

        :param event: Event identifier string
        :param stamp: A UTC datetime indicating the document period
        :type event: str
        :type stamp: datetime.datetime

        """
    period = cls.config_period
    query = {'_id': cls.record_id(event, stamp)}
    update = {}
    for interval in cls.config_intervals:
        key = cls._map_interval(interval)
        query[key] = {'$exists': 0}
        update[key] = cls._preallocate_interval(period, interval, stamp)
    update[cls.meta.event] = event
    update[cls.meta.period] = cls._period(stamp)
    update = {'$set': update}
    return query, update


def field2read_only(field, **kwargs):
    """Return the dictionary of swagger field attributes for a dump_only field.

    :param Field field: A marshmallow field.
    :rtype: dict
    """
    attributes = {}
    if field.dump_only:
        attributes['readOnly'] = True
    return attributes


def _convert_string(key):
    """Convert OEIS String to Integer."""
    if isinstance(key, str):
        key = int(key.strip().upper().strip('A'))
    return key


def atse_reRegisterSchema(schema_id, schema):
    """ re-registering schema """


def str2bool(v):
    """ Convert string to a boolean value.
    References
    ----------
    https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python/715468#715468
    """
    return str(v).lower() in ('yes', 'true', 't', '1')


def getObject():
    """Return the object.
        """


@staticmethod
def wb_error_log(*params):
    """
            接受不定个数的参数, 并print出来
            """
    print('*' * 50)
    print('###wb-error-log: ')
    for param in params:
        print(param, end='')
    print()
    print('*' * 50)


def _defitsify_slice(slices):
    """
    Convert a FITS-style slice specification into a python slice.

    This means two things:
    + Subtract 1 from starting index because in the FITS
      specification arrays are one-based.
    + Do **not** subtract 1 from the ending index because the python
      convention for a slice is for the last value to be one less than the
      stop value. In other words, this subtraction is already built into
      python.
    + Reverse the order of the slices, because the FITS specification dictates
      that the first axis is the one along which the index varies most rapidly
      (aka FORTRAN order).
    """
    python_slice = []
    for a_slice in slices[::-1]:
        new_start = a_slice.start - 1 if a_slice.start is not None else None
        if new_start is not None and new_start < 0:
            raise ValueError('Smallest permissible FITS index is 1')
        if a_slice.stop is not None and a_slice.stop < 0:
            raise ValueError('Negative final index not allowed for FITS slice')
        new_slice = slice(new_start, a_slice.stop, a_slice.step)
        if (a_slice.start is not None and a_slice.stop is not None and
            a_slice.start > a_slice.stop):
            new_step = -1 if a_slice.step is None else -a_slice.step
            new_stop = None if a_slice.stop == 1 else a_slice.stop - 2
            new_slice = slice(new_start, new_stop, new_step)
        python_slice.append(new_slice)
    return python_slice


def fileSize(f):
    """returns the size of a file like object in bytes/octets"""
    offset = f.tell()
    f.seek(0, 2)
    size = f.tell()
    f.seek(offset)
    return size


def left_part_of(txt, sub_txt, n=1):
    """
    Return the left part before the nth of sub_txt appeared in txt.

    :param txt: text
    :param sub_txt: separate text
    :param n: the nth of sub_txt(default:1)
    """
    parts = txt.split(sub_txt)
    return sub_txt.join(parts[:n])


def snap_cursor_to_center():
    """Snap 3D cursor to the world origin

    """
    pass


def jacardCoefficient(a, b):
    """Return the Jacard coefficient of a and b.

    The jacard coefficient is defined as the overlap between two sets: the sum
    of all equal elements divided by the size of the sets.

    Mind that a and b must b in Hamming space, so every element must either be
    1 or 0.
    """
    if a.shape != b.shape:
        raise ValueError('Arrays must be of same shape')
    length = a.shape[0]
    a = a.astype(bool)
    b = b.astype(bool)
    return (a == b).sum() / length


def name_from_req(req):
    """
    Get the distribution name from a requirement.

    :type req: packaging.requirements.Requirement
    :rtype: str
    """
    return req.name if hasattr(req, 'name') else req.key


@classmethod
def fromOpenIDRequest(cls, request):
    """Instantiate a Request object from the arguments in a
        C{checkid_*} OpenID message
        """
    self = cls()
    args = request.message.getArgs(self.ns_uri)
    is_openid1 = request.message.isOpenID1()
    if args == {}:
        return None
    self.parseExtensionArgs(args, is_openid1)
    return self


def get_size():
    """Return a Deferred that will fire with the length of the data to be
        uploaded, in bytes. This will be called before the data is actually
        used, to compute encoding parameters.
        """


def d_price_d_rate(crv):
    """First derivative of each node in a discount curve to it's discount rates.

    The crv holds zero coupon bond prices in the form: z_i = exp(-r_i * ttm_i)
    """
    return -1 * crv.sched_maturity * crv.discount_factor(crv.sched_maturity)


def rho_to_V(rho, MW):
    """
    Return the molar volume (V) in m^3/mol given the density (rho) in
    kg/m^3 and molecular weight (MW) in g/mol.

    .. math::
        V = \\left(\\frac{1000 \\rho}{MW}\\right)^{-1}

    Parameters
    ----------
    rho : float
        Density, [kg/m^3]
    MW : float
        Molecular weight, [g/mol]

    Returns
    -------
    V : float
        Molar volume, [m^3/mol]

    Examples
    --------
    >>> V(652.9, 86.18)
    0.00013199571144126206

    """
    return MW / rho / 1000.0


def _normalizepath(path_segments):
    """
	Internal helper function for normalizing a path list.

	Should be equivalent to RFC2396, Section 5.2 (6) (c)-(f) with the exception
	of removing empty path_segments.
	"""
    new_path_segments = []
    l = len(path_segments)
    for i in range(l):
        segment = path_segments[i]
        if not segment or segment == '.':
            if i == l - 1:
                new_path_segments.append('')
        elif segment == '..' and len(new_path_segments) and new_path_segments[
            -1] != '..':
            new_path_segments.pop()
            if i == l - 1:
                new_path_segments.append('')
        else:
            new_path_segments.append(segment)
    return new_path_segments


def receive_v1_membership_report(group_state: 'GroupState'):
    """
    Received IGMP Version 1 Membership Report packet regarding group GroupState
    """
    group_state.group_state_logger.debug(
        'Querier Version1MembersPresent: receive_v1_membership_report')
    group_state.set_timer()
    group_state.set_v1_host_timer()


def describe_analysis_schemes(DomainName=None, AnalysisSchemeNames=None,
    Deployed=None):
    """
    Gets the analysis schemes configured for a domain. An analysis scheme defines language-specific text processing options for a text field. Can be limited to specific analysis schemes by name. By default, shows all analysis schemes and includes any pending changes to the configuration. Set the Deployed option to true to show the active configuration and exclude pending changes. For more information, see Configuring Analysis Schemes in the Amazon CloudSearch Developer Guide .
    See also: AWS API Documentation

    :example: response = client.describe_analysis_schemes(
        DomainName='string',
        AnalysisSchemeNames=[
            'string',
        ],
        Deployed=True|False
    )

    :type DomainName: string
    :param DomainName: [REQUIRED]
            The name of the domain you want to describe.

    :type AnalysisSchemeNames: list
    :param AnalysisSchemeNames: The analysis schemes you want to describe.
            (string) --Names must begin with a letter and can contain the following characters: a-z (lowercase), 0-9, and _ (underscore).

    :type Deployed: boolean
    :param Deployed: Whether to display the deployed configuration (true ) or include any pending changes (false ). Defaults to false .

    :rtype: dict
    :return: {
        'AnalysisSchemes': [
            {
                'Options': {
                    'AnalysisSchemeName': 'string',
                    'AnalysisSchemeLanguage': 'ar'|'bg'|'ca'|'cs'|'da'|'de'|'el'|'en'|'es'|'eu'|'fa'|'fi'|'fr'|'ga'|'gl'|'he'|'hi'|'hu'|'hy'|'id'|'it'|'ja'|'ko'|'lv'|'mul'|'nl'|'no'|'pt'|'ro'|'ru'|'sv'|'th'|'tr'|'zh-Hans'|'zh-Hant',
                    'AnalysisOptions': {
                        'Synonyms': 'string',
                        'Stopwords': 'string',
                        'StemmingDictionary': 'string',
                        'JapaneseTokenizationDictionary': 'string',
                        'AlgorithmicStemming': 'none'|'minimal'|'light'|'full'
                    }
                },
                'Status': {
                    'CreationDate': datetime(2015, 1, 1),
                    'UpdateDate': datetime(2015, 1, 1),
                    'UpdateVersion': 123,
                    'State': 'RequiresIndexDocuments'|'Processing'|'Active'|'FailedToValidate',
                    'PendingDeletion': True|False
                }
            },
        ]
    }

    :returns:
    RequiresIndexDocuments : the option's latest value will not be deployed until  IndexDocuments has been called and indexing is complete.
    Processing : the option's latest value is in the process of being activated.
    Active : the option's latest value is completely deployed.
    FailedToValidate : the option value is not compatible with the domain's data and cannot be used to index the data. You must either modify the option value or update or remove the incompatible documents.

    """
    pass


def try_flatten(sequence):
    """
    trying to flatten a sequence;
    - if it is none or empty, return none
    - if len(it)==1, return it's only element(FLATTEN)
    - if len(it)>1, return itself untouched
    :param sequence:
    :return:
    """
    if sequence is None or len(sequence) == 0:
        return None
    if len(sequence) == 1:
        return tuple(sequence)[0]
    return sequence


def p_prim_expr_5(p):
    """PrimaryExpr : FunctionCall"""
    p[0] = p[1]


def stamp_expt_weight(base_feature, atlas, smoothing_param, node_size,
    weight_method):
    """Constructs a string to uniquely identify a given feature extraction method."""
    expt_id = '{}_{}_smoothing{}_size{}_edgeweight_{}'.format(base_feature,
        atlas, smoothing_param, node_size, weight_method)
    return expt_id


def opsite(siteli, tsl=0):
    """
    open a list of websites.
    siteli must be a list, each element of which is one of the websites that you want to open in one single web browser.
    """
    import time
    import numpy as np
    from selenium import webdriver
    osite = webdriver.Chrome()
    n = 1
    for i in siteli:
        osite.get(i)
        time.sleep(tsl * np.random.rand() + 0.002)
        osite.execute_script('window.open()')
        handles = osite.window_handles
        osite.switch_to.window(handles[n])
        n += 1
    osite.close()
    osite.switch_to.window(handles[0])


@classmethod
def get_executable(cls):
    """
        Return the path to the executable code for this pipeline stage.
        """
    return cls.pipeline_stages[cls.name][1]


def is_callable(request):
    """
    Проверка вызова метода.

    Когда в POST запросе есть ключ 'jsonData' или 'method', то это вызов метода.
    Когда в GET запросе есть ключ 'method', то это тоже вызов метода.
    Иначе - это просмотр документации.
    """
    if request.method == 'GET':
        if 'method' in request.GET:
            return True
    else:
        req = request.POST
        if 'jsonData' in req or 'method' in req:
            return True
    return False


def _make_argument_list(*args, **kwargs):
    """

    Turn pythonic list of positional arguments and keyword arguments
    into a list of strings.

    N.B.: subprocess.Popen works best with each argument as item in
    list, not as a single string. Otherwise it breaks on starlink
    commands that are really python scripts.

    """
    output = []
    for i in args:
        output.append(str(i) + ' ')
    for key, value in kwargs.items():
        if key[-1] == '_':
            key = key[:-1]
        output.append(str(key) + '=' + str(value))
    output = [i.rstrip() for i in output]
    return output


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

    The ".dev0" means dirty.

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


@classmethod
def create_module(cls, spec):
    """Create a module using the default machinery."""
    return None


def _file_string_binary_search_any(fh, string):
    """
    perform a binary_search for a string in a sorted text file
    it will quickly return any match, not necessarily the first or the last in the file
    """
    found = None
    fh.seek(0)
    line = fh.readline()
    if line.startswith(string):
        found = line
    else:
        lo = 0
        fh.seek(0, 2)
        hi = fh.tell()
        while hi - lo > 1:
            mid = (hi + lo) // 2
            fh.seek(mid, 0)
            fh.readline()
            line = fh.readline()
            if line.startswith(string):
                found = line
                break
            if string > line:
                lo = mid
            else:
                hi = mid
        if found is None:
            fh.seek(hi)
            line = fh.readline()
            if line.startswith(string):
                found = line
    if found is not None:
        return found
    return None


def mark_sharp(clear: bool=False, use_verts: bool=False):
    """(Un)mark selected edges as sharp

    :param clear: Clear
    :type clear: bool
    :param use_verts: Vertices, Consider vertices instead of edges to select which edges to (un)tag as sharp
    :type use_verts: bool
    """
    pass


def insert(key):
    """Add the key (value) to the set.

        If the key was already in the set, return 0, otherwise return 1.
        """


def parent_template_name(parent_arg):
    """
    Given the argument of an {% extends %} tag, return the name of the template to which it links

    If the argument is a variable, return "__unknown__".  This is a static analyser of the template
    hierarchy, and cannot know all possible values that might be provided.
    """
    parent = parent_arg.strip('"\'')
    if parent == parent_arg:
        parent = '__unknown__'
    return parent


def to_league_name(league_name):
    """Maps league name to the league name used by Understat for ease of use.
    """
    league_mapper = {'epl': 'EPL', 'la_liga': 'La_liga', 'bundesliga':
        'Bundesliga', 'serie_a': 'Serie_A', 'ligue_1': 'Ligue_1', 'rfpl':
        'RFPL'}
    try:
        return league_mapper[league_name]
    except KeyError:
        return league_name


def _rfind(stack, elem, default=None):
    """
    Like _find but starts from the back.
    """
    for i in reversed(range(len(stack))):
        if stack[i] == elem:
            return i
    else:
        return default


def extrude_region_shrink_fatten(MESH_OT_extrude_region=None,
    TRANSFORM_OT_shrink_fatten=None):
    """Extrude region and move result

    :param MESH_OT_extrude_region: Extrude Region, Extrude region of faces
    :param TRANSFORM_OT_shrink_fatten: Shrink/Fatten, Shrink/fatten selected vertices along normals
    """
    pass


def get_function_configuration(FunctionName=None, Qualifier=None):
    """
    Returns the configuration information of the Lambda function. This the same information you provided as parameters when uploading the function by using  CreateFunction .
    If you are using the versioning feature, you can retrieve this information for a specific function version by using the optional Qualifier parameter and specifying the function version or alias that points to it. If you don't provide it, the API returns information about the $LATEST version of the function. For more information about versioning, see AWS Lambda Function Versioning and Aliases .
    This operation requires permission for the lambda:GetFunctionConfiguration operation.
    See also: AWS API Documentation

    Examples
    This operation retrieves a Lambda function's event source mapping
    Expected Output:

    :example: response = client.get_function_configuration(
        FunctionName='string',
        Qualifier='string'
    )

    :type FunctionName: string
    :param FunctionName: [REQUIRED]
            The name of the Lambda function for which you want to retrieve the configuration information.
            You can specify a function name (for example, Thumbnail ) or you can specify Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail ). AWS Lambda also allows you to specify a partial ARN (for example, account-id:Thumbnail ). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 characters in length.

    :type Qualifier: string
    :param Qualifier: Using this optional parameter you can specify a function version or an alias name. If you specify function version, the API uses qualified function ARN and returns information about the specific function version. If you specify an alias name, the API uses the alias ARN and returns information about the function version to which the alias points.
            If you don't specify this parameter, the API uses unqualified function ARN, and returns information about the $LATEST function version.

    :rtype: dict
    :return: {
        'FunctionName': 'string',
        'FunctionArn': 'string',
        'Runtime': 'nodejs'|'nodejs4.3'|'nodejs6.10'|'java8'|'python2.7'|'python3.6'|'dotnetcore1.0'|'nodejs4.3-edge',
        'Role': 'string',
        'Handler': 'string',
        'CodeSize': 123,
        'Description': 'string',
        'Timeout': 123,
        'MemorySize': 123,
        'LastModified': 'string',
        'CodeSha256': 'string',
        'Version': 'string',
        'VpcConfig': {
            'SubnetIds': [
                'string',
            ],
            'SecurityGroupIds': [
                'string',
            ],
            'VpcId': 'string'
        },
        'DeadLetterConfig': {
            'TargetArn': 'string'
        },
        'Environment': {
            'Variables': {
                'string': 'string'
            },
            'Error': {
                'ErrorCode': 'string',
                'Message': 'string'
            }
        },
        'KMSKeyArn': 'string',
        'TracingConfig': {
            'Mode': 'Active'|'PassThrough'
        }
    }

    :returns:
    (string) --

    """
    pass


def getListForAddress(address):
    """Returns an IMailingList object corresponding to the address given,
           or None iuf no list is found."""


def getValue(token):
    """Return a value for a given identifier token

        LookupError is raised if there isn't a value in the source.
        """


def p_expr_stmt_star_1(p):
    """expr_stmt_star : EQUAL yield_expr"""
    p[0] = [p[2]]


@classmethod
def _get(cls):
    """Function returns the instance"""
    return cls.instance


@staticmethod
def from_json(json_response):
    """Return a submission object from the json response."""
    submission = json_response[0]['data']['children'][0]
    submission.comments = json_response[1]['data']['children']
    return submission


def write_m3u_playlist(filename, files):
    """
    Write an M3U playlist named filename containing files.
    """
    out = open(filename, 'w', encoding='windows-1252')
    for f in files:
        out.write(f)
        out.write('\n')
    out.close()


@staticmethod
def _item_to_section_key(item):
    """Converts an item description to a section-key pair.

        @param item: the item to be converted
        @return: if C{item} contains a period (C{.}), it is splitted into two parts
          at the first period, then the two parts are returned, so the part before
          the period is the section. If C{item} does not contain a period, the
          section is assumed to be C{general}, and the second part of the returned
          pair contains C{item} unchanged"""
    if '.' in item:
        section, key = item.split('.', 1)
    else:
        section, key = 'general', item
    return section, key


def get_google_query_url(query):
    """Get Google query URL."""
    base_url = 'www.google.com'
    if not query:
        return 'http://{0}'.format(base_url)
    return 'http://{0}/search?q={1}'.format(base_url, query)


def identical(image):
    """
    Return input image unchanged.

    :param numpy.array image: Should be a numpy array of an image.
    :return: Same as input
    :rtype: Same as input
    """
    return image


def encode_version(major: int, minor: int):
    """
    Encodes the version number into something that the binary ZIP format
    understands.

    Parameters
    ----------
    major
        Major version number (must not exceed 6553)
    minor
        Minor version number (must not exceed 9)

    Returns
    -------
    Encoded version number

    Raises
    ------
    ValueError
        If the major or minor values are inadequate
    """
    if major < 0 or minor < 0:
        raise ValueError(f'Negative version number was provided')
    if minor >= 10:
        raise ValueError(f'Minor "{minor}" cannot exceed 10.')
    version = major * 10 + minor
    if version > 65535:
        raise ValueError(f'Version {major}.{minor} is too high to be encoded')
    return version


def array_offset(x):
    """Get offset of array data from base data in bytes."""
    if x.base is None:
        return 0
    base_start = x.base.__array_interface__['data'][0]
    start = x.__array_interface__['data'][0]
    return start - base_start


def get_oshape_of_gather_nd_op(dshape, ishape):
    """Given data and index shapes, get the output `NDArray` shape.
    This basically implements the infer shape logic of op gather_nd."""
    assert len(dshape) > 0 and len(ishape) > 0
    oshape = list(ishape[1:])
    if ishape[0] < len(dshape):
        oshape.extend(dshape[ishape[0]:])
    return tuple(oshape)


def commitctx(ctx, error=False, origctx=None):
    """Commit a commitctx instance to the repository."""


def value_from_atts_elem(elem):
    """ value_from_atts_elem takes an attribute element and retuns a string value

    :type elem: dict
    :param elem: Element from the attributes map

    :rtype: str
    :return: A string rep of the element value
    """
    if elem.get('string_value') is not None:
        return elem.get('string_value').get('value')
    elif elem.get('int_value') is not None:
        return str(elem.get('int_value'))
    elif elem.get('bool_value') is not None:
        return str(elem.get('bool_value'))
    elif elem.get('double_value') is not None:
        return str(elem.get('double_value').get('value'))
    return ''


def _consume_unicode_range(css, pos):
    """Return (range, new_pos)

    The given pos is assume to be just after the '+' of 'U+' or 'u+'.

    """
    length = len(css)
    start_pos = pos
    max_pos = min(pos + 6, length)
    while pos < max_pos and css[pos] in '0123456789abcdefABCDEF':
        pos += 1
    start = css[start_pos:pos]
    start_pos = pos
    while pos < max_pos and css[pos] == '?':
        pos += 1
    question_marks = pos - start_pos
    if question_marks:
        end = start + 'F' * question_marks
        start = start + '0' * question_marks
    elif pos + 1 < length and css[pos] == '-' and css[pos + 1
        ] in '0123456789abcdefABCDEF':
        pos += 1
        start_pos = pos
        max_pos = min(pos + 6, length)
        while pos < max_pos and css[pos] in '0123456789abcdefABCDEF':
            pos += 1
        end = css[start_pos:pos]
    else:
        end = start
    return int(start, 16), int(end, 16), pos


def bytes2human(n, format='%(value).1f%(symbol)s'):
    """Used by various scripts. See:
    http://goo.gl/zeJZl

    >>> bytes2human(10000)
    '9.8K'
    >>> bytes2human(100001221)
    '95.4M'
    """
    symbols = 'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
    prefix = {}
    for i, s in enumerate(symbols[1:]):
        prefix[s] = 1 << (i + 1) * 10
    for symbol in reversed(symbols[1:]):
        if n >= prefix[symbol]:
            value = float(n) / prefix[symbol]
            return format % locals()
    return format % dict(symbol=symbols[0], value=n)


def delete_usercache(apps, schema_editor):
    """
    Deletes the usercache table for all users
    """
    Usercache = apps.get_model('core', 'Usercache')
    for cache in Usercache.objects.all():
        cache.delete()


def umls_to_snomed(cdb, pickle_path):
    """ Map UMLS CDB to SNOMED concepts
    """
    import pickle
    data = pickle.load(open(pickle_path, 'rb'))
    for key in data.keys():
        cui = str(key)
        for snomed_cui in data[key]:
            if 'S-' in str(snomed_cui):
                snomed_cui = str(snomed_cui)
            else:
                snomed_cui = 'S-' + str(snomed_cui)
            if key in cdb.cui2info:
                if 'snomed' in cdb.cui2info[key]:
                    cdb.cui2info[cui]['snomed'].append(snomed_cui)
                else:
                    cdb.cui2info[cui]['snomed'] = [snomed_cui]


def p_step_1(p):
    """Step : axis DOUBLECOLON NodeTest PredicateList"""
    p[0] = 'step', p[1], p[3], p[4]


def get_dates_umich():
    """
    These are all the selectable dates in the UMich long term robotics dataset.

    :return: list -- all of the available dates that can be downloaded
    """
    dates = []
    dates.append('2012-01-08')
    dates.append('2012-01-15')
    dates.append('2012-01-22')
    dates.append('2012-02-02')
    dates.append('2012-02-04')
    dates.append('2012-02-05')
    dates.append('2012-02-12')
    dates.append('2012-02-18')
    dates.append('2012-02-19')
    dates.append('2012-03-17')
    dates.append('2012-03-25')
    dates.append('2012-03-31')
    dates.append('2012-04-29')
    dates.append('2012-05-11')
    dates.append('2012-05-26')
    dates.append('2012-06-15')
    dates.append('2012-08-04')
    dates.append('2012-08-20')
    dates.append('2012-09-28')
    dates.append('2012-10-28')
    dates.append('2012-11-04')
    dates.append('2012-11-16')
    dates.append('2012-11-17')
    dates.append('2012-12-01')
    dates.append('2013-01-10')
    dates.append('2013-02-23')
    dates.append('2013-04-05')
    return dates


def _linear_range_transform(range_, factor, asymmetry=0.0):
    """Return a range that is `factor` larger than `range_`.

    The amount by which the extension is done is the direction of
    each boundary is controlled by a float `asymmetry`, which should
    be between -1 and 1. An `asymmetry` of 0 will extend the range
    symmetrically in the direction of both boundaries. An `asymmetry`
    of -1 (+1) will extend the range in the direction of the first
    (second) boundary, leaving the other boundary unchanged."""
    assert len(range_) == 2
    assert factor > 0.0
    assert -1.0 <= asymmetry <= 1.0
    _m = 0.5 * (range_[1] + range_[0])
    _d = 0.5 * (range_[1] - range_[0])
    _asymm_factor = 1.0 + asymmetry
    return _m - factor * (2.0 - _asymm_factor
        ) * _d, _m + factor * _asymm_factor * _d


def clamp(n, lower, upper):
    """
    Restricts the given number to a lower and upper bound (inclusive)

    :param n:     input number
    :param lower: lower bound (inclusive)
    :param upper: upper bound (inclusive)
    :return:      clamped number
    """
    if lower > upper:
        lower, upper = upper, lower
    return max(min(upper, n), lower)


def load_win32file(finder, module):
    """the win32file module implicitly loads the pywintypes and win32timezone
       module; make sure this happens."""
    finder.IncludeModule('pywintypes')
    finder.IncludeModule('win32timezone')


def session_draw_bis_melty(sessions_id, weblog, weblog_columns_dict):
    """
    Draw the graph of sessions with sessions_id given in entry
    """
    from graph_tool.all import Graph
    from graph_tool.all import graph_draw
    session = weblog[weblog.session_id == sessions_id]
    session = session.rename(index=str, columns={weblog_columns_dict[
        'requested_page_column']: 'requested_page', weblog_columns_dict[
        'referrer_page_column']: 'referrer_page'})
    s_pages = session[['requested_page', 'requested_external']]
    s_pages_ref = session[['referrer_page', 'referrer_external']]
    s_pages_ref = s_pages_ref.rename(index=str, columns={'referrer_page':
        'requested_page', 'referrer_external': 'requested_external'})
    s_pages = s_pages.append(s_pages_ref)
    s_pages.drop_duplicates(subset='requested_page', inplace=True)
    g = Graph()
    v = {}
    halo = g.new_vertex_property('bool')
    for row in s_pages.itertuples():
        v[row.requested_page] = g.add_vertex()
        if row.requested_external:
            halo[v[row.requested_page]] = True
        else:
            halo[v[row.requested_page]] = False
    session.apply(lambda x: g.add_edge(v[x.referrer_page], v[x.
        requested_page]), axis=1)
    graph_draw(g, vertex_halo=halo, output='./_session' + str(sessions_id) +
        '.png')
    return


def _lemmatize_wrapper_general_patternlib(row, lemmatizer):
    """Wrapper function to lemmatize texts using ``pattern`` package."""
    tok, pos = row
    if pos.startswith('NP'):
        return lemmatizer.singularize(tok)
    elif pos.startswith('V'):
        return lemmatizer.conjugate(tok, lemmatizer.INFINITIVE)
    elif pos.startswith('ADJ') or pos.startswith('ADV'):
        return lemmatizer.predicative(tok)
    return tok


def get_names(query):
    """
    Extracts the function and class name from a query string.
    The query string is in the format `Class.function`.
    Functions starts with a lower case letter and classes starts
    with an upper case letter.

    Arguments:
        query: The string to process.

    Returns:
        tuple: A tuple containing the class name, function name,
               and type. The class name or function name can be empty.

    """
    funcname = ''
    classname = ''
    dtype = ''
    members = query.split('.')
    if len(members) == 1:
        if members[0] == '':
            dtype = 'module'
        elif members[0][0].isupper():
            classname = query
            dtype = 'class'
        else:
            funcname = query
            dtype = 'function'
    elif len(members) == 2:
        classname = members[0]
        funcname = members[1]
        dtype = 'method'
    else:
        raise ValueError('Unable to parse: `%s`' % query)
    return classname, funcname, dtype


def _validate_param_grid(param_grid):
    """Check if the parameter values are valid

    This basically does the same checks as in the constructor of the
    :class:`~.core.GenSVM` class, but for the entire parameter grid.

    """
    conditions = {'p': lambda x: 1.0 <= x <= 2.0, 'kappa': lambda x: x > -
        1.0, 'lmd': lambda x: x > 0, 'epsilon': lambda x: x > 0, 'gamma':
        lambda x: x != 0, 'weights': lambda x: x in ['unit', 'group']}
    for param in conditions:
        if param in param_grid:
            if not all(map(conditions[param], param_grid[param])):
                raise ValueError('Invalid value in grid for parameter: %s.' %
                    param)


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 delete_health_check(HealthCheckId=None):
    """
    Deletes a health check.
    See also: AWS API Documentation

    :example: response = client.delete_health_check(
        HealthCheckId='string'
    )

    :type HealthCheckId: string
    :param HealthCheckId: [REQUIRED]
            The ID of the health check that you want to delete.

    :rtype: dict
    :return: {}

    """
    pass


def _get_colorbar_properties(old_artist):
    """
    Returns the parameters for recreating the colorbar.

    Parameters
    ----------
    old_artist : matplotlib.artist.Artist
        The artist whose colorbar to copy.

    Returns
    -------
    colorbar : dict
        Dictionary of parameters.
    """
    cb = getattr(old_artist, 'colorbar')
    if cb is not None:
        colorbar = {'show': True, 'orientation': cb.orientation}
        if hasattr(cb, '_label') and cb._label:
            colorbar['label'] = cb._label
        return colorbar
    else:
        return {}


def product(v1, v2):
    """
    Calculate the scalar product of two vectors
    """
    return v1[0] * v2[0] + v1[1] * v2[1]


def _parse_path(path):
    """
    This function is used to parse a path string into a sequence.  Any empty strings
    are discarded.

    :param path: the string to parse.
    :return: the resulting sequence
    """
    result = []
    if path.startswith('#/'):
        path = path[2:]
    for item in path.split('/'):
        if len(item) > 0:
            if item[:1] == '[' and item[-1:] == ']':
                result.append(int(item[1:-1]))
            else:
                result.append(item)
    return result


def message_variable(func):
    """
    Decorator which marks a function as being safe to use as a message variable.
    """
    func.is_message_variable = True
    return func


def callRemoteOnly(name, *args, **kwargs):
    """Invoke a method on the remote object with which I am associated.

        This form is for one-way messages that do not require results or even
        acknowledgement of completion. I do not wait for the method to finish
        executing. The remote end will be instructed to not send any
        response. There is no way to know whether the method was successfully
        delivered or not.

        I always return None.
        """


def check_diff(repo):
    """Checking for changed files"""
    is_diff = False
    if repo.git.diff() != '':
        is_diff = True
    return is_diff


def lambd_CO2_HSO4_HMW84(T, P):
    """n-c: carbon-dioxide bisulfate [HMW84]."""
    lambd = -0.003
    valid = T == 298.15
    return lambd, valid


def ms_format(milliseconds: float) ->str:
    """Slightly smart formating of an elapsed time
    """
    assert milliseconds >= 0
    if milliseconds < 1:
        return f'{milliseconds:.3f}ms'
    if milliseconds < 1000:
        return f'{milliseconds:.2f}ms'
    return f'{milliseconds / 1000:.3f}sec'


def write_vec_extern(f, vec, name, vec_type):
    """
    Write vector prototype to file
    """
    f.write('extern %s %s[%d];\n' % (vec_type, name, len(vec)))


def ticklabel_format(value):
    """
    Pick formatter for ytick labels. If possible, just print out the
    value with the same precision as the branch value. If that doesn't
    fit, switch to scientific format.
    """
    bvs = str(value)
    if len(bvs) < 7:
        fp = len(bvs) - (bvs.index('.') + 1) if '.' in bvs else 0
        return f'%.{fp}f'
    else:
        return '%.1e'


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