def material_drop(object: str='Object', material: str='Material'):
    """Drag material to object in Outliner

    :param object: Object, Target Object
    :type object: str
    :param material: Material, Target Material
    :type material: str
    """
    pass


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

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


def find_item_class(player, classobj, locations=None, ignore_dark=False):
    """
    Find the first item that is an instance of a specific class in the provided
    locations

    :param text_game_maker.player.player.Player player: player object
    :param str name: name of item to find
    :param [[text_game_maker.game_objects.items.Item]] locations: location        lists to search
    :return: found item (None if no matching item is found)
    :rtype: text_game_maker.items.Item
    """
    if not ignore_dark and not player.can_see():
        return None
    if locations is None:
        locations = player.current.items.values()
    for itemlist in locations:
        for item in itemlist:
            if isinstance(item, classobj):
                return item
    return None


def set_flags(backend, flags):
    """Set proba on backend"""
    resets = list()
    if 'layer' in backend.__class__.__name__.lower():
        updates = [backend] + backend.learners
    elif 'group' in backend.__class__.__name__.lower():
        updates = backend.learners
    elif not isinstance(backend, list):
        updates = [backend]
    else:
        updates = backend
    for obj in updates:
        _res = dict()
        for key, val in flags.items():
            if hasattr(obj, key):
                _res[key] = getattr(obj, key)
                setattr(obj, key, val)
        resets.append((obj, _res))
    return resets


@staticmethod
def _truthy(a):
    """Check that argument evaluates to True according to core JsonLogic."""
    return bool(a)


def untitlize(s):
    """FooBar -> fooBar"""
    if not s:
        return s
    else:
        return '{}{}'.format(s[0].lower(), s[1:])


def set_default_order(kwargs):
    """
    Set order parameter in kwargs for scikit-image functions.

    Default order is 1, which performs a linear interpolation of pixel values
    when images are rotated, resized and sheared. This is fine for images
    but causes unwanted pixel values in masks. This function set the default
    order to 0, which disables the interpolation.

    :param kwargs kwargs: Dictionary with keyword arguments.
    """
    if 'order' not in kwargs:
        kwargs['order'] = 0


@classmethod
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
    "\n        Return the ASCII string parsed from *stream_rdr* at *value_offset*.\n        The length of the string, including a terminating '\x00' (NUL)\n        character, is in *value_count*.\n        "
    return stream_rdr.read_str(value_count - 1, value_offset)


@classmethod
def ordered(cls, objs):
    """
        Returns the iterable ordered the correct way, this is a class method
        because we don"t know what the type of the iterable will be.
        """
    objs = list(objs)
    objs.sort(key=lambda o: o.latest_message.sent_at, reverse=True)
    return objs


def buildingname(ddtt):
    """return building name"""
    idf = ddtt.theidf
    building = idf.idfobjects['building'.upper()][0]
    return building.Name


@staticmethod
def sign(tensor):
    """Computes the element-wise sign of the given input tensor.

        Parameters
        ----------
        tensor : tensor

        Returns
        -------
        out : tensor
        """
    raise NotImplementedError


@classmethod
def join(cls, table, on, join_type=None):
    """
        Adds a join clause to the current query.
        """
    if type(on) == tuple:
        on = cls.__db__.get_table(on[0]), on[1]
    cls.__query__.join(cls.__db__.get_table(table), on, join_type)
    return cls


@classmethod
def is_pre_started_status(cls, status):
    """
        Returns a boolean if the status passed is prior to "started" state.
        """
    return status in [cls.created, cls.download_software_clicked, cls.
        ready_to_start]


def get_variable_changes(older, newer):
    """Generate sequence of changes between two dictionaries

    Expects to have two variable/namespace dictionaries
    passed as arguments, and it yields the differences
    assuming the first is the older and the second is
    the newer.
    """
    for name in sorted(newer.keys()):
        if name not in older or older[name] != newer[name]:
            yield name, newer[name]


def _atomise_author(author):
    """
    Convert author from whatever it is to a dictionary representing an
    atom:Person construct.
    """
    if type(author) is dict:
        return author
    elif author.startswith('http://') or author.startswith('www'):
        return {'uri': author}
    elif '@' in author and '.' in author:
        return {'email': author}
    else:
        return {'name': author}


def factorial(num):
    """
    Returns the factorial of the input number. Factorial of a number less than or equals to 1 will be returned as 1
    """
    if num < 1:
        print('Input must be >= 1')
    f = 1
    while num > 1:
        f = f * num
        num = num - 1
    return f


@classmethod
def get_name(cls):
    """ Returns the name of the supplier.
		"""
    return 'mnist'


@classmethod
def from_pagarme_dict(cls, django_user_id, pagarme_transaction):
    """
        Creates UserPaymentProfile from pagarme api json transaction
        :param django_user_id: django user id
        :param pagarme_transaction: pagarme api transaction dict
        :return: UserPaymentProfile
        """
    customer = pagarme_transaction['customer']
    document = customer['documents'][-1]
    address = pagarme_transaction['billing']['address']
    return cls(user_id=django_user_id, customer_type=customer['type'],
        costumer_country=customer['country'], document_number=document[
        'number'], document_type=document['type'], name=customer['name'],
        email=customer['email'], phone=customer['phone_numbers'][-1].
        replace('+', ''), street=address['street'], complementary=address[
        'complementary'], street_number=address['street_number'],
        neighborhood=address['neighborhood'], city=address['city'], state=
        address['state'], zipcode=address['zipcode'], address_country=
        address['country'])


def switchUnits():
    """Function to switch between unit systems"""
    global englishUnits
    englishUnits = not englishUnits
    if englishUnits:
        print('Using English units')
    else:
        print('Using SI Units')


def context_items(context, min=None, max=None, limit=100):
    """Filter (key, IStatusUpdate) items by IMicroblogContext object.
        min and max are longint IStatusUpdate.id keys.
        limit returns [:limit] most recent items
        context <object> filters on StatusUpdates keyed to that context's UUID.
        """


@classmethod
def disable(cls):
    """Disables animation domain notifications.
        """
    return cls.build_send_payload('disable', {}), None


def anim_to_html(anim):
    """
    Function to help with inline animations in ipython notebooks:

    >>> import exocartographer.visualize as ev
    >>> from matplotlib import animation
    >>> from IPython.display import HTML

    >>> animation.Animation._repr_html_ = ev.anim_to_html

    This first appeared as a blog post on Pythonic Perambulations:
    https://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
    """
    from tempfile import NamedTemporaryFile
    VIDEO_TAG = """<video controls>
     <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
     Your browser does not support the video tag.
    </video>"""
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=30, extra_args=['-vcodec', 'libx264'])
            video = open(f.name, 'rb').read()
        anim._encoded_video = video.encode('base64')
    return VIDEO_TAG.format(anim._encoded_video)


def unsupported(function):
    """Decorator to mark player function as unsupported."""
    function.__is_supported__ = False
    return function


@classmethod
def module_repr(cls, module):
    """Return repr for the module.

        The method is deprecated.  The import machinery does the job itself.

        """
    return '<module {!r} (namespace)>'.format(module.__name__)


def uniquify(l):
    """Takes a list `l` and returns a list of the unique elements in `l`
    in the order in which they appeared.

    """
    mem = set([])
    out = []
    for e in l:
        if e not in mem:
            mem.add(e)
            out.append(e)
    return out


def float_range(start=0, stop=None, step=1):
    """Much like the built-in function range, but accepts floats"""
    while start < stop:
        yield float(start)
        start += step


def filter_contacts(cf, source_sel, target_sel, filter_sel=('target',
    'distance')):
    """
    Filter contact dataframe for multiple occurrences of source-target
    selections based on a filter criterion.

    :param cf:          Contact DataFrame
    :type cf:           :pandas:DataFrame
    :param source_sel:  Column label for source selection
    :type source_sel:   :py:str
    :param target_sel:  Column label for target selection
    :type target_sel:   :py:sel
    :param filter_sel:  Column label to sort selection on
                        and filter all but the first row

    :return:            Filtered contact DataFrame
    :rtype:             :pandas:DataFrame
    """
    exclude_index = []
    for pair in (('source', 'target'), ('target', 'source')):
        source_mult = cf[pair[0], source_sel].value_counts()
        source_mult = set(source_mult[source_mult > 1].index)
        target_mult = cf[pair[1], target_sel].value_counts()
        target_mult = set(target_mult[target_mult > 1].index)
        for a in source_mult:
            for b in target_mult:
                sel = cf[(cf[pair[0], source_sel] == a) & (cf[pair[1],
                    target_sel] == b)]
                if len(sel) > 1:
                    exclude_index.extend(list(sel.sort_values(by=filter_sel
                        ).iloc[1:].index))
    return cf.loc[~cf.index.isin(exclude_index)]


def _LDRSW_register(cpu, reg_op, mem_op):
    """
        LDRSW (register).

        :param reg_op: destination register.
        :param mem_op: memory.
        """
    cpu._ldr_str_register(reg_op, mem_op, ldr=True, size=32, sextend=True)


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

        :param DeviceApprovalsChangeUnlinkActionType val:
        :rtype: EventType
        """
    return cls('device_approvals_change_unlink_action', val)


def set_epsilon(e):
    """Sets the value of the fuzz factor used in numeric expressions.

    # Arguments
        e: float. New value of epsilon.

    # Example
    ```python
        >>> from keras import backend as K
        >>> K.epsilon()
        1e-07
        >>> K.set_epsilon(1e-05)
        >>> K.epsilon()
        1e-05
    ```
    """
    global _EPSILON
    _EPSILON = float(e)


def _check_resources(name, expr, resources):
    """Validate that the expression and resources passed match up.

    Parameters
    ----------
    name : str
        The name of the argument we are checking.
    expr : Expr
        The potentially bound expr.
    resources
        The explicitly passed resources to compute expr.

    Raises
    ------
    ValueError
        If the resources do not match for an expression.
    """
    if expr is None:
        return
    bound = expr._resources()
    if not bound and resources is None:
        raise ValueError('no resources provided to compute %s' % name)
    if bound and resources:
        raise ValueError(
            'explicit and implicit resources provided to compute %s' % name)


def add_build_arguments(parser):
    """Add argparse parser arguments used in building."""
    parser.add_argument('--prettify', action='store_false', help=
        'prettify output')
    parser.add_argument('--configset', nargs='*', default=[], help=
        'config sets')
    parser.add_argument('config', nargs='*', help='config variables (FOO=bar)')
    return parser


def _headers_to_native_string(headers):
    """
    A temporary shim to convert received headers to native strings, to match
    the behaviour of httplib. We will reconsider this later in the process.
    """
    for n, v in headers:
        if not isinstance(n, str):
            n = n.decode('latin1')
        if not isinstance(v, str):
            v = v.decode('latin1')
        yield n, v


def to_zero_index_slice(s):
    """Convert 1-based to 0-based position.

    Parameters
    ----------
    s : slice

    Returns
    -------
    slice

    Example
    -------
    Assumes that values are both positive or both negative.
    Coordinate values are positive:
    >>> s1 = slice(1, 5)
    >>> to_zero_index_slice(s1)
    slice(0, 5, None)
    >>> s2 = slice(10, 50)
    >>> to_zero_index_slice(s2)
    slice(9, 50, None)

    Coordinate values are negative:
    >>> s3 = slice(-1, -5)
    >>> to_zero_index_slice(s3)
    slice(-1, -6, None)
    >>> s4 = slice(-5, -10)
    >>> to_zero_index_slice(s4)
    slice(-5, -11, None)

    """
    if s.start < 0:
        return slice(s.start, s.stop - 1, s.step)
    return slice(s.start - 1, s.stop, s.step)


def dictvalue(dct, key, defvalue=None):
    """return the value of the dct given the key.
    return default value if key does not exist"""
    return dct.setdefault(key, defvalue)


def _format_eval_result(value, show_stdv=True):
    """Format metric string."""
    if len(value) == 4:
        return "%s's %s: %g" % (value[0], value[1], value[2])
    elif len(value) == 5:
        if show_stdv:
            return "%s's %s: %g + %g" % (value[0], value[1], value[2], value[4]
                )
        else:
            return "%s's %s: %g" % (value[0], value[1], value[2])
    else:
        raise ValueError('Wrong metric value')


def stringify(value):
    """ Takes variously formatted hex values and outputs them in simple string format """
    out = ''
    if value:
        out = (hex(value) if isinstance(value, int) else value).replace('0x',
            '').upper()
    return out


def paste_driver_button():
    """Paste the driver in the copy/paste buffer for the highlighted button

    """
    pass


def _is_package_in_list(module_name, list_packages, no_wheel=False):
    """
    determines of this package is the one for the given module_name

    @param      list_packages       list of packages names (list of wheel)
    @param      module_name         module name
    @param      no_wheel            skip wheels
    @return                         package name
    """
    module_name = module_name.lower()
    p = '.' in module_name
    if p:
        pp = module_name.replace('.', '_')
    d = '-' in module_name
    if d:
        pd = module_name.split('-')
        if len(pd[-1]) == 0:
            pd = '_'.join(pd[:-1]) + '-'
        else:
            pd = '_'.join(pd)
    for a in list_packages:
        al = a.lower()
        if no_wheel and al.endswith('.whl'):
            continue
        if module_name == 'python' and '.msi' not in a:
            continue
        if 'theme-' in al:
            al = al.split('theme-')
            al = al[0].replace('-', '_') + 'theme-' + al[1]
        if al.startswith(module_name):
            return a
        if p and al.startswith(pp):
            return a
        if d and al.startswith(pd):
            return a
    return None


def doFPAcalc(NISTpk, ttArr, twotheta, calcwid, step):
    """Compute a single peak using a NIST profile object

    :param object NISTpk: a peak profile computational object from the
      NIST XRD Fundamental Parameters Code, typically established from
      a call to :func:`SetupFPAcalc`
    :param np.Array ttArr: an evenly-spaced grid of two-theta points (degrees)
    :param float twotheta: nominal center of peak (degrees)
    :param float calcwid: width to perform convolution (degrees)
    :param float step: step size
    """
    center_bin_idx = min(ttArr.searchsorted(twotheta), len(ttArr) - 1)
    NISTpk.set_optimized_window(twotheta_exact_bin_spacing_deg=step,
        twotheta_window_center_deg=ttArr[center_bin_idx],
        twotheta_approx_window_fullwidth_deg=calcwid)
    NISTpk.set_parameters(twotheta0_deg=twotheta)
    return center_bin_idx, NISTpk.compute_line_profile()


def get_last_quarter(month, year):
    """
    Get last quarter of given month and year
    :param month: given month
    :param year: given year
    :return: last quarter and it's year
    """
    last_quarter = (month - 1) // 3
    if last_quarter == 0:
        last_quarter = 4
        last_year = year - 1
    else:
        last_year = year
    return last_quarter, last_year


@classmethod
def get_valid_keys(cls):
    """
        Return a list of valid keys to be passed to the __init__
        """
    return super().get_valid_keys() + ['tot_num_mpiprocs',
        'default_mpiprocs_per_machine']


def format_size(size):
    """Return file size as string from byte size."""
    for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
        if size < 2048:
            return '%.f %s' % (size, unit)
        size /= 1024.0


def t_STRUCTURE(t):
    """([ ]+)field[ ]declaration:[ ](.+);\\n"""
    tab = int(len(t.lexer.lexmatch.group(10)) / 2)
    declaration = t.lexer.lexmatch.group(11).replace('\n', ' ')
    t.value = [tab, {'field': declaration, 'value': None}]
    return t


def p_simple_stmt(p):
    """ simple_stmt : small_stmt
                    | simple_stmt ";" small_stmt """
    if len(p) == 2:
        p[0] = ['STATEMENTS', [p[1]]]
    else:
        p[0] = ['STATEMENTS', p[1][1] + [p[3]]]


def vertex_group_copy():
    """Make a copy of the active vertex group

    """
    pass


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

        :param DurationLogInfo val:
        :rtype: WebSessionsIdleLengthPolicy
        """
    return cls('defined', val)


def cut(cut, node_indices):
    """Check that the cut is for only the given nodes."""
    if cut.indices != node_indices:
        raise ValueError('{} nodes are not equal to subsystem nodes {}'.
            format(cut, node_indices))


def unquote_header_value(value, is_filename=False):
    """Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    :rtype: str
    """
    if value and value[0] == value[-1] == '"':
        value = value[1:-1]
        if not is_filename or value[:2] != '\\\\':
            return value.replace('\\\\', '\\').replace('\\"', '"')
    return value


@staticmethod
def colorize(text, color_number=None):
    """Return colorized version of 'text', with terminal color 'color_number' (31, 32...).
        Return bare text if 'color_number' is None.
        """
    if color_number is None:
        return text
    return '\x1b[{n}m{t}\x1b[0m'.format(t=text, n=color_number)


@staticmethod
def return_true(*args):
    """_return_true function to keep easy flow through get_kmer_counts_from_reference_given_bed
        :param args: takes in an assortemnt of argumetns and returns true
        :return:
        """
    return True


@classmethod
def parse_l2_depth(cls, instmt, raw):
    """
        Parse raw data to L2 depth
        :param instmt: Instrument
        :param raw: Raw data in JSON
        """
    raise Exception('parse_l2_depth should not be called.')


@classmethod
def AddCommandLineArguments(cls, argument_group, category=None, names=None):
    """Adds command line arguments to a configuration object.

    Args:
      argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
          argparse group.
      category (Optional[str]): category of helpers to apply to
          the group, such as storage, output, where None will apply the
          arguments to all helpers. The category can be used to add arguments
          to a specific group of registered helpers.
      names (Optional[list[str]]): names of argument helpers to apply,
          where None will apply the arguments to all helpers.
    """
    for helper_name, helper_class in sorted(cls._helper_classes.items()):
        if (category and helper_class.CATEGORY != category or names and
            helper_name not in names):
            continue
        helper_class.AddArguments(argument_group)


def to_locale(language):
    """
    Simplified copy of `django.utils.translation.to_locale`, but we
    need it while the `settings` module is being loaded, i.e. we
    cannot yet import django.utils.translation.  Also we don't need
    the to_lower argument.
    """
    p = language.find('-')
    if p >= 0:
        if len(language[p + 1:]) > 2:
            return language[:p].lower() + '_' + language[p + 1].upper(
                ) + language[p + 2:].lower()
        return language[:p].lower() + '_' + language[p + 1:].upper()
    else:
        return language.lower()


def initiate_layer_upload(registryId=None, repositoryName=None):
    """
    Notify Amazon ECR that you intend to upload an image layer.
    See also: AWS API Documentation

    :example: response = client.initiate_layer_upload(
        registryId='string',
        repositoryName='string'
    )

    :type registryId: string
    :param registryId: The AWS account ID associated with the registry that you intend to upload layers to. If you do not specify a registry, the default registry is assumed.

    :type repositoryName: string
    :param repositoryName: [REQUIRED]
            The name of the repository that you intend to upload layers to.

    :rtype: dict
    :return: {
        'uploadId': 'string',
        'partSize': 123
    }

    """
    pass


def drop_all():
    """Drop all tables and sequences."""


def g_to_l(g):
    """
    Convert US gallons to liters
    """
    return g / 0.26417


def enum_eq(enum, value) ->bool:
    """
    Checks equality of `enum` and `value`.

    Parameters
    ----------
    enum : Enum
        The enumerator instance
    value : any
        The value or enumerator instance to be compared.
    """
    return enum == value or enum.value == value


def _format_summary(lines, element, spacer='  '):
    """Adds the element's summary tag to the lines if it exists."""
    summary = spacer + element.summary
    if element.summary == '':
        summary = (spacer +
            'No description given in XML documentation for this element.')
    lines.append(summary)


def print_var(variable):
    """print the variable"""
    print(str(variable))


@classmethod
def canClearBrowserCache(cls):
    """Tells whether clearing browser cache is supported.
        """
    return cls.build_send_payload('canClearBrowserCache', {}
        ), cls.convert_payload({'result': {'class': bool, 'optional': False}})


def merge(json, firstField, secondField):
    """
    merge two fields of a json into an array of { firstField : secondField }
    """
    merged = []
    for i in range(0, len(json[firstField])):
        merged.append({json[firstField][i]: json[secondField][i]})
    return merged


@classmethod
def BigInt(cls):
    """Postgres BigInt Type"""
    return cls(int, 'BIGINT')


def unchanged(func, *args):
    """Return True if `func` applied to the `args` is unchanged.
    Can be used instead of `assert foo == foo`.

    Examples
    ========

    >>> from sympy import Piecewise, cos, pi
    >>> from sympy.core.expr import unchanged
    >>> from sympy.abc import x

    >>> unchanged(cos, 1)  # instead of assert cos(1) == cos(1)
    True

    >>> unchanged(cos, pi)
    False

    Comparison of args uses the builtin capabilities of the object's
    arguments to test for equality so args can be defined loosely. Here,
    the ExprCondPair arguments of Piecewise compare as equal to the
    tuples that can be used to create the Piecewise:

    >>> unchanged(Piecewise, (x, x > 1), (0, True))
    True
    """
    f = func(*args)
    return f.func == func and f.args == args


def recalc_orig(dic, data, fn, axis=-1):
    """
    Recalculate the origin for given axis
    """
    s = float(data.shape[axis])
    if dic[fn + 'QUADFLAG'] == 0 and axis != -1:
        s = int(s / 2.0)
    if dic['FD2DPHASE'] == 1 and fn != 'FDF2' and dic[fn + 'FTFLAG'] != 1:
        s = int(s / 2.0)
    sw = dic[fn + 'SW']
    car = dic[fn + 'CAR']
    obs = dic[fn + 'OBS']
    s2 = float(dic[fn + 'CENTER'])
    dic[fn + 'ORIG'] = car * obs - sw * ((s - s2) / s)
    return dic


def get_random_walk_spanning_tree(graph):
    """Generate a spanning tree from the directed graph using the random walk approach.

    This was proposed independently by by Broder (1989) and Aldous (1990). It simply generates random walks until all
    nodes have been covered.

    Algorithm:

    1. Choose a starting vertex s arbitrarily. Set T_V ← {s} and T_E ← ∅.
    2. Do a simple random walk starting at s. Whenever we cross an edge e = {u, v} with v ∈ V ,
        add v to TV and add e to TE.
    3. Stop the random walk when TV = V . Output T = (T_V , T_E) as our spanning tree

    :param networkx.DiGraph graph: The input graph
    :rtype: networkx.DiGraph

    .. seealso::

        - https://math.dartmouth.edu/~pw/math100w13/kothari.pdf
        - http://keyulux.com/pdf/spanning_tree.pdf

    """
    raise NotImplementedError


def connect(src, target, reftype):
    """Connect ``src_object`` to ``target_object`` using the reference
        type ``reftype``.  ``src`` and ``target`` may be objects or object
        identifiers."""


def list_to_dict(wc_list, order_list):
    """ Create a dictionary from a list wc_list, using keys in order_list """
    wc_dict = {}
    for wc_ind in range(len(order_list)):
        wc_dict[order_list[wc_ind]] = wc_list[wc_ind]
    return wc_dict


def SizeBenefitSickHosp(t):
    """Sickness hospitalization benefit per policy"""
    return 0


def select(extend: bool=False, deselect: bool=False, toggle: bool=False,
    center: bool=False, enumerate: bool=False, object: bool=False, location:
    int=(0, 0)):
    """Activate/select item(s)

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


def pythonbit():
    """Returns 64 or 32 depending if the python interpreter is 32 or 64 bit"""
    import struct
    return struct.calcsize('P') * 8


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 extended_gcd(aa, bb):
    """
    Algorithm: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2

    parameters:
    aa, bb: int

    return: r, s, t

    r = s * aa + t * bb
    """
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder,
            remainder)
        x, lastx = lastx - quotient * x, x
        y, lasty = lasty - quotient * y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb <
        0 else 1)


def provider_parser(subparser):
    """Generate provider parser for OVH"""
    subparser.description = """
        OVH Provider requires a token with full rights on /domain/*.
        It can be generated for your OVH account on the following URL:
        https://api.ovh.com/createToken/index.cgi?GET=/domain/*&PUT=/domain/*&POST=/domain/*&DELETE=/domain/*"""
    subparser.add_argument('--auth-entrypoint', help=
        'specify the OVH entrypoint', choices=['ovh-eu', 'ovh-ca',
        'soyoustart-eu', 'soyoustart-ca', 'kimsufi-eu', 'kimsufi-ca'])
    subparser.add_argument('--auth-application-key', help=
        'specify the application key')
    subparser.add_argument('--auth-application-secret', help=
        'specify the application secret')
    subparser.add_argument('--auth-consumer-key', help=
        'specify the consumer key')


def get_selected_fedge() ->'freestyle.types.FEdge':
    """Returns the selected FEdge.

    :return:  The selected FEdge.
    """
    pass


def unpad(bytestring, k=16):
    """
    Remove the PKCS#7 padding from a text bytestring.
    """
    val = bytestring[-1]
    if val > k:
        raise ValueError('Input is not padded or padding is corrupt')
    l = len(bytestring) - val
    return bytestring[:l]


def iter_index(model, index):
    """
    Iterate over child indexes of a `QModelIndex` in a `model`.
    """
    for row in range(model.rowCount(index)):
        yield model.index(row, 0, index)


@staticmethod
def _get_id_mapping(issue_id):
    """
        Get the Jira value mapping for the ID field.

        :param issue_id: Issue ID
        :return: Jira value mapping for the ID
        """
    return str(issue_id)


def duplicate_metaelems():
    """Duplicate selected metaelement(s)

    """
    pass


def manage_pasteObjects(cb_copy_data=None, REQUEST=None):
    """Paste previously copied objects into the current object.

        If calling manage_pasteObjects from python code, pass the result of a
        previous call to manage_cutObjects or manage_copyObjects as the first
        argument.
        """


def isbinary(s, params, ui, **kwargs):
    """Filter to do nothing with the file."""
    return s


def _add_all_sources(ret_src, params, from_source):
    """Adds the sources from from_source of all given parameters into the
    lhs sources multidict"""
    for param in params:
        ret_src.setdefault(param.name, []).extend(from_source.get(param.
            name, ()))


def aa_unicode_ascii_utf8_issue():
    """Take All csv in a folder and provide Table, Column Schema, type

 METHOD FOR Unicode / ASCII issue
1. Decode early
Decode to <type 'unicode'> ASAP
df['PREF_NAME']=       df['PREF_NAME'].apply(to_unicode)

2. Unicode everywhere

3. Encode late
# >>> f = open('/tmp/ivan_out.txt','w')
# >>> f.write(ivan_uni.encode('utf-8'))

Important methods
s.decode(encoding)  <type 'str'> to <type 'unicode'>
u.encode(encoding)  <type 'unicode'> to <type 'str'>

http://farmdev.com/talks/unicode/

   """


@staticmethod
def _file_can_be_imported(entry):
    """ Verify if a directory entry is a non-magic Python file."""
    if entry.is_file() and not entry.name.startswith('__'
        ) and entry.name.endswith('.py'):
        return True
    return False


def format_fasta(header, sequence, line_length=60):
    """Format sequence as in fasta with leading '>'.

    Args:
        header (str): description.
        sequence (str): sequence to wrap over lines.
        line_length (int, optional): line break. Defaults to 80.

    Returns:
        str: fasta file entry.
    """
    lines = ['>{header}\n'.format(header=header)]
    for i in range(0, len(sequence), line_length):
        lines.append(sequence[i:i + line_length] + '\n')
    return ''.join(lines)


def scientific(value, precision=2):
    """Return number in string scientific notation z.wq x 10ⁿ.

    Examples:
        float(0.3) will return "3.00 x 10⁻¹"
        int(500) will return "5.00 x 10²"
    This will always return a string.

    Args:
        value (int, float, string): Input number.
        precision (int): Number of decimal for first part of the number.

    Returns:
        str: number in scientific notation z.wq x 10ⁿ.
    """
    exponents = {'0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵',
        '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹', '+': '⁺', '-': '⁻'}
    negative = False
    try:
        if '-' in str(value):
            value = str(value).replace('-', '')
            negative = True
        if isinstance(value, str):
            value = float(value)
        fmt = '{:.%se}' % str(int(precision))
        n = fmt.format(value)
    except (ValueError, TypeError):
        return value
    part1, part2 = n.split('e')
    if '-0' in part2:
        part2 = part2.replace('-0', '-')
    if '+0' in part2:
        part2 = part2.replace('+0', '')
    new_part2 = []
    if negative:
        new_part2.append(exponents['-'])
    for char in part2:
        new_part2.append(exponents[char])
    final_str = part1 + ' x 10' + ''.join(new_part2)
    return final_str


def get_application_properties(topology, node, name):
    """Return a dictionary containing all the properties of an application
    deployed on a node

    Parameters
    ----------
    topology : Topology
        The topology
    node : any hashable type
        The ID of the node
    name : str
        The name of the application

    Returns
    -------
    applications : dict
        A dictionary containing the properties of the application
    """
    if 'application' not in topology.node[node]:
        raise ValueError('There is no such application deployed on the node')
    return topology.node[node]['application'][name]


def parse_lsb_release(lines):
    """
    Extract OS id from content of /etc/lsb-release files (in Debian derived OSs).
    """
    name = 'unknown'
    version = ''
    for l in lines:
        if l.startswith('DISTRIB_ID='):
            name = l.strip()[11:].lower()
        elif l.startswith('DISTRIB_RELEASE='):
            version = l.strip()[16:].replace('.', '')
    return name, version


@classmethod
def is_valid(cls, name):
    """Check if a string is a valid vm mode

        :param name: vm mode name to validate

        :returns: True if @name is valid
        """
    return name in cls.ALL


def getRestPolefigDerv(HKL, Grid, SHCoeff):
    """default doc string

    :param type name: description

    :returns: type name: description

    """
    pass


def chunks(l, n):
    """Generator that splits a list into equal peices of length n

    Parameters
    ----------
    l: Array-like
        Array to be split
    n: Integer
        Length of each sub array
    """
    for i in range(0, len(l), n):
        yield l[i:i + n]


def addComment(comment):
    """Add a comment to the entry."""


def register_domain(name=None, description=None,
    workflowExecutionRetentionPeriodInDays=None):
    """
    Registers a new domain.
    Access Control
    You can use IAM policies to control this action's access to Amazon SWF resources as follows:
    If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified constraints, the action fails. The associated event attribute's cause parameter will be set to OPERATION_NOT_PERMITTED. For details and example IAM policies, see Using IAM to Manage Access to Amazon SWF Workflows .
    See also: AWS API Documentation

    :example: response = client.register_domain(
        name='string',
        description='string',
        workflowExecutionRetentionPeriodInDays='string'
    )

    :type name: string
    :param name: [REQUIRED]
            Name of the domain to register. The name must be unique in the region that the domain is registered in.
            The specified string must not start or end with whitespace. It must not contain a : (colon), / (slash), | (vertical bar), or any control characters (u0000-u001f | u007f - u009f). Also, it must not contain the literal string quotarnquot.

    :type description: string
    :param description: A text description of the domain.

    :type workflowExecutionRetentionPeriodInDays: string
    :param workflowExecutionRetentionPeriodInDays: [REQUIRED]
            The duration (in days) that records and histories of workflow executions on the domain should be kept by the service. After the retention period, the workflow execution is not available in the results of visibility calls.
            If you pass the value NONE or 0 (zero), then the workflow execution history will not be retained. As soon as the workflow execution completes, the execution record and its history are deleted.
            The maximum workflow execution retention period is 90 days. For more information about Amazon SWF service limits, see: Amazon SWF Service Limits in the Amazon SWF Developer Guide .

    :returns:
    name (string) -- [REQUIRED]
    Name of the domain to register. The name must be unique in the region that the domain is registered in.
    The specified string must not start or end with whitespace. It must not contain a : (colon), / (slash), | (vertical bar), or any control characters (u0000-u001f | u007f - u009f). Also, it must not contain the literal string quotarnquot.

    description (string) -- A text description of the domain.
    workflowExecutionRetentionPeriodInDays (string) -- [REQUIRED]
    The duration (in days) that records and histories of workflow executions on the domain should be kept by the service. After the retention period, the workflow execution is not available in the results of visibility calls.
    If you pass the value NONE or 0 (zero), then the workflow execution history will not be retained. As soon as the workflow execution completes, the execution record and its history are deleted.
    The maximum workflow execution retention period is 90 days. For more information about Amazon SWF service limits, see: Amazon SWF Service Limits in the Amazon SWF Developer Guide .

    """
    pass


def multiply(x, factor):
    """multiply tensor by factor"""
    return x * factor


@staticmethod
def _build_result_metainfo(args):
    """
        Internal helper for collecting metadata from args to results
        """
    data = dict()
    if hasattr(args, 'branch') and args.branch:
        data['build_branch'] = args.branch
    if hasattr(args, 'commitId') and args.commitId:
        data['buildcommit'] = args.commitId
    if hasattr(args, 'gitUrl') and args.gitUrl:
        data['build_git_url'] = args.gitUrl
    if hasattr(args, 'buildUrl') and args.buildUrl:
        data['build_url'] = args.buildUrl
    if hasattr(args, 'campaign') and args.campaign:
        data['campaign'] = args.campaign
    if hasattr(args, 'jobId') and args.jobId:
        data['job_id'] = args.jobId
    if hasattr(args, 'toolchain') and args.toolchain:
        data['toolchain'] = args.toolchain
    if hasattr(args, 'buildDate') and args.buildDate:
        data['build_date'] = args.buildDate
    return data


def dictUpdate(dikt: 'Dict[Any, Any]', by: 'Dict[Any, Any]'
    ) ->'Dict[Any, Any]':
    """ Updates a dictionary by another one, returning a new copy without touching any of the passed dictionaries. """
    d = dict(dikt)
    d.update(by)
    return d


def _is_fix_comment(line, isstrict):
    """
    Check whether line is a comment line in fixed format Fortran source.

    :param str line: Line of code to check
    :param bool isstrict: Whether we are strictly enforcing fixed/free fmt

    References
    ----------
    :f2008:`3.3.3`
    """
    if line:
        if line[0] in '*cC!':
            return True
        if not isstrict:
            i = line.find('!')
            if i != -1:
                start = line[:i].lstrip()
                if not start:
                    if i == 5:
                        return False
                    return True
                else:
                    pass
    elif line == '':
        return True
    return False


def _to_bool(x):
    """convert array values to boolean values.

    Args:
        x (array): values should be  0 or 1

    Returns:
        array: boolean array
    """
    return x.astype(bool)


def describe_virtual_gateways():
    """
    Returns a list of virtual private gateways owned by the AWS account.
    You can create one or more AWS Direct Connect private virtual interfaces linking to a virtual private gateway. A virtual private gateway can be managed via Amazon Virtual Private Cloud (VPC) console or the EC2 CreateVpnGateway action.
    See also: AWS API Documentation

    :example: response = client.describe_virtual_gateways()

    :rtype: dict
    :return: {
        'virtualGateways': [
            {
                'virtualGatewayId': 'string',
                'virtualGatewayState': 'string'
            },
        ]
    }

    """
    pass


@classmethod
def run_service_start(cls, options=None):
    """Build foreman-maintain advanced procedure run
         service-start"""
    cls.command_sub = 'service-start'
    if options is None:
        options = {}
    result = cls._construct_command(options)
    return result


@staticmethod
def getCreateTable():
    """Create the table to hold the hostnames"""
    return 'create table host (host char(256))'


def _add_keys_to_request(request_field_pb, key_pbs):
    """Add protobuf keys to a request object.

    :type request_field_pb: `RepeatedCompositeFieldContainer`
    :param request_field_pb: A repeated proto field that contains keys.

    :type key_pbs: list of :class:`gcloud.datastore._generated.entity_pb2.Key`
    :param key_pbs: The keys to add to a request.
    """
    for key_pb in key_pbs:
        request_field_pb.add().CopyFrom(key_pb)


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


@classmethod
def parse(cls, reader, track_offset):
    """returns this cuesheet index from a BitstreamReader"""
    offset, number = reader.parse('64U8u24p')
    return cls(track_offset=track_offset, offset=offset, number=number)


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 find_signature_end(model_string):
    """
    Find the index of the colon in the function signature.
    :param model_string: string
        source code of the model
    :return: int
        the index of the colon
    """
    index, brace_depth = 0, 0
    while index < len(model_string):
        ch = model_string[index]
        if brace_depth == 0 and ch == ':':
            break
        if ch == '#':
            index += 1
            while index < len(model_string) and model_string[index] != '\n':
                index += 1
            index += 1
        elif ch in ['"', "'"]:
            string_depth = 0
            while index < len(model_string) and model_string[index] == ch:
                string_depth += 1
                index += 1
            if string_depth == 2:
                string_depth = 1
            index += string_depth
            while index < len(model_string):
                if model_string[index] == '\\':
                    index += 2
                elif model_string[index] == ch:
                    string_depth -= 1
                    if string_depth == 0:
                        break
                    index += 1
                else:
                    index += 1
            index += 1
        elif ch == '(':
            brace_depth += 1
            index += 1
        elif ch == ')':
            brace_depth -= 1
            index += 1
        else:
            index += 1
    return index


def p_exprlt(p):
    """ expr : expr LT 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 __compute_cluster_assignment(centroid_indices, items, distance_matrix):
    """Get a dictionary with cluster ids as keys and arrays of assinged item indices as values"""
    labels = {}
    for centroid_index in centroid_indices:
        labels[centroid_index] = []
    for item_index in range(len(items)):
        min_distance = float('inf')
        closest_centroid = -1
        for centroid_index in centroid_indices:
            dist = distance_matrix[centroid_index, item_index]
            if dist < min_distance:
                min_distance = dist
                closest_centroid = centroid_index
        labels[closest_centroid].append(item_index)
    return labels


def read_html_from_file(file_path):
    """This function can be useful for offline debug"""
    with open(file_path, 'rU') as fd:
        html = fd.read()
    return html


def ms_from_timedelta(td):
    """
    Получает дельту, возвращает миллисекунды
    """
    return td.seconds * 1000 + td.microseconds / 1000.0


def _create(cls, val, name, attr):
    """ Create instance from the class that will be set in the metaclass.
            The `value` and `name` atrributes have counterparts with `_` to
            allow these names to be overriten and still be available.
            This function also set all the instance attributes.
        """
    error = hasattr(cls, name)
    self = cls(name)
    if error or not isinstance(self, cls):
        cls_ = type(self)
        parent = 'parent ' if cls != type(self) else ''
        raise RuntimeError('Name %r already on %sclass %r' % (name, parent,
            cls_.__name__))
    self._value = self.value = val
    self._name = self.name = name
    for k, v in attr.items():
        setattr(self, k, v)
    return self


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


def get_kwargs_defaults(argspec):
    """Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec."""
    arg_names = tuple(argspec.args)
    defaults = argspec.defaults or ()
    num_args = len(argspec.args) - len(defaults)
    kwargs_defaults = {}
    for i, default_value in enumerate(defaults):
        kwargs_defaults[arg_names[num_args + i]] = default_value
    return kwargs_defaults


def text_underline(cr, x, y, text, offset=1.5):
    """
    Draw text with underline.
    """
    x_bear, y_bear, w, h, x_adv, y_adv = cr.text_extents(text)
    cr.move_to(x, y - y_bear)
    cr.show_text(text)
    cr.move_to(x, y - y_bear + offset)
    cr.set_line_width(1.0)
    cr.rel_line_to(x_adv, 0)
    cr.stroke()


def replace(text, replacements):
    """
  Replaces multiple slices of text with new values. This is a convenience method for making code
  modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is
  an iterable of ``(start, end, new_text)`` tuples.

  For example, ``replace("this is a test", [(0, 4, "X"), (8, 9, "THE")])`` produces
  ``"X is THE test"``.
  """
    p = 0
    parts = []
    for start, end, new_text in sorted(replacements):
        parts.append(text[p:start])
        parts.append(new_text)
        p = end
    parts.append(text[p:])
    return ''.join(parts)


@staticmethod
def _get_key(sample, project):
    """
        Key is created by joining the sample and project id together with a period
        :param sample:
        :param project:
        :return:
        """
    return sample + '.' + project


def reraise_exception(exn):
    """Called in an exception handler to re-raise the exception."""
    raise exn


def _create_security_groups(ec2_client, config):
    """Create and authorize a security group in AWS
    """
    if config.get('description') is None:
        config['description'] = 'A security group set by red-panda'
    if config.get('group_name') is None:
        raise ValueError("Value config['group_name'] must be provided")
    if config.get('vpc_id') is None:
        raise ValueError("Value config['vpc_id'] must be provided")
    response = ec2_client.create_security_group(Description=config[
        'description'], GroupName=config['group_name'], VpcId=config[
        'vpc_id'], DryRun=False)
    if config.get('ip_permission') is None:
        config['ip_permission'] = [{'IpProtocol': 'TCP', 'FromPort': 8786,
            'ToPort': 8787, 'IpRanges': [{'CidrIp': '0.0.0.0/0',
            'Description': 'Anywhere'}], 'Ipv6Ranges': [{'CidrIpv6': '::/0',
            'Description': 'Anywhere'}]}, {'IpProtocol': 'TCP', 'FromPort':
            0, 'ToPort': 65535, 'UserIdGroupPairs': [{'GroupName': None}]}]
    ec2_client.authorize_security_group_ingress(GroupId=response['GroupId'],
        IpPermissions=config['ip_permission'], DryRun=False)


def AD(df, high='High', low='Low', close='Close', volume='Volume'):
    """
    Chaikin A/D Line
    Returns: list of floats = jhta.AD(df, high='High', low='Low', close='Close', volume='Volume')
    Source: https://www.fmlabs.com/reference/default.htm?url=AccumDist.htm
    """
    ad_list = []
    for i in range(len(df[close])):
        ad = 0
        if i > 0:
            clv = (df[close][i] - df[low][i] - (df[high][i] - df[close][i])
                ) / (df[high][i] - df[low][i])
            ad = ad_list[i - 1] + clv * df[volume][i]
        ad_list.append(ad)
    return ad_list


def get_object_spec(obj):
    """
    Returns the "object spec" string for the given object.
    """
    return '{}:{}'.format(obj.__module__, obj.__class__.__name__)


def quantify(iterable, pred=bool):
    """Return the how many times the predicate is true.

        >>> quantify([True, False, True])
        2

    """
    return sum(map(pred, iterable))


def make_message_header(src, dest, cmd, transaction_id):
    """
        Make the message header. Helper function
    """
    return '%s%s%s\x00%s' % (chr(dest + 7 & 255), chr(src & 255), chr(cmd &
        255), transaction_id)


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 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 list_processes(session, attributes='Name,ProcessId'):
    """
    Description: return list of all proccesses on windows machine

    :param session: instance of Windows, which hold session to win machine
    :type session: winremote.Windows
    :param attributes: comma delimited name of attributes to be returned
    :type attributes: str
    :returns: list of processes info
    :rtype: list of dict
    """
    return session._wmi.query('select %s from Win32_process' % attributes)


@staticmethod
def string_url_regex(str_name):
    """
		Returns regex for url mapping with sting param
		"""
    return '(?P<%s>[^ \\,\\:\\;\\"\\\\/\']+)' % str_name


def reports_display_update():
    """Update the display of reports in Blender UI (internal use)

    """
    pass


def includeme(config):
    """
    void function used to ensure the models are added to the metadatas
    """
    pass


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

        :param ShowcaseAddMemberDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_add_member_details', val)


def new_Msg(client, userdata, message):
    """ Arguements passed in by the subscription service:
        client: The MQTT client object
        user_data: User data that was included in the message payload
        message: The message that was received
    """
    print(client)
    print(userdata)
    print(str(message.payload))


def getAccessTime():
    """
        Retrieve the time that this file was last accessed.

        @return: a number of seconds from the epoch.
        @rtype: L{float}
        """


def custom_startswith(string, incomplete):
    """
    A custom completion matching that supports:
        * Matching anywhere on the string
        * Case insensitive matching
    """
    string = string.lower()
    incomplete = incomplete.lower()
    return incomplete in string


def select_linked(extend: bool=False):
    """Select bones related to selected ones by parent/child relationships

    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


def mesh_split_face(mesh, fkey, u, v):
    """Split a face by inserting an edge between two specified vertices.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        Instance of a mesh
    fkey : str
        The face key.
    u : str
        The key of the first split vertex.
    v : str
        The key of the second split vertex.

    """
    if u not in mesh.face[fkey] or v not in mesh.face[fkey]:
        raise ValueError('The split vertices do not belong to the split face.')
    face = mesh.face[fkey]
    i = face.index(u)
    j = face.index(v)
    if i + 1 == j:
        raise ValueError('The split vertices are neighbors.')
    if j > i:
        f = face[i:j + 1]
        g = face[j:] + face[:i + 1]
    else:
        f = face[i:] + face[:j + 1]
        g = face[j:i + 1]
    f = mesh.add_face(f)
    g = mesh.add_face(g)
    del mesh.face[fkey]
    return f, g


def p_col_expr(p):
    """col_expr :  identifier '=' expr"""
    p[0] = p[1], p[3]


def lambd_H3PO4_H_PS76(T, P):
    """n-c: phosphoric-acid hydrogen [PS76]."""
    lambd = 0.29
    valid = T == 298.15
    return lambd, valid


def get_references_to(content, name=None, depth=None):
    """Get all references where the given content is a target,
        optionaly tagged with name.

        If depth is mentioned, search for all content from which
        you can reach the given content in less than depth steps.
        """


def extract_code(lines, node, lstrip='', ljoin='\n', strip=''):
    """Get corresponding text in the code

    Arguments:
    lines -- code splitted by linebreak
    node -- PyPosAST enhanced node

    Keyword Arguments:
    lstrip -- During extraction, strip lines with this arg (default="")
    ljoin -- During extraction, join lines with this arg (default="
")
    strip -- After extraction, strip all code with this arg (default="")
    """
    first_line, first_col = node.first_line - 1, node.first_col
    last_line, last_col = node.last_line - 1, node.last_col
    if first_line == last_line:
        return lines[first_line][first_col:last_col].strip(strip)
    result = []
    result.append(lines[first_line][first_col:].strip(lstrip))
    if first_line + 1 != last_line:
        for line in range(first_line + 1, last_line):
            result.append(lines[line].strip(lstrip))
    result.append(lines[last_line][:last_col].strip(lstrip))
    return ljoin.join(result).strip(strip)


@classmethod
def _special_case_plural(cls, word: str) ->str:
    """Returns either a special case plural of its argument, or the empty string if it doesn't know."""
    return cls._SPECIAL_PLURALS.get(word, '')


def write_details(grid_obj, path_to_file):
    """
        Reads in the grid3D object after calculation and writes out the important details into a named file

        :type grid_obj: An instance of the class grid3D
        :param grid_obj: grid3D object after calculation

        :type path_to_folder: str
        :param path_to_folder: Path to the folder where you want the file to be written to.

        :raises:

        :rtype:
        """
    f1 = open(path_to_file, 'w')
    f1.write(str(grid_obj.nx_total) + '\t' + str(grid_obj.ny_total) + '\t' +
        str(grid_obj.nz_total) + '\n')
    f1.write(str(grid_obj.nx_cells) + '\t' + str(grid_obj.ny_cells) + '\t' +
        str(grid_obj.nz_cells) + '\n')
    f1.write(str(grid_obj.la) + '\t' + str(grid_obj.lb) + '\t' + str(
        grid_obj.lc) + '\n')
    f1.write(str(grid_obj.alpha) + '\t' + str(grid_obj.beta) + '\t' + str(
        grid_obj.gamma) + '\n')
    f1.close()


def p_case_statement(t):
    """case_statement : CASE value COLON"""
    t[0] = [t[2]]


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

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

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


def helptext() ->str:
    """ Simple Helptext For Plugin """
    return 'For managing plugins for use by forge.'


@classmethod
def check_required_modules(cls, mods):
    """Check that modules in `mods` list are available.

        Parameters
        ----------
        mods : list of str
            List of modules. Modules can have specified versions (eg 'numpy>=1.15')

        Returns
        -------
        bool
            True if all modules in list are available.
        """
    for mod in mods:
        if mod in cls._import_cache:
            if not cls._import_cache[mod]:
                return False
        if cls._module_checker.check(mod):
            cls._import_cache[mod] = True
        else:
            cls._import_cache[mod] = False
            return False
    return True


def Nu_horizontal_plate_laminar_Baehr(Re, Pr):
    """Calculates Nusselt number for laminar flow across an **isothermal**
    flat plate at a specified `Re` and `Pr`, both evaluated at the bulk
    temperature. No other wall correction is necessary for this formulation.
    Four different equations are used for different Prandtl number ranges.

    The equation for the common Prandtl number range is also recommended in
    [2]_ and [3]_.

    if :math:`\\text{Pr} < 0.005`:

    .. math::
        \\text{Nu}_L = 1.128\\text{Re}^{0.5}\\text{Pr}^{0.5}

    if :math:`0.005 < \\text{Pr} < 0.05`:

    .. math::
        \\text{Nu}_L = 1.0\\text{Re}^{0.5}\\text{Pr}^{0.5}

    if :math:`0.6 < \\text{Pr} < 10`:

    .. math::
        \\text{Nu}_L = 0.664\\text{Re}^{0.5}\\text{Pr}^{1/3}

    if :math:`\\text{Pr} > 10`:

    .. math::
        \\text{Nu}_L = 0.678\\text{Re}^{0.5}\\text{Pr}^{1/3}

    Parameters
    ----------
    Re : float
        Reynolds number with respect to plate length and bulk fluid properties,
        [-]
    Pr : float
        Prandtl number at bulk temperature, [-]

    Returns
    -------
    Nu : float
        Nusselt number with respect to plate length and bulk temperature, [-]

    Notes
    -----
    Does not take into account the impact of free convection, which can
    increase the convection substantially.

    Examples
    --------
    >>> Nu_horizontal_plate_laminar_Baehr(1e5, 0.7)
    186.4378528752262

    References
    ----------
    .. [1] Baehr, Hans Dieter, and Karl Stephan. Heat and Mass Transfer.
       Springer, 2013.
    .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and
       David P. DeWitt. Introduction to Heat Transfer. 6E.
       Hoboken, NJ: Wiley, 2011.
    .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd ed. 2010 edition.
       Berlin ; New York: Springer, 2010.
    """
    if Pr < 0.005:
        return 1.128 * (Re * Pr) ** 0.5
    elif Pr < 0.05:
        return (Re * Pr) ** 0.5
    elif Pr < 10.0:
        return 0.664 * Re ** 0.5 * Pr ** (1 / 3.0)
    else:
        return 0.678 * Re ** 0.5 * Pr ** (1 / 3.0)


@staticmethod
def evaluate_fn_join(expression):
    """ Return the joined stuff """
    results = []
    new_values_list = []
    temp = expression.split('[')[1]
    delimiter = temp.split(',')[0].strip("'")
    values = expression.split('[')[2]
    values = values.split(']]')[0]
    values_list = values.split(', ')
    for value in values_list:
        new_values_list.append(value.strip("'"))
    result = delimiter.join(new_values_list)
    results.append(result)
    return results


def to_int(string):
    """Convert a one element byte string to int for python 2 support."""
    if isinstance(string, str):
        return ord(string[0])
    else:
        return string


@classmethod
def remove_from_postmortem_exclusion_list(cls, pathname, bits=None):
    """
        Removes the given filename to the exclusion list for postmortem
        debugging from the Registry.

        @warning: This method requires administrative rights.

        @warning: Don't ever delete entries you haven't created yourself!
            Some entries are set by default for your version of Windows.
            Deleting them might deadlock your system under some circumstances.

            For more details see:
            U{http://msdn.microsoft.com/en-us/library/bb204634(v=vs.85).aspx}

        @see: L{get_postmortem_exclusion_list}

        @type  pathname: str
        @param pathname: Application pathname to remove from the postmortem
            debugging exclusion list.

        @type  bits: int
        @param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
            64 bits debugger. Set to {None} for the default (L{System.bits}).

        @raise WindowsError:
            Raises an exception on error.
        """
    if bits is None:
        bits = cls.bits
    elif bits not in (32, 64):
        raise NotImplementedError('Unknown architecture (%r bits)' % bits)
    if bits == 32 and cls.bits == 64:
        keyname = (
            'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
            )
    else:
        keyname = (
            'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
            )
    try:
        key = cls.registry[keyname]
    except KeyError:
        return
    try:
        del key[pathname]
    except KeyError:
        return


def addDashboardOptions(parser, with_submit=True):
    """
    Add dashboard-related options to the option parser (optparse.OptionParser
    instance).
    """
    from optparse import OptionGroup
    group = OptionGroup(parser, 'Dashboard Options')
    if with_submit:
        group.add_option('--submit', action='store_true', default=False,
            help='submit the results to Dashboard server')
        group.add_option('--no-submit', action='store_false', dest='submit',
            help='do not submit the results to Dashboard server (default)')
    group.add_option('--flavour', default='nightly', help=
        'which build server to use (build flavour)')
    group.add_option('--db-url', help=
        'database server to use instead of the default one')
    group.add_option('--db-name', help=
        'override database name [default: nightlies-{flavour}]')
    parser.add_option_group(group)
    return parser


def quaternion_real(quaternion):
    """Return real part of quaternion.

    >>> quaternion_real([3, 0, 1, 2])
    3.0

    """
    return float(quaternion[0])


@staticmethod
def update_body():
    """Return a dict for updating a repository. Should be overridden.

        :raises: ``NotImplementedError`` if not implemented by a child class.
        """
    raise NotImplementedError()


def logical_or(image1, image2):
    """Logical OR between two images.

    .. code-block:: python

        out = ((image1 or image2) % MAX)

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image1.load()
    image2.load()
    return image1._new(image1.im.chop_or(image2.im))


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

        :param es_major: major version of Elasticsearch, as string
        :returns: dictionary with a key, 'items', with the mapping
        """
    mapping = """
        {
            "properties": {
               "main_description_analyzed": {
                    "type": "text",
                    "index": true
               },
               "summary_analyzed": {
                    "type": "text",
                    "index": true
               }
           }
        }"""
    return {'items': mapping}


def formula_2013_01_01(foyer_fiscal, period):
    """
        A partir des revenus de 2013, certains revenus du capital qui pouvaient
        profiter du prélèvement forfaitaire libératoire sont passés à l'imposition obligatoire au barème.
        Mais un prélèvement forfaitaire demeure à partir de 2013, pour éviter les trous de trésorerie
        (car un prélèvement forfaitaire est à la source). Ce prélèvement est non-libératoire : il
        correspond à un acompte d'IRPP, qui est donc déduit de l'impôt dû au moment du calcul de
        l'impôt final après déclaration des revenus
        """
    f2ck = foyer_fiscal('f2ck', period)
    return f2ck


def axis(name=None, cols=None, values=None, units=None):
    """Convenience function for generating axis descriptions when defining MetaArrays"""
    ax = {}
    cNameOrder = ['name', 'units', 'title']
    if name is not None:
        ax['name'] = name
    if values is not None:
        ax['values'] = values
    if units is not None:
        ax['units'] = units
    if cols is not None:
        ax['cols'] = []
        for c in cols:
            if type(c) != list and type(c) != tuple:
                c = [c]
            col = {}
            for i in range(0, len(c)):
                col[cNameOrder[i]] = c[i]
            ax['cols'].append(col)
    return ax


@classmethod
def is_datasource_for(cls, data, header, **kwargs):
    """Determines if header corresponds to an SWAP image"""
    return header.get('instrume') == 'SWAP'


def _split_dict(in_dict, key_names, nullable_fields=frozenset()):
    """
    Split a dict into two dicts. Keys in key_names go into the new dict if
    their value is present and not None, allowing for None values if the key
    name is present in the nullable_fields set.
    return (updated original dict, new dict)
    """
    new_dict = {}
    for key_name in key_names:
        if key_name in in_dict:
            val = in_dict.pop(key_name, None)
            if val is not None or val is None and key_name in nullable_fields:
                new_dict[key_name] = val
    return in_dict, new_dict


def CompatibleAllocatedModules(Task, CurrentSched, TaskMapping):
    """
	return a sublist of allocated modules that are compatible with Task.
	"""
    CompModList = []
    CompModule = TaskMapping[Task]
    for AllocatedModule in CurrentSched.keys():
        if AllocatedModule.Name == CompModule.Name:
            CompModList.append(AllocatedModule)
    return CompModList


def get_roles_for_permission(permission_id):
    """Get the roles that have a permission.

        Return a sequence of (role id, setting) tuples for the given
        permission.

        If no roles have been granted this permission, then the empty list is
        returned.
        """


def dic2axisheader(dic):
    """
    Convert a Sparky parameter axis diction into a axisherder list.
    """
    al = [0] * 12
    al[0] = dic['nucleus'].encode()
    al[1] = dic['spectral_shift']
    al[2] = dic['npoints']
    al[3] = dic['size']
    al[4] = dic['bsize']
    al[5] = dic['spectrometer_freq']
    al[6] = dic['spectral_width']
    al[7] = dic['xmtr_freq']
    al[8] = dic['zero_order']
    al[9] = dic['first_order']
    al[10] = dic['first_pt_scale']
    al[11] = dic['extended']
    return al


def valley_list(perm):
    """Returns the list of valleys of the permutation.

    >>> Permutation(3241756).valley_list()
    [1, 3, 5]
    """
    return perm.complement().peak_list()


def show_one_level(open: bool=True):
    """Expand/collapse all entries by one level

    :param open: Open, Expand all entries one level deep
    :type open: bool
    """
    pass


@staticmethod
def _parse(event):
    """
        Parse slack event, removing @ mention
        """
    words = event.event['text'].split(' ')
    words.pop(0)
    return ' '.join(words), event.event['user'], event.event['channel']


@classmethod
def stop_watching(cls):
    """ Remove all files that are being watched.
        """
    cls.observer.unschedule_all()


def inverse_mod(a, m):
    """Inverse of a mod m."""
    if a < 0 or m <= a:
        a = a % m
    c, d = a, m
    uc, vc, ud, vd = 1, 0, 0, 1
    while c != 0:
        q, c, d = divmod(d, c) + (c,)
        uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc
    assert d == 1
    if ud > 0:
        return ud
    else:
        return ud + m


def parse_SpinOrbit(upf_dict, root):
    """
    Spin orbit coupling.
    """
    if not upf_dict['header']['spin_orbit']:
        return
    proj_num = upf_dict['header']['number_of_proj']
    for i in range(proj_num):
        node = root.findall('./PP_SPIN_ORB/PP_RELBETA.%i' % (i + 1))[0]
        upf_dict['beta_projectors'][i]['angular_momentum'] = float(node.
            attrib['lll'])
        upf_dict['beta_projectors'][i]['total_angular_momentum'] = float(node
            .attrib['jjj'])


def machine_id(machine_id):
    """
    Validates the machine_id
    Must be a 64 byte lowercase hex string.
    A sha256sum, in effect.
    """
    if not isinstance(machine_id, str):
        raise TypeError('machine_id must be a string.')
    if len(machine_id) != 64:
        raise ValueError('machine_id must be exactly 64 bytes/characters.')
    for letter in machine_id:
        if letter not in '0123456789abcdef':
            raise ValueError('machine_id must be only 0-9, a-f (lowercase)')
    return True


@staticmethod
def _flavor_ordering_key(flavor):
    """
        Return the value to use when sorting flavors.

        By default, flavors are sorted lexicographically by:
        - nr. of vCPUS (first),
        - amount of RAM,
        - size of disk (last).
        """
    return flavor.vcpus, flavor.ram, flavor.disk


def rchop(text, end):
    """ Removes the end from the text if the text ends with it. """
    if text.endswith(end):
        return text[:-len(end)]
    return text


def _swap_dimensions(ds, geometry, drop_old=True):
    """Replace logical coordinates with physical ones. Does not work for llc.
    """
    keep_attrs = ['axis', 'c_grid_axis_shift']
    ds = ds.reset_coords()
    if geometry.lower() in ('llc', 'curvilinear'):
        raise ValueError("Can't swap dimensions if `geometry` is `llc`")
    for orig_dim in ds.dims:
        if 'swap_dim' in ds[orig_dim].attrs:
            new_dim = ds[orig_dim].attrs['swap_dim']
            coord_var = ds[new_dim]
            for coord_dim in coord_var.dims:
                if coord_dim != orig_dim:
                    coord_var = coord_var.isel(**{coord_dim: 0}).drop(coord_dim
                        )
            ds[new_dim] = coord_var
            for key in keep_attrs:
                if key in ds[orig_dim].attrs:
                    ds[new_dim].attrs[key] = ds[orig_dim].attrs[key]
    for orig_dim in ds.dims:
        if 'swap_dim' in ds[orig_dim].attrs:
            new_dim = ds[orig_dim].attrs['swap_dim']
            ds = ds.swap_dims({orig_dim: new_dim})
            if drop_old:
                ds = ds.drop(orig_dim)
    return ds


def cast_to_boolean(value):
    """
    Cast a string to a boolean. Raise a TypeError exception if the
    given value cannot be casted.

    Case insensitive.

    """
    value = value.lower()
    boolean_states = {'true': True, 'false': False}
    if value in boolean_states:
        return boolean_states[value]
    raise TypeError


def measure_line_index_recover_spectrum(wave, params, norm=False):
    """ recover the fitted line profile from params

    Parameters
    ----------
    wave: array-like
        the wavelength to which the recovered flux correspond

    params: 5-element tuple
        the 1 to 5 elements are:
        mod_linear_slope
        mod_linear_intercept
        mod_gauss_amplitude
        mod_gauss_center
        mod_gauss_sigma

    norm: bool
        if True, linear model (continuum) is deprecated
        else linear + Gaussian model is used

    """
    from lmfit.models import LinearModel, GaussianModel
    mod_linear = LinearModel(prefix='mod_linear_')
    mod_gauss = GaussianModel(prefix='mod_gauss_')
    par_linear = mod_linear.make_params()
    par_gauss = mod_gauss.make_params()
    par_linear['mod_linear_slope'].value = params[0]
    par_linear['mod_linear_intercept'].value = params[1]
    par_gauss['mod_gauss_amplitude'].value = params[2]
    par_gauss['mod_gauss_center'].value = params[3]
    par_gauss['mod_gauss_sigma'].value = params[4]
    if not norm:
        flux = 1 - mod_gauss.eval(params=par_gauss, x=wave)
    else:
        flux = (1 - mod_gauss.eval(params=par_gauss, x=wave)
            ) * mod_linear.eval(params=par_linear, x=wave)
    return flux


def set_guess(guess):
    """Set the default value of the ``guess`` parameter for read()

    :param guess: New default ``guess`` value (True|False)
    """
    global _GUESS
    _GUESS = guess


def addAttachment(filename, content, mime_type):
    """
           Adds an attachment to this message
        """


def extract_file_contents(filename):
    """ The first step in importing, takes a file and converts to
        a string.
    """
    disavow_contents = ''
    with open(filename, 'r') as disavow_file:
        file_contents = disavow_file.read()
        try:
            disavow_contents = file_contents.decode('utf-8-sig')
        except UnicodeDecodeError:
            disavow_contents = file_contents.decode('utf-16')
    return disavow_contents


@classmethod
def unregister(cls):
    """Removes all plugin meta information and makes it undiscoverable."""
    cls._meta_clear()


def getmembers(obj, predicate=None):
    """Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate."""
    results = []
    for key in dir(obj):
        try:
            value = getattr(obj, key)
        except AttributeError:
            continue
        if not predicate or predicate(value):
            results.append((key, value))
    results.sort()
    return results


def return_empty(*args, **kwargs):
    """function that returns an empty string"""
    return ''


def get_iter(dictionary):
    """
    Just a wrapper method that handles Python2->Python3 dict iterations
    :param dictionary: (Dict)
    :return: (Dict)
    """
    try:
        return dictionary.iteritems()
    except AttributeError:
        return dictionary.items()


def time_correction(EoT, longitude, GMTOffset):
    """Return the time correction (minutes) where EoT is the equation of time,
    and given location longitude (degrees) and the GMT offset (hours)"""
    LSTM = 15.0 * GMTOffset
    TimeCorrection = 4.0 * (longitude - LSTM) + EoT
    return TimeCorrection


def _script_callback_option_parser(option, opt_str, value, parser):
    """
    Store a script's URL or path along to its attribute 'defer', 'async' or None
    """
    attr = ('defer' in opt_str and 'defer' or 'async' in opt_str and
        'async' or None)
    parser.values.script = parser.values.script or []
    parser.values.script.append((value, attr))
    return


def default_formfield_for_dbfield(model_admin, db_field, form_field,
    request, **kwargs):
    """
    A system wide hook to change how db_field are displayed as formfields
    :param model_admin: the ModelAdmin instance
    :param db_field: db_field
    :param form_field: the default form_field
    :param request: the current request

    :return: form_field to be used
    """
    return form_field


def pkg2dir(package):
    """
    Return directory path from UML package class.
    """
    name = []
    while package:
        name.insert(0, package.name)
        package = package.package
    return '/'.join(name)


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

        :param SfTeamInviteType val:
        :rtype: EventType
        """
    return cls('sf_team_invite', val)


def param_name(param_name, rig_type):
    """ Get the actual parameter name, sans-rig-type.
    """
    return param_name[len(rig_type) + 1:]


def mat311mod(a, b):
    """
    Compute moduli of a 3x1 matrix.

    Parameters
    ----------
    a : tuple of float
        3x1 matrix
    b : float
        modulus

    Returns
    -------
    res : tuple of float
        3x1 matrix
    """
    res = [0, 0, 0]
    r3 = range(3)
    for i in r3:
        res[i] = int(a[i] - int(a[i] / b) * b)
    return res


def pytest_xdist_node_collection_finished(node, ids):
    """called by the master node when a node finishes collecting.
    """


def calculate_polynomial_term(coefficient, variable, order):
    """Calculates a term in a polynomial.

    Args:
        coefficient (float): The coefficient to use in
            calculating the polynomial term.
        variable (float): Value to plug in for the variable in the polynomial
            term.
        order (int): Integer to use as the order of the polynomial term.

    Returns:
        float: The result of coefficient * variable**(order)

    Raises:
        TypeError: A non-integer order is given.
    """
    if type(order) != int:
        raise TypeError('Non-integer order in polynomial term')
    else:
        return coefficient * variable ** order


@classmethod
def black(cls):
    """Predefined black color (box) representation"""
    return cls('black', '000', 'X', 2)


@staticmethod
def transform_match_data(dataframe, fields_to_title_case, fields_to_upper_case
    ):
    """Change strings of certain DataFrame columns to title case and upper case"""
    for field in fields_to_upper_case:
        dataframe[field] = dataframe[field].apply(lambda x: x.title() if
            isinstance(x, str) else x)
    for field in fields_to_title_case:
        dataframe[field] = dataframe[field].apply(lambda x: x.upper() if
            isinstance(x, str) else x)


def line_search_subject(line):
    """get the source one searches for"""
    l = line.split()
    if len(l) > 1 and 'search' in l:
        i = l.index('search')
        return l[i + 1]
    else:
        return None


def distinct(not_distinct_list: list):
    """
    Returns a list with no duplicate elements
    """
    return list(set(not_distinct_list))


def delete_record(db: dict, record_id: int, total_records):
    """Delete a record specified by record_id
    """
    for i in range(record_id, total_records):
        db['db'][str(record_id)] = db['db'][record_id + 1]
    del db['db'][str(total_records)]


def wang_ryzin_reg(h, Xi, x):
    """
    A version for the Wang-Ryzin kernel for nonparametric regression.

    Suggested by Li and Racine in [1] ch.4
    """
    return h ** abs(Xi - x)


def delete_list_duplicated(list_data):
    """
    Delete the list duplicated key_value
    :param list_data:
    :return:(list) new_list_data
    """
    assert isinstance(list_data, list)
    return sorted(set(list_data), key=list_data.index)


def _get_orbit_number_from_message_data(msg_data):
    """Get orbit number from message data"""
    if 'orbit_number' in msg_data:
        return msg_data['orbit_number']
    else:
        return None


@staticmethod
def _create_key(lang, instance):
    """Crea la clave única de la caché"""
    model_name = instance.__class__.__name__
    return '{0}__{1}_{2}'.format(lang, model_name, instance.id)


def mass_wmg(weight, gravitational_field_strength):
    """Usage: mass_wmg(weight (Newtons), gravitational field strength)"""
    return weight / gravitational_field_strength


def flatten_sequence(sequence, isinstance=isinstance, StringTypes=
    StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten):
    """Flatten a sequence to a non-nested list.

    Same as flatten(), but it does not handle the single scalar
    case. This is slightly more efficient when one knows that
    the sequence to flatten can not be a scalar.
    """
    result = []
    for item in sequence:
        if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes
            ):
            result.append(item)
        else:
            do_flatten(item, result)
    return result


def merge_local_contact_info(settings=None, mapping=None, data=None):
    """Merge values of locally provided contact info."""
    keys_internal = ['force', 'use_custom_info']
    data.clear()
    for key, value in settings.items():
        if key in keys_internal:
            continue
        if value is None:
            continue
        mapped_key = mapping.get(key)
        if mapped_key is None:
            continue
        data[mapped_key] = value


def path_shift(script_name, path_info, shift=1):
    """ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.

        :return: The modified paths.
        :param script_name: The SCRIPT_NAME path.
        :param script_name: The PATH_INFO path.
        :param shift: The number of path fragments to shift. May be negative to
          change the shift direction. (default: 1)
    """
    if shift == 0:
        return script_name, path_info
    pathlist = path_info.strip('/').split('/')
    scriptlist = script_name.strip('/').split('/')
    if pathlist and pathlist[0] == '':
        pathlist = []
    if scriptlist and scriptlist[0] == '':
        scriptlist = []
    if 0 < shift <= len(pathlist):
        moved = pathlist[:shift]
        scriptlist = scriptlist + moved
        pathlist = pathlist[shift:]
    elif 0 > shift >= -len(scriptlist):
        moved = scriptlist[shift:]
        pathlist = moved + pathlist
        scriptlist = scriptlist[:shift]
    else:
        empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
        raise AssertionError('Cannot shift. Nothing left from %s' % empty)
    new_script_name = '/' + '/'.join(scriptlist)
    new_path_info = '/' + '/'.join(pathlist)
    if path_info.endswith('/') and pathlist:
        new_path_info += '/'
    return new_script_name, new_path_info


def get(isamAppliance, check_mode=False, force=False):
    """
    Retrieve runtime component replicaiton status
    """
    return isamAppliance.invoke_get(
        'Retrieving web runtime component replication status',
        '/isam/runtime_components?cluster=true')


def browse_interactive(pose_index: int=-1):
    """Interactively browse poses in 3D-View

    :param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)
    :type pose_index: int
    """
    pass


def skip_equivalent_effect_values(causes_effects):
    """Returns only first key: value mapping for equivalent
    effect values."""
    effects = set()
    result = dict()
    for cause, effect in causes_effects.items():
        if effect not in effects:
            effects.add(effect)
            result[cause] = effect
    return result


@classmethod
def from_config_dict(cls, config_dict, **extra_kwargs):
    """
        Convert a dictionary, checking for invalid keys, that can be
        safely passed as kwargs. Checks only for the presence of options
        (keys), not their types. Converts dashes to underscores in
        option names.

        Considers optional arguments to cls.__init__() optional options,
        and required arguments to cls.__init__() required options.
        Rejects options also found in extra_kwargs.
        """
    if isinstance(config_dict, cls):
        return config_dict
    required_args, optional_args = cls._find_args(extra_kwargs)
    kwargs = {}
    for raw_key in config_dict:
        key = cls._to_field(raw_key)
        if key not in required_args + optional_args:
            raise ValueError("Unknown config key `{}'".format(raw_key))
        kwargs[key] = config_dict[raw_key]
    for key in required_args:
        if key not in kwargs:
            raw_key = cls._to_config(key)
            raise ValueError("Missing required config key `{}'".format(raw_key)
                )
    kwargs.update(extra_kwargs)
    return cls(**kwargs)


def change_color(u, X, Y, N, H, F, C, L):
    """Change the color of 'u' from X to Y and update N, H, F, C."""
    assert F[u] == X and X != Y
    F[u] = Y
    for k in C.keys():
        if N[u, k] == 0:
            H[X, k] -= 1
            H[Y, k] += 1
    for v in L[u]:
        N[v, X] -= 1
        N[v, Y] += 1
        if N[v, X] == 0:
            H[F[v], X] += 1
        if N[v, Y] == 1:
            H[F[v], Y] -= 1
    C[X].remove(u)
    C[Y].append(u)


@classmethod
def get_by_auth_password(cls, auth_id, password):
    """Returns a user object, validating password.

        :param auth_id:
            Authentication id.
        :param password:
            Password to be checked.
        :returns:
            A user object, if found and password matches.
        :raises:
            ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
        """


def missing_in_pattern(pattern, missing='Ø'):
    """Utility function for quick access of missing data."""
    return pattern.count(missing)


def make_section_str(str='', width=60, symbol='-'):
    """Generate string for starting/ending sections of log messages"""
    strlen = len(str)
    dash_len = width - strlen if strlen < width else 0
    side_dash = symbol * (dash_len // 2)
    section_str = '{}{}{}'.format(side_dash, str, side_dash)
    return section_str


def doStop():
    """
        Called every time this is unconnected from a Port or Connector.
        """


def write_text_to_file(text, filename):
    """Append text to file"""
    with open(filename, mode='a') as text_file:
        text_file.write(text)
    text_file.close()
    return filename


def put_event_selectors(TrailName=None, EventSelectors=None):
    """
    Configures an event selector for your trail. Use event selectors to specify whether you want your trail to log management and/or data events. When an event occurs in your account, CloudTrail evaluates the event selectors in all trails. For each trail, if the event matches any event selector, the trail processes and logs the event. If the event doesn't match any event selector, the trail doesn't log the event.
    Example
    The PutEventSelectors operation must be called from the region in which the trail was created; otherwise, an InvalidHomeRegionException is thrown.
    You can configure up to five event selectors for each trail. For more information, see Logging Data and Management Events for Trails in the AWS CloudTrail User Guide .
    See also: AWS API Documentation

    :example: response = client.put_event_selectors(
        TrailName='string',
        EventSelectors=[
            {
                'ReadWriteType': 'ReadOnly'|'WriteOnly'|'All',
                'IncludeManagementEvents': True|False,
                'DataResources': [
                    {
                        'Type': 'string',
                        'Values': [
                            'string',
                        ]
                    },
                ]
            },
        ]
    )

    :type TrailName: string
    :param TrailName: [REQUIRED]
            Specifies the name of the trail or trail ARN. If you specify a trail name, the string must meet the following requirements:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes (-)
            Start with a letter or number, and end with a letter or number
            Be between 3 and 128 characters
            Have no adjacent periods, underscores or dashes. Names like my-_namespace and my--namespace are invalid.
            Not be in IP address format (for example, 192.168.5.4)
            If you specify a trail ARN, it must be in the format:
            arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail

    :type EventSelectors: list
    :param EventSelectors: [REQUIRED]
            Specifies the settings for your event selectors. You can configure up to five event selectors for a trail.
            (dict) --Use event selectors to specify whether you want your trail to log management and/or data events. When an event occurs in your account, CloudTrail evaluates the event selector for all trails. For each trail, if the event matches any event selector, the trail processes and logs the event. If the event doesn't match any event selector, the trail doesn't log the event.
            You can configure up to five event selectors for a trail.
            ReadWriteType (string) --Specify if you want your trail to log read-only events, write-only events, or all. For example, the EC2 GetConsoleOutput is a read-only API operation and RunInstances is a write-only API operation.
            By default, the value is All .
            IncludeManagementEvents (boolean) --Specify if you want your event selector to include management events for your trail.
            For more information, see Management Events in the AWS CloudTrail User Guide .
            By default, the value is true .
            DataResources (list) --CloudTrail supports logging only data events for S3 objects. You can specify up to 250 S3 buckets and object prefixes for a trail.
            For more information, see Data Events in the AWS CloudTrail User Guide .
            (dict) --The Amazon S3 objects that you specify in your event selectors for your trail to log data events. Data events are object-level API operations that access S3 objects, such as GetObject , DeleteObject , and PutObject . You can specify up to 250 S3 buckets and object prefixes for a trail.
            Example
            You create an event selector for a trail and specify an S3 bucket and an empty prefix, such as arn:aws:s3:::bucket-1/ .
            You upload an image file to bucket-1 .
            The PutObject API operation occurs on an object in the S3 bucket that you specified in the event selector. The trail processes and logs the event.
            You upload another image file to a different S3 bucket named arn:aws:s3:::bucket-2 .
            The event occurs on an object in an S3 bucket that you didn't specify in the event selector. The trail doesn t log the event.
            Type (string) --The resource type in which you want to log data events. You can specify only the following value: AWS::S3::Object .
            Values (list) --A list of ARN-like strings for the specified S3 objects.
            To log data events for all objects in an S3 bucket, specify the bucket and an empty object prefix such as arn:aws:s3:::bucket-1/ . The trail logs data events for all objects in this S3 bucket.
            To log data events for specific objects, specify the S3 bucket and object prefix such as arn:aws:s3:::bucket-1/example-images . The trail logs data events for objects in this S3 bucket that match the prefix.
            (string) --

    :rtype: dict
    :return: {
        'TrailARN': 'string',
        'EventSelectors': [
            {
                'ReadWriteType': 'ReadOnly'|'WriteOnly'|'All',
                'IncludeManagementEvents': True|False,
                'DataResources': [
                    {
                        'Type': 'string',
                        'Values': [
                            'string',
                        ]
                    },
                ]
            },
        ]
    }

    :returns:
    TrailName (string) -- [REQUIRED]
    Specifies the name of the trail or trail ARN. If you specify a trail name, the string must meet the following requirements:

    Contain only ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes (-)
    Start with a letter or number, and end with a letter or number
    Be between 3 and 128 characters
    Have no adjacent periods, underscores or dashes. Names like my-_namespace and my--namespace are invalid.
    Not be in IP address format (for example, 192.168.5.4)

    If you specify a trail ARN, it must be in the format:

    arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail

    EventSelectors (list) -- [REQUIRED]
    Specifies the settings for your event selectors. You can configure up to five event selectors for a trail.

    (dict) --Use event selectors to specify whether you want your trail to log management and/or data events. When an event occurs in your account, CloudTrail evaluates the event selector for all trails. For each trail, if the event matches any event selector, the trail processes and logs the event. If the event doesn't match any event selector, the trail doesn't log the event.
    You can configure up to five event selectors for a trail.

    ReadWriteType (string) --Specify if you want your trail to log read-only events, write-only events, or all. For example, the EC2 GetConsoleOutput is a read-only API operation and RunInstances is a write-only API operation.
    By default, the value is All .

    IncludeManagementEvents (boolean) --Specify if you want your event selector to include management events for your trail.
    For more information, see Management Events in the AWS CloudTrail User Guide .
    By default, the value is true .

    DataResources (list) --CloudTrail supports logging only data events for S3 objects. You can specify up to 250 S3 buckets and object prefixes for a trail.
    For more information, see Data Events in the AWS CloudTrail User Guide .

    (dict) --The Amazon S3 objects that you specify in your event selectors for your trail to log data events. Data events are object-level API operations that access S3 objects, such as GetObject , DeleteObject , and PutObject . You can specify up to 250 S3 buckets and object prefixes for a trail.
    Example

    You create an event selector for a trail and specify an S3 bucket and an empty prefix, such as arn:aws:s3:::bucket-1/ .
    You upload an image file to bucket-1 .
    The PutObject API operation occurs on an object in the S3 bucket that you specified in the event selector. The trail processes and logs the event.
    You upload another image file to a different S3 bucket named arn:aws:s3:::bucket-2 .
    The event occurs on an object in an S3 bucket that you didn't specify in the event selector. The trail doesnt log the event.

    Type (string) --The resource type in which you want to log data events. You can specify only the following value: AWS::S3::Object .

    Values (list) --A list of ARN-like strings for the specified S3 objects.
    To log data events for all objects in an S3 bucket, specify the bucket and an empty object prefix such as arn:aws:s3:::bucket-1/ . The trail logs data events for all objects in this S3 bucket.
    To log data events for specific objects, specify the S3 bucket and object prefix such as arn:aws:s3:::bucket-1/example-images . The trail logs data events for objects in this S3 bucket that match the prefix.

    (string) --

    """
    pass


@staticmethod
def is_julian(year, month, day):
    """This method returns True if given date is in the Julian calendar.

        :param year: Year
        :type y: int
        :param month: Month
        :type m: int
        :param day: Day
        :type day: int

        :returns: Whether the provided date belongs to Julian calendar or not.
        :rtype: bool

        >>> Epoch.is_julian(1997, 5, 27.1)
        False
        >>> Epoch.is_julian(1397, 7, 7.0)
        True
        """
    if (year < 1582 or year == 1582 and month < 10 or year == 1582 and
        month == 10 and day < 5.0):
        return True
    else:
        return False


def readle(b: bytes) ->int:
    """Convert little-endian bytes to an int."""
    return int.from_bytes(b, 'little')


def setQualifiedFormats(qualified_formats):
    """Set the qualified Formats elements.

        The argument must be a sequence of Format `IDublinCoreElementItem`.
        """


def verify_input(json_data):
    """
    Verifies the validity of an API request content

    :param json_data: Parsed JSON accepted from API call
    :type json_data: dict
    :return: Data for the the process function
    """
    if 'callback_uri' not in json_data:
        raise ValueError('callback_uri not supplied')
    return json_data