@classmethod
def list(cls, context, limit=None, marker=None, sort_key=None, sort_dir=None):
    """Return a list of Portgroup objects.

        :param cls: the :class:`Portgroup`
        :param context: Security context.
        :param limit: Maximum number of resources to return in a single result.
        :param marker: Pagination marker for large data sets.
        :param sort_key: Column to sort results by.
        :param sort_dir: Direction to sort. "asc" or "desc".
        :returns: A list of :class:`Portgroup` object.
        :raises: InvalidParameterValue

        """
    db_portgroups = cls.dbapi.get_portgroup_list(limit=limit, marker=marker,
        sort_key=sort_key, sort_dir=sort_dir)
    return cls._from_db_object_list(context, db_portgroups)


def __iter__():
    """Return an iterator object.
        """


def compute_auc(xs, ys):
    """
  Compute area under curve (AuC).

  Parameters
  ----------
  xs : list
    A list of x values.
  ys : list
    A list of y values corresponding to x.

  Returns
  -------
  float
    Area under curve.
  """
    length = xs[-1] - xs[0]
    area = 0
    for i in range(len(ys) - 1):
        area += (ys[i] + ys[i + 1]) * (xs[i + 1] - xs[i]) / 2 / length
    return area


@staticmethod
def _parkey_from_filename(filename):
    """Extract parkey from component filename in the format of
        ``name[parkey#]``.

        """
    if filename.endswith('#]'):
        x = filename.split('[')
        parkey = x[1][:-2]
    else:
        parkey = None
    return parkey


def get_node_presence_from_link(node_presence, n, b, e):
    """
    Return the maximal temporal node corresponding to (b,e,n)
    :param n: node
    :param b: beginning of the interval (time)
    :param e: ending of the interval (time)
    :return: Maximal temporal node presence corresponding to (b,e,n) : (t0,t1)
    """
    for t0, t1 in zip(node_presence[n][::2], node_presence[n][1::2]):
        if t0 <= b and e <= t1:
            return t0, t1
    return None


def get_field(fields, field):
    """Returns fields[field], raises AttributeError on KeyError."""
    try:
        return fields[field]
    except KeyError:
        raise AttributeError("'syrecord' object has no attribute '{0}'".
            format(field))


def rollback():
    """Rollback changes for transaction capable ICacheAreas"""


@classmethod
def get(cls, project_id, blueprint_id):
    """ Retrieve a blueprint chart.

        Parameters
        ----------
        project_id : str
            The project's id.
        blueprint_id : str
            Id of blueprint to retrieve chart.

        Returns
        -------
        BlueprintChart
            The queried blueprint chart.
        """
    url = 'projects/{}/blueprints/{}/blueprintChart/'.format(project_id,
        blueprint_id)
    return cls.from_location(url)


@classmethod
def get_children_attr(cls, obj):
    """
        >>> class A: hello="world"
        >>> list(filter(lambda f: not f[0].startswith("_"), JsonFind.get_children_attr(A)))
        [('hello', 'world')]
        """
    return obj.__dict__.items()


@classmethod
def global_config(cls, key, *args):
    """ This reads or sets the global settings stored in class.settings. """
    if args:
        cls.settings = cls.settings.copy()
        cls.settings[key] = args[0]
    else:
        return cls.settings[key]


@classmethod
def run(cls):
    """Entry point for running job from the command-line.

        This is also the entry point when a mapper or reducer is run
        by Hadoop Streaming.

        Does one of:

        * Run a mapper (:option:`--mapper`). See :py:meth:`run_mapper`
        * Run a combiner (:option:`--combiner`). See :py:meth:`run_combiner`
        * Run a reducer (:option:`--reducer`). See :py:meth:`run_reducer`
        * Run the entire job. See :py:meth:`run_job`
        """
    cls().execute()


def out_of_range(n: int) ->bool:
    """
    Return True if `n` could not be represented as either a 16-bit signed or unsigned
    integer.
    """
    return n < -32768 or n >= 65536


def price_to_earnings(price, eps):
    """Computes price to earnings ratio.

    @params
    -------
    price: price per share
    eps: earnings per share, calculated by "net income / # of shares"

    returns
    -------
    Returns price to earnings ratio, int or float
    """
    pe = price / eps
    return pe


def quote_ident(text):
    """Replace every instance of ' with  *and* place ' on each end"""
    return '"' + text.replace('"', '""') + '"'


def nasnet_dual_path_scheme_ordinal(module, x, _):
    """
    NASNet specific scheme of dual path response for an ordinal module with dual inputs/outputs in a DualPathSequential
    module.

    Parameters:
    ----------
    module : nn.Module
        A module.
    x : Tensor
        Current processed tensor.

    Returns
    -------
    x_next : Tensor
        Next processed tensor.
    x : Tensor
        Current processed tensor.
    """
    return module(x), x


def guess_input_handler(seqs, add_seq_names=False):
    """Returns the name of the input handler for seqs."""
    if isinstance(seqs, str):
        if '\n' in seqs:
            return '_input_as_multiline_string'
        else:
            return '_input_as_string'
    if isinstance(seqs, list) and len(seqs) and isinstance(seqs[0], tuple):
        return '_input_as_seq_id_seq_pairs'
    if add_seq_names:
        return '_input_as_seqs'
    return '_input_as_lines'


@classmethod
def getAnyAppWithWindow(cls):
    """Get a random app that has windows.

        Raise a ValueError exception if no GUI applications are found.
        """
    return cls.with_window()


def is_namedtuple(obj):
    """Check if `obj` is a namedtuple."""
    return isinstance(obj, tuple) and hasattr(obj, '_fields')


@classmethod
def from_settings(cls, settings, prefix='mail.'):
    """Create a new instance of 'DebugMailer' from settings dict.

        :param settings: a settings dict-like
        :param prefix: prefix separating 'pyramid_mailer' settings
        """
    settings = settings or {}
    top_level_directory = settings.get(prefix + 'top_level_directory')
    if top_level_directory is None:
        raise ValueError(
            "DebugMailer:  must specify '%stop_level_directory'" % prefix)
    return cls(top_level_directory)


def Sub2(a, b):
    """Return difference of 2d vectors, a-b."""
    return a[0] - b[0], a[1] - b[1]


def __nonzero__():
    """Return Boolean cast of the value as True or False."""


def delay_map(wait):
    """
        invoke call on each incoming thing after delay `wait`

        @param wait: time in seconds
        """


def dot(u, v, w, a, b):
    """
    Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and
    `v = (v_{1}, v_{2})` which is defined in order to reduce solution of
    the congruence equation `X^2 - aZ^2 \\equiv 0 \\ (mod \\ b)`.

    """
    u_1, u_2 = u
    v_1, v_2 = v
    return (w * u_1 + b * u_2) * (w * v_1 + b * v_2) + abs(a) * u_1 * v_1


@classmethod
def find_matching(cls, path, patterns):
    """Yield all matching patterns for path."""
    for pattern in patterns:
        if pattern.match(path):
            yield pattern


def hashable(val):
    """Test if `val` is hashable and if not, get it's string representation

    Parameters
    ----------
    val: object
        Any (possibly not hashable) python object

    Returns
    -------
    val or string
        The given `val` if it is hashable or it's string representation"""
    if val is None:
        return val
    try:
        hash(val)
    except TypeError:
        return repr(val)
    else:
        return val


def slicify(slc, dim):
    """
    Force a slice to have defined start, stop, and step from a known dim.
    Start and stop will always be positive. Step may be negative.

    There is an exception where a negative step overflows the stop needs to have
    the default value set to -1. This is the only case of a negative start/stop
    value.

    Parameters
    ----------
    slc : slice or int
        The slice to modify, or int to convert to a slice

    dim : tuple
        Bound for slice
    """
    if isinstance(slc, slice):
        start = 0 if slc.start is None else slc.start
        stop = dim if slc.stop is None else slc.stop
        step = 1 if slc.step is None else slc.step
        if start < 0:
            start += dim
        if stop < 0:
            stop += dim
        if step > 0:
            if start < 0:
                start = 0
            if stop > dim:
                stop = dim
        else:
            if stop < 0:
                stop = -1
            if start > dim:
                start = dim - 1
        return slice(start, stop, step)
    elif isinstance(slc, int):
        if slc < 0:
            slc += dim
        return slice(slc, slc + 1, 1)
    else:
        raise ValueError('Type for slice %s not recongized' % type(slc))


def count(seq):
    """ Count the number of items in seq

    Like the builtin ``len`` but works on lazy sequencies.

    Not to be confused with ``itertools.count``

    See also:
        len
    """
    if hasattr(seq, '__len__'):
        return len(seq)
    return sum(1 for i in seq)


@classmethod
def parse(cls, type_name, line, field_order=None):
    """ Parse an ASS line from text format. Has an optional field order
        parameter in case you have some wonky format.
        """
    if field_order is None:
        field_order = cls.DEFAULT_FIELD_ORDER
    parts = line.split(',', len(field_order) - 1)
    if len(parts) != len(field_order):
        raise ValueError('arity of line does not match arity of field order')
    fields = {}
    for field_name, field in zip(field_order, parts):
        if field_name in cls._field_mappings:
            field = cls._field_mappings[field_name].parse(field)
        fields[field_name] = field
    return cls(**fields, type_name=type_name)


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

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

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


def module_names(path: str, recursive: bool=False) ->list:
    """Return a list of modules which can be imported from path.

    :param path: a directory to scan.
    :type path: str
    :param recursive: Also return submodule names for packages.
    :type recursive: bool
    :return:  a list of string pairs (module_name, module_file).
    """
    pass


@classmethod
def search(cls, body, resolve_hits=True):
    """Retrieve objects from elasticsearch via a search query

        Returns the ES search result. If resolve_hits is set to true the hits
        are converted to Documents.
        """
    docs = cls._get_es().search(index=cls.INDEX, doc_type=cls.DOC_TYPE,
        body=body)
    if resolve_hits:
        data = []
        for d in docs['hits']['hits']:
            data.append(cls.from_raw_es_data(d))
        docs['hits']['hits'] = data
    return docs


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

        :param BinderReorderPageType val:
        :rtype: EventType
        """
    return cls('binder_reorder_page', val)


def get_service_type(f):
    """Retrieves service type from function."""
    return getattr(f, 'service_type', None)


@staticmethod
def detect(fd_obj, image):
    """
        Returns ROI (size-4 tuple of (x, y, w, h)) of the face detected, or None
        if no face detected.

        This method may be overridden by a derived class to use your own custom
        face detector as the main routine. Simply make sure this method returns
        a face ROI is a face is detected, or None if no face is detected.
        """
    return None


def close():
    """
        Close the wormhole.

        This frees all resources associated with the wormhole (including
        server-side queues and any established network connections).

        For operational purposes, it informs the server that the wormhole
        closed "happy".  Less-happy moods may be reported if the connection
        closed due to a ``WrongPasswordError`` or because of a timeout.

        ``close()`` returns a Deferred, which fires after the server has been
        informed and the sockets have been shut down.  One-shot applications
        should delay shutdown until this Deferred has fired, to increase the
        chances that server resources will be freed.  Long-running
        applications can probably ignore the Deferred, as they'll probably
        remain running long enough to allow the shutdown to complete.

        The Deferred will errback if the wormhole had problems, like a
        ``WrongPasswordError``.

        :return: a Deferred that fires when shutdown is complete
        :rtype: ``Deferred``
        """


@classmethod
def _reals_index(cls, reals, index):
    """Map initial real root index to an index in a factor where the root belongs."""
    i = 0
    for j, (_, factor, k) in enumerate(reals):
        if index < i + k:
            poly, index = factor, 0
            for _, factor, _ in reals[:j]:
                if factor == poly:
                    index += 1
            return poly, index
        else:
            i += k


def vert_connect_path():
    """Connect vertices by their selection order, creating edges, splitting faces

    """
    pass


def addBatchSystemConfigOptions(config, batchSystem, options):
    """Adds configurations options to the config derived from the decision about the batch system.
    """
    config.attrib['rescue_jobs_frequency'] = str(float(batchSystem.
        getRescueJobFrequency()))
    if options.rescueJobsFrequency != None:
        config.attrib['rescue_jobs_frequency'] = str(float(options.
            rescueJobsFrequency))


def is_typical(msds, frame, lower=0.1, upper=0.9):
    """Identify which paritcles' MSDs are in the central quantile.

    Parameters
    ----------
    msds : DataFrame
        This should be organized like the output of imsd().
        Columns correspond to particles, indexed by lagtime in frames.
    frame : integer
        Compare MSDs at this lag interval.
    lower : float between 0 and 1, default 0.1
        Probes with MSD up to this quantile are deemed outliers.
    upper : float between 0 and 1, default 0.9
        Probes with MSD above this quantile are deemed outliers.

    Returns
    -------
    Series of boolean values, indexed by particle number
    True = typical particle, False = outlier particle

    Examples
    --------

    >>> m = tp.imsd(traj, MPP, FPS)
    >>> # Index by particle ID, slice using boolean output from is_typical(), and then
    >>> # restore the original index, frame number.
    >>> typical_traj = traj.set_index('particle').ix[is_typical(m)]    .reset_index().set_index('frame', drop=False)
    """
    a, b = msds.iloc[frame].quantile(lower), msds.iloc[frame].quantile(upper)
    return (msds.iloc[frame] > a) & (msds.iloc[frame] < b)


def read_file(filename):
    """Read full contents of given file."""
    try:
        with open(filename) as f:
            return f.read()
    except FileNotFoundError:
        return ''


def format_CALL_FUNCTION_pos_name_encoded(argc):
    """Encoded positional and named args. Used to
    up to about 3.6 where wordcodes are used and
    a different encoding occurs. Pypy36 though
    sticks to this encoded version though."""
    pos_args = argc & 255
    name = argc >> 8 & 255
    return '%d positional, %d named' % (pos_args, name)


def main(in_filename, out_filename):
    """
    Run the filter module via console.

    Parameters
    ----------
    in_filename: str
            Name of the file containing the numpy array point data to be
            filtered.
    out_filename: str
            Name of the file to save the numpy array of filtered point data.

    """
    import numpy as np
    if type(in_filename) is not str:
        print('Wrong argument for input file name')
        return
    if type(out_filename) is not str:
        print('Wrong argument for output file name')
        return
    in_data = np.load(in_filename)
    out_data = filter.apply_filter(in_data[:, (0)], in_data[:, (1)])
    np.save(out_filename, out_data)


def _column_number_to_letters(number):
    """
    Converts given column number into a column letters.

    Right shifts the column index by 26 to find column letters in reverse
    order. These numbers are 1-based, and can be converted to ASCII
    ordinals by adding 64.

    Parameters
    ----------
    number : int
        Column number to convert to column letters.

    Returns
    -------
    unicode
        Column letters.

    References
    ----------
    :cite:`OpenpyxlDevelopers2019`

    Examples
    --------
    # Doctests skip for Python 2.x compatibility.
    >>> _column_number_to_letters(128)  # doctest: +SKIP
    'DX'
    """
    assert 1 <= number <= 18278, 'Column number {0} must be in range [1, 18278]!'.format(
        number)
    letters = []
    while number > 0:
        number, remainder = divmod(number, 26)
        if remainder == 0:
            remainder = 26
            number -= 1
        letters.append(chr(remainder + 64))
    return ''.join(reversed(letters))


@classmethod
def insert(cls, c, **kwargs):
    """Inserts an element to the table."""
    verified = {}
    for column in cls.columns:
        try:
            value = kwargs[column.name]
        except KeyError:
            continue
        check = column.column_type.python
        if value is None and not column.nullable:
            raise TypeError(
                f'Cannot pass None to non-nullable column {column.name}.')
        elif (not check or not isinstance(value, check)) and value is not None:
            fmt = (
                'column {0.name} expected {1.__name__}, received {2.__class__.__name__}'
                )
            raise TypeError(fmt.format(column, check, value))
        verified[column.name] = value
    sql = 'INSERT INTO {0} ({1}) VALUES ({2});'.format(cls.__tablename__,
        ', '.join(verified), ', '.join('?' for _ in verified))
    c.execute(sql, tuple(verified.values()))


def quality_score(row):
    """
    https://doi.org/10.1038/s41586-019-0965-1
    """
    return row['Completeness'] - 5 * row['Contamination']


def has_encoding(string_buffer, encoding):
    """
    Determines if the provided buffer is encoded in the provided encoding.

    :type string_buffer: String
    :param string_buffer: The string buffer.
    :type encoding: String
    :param encoding: The encoding against which to test the string buffer.
    """
    has_encoding = None
    try:
        string_buffer.decode(encoding)
        has_encoding = True
    except:
        has_encoding = False
    return has_encoding


def _reverse_lookup(idx: int, types: [str]) ->str:
    """
    Converts an integer value back to the string representation
    :param idx: integer value
    :param types: list of types
    :return: the string value or None if not found (idx == 0)
    """
    if idx == 0:
        return ''
    else:
        return types[idx - 1]


def _add_pattern_labels(ax, analysis, xtick_types, xfontsize):
    """Add pattern labels to the left of xticklabels. Use to distinguish different patterns."""
    xticktext = list(next(zip(*analysis.format_column_headers(xtick_types,
        firstcolumn=True))))
    xticktext = '\n'.join([''] + xticktext)
    fig = ax.figure
    fig.draw(fig.canvas.get_renderer())
    xticklabels = ax.get_xticklabels()[0]
    _, y = xticklabels.get_transform().transform(xticklabels.get_position())
    x, _ = ax.transAxes.transform((0, 0))
    x, y = fig.transFigure.inverted().transform([x, y])
    fig.text(x, y, xticktext, ha='right', va='top', fontsize=xfontsize)


@classmethod
def migrate(cls, resource, datacenter_id, background=False):
    """ Migrate a disk to another datacenter. """
    disk_id = cls.usable_id(resource)
    result = cls.call('hosting.disk.migrate', disk_id, datacenter_id)
    if background:
        return result
    cls.echo('Disk migration in progress.')
    cls.display_progress(result)
    return result


def dict_to_sequence(d):
    """Returns an internal sequence dictionary update."""
    if hasattr(d, 'items'):
        d = d.items()
    return d


def ltrim1(l, proportiontocut, tail='right'):
    """
Slices off the passed proportion of items from ONE end of the passed
list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost'
10% of scores).  Slices off LESS if proportion results in a non-integer
slice index (i.e., conservatively slices off proportiontocut).

Usage:   ltrim1 (l,proportiontocut,tail='right')  or set tail='left'
Returns: trimmed version of list l
"""
    if tail == 'right':
        lowercut = 0
        uppercut = len(l) - int(proportiontocut * len(l))
    elif tail == 'left':
        lowercut = int(proportiontocut * len(l))
        uppercut = len(l)
    return l[lowercut:uppercut]


@classmethod
def from_dict(cls, d):
    """
        Instances the class from a dictionary representation.

        :param d: Dictionary containing a serialised object.
        :return: An object instance.
        """
    return cls(d['description'])


def linear_1d(module, grad_input, grad_output):
    """No change made to gradients."""
    return None


@staticmethod
def _getAncestor(adaptor, tokenNames, t, goal):
    """Helper for static inContext."""
    while t is not None:
        name = tokenNames[adaptor.getType(t)]
        if name == goal:
            return t
        t = adaptor.getParent(t)
    return None


def _remove_key_prefix(json_, sep):
    """
    去除key在第一个sep之前的部分
    """
    key_path = next(iter(json_))
    next_sep_pos = key_path.find(sep) + 1
    ret = {}
    for key, value in json_.items():
        ret[key[next_sep_pos:]] = value
    return ret


def _guess_extension(content_type):
    """
    Python's `mimetypes.guess_extension` is no use because it simply returns
    the first of an unordered set. We use the same set of media types here,
    but take a reasonable preference on what extension to map to.
    """
    return {'application/javascript': '.js', 'application/msword': '.doc',
        'application/octet-stream': '.bin', 'application/oda': '.oda',
        'application/pdf': '.pdf', 'application/pkcs7-mime': '.p7c',
        'application/postscript': '.ps', 'application/vnd.apple.mpegurl':
        '.m3u', 'application/vnd.ms-excel': '.xls',
        'application/vnd.ms-powerpoint': '.ppt', 'application/x-bcpio':
        '.bcpio', 'application/x-cpio': '.cpio', 'application/x-csh':
        '.csh', 'application/x-dvi': '.dvi', 'application/x-gtar': '.gtar',
        'application/x-hdf': '.hdf', 'application/x-latex': '.latex',
        'application/x-mif': '.mif', 'application/x-netcdf': '.nc',
        'application/x-pkcs12': '.p12', 'application/x-pn-realaudio':
        '.ram', 'application/x-python-code': '.pyc', 'application/x-sh':
        '.sh', 'application/x-shar': '.shar',
        'application/x-shockwave-flash': '.swf', 'application/x-sv4cpio':
        '.sv4cpio', 'application/x-sv4crc': '.sv4crc', 'application/x-tar':
        '.tar', 'application/x-tcl': '.tcl', 'application/x-tex': '.tex',
        'application/x-texinfo': '.texinfo', 'application/x-troff': '.tr',
        'application/x-troff-man': '.man', 'application/x-troff-me': '.me',
        'application/x-troff-ms': '.ms', 'application/x-ustar': '.ustar',
        'application/x-wais-source': '.src', 'application/xml': '.xml',
        'application/zip': '.zip', 'audio/basic': '.au', 'audio/mpeg':
        '.mp3', 'audio/x-aiff': '.aif', 'audio/x-pn-realaudio': '.ra',
        'audio/x-wav': '.wav', 'image/gif': '.gif', 'image/ief': '.ief',
        'image/jpeg': '.jpe', 'image/png': '.png', 'image/svg+xml': '.svg',
        'image/tiff': '.tiff', 'image/vnd.microsoft.icon': '.ico',
        'image/x-cmu-raster': '.ras', 'image/x-ms-bmp': '.bmp',
        'image/x-portable-anymap': '.pnm', 'image/x-portable-bitmap':
        '.pbm', 'image/x-portable-graymap': '.pgm',
        'image/x-portable-pixmap': '.ppm', 'image/x-rgb': '.rgb',
        'image/x-xbitmap': '.xbm', 'image/x-xpixmap': '.xpm',
        'image/x-xwindowdump': '.xwd', 'message/rfc822': '.eml', 'text/css':
        '.css', 'text/csv': '.csv', 'text/html': '.html', 'text/plain':
        '.txt', 'text/richtext': '.rtx', 'text/tab-separated-values':
        '.tsv', 'text/x-python': '.py', 'text/x-setext': '.etx',
        'text/x-sgml': '.sgml', 'text/x-vcard': '.vcf', 'text/xml': '.xml',
        'video/mp4': '.mp4', 'video/mpeg': '.mpeg', 'video/quicktime':
        '.mov', 'video/webm': '.webm', 'video/x-msvideo': '.avi',
        'video/x-sgi-movie': '.movie'}.get(content_type, '')


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


@classmethod
def op_returns_boolean(cls, op):
    """
        Checks whether a given operator is boolean.
        """
    return cls.is_cmp(op) or cls.is_equal(op) or cls.is_boolean(op)


def get_documentation_part(restApiId=None, documentationPartId=None):
    """
    See also: AWS API Documentation

    :example: response = client.get_documentation_part(
        restApiId='string',
        documentationPartId='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            [Required] The identifier of an API of the to-be-retrieved documentation part.

    :type documentationPartId: string
    :param documentationPartId: [REQUIRED]
            [Required] The identifier of the to-be-retrieved documentation part.

    :rtype: dict
    :return: {
        'id': 'string',
        'location': {
            'type': 'API'|'AUTHORIZER'|'MODEL'|'RESOURCE'|'METHOD'|'PATH_PARAMETER'|'QUERY_PARAMETER'|'REQUEST_HEADER'|'REQUEST_BODY'|'RESPONSE'|'RESPONSE_HEADER'|'RESPONSE_BODY',
            'path': 'string',
            'method': 'string',
            'statusCode': 'string',
            'name': 'string'
        },
        'properties': 'string'
    }

    """
    pass


def _batch_update_simple_np(np_view, i, to_add):
    """Update the shared memory underneath the numpy view.
    to_add is again passed by reference."""
    np_view[i, ...] = to_add


@staticmethod
def get_rule_id_by_name(root, rule_name):
    """Get the rule ID based on name."""
    rules = root.findall('rule')
    for rule in rules:
        if rule.find('name').text == rule_name:
            return rule.attrib['id']


def _clean_sxm_header(header_dict):
    """
    Cleanup header dicitonary key-value pairs.

    Parameters
    ----------
    header_dict : dict
        Should be dict returned from _parse_sxm_header method.

    Returns
    -------
    clean_header_dict : dict
        Cleaned header dictionary.
    """
    pass


def subdict(super_dict, keys):
    """
    Returns a subset of the super_dict with the specified keys.
    """
    sub_dict = {}
    valid_keys = super_dict.keys()
    for key in keys:
        if key in valid_keys:
            sub_dict[key] = super_dict[key]
    return sub_dict


def get_alpha_from_conf_percentage(conf_percentage):
    """
    Calculates `100 - conf_percentage`, which is useful for calculating alpha
    levels.
    """
    return 100.0 - conf_percentage


@classmethod
def export_journal(cls, journal):
    """Returns a Markdown representation of an entire journal."""
    out = []
    year, month = -1, -1
    for e in journal.entries:
        if not e.date.year == year:
            year = e.date.year
            out.append('# ' + str(year))
            out.append('')
        if not e.date.month == month:
            month = e.date.month
            out.append('## ' + e.date.strftime('%B'))
            out.append('')
        out.append(cls.export_entry(e, False))
    result = '\n'.join(out)
    return result


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 heading_mark(title, char):
    """
    Given an input title and character, creates the reStructuredText underline
    according to the length of the title.

    **Parameters**
        **title** (str)
            The title that is being underlined, length assumed to be >= 1.

        **char** (str)
            The single character being used for this heading, e.g.
            :data:`~exhale.configs.SECTION_HEADING_CHAR`.

    **Return**
        **str**
            Returns ``len(title) * char``.
    """
    return len(title) * char


def get_linearity_coeff(u, v):
    """
    Given the two 2-dimensional vectors ``u`` and ``v``, return ``a`` so that
    ``v = a*u``

    If the vectors are not colinear, a ``ValueError`` is raised.

    EXAMPLES::

        sage: from flatsurf.geometry.straight_line_trajectory import get_linearity_coeff

        sage: V = VectorSpace(QQ,2)
        sage: get_linearity_coeff(V((1,0)), V((2,0)))
        2
        sage: get_linearity_coeff(V((2,0)), V((1,0)))
        1/2
        sage: get_linearity_coeff(V((0,1)), V((0,2)))
        2
        sage: get_linearity_coeff(V((0,2)), V((0,1)))
        1/2
        sage: get_linearity_coeff(V((1,2)), V((-2,-4)))
        -2

        sage: get_linearity_coeff(V((1,1)), V((-1,1)))
        Traceback (most recent call last):
        ...
        ValueError: non colinear
    """
    if u[0]:
        a = v[0] / u[0]
        if v[1] != a * u[1]:
            raise ValueError('non colinear')
        return a
    elif v[0]:
        raise ValueError('non colinear')
    elif u[1]:
        return v[1] / u[1]
    else:
        raise ValueError('zero vector')


def shape_key_retime():
    """Resets the timing for absolute shape keys

    """
    pass


def InternalCycles(model, allowedreacs=None, reacsbounds={}, tol=1e-10):
    """ pre: reacsbounds={reac:(lo,hi)}, all external reactions blocked
       post: model with reactions in internal cycles (for doing elementary modes) """
    state = model.GetState()
    model.SetConstraints(reacsbounds)
    if allowedreacs == None:
        rd = model.AllFluxRange()
        allowedreacs = rd.Allowed(tol=tol).keys()
    model.SetState(state)
    if len(allowedreacs) > 0:
        armodel = model.SubModel(allowedreacs)
        return armodel


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

        :param SharingFileAccessError val:
        :rtype: AddFileMemberError
        """
    return cls('access_error', val)


def update_stage(restApiId=None, stageName=None, patchOperations=None):
    """
    Changes information about a  Stage resource.
    See also: AWS API Documentation

    :example: response = client.update_stage(
        restApiId='string',
        stageName='string',
        patchOperations=[
            {
                'op': 'add'|'remove'|'replace'|'move'|'copy'|'test',
                'path': 'string',
                'value': 'string',
                'from': 'string'
            },
        ]
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            The identifier of the RestApi resource for the Stage resource to change information about.

    :type stageName: string
    :param stageName: [REQUIRED]
            The name of the Stage resource to change information about.

    :type patchOperations: list
    :param patchOperations: A list of update operations to be applied to the specified resource and in the order specified in this list.
            (dict) -- A single patch operation to apply to the specified resource. Please refer to http://tools.ietf.org/html/rfc6902#section-4 for an explanation of how each operation is used.
            op (string) --An update operation to be performed with this PATCH request. The valid value can be 'add', 'remove', or 'replace'. Not all valid operations are supported for a given resource. Support of the operations depends on specific operational contexts. Attempts to apply an unsupported operation on a resource will return an error message.
            path (string) --The op operation's target, as identified by a JSON Pointer value that references a location within the targeted resource. For example, if the target resource has an updateable property of {'name':'value'} , the path for this property is /name . If the name property value is a JSON object (e.g., {'name': {'child/name': 'child-value'}} ), the path for the child/name property will be /name/child~1name . Any slash ('/') character appearing in path names must be escaped with '~1', as shown in the example above. Each op operation can have only one path associated with it.
            value (string) --The new target value of the update operation. When using AWS CLI to update a property of a JSON value, enclose the JSON object with a pair of single quotes in a Linux shell, e.g., '{'a': ...}'. In a Windows shell, see Using JSON for Parameters .
            from (string) --Not supported.

    :rtype: dict
    :return: {
        'deploymentId': 'string',
        'clientCertificateId': 'string',
        'stageName': 'string',
        'description': 'string',
        'cacheClusterEnabled': True|False,
        'cacheClusterSize': '0.5'|'1.6'|'6.1'|'13.5'|'28.4'|'58.2'|'118'|'237',
        'cacheClusterStatus': 'CREATE_IN_PROGRESS'|'AVAILABLE'|'DELETE_IN_PROGRESS'|'NOT_AVAILABLE'|'FLUSH_IN_PROGRESS',
        'methodSettings': {
            'string': {
                'metricsEnabled': True|False,
                'loggingLevel': 'string',
                'dataTraceEnabled': True|False,
                'throttlingBurstLimit': 123,
                'throttlingRateLimit': 123.0,
                'cachingEnabled': True|False,
                'cacheTtlInSeconds': 123,
                'cacheDataEncrypted': True|False,
                'requireAuthorizationForCacheControl': True|False,
                'unauthorizedCacheControlHeaderStrategy': 'FAIL_WITH_403'|'SUCCEED_WITH_RESPONSE_HEADER'|'SUCCEED_WITHOUT_RESPONSE_HEADER'
            }
        },
        'variables': {
            'string': 'string'
        },
        'documentationVersion': 'string',
        'createdDate': datetime(2015, 1, 1),
        'lastUpdatedDate': datetime(2015, 1, 1)
    }

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

    """
    pass


@staticmethod
def _all_packages(pkg_name):
    """
        >>> list(install_lib._all_packages('foo.bar.baz'))
        ['foo.bar.baz', 'foo.bar', 'foo']
        """
    while pkg_name:
        yield pkg_name
        pkg_name, sep, child = pkg_name.rpartition('.')


def make_document_id(rule_id, substrate_id):
    """
    Generate a document ID
    """
    return rule_id + '_' + substrate_id


def api_version_check(api_version, required_version):
    """Raises a NotImplementedError if the api_version of the connection isn't sufficient
    """
    if api_version < required_version:
        raise NotImplementedError('Call requires API version {0} or higher'
            .format(required_version))


def get_metrics(response):
    """
    Extract asked metrics from api response
    @list_metrics : list of dict
    """
    list_metrics = []
    for i in response['reports'][0]['columnHeader']['metricHeader'][
        'metricHeaderEntries']:
        list_metrics.append(i['name'])
    return list_metrics


def _compute_hedges_correction_factor(n1, n2):
    """
    Computes the bias correction factor for Hedges' g.

    See https://en.wikipedia.org/wiki/Effect_size#Hedges'_g

    Returns
    -------
        j: float

    References
    ----------
    Larry V. Hedges & Ingram Olkin (1985).
    Statistical Methods for Meta-Analysis. Orlando: Academic Press.
    ISBN 0-12-336380-2.
    """
    from scipy.special import gamma
    from numpy import sqrt, isinf
    import warnings
    df = n1 + n2 - 2
    numer = gamma(df / 2)
    denom0 = gamma((df - 1) / 2)
    denom = sqrt(df / 2) * denom0
    if isinf(numer) or isinf(denom):
        df_sum = n1 + n2
        denom = 4 * df_sum - 9
        out = 1 - 3 / denom
    else:
        out = numer / denom
    return out


def bit_vec_val(v, size):
    """
    Declares a bit vector value
    :param v: int, value of the bit vector
    :param size: size of the bit vector
    """
    return '(_ bv{} {})'.format(v, size)


@classmethod
def default(cls, **kwargs):
    """Add key=value pairs only if key is missing."""
    return cls(lambda data: {**kwargs, **data})


@staticmethod
def _classification_function_five(salary, commission, age, elevel, car,
    zipcode, hvalue, hyears, loan):
    """ classification_function_five

        Parameters
        ----------
        salary: float
            Numeric feature: Salary.

        commission: float
            Numeric feature: Commission.

        age: int
            Numeric feature: Age.

        elevel: int
            Categorical feature: Education level.

        car: int
            Categorical feature: Car maker.

        zipcode; int
            Categorical feature: Zipcode.

        hvalue: flaot
            Numeric feature: Value of the house.

        hyears: float
            Numeric feature: Years house owned.

        loan: float
            Numeric feature: Total amount of loan.

        Returns
        -------
        int
            Returns the sample class label, either 0 or 1.

        """
    totalsalary = salary + commission
    if age < 40:
        return 0 if 50000 <= totalsalary and totalsalary <= 100000 else 1
    elif age < 60:
        return 0 if 75000 <= totalsalary and totalsalary <= 125000 else 1
    else:
        return 0 if 25000 <= totalsalary and totalsalary <= 75000 else 1


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

        :param PaperContentPermanentlyDeleteType val:
        :rtype: EventType
        """
    return cls('paper_content_permanently_delete', val)


@staticmethod
def float_f(f):
    """Formats a float for printing to std out."""
    return '{:.2f}'.format(f)


def double_replace(string):
    """Replaces -1 by -, and 1 by +. Accepts string as input.

    >>> double_replace('-1 1 -1 1')
    '- + - +'
    """
    return string.replace('-1', '-').replace('1', '+')


def create_zip(archive, compression, cmd, verbosity, interactive, filenames):
    """Create a ZIP archive."""
    cmdlist = [cmd, '-r', '-9']
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.append(archive)
    cmdlist.extend(filenames)
    return cmdlist


@classmethod
def clearGeolocationOverride(cls):
    """Clears the overriden Geolocation Position and Error.
        """
    return cls.build_send_payload('clearGeolocationOverride', {}), None


@staticmethod
def not_in(a, b):
    """ Naively implement non-membership test. """
    return a not in b


@classmethod
def _get_ax_layer(cls, ax, primary=True):
    """get left (primary) or right (secondary) axes"""
    if primary:
        return getattr(ax, 'left_ax', ax)
    else:
        return getattr(ax, 'right_ax', ax)


def match_any(text, regexes):
    """
    Returns whether the given text matches any of the given regular expressions.

    :param unicode text: The text to check for match.
    :param list(unicode) regexes: List of regular expressions.
    :return boolean:
        Return True if the given text matches any of the given regular expressions.
    """
    import re
    for i_regex in regexes:
        if re.match(i_regex, text) != None:
            return True
    return False


def __nonzero__():
    """return True if the queue contains more than zero items, else False.
        """


@classmethod
def add_parser_arguments(cls, parser, interpreter, meta, app_data):
    """Add CLI arguments for the creator.

        :param parser: the CLI parser
        :param interpreter: the interpreter we're asked to create virtual environment for
        :param meta: value as returned by :meth:`can_create`
        """
    parser.add_argument('dest', help='directory to create virtualenv at',
        type=cls.validate_dest)
    parser.add_argument('--clear', dest='clear', action='store_true', help=
        'remove the destination directory if exist before starting (will overwrite files otherwise)'
        , default=False)


@classmethod
def inherit(cls, name, *parents):
    """
        Inherit this model (use the Swagger composition pattern aka. allOf)
        :param str name: The new model name
        :param dict fields: The new model extra fields
        """
    model = cls(name, parents[-1])
    model.__parents__ = parents[:-1]
    return model


def _prepare_filter_fixed_ips(client_manager, parsed_args):
    """Fix and properly format fixed_ip option for filtering.

    Appropriately convert any subnet names to their respective ids.
    Convert fixed_ips in parsed args to be in valid list format for filter:
    ['subnet_id=foo'].
    """
    client = client_manager.network
    ips = []
    for ip_spec in parsed_args.fixed_ip:
        if 'subnet' in ip_spec:
            subnet_name_id = ip_spec['subnet']
            if subnet_name_id:
                _subnet = client.find_subnet(subnet_name_id, ignore_missing
                    =False)
                ips.append('subnet_id=%s' % _subnet.id)
        if 'ip-address' in ip_spec:
            ips.append('ip_address=%s' % ip_spec['ip-address'])
        if 'ip-substring' in ip_spec:
            ips.append('ip_address_substr=%s' % ip_spec['ip-substring'])
    return ips


def pick(seq, func, maxobj=None):
    """Picks the object obj where func(obj) has the highest value."""
    maxscore = None
    for obj in seq:
        score = func(obj)
        if maxscore is None or maxscore < score:
            maxscore, maxobj = score, obj
    return maxobj


def createInputState(qc, reg, n, pie):
    """
    Computes the quantum Fourier transform of reg, one qubit at
    a time.
    Apply one Hadamard gate to the nth qubit of the quantum register reg, and
    then apply repeated phase rotations with parameters being pi divided by
    increasing powers of two.
    """
    qc.h(reg[n])
    for i in range(0, n):
        qc.cu1(pie / float(2 ** (i + 1)), reg[n - (i + 1)], reg[n])


def check_type(value):
    """
    Checks the type of character of the input.

    :param value:   character to check

    :returns:    0 if letter, 2 if space, or 1 if number
    """
    if value.isalpha():
        return 0
    elif value.isspace():
        return 2
    else:
        return 1


@classmethod
def kill_process(cls, package_name):
    """
        Stops given app::

            ADB.kill_process('com.android.chrome')

        :param str package_name: Package name to stop
        :return:
        """
    cls.exec_cmd('shell am force-stop {0}'.format(package_name)).wait()


def keyconfig_activate(filepath: str=''):
    """Undocumented contribute <https://developer.blender.org/T51061>

    :param filepath: filepath
    :type filepath: str
    """
    pass


@staticmethod
def _get_crossreference(dct, rel, dst):
    """Get pathway crossReference."""
    assert dst['databaseName'] in set(['BioModels Database', 'OMIM']), dst
    assert dst['schemaClass'] == 'DatabaseIdentifier'
    assert rel['stoichiometry'] == 1
    if 'crossreference' not in dct:
        dct['crossreference'] = [dst['displayName']]
    else:
        dct['crossreference'].append(dst['displayName'])


@classmethod
def restore(cls, data):
    """
        cannot restore here because we don't know what type of enum it is
        """
    raise NotImplementedError


@classmethod
def update(cls, spec, document, **kwargs):
    """Modify existing documents matching `spec` using the operations from
        `update`.

        Like :py:meth:`Collection.update <pymongo.collection.Collection.update>`
        """
    return cls._dbcollection.update(spec, document, **kwargs)


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

    """
    pass


@classmethod
def read(cls, iprot):
    """
        Read a new object from the given input protocol and return the object.

        :type iprot: thryft.protocol._input_protocol._InputProtocol
        :rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration
        """
    init_kwds = {}
    iprot.read_struct_begin()
    while True:
        ifield_name, ifield_type, _ifield_id = iprot.read_field_begin()
        if ifield_type == 0:
            break
        elif ifield_name == 'images_per_object':
            init_kwds['images_per_object'] = iprot.read_i32()
        elif ifield_name == 'objects':
            init_kwds['objects'] = iprot.read_i32()
        iprot.read_field_end()
    iprot.read_struct_end()
    return cls(**init_kwds)


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 deserialize_hex(cls, raw: str) ->'EthTx':
    """Serialize a transaction from hex."""
    r = raw
    if r[:2] == '0x':
        r = r[2:]
    return cls.deserialize(bytes.fromhex(r))


def both_none_or_same_str(var1, var2):
    """Determine wheter both vars are the same. Either None or float"""
    if var1 is None:
        return var2 is None
    else:
        return var2 is not None and var1 == var2


def apply_correspondence(correspondence_src, correspondence_dst, vertices):
    """
    Apply a correspondence defined between two vertex sets to a new set.

    Identifies a correspondence between `correspondence_src` and
    `correspondence_dst` then applies that correspondence to `vertices`.
    That is, `correspondence_src` is to `correspondence_dst` as `vertices` is
    to [ return value ].

    `correspondence_src` and `vertices` must have the same topology. The return
    value will have the same topology as `correspondence_dst`. Arguments can
    be passed as `chumpy` or `numpy` arrays.

    The most common usecase here is establishing a relationship between an
    alignment and a pointcloud or set of landmarks. The pointcloud or landmarks
    can then be moved automatically as the alignment is adjusted (e.g. fit to a
    different mesh, reposed, etc).

    Args:
        correspondence_src: The source vertices for the correspondence
        correspondence_dst: The destination vertices for the correspondence
        vertices: The vertices to map using the defined correspondence

    Returns:
        the mapped version of `vertices`

    Example usage
    -------------

    >>> transformed_scan_vertices = apply_correspondence(
    ...     correspondence_src=alignment.v,
    ...     correspondence_dst=scan.v,
    ...     vertices=reposed_alignment.v
    ... )
    >>> transformed_scan = Mesh(v=transformed_scan_vertices, vc=scan.vc)

    """
    import chumpy as ch
    from bodylabs.mesh.landmarking.transformed_lm import TransformedCoeffs
    from bodylabs.mesh.landmarking.transformed_lm import TransformedLms
    ch_desired = any([isinstance(correspondence_src, ch.Ch), isinstance(
        correspondence_dst, ch.Ch), isinstance(vertices, ch.Ch)])
    coeffs = TransformedCoeffs(src_v=correspondence_src, dst_v=
        correspondence_dst)
    transformed_vertices = TransformedLms(transformed_coeffs=coeffs, src_v=
        vertices)
    return transformed_vertices if ch_desired else transformed_vertices.r


def get_data(data, *keys, optional=False):
    """ 从字典数据类型中批量获取变量。get list data from dict.

    Examples::

        offset, limit, from_date, to_date = get_data(request.data, 'offset', 'limit', 'from', 'to', optional=True)

    :type data: dict
    :type keys: str
    :type optional: bool
    """
    if optional:
        return map(lambda key: data.get(key), keys)
    return map(lambda key: data[key], keys)


def isErrorNode(node):
    """
    Return true if the node is a negative reply
    """
    return node and node.getType() == 'error'


def configure(conf):
    """
	Detects the program dbus-binding-tool and sets ``conf.env.DBUS_BINDING_TOOL``
	"""
    conf.find_program('dbus-binding-tool', var='DBUS_BINDING_TOOL')


@staticmethod
def _get_data_key(request, headers=None):
    """
        This method returns which key should be used when sending data through the requests library.
        A JSON request requires the "json" key while other requests require "data".

        :param request: (dict) a dictionary representing a request
        :param headers: (dict) a dictionary representing request headers
        :return: key to use when passing data to the requests library
        """
    if 'data' in request:
        return 'data'
    elif 'json' in request:
        return 'json'
    elif headers:
        return 'json' if headers.get('Content-Type'
            ) == 'application/json' else 'data'
    raise AssertionError(
        'Could not determine data_key for request {} or headers {}'.format(
        request, headers))


def getMessage(cursor, msg_id, trigger):
    """
    Gets the newest message

    :returns: Containing the message itself as string and the conversation ID
    :rtype: dict
    """
    query = (
        'SELECT message_id, content FROM message_entry WHERE (user_id <> 5 AND id = {})'
        .format(msg_id))
    cursor.execute(query)
    result = cursor.fetchone()
    message_id = result[0]
    if result[1][:len(trigger)] == trigger:
        message = result[1][len(trigger):].strip()
    else:
        message = result[1].strip()
    messagedata = {'message': message, 'message_id': message_id}
    return messagedata


def _zbc_to_hgvs(i):
    """Convert zero-based coordinate to hgvs (1 based, missing zero)"""
    if i >= 0:
        i += 1
    return i


def list_zip(archive, compression, cmd, verbosity, interactive):
    """List a ZIP archive."""
    cmdlist = [cmd, '-l']
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.extend(['--', archive])
    return cmdlist


@classmethod
def light_grey(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x979c9f``."""
    return cls(9936031)


def __len__():
    """Return number of terms."""


def touch():
    """Set modification date to now.
        """


def section_header(section_name: str) ->str:
    """
    Constructs a Phase Header given a Phase Name
    :param section_name:
    """
    return '[' + section_name + ']'


def fix_lines(text, ending='\n', replace=True, final=False):
    """fix line ending in text: 'replace' all or not, ensure 'final' line ending"""
    if not text or not ending:
        return text
    if replace:
        if ending == '\n':
            text = text.replace('\r\n', '\n')
        elif ending == '\r\n':
            text = text.replace('\r\n', '\n').replace('\n', '\r\n')
    if not final:
        return text
    return text.rstrip() + ending


def is_int(obj: object) ->bool:
    """
    ``True`` only if the passed object is an integer.
    """
    return isinstance(obj, int)


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_bool()
    return parameters


def qsize_to_tuple(sz):
    """ Convert QSize (or its variants) to (width, height) tuple """
    return sz.width(), sz.height()


def getAltFromCoord(first_coord, second_coord):
    """
    Return VCF alternative field value for the breakend of the 5' and 3' shard of fusion.

    :param first_coord: Coordinates of the breakend for the first 5' shard in fusion.
    :type first_coord: dict
    :param second_coord: Coordinates of the breakend for the first 3' shard in fusion.
    :type second_coord: dict
    :return: Alternative for the first shard in fusion and alternative for the first shard in fusion.
    :rtype: (dict, dict))
    """
    first_alt = None
    second_alt = None
    if first_coord['strand'] == '+':
        if second_coord['strand'] == '-':
            first_alt = 'N]{}:{}]'.format(second_coord['chrom'],
                second_coord['pos'])
            second_alt = 'N]{}:{}]'.format(first_coord['chrom'],
                first_coord['pos'])
        else:
            first_alt = 'N[{}:{}['.format(second_coord['chrom'],
                second_coord['pos'])
            second_alt = ']{}:{}]N'.format(first_coord['chrom'],
                first_coord['pos'])
    elif second_coord['strand'] == '-':
        first_alt = ']{}:{}]N'.format(second_coord['chrom'], second_coord[
            'pos'])
        second_alt = 'N[{}:{}['.format(first_coord['chrom'], first_coord['pos']
            )
    else:
        first_alt = '[{}:{}[N'.format(second_coord['chrom'], second_coord[
            'pos'])
        second_alt = '[{}:{}[N'.format(first_coord['chrom'], first_coord['pos']
            )
    return first_alt, second_alt


def get_word_list_eng(text):
    """A naive function that extracts English words from raw texts.

    :param text: The raw text.
    :return words: A list of strings.
    """
    words, index = [''], 0
    while index < len(text):
        while index < len(text) and ('a' <= text[index] <= 'z' or 'A' <=
            text[index] <= 'Z'):
            words[-1] += text[index]
            index += 1
        if words[-1]:
            words.append('')
        while index < len(text) and not ('a' <= text[index] <= 'z' or 'A' <=
            text[index] <= 'Z'):
            if text[index] != ' ':
                words[-1] += text[index]
            index += 1
        if words[-1]:
            words.append('')
    if not words[-1]:
        words.pop()
    return words


def _remove_t0_from_wide_db(times_needed, _db):
    """
    This function finds the first set of values for each model and scenario and
    subtracts them from all values to remove the offset.
    """
    for model, scenario in set(zip(_db.index.get_level_values('model'), _db
        .index.get_level_values('scenario'))):
        offset = _db.loc[model, scenario, min(times_needed)].copy(
            ).values.squeeze()
        for time in times_needed:
            _db.loc[model, scenario, time] = _db.loc[model, scenario, time
                ] - offset


def require_activation_setting_value(kerno) ->bool:
    """Return the value of a certain setting."""
    return kerno.pluserable_settings.bool('require_activation', default=True)


def group_membership_v1_timeout(group_state: 'GroupState'):
    """
    v1 host timer associated with group GroupState object has expired
    """
    group_state.group_state_logger.debug(
        'Querier NoMembersPresent: group_membership_v1_timeout')
    return


def _raw_compile(f_code):
    """
    Compile some code for injection into the locals().
    We cheat the systems by giving the f_code as the filename.
    This allows programmers to actually see the autogenerated output instead of just "<string>".

    :param f_code: the code to compile for execution
    :type f_code: str
    :return: the compiled code object
    :rtype: code
    """
    return compile(f_code, '<string>' + f_code, 'exec')


def get_motion_default(settings, motion_frames, queue_com, name):
    """
    Set the default values for the motion correction software.

    settings - TranSPHIRE settings.
    motion_frames - Sub frame settings.
    queue_com - Queue for communication.
    name - Name of the process.

    Returns:
    True, if dose weighting will be applied.
    """
    motion_name = settings['Copy']['Motion']
    if (motion_name == 'MotionCor2 v1.0.0' or motion_name ==
        'MotionCor2 v1.0.5' or motion_name == 'MotionCor2 v1.1.0'):
        motion_frames['last'] = int(settings['General']['Number of frames']
            ) - int(settings[motion_name]['-Trunc'])
        motion_frames['first'] = int(settings[motion_name]['-Throw']) + 1
        return bool(settings[motion_name]['-FmDose'] != '0' and settings[
            motion_name]['-PixSize'] != '0' and settings[motion_name]['-kV'
            ] != '0')
    else:
        message = '\n'.join(['{0}: Motion version not known.'.format(
            motion_name), 'Please contact the TranSPHIRE authors!'])
        queue_com['error'].put(message, name)
        raise IOError(message)


def create_project(name=None, id=None, description=None, clientRequestToken
    =None):
    """
    Reserved for future use. To create a project, use the AWS CodeStar console.
    See also: AWS API Documentation

    :example: response = client.create_project(
        name='string',
        id='string',
        description='string',
        clientRequestToken='string'
    )

    :type name: string
    :param name: [REQUIRED]
            Reserved for future use.

    :type id: string
    :param id: [REQUIRED]
            Reserved for future use.

    :type description: string
    :param description: Reserved for future use.

    :type clientRequestToken: string
    :param clientRequestToken: Reserved for future use.

    :rtype: dict
    :return: {
        'id': 'string',
        'arn': 'string',
        'clientRequestToken': 'string',
        'projectTemplateId': 'string'
    }

    """
    pass


def lines_subtext(text, start_line, end_line):
    """Return the text excerpt between the specified lines."""
    return '\n'.join(text.split('\n')[start_line:end_line])


def psi_H_Mg_CO3_HMW84(T, P):
    """c-c'-a: hydrogen magnesium carbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def hide_tracks_clear():
    """Clear hide selected tracks

    """
    pass


@property
def __members__(cls):
    """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a copy of the internal mapping.

        """
    return cls._member_map_.copy()


def parse_keqv_list(ln):
    """Parse list of key=value strings where keys are not duplicated."""
    parsed = {}
    for elt in ln:
        k, v = elt.split('=', 1)
        if v[0:1] == '"' and v[-1:] == '"':
            v = v[1:-1]
        parsed[k] = v
    return parsed


def calcRectCenter(l, t, r, b):
    """ returns rect center point -> x,y
        calcRectCenter(l,t,r,b)
    """
    return l + (r - l) * 0.5, t + (b - t) * 0.5


@classmethod
def from_celcius(cls, val):
    """Convert `val` ºC to K"""
    return (val + 273.15) * cls.kelvin


def reset_bounce_info():
    """Reset the bounce related information. """


def statislink(st):
    """check whether a stat result is a symlink"""
    return False


def particle_edit_toggle():
    """Toggle particle edit mode

    """
    pass


def _testAngledMarginPen():
    """
    >>> glyph = _makeTestGlyph()
    >>> pen = AngledMarginPen(dict(), width=0, italicAngle=10)
    >>> glyph.draw(pen)
    >>> pen.margin
    (117.63269807084649, -1041.061584566772)
    """


@classmethod
def down(cls):
    """Sample down migration code"""
    """
        SpannerDb.execute_ddl_query('''
                DROP TABLE sample
                ''')
        """


def children():
    """
        List the children of this path object.

        @return: a sequence of the children of the directory at this file path.
        @raise Exception: if the file at this file path is not a directory.
        """


def stackedProgressBar(barStyle='plain', infoWidth='10', successWidth='10',
    warningWidth='10', errorWidth='10'):
    """
    *Generate a progress bar - TBS style*

    **Key Arguments:**
        - ``barLevel`` -- the level/color of progress [ "info" | "success" | "warning" | "danger"]
        - ``barStyle`` -- style of the progress bar [ "plain" | "striped" | "striped-active" ]
        - ``infoWidth`` -- the precentage width of the info level bar
        - ``successWidth`` -- the precentage width of the success level bar
        - ``warningWidth`` -- the precentage width of the warning level bar
        - ``errorWidth`` -- the precentage width of the error level bar

    **Return:**
        - ``progressBar`` -- the progressBar
    """
    if barStyle == 'striped':
        barStyle = 'progress-striped'
    elif barStyle == 'striped-active':
        barStyle = 'progress-striped active'
    else:
        barStyle = ''
    stackedProgressBar = (
        """

"""
         % locals())
    return stackedProgressBar


def get_creation_datetime():
    """Return of creation datetime of the object. Return None if
        not supported.
        """


def try_(func, default=None):
    """Try return the result of func, else return default."""
    try:
        return func()
    except Exception:
        return default


def should_build_with_cython(package, release=None):
    """Returns the previously used Cython version (or 'unknown' if not
    previously built) if Cython should be used to build extension modules from
    pyx files.  If the ``release`` parameter is not specified an attempt is
    made to determine the release flag from `astropy.version`.
    """
    try:
        version_module = __import__(package + '.cython_version', fromlist=[
            'release', 'cython_version'])
    except ImportError:
        version_module = None
    if release is None and version_module is not None:
        try:
            release = version_module.release
        except AttributeError:
            pass
    try:
        cython_version = version_module.cython_version
    except AttributeError:
        cython_version = 'unknown'
    have_cython = False
    try:
        import Cython
        have_cython = True
    except ImportError:
        pass
    if have_cython and (not release or cython_version == 'unknown'):
        return cython_version
    else:
        return False


def medial_wall_to_nan(in_file, subjects_dir, target_subject, newpath=None):
    """ Convert values on medial wall to NaNs
    """
    import nibabel as nb
    import numpy as np
    import os
    fn = os.path.basename(in_file)
    if not target_subject.startswith('fs'):
        return in_file
    cortex = nb.freesurfer.read_label(os.path.join(subjects_dir,
        target_subject, 'label', '{}.cortex.label'.format(fn[:2])))
    func = nb.load(in_file)
    medial = np.delete(np.arange(len(func.darrays[0].data)), cortex)
    for darray in func.darrays:
        darray.data[medial] = np.nan
    out_file = os.path.join(newpath or os.getcwd(), fn)
    func.to_filename(out_file)
    return out_file


def minmax(a, b):
    """ `default` argument cannot be used, because the C level function doesn't have a default value
		but an overload.
	"""
    if a <= b:
        return a, b
    else:
        return b, a


def keyitem_remove(item_id: int=0):
    """Remove key map item

    :param item_id: Item Identifier, Identifier of the item to remove
    :type item_id: int
    """
    pass


def _snooze(filecnt):
    """Sleep for a little while.

        :param filecnt: The number of messages in the queue the last time
            through.  Runners can decide to continue to do work, or sleep for
            a while based on this value.  By default, the base runner only
            snoozes when there was nothing to do last time around.
        :type filecnt: int
        """


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 to_bytes(value):
    """ str to bytes (py3k) """
    vtype = type(value)
    if vtype == bytes or vtype == type(None):
        return value
    try:
        return vtype.encode(value)
    except UnicodeEncodeError:
        pass
    return value


def KK_RC67_fit(params, w, t_values):
    """
    Kramers-Kronig Function: -RC-

    Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
    """
    Rs = params['Rs']
    R1 = params['R1']
    R2 = params['R2']
    R3 = params['R3']
    R4 = params['R4']
    R5 = params['R5']
    R6 = params['R6']
    R7 = params['R7']
    R8 = params['R8']
    R9 = params['R9']
    R10 = params['R10']
    R11 = params['R11']
    R12 = params['R12']
    R13 = params['R13']
    R14 = params['R14']
    R15 = params['R15']
    R16 = params['R16']
    R17 = params['R17']
    R18 = params['R18']
    R19 = params['R19']
    R20 = params['R20']
    R21 = params['R21']
    R22 = params['R22']
    R23 = params['R23']
    R24 = params['R24']
    R25 = params['R25']
    R26 = params['R26']
    R27 = params['R27']
    R28 = params['R28']
    R29 = params['R29']
    R30 = params['R30']
    R31 = params['R31']
    R32 = params['R32']
    R33 = params['R33']
    R34 = params['R34']
    R35 = params['R35']
    R36 = params['R36']
    R37 = params['R37']
    R38 = params['R38']
    R39 = params['R39']
    R40 = params['R40']
    R41 = params['R41']
    R42 = params['R42']
    R43 = params['R43']
    R44 = params['R44']
    R45 = params['R45']
    R46 = params['R46']
    R47 = params['R47']
    R48 = params['R48']
    R49 = params['R49']
    R50 = params['R50']
    R51 = params['R51']
    R52 = params['R52']
    R53 = params['R53']
    R54 = params['R54']
    R55 = params['R55']
    R56 = params['R56']
    R57 = params['R57']
    R58 = params['R58']
    R59 = params['R59']
    R60 = params['R60']
    R61 = params['R61']
    R62 = params['R62']
    R63 = params['R63']
    R64 = params['R64']
    R65 = params['R65']
    R66 = params['R66']
    R67 = params['R67']
    return Rs + R1 / (1 + w * 1.0j * t_values[0]) + R2 / (1 + w * 1.0j *
        t_values[1]) + R3 / (1 + w * 1.0j * t_values[2]) + R4 / (1 + w *
        1.0j * t_values[3]) + R5 / (1 + w * 1.0j * t_values[4]) + R6 / (1 +
        w * 1.0j * t_values[5]) + R7 / (1 + w * 1.0j * t_values[6]) + R8 / (
        1 + w * 1.0j * t_values[7]) + R9 / (1 + w * 1.0j * t_values[8]
        ) + R10 / (1 + w * 1.0j * t_values[9]) + R11 / (1 + w * 1.0j *
        t_values[10]) + R12 / (1 + w * 1.0j * t_values[11]) + R13 / (1 + w *
        1.0j * t_values[12]) + R14 / (1 + w * 1.0j * t_values[13]) + R15 / (
        1 + w * 1.0j * t_values[14]) + R16 / (1 + w * 1.0j * t_values[15]
        ) + R17 / (1 + w * 1.0j * t_values[16]) + R18 / (1 + w * 1.0j *
        t_values[17]) + R19 / (1 + w * 1.0j * t_values[18]) + R20 / (1 + w *
        1.0j * t_values[19]) + R21 / (1 + w * 1.0j * t_values[20]) + R22 / (
        1 + w * 1.0j * t_values[21]) + R23 / (1 + w * 1.0j * t_values[22]
        ) + R24 / (1 + w * 1.0j * t_values[23]) + R25 / (1 + w * 1.0j *
        t_values[24]) + R26 / (1 + w * 1.0j * t_values[25]) + R27 / (1 + w *
        1.0j * t_values[26]) + R28 / (1 + w * 1.0j * t_values[27]) + R29 / (
        1 + w * 1.0j * t_values[28]) + R30 / (1 + w * 1.0j * t_values[29]
        ) + R31 / (1 + w * 1.0j * t_values[30]) + R32 / (1 + w * 1.0j *
        t_values[31]) + R33 / (1 + w * 1.0j * t_values[32]) + R34 / (1 + w *
        1.0j * t_values[33]) + R35 / (1 + w * 1.0j * t_values[34]) + R36 / (
        1 + w * 1.0j * t_values[35]) + R37 / (1 + w * 1.0j * t_values[36]
        ) + R38 / (1 + w * 1.0j * t_values[37]) + R39 / (1 + w * 1.0j *
        t_values[38]) + R40 / (1 + w * 1.0j * t_values[39]) + R41 / (1 + w *
        1.0j * t_values[40]) + R42 / (1 + w * 1.0j * t_values[41]) + R43 / (
        1 + w * 1.0j * t_values[42]) + R44 / (1 + w * 1.0j * t_values[43]
        ) + R45 / (1 + w * 1.0j * t_values[44]) + R46 / (1 + w * 1.0j *
        t_values[45]) + R47 / (1 + w * 1.0j * t_values[46]) + R48 / (1 + w *
        1.0j * t_values[47]) + R49 / (1 + w * 1.0j * t_values[48]) + R50 / (
        1 + w * 1.0j * t_values[49]) + R51 / (1 + w * 1.0j * t_values[50]
        ) + R52 / (1 + w * 1.0j * t_values[51]) + R53 / (1 + w * 1.0j *
        t_values[52]) + R54 / (1 + w * 1.0j * t_values[53]) + R55 / (1 + w *
        1.0j * t_values[54]) + R56 / (1 + w * 1.0j * t_values[55]) + R57 / (
        1 + w * 1.0j * t_values[56]) + R58 / (1 + w * 1.0j * t_values[57]
        ) + R59 / (1 + w * 1.0j * t_values[58]) + R60 / (1 + w * 1.0j *
        t_values[59]) + R61 / (1 + w * 1.0j * t_values[60]) + R62 / (1 + w *
        1.0j * t_values[61]) + R63 / (1 + w * 1.0j * t_values[62]) + R64 / (
        1 + w * 1.0j * t_values[63]) + R65 / (1 + w * 1.0j * t_values[64]
        ) + R66 / (1 + w * 1.0j * t_values[65]) + R67 / (1 + w * 1.0j *
        t_values[66])


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


@staticmethod
def to_reaumur(delisle):
    """ Convert delisle to reaumur """
    return 80 - delisle * 8 / 15


def make_skills_section(skls, indent):
    """
    Create the liens of the skill section
    Args:
        skls: the list of skills
        indent: the original indentation

    Returns:
        A list of lines of the skill section
    """
    lines = []
    for skl in skls:
        lines.append(f'{indent}<li>{skl}</li>')
    return lines


@classmethod
def disable(cls):
    """Disables log domain, prevents further log entries from being reported to the client.
        """
    return cls.build_send_payload('disable', {}), None


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

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

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


def hadjust(w, orientation):
    """Ostensibly, a function to reduce the vertical footprint of a widget
    that is normally used in a vertical stack (usually a Splitter), when it
    is instead used in a horizontal orientation.
    """
    if orientation != 'horizontal':
        return w
    return w


def msb(n):
    """! @brief Return the bit number of the highest set bit."""
    ndx = 0
    while 1 < n:
        n = n >> 1
        ndx += 1
    return ndx


@staticmethod
def _collect_parameters(parameter_names, args, kwargs, defaults):
    """Creates a dictionary mapping parameters names to their values in the method call.

        :param parameter_names: The method's parameter names
        :type parameter_names: list[string]
        :param args: *args passed into the method
        :type args: list[object]
        :param kwargs: **kwargs passed into the method
        :type kwargs: dict[string, object]
        :param defaults: The method's default values
        :type defaults: list[object]
        :return: Dictionary mapping parameter names to values
        :rtype: dict[string, object]
        """
    parameters = {}
    if defaults is not None:
        zipped_defaults = zip(reversed(parameter_names), reversed(defaults))
        for name, default in zipped_defaults:
            parameters[name] = default
    for name, value in zip(parameter_names, args):
        parameters[name] = value
    for name, value in kwargs.items():
        parameters[name] = value
    return parameters


def get_last_idx(iterable, func):
    """
    获取最后一个符合条件数据的数组索引
    :param iterable:
    :param func:
    :return:
    """
    count = len(iterable)
    for n in range(count - 1, -1, -1):
        if func(iterable[n]):
            return n
    return None


def add_object_align_init(context, operator):
    """
    Return a matrix using the operator settings and view context.

    :arg context: The context to use.
    :type context: :class:`bpy.types.Context`
    :arg operator: The operator, checked for location and rotation properties.
    :type operator: :class:`bpy.types.Operator`
    :return: the matrix from the context and settings.
    :rtype: :class:`mathutils.Matrix`
    """
    from mathutils import Matrix, Vector, Euler
    properties = operator.properties if operator is not None else None
    space_data = context.space_data
    if space_data and space_data.type != 'VIEW_3D':
        space_data = None
    if operator and properties.is_property_set('location'):
        location = Matrix.Translation(Vector(properties.location))
    else:
        if space_data:
            location = Matrix.Translation(space_data.cursor_location)
        else:
            location = Matrix.Translation(context.scene.cursor_location)
        if operator:
            properties.location = location.to_translation()
    view_align = context.user_preferences.edit.object_align == 'VIEW'
    view_align_force = False
    if operator:
        if properties.is_property_set('view_align'):
            view_align = view_align_force = operator.view_align
        elif properties.is_property_set('rotation'):
            value = properties.rotation[:]
            properties.view_align = view_align
            properties.rotation = value
            del value
        else:
            properties.view_align = view_align
    if operator and (properties.is_property_set('rotation') and not
        view_align_force):
        rotation = Euler(properties.rotation).to_matrix().to_4x4()
    else:
        if view_align and space_data:
            rotation = space_data.region_3d.view_matrix.to_3x3().inverted()
            rotation.resize_4x4()
        else:
            rotation = Matrix()
        if operator:
            properties.rotation = rotation.to_euler()
    return location * rotation


@staticmethod
def is_genome_declaration_string(data_string):
    """ Checks if supplied string after stripping corresponds to ``genome declaration``

        :param data_string: a string to check genome name declaration in
        :type data_string: ``str``
        :return: a flag indicating if supplied string corresponds to genome name declaration
        :rtype: ``Boolean``
        """
    data_string = data_string.strip()
    return data_string.startswith('>') and len(data_string) > 1


@classmethod
def from_cli_single_ifo(cls, opt, ifo):
    """Create an InjFilterRejector instance from command-line options."""
    injection_file = opt.injection_file[ifo]
    chirp_time_window = opt.injection_filter_rejector_chirp_time_window[ifo]
    match_threshold = opt.injection_filter_rejector_match_threshold[ifo]
    coarsematch_deltaf = opt.injection_filter_rejector_coarsematch_deltaf[ifo]
    coarsematch_fmax = opt.injection_filter_rejector_coarsematch_fmax[ifo]
    seg_buffer = opt.injection_filter_rejector_seg_buffer[ifo]
    if opt.injection_filter_rejector_f_lower[ifo] is not None:
        f_lower = opt.injection_filter_rejector_f_lower[ifo]
    else:
        f_lower = opt.low_frequency_cutoff
    return cls(injection_file, chirp_time_window, match_threshold, f_lower,
        coarsematch_deltaf, coarsematch_fmax, seg_buffer=seg_buffer)


def domain_from_email(address):
    """
    Method to extract a domain without sld or tld from an email address

    :param address: email address to extract from
    :type address: str

    :return: domain (str)
    """
    return address.split('@')[1].split('.')[0]


def p_slicing(p):
    """slicing :  primary "[" proper_slice "]"
               |  primary "[" slice_list "]" """
    p[0] = ['SLICE', p[1], p[3]]


def distance_pivot_mfd(moment, force):
    """Usage: Calculate perpendicular distance from the pivot from force and the moment """
    return moment / force


@staticmethod
def func_numpy(*args):
    """
        Numpy implementation of the op logic. Returns a tuple.
        """
    raise NotImplementedError


def select_word():
    """Select word at cursor position

    """
    pass


def display_cellwidth_full():
    """
    Displays Jupyter Notebook cells with with = 100% of screen size
    """
    from IPython.core.display import display, HTML
    display(HTML('<style>.container { width:100% !important; }</style>'))
    return None


@classmethod
def _extract_error_message(cls, response):
    """Extracts an error message from an error response.

        If the server has sent a JSON response with an 'error' field, which is the typical
        behavior of the Realtime Database REST API, parses the response to retrieve the error
        message. If the server has sent a non-JSON response, returns the full response
        as the error message.
        """
    message = None
    try:
        data = response.json()
        if isinstance(data, dict):
            message = data.get('error')
    except ValueError:
        pass
    if not message:
        message = 'Unexpected response from database: {0}'.format(response.
            content.decode())
    return message


def files_in_DS(s, DS):
    """ Returns a list of files used in a given job in a given dataset"""
    if DS in s.infiles:
        return s.infiles[DS]
    else:
        return []


def create_application_version(ApplicationName=None, VersionLabel=None,
    Description=None, SourceBuildInformation=None, SourceBundle=None,
    BuildConfiguration=None, AutoCreateApplication=None, Process=None):
    """
    Creates an application version for the specified application. You can create an application version from a source bundle in Amazon S3, a commit in AWS CodeCommit, or the output of an AWS CodeBuild build as follows:
    Specify a commit in an AWS CodeCommit repository with SourceBuildInformation .
    Specify a build in an AWS CodeBuild with SourceBuildInformation and BuildConfiguration .
    Specify a source bundle in S3 with SourceBundle
    Omit both SourceBuildInformation and SourceBundle to use the default sample application.
    See also: AWS API Documentation

    Examples
    The following operation creates a new version (v1) of an application named my-app:
    Expected Output:

    :example: response = client.create_application_version(
        ApplicationName='string',
        VersionLabel='string',
        Description='string',
        SourceBuildInformation={
            'SourceType': 'Git'|'Zip',
            'SourceRepository': 'CodeCommit'|'S3',
            'SourceLocation': 'string'
        },
        SourceBundle={
            'S3Bucket': 'string',
            'S3Key': 'string'
        },
        BuildConfiguration={
            'ArtifactName': 'string',
            'CodeBuildServiceRole': 'string',
            'ComputeType': 'BUILD_GENERAL1_SMALL'|'BUILD_GENERAL1_MEDIUM'|'BUILD_GENERAL1_LARGE',
            'Image': 'string',
            'TimeoutInMinutes': 123
        },
        AutoCreateApplication=True|False,
        Process=True|False
    )

    :type ApplicationName: string
    :param ApplicationName: [REQUIRED]
            The name of the application. If no application is found with this name, and AutoCreateApplication is false , returns an InvalidParameterValue error.

    :type VersionLabel: string
    :param VersionLabel: [REQUIRED]
            A label identifying this version.
            Constraint: Must be unique per application. If an application version already exists with this label for the specified application, AWS Elastic Beanstalk returns an InvalidParameterValue error.

    :type Description: string
    :param Description: Describes this version.

    :type SourceBuildInformation: dict
    :param SourceBuildInformation: Specify a commit in an AWS CodeCommit Git repository to use as the source code for the application version.
            SourceType (string) -- [REQUIRED]The type of repository.
            Git
            Zip
            SourceRepository (string) -- [REQUIRED]Location where the repository is stored.
            CodeCommit
            S3
            SourceLocation (string) -- [REQUIRED]The location of the source code, as a formatted string, depending on the value of SourceRepository
            For CodeCommit , the format is the repository name and commit ID, separated by a forward slash. For example, my-git-repo/265cfa0cf6af46153527f55d6503ec030551f57a .
            For S3 , the format is the S3 bucket name and object key, separated by a forward slash. For example, my-s3-bucket/Folders/my-source-file .

    :type SourceBundle: dict
    :param SourceBundle: The Amazon S3 bucket and key that identify the location of the source bundle for this version.
            Note
            The Amazon S3 bucket must be in the same region as the environment.
            Specify a source bundle in S3 or a commit in an AWS CodeCommit repository (with SourceBuildInformation ), but not both. If neither SourceBundle nor SourceBuildInformation are provided, Elastic Beanstalk uses a sample application.
            S3Bucket (string) --The Amazon S3 bucket where the data is located.
            S3Key (string) --The Amazon S3 key where the data is located.

    :type BuildConfiguration: dict
    :param BuildConfiguration: Settings for an AWS CodeBuild build.
            ArtifactName (string) --The name of the artifact of the CodeBuild build. If provided, Elastic Beanstalk stores the build artifact in the S3 location S3-bucket /resources/application-name /codebuild/codebuild-version-label -artifact-name .zip. If not provided, Elastic Beanstalk stores the build artifact in the S3 location S3-bucket /resources/application-name /codebuild/codebuild-version-label .zip.
            CodeBuildServiceRole (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that enables AWS CodeBuild to interact with dependent AWS services on behalf of the AWS account.
            ComputeType (string) --Information about the compute resources the build project will use.
            BUILD_GENERAL1_SMALL: Use up to 3 GB memory and 2 vCPUs for builds
            BUILD_GENERAL1_MEDIUM: Use up to 7 GB memory and 4 vCPUs for builds
            BUILD_GENERAL1_LARGE: Use up to 15 GB memory and 8 vCPUs for builds
            Image (string) -- [REQUIRED]The ID of the Docker image to use for this build project.
            TimeoutInMinutes (integer) --How long in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait until timing out any related build that does not get marked as completed. The default is 60 minutes.

    :type AutoCreateApplication: boolean
    :param AutoCreateApplication: Set to true to create an application with the specified name if it doesn't already exist.

    :type Process: boolean
    :param Process: Preprocesses and validates the environment manifest and configuration files in the source bundle. Validating configuration files can identify issues prior to deploying the application version to an environment.

    :rtype: dict
    :return: {
        'ApplicationVersion': {
            'ApplicationName': 'string',
            'Description': 'string',
            'VersionLabel': 'string',
            'SourceBuildInformation': {
                'SourceType': 'Git'|'Zip',
                'SourceRepository': 'CodeCommit'|'S3',
                'SourceLocation': 'string'
            },
            'BuildArn': 'string',
            'SourceBundle': {
                'S3Bucket': 'string',
                'S3Key': 'string'
            },
            'DateCreated': datetime(2015, 1, 1),
            'DateUpdated': datetime(2015, 1, 1),
            'Status': 'Processed'|'Unprocessed'|'Failed'|'Processing'|'Building'
        }
    }

    :returns:
    Git
    Zip

    """
    pass


def _get_entity_pair(entity_id, entities, cache, get_input_peer=get_input_peer
    ):
    """
    Returns ``(entity, input_entity)`` for the given entity ID.
    """
    entity = entities.get(entity_id)
    try:
        input_entity = cache[entity_id]
    except KeyError:
        try:
            input_entity = get_input_peer(entity)
        except TypeError:
            input_entity = None
    return entity, input_entity


@classmethod
def _from_raw_error(cls, map, error):
    """Construct a :class:`ComponentError` from a raw component error returned from an execute node."""
    return cls(map=map, component=error.component, exception_msg=error.
        exception_msg, node_info=error.node_info, python_info=error.
        python_info, scratch_dir_contents=error.scratch_dir_contents,
        stack_summary=error.stack_summary)


def new_or_existing(key):
    """return existing session with *key* or create one."""


def check_spacy():
    """
    Import necessary components from spaCy to perform tokenization.
    """
    try:
        import spacy
    except ImportError:
        raise ImportError(
            'spaCy is used but not installed on your machine. Go to https://spacy.io/usage for installation instructions.'
            )
    return True


def get_emails_by_permission(permission_code):
    """
    Get all email addresses of members by permission of user
    """
    from juntagrico.dao.memberdao import MemberDao
    emails = MemberDao.members_by_permission(permission_code).values_list(
        'email', flat=True)
    return emails


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 determine_refframe(phdr):
    """Determine the reference frame and equinox in standard FITS WCS terms.

    Parameters
    ----------
    phdr : `astropy.io.fits.Header`
        Primary Header of an observation

    Returns
    -------
    out : str, float
        Reference frame ('ICRS', 'FK5', 'FK4') and equinox

    """
    equinox = phdr.get('EQUINOX')
    radesys = phdr.get('RADESYS') or phdr.get('RADECSYS')
    if radesys == 'FK5' and equinox == 2000.0:
        return 'FK5', equinox
    elif radesys:
        return radesys, None
    elif equinox is not None:
        return 'FK4' if equinox < 1984.0 else 'FK5', equinox
    else:
        return None, None


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 topic_matches_sub(sub, topic):
    """Check whether a topic matches a subscription.

    For example:

    foo/bar would match the subscription foo/# or +/bar
    non/matching would not match the subscription non/+/+
    """
    result = True
    multilevel_wildcard = False
    slen = len(sub)
    tlen = len(topic)
    if slen > 0 and tlen > 0:
        if sub[0] == '$' and topic[0] != '$' or topic[0] == '$' and sub[0
            ] != '$':
            return False
    spos = 0
    tpos = 0
    while spos < slen and tpos < tlen:
        if sub[spos] == topic[tpos]:
            if tpos == tlen - 1:
                if spos == slen - 3 and sub[spos + 1] == '/' and sub[spos + 2
                    ] == '#':
                    result = True
                    multilevel_wildcard = True
                    break
            spos += 1
            tpos += 1
            if tpos == tlen and spos == slen - 1 and sub[spos] == '+':
                spos += 1
                result = True
                break
        elif sub[spos] == '+':
            spos += 1
            while tpos < tlen and topic[tpos] != '/':
                tpos += 1
            if tpos == tlen and spos == slen:
                result = True
                break
        elif sub[spos] == '#':
            multilevel_wildcard = True
            if spos + 1 != slen:
                result = False
                break
            else:
                result = True
                break
        else:
            result = False
            break
    if not multilevel_wildcard and (tpos < tlen or spos < slen):
        result = False
    return result


def getappattr(path):
    """Get attribute from current_app recursively.

    Example: ``getappattr('amqp.get_task_consumer')``.

    """
    from celery import current_app
    return current_app._rgetattr(path)


def subtract(num1, num2):
    """
    definition: func(arg1, arg2) {...}
    objective : the function returns you arg1 - arg2
    """
    return num1 - num2


def extensions_list(fp, comp_ext_list=['gz', 'tgz', 'zip', 'xz', 'bz2'], **
    kwargs):
    """
    Return The extension of a file in lower-case. If archived file ("gz", "tgz", "zip", "xz", "bz2")
    the method will output the base extension + the archive extension as a list
    """
    split_name = fp.split('/')[-1].split('.')
    if len(split_name) == 1:
        return []
    elif len(split_name) > 2 and split_name[-1].lower() in comp_ext_list:
        return [split_name[-2].lower(), split_name[-1].lower()]
    else:
        return [split_name[-1].lower()]


def fill():
    """Add bone between selected joint(s) and/or 3D-Cursor

    """
    pass


def select_less():
    """Reduce current selection by deselecting boundary elements

    """
    pass


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

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
         {
            "dynamic":true,
                "properties": {
                    "data": {
                        "properties": {
                            "versions_data": {
                                "dynamic":false,
                                "properties": {}
                            }
                        }
                    }
                }
        }
        """
    return {'items': mapping}


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

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

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


def logical_xor(image1, image2):
    """Logical XOR between two images. At least one of the images must have
    mode "1".

    .. code-block:: python

        out = ((bool(image1) != bool(image2)) % MAX)

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


def uint_to_slv(uint, width, allow_undefined=True):
    """
    Convert an unsigned integer to a string of '0' and '1'.

    >>> uint_to_slv(10, width=6)
    '001010'
    >>> uint_to_slv(3, width=3)
    '011'
    """
    if uint is None:
        slv = 'U' * width
        assert allow_undefined
    else:
        bits = []
        for w in range(width):
            bits.append('1' if uint % 2 else '0')
            uint //= 2
        slv = ''.join(reversed(bits))
    return slv


def onfinished():
    """Called after all objects have been emitted from the command function.

        Implementations should return an iterator of objects to forward to
        the output layer.

        This method can be a generator.
        """


def url(value):
    """Initializes the Scoggle API url"""
    global API_URL
    API_URL = value


def add_many_to_dict_val_set(dict_obj, key, val_list):
    """Adds the given value list to the set mapped by the given key.
    If the key is missing from the dict, the given mapping is added.

    Example
    -------
    >>> dict_obj = {'a': set([1, 2])}
    >>> add_many_to_dict_val_set(dict_obj, 'a', [2, 3])
    >>> print(dict_obj['a'])
    {1, 2, 3}
    >>> add_many_to_dict_val_set(dict_obj, 'b', [2, 3])
    >>> print(dict_obj['b'])
    {2, 3}
    """
    try:
        dict_obj[key].update(val_list)
    except KeyError:
        dict_obj[key] = set(val_list)


@classmethod
def set_axes_labels(cls, axes=None, plotconfig=None, figkwargs=None,
    label_dict=None):
    """Set axes labels.

        Parameters
        ----------
        axes : `matplotlib.axes`
        plotconfig : `PlotConfig`
        figkwargs : dict
        label_dict : dict

        """
    if label_dict is not None:
        xlabel = label_dict[plotconfig.strtype][plotconfig.xaxis.var]
        ylabel = label_dict[plotconfig.strtype][plotconfig.yaxis.var]
    else:
        xlabel = plotconfig.xaxis.label
        ylabel = plotconfig.yaxis.label
    axes.set_xlabel(xlabel, labelpad=figkwargs['labelpad'])
    axes.set_ylabel(ylabel, labelpad=figkwargs['labelpad'])


def traverse(name, context=None):
    """Traverse to a sub object called name, starting from root,
        or from content is specified.
        """


def is_class(typ) ->bool:
    """Returns True if the parameter is a class type
    """
    return isinstance(typ, type) and typ is not type(None)


def gotLength(length):
    """
        Called when L{HTTPChannel} has determined the length, if any,
        of the incoming request's body.

        @param length: The length of the request's body.
        @type length: L{int} if the request declares its body's length
            and L{None} if it does not.
        """


@classmethod
def _notEmpty(cls, val, **kwargs):
    """
        ensures a value is not empty
        """
    if val:
        return True
    else:
        return False


def find():
    """Find specified text

    """
    pass


@classmethod
def from_index(cls, index):
    """Return the Enum value at a given index."""
    return cls.ALL[index]


@classmethod
def program_name(cls):
    """Return the name of the program that this main window represents"""
    return 'MCR-ALS'


def translate(value, left_min, left_max, right_min, right_max):
    """This code maps values from the left range and interpolates to the
    corresponding range on the right. This is used to translate the amino acid
    substition matrix scores to a scale between 0 and 1 for making alphamaps.

    I don't know if this works if the directionality of the ranges are swapped.
      IE [5, -10] mapped to [0, 1]

    args:
      <value> - the value in [<left_min>:<left_max>] to scale between
                 [<right_min>:<right_max>]
      <left_min> - the 'min' of the left (source) range
      <left_max> - the 'max' of the left (source) range
      <right_min> - the 'min' of the right (target) range
      <right_max>   the 'max' of the right (target) range

    output:
      the <value>(float) scaled between <right_min> and <right_max>
    """
    left_span = left_max - left_min
    right_span = right_max - right_min
    value_scaled = float(value - left_min) / float(left_span)
    return right_min + value_scaled * right_span


def allclose(x, y, rtol=1e-05, atol=1e-08):
    """Returns True if x and y are sufficiently close, elementwise.

    Parameters
    ----------
    rtol : float
        The relative error tolerance.
    atol : float
        The absolute error tolerance.

    """
    for xi, yi in zip(x, y):
        if not abs(xi - yi) <= atol + rtol * abs(yi):
            return False
    return True


def unset_default_sampler():
    """Resets the default sampler back to None.

    Examples
    --------
    This example sets sampler0 as the default sampler, verifies the setting,
    then resets the default, and verifies the resetting.

    >>> dnx.set_default_sampler(sampler0)  # doctest: +SKIP
    >>> print(dnx.get_default_sampler())  # doctest: +SKIP
    'sampler0'
    >>> dnx.unset_default_sampler()  # doctest: +SKIP
    >>> print(dnx.get_default_sampler())  # doctest: +SKIP
    None
    """
    global _SAMPLER
    _SAMPLER = None


@classmethod
def from_values(cls, *args):
    """Construct a Stack from given values.

		Params:
		*args: Integer values to be pushed onto the stack being created.

		Returns: The newly created Stack object
		"""
    stk = cls(len(args))
    for val in args:
        stk.push(val)
    return stk


@classmethod
def CheckFilterExpression(cls, parser_filter_expression):
    """Checks parser and plugin names in a parser filter expression.

    Args:
      parser_filter_expression (str): parser filter expression,
          where None represents all parsers and plugins.

          A parser filter expression is a comma separated value string that
          denotes which parsers and plugins should be used. See
          filters/parser_filter.py for details of the expression syntax.

          This function does not support presets, and requires a parser filter
          expression where presets have been expanded.

    Returns:
      tuple: containing:

      * set(str): parser filter expression elements that contain known parser
          and/or plugin names.
      * set(str): parser filter expression elements that contain unknown parser
          and/or plugin names.
    """
    if not parser_filter_expression:
        return set(cls._parser_classes.keys()), set()
    known_parser_elements = set()
    unknown_parser_elements = set()
    for element in parser_filter_expression.split(','):
        parser_expression = element
        if element.startswith('!'):
            parser_expression = element[1:]
        parser_name, _, plugin_name = parser_expression.partition('/')
        parser_class = cls._parser_classes.get(parser_name, None)
        if not parser_class:
            unknown_parser_elements.add(element)
            continue
        if not plugin_name:
            known_parser_elements.add(element)
            continue
        if parser_class.SupportsPlugins():
            plugins = dict(parser_class.GetPlugins())
            if plugin_name in plugins:
                known_parser_elements.add(element)
            else:
                unknown_parser_elements.add(element)
    return known_parser_elements, unknown_parser_elements


def set_array_axis_names(kernel, ary_names, dim_names):
    """
    .. versionchanged:: 2016.2

        This function was called :func:`set_array_dim_names` before version 2016.2.
    """
    from loopy.kernel.tools import ArrayChanger
    if isinstance(ary_names, str):
        ary_names = ary_names.split(',')
    if isinstance(dim_names, str):
        dim_names = tuple(dim_names.split(','))
    for ary_name in ary_names:
        achng = ArrayChanger(kernel, ary_name)
        ary = achng.get()
        ary = ary.copy(dim_names=dim_names)
        kernel = achng.with_changed_array(ary)
    return kernel