@classmethod
def serialize(cls, entity, value):
    """Serialize a value for this attribute that is suitable for storage.

        This will be called by the blob when serializing itself, override it
        to perform any necessary conversion or sanitation.

        :param entity: The entity this attribute is on
        :param value: The value to serialize
        :returns: The serialized value

        """
    return value


def remove_comment_wrappers_from_html(html_string):
    """This function removes comment wrappers (i.e. ``<!--`` and ``-->``) from an HTML string.

    .. versionadded:: 2.5.1

    :param html_string: The HTML string from which to remove comment wrappers
    :type html_string: str
    :returns: The HTML string with comment wrappers removed
    """
    start_comment_position = html_string.find('<!--')
    end_comment_position = html_string.find('-->')
    last_start_comment_position = html_string.rfind('<!--')
    last_end_comment_position = html_string.rfind('-->')
    return html_string.replace(html_string[start_comment_position:
        end_comment_position + 3], '').replace(html_string[
        last_start_comment_position:last_end_comment_position + 3], '')


def _sort_messages(messages, sort_by):
    """
    Sort the given message iterable by the given criteria.

    Always returns a list.

    :param messages: An iterable of Messages.
    :param sort_by: Sort by which criteria? Options are `message` and `location`.
    :return: list[Message]
    """
    messages = list(messages)
    if sort_by == 'message':
        messages.sort()
    elif sort_by == 'location':
        messages.sort(key=lambda m: m.locations)
    return messages


def validate_ppoi_tuple(value):
    """
    Validates that a tuple (`value`)...
    ...has a len of exactly 2
    ...both values are floats/ints that are greater-than-or-equal-to 0
       AND less-than-or-equal-to 1
    """
    valid = True
    while valid is True:
        if len(value) == 2 and isinstance(value, tuple):
            for x in value:
                if x >= 0 and x <= 1:
                    pass
                else:
                    valid = False
            break
        else:
            valid = False
    return valid


def cuda_is_available(backend):
    """Check if cuda is avaible for the current backend

    Parameters
    ----------
    backend : obj
        A backend object

    Returns
    -------
    cuda_available : bool
        Whether or not cuda is there.
    """
    cuda_supported_backends = ['torch', 'tensorflow']
    backend_name = backend.__name__
    if backend_name in cuda_supported_backends:
        if backend.name == 'torch' or 'torchvision':
            cuda_available = backend.cuda.is_available()
    else:
        cuda_available = False
    return cuda_available


def parse_version(version: str) ->tuple:
    """Parse a string formatted X[.Y.Z] version number into a tuple

    >>> parse_version('10.2.3')
    (10, 2, 3)

    >>> parse_version('12')
    (12, 0, 0)
    """
    parts = version.split('.')
    missing = 3 - len(parts)
    return tuple(map(int, parts + ['0'] * missing))


def iterable_to_dict(items, key_attr_name):
    """Converts iterable of certain objects to dict.

    :param iterable items:
    :param string key_attr_name: Attribute to use as a dictionary key.
    :return dict:
    """
    items_dict = {}
    for item in items:
        items_dict.update({getattr(item, key_attr_name): item})
    return items_dict


@classmethod
def set_game_settings(cls, game_settings):
    """
        set up some Balance settings on engine
        :param game_settings: settings of the Balance
        """
    if hasattr(game_settings, 'scenes_list'):
        cls.scenes = game_settings.scenes_list
    else:
        raise Exception('No scenes_list in game_settings file!')
    if hasattr(game_settings, 'game_name'):
        cls.game_name = game_settings.game_name
    if hasattr(game_settings, 'screen_width'):
        cls.screen_width = game_settings.screen_width
    if hasattr(game_settings, 'screen_height'):
        cls.screen_height = game_settings.screen_height


def search_items(keywords):
    """Search the items in the filters.
        """


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

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


def on_message(json_response):
    """Receive a JSON response and do stuff with it"""
    print(list(json_response.keys()))


@staticmethod
def founder():
    """Name the Havoc founder"""
    return 'Rick Hovac'


def _test():
    """perform internal tests."""
    import doctest
    doctest.testmod()


@classmethod
def _parse_media_type_params(cls, media_type_params_segment):
    """
        Parse media type parameters segment into list of (name, value) tuples.
        """
    media_type_params = cls.parameters_compiled_re.findall(
        media_type_params_segment)
    for index, (name, value) in enumerate(media_type_params):
        if value.startswith('"') and value.endswith('"'):
            value = cls._process_quoted_string_token(token=value)
            media_type_params[index] = name, value
    return media_type_params


def unitsum_tuples(n, k, mn, mx):
    """Generates unitsum k-tuples with elements from mn to mx.

    This function is more general than slots(n,k,normalized=True), as it can
    return unitsum vectors with elements outside of (0,1).

    In order to generate unitsum samples, the following must be satisfied:
        1 = mx + (k-1) * mn

    Parameters
    ----------
    n : int
        The number of increments to include between mn and mx. n >= 1. The
        meaning of n is similar to the n in slots(n,k) and represents the
        number of ``items'' to place in each slot.
    k : int
        The length of the tuples (equivalently, the number of slots).
    mn : float
        The minimum value in the unitsum samples.
    mx : float
        The maximum value in the unitsum samples.

    Examples
    --------
    >>> s = unitsum_tuples(3, 2, .2, .8)
    >>> s.next()
    (0.20000000000000001, 0.80000000000000004)
    >>> s.next()
    (0.40000000000000008, 0.60000000000000009)
    >>> s.next()
    (0.60000000000000009, 0.40000000000000002)
    >>> s.next()
    (0.80000000000000004, 0.19999999999999996)

    """
    s = mx + (k - 1) * mn
    tol = 1e-09
    if not abs(s - 1) <= tol:
        msg = 'Specified min and max will not create unitsum tuples.'
        e = Exception(msg)
        raise e
    n += 1
    if mn < 0:
        shift = float(abs(mn))
    else:
        shift = -float(mn)
    seq, i = [mx + shift] * k + [0], k
    while i:
        t = tuple(seq[i] - seq[i + 1] - shift for i in range(k))
        s = float(sum(t))
        assert s > 0.001
        yield tuple(t)
        for idx, val in enumerate(seq):
            if abs(val) < 1e-09:
                i = idx - 1
                break
        seq[i:k] = [seq[i] - (mx - mn) / float(n - 1)] * (k - i)


def create_astropy_constant(py_obj, h_group, call_id=0, **kwargs):
    """ dumps an astropy constant

    Args:
        py_obj: python object to dump; should be a python type (int, float, bool etc)
        h_group (h5.File.group): group to dump data into.
        call_id (int): index to identify object's relative location in the iterable.
    """
    d = h_group.create_dataset('data_%i' % call_id, data=py_obj.value,
        dtype='float64')
    d.attrs['type'] = [b'astropy_constant']
    d.attrs['unit'] = [str(py_obj.unit)]
    d.attrs['abbrev'] = [str(py_obj.abbrev)]
    d.attrs['name'] = [str(py_obj.name)]
    d.attrs['reference'] = [str(py_obj.reference)]
    d.attrs['uncertainty'] = [py_obj.uncertainty]
    if py_obj.system:
        d.attrs['system'] = [py_obj.system]


def escape(data, quote=True):
    """
  Escapes special characters into their html entities
  Replace special characters "&", "<" and ">" to HTML-safe sequences.
  If the optional flag quote is true, the quotation mark character (")
  is also translated.

  This is used to escape content that appears in the body of an HTML document
  """
    data = data.replace('&', '&')
    data = data.replace('<', '<')
    data = data.replace('>', '>')
    if quote:
        data = data.replace('"', '"')
    return data


def remove_namespace_from_string(name):
    """
    Removes the namespace from the given string
    :param name: str, string we want to remove namespace from
    :return: str
    """
    sub_name = name.split(':')
    new_name = ''
    if sub_name:
        new_name = sub_name[-1]
    return new_name


def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'ifd_style':
        "The type of physical interface (ifd) supported by the device. Choices are 'CLASSIC' or 'SWITCH'."
        }


@classmethod
def send_error(cls, channel, status, msg, **extra):
    """Send a control packet with an error"""
    error = {'service': 'command', 'type': 'error', 'status': status, 'msg':
        msg}
    error.update(extra)
    channel.send_control(error)


def reup():
    """put incoming things in incoming things as one incoming thing"""


def chunker(reader, width):
    """Yield chunks from lines in reader with given width."""
    for line in reader:
        line = line[:-1]
        if line == '':
            yield ''
            continue
        for offset in range(0, len(line), width):
            yield line[offset:offset + width]


def channels_clean_empty():
    """Delete all empty animation data containers from visible data-blocks

    """
    pass


def pretty_name(name):
    """Converts 'first_name' to 'First name'"""
    if not name:
        return u''
    return name.replace('_', ' ').capitalize()


def findOrEmpty(obj: dict, param: str, padding: bool=False):
    """ Finds a string parameter in an dict, adds a space before the value if set """
    if param not in obj:
        return ''
    if padding:
        return ' ' + str(obj[param])
    return obj[param]


@classmethod
def get_all(cls, return_type):
    """
        Return list of (suffix, return_type, post_processor)
        """
    default = cls.get_default(return_type)
    alternate = cls.get_alternate_post_processor(return_type)
    result = [('', return_type, default)]
    if alternate:
        result.append(alternate)
    return result


def format_time(elapsed):
    """Formats elapsed seconds into a human readable format."""
    hours = int(elapsed / (60 * 60))
    minutes = int(elapsed % (60 * 60) / 60)
    seconds = int(elapsed % 60)
    rval = ''
    if hours:
        rval += '{0}h'.format(hours)
    if elapsed > 60:
        rval += '{0}m'.format(minutes)
    rval += '{0}s'.format(seconds)
    return rval


def distance_score(neighbors):
    """
    Calculates a distance-score for a peak given its neighbors.

    Parameters
    ----------
    neighbors : list of peaks
        The query peak's neighbors.

    Returns
    -------
    float
        The distance-score.

    Notes
    -----
    Lower distance-scores are better.
    """
    score = 0
    for neighbor in neighbors:
        score += neighbor['distance']
    return score / len(neighbors)


@staticmethod
def get_opt(opt_name, args):
    """Return option name and value.

        :param opt_name: name of the option, e.g., "username"
        :param args: parsed arguments
        """
    return opt_name, getattr(args, 'os_%s' % opt_name, None)


@classmethod
def parseKwargs(cls, config_psf, logger):
    """Parse the psf field of a configuration dict and return the kwargs to use for
        initializing an instance of the class.

        :param config_psf:      The psf field of the configuration dict, config['psf']
        :param logger:          A logger object for logging debug info. [default: None]

        :returns: a kwargs dict to pass to the initializer
        """
    import piff
    kwargs = {}
    kwargs.update(config_psf)
    kwargs.pop('type', None)
    for key in ['model', 'interp']:
        if key not in kwargs:
            raise ValueError(
                '%s field is required in psf field for type=Simple' % key)
    model = piff.Model.process(kwargs.pop('model'), logger=logger)
    kwargs['model'] = model
    interp = piff.Interp.process(kwargs.pop('interp'), logger=logger)
    kwargs['interp'] = interp
    if 'outliers' in kwargs:
        outliers = piff.Outliers.process(kwargs.pop('outliers'), logger=logger)
        kwargs['outliers'] = outliers
    return kwargs


def _build_simple_row(padded_cells, rowfmt):
    """Format row according to DataRow format without padding."""
    begin, sep, end = rowfmt
    return (begin + sep.join(padded_cells) + end).rstrip()


@classmethod
def Scale(cls, sx, sy):
    """Returns affine transformation for scaling by `sx`, `sy`."""
    return cls(sx, 0, 0, 0, sy, 0)


def get_diff_index(patch, line_nr):
    """
    Takes a patch and receives the position of the given line number in it.

    >>> patch = ('---/version/a\\n'
    ...          '+++/version/b\\n'
    ...          '@@ -1,2 +1,4 @@\\n'
    ...          ' # test\\n'  # Line 1
    ...          '+\\n'  # Line 2
    ...          '-a test repo\\n'  # Line 3
    ...          '+something new\\n'  # Line 3
    ...          ' something old\\n')  # Line 4
    >>> get_diff_index(patch, 1)
    1
    >>> get_diff_index(patch, 3)
    4
    >>> get_diff_index(patch, 4)
    5

    If the line isn't covered in the patch, it'll return None:

    >>> get_diff_index(patch, 8)

    Sometimes patches contain the function and shall still be interpreted
    correctly:

    >>> patch = ('@@ -464,11 +464,10 @@ def get_action_info(section, action):\\n'
    ...          ' line 464\\n'
    ...          ' line 465\\n'
    ...          ' line 466\\n'
    ...          '-line 467\\n'
    ...          '-line 468\\n'
    ...          '+line 467\\n'
    ...          '+line 468\\n'
    ...          ' line 469\\n')
    >>> get_diff_index(patch, 465)
    2
    >>> get_diff_index(patch, 467)
    6

    :param patch: A list of lines of a unified diff.
    :param line_nr: The line number to identify.
    :return: The position in the Patch or None
    """
    patch = patch.splitlines(True)
    current_line_added = 0
    current_diff_index = 0
    for line in patch:
        if line.startswith('---') or line.startswith('+++'):
            continue
        if line.startswith('@@'):
            values = line[line.find('-'):line.find(' @@', 3)]
            _, added = tuple(values.split(' '))
            current_line_added = int(added.split(',')[0][1:])
        elif line.startswith('+') or line.startswith(' '):
            if current_line_added == line_nr:
                return current_diff_index
            current_line_added += 1
        current_diff_index += 1
    return None


@classmethod
def can_handle(cls, *args, **kwargs):
    """
        Advise if it's a valid class for arguments pased to the method
        """
    return False


def sh_quote_safe(arg):
    """
    Escape a string for safely passing as argument to a shell command.

    Return a single-quoted string that expands to the exact literal
    contents of `text` when used as an argument to a shell command.
    Examples (note that backslashes are doubled because of Python's
    string read syntax)::

      >>> print(sh_quote_safe("arg"))
      'arg'
      >>> print(sh_quote_safe("'arg'"))
      ''\\''arg'\\'''

    """
    return "'" + str(arg).replace("'", "'\\''") + "'"


def glLoadName(name: int):
    """Load a name onto the name stack.

    :param name: Specifies a name that will replace the top value on the name stack.
    :type name: int
    """
    pass


@classmethod
def list_user(cls, user, drop_incompat_keys=False):
    """Patch a user list object"""
    user['profile_picture'] = user['profile_pic_url']
    if drop_incompat_keys:
        cls._drop_keys(user, ['followed_by_viewer', 'is_verified',
            'profile_pic_url', 'requested_by_viewer'])
    return user


def principal_component(amount, rate, years, periods):
    """
    Calculates the principal compouding component of a financial application.

    Parameters
    ----------
    amount : float
        The principal component amount, i.e., the initial investment.
    rate : float
        The annualized compouding interest rate.
    years : int
        The number of years of the application.
    periods : int
        The number of compounding periods per years.

    Returns
    -------
    out : float
        The value of the principal components after the given years.
    """
    return amount * (1 + rate / periods) ** (years * periods)


def cambiar_vals(símismo, valores):
    """
        Esta función cambia el valor de uno o más variables del modelo.

        Parameters
        ----------
        valores : dict
            Un diccionario de variables y sus valores para cambiar.
        """
    símismo.variables.cambiar_vals(valores=valores)


def merge_outfiles(filelist, outfile_name):
    """  merge the output from multiple BLAST runs of type 6 output (no headers)
    """
    with open(outfile_name, 'a') as outf:
        for idx, f in enumerate(filelist):
            with open(f, 'r') as inf:
                for line in inf:
                    outf.write(line)
    return outfile_name


def _get_frames(d, cross=False, mask=None):
    """gets two frames (or one frame and NoneType) from dual (or single) frame data"""
    if cross == True:
        x1, x2 = d
        if mask is not None:
            x1, x2 = x1[mask], x2[mask]
    else:
        if len(d) == 1 and isinstance(d, tuple):
            x1, = d
        else:
            x1 = d
        if mask is not None:
            x1 = x1[mask]
        x2 = None
    return x1, x2


@staticmethod
def newsgroup_link(newsgroup_string):
    """
        @param newsgroup_string: Usenet name
            i.e: news:comp.emacs
        @param return: [[news:comp.emacs][comp.emacs]]
        """
    return '[[news:' + newsgroup_string + '][' + newsgroup_string + ']]'


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

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

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


@staticmethod
def _validate_fp_type(fp_type: str) ->None:
    """Validate that the delta fixed point type is supported."""
    if fp_type not in {'safe_linear', 'linear', 'safe_nonlinear', 'nonlinear'}:
        raise ValueError(
            "fp_type must be 'safe_linear', 'linear', 'safe_nonlinear', or 'nonlinear'."
            )


def move_down():
    """Move selected strips down a track if there’s room

    """
    pass


def environ_to_unicode(s, enc='UTF-8'):
    """
    Decode a WSGI environ value to a unicode string
    """
    return s.encode('iso-8859-1').decode(enc)


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


def crit_dim_var(var):
    """Check if nested dict or not

    Arguments
    ---------
    var : dict
        Dictionary to test wheter single or multidimensional parameter

    Returns
    -------
    single_dimension : bool
        True: Single dimension, False: Multidimensional parameter
    """
    single_dimension = True
    exclude = ['regional_vals_by', 'regional_vals_ey']
    if type(var) is list:
        for list_entry in var:
            for key, value in list_entry.items():
                if type(value) is not list:
                    if hasattr(value, 'keys') and key not in exclude:
                        if len(value.keys()) != 0:
                            single_dimension = False
                        else:
                            pass
    else:
        for key, value in var.items():
            if type(value) is not list:
                if hasattr(value, 'keys') and key not in exclude:
                    if len(value.keys()) != 0:
                        single_dimension = False
            elif value == []:
                pass
            else:
                single_dimension = False
    return single_dimension


def adaptative_myers_k(sc_len, edit_frac):
    """Calculate the edit distance allowed as a function of the read length"""
    return float(sc_len * edit_frac)


def select_warp_gates(action, action_space, select_add):
    """Select all warp gates."""
    del action_space
    action.action_ui.select_warp_gates.selection_add = select_add


def transform_first_char(string, method):
    """Uses method() on the first character of string."""
    if len(string) == 0:
        return string
    if len(string) == 1:
        return method(string)
    return method(string[0]) + string[1:]


def simply_ignore(warnings_):
    """Set warnings to ignore all.

    Usage:
        import warnings; simply_ignore(warnings)
    """
    warnings_.simplefilter('ignore')


def identity(x):
    """
    Returns the input
    """
    return x


def lookupAuthority(name, timeout=None):
    """
        Perform an SOA record lookup.

        @type name: C{str}
        @param name: DNS name to resolve.

        @type timeout: Sequence of C{int}
        @param timeout: Number of seconds after which to reissue the query.
            When the last timeout expires, the query is considered failed.

        @rtype: L{Deferred}
        @return: A L{Deferred} which fires with a three-tuple of lists of
            L{twisted.names.dns.RRHeader} instances.  The first element of the
            tuple gives answers.  The second element of the tuple gives
            authorities.  The third element of the tuple gives additional
            information.  The L{Deferred} may instead fail with one of the
            exceptions defined in L{twisted.names.error} or with
            C{NotImplementedError}.
        """


@classmethod
def get(cls, dataset_id):
    """Get information about a dataset.

        Parameters
        ----------
        dataset_id : string
            the id of the dataset

        Returns
        -------
        dataset : Dataset
            the queried dataset
        """
    path = '{}{}/'.format(cls._path, dataset_id)
    return cls.from_location(path)


def nPVI(streamForAnalysis):
    """
    Algorithm to give the normalized pairwise variability index
    (Low, Grabe, & Nolan, 2000) of the rhythm of a stream.

    Used by Aniruddh D. Patel to argue for national differences between musical
    themes.  First encountered it in a presentation by Patel, Chew, Francois,
    and Child at MIT.

    n.b. -- takes the distance between each element, including clefs, keys, etc.
    use .notesAndRests etc. to filter out elements that are not useful (though this will skip
    zero length objects)

    n.b. # 2 -- duration is used rather than actual distance -- for gapless
    streams (the norm) these two measures will be identical.

    >>> s2 = converter.parse('tinynotation: 4/4 C4 D E F G').flat.notesAndRests.stream()
    >>> analysis.patel.nPVI(s2)
    0.0

    >>> s3 = converter.parse('tinynotation: 4/4 C4 D8 C4 D8 C4').flat.notesAndRests.stream()
    >>> analysis.patel.nPVI(s3)
    66.6666...

    >>> s4 = corpus.parse('bwv66.6').parts[0].flat.notesAndRests.stream()
    >>> analysis.patel.nPVI(s4)
    12.96296...
    """
    s = streamForAnalysis
    totalElements = len(s)
    summation = 0
    prevQL = s[0].quarterLength
    for i in range(1, totalElements):
        thisQL = s[i].quarterLength
        if thisQL > 0 and prevQL > 0:
            summation += abs(thisQL - prevQL) / ((thisQL + prevQL) / 2.0)
        else:
            pass
        prevQL = thisQL
    final = summation * 100 / (totalElements - 1)
    return final


def crf_viterbi_accuracy(y_true, y_pred):
    """
    Use Viterbi algorithm to get best path, and compute its accuracy.
    `y_pred` must be an output from CRF.
    """
    crf, idx = y_pred._keras_history[:2]
    return crf.get_accuracy(y_true, y_pred)


@classmethod
def set_information_criteria(cls, min_binding_ic=None, max_dist=None):
    """
        Set parameters for
        :param min_binding_ic:
        :param max_dist:
        :return:
        """
    cls.min_binding_ic = (cls.min_binding_ic if min_binding_ic is None else
        min_binding_ic)
    cls.max_dist = cls.max_dist if max_dist is None else max_dist


def calculate_gear_box_heat(gear_box_efficiency, gear_box_power_out, delta_time
    ):
    """
    Calculates the gear box temperature heat [W].

    :param gear_box_efficiency:
        Gear box efficiency [-].
    :type gear_box_efficiency: float

    :param gear_box_power_out:
        Power at wheels [kW].
    :type gear_box_power_out: float

    :param delta_time:
        Time step [s].
    :type delta_time: float

    :return:
        Gear box heat [W].
    :rtype: float
    """
    if gear_box_efficiency and gear_box_power_out:
        eff = gear_box_efficiency
        return abs(gear_box_power_out) * (1.0 - eff) * 1000.0 * delta_time
    return 0.0


@classmethod
def from_remote(cls, config, remote):
    """Return an instance suitable for cloning into."""
    if config.strip_path:
        relative_path = remote.gitlab_path.relative_to(config.paths[0])
    else:
        relative_path = remote.gitlab_path
    instance = cls(config.base_path, relative_path)
    instance._gitlab_path = remote.gitlab_path
    return instance


@classmethod
def dphi_dt0(cls, theta, phi, phi1, phi2, r1=10, r2=10):
    """Fokkema2012, eq 4.19"""
    return -(cls.dphi_dt1(theta, phi, phi1, phi2, r1, r2) + cls.dphi_dt2(
        theta, phi, phi1, phi2, r1, r2))


def samestat(s1, s2):
    """Test whether two stat buffers reference the same file"""
    return s1.st_ino == s2.st_ino and s1.st_dev == s2.st_dev


@classmethod
def _compute_magnitude(cls, rup, coeffs):
    """
        Compute first two terms of equation (1) on p. 1200:

        ``b1 + b2 * M``
        """
    return coeffs['b1'] + coeffs['b2'] * rup.mag


def o(r, t):
    """
    Transform to the Boltzmann variable.

    Returns the Boltzmann variable at the given `r` and `t`, which is the
    result of applying the Boltzmann transformation:

    .. math::
        o(r,t) = r/\\sqrt t

    Parameters
    ----------
    r : float or numpy.ndarray
        Location(s). If a `numpy.ndarray`, it must have a shape broadcastable
        with `t`.
    t : float or numpy.ndarray
        Time(s). If a `numpy.ndarray`, it must have a shape broadcastable with
        `r`. Values must be positive.

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

    See also
    --------
    do_dr
    do_dt
    r
    t
    as_o
    """
    return r / t ** 0.5


def keyingset_button_remove():
    """Remove current UI-active property from current keying set

    """
    pass


def uri_for(reference):
    """
    Utility function for accessing the URI or a reference.

    :param reference:
    :return:
    """
    return reference._uri


def snake(s):
    """Convert from title or camelCase to snake_case."""
    if len(s) < 2:
        return s.lower()
    out = s[0].lower()
    for c in s[1:]:
        if c.isupper():
            out += '_'
            c = c.lower()
        out += c
    return out


def ask_if_snapshot_wanted():
    """Return whether user wants a snapshot."""
    says = input(
        """Would you like to generate a snapshot at the end?
If so, then once the routes are calculated (and displayed, if you wanted that),
you'll be asked to provide a time for the snapshot.
That snapshot will appear in the console here, and will also be stored in
a new file "package_snapshot.txt" in the directory you are running this from.
If you would like a snapshot later, press "y" or "yes", then Enter.
Otherwise, press any other key, like Enter or "n".
"""
        )
    return says.lower().strip() in ('y', 'yes')


def merge_glycan_substructure_dict_to_substructure_dict(
    glycan_substructure_dict, glycan_dict, combine_original=True):
    """
    merge glycan_substructure_dict to substructure_dict
    :param glycan_substructure_dict: dict_ID_dict_degree_list
    :param combine_original: Check if you need add the original glycan to the substructure-vec
    :return:
    """
    print('Start merge_glycan_substructure_to_substructure_dict')
    _substructure_dic = {}
    for i in sorted(list(glycan_substructure_dict.keys()), reverse=True):
        for j in glycan_substructure_dict[i].keys():
            if j not in _substructure_dic.keys():
                _substructure_dic[j] = glycan_substructure_dict[i][j][:]
            else:
                _substructure_dic[j].extend(glycan_substructure_dict[i][j][:])
    if combine_original:
        print('combine original')
        for i in glycan_dict.keys():
            if str(len(glycan_dict[i])) not in _substructure_dic.keys():
                print('add new glycan degree')
                _substructure_dic[str(len(glycan_dict[i]))] = [glycan_dict[i]]
            else:
                _substructure_dic[str(len(glycan_dict[i]))].append(glycan_dict
                    [i])
    return _substructure_dic


@classmethod
def from_dict(cls, d):
    """
        Construct a `Search` instance from a raw dict containing the search
        body. Useful when migrating from raw dictionaries.

        Example::

            s = Search.from_dict({
                "query": {
                    "bool": {
                        "must": [...]
                    }
                },
                "aggs": {...}
            })
            s = s.filter('term', published=True)
        """
    s = cls()
    s.update_from_dict(d)
    return s


@classmethod
def get_count(cls, request):
    """
        Get Total Count of dataset
        """
    raise NotImplementedError()


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

    The ".dev0" means dirty.

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


@classmethod
def index(class_, name):
    """helper; returns index of field name in row"""
    return class_.names().index(name)


def slot_copy():
    """Copy the material texture settings and nodes

    """
    pass


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

    :return: schema dictionary
    :rtype: dict
    """
    return {'mongo_indexes': {'index_updated': [('_updated', 1)],
        'index_name': [('name', 1)]}, 'schema': {'schema_version': {'type':
        'integer', 'default': 1}, 'imported_from': {'schema_version': 1,
        'title': 'Imported from', 'comment':
        'Item importation source (alignak-backend-import, ...)', 'type':
        'string', 'default': 'unknown'}, 'definition_order': {
        'schema_version': 1, 'title': 'Definition order', 'comment':
        'Priority level if several elements have the same name', 'type':
        'integer', 'default': 100}, 'name': {'schema_version': 1, 'title':
        'Hosts group name', 'comment': 'Unique hosts group name', 'type':
        'string', 'required': True, 'empty': False, 'unique': True},
        'alias': {'schema_version': 1, 'title': 'Alias', 'comment':
        'Element friendly name used by the Web User Interface.', 'type':
        'string', 'default': ''}, 'notes': {'schema_version': 1, 'title':
        'Notes', 'comment':
        'Element notes. Free text to store element information.', 'type':
        'string', 'default': ''}, 'notes_url': {'schema_version': 1,
        'title': 'Notes URL', 'comment':
        'Element notes URL. Displayed in the Web UI as some URL to be navigatesd. Note that a very specific text format must be used for this field, see the Web UI documentation.'
        , 'type': 'string', 'default': ''}, 'action_url': {'schema_version':
        1, 'title': 'Actions URL', 'comment':
        'Element actions URL. Displayed in the Web UI as some available actions. Note that a very specific text format must be used for this field, see the Web UI documentation.'
        , 'type': 'string', 'default': ''}, 'hostgroups': {'schema_version':
        1, 'title': 'Groups', 'comment': 'List of the groups of this group',
        'type': 'list', 'schema': {'type': 'objectid', 'data_relation': {
        'resource': 'hostgroup', 'embeddable': True}}, 'default': []},
        'hosts': {'schema_version': 1, 'title': 'Members', 'comment':
        'List of the members of this group', 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'host',
        'embeddable': True}}, 'default': []}, '_level': {'schema_version':
        1, 'title': 'Level', 'comment': 'Level in the hierarchy', 'type':
        'integer', 'default': 0}, '_parent': {'schema_version': 1, 'title':
        'Parent', 'comment': 'Immediate parent in the hierarchy', 'type':
        'objectid', 'data_relation': {'resource': 'hostgroup', 'embeddable':
        True}, 'nullable': True, 'default': None}, '_tree_parents': {
        'schema_version': 1, 'title': 'Parents', 'comment':
        'List of parents in the hierarchy', 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'hostgroup',
        'embeddable': True}}, 'default': []}, '_realm': {'schema_version':
        1, 'title': 'Realm', 'comment': 'Realm this element belongs to.',
        'type': 'objectid', 'data_relation': {'resource': 'realm',
        'embeddable': True}, 'required': True}, '_sub_realm': {
        'schema_version': 1, 'title': 'Sub-realms', 'comment':
        'Is this element visible in the sub-realms of its realm?', 'type':
        'boolean', 'default': True}, '_users_read': {'schema_version': 1,
        'type': 'list', 'schema': {'type': 'objectid', 'data_relation': {
        'resource': 'user', 'embeddable': True}}}, '_users_update': {
        'schema_version': 1, 'type': 'list', 'schema': {'type': 'objectid',
        'data_relation': {'resource': 'user', 'embeddable': True}}},
        '_users_delete': {'schema_version': 1, 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'user',
        'embeddable': True}}}}, 'schema_deleted': {}}


def _configSpecial_Volume3DOpts_clipPlane(target, parser, shortArg, longArg,
    helpText):
    """Configures the ``clipPlane`` option for the ``VolumeOpts`` class.
    This option allows a clip plane to be defined - the user provides
    the position, azimuth and inclination as a single argument.
    """
    parser.add_argument(shortArg, longArg, type=float, nargs=3, action=
        'append', metavar=('POS', 'AZI', 'INC'), help=helpText)


def getHistory(obj, oldestFirst=False, preserve=()):
    """Returns the history of a content.

        Return the oldest version first  when ``oldestFirst`` set to
        ``True``. Default is ``False`` (youngest version first).

        Returns a sequence (``IHistory``) of ``IVersionData`` objects.
        """


def __new__(cls, data=None, gap=None, moltype=None):
    """Returns a new Enumeration object.

        data can be any sequence that can be passed to the tuple() constructor.

        Takes gap as an argument but ignores it (handled in __init__).
        """
    data = data or []
    return tuple.__new__(cls, data)


@classmethod
def transform(cls, string):
    """ Transforms `string`. """
    raise NotImplementedError(
        "Method 'transform' isn't implemented in '{cls}' class".format(cls=
        cls.__name__))


@classmethod
def parse_lines(cls, lines):
    """Parse a list of lines."""
    reports = []
    for line_nb, line in enumerate(lines):
        response = cls.parse_line(line, line_nb)
        reports.append(response)
    return reports


def get_zre_from_tau(params, tau):
    """
    Get reionization redshift given optical depth tau

    :param params: :class:`.model.CAMBparams` instance
    :param tau: optical depth
    :return: reionization redshift (or negative number if error)
    """
    return params.Reion.get_zre(params, tau)


@classmethod
def from_url(cls, es_url):
    """Initialize an ElasticSearch with single url"""
    hosts = [es_url]
    return cls(hosts=hosts)


def set_buffer_sizes_constant(topology, buffer_size, buffer_unit='bytes',
    interfaces=None):
    """
    Assign a constant buffer size to all selected interfaces

    Parameters
    ----------
    topology : Topology or DirectedTopology
        The topology on which buffer sizes are applied.
    buffer_size : int
        The constant buffer_size to be applied to all interface
    buffer_unit : string, unit
        The unit of buffer sizes. Supported units are: *bytes* and *packets*
    interfaces : iterable container of tuples, optional
        Iterable container of selected interfaces on which buffer sizes are
        applied.
        An interface is defined by the tuple (u,v) where u is the node on which
        the interface is located and (u,v) is the link to which the buffer
        flushes.

    Examples
    --------
    >>> import fnss
    >>> topology = fnss.Topology()
    >>> topology.add_path([1, 2, 4, 5, 8])
    >>> fnss.set_buffer_sizes_constant(topology, 100000, buffer_unit='bytes',     ... interfaces=[(1,2), (5,8), (4,5)])
    """
    if buffer_size < 0:
        raise ValueError('The buffer_size argument cannot be negative')
    if interfaces is not None and 'buffer_unit' in topology.graph:
        curr_buffer_unit = topology.graph['buffer_unit']
        if curr_buffer_unit != buffer_unit:
            raise ValueError(
                'The topology already contains buffer sizes expressed in %s. Use that unit instead of %s'
                 % (curr_buffer_unit, buffer_unit))
    topology.graph['buffer_unit'] = buffer_unit
    edges = topology.edges() if interfaces is None else interfaces
    for u, v in edges:
        topology.adj[u][v]['buffer'] = buffer_size


def T(*args):
    """A function that always returns true. Any passed in parameters are ignored"""
    return True


def remove_nodes(max_nodes):
    """
    Deletes given max nodes
    :param max_nodes: list<MaxPlus.INode>
    """
    if type(max_nodes) not in [list, tuple]:
        max_nodes = [max_nodes]
    for obj in max_nodes:
        obj.Delete()


def mkcols(l, rows):
    """
    Compute the size of our columns by first making them a divisible of our row
    height and then splitting our list into smaller lists the size of the row
    height.
    """
    cols = []
    base = 0
    while len(l) > rows and len(l) % rows != 0:
        l.append('')
    for i in range(rows, len(l) + rows, rows):
        cols.append(l[base:i])
        base = i
    return cols


def getFormData(pos):
    """
    Function generating a script to extract data for a form element.

    @param pos position to extract data at
    @type QPoint
    @return script to extract form data
    @rtype str
    """
    source = """
(function() {{
    var e = document.elementFromPoint({0}, {1});
    if (!e || e.tagName.toLowerCase() != 'input')
        return;
    var fe = e.parentElement;
    while (fe) {{
        if (fe.tagName.toLowerCase() != 'form')
            break;
        fe = fe.parentElement;
    }}
    if (!fe)
        return;
    var res = {{
        method: fe.method.toLowerCase(),
        action: fe.action,
        inputName: e.name,
        inputs: [],
    }};
    for (var i = 0; i < fe.length; ++i) {{
        var input = fe.elements[i];
        res.inputs.push([input.name, input.value]);
    }}
    return res;
}})()"""
    return source.format(pos.x(), pos.y())


def chunks(l, n):
    """
    split successive n-sized chunks from a list.
    """
    for i in range(0, len(l), n):
        yield l[i:i + n]


@staticmethod
def _calculate_max_edges(machine_graph):
    """ Deduces the max incoming edges for any vertex

        :param machine_graph: the machine graph of the application
        :return:            the max number of incoming edges to any vertex in the application
        """
    max_in_edges = 0
    for vertex in machine_graph.vertices:
        n_incoming_edges = len(machine_graph.get_edges_ending_at_vertex(vertex)
            )
        if n_incoming_edges > max_in_edges:
            max_in_edges = n_incoming_edges
    return max_in_edges


def literal(text):
    """" Returns the given value, ignoring the tokens alltogether. """
    return lambda tokens: text


def rpc_list():
    """Returns registered RPC functions names.

    :rtype: tuple
    """
    return tuple()


def keys():
    """Allows user to input tokens and keys

        Returns:
            (token, tokenSecret, key, keysecret) (:obj: 'str'): Tuple containing API access credentials

            """
    token = input('Please enter access token: ')
    tokenSecret = input('Please enter access token secret: ')
    key = input('Please enter consumer key: ')
    keySecret = input('Please enter consumer key secret: ')
    return token, tokenSecret, key, keySecret


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 get_user_ip(request):
    """ Get the ipaddress of the user """
    ipaddress = request.environ.get('REMOTE_ADDR', None)
    if 'X-Forwarded-For' in request.headers.keys():
        ipaddress = request.headers['X-Forwarded-For']
    return ipaddress


def is_staff(request, view, obj=None):
    """
    Checks if the current user is a staff member.
    """
    return request.user.is_staff


@staticmethod
def disconnect(controller_widget, control_name, control_instance):
    """ Disconnect a 'Bool' controller trait and a 'BoolControlWidget'
        controller widget control.

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


def add_toc(source: str) ->str:
    """Add table of contents to the beginning of the page source"""
    result = (
        '<ac:structured-macro ac:macro-id="1" ac:name="toc" ac:schema-version="1"/>\n'
         + source)
    return result


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 keyingset_remove_selected():
    """Remove selected items (blue-gray rows) from active Keying Set

    """
    pass


def set_zero_nodata(raster):
    """
    Mask out any pixels which have value=0 (in addition to previously masked pixels)
    """
    return raster.copy_with(image=raster.image.filled(0), nodata=0)


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


def to_deg(value, loc):
    """
    Converts decimal coordinates into degrees, minutes and seconds tuple
    value is float gps-value, loc is direction list ["S", "N"] or ["W", "E"]
    return: tuple like (25, 13, 48.343 ,'N')
    """
    if value < 0:
        loc_value = loc[0]
    elif value > 0:
        loc_value = loc[1]
    else:
        loc_value = ''
    abs_value = abs(value)
    deg = int(abs_value)
    t1 = (abs_value - deg) * 60
    min = int(t1)
    sec = round((t1 - min) * 60, 5)
    return deg, min, sec, loc_value


def sfr_from_L_nu(luminosity):
    """Use Kennicutt (1998) conversion from UV luminosity to star formation rate.

    Parameters
    ----------

    luminosity:
        the luminosity in units of ergs s^-1 Hz^-1 anywhere between
        1500-2800 Angstroms.

    Returns
    -------

    The SFR in Msun/year.

    Notes
    -----

    Kennicutt (1998ARA&A..36..189K) says:

       SFR/(MSun/year) = 1.4 * 10^-28 (L_nu/ergs s^-1 Hz^-1)

    where L_nu is the UV luminosity anywhere between 1500-2800 Angstroms.
    """
    return 1.4e-28 * luminosity


def flush_edits():
    """Flush edit data from active editing modes

    """
    pass


def set_cache(session):
    """Set cache used by plugins."""
    if not hasattr(session, '_docstrings_cache'):
        session._docstrings_cache = {}
    if '_parsed_files' not in session._docstrings_cache:
        session._docstrings_cache['_parsed_files'] = set()
    if not hasattr(session, '_test_dirs_cache'):
        session._test_dirs_cache = set(), set()


def ping(*args, **kwargs):
    """
    Check if current application is running.

    :return: Pong response.
    """
    return {'pong': True}


def getAttribute(alternate=None):
    """Returns the current attribute.
        """


def get_current_phy_conf(update, device_id):
    """
    Lookup current configuration for a network device.

    This includes information such as the Wi-Fi channel.

    Returns a dictionary, which may be empty if no configuration was found.
    """
    hostConfig = update.cache_get('hostConfig')
    for dev in hostConfig.get('wifi', []):
        if dev.get('id', None) == device_id:
            return dev
    return {}


def locate(obj, parent, name=None):
    """Update a location's coordinates."""
    obj.__parent__ = parent
    obj.__name__ = name


@staticmethod
def zeros(shape, dtype=None):
    """Return a new tensor of given shape and type, filled with zeros.

        Parameters
        ----------
        shape : int or sequence of ints
            Shape of the new tensor.
        dtype : data-type, optional
            The desired data-type for the tensor.
        """
    raise NotImplementedError


def TanimotoDistances(fp1, fps):
    """
    Returns the tanimoto row based on fingeprints passed

    Parameters
    ----------
    fp1: rdkit fingerprint
        The rdkit fingerprint computed used as reference
    fps: list
        The list of the rdkit fingerprint computed

    Returns
    -------
    tanimotorow: list
        A list with the tanimoto row similarities
    """
    from rdkit import DataStructs
    tanimoto_row = []
    for fp2 in fps:
        tani = 1 - DataStructs.FingerprintSimilarity(fp1, fp2)
        tanimoto_row.append(tani)
    return tanimoto_row


def __material_vm(d):
    """ Fixed length data fields for visual materials. """
    return d[0:3], d[3], d[4], d[5:10], d[10], d[11], d[12:15], d[15], d[16]


@classmethod
def get_region_rep_profile(cls, gen_fpath, rev_summary, gid_col='gen_gids',
    cf_dset='cf_profile', rep_method='meanoid', err_method='rmse', weight=
    'gid_counts', n_profiles=1):
    """Class method for parallelization of rep profile calc.

        Parameters
        ----------
        gen_fpath : str
            Filepath to reV gen output file to extract "cf_profile" from.
        rev_summary : pd.DataFrame
            Aggregated rev supply curve summary file trimmed to just one
            region to get a rep profile for.
        gid_col : str
            Column label in rev_summary that contains the generation gids
            (data index in gen_fpath).
        cf_dset : str
            Dataset name to pull generation profiles from.
        rep_method : str
            Method identifier for calculation of the representative profile.
        err_method : str
            Method identifier for calculation of error from the representative
            profile.
        weight : str | None
            Column in rev_summary used to apply weighted mean to profiles.
            The supply curve table data in the weight column should have
            weight values corresponding to the gid_col in the same row.
        n_profiles : int
            Number of representative profiles to retrieve.

        Returns
        -------
        rep_profile : np.ndarray
            (time, n_profiles) array for the most representative profile(s)
        i_rep : list
            Column Index in profiles of the representative profile(s).
        gen_gid_reps : list
            Generation gid(s) of the representative profile(s).
        res_gid_reps : list
            Resource gid(s) of the representative profile(s).
        """
    r = cls(gen_fpath, rev_summary, gid_col=gid_col, cf_dset=cf_dset,
        rep_method=rep_method, err_method=err_method, weight=weight,
        n_profiles=n_profiles)
    return r.rep_profiles, r.i_reps, r.rep_gen_gids, r.rep_res_gids


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 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 _export(subs, shared):
    """Configure the `doorstop export` subparser."""
    info = 'export a document as YAML or another format'
    sub = subs.add_parser('export', description=info.capitalize() + '.',
        help=info, **shared)
    sub.add_argument('prefix', help="prefix of document to export or 'all'")
    sub.add_argument('path', nargs='?', help=
        "path to exported file or directory for 'all'")
    group = sub.add_mutually_exclusive_group()
    group.add_argument('-y', '--yaml', action='store_true', help=
        'output YAML (default when no path)')
    group.add_argument('-c', '--csv', action='store_true', help=
        "output CSV (default for 'all')")
    group.add_argument('-t', '--tsv', action='store_true', help='output TSV')
    group.add_argument('-x', '--xlsx', action='store_true', help='output XLSX')
    sub.add_argument('-w', '--width', type=int, help=
        'limit line width on text output')


def _remove_code(code, parameters):
    """Remove code that should not be generated."""
    for key in code:
        flag = 'no-' + key
        if flag in parameters and parameters[flag]:
            msg = '// Function %s not generated (compiled with -f%s)' % (key,
                flag)
            code[key] = format['exception'](msg)


def is_number(value) ->bool:
    """
        Check if value is a number
    """
    return isinstance(value, (float, int))


def _calculate_ranges(value, numsplits):
    """Calculate the number of ranges of bytes, return a list of ranges."""
    lst = []
    for i in range(numsplits):
        lst.append('{0}-{1}'.format(i if i == 0 else int(round(1 + i *
            value / (numsplits * 1.0), 0)), int(round(1 + i * value / (
            numsplits * 1.0) + value / (numsplits * 1.0) - 1, 0))))
    return tuple(lst)


def previous():
    """Move to previous folder

    """
    pass


def normalise_version_str(version_num, normal_len):
    """Normalise the length of the version string by adding .0 at the end

    >>> normalise_version_str(1.0, 3)
    1.0.0

    >>> normalise_version_str(1.0.0, 4)
    1.0.0.0
    """
    version_num_parts = len(version_num.split('.'))
    if version_num_parts < normal_len:
        for i in range(version_num_parts, normal_len):
            version_num = version_num + '.0'
    return version_num


@staticmethod
def p_var_selection_characteristic(p):
    """var_selection_characteristic : VAR_SELECTION_CHARACTERISTIC IDENT"""
    p[0] = p[2]


@staticmethod
def ascending(width=12):
    """Creates an ascending register inflection.

        ::

            >>> inflection = consort.RegisterInflection.ascending()
            >>> print(format(inflection))
            consort.tools.RegisterInflection(
                inflections=abjad.IntervalSegment(
                    (
                        abjad.NumberedInterval(-6),
                        abjad.NumberedInterval(6),
                        ),
                    item_class=abjad.NumberedInterval,
                    ),
                ratio=abjad.Ratio((1,)),
                )

        Emits new register inflection.
        """
    import consort
    half_width = abs(int(width / 2))
    return consort.RegisterInflection(inflections=(0 - half_width,
        half_width), ratio=(1,))


@staticmethod
def _indexing_repr(value):
    """Represent values as used in canonical slicing syntax"""
    if value is Ellipsis:
        return '...'
    elif isinstance(value, slice):
        start = value.start if value.start is not None else ''
        stop = value.stop if value.stop is not None else ''
        step = ':{}'.format(value.step) if value.step is not None else ''
        return '{}:{}{}'.format(start, stop, step)
    return repr(value)


def select_more():
    """Select connected parent/child objects

    """
    pass


def createDraft(userId, targetKey, factory=None):
    """Create a new draft for the given user id and target, indicated by
        a string key (normally a string representation for an uuid, but may be
        more complex). Returns the new draft.

        The ``factory`` parameter can be used to pass a custom factory to
        create the draft object. It should be callable that takes two
        arguments: userId and soruceKey. The factory may set the ``__name__``
        attribute on the returned draft. This will be used, but may have a
        numeric suffix appended to ensure uniqueness.

        If ``factory`` is omitted, a basic, annotatable ``IDraft`` object will
        be created.
        """


def format_email_addressee(user):
    """
		Takes an auth.User and outputs named email format "Jim Smith <jimsmith@blah.com>"
		when possible. Otherwise just returns email.

		Raw email instead of named format gets the attention of spam filters.
	"""
    if user.first_name and user.last_name:
        return '%s %s <%s>' % (user.first_name, user.last_name, user.email)
    elif user.first_name:
        return '%s %s <%s>' % (user.first_name, user.last_name, user.email)
    else:
        return user.email


def write_problems(problems, file, summarize=False, limit=0):
    """
    Write problems as restructured text to a file (or stdout/stderr).

    """
    w = file.write
    w('\n=================\nValidation Report\n=================\n')
    counts = dict()
    total = 0
    for i, p in enumerate(problems):
        if limit and i >= limit:
            break
        if total == 0 and not summarize:
            w('\nProblems\n========\n')
        total += 1
        code = p['code']
        if code in counts:
            counts[code] += 1
        else:
            counts[code] = 1
        if not summarize:
            ptitle = '\n%s - %s\n' % (p['code'], p['message'])
            w(ptitle)
            underline = ''
            for i in range(len(ptitle.strip())):
                underline += '-'
            underline += '\n'
            w(underline)
            for k in sorted(p.viewkeys() - set(['code', 'message', 'context'])
                ):
                w(':%s: %s\n' % (k, p[k]))
            if 'context' in p:
                c = p['context']
                for k in sorted(c.viewkeys()):
                    w(':%s: %s\n' % (k, c[k]))
    w('\nSummary\n=======\n\nFound %s%s problem%s in total.\n\n' % (
        'at least ' if limit else '', total, 's' if total != 1 else ''))
    for code in sorted(counts.viewkeys()):
        w(':%s: %s\n' % (code, counts[code]))
    return total


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


def vector_multiply(vector, value):
    """
    Multiples given vector by a value
    :param vector: list(float, float, float)
    :param value: float ,value to multiple vector by
    :return: list(float, float, float)
    """
    result = [vector[0] * value, vector[1] * value, vector[2] * value]
    return result


def getHeaders():
    """Return the response headers.

        The headers will be returned as a list of tuples according to the WSGI
        specification.
        """


def escape_zoho_characters_v2(input_string) ->str:
    """ Note: this is only needed for searching, as in the yield_from_page method.
    This is an example
    :param input_string:
    :return:
    """
    if '\\(' in input_string or '\\)' in input_string:
        return input_string
    else:
        table = str.maketrans({'(': '\\(', ')': '\\)'})
        return input_string.translate(table)


def set_params(data_size, required_shares, max_shares):
    """Set the params. They have to be exactly the same ones that were
        used for encoding."""


def save_mantid_MDHisto(dataArray, filename):
    """Save a file that can be read in using Mantid's LoadMD"""
    import h5py
    import numpy as np
    f = h5py.File(filename, 'w')
    top = f.create_group('MDHistoWorkspace')
    top.attrs['NX_class'] = 'NXentry'
    top.attrs['SaveMDVersion'] = 2
    data = top.create_group('data')
    data.attrs['NX_class'] = 'NXdata'
    signal = data.create_dataset('signal', data=dataArray.values,
        compression='gzip')
    signal.attrs['axes'] = ':'.join(dataArray.coords.dims)
    signal.attrs['signal'] = 1
    for axis in dataArray.coords.dims:
        axis_array = dataArray.coords[axis].values
        bin_size = (axis_array[-1] - axis_array[0]) / (len(axis_array) - 1)
        axis_array -= bin_size * 0.5
        axis_array = np.append(axis_array, axis_array[-1] + bin_size)
        a = data.create_dataset(axis, data=axis_array)
        a.attrs['frame'] = 'HKL'
        a.attrs['long_name'] = axis
        a.attrs['units'] = 'A^-1'
    data.create_dataset('errors_squared', data=dataArray.values,
        compression='gzip')
    data.create_dataset('mask', data=np.zeros(dataArray.shape, dtype=np.
        int8), compression='gzip')
    data.create_dataset('num_events', data=np.ones(dataArray.shape),
        compression='gzip')
    f.close()


@staticmethod
def _get_cfg_node(cfg, state):
    """
        Get the CFGNode object on the control flow graph given an angr state.

        :param angr.analyses.CFGEmulated cfg:   An instance of CFGEmulated.
        :param angr.SimState state:             The current state.
        :return: A CFGNode instance if the node exists, or None if the node cannot be found.
        :rtype: CFGNode or None
        """
    call_stack_suffix = state.callstack.stack_suffix(cfg.
        context_sensitivity_level)
    is_syscall = (state.history.jumpkind is not None and state.history.
        jumpkind.startswith('Ijk_Sys'))
    block_id = cfg._generate_block_id(call_stack_suffix, state.addr, is_syscall
        )
    return cfg.get_node(block_id)


def getTOFsig(ins, dsp):
    """get TOF peak profile sigma^2

    :param dict ins: instrument parameters with at least 'sig-0', 'sig-1' & 'sig-q'
      as values only
    :param float dsp: d-spacing of peak

    :returns: float getTOFsig: peak sigma^2

    """
    return ins['sig-0'] + ins['sig-1'] * dsp ** 2 + ins['sig-2'
        ] * dsp ** 4 + ins['sig-q'] * dsp


def union1d(ar1, ar2, aggregate_size=None):
    """
    Find the union of two tensors.

    Return the unique, sorted tensor of values that are in either of the two
    input tensors.

    Parameters
    ----------
    ar1, ar2 : array_like
        Input tensors. They are flattened if they are not already 1D.

    Returns
    -------
    union1d : Tensor
        Unique, sorted union of the input tensors.

    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.union1d([-1, 0, 1], [-2, 0, 2]).execute()
    array([-2, -1,  0,  1,  2])

    To find the union of more than two arrays, use functools.reduce:

    >>> from functools import reduce
    >>> reduce(mt.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2])).execute()
    array([1, 2, 3, 4, 6])
    """
    from ..base import unique, sort
    from .concatenate import concatenate
    result = unique(concatenate((ar1, ar2), axis=None), aggregate_size=
        aggregate_size)
    if aggregate_size == 1:
        return result
    return sort(result)


@classmethod
def assertEqual(cls, first, second, msg=None):
    """
        Classmethod equivalent to unittest.TestCase method
        """
    asserter = None
    if type(first) is type(second):
        asserter = cls.equality_type_funcs.get(type(first))
        try:
            basestring = basestring
        except NameError:
            basestring = str
        if asserter is not None:
            if isinstance(asserter, basestring):
                asserter = getattr(cls, asserter)
    if asserter is None:
        asserter = cls.simple_equality
    if msg is None:
        asserter(first, second)
    else:
        asserter(first, second, msg=msg)


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = ' (HEAD -> master, tag: v2.2.0)'
    git_full = '2e7e671565cc19c814f7093912c92a734e3bfb61'
    git_date = '2018-11-25 23:01:21 -0500'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


@classmethod
def get_period_start_datetime(cls, log_time, summary_freq):
    """Periods can be: days, weeks, months, years.
        Days referenced from midnight on the current computer's clock.
        Weeks referenced from Monday morning @ 00:00:00am.
        Months and years follow from the above."""
    summary_freq_qty = summary_freq[0]
    summary_freq_period = summary_freq[1].lower()
    base_time = log_time.replace(microsecond=0, second=0, minute=0, hour=0)
    if summary_freq_period in ['day', 'days']:
        assert summary_freq_qty == 1, 'Days only supports 1'
        return base_time
    elif summary_freq_period in ['week', 'weeks']:
        assert summary_freq_qty == 1, 'Weeks only supports 1'
        raise NotImplementedError('Still working to implement weeks.')
    elif summary_freq_period in ['month', 'months']:
        assert summary_freq_qty in [1, 2, 3, 4, 6
            ], 'Months only supports [1,2,3,4,6]'
        return base_time.replace(day=1, month=log_time.month /
            summary_freq_qty * summary_freq_qty)
    elif summary_freq_period in ['year', 'years']:
        assert summary_freq_qty in [1, 2, 3, 4, 6], 'Years only supports 1'
        return base_time.replace(day=1, month=1)
    else:
        raise NotImplementedError(
            'Unrecognized summary frequency period: %s' % summary_freq_period)


@classmethod
def _compute_soil_amplification(cls, C, vs30, pga_rock, imt):
    """
        Compute soil amplification (5th, 6th, and 7th terms in equation 1,
        page 1706).
        """
    Sc, Sd, Se = cls._compute_site_class_dummy_variables(vs30)
    sl = cls._compute_soil_linear_factor(pga_rock, imt)
    return C['c5'] * sl * Sc + C['c6'] * sl * Sd + C['c7'] * sl * Se


def normalize_slice(s):
    """ Replace Nones in slices with integers

    >>> normalize_slice(slice(None, None, None))
    slice(0, None, 1)
    """
    start, stop, step = s.start, s.stop, s.step
    if start is None:
        start = 0
    if step is None:
        step = 1
    if start < 0 or step < 0 or stop is not None and stop < 0:
        raise NotImplementedError()
    return slice(start, stop, step)


def get_default_max_worker_restart(config):
    """gets the default value of --max-worker-restart option if it is not provided.

    Use a reasonable default to avoid workers from restarting endlessly due to crashing collections (#226).
    """
    result = config.option.maxworkerrestart
    if result is not None:
        result = int(result)
    elif config.option.numprocesses:
        result = config.option.numprocesses * 4
    return result


def p_fields1(p):
    """
    fields : value_fields TERMINAL_FIELD
    """
    p[0] = p[1]


@staticmethod
def get_filename_image():
    """
        Retorna a url da imagem da infog2 como padrão
        :return: a url
        """
    return (
        'https://cdn3.iconfinder.com/data/icons/meanicons-4/512/meanicons_60-128.png'
        )


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


@classmethod
def prepend(cls, draw_func):
    """
        Prepend a draw function to this menu, takes the same arguments as
        the menus draw function
        """
    draw_funcs = cls._dyn_ui_initialize()
    draw_funcs.insert(0, draw_func)


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 UpSampling(*data, **kwargs):
    """Upsamples the given input data.

    Two algorithms (``sample_type``) are available for upsampling:

    - Nearest Neighbor
    - Bilinear

    **Nearest Neighbor Upsampling**

    Input data is expected to be NCHW.

    Example::

      x = [[[[1. 1. 1.]
             [1. 1. 1.]
             [1. 1. 1.]]]]

      UpSampling(x, scale=2, sample_type='nearest') = [[[[1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]
                                                         [1. 1. 1. 1. 1. 1.]]]]

    **Bilinear Upsampling**

    Uses `deconvolution` algorithm under the hood. You need provide both input data and the kernel.

    Input data is expected to be NCHW.

    `num_filter` is expected to be same as the number of channels.

    Example::

      x = [[[[1. 1. 1.]
             [1. 1. 1.]
             [1. 1. 1.]]]]

      w = [[[[1. 1. 1. 1.]
             [1. 1. 1. 1.]
             [1. 1. 1. 1.]
             [1. 1. 1. 1.]]]]

      UpSampling(x, w, scale=2, sample_type='bilinear', num_filter=1) = [[[[1. 2. 2. 2. 2. 1.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [2. 4. 4. 4. 4. 2.]
                                                                           [1. 2. 2. 2. 2. 1.]]]]

    Defined in src/operator/nn/upsampling.cc:L173
    This function support variable length of positional input.

    Parameters
    ----------
    data : Symbol[]
        Array of tensors to upsample. For bilinear upsampling, there should be 2 inputs - 1 data and 1 weight.
    scale : int, required
        Up sampling scale
    num_filter : int, optional, default='0'
        Input filter. Only used by bilinear sample_type.Since bilinear upsampling uses deconvolution, num_filters is set to the number of channels.
    sample_type : {'bilinear', 'nearest'}, required
        upsampling method
    multi_input_mode : {'concat', 'sum'},optional, default='concat'
        How to handle multiple input. concat means concatenate upsampled images along the channel dimension. sum means add all images together, only available for nearest neighbor upsampling.
    workspace : long (non-negative), optional, default=512
        Tmp workspace for deconvolution (MB)

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

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


def _concat_ids(spark, dataset, columnNames):
    """Concatenates structureId and chainId fields into a single key if chainId
    field is present

    Parameters
    ----------
    spark : :obj:`SparkSession <pyspark.sql.SparkSession>`
    dataset : Dataframe
    columnNames : list
    """
    if 'chainId' in dataset.columns:
        dataset.createOrReplaceTempView('table')
        sql = (
            "SELECT CONCAT(structureId,'.',chainId) as structureChainId," +
            'structureId,chainId,%s' % ','.join(columnNames) + ' from table')
        dataset = spark.sql(sql)
    return dataset


@classmethod
def values(cls):
    """
        Return the possible values that this enum can take on.

        Returns:
            list: A list of strings of the values that this enum can represent.
        """
    return list(cls._reg.keys())


def observed_name(name):
    """Return `_name_observed`."""
    return '_{}_observed'.format(name)


def vo_raise(exception_class, args=(), config=None, pos=None):
    """
    Raise an exception, with proper position information if available.
    """
    if config is None:
        config = {}
    raise exception_class(args, config, pos)


def bech32_polymod(values):
    """Internal function that computes the Bech32 checksum."""
    generator = [996825010, 642813549, 513874426, 1027748829, 705979059]
    chk = 1
    for value in values:
        top = chk >> 25
        chk = (chk & 33554431) << 5 ^ value
        for i in range(5):
            chk ^= generator[i] if top >> i & 1 else 0
    return chk


def broadcast_not_equal(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Returns the result of element-wise **not equal to** (!=) comparison operation with broadcasting.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_not_equal(x, y) = [[ 1.,  1.,  1.],
                                    [ 0.,  0.,  0.]]

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L64

    Parameters
    ----------
    lhs : NDArray
        First input to the function
    rhs : NDArray
        Second input to the function

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

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


@staticmethod
def connect():
    """Connect the transport class. This function must be overridden.
        :return: True-like value when connection successful,
                 False-like value otherwise."""
    return False


def inverseDict(data):
    """
    Inverse a dictionary.

    >>> inverseDict({"0x10": 16, "0x20": 32}) == {32: '0x20', 16: '0x10'}
    True
    """
    result = {}
    for key, value in data.items():
        result[value] = key
    return result


def __len__():
    """Return the number of results (with start/limit restrictions), that
        is the same than count.
        """


def poke_64(library, session, address, data):
    """Write an 64-bit value from the specified address.

    Corresponds to viPoke64 function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param address: Source address to read the value.
    :param data: value to be written to the bus.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viPoke64(session, address, data)


def adaptive_regularization_weights_from_pixel_signals(inner_coefficient,
    outer_coefficient, pixel_signals):
    """Compute the regularization weights, which are the effective regularization coefficient of every     pixel. They are computed using the (hyper) pixel-signal of each pixel.

    Two regularization coefficients are used, corresponding to the:

    1) (pixel_signals) - pixels with a high pixel-signal (i.e. where the signal is located in the pixelization).
    2) (1.0 - pixel_signals) - pixels with a low pixel-signal (i.e. where the signal is not located in the      pixelization).

    Parameters
    ----------
    coefficients : (float, float)
        The regularization coefficients which controls the degree of smoothing of the inversion reconstruction.
    pixel_signals : ndarray
        The estimated signal in every pixelization pixel, used to change the regularization weighting of high signal         and low signal pixelizations.
    """
    return (inner_coefficient * pixel_signals + outer_coefficient * (1.0 -
        pixel_signals)) ** 2.0


def setResponseCode(code, message=None):
    """
        Set the HTTP response code.
        """


def unlock_all():
    """Unlock all Grease Pencil layers so that they can be edited

    """
    pass


@classmethod
def _can_handle_query(cls, *query):
    """
        Answers whether client can service the query.

        Parameters
        ----------
        query : list of query objects

        Returns
        -------
        boolean
            answer as to whether client can service the query
        """
    chk_var = 0
    for x in query:
        if x.__class__.__name__ == 'Instrument' and x.value.lower() == 'eve':
            chk_var += 1
        elif x.__class__.__name__ == 'Level' and x.value == 0:
            chk_var += 1
    if chk_var == 2:
        return True
    return False


def base64_str_to_img(base64_str):
    """
    Convert base64 string to an image array. The function can handle raw string or bytes encoded sting.

    Arguments:
    ----------
        base64_str: bytes or raw string of image in base64 format

    Returns:
    --------
        img: standard image array
    """
    import base64
    import io
    import cv2
    import imageio
    if type(base64_str) == type(b''):
        base64_str = base64_str.decode()
    img = imageio.imread(io.BytesIO(base64.b64decode(base64_str)))
    return img


def _canonicalize_extension(ext):
    """Returns a transformed ext that has a uniform pattern.
    Specifically, if ``ext`` has a leading . then it is simply returned.
    If ``ext`` doesn't have a leading . then it is prepended.
    Exceptions to this are if ``ext`` is ``None`` or "". If ``ext``
    is "" then "" is return. If ``ext`` is None then None is returned.

    :param ext: The extension to canonicalize.
    :returns: The canonicalized extension.

    """
    if ext is None or ext == '' or ext.startswith('.'):
        return ext
    return '.' + ext


def get_numpy_include_path():
    """
    Gets the path to the numpy headers.
    """
    import builtins
    if hasattr(builtins, '__NUMPY_SETUP__'):
        del builtins.__NUMPY_SETUP__
    import imp
    import numpy
    imp.reload(numpy)
    try:
        numpy_include = numpy.get_include()
    except AttributeError:
        numpy_include = numpy.get_numpy_include()
    return numpy_include


def subscribe(subscriber, type_name=None):
    """
        Makes 'subscriber' a subscriber of the list.  'subscriber' can be
        any of the supported subscription types.
        """


def str_to_span(string):
    """ Return the equivalent interval time in seconds.

    Parameters
    ----------
    string : str
        Time periodicity

    Returns
    -------
    span : int
        Number of seconds in time interval.

    Examples
    --------
    >>> str_to_span('minutely')
    60

    """
    if string.lower() in ['weekly', 'week', '7d', '1w', 'w']:
        return 604800
    elif string.lower() in ['daily', 'day', '24h', '1d', 'd']:
        return 86400
    elif string.lower() in ['bi-hourly', 'bi-hour', '2h']:
        return 7200
    elif string.lower() in ['hourly', 'hour', '1h', '60min', 'h']:
        return 3600
    elif string.lower() in ['half-hourly', 'half-hour', '30min']:
        return 1800
    elif string.lower() in ['5-minute', 'five-minute', '5 minute',
        'five minute', '5min']:
        return 300
    elif string.lower() in ['minutely', 'minute', '1min', 'min']:
        return 60
    else:
        print(
            """Error, string not understood.
String must be "minutely", "5 minute", "hourly", "daily" or "weekly"."""
            )


def _get_filename(fd):
    """
    Helper function to get to file name from a file descriptor or filename.

    :param fd: file descriptor or filename.

    :returns: the filename.
    """
    if hasattr(fd, 'name'):
        return fd.name
    return fd


def next_hypercube(pos, div):
    """Jumps to next hypercube in cubical cover

    Parameters
    ----------
    pos : :obj:`list`
        List of integer values specifying the position of the current
        hypercube. This is edited to the next hypercube.

    div : :obj:`list`
        List of integer values specifying how many hypercubes divide each
        dimension.

    Example
    -------
        >>> pos = [1,1,1]
        >>> div = [3,3,2]
        >>> next_hypercube(pos, div)
        >>> pos
        [1, 2, 0]

    """
    for i in range(len(pos)):
        if pos[-i - 1] < div[-i - 1] - 1:
            pos[-i - 1] += 1
            for k in range(i):
                pos[-k - 1] = 0
            break


@staticmethod
def conll_as_string(doc):
    """ Dump the loaded CoNLL-U format list data to string. """
    return_string = ''
    for sent in doc:
        for ln in sent:
            return_string += '\t'.join(ln) + '\n'
        return_string += '\n'
    return return_string


@classmethod
def register_model(cls, ModelClass, form_field=None, widget=None, title=
    None, prefix=None):
    """
        Register a model to use in the URL field.

        This function needs to be called once for every model
        that should be selectable in the URL field.

        :param ModelClass: The model to register.
        :param form_field: The form field class used to render the field. This can be a lambda for lazy evaluation.
        :param widget: The widget class, can be used instead of the form field.
        :param title: The title of the model, by default it uses the models ``verbose_name``.
        :param prefix: A custom prefix for the model in the serialized database format. By default it uses "appname.modelname".
        """
    cls._static_registry.register(ModelClass, form_field, widget, title, prefix
        )


def __call__(cls, *args, **kwargs):
    """
        Возвращает экземпляр класса. Наличие данной функции говорит о том,
        что класс является функтором (функциональным объектом).
        @param args: дополнительные параметры в виде списка.
        @param kwargs: дополнительные параметры в виде словаря.
        @return: экземпляр класса.
        """
    if cls.__instance is None:
        cls.__instance = super().__call__(*args, **kwargs)
    return cls.__instance


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

    The ".dev0" means dirty.

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


@classmethod
def compare(cls, target, reference, substituents=True, tolerance=0, visited
    =None):
    """
        A generalization of :meth:`~Monosaccharide.topological_equality` which allows for ``target``
        to be matched to ``reference``, but for ``reference`` to include more. Consequently,
        this method is not commutative.

        Parameters
        ----------
        target: :class:`~.Monosaccharide`
            The monosaccharide to compare
        reference: :class:`~.Monosaccharide`
            The monosaccharide to compare against
        substituents: :class:`bool`, optional
            Whether or not to compare with the substituents of each node. Defaults
            to :const:`True`.
        tolerance: :class:`float`, optional
            The maximum difference to permit between nodes for inclusion. Defaults
            to 0

        Returns
        -------
        :class:`float`
            The inclusion score. Greater than 0 indicates topological inclusion,
            though larger corresponds to better alignment.

        See Also
        --------
        :func:`~.commutative_similarity_score_with_tolerance`
        exact_ordering_inclusion
        """
    inst = cls(target, reference, substituents=substituents, tolerance=
        tolerance, visited=visited)
    score = inst.test()
    return score


@staticmethod
def _find_description(module):
    """
        Set the description module param to name if description is blank
        :param module: the module to validate
        :return: string description
        """
    description = module.params.get('description')
    if not description:
        description = module.params.get('name')
    return description


def make_url(region, bucket_name, obj_path, version=None):
    """
        This link describes the format of Path Style URLs
        http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro
    """
    base = 'https://s3.amazonaws.com'
    if region and region != 'us-east-1':
        base = 'https://s3-{0}.amazonaws.com'.format(region)
    result = '{0}/{1}/{2}'.format(base, bucket_name, obj_path)
    if version:
        result = '{0}?versionId={1}'.format(result, version)
    return result


def read_homefile(filepath: str='', load_ui: bool=True):
    """Open the default file (doesn’t save the current file)

    :param filepath: File Path, Path to an alternative start-up file
    :type filepath: str
    :param load_ui: Load UI, Load user interface setup from the .blend file
    :type load_ui: bool
    """
    pass


def load_spec(filename):
    """
    Load a protobuf model specification from file

    Parameters
    ----------
    filename: str
        Location on disk (a valid filepath) from which the file is loaded
        as a protobuf spec.

    Returns
    -------
    model_spec: Model_pb
        Protobuf representation of the model

    Examples
    --------
    .. sourcecode:: python

        >>> spec = coremltools.utils.load_spec('HousePricer.mlmodel')

    See Also
    --------
    save_spec
    """
    from ..proto import Model_pb2
    spec = Model_pb2.Model()
    with open(filename, 'rb') as f:
        contents = f.read()
        spec.ParseFromString(contents)
        return spec


@staticmethod
def reset(sample_idx):
    """Reset layer variables."""
    pass


@classmethod
def getDrainInfo(cls):
    """
        Return drainStats class variable
        """
    return cls.drainStats


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

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

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


@classmethod
def testnet_network(cls) ->'Network':
    """Get the :class:`Network` object representing the TESTNET Network.

        :return: TESTNET Network
        """
    return cls(cls.TESTNET_NETWORK_PASSPHRASE)


def unquote_plus(bs):
    """Bytes version of urllib.parse.unquote_plus."""
    bs = bs.replace(b'+', b' ')
    atoms = bs.split(b'%')
    for i in range(1, len(atoms)):
        item = atoms[i]
        try:
            pct = int(item[:2], 16)
            atoms[i] = bytes([pct]) + item[2:]
        except ValueError:
            pass
    return b''.join(atoms)


def str_display_width(s):
    """
        from elist.utils import *
        str_display_width('a')
        str_display_width('去')
    """
    s = str(s)
    width = 0
    len = s.__len__()
    for i in range(0, len):
        sublen = s[i].encode().__len__()
        sublen = int(sublen / 2 + 1 / 2)
        width = width + sublen
    return width


def is_greyscale_palette(palette):
    """Return whether the palette is greyscale only."""
    for i in range(256):
        j = i * 3
        if palette[j] != palette[j + 1] != palette[j + 2]:
            return False
    return True


def _get_corner_points(x0, y0, x1, y1):
    """
    Returns the corner points of a scatter rectangle

    :param x0: x-start
    :param y0: y-lower
    :param x1: x-end
    :param y1: y-upper
    :return: ([x], [y]), tuple of lists containing the x and y values
    """
    return [x0, x1, x1, x0], [y0, y0, y1, y1]


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

        :param ShowcaseDeleteCommentType val:
        :rtype: EventType
        """
    return cls('showcase_delete_comment', val)


def overlay(old_values, new_values):
    """Overlay a new set of values on an old set.
       If old_values[i] != new_values[i], uses new_values[i],
       except if new_values[i] evaluates to False.
    """
    overlaid_vals = []
    for ov, nv in zip(old_values, new_values):
        if not nv or ov == nv:
            overlaid_vals.append(ov)
        else:
            overlaid_vals.append(nv)
    return overlaid_vals


def get_episode(series, episode_season, episode_number, language=None):
    """
  Get an episode informations.

  :param series: the series created with :func:`~thetvdb_api.api.set_series`
  :param episode_season: the number of the season
  :type episode_season: int or str
  :param episode_number: the number of the episode in the season
  :type episode_number: int or str
  :param language: a language accepted by theTVDB.com (see :doc:`languages`)
  :type language: str or None
  :returns: a dictionary of all the episode informations provided by theTVDB.com.
  :rtype: dict
  :raises: :mod:`thetvdb_api.theTVDBError` if something went wrong
  """
    return series.get_episode(episode_season, episode_number, language)


def generic(rank, fetch, values, argument):
    """
    Yield (value, score) pairs from values' attributes against the argument,
    according to rank.
    """
    for value in values:
        generate = fetch(value)
        attributes = tuple(generate)
        if not attributes:
            continue
        score = rank(attributes, argument)
        yield value, score


@classmethod
def disassemble(cls, *args):
    """
        Disassemble the integer arguments into an operation. Subclasses do not
        generally need to override this method; it is provided only for the special
        purposes of the INC and DEC classes.
        """
    return cls(*args)


@classmethod
def topic(cls, **kwargs) ->str:
    """Get MQTT topic for this message type."""
    return 'hermes/hotword/toggleOff'


def textfile_generator(textfile, linebreak=True, encoding=None):
    """ Return a generator that reads lines in a text file.

    :param textfile: file object of a text file
    :param linebreak: whether to return a line break at the end of each line (Default: True)
    :param encoding: encoding of the text file (Default: None)
    :return: a generator that reads lines in a text file
    :type textfile: file
    :type linebreak: bool
    :type encoding: str
    :rtype: generator
    """
    for t in textfile:
        if len(t) > 0:
            if encoding is None:
                yield t.strip() + ('\n' if linebreak else '')
            else:
                yield t.decode(encoding).strip() + ('\n' if linebreak else '')


@staticmethod
def getHelp():
    """Returns link to online manual"""
    help = (
        'See manual, available on the MOTHUR wiki:\nhttp://schloss.micro.umass.edu/mothur/'
        )
    return help


def select_less():
    """Deselect UV vertices at the boundary of each selection region

    """
    pass


def get_arraytype():
    """pygame.surfarray.get_arraytype (): return str

    DEPRECATED - only numpy arrays are now supported.
    """
    return 'numpy'


def get_non_mapped_fs(row):
    """
    those entries without the fs length
    """
    if 'CSQN=Frameshift;imprecise' in row['info']:
        return True
    return False


@classmethod
def remove_by_example(cls, collection, example_data, wait_for_sync=None,
    limit=None):
    """
            This will find all documents in the collection that match the specified example object.

            Note: the limit attribute is not supported on sharded collections. Using it will result in an error.
            The options attributes waitForSync and limit can given yet without an ecapsulation into a json object.
            But this may be deprecated in future versions of arango

            Returns result dict of the request.

            :param collection Collection instance
            :param example_data An example document that all collection documents are compared against.

            :param wait_for_sync  if set to true, then all removal operations will instantly be synchronised to disk.
            If this is not specified, then the collection's default sync behavior will be applied.

            :param limit an optional value that determines how many documents to replace at most. If limit is
            specified but is less than the number of documents in the collection, it is undefined which of the
            documents will be replaced.
        """
    kwargs = {'options': {'waitForSync': wait_for_sync, 'limit': limit}}
    return cls._construct_query(name='remove-by-example', collection=
        collection, example=example_data, result=False, **kwargs)


def season_episode_number(name):
    """
    Extract Season & Episode number from file name.

    Args:
        name: File name

    Returns: Season number & episode number
    """
    fix = {'0423uncut.html': '0423-0424.html', '0624.html':
        '0624-0625.html', '0723.html': '0723-0724.html', '0823.html':
        '0823-0824.html'}
    if name in fix:
        name = fix[name]
    num = name.split('.')[0]
    season = num[:2]
    episode = num[2:4]
    if '-' in num:
        episode += '-' + num[7:9]
    return season, episode


def match(trace, source, destination, channel=None):
    """
    Find matching rows in the k7
    :param pandas.Dataframe trace:
    :param int source:
    :param int destination:
    :param int channel:
    :return: None | pandas.core.series.Series
    """
    for index, row in trace.iterrows():
        if row['src'] == source and row['dst'] == destination and row['channel'
            ] == channel:
            return row
    return None


def _chunks_(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]


def intersect_point_tri(pt: 'mathutils.Vector', tri_p1: 'mathutils.Vector',
    tri_p2: 'mathutils.Vector', tri_p3: 'mathutils.Vector'
    ) ->'mathutils.Vector':
    """Takes 4 vectors: one is the point and the next 3 define the triangle.

    :param pt: Point
    :type pt: 'mathutils.Vector'
    :param tri_p1: First point of the triangle
    :type tri_p1: 'mathutils.Vector'
    :param tri_p2: Second point of the triangle
    :type tri_p2: 'mathutils.Vector'
    :param tri_p3: Third point of the triangle
    :type tri_p3: 'mathutils.Vector'
    :return:  Point on the triangles plane or None if its outside the triangle
    """
    pass


def nrow(records):
    """Return the number of rows in the records

    :param records: a list of dictionaries
    :returns: an integer

    >>> movies = [
    ... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
    ... {'title': 'Life of Brian', 'year': 1979, 'budget': 4E6, 'total_gross': 20E6},
    ... {'title': 'The Meaning of Life', 'year': 1983, 'budget': 9E6, 'total_gross': 14.9E6}
    ... ]
    >>> nrow(movies)
    3

    """
    return len(records)


def index_startswith_substring(the_list, substring):
    """What is this? What is it used for?"""
    for i, s in enumerate(the_list):
        if s.startswith(substring):
            return i
    return -1


def format_lazy_import(names):
    """Formats lazy import lines"""
    lines = ''
    for _, name, asname in names:
        pkg, _, _ = name.partition('.')
        if asname is None:
            line = '{pkg} = _LazyModule.load({pkg!r}, {mod!r})\n'
        else:
            line = (
                '{asname} = _LazyModule.load({pkg!r}, {mod!r}, {asname!r})\n')
        lines += line.format(pkg=pkg, mod=name, asname=asname)
    return lines


@staticmethod
def _group_to_string(group_by):
    """Returns a string representation of the specified grouping
        fields.

        This is essentially the inverse operation of the parsing that is
        done when reading the grouping fields from the query parameters
        of the request string in a :http:method:`get` request.

        """
    return ','.join(group_by)


def set_id(node_label, old_id, new_id):
    """Generate a subquery to set new id for the node."""
    query = "MATCH (n:{} {{id : '{}'}})\n".format(node_label, old_id
        ) + "SET n.id = '{}'".format(new_id)
    return query


def unaligned_read(read, tags=[]):
    """Create an unaligned sam record for a read.

    :param read: a `Read` namedtuple.
    :param tags: list containing additional tags to add to sam record.

    :returns: a (string) sam record.
    """
    sam = '\t'.join((read.read_id, '4', '*', '0', '255', '*', '*', '0', '0',
        read.sequence, read.quality, *tags))
    return sam


def fill_blanks(aut, as_bdd=False, rabin=False):
    """Add `"True"` to empty attributes `init`, `action`, `win`.

    @param as_bdd: if `True`, then represent `"True"` as `1`
    """
    if as_bdd:
        true = aut.bdd.true
        false = aut.bdd.false
    else:
        true = 'True'
        false = 'False'
    for d in (aut.init, aut.action):
        for k, v in d.items():
            if not v:
                d[k] = [true]
    if not aut.win['<>[]']:
        if rabin:
            aut.win['<>[]'] = [true]
        else:
            aut.win['<>[]'] = [false]
    if not aut.win['[]<>']:
        aut.win['[]<>'] = [true]
    for d in (aut.init, aut.action, aut.win):
        for k in d:
            assert len(d[k]) > 0


@classmethod
def get_erase_command(cls, block: str) ->str:
    """Get the erase command for a specified block kind"""
    return getattr(cls, 'CMD_ERASE_%s' % block.upper())


def mapfi(ol, map_func_args, **kwargs):
    """
        #mapfi            共享相同的o,v不作为map_func参数
        #                 share common other_args,NOT take value as a param for map_func
        #map_func         diff_func(index,*common_args)
    """
    diff_funcs_arr = kwargs['map_funcs']
    lngth = ol.__len__()
    rslt = []
    for i in range(0, lngth):
        index = i
        value = ol[i]
        func = diff_funcs_arr[i]
        args = map_func_args
        ele = func(index, *args)
        rslt.append(ele)
    return rslt


def read_file(filename, mode='r'):
    """ Reads from 'filename' """
    with open(filename, mode) as file_to_read:
        return file_to_read.read()


def find_cycle(targets):
    """
    Given a dict representing a target dependency graph, return a list of any
    nodes involved in a dependency cycle.  Returns the first cycle found.
    """
    todo = set(targets.keys())
    while todo:
        node = todo.pop()
        stack = [node]
        while stack:
            top = stack[-1]
            for node in targets[top]:
                if node in stack:
                    return stack[stack.index(node):]
                if node in todo:
                    stack.append(node)
                    todo.remove(node)
                    break
            else:
                node = stack.pop()
    return None