def user_is_registrar(user, ra=None):
    """
    This function can be used to check whether a user is associated with ANY Registration Authority or associated with a
    specific Registration Authority.
    :param user: User object.
    :param ra: (Optional) Registration Authority object.
    :return: Boolean
    """
    if user.is_anonymous:
        return False
    if user.is_superuser:
        return True
    elif ra is None:
        return user.registrar_in.count() > 0
    else:
        return user in ra.registrars.all()


def change_zoom(ax, zoom_range, center=[0, 0, 0]):
    """
  Change the zoom of a 3d plot

  :author: Philipp Ruessmann

  :param ax: axis which is zoomed
  :param zoom_range: range to which the image is zoomed, total range from center-zoom_range to center+zoom_range
  :param center: center of the zoomed region (optional, defaults to origin)
  """
    ax.set_xlim(center[0] - zoom_range, center[0] + zoom_range)
    ax.set_ylim(center[1] - zoom_range, center[1] + zoom_range)
    ax.set_zlim(center[2] - zoom_range, center[2] + zoom_range)


def _measureType(x):
    """Takes Numeric Code and returns String API code

    Input Values: 1:"Base", 2:"Advanced", 3:"Misc", 4:"Four Factors", 5:"Scoring", 6:"Opponent", 7:"Usage"

    Used in:

    """
    measure = {(1): 'Base', (2): 'Advanced', (3): 'Misc', (4):
        'Four Factors', (5): 'Scoring', (6): 'Opponent', (7): 'Usage'}
    try:
        return measure[x]
    except:
        raise ValueError('Please enter a number between 1 and ' + str(len(
            measure)))


@classmethod
def get_all_transactions_by_address(cls, address):
    """Gets all transactions in dict related to an address.

        :param address: bch address
        :type address: ``str``
        :raises ConnectionError: If all API services fail.
        :rtype: ``list'' of ``dict``
        :return: All transactions in dict related to the address
        """
    for api_call in cls.GET_ALL_TXS_BY_ADDRESS:
        try:
            return api_call(address)
        except cls.IGNORED_ERRORS:
            pass
    raise ConnectionError('All APIs are unreachable.')


def _tag_depth(path, depth=None):
    """Add depth tag to path."""
    if not path or path[0] != '/':
        raise ValueError('Path must start with /!')
    if depth is None:
        depth = path.count('/')
    return '{}{}'.format(depth, path).encode('utf-8')


def roce(net_income, preferred_dividends, average_common_equity):
    """Computes return on common equity.

    @params
    -------
    net_income: net income
    preferred_dividends: preferred dividends
    average_common_equity: average common equity

    returns
    -------
    Return on common equity, int or float

    explanation
    -----------

    """
    return (net_income - preferred_dividends) / average_common_equity


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 remove_prohibited_element(tag_name, document_element):
    """
        To fit the Evernote DTD need, drop this tag name
    """
    elements = document_element.getElementsByTagName(tag_name)
    for element in elements:
        p = element.parentNode
        p.removeChild(element)


def build_template(data):
    """
    Build and return an addressbook file template
    """
    template = (
        '# abook addressbook file\n\n[format]\nprogram=abook\nversion=0.6.1\n\n'
        )
    for index, entry in enumerate(data):
        template += (
            f"\n[{index}]\nname={entry['name']}\nemail={','.join(entry['email'])}\n"
            )
        if entry['notes']:
            template += f"notes={entry['notes']}\n"
        if entry['custom1']:
            template += f"custom1={entry['custom1']}\n"
    template += '\n'
    return template


def clear_cache():
    """Clear translations cache
    """
    global _translated_strings_cache
    _translated_strings_cache = {}


@classmethod
def _create_join(cls, left, right, onclause=None, isouter=False, full=False):
    """Produce a :class:`_expression.Join` object, given two
        :class:`_expression.FromClause`
        expressions.

        E.g.::

            j = join(user_table, address_table,
                     user_table.c.id == address_table.c.user_id)
            stmt = select([user_table]).select_from(j)

        would emit SQL along the lines of::

            SELECT user.id, user.name FROM user
            JOIN address ON user.id = address.user_id

        Similar functionality is available given any
        :class:`_expression.FromClause` object (e.g. such as a
        :class:`_schema.Table`) using
        the :meth:`_expression.FromClause.join` method.

        :param left: The left side of the join.

        :param right: the right side of the join; this is any
         :class:`_expression.FromClause` object such as a
         :class:`_schema.Table` object, and
         may also be a selectable-compatible object such as an ORM-mapped
         class.

        :param onclause: a SQL expression representing the ON clause of the
         join.  If left at ``None``, :meth:`_expression.FromClause.join`
         will attempt to
         join the two tables based on a foreign key relationship.

        :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.

        :param full: if True, render a FULL OUTER JOIN, instead of JOIN.

         .. versionadded:: 1.1

        .. seealso::

            :meth:`_expression.FromClause.join` - method form,
            based on a given left side

            :class:`_expression.Join` - the type of object produced

        """
    return cls(left, right, onclause, isouter, full)


def is_state_by_state(tpm):
    """Return ``True`` if ``tpm`` is in state-by-state form, otherwise
    ``False``.
    """
    return tpm.ndim == 2 and tpm.shape[0] == tpm.shape[1]


def slope(p1, p2):
    """Returns the slope of the line from p1 to p2."""
    return float(p2[1] - p1[1]) / (p2[0] - p1[0])


def addEvent(event, fd, action):
    """
        Add a new win32 event to the event loop.

        @param event: a Win32 event object created using win32event.CreateEvent()

        @param fd: an instance of L{twisted.internet.abstract.FileDescriptor}

        @param action: a string that is a method name of the fd instance.
                       This method is called in response to the event.

        @return: None
        """


def to_proper_degrees(theta):
    """
    Converts theta (degrees) to be within -180 and 180.
    """
    if theta > 180 or theta < -180:
        theta = theta % 180
    return theta


def get_model_pk_attr_name(model_class):
    """
    Get the primary key attribute name from a Declarative model class

    :param Type[DeclarativeMeta] model_class: a Declarative class

    :return: str: a Column name
    """
    primary_key_columns = list(filter(lambda attr_col: attr_col[1].
        primary_key, model_class.__mapper__.columns.items()))
    if len(primary_key_columns) == 1:
        return primary_key_columns.pop()[0]
    elif len(primary_key_columns) < 1:
        raise RuntimeError(f"Couldn't find attribute for {model_class}")
    else:
        raise RuntimeError('Multiple primary keys still not supported')


@classmethod
def from_directive(cls, directive, app):
    """Return one of these whose state is all derived from a directive.

        This is suitable for top-level calls but not for when a renderer is
        being called from a different renderer, lest content and such from the
        outer directive be duplicated in the inner directive.

        :arg directive: The associated Sphinx directive
        :arg app: The Sphinx global app object. Some methods need this.

        """
    return cls(directive, app, arguments=directive.arguments, content=
        directive.content, options=directive.options)


def preset_add(name: str='', remove_name: bool=False, remove_active: bool=False
    ):
    """Add or remove a Safe Areas Preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_name: remove_name
    :type remove_name: bool
    :param remove_active: remove_active
    :type remove_active: bool
    """
    pass


def sequence_accuracy_score(y_true, y_pred):
    """
    Return sequence accuracy score. Match is counted only when two sequences
    are equal.
    """
    total = len(y_true)
    if not total:
        return 0
    matches = sum(1 for yseq_true, yseq_pred in zip(y_true, y_pred) if
        yseq_true == yseq_pred)
    return matches / total


def _filter_options(options, *names):
    """
        Return a subset of C{options} including only those listed in C{names}.  This is a
        utility method.  Its main purpose is to build a subset of options dictionary for
        C{L{_generate_derived_type_dictionary}} method, which is safe to use as locals or
        globals for evaluating method definitions.

        @param options: full dictionary of options.
        @type  options: C{dict}

        @param names:   permitted options.

        @rtype:         C{dict}
        """
    filtered_options = {}
    for name in names:
        if name in options:
            filtered_options[name] = options[name]
    return filtered_options


@staticmethod
def vertex_count(**kwargs):
    """Return the number of vertices as a function of the input data."""
    return 0


def setBias_thresh(bias_thresh_value):
    """ Copy bias_thresh to a variable that is global for this file.

        Parameters
        ----------
        bias_thresh_value : float
            value of bias_thresh
        """
    global bias_thresh
    bias_thresh = bias_thresh_value


@staticmethod
def __convert_result_from_old_client(api_result):
    """
        Tuple results always come without schema data, it is called by old clients
        new clients calls using return_schema=True and the result will be returned using a dict
        """
    if isinstance(api_result, (tuple, list)):
        result_url, total_rows, total_size, explicit_query = api_result
        api_result = {'ok': True, 'result_url': result_url,
            'total_data_points': total_rows, 'total_size': total_size,
            'explicit_query': explicit_query}
    return api_result


def _encodeRelativeValidityPeriod(validityPeriod):
    """ Encodes the specified relative validity period timedelta into an integer for use in an SMS PDU
    (based on the table in section 9.2.3.12 of GSM 03.40)

    :param validityPeriod: The validity period to encode
    :type validityPeriod: datetime.timedelta
    :rtype: int
    """
    seconds = validityPeriod.seconds + validityPeriod.days * 24 * 3600
    if seconds <= 43200:
        tpVp = int(seconds / 300) - 1
    elif seconds <= 86400:
        tpVp = int((seconds - 43200) / 1800) + 143
    elif validityPeriod.days <= 30:
        tpVp = validityPeriod.days + 166
    elif validityPeriod.days <= 441:
        tpVp = int(validityPeriod.days / 7) + 192
    else:
        raise ValueError(
            'Validity period too long; tpVp limited to 1 octet (max value: 255)'
            )
    return tpVp


def _to_str_list(data, transferer=id):
    """
    何らかのリストを文字列のリストにする
    """
    return list(map(lambda e: transferer(e), data))


def html_quote(line):
    """Change HTML special characters to their codes.

    Follows ISO 8859-1 Characters changed: `&`, `<` and `>`.
    """
    result = line
    if '`' not in result:
        result = line.replace('&', '&')
        result = result.replace('<', '<')
        result = result.replace('>', '>')
    return result


def fill_with_neg_inf(t):
    """FP16-compatible function that fills a tensor with -inf."""
    return t.float().fill_(float('-inf')).type_as(t)


def adjust_to_360(val, key):
    """
    Take in a value and a key.  If the key is of the type:
    declination/longitude/azimuth/direction, adjust it to be within
    the range 0-360 as required by the MagIC data model
    """
    CheckDec = ['_dec', '_lon', '_azimuth', 'dip_direction']
    adjust = False
    for dec_key in CheckDec:
        if dec_key in key:
            if key.endswith(dec_key) or key.endswith('_'):
                adjust = True
    if not val:
        return ''
    elif not adjust:
        return val
    elif adjust:
        new_val = float(val) % 360
        if new_val != float(val):
            print('-I- adjusted {} {} to 0=>360.: {}'.format(key, val, new_val)
                )
        return new_val


def _get_contain_size(src_img_size, dst_img_size):
    """Get image size which fit `dst_img_size`.

    Args:
        src_img_size (int, int): (x, y)
        dst_img_size (int, int): (x, y)

    Returns:
        (int, int): (x, y)
    """
    ratio_x = dst_img_size[0] / src_img_size[0]
    ratio_y = dst_img_size[1] / src_img_size[1]
    if ratio_x < ratio_y:
        size = dst_img_size[0], int(src_img_size[1] * ratio_x)
    else:
        size = int(src_img_size[0] * ratio_y), dst_img_size[1]
    return size


def count_voxels(masked_in, masked_out):
    """Count voxels in and outside the mask"""
    count_in = len(masked_in[masked_in != 0])
    count_out = len(masked_out[masked_out != 0])
    return count_in, count_out


@staticmethod
def validate(data):
    """
        Validates `data` for use in this container
        """
    return hasattr(data, 'count') and callable(data.count) and hasattr(data,
        'order_by') and callable(data.order_by)


def reg2bins_csi(rbeg, rend, min_shift=14, depth=5):
    """Generates bin ids which overlap the specified region.

    Args:
        rbeg (int): inclusive beginning position of region
        rend (int): exclusive end position of region

    Yields:
        (int): bin IDs for overlapping bins of region

    Raises:
        AssertionError (Exception): if the range is malformed or invalid
    """
    assert 0 <= rbeg <= rend, 'Invalid region {}, {}'.format(rbeg, rend)
    bins = []
    shift = min_shift + depth * 3
    rend -= 1
    level = total = 0
    while level <= depth:
        beg = total + (rbeg >> shift)
        end = total + (rend >> shift)
        i = beg
        while i <= end:
            yield i
            i += 1
        shift -= 3
        total += 1 << level * 3
        level += 1


def upper(x):
    """Returns the upper extreme of an uncertain quantity.
     This free function allows multiple uncertain quantity types to be supported
     in a generic way."""
    try:
        return x.upper
    except:
        try:
            return x.value + x.error
        except:
            return x


def remove(name, send_events=True, moving=None, loading=False):
    """ Same thing as ``__delitem__``.

        If ``send_events`` is false, suppress the sending of folder events.  If
        ``moving`` is not ``None``, it should be the folder object from which
        the object is being moved; the events sent will indicate that a move is
        in process.
        """


@classmethod
def register_model_query_hook(cls, model, name, query_hook, filter_hook,
    result_filters=None):
    """Register a hook to be invoked when a query is executed.

        Add the hooks to the _model_query_hooks dict. Models are the keys
        of this dict, whereas the value is another dict mapping hook names to
        callables performing the hook.
        Each hook has a "query" component, used to build the query expression
        and a "filter" component, which is used to build the filter expression.

        Query hooks take as input the query being built and return a
        transformed query expression.

        Filter hooks take as input the filter expression being built and return
        a transformed filter expression
        """
    model_hooks = cls._model_query_hooks.get(model)
    if not model_hooks:
        model_hooks = {}
        cls._model_query_hooks[model] = model_hooks
    model_hooks[name] = {'query': query_hook, 'filter': filter_hook,
        'result_filters': result_filters}


def p_enum_constant_list_2(t):
    """enum_constant_list : enum_constant COMMA enum_constant_list"""
    t[0] = t[1] + t[3]


@staticmethod
def variety_net_positions(fields='', symbol='RB', broker='永安期货', date=
    '2018-08-08'):
    """
        奇货可查-商品-商品净持仓数据接口
        :param fields: 需要返回的字段
        :type fields: str
        :param symbol: 查询品种编码
        :type symbol: str
        :param broker: 席位
        :type broker: str
        :param date: 查询日期
        :type date: str
        :return: 商品-商品净持仓数据
        :rtype: dict
        trans_date	date	查询日期
        net_position	int	净持仓数据
        """
    pass


def add_wait(parser):
    """ Add --wait option to parser """
    parser.add_argument('--wait', type=int, default=5, help=
        'Seconds to wait before killing topology. (default: %(default)s)')


def smooth():
    """Flatten angles of selected points

    """
    pass


def bin_to_gray(bin_list):
    """
    Convert from binary coding to gray coding.

    We assume big endian encoding.

    Examples
    ========

    >>> bin_to_gray('111')
    '100'

    See Also
    ========
    gray_to_bin

    """
    b = [bin_list[0]]
    for i in range(len(bin_list) - 1):
        b += str(int(bin_list[i]) ^ int(b[i - 1]))
    return ''.join(b)


def broadcast_minimum(lhs=None, rhs=None, name=None, attr=None, out=None,
    **kwargs):
    """Returns element-wise minimum of the input arrays with broadcasting.

    This function compares two input arrays and returns a new array having the element-wise minima.

    Example::

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

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

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

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_extended.cc:L117

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

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

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


@classmethod
def run(cls, list_of_methods, data, measurements_per_day=1):
    """
        Runs all signature methods from the given list and returns
        the result as a list of (variable, result) tuples.
        Multivariate hydrology are handled accordingly

        :param list_of_methods: A list of signature method objects
        :param data: A time series sequence
        :param measurements_per_day: Number of measurements per day (needed for some hydrology)
        :return: a list of (variable, result) tuples, len(result) might be
                longer then len(list_of_methods)
        """
    res = []
    for m in list_of_methods:
        res.extend(m(data, measurements_per_day))
    return res


def render_build_args(image_options, ns):
    """
    Render buildArgs from chartpress.yaml that could be templates, using
    provided namespace that contains keys with dynamic values such as
    LAST_COMMIT or TAG.

    Args:
    image_options (dict):
        The dictionary for a given image from chartpress.yaml.
        Fields in `image_options['buildArgs']` will be rendered
        and returned, if defined.
    ns (dict): the namespace used when rendering templated arguments
    """
    build_args = image_options.get('buildArgs', {})
    for key, value in build_args.items():
        build_args[key] = value.format(**ns)
    return build_args


def store_kibana_dashboard(dashboard_path, collector_ip, kibana_port,
    dashboard_id):
    """Store dashboard webpage"""
    with open(dashboard_path, 'w') as dfd:
        html = (
            '<iframe src="http://{0}:{1}/app/kibana#/dashboard/{2}?embed=true&_g=()" height=1000\\% width=100\\%></iframe>'
            .format(collector_ip, kibana_port, dashboard_id))
        dfd.write(html)


def get_incremental_step_size(min_win_size, max_win_size, start_step_len):
    """
    generates a list of incremental windows sizes (measured in bins)

    :param min_win_size: starting window size
    :param max_win_size: end window size
    :param start_step_len: start length
    :return: incremental_step list of bin lengths
    """
    incremental_step = []
    step = -1
    while 1:
        step += 1
        inc_step = min_win_size + int(start_step_len * step ** 1.5)
        if step > 1 and inc_step == incremental_step[-1]:
            continue
        if inc_step > max_win_size:
            break
        incremental_step.append(inc_step)
    return incremental_step


def addListing(parser):
    """
    Add option to request the list of versions.
    """
    if hasattr(parser, 'add_option'):
        from .options_old import addListing
        return addListing(parser)
    parser.add_argument('-l', '--list', action='store_true', help=
        'list the available versions of the requested project and exit',
        default=False)
    parser.add_argument('--list-versions', action='store_true', dest='list',
        help='obsolete spelling of --list', default=False)
    parser.add_argument('-L', '--list-platforms', action='store_true', help
        =
        'list the available platforms for the requested project/version and exit'
        , default=False)
    return parser


def invset(chars):
    """ Return a set with_what all characters *except* the ones in chars.
    """
    return set(chars, 0)


@staticmethod
def _combine_headers(response):
    """
        Combine "normal" http headers with the cookie headers into single list
        """
    return response.headers + response.cookies.cookie_headers


def calculate_passed_days(timestamp1, timestamp2):
    """
    Calculates the number of days between two timestamps.
    """
    if timestamp2 is None:
        return 0
    diff = timestamp1 - timestamp2
    min_sec = divmod(diff.days * 86400 + diff.seconds, 60)
    return min_sec[0] / (24 * 60)


def get_markings(obj):
    """
    Get all object level markings from the given SDO or SRO object.

    Args:
        obj: A SDO or SRO object.

    Returns:
        list: Marking identifiers contained in the SDO or SRO. Empty list if no
            markings are present in `object_marking_refs`.

    """
    return obj.get('object_marking_refs', [])


def delete_loose(use_verts: bool=True, use_edges: bool=True, use_faces:
    bool=False):
    """Delete loose vertices, edges or faces

    :param use_verts: Vertices, Remove loose vertices
    :type use_verts: bool
    :param use_edges: Edges, Remove loose edges
    :type use_edges: bool
    :param use_faces: Faces, Remove loose faces
    :type use_faces: bool
    """
    pass


def header2extent(header):
    """ convert a header dict to a 4-element tuple (left, right, bottom, top)
    all four elements shows the coordinates at the edge of a cell, not center
    """
    left = header['xllcorner']
    right = header['xllcorner'] + header['ncols'] * header['cellsize']
    bottom = header['yllcorner']
    top = header['yllcorner'] + header['nrows'] * header['cellsize']
    extent = left, right, bottom, top
    return extent


def ndim(input):
    """Return the number of dimensions of the tensor.

    Parameters
    ----------
    input : Tensor
        The input tensor.

    Returns
    -------
    int
        The number of dimensions
    """
    pass


def finalize_variable_expression(result: str) ->str:
    """Return empty strings for undefined template variables."""
    if result is None:
        return ''
    else:
        return result


def create_data_structure(emojis):
    """Create data structure to store the emojis
    :param emojis: Dictionary of emoji
    :type emojis: dict
    :rtype: dict
    """
    head = dict()
    for word in emojis.keys():
        current = head
        for char in word:
            try:
                current = current[char]
            except KeyError:
                _ = dict()
                current[char] = _
                current = _
        current['__end__'] = True
    return head


def _run_wsgi_app(*args):
    """This function replaces itself to ensure that the test module is not
    imported unless required.  DO NOT USE!
    """
    global _run_wsgi_app
    from ..test import run_wsgi_app as _run_wsgi_app
    return _run_wsgi_app(*args)


def is_closed(provider):
    """Test if provider is closed.

    :param provider: ingest provider
    """
    return provider.get('is_closed', False)


def canonicalize_node_size(node):
    """
    Given a node description from the GCE API returns the canonical cloudless
    format.
    """
    return {'type': node.name, 'memory': int(node.ram * 1000 * 1000),
        'cpus': float(node.extra['guestCpus']), 'storage': node.disk * 1024,
        'location': node.extra['zone'].name}


def std_scalar(comment, valueType='integer', option=0, **kwargs):
    """Description for standard scalar column."""
    return dict(comment=comment, valueType=valueType, dataManagerType=
        'StandardStMan', dataManagerGroup='StandardStMan', option=option,
        maxlen=0, **kwargs)


def str_format_old_to_new(string):
    """

    convert old format style to new style. Works for digits only

    %05d is converted to {:05d}

    :param string:

    :return:

    """
    import re
    return re.sub('%(\\d*d)', '{:\\1}', string)


def replace_route(DryRun=None, RouteTableId=None, DestinationCidrBlock=None,
    GatewayId=None, DestinationIpv6CidrBlock=None,
    EgressOnlyInternetGatewayId=None, InstanceId=None, NetworkInterfaceId=
    None, VpcPeeringConnectionId=None, NatGatewayId=None):
    """
    Replaces an existing route within a route table in a VPC. You must provide only one of the following: Internet gateway or virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, or egress-only Internet gateway.
    For more information about route tables, see Route Tables in the Amazon Virtual Private Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example replaces the specified route in the specified table table. The new route matches the specified CIDR and sends the traffic to the specified virtual private gateway.
    Expected Output:

    :example: response = client.replace_route(
        DryRun=True|False,
        RouteTableId='string',
        DestinationCidrBlock='string',
        GatewayId='string',
        DestinationIpv6CidrBlock='string',
        EgressOnlyInternetGatewayId='string',
        InstanceId='string',
        NetworkInterfaceId='string',
        VpcPeeringConnectionId='string',
        NatGatewayId='string'
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type RouteTableId: string
    :param RouteTableId: [REQUIRED]
            The ID of the route table.

    :type DestinationCidrBlock: string
    :param DestinationCidrBlock: The IPv4 CIDR address block used for the destination match. The value you provide must match the CIDR of an existing route in the table.

    :type GatewayId: string
    :param GatewayId: The ID of an Internet gateway or virtual private gateway.

    :type DestinationIpv6CidrBlock: string
    :param DestinationIpv6CidrBlock: The IPv6 CIDR address block used for the destination match. The value you provide must match the CIDR of an existing route in the table.

    :type EgressOnlyInternetGatewayId: string
    :param EgressOnlyInternetGatewayId: [IPv6 traffic only] The ID of an egress-only Internet gateway.

    :type InstanceId: string
    :param InstanceId: The ID of a NAT instance in your VPC.

    :type NetworkInterfaceId: string
    :param NetworkInterfaceId: The ID of a network interface.

    :type VpcPeeringConnectionId: string
    :param VpcPeeringConnectionId: The ID of a VPC peering connection.

    :type NatGatewayId: string
    :param NatGatewayId: [IPv4 traffic only] The ID of a NAT gateway.

    :return: response = client.replace_route(
        DestinationCidrBlock='10.0.0.0/16',
        GatewayId='vgw-9a4cacf3',
        RouteTableId='rtb-22574640',
    )

    print(response)

    """
    pass


@classmethod
def all(cls):
    """
        Return an iterator that successively yields saved model
        instances. Models are saved in an unordered :py:class:`Set`,
        so the iterator will return them in arbitrary order.

        Example::

            for note in Note.all():
                print note.content

        To return models in sorted order, see :py:meth:`Model.query`.
        Example returning all records, sorted newest to oldest::

            for note in Note.query(order_by=Note.timestamp.desc()):
                print note.timestamp, note.content
        """
    for result in cls._query.all_index():
        yield cls.load(result, convert_key=False)


def p_tocfile(t):
    """tocfile : headers tracks"""
    from audiotools.toc import TOCFile
    args = dict(t[1])
    args['tracks'] = t[2]
    t[0] = TOCFile(**args)


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

        :param SharedContentChangeInviteeRoleDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_change_invitee_role_details', val)


@staticmethod
def format_interval(t):
    """
        Formats a number of seconds as a clock time, [H:]MM:SS

        Parameters
        ----------
        t  : int
            Number of seconds.

        Returns
        -------
        out  : str
            [H:]MM:SS
        """
    mins, s = divmod(int(t), 60)
    h, m = divmod(mins, 60)
    if h:
        return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
    else:
        return '{0:02d}:{1:02d}'.format(m, s)


def lb_deleted_xml():
    """
    Return XML representation of CLB marked as DELETED
    """
    return (
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><message xmlns="http://docs.openstack.org/loadbalancers/api/v1.0" code="410">The loadbalancer is marked as deleted.</message>'
        , 410)


def strf3(val):
    """Formate une valeur float avec mantisse de taille raisonnable"""
    if val == 0.0:
        return '0.0'
    elif abs(val) > 1.0:
        strg = '{0:.3f}'.format(val)
    elif abs(val) > 0.01:
        strg = '{0:.6f}'.format(val)
    else:
        return '{0:.7e}'.format(val)
    if strg[-1] == '0':
        if strg[-2] == '0':
            if strg[-3] == '0':
                if strg[-4] == '0':
                    return strg[:-3]
                return strg[:-2]
            return strg[:-1]
        if strg[-2] != '.':
            return strg[:-1]
    return strg


def facet_data(facets):
    """ See adapters.FacetBuilder
        """


def create_object(DirectoryArn=None, SchemaFacets=None, ObjectAttributeList
    =None, ParentReference=None, LinkName=None):
    """
    Creates an object in a  Directory . Additionally attaches the object to a parent, if a parent reference and LinkName is specified. An object is simply a collection of  Facet attributes. You can also use this API call to create a policy object, if the facet from which you create the object is a policy facet.
    See also: AWS API Documentation

    :example: response = client.create_object(
        DirectoryArn='string',
        SchemaFacets=[
            {
                'SchemaArn': 'string',
                'FacetName': 'string'
            },
        ],
        ObjectAttributeList=[
            {
                'Key': {
                    'SchemaArn': 'string',
                    'FacetName': 'string',
                    'Name': 'string'
                },
                'Value': {
                    'StringValue': 'string',
                    'BinaryValue': b'bytes',
                    'BooleanValue': True|False,
                    'NumberValue': 'string',
                    'DatetimeValue': datetime(2015, 1, 1)
                }
            },
        ],
        ParentReference={
            'Selector': 'string'
        },
        LinkName='string'
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The Amazon Resource Name (ARN) that is associated with the Directory in which the object will be created. For more information, see arns .

    :type SchemaFacets: list
    :param SchemaFacets: [REQUIRED]
            A list of schema facets to be associated with the object that contains SchemaArn and facet name. For more information, see arns .
            (dict) --A facet.
            SchemaArn (string) --The ARN of the schema that contains the facet.
            FacetName (string) --The name of the facet.

    :type ObjectAttributeList: list
    :param ObjectAttributeList: The attribute map whose attribute ARN contains the key and attribute value as the map value.
            (dict) --The combination of an attribute key and an attribute value.
            Key (dict) -- [REQUIRED]The key of the attribute.
            SchemaArn (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the schema that contains the facet and attribute.
            FacetName (string) -- [REQUIRED]The name of the facet that the attribute exists within.
            Name (string) -- [REQUIRED]The name of the attribute.
            Value (dict) -- [REQUIRED]The value of the attribute.
            StringValue (string) --A string data value.
            BinaryValue (bytes) --A binary data value.
            BooleanValue (boolean) --A Boolean data value.
            NumberValue (string) --A number data value.
            DatetimeValue (datetime) --A date and time value.

    :type ParentReference: dict
    :param ParentReference: If specified, the parent reference to which this object will be attached.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

    :type LinkName: string
    :param LinkName: The name of link that is used to attach this object to a parent.

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

    """
    pass


@classmethod
def from_raw_data(cls, data):
    """
        Returns an instance of this class
        from the raw data

        :param data: A serialized DynamoDB object
        """
    if data is None:
        raise ValueError('Received no data to construct object')
    attributes = {}
    for name, value in data.items():
        attr_name = cls._dynamo_to_python_attr(name)
        attr = cls.get_attributes().get(attr_name, None)
        if attr:
            attributes[attr_name] = attr.deserialize(attr.get_value(value))
    return cls(_user_instantiated=False, **attributes)


def _check_arguments(d):
    """
    如果 d 全为空值,None ,则返回False . d.values有一个不为空,None,0 则 返回True
    """
    copy = d.copy()
    return any(copy.values())


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

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

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


def subtype_iter(synthases):
    """Iterate subtype groups in a collection of Synthase objects."""
    _synthases = sorted(synthases, key=lambda s: s.subtype)
    _group, _subtype = '', []
    for synthase in _synthases:
        if synthase.subtype != _subtype:
            if _group:
                yield _group
            _group, _subtype = [synthase], synthase.subtype
        else:
            _group.append(synthase)
    yield _group


def test_arc(archive, compression, cmd, verbosity, interactive):
    """Test a ARC archive."""
    return [cmd, 't', archive]


def get_split_start_stops_without_gene_calls(contig_length, split_length):
    """Returns split start stop locations for a given contig length."""
    num_chunks = int(contig_length / split_length)
    if num_chunks < 2:
        return [(0, contig_length)]
    chunks = []
    for i in range(0, num_chunks):
        chunks.append((i * split_length, (i + 1) * split_length))
    chunks.append(((i + 1) * split_length, contig_length))
    if chunks[-1][1] - chunks[-1][0] < split_length / 2:
        last_tuple = chunks[-2][0], contig_length
        chunks.pop()
        chunks.pop()
        chunks.append(last_tuple)
    return chunks


@classmethod
def order_and_label(cls, t):
    """Order and label of a discrete type.

        Cf. :meth:`Profile.order_and_label`.

        Examples
        --------
            >>> ProfileTwelve.order_and_label('ab_c')
            ('abc', '$r(ab\\\\_c)$')
            >>> ProfileTwelve.order_and_label('a~b>c')
            ('a~b>c', '$r(a\\\\sim b>c)$')
        """
    if len(t) == 4:
        return t.replace('_', ''), ('$r(%s)$' % t).replace('_', '\\_')
    else:
        return cls.order_and_label_weak(t)


def getHTTPCachingHeaders(content, view_method, keywords, time=None):
    """ Update HTTP caching headers in REQUEST

        o 'content' is the content object being published.

        o 'view_method' is the name of the view being published

        o 'keywords' is a set of extra keywords modifying the view.

        o If 'time' is supplied, use it instead of the current time
          (for reliable testing).
        """


@classmethod
def validReasons(cls):
    """ Returns a tuple with all valid reasond
        """
    return cls.__VALID_REASONS


def _curio_runner(coroutine):
    """
    handler for curio autoawait
    """
    import curio
    return curio.run(coroutine)


@staticmethod
def setup_command_line(parser):
    """Setup the command line options for Parity Principle formula

        Arguments:
        - `parser`: parser to load with options.
        """
    parser.add_argument('N', metavar='<N>', type=int, help='domain size')


def fixType(n):
    """
    If n is an integer, convert to a float, but leave complex as
    complex.
    """
    if type(n) == int:
        return float(n)
    else:
        return n


def write(packet):
    """
        Write packet to address we are connected to.
        """


@staticmethod
def all_transports():
    """Reimplemented safetlib.transport.all_transports so that we can
        enable/disable specific transports.
        """
    try:
        from safetlib.transport import all_transports
    except ImportError:
        transports = []
        try:
            from safetlib.transport_hid import HidTransport
            transports.append(HidTransport)
        except BaseException:
            pass
        try:
            from safetlib.transport_webusb import WebUsbTransport
            transports.append(WebUsbTransport)
        except BaseException:
            pass
    else:
        transports = []
        try:
            from safetlib.transport.hid import HidTransport
            transports.append(HidTransport)
        except BaseException:
            pass
        try:
            from safetlib.transport.webusb import WebUsbTransport
            transports.append(WebUsbTransport)
        except BaseException:
            pass
        return transports
    return transports


@classmethod
def from_tabular(cls, *args, **kwargs):
    """
        Construct Corpus object by loading documents from a tabular file, i.e. CSV or Excel file. See method
        :meth:`~tmtoolkit.corpus.Corpus.add_tabular()` for available arguments.

        :return: Corpus instance
        """
    return cls().add_tabular(*args, **kwargs)


def trim_text(text, max_len):
    """
    Trim input text to fit the `max_len` condition.

    If trim is needed: keep the first 1/3rd of the budget on the top,
    and the other 2 thirds on the bottom.
    """
    if len(text) <= max_len:
        return text
    trimmed_text = (
        u'{top_third}\n```\n*...trimmed...*\n```\n{bottom_two_third}\n'.
        format(top_third=text[:max_len // 3], bottom_two_third=text[len(
        text) - 2 * max_len // 3:]))
    return trimmed_text


def setup_time(t):
    """Takes a time generally assumed to be quite small and blows it
    up into millisecond time.

    For example:
        0.004 seconds     -> 4 ms
        0.00025 seconds   -> 0.25 ms

    The result is returned as a string.

    """
    t = t * 1000
    t = '%0.2f' % t
    return t


def parse(signature):
    """ Parses the header value
    and returns a list (<auth_header_prefix>, <access_key>, <hmac_hex_digest>).
    """
    prefix, access_key_hmac_digest = signature.split(' ', 1)
    return [prefix] + access_key_hmac_digest.split(':')


def broadcast_mul(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs
    ):
    """Returns element-wise product of the input arrays with broadcasting.

    Example::

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

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

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

    Supported sparse operations:

       broadcast_mul(csr, dense(1D)) = csr

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L146

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

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

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


def delete_bucket_metrics_configuration(Bucket=None, Id=None):
    """
    Deletes a metrics configuration (specified by the metrics configuration ID) from the bucket.
    See also: AWS API Documentation

    :example: response = client.delete_bucket_metrics_configuration(
        Bucket='string',
        Id='string'
    )

    :type Bucket: string
    :param Bucket: [REQUIRED] The name of the bucket containing the metrics configuration to delete.

    :type Id: string
    :param Id: [REQUIRED] The ID used to identify the metrics configuration.

    """
    pass


def get_preferred_sparse_format():
    """Get the preferred sparse matrix format supported by the backend.

    Different backends have their preferred backend. This info is useful when
    constructing a sparse matrix.
    """
    return 'csr'


def remove_quotes(string: str) ->str:
    """
    Removes quotes from around a string, if they are present.

    :param string:  The string to remove quotes from.
    :return:        The string without quotes.
    """
    if string.startswith('"') and string.endswith('"'):
        string = string[1:-1]
    elif string.endswith("'") and string.endswith("'"):
        string = string[1:-1]
    return string


def flip_xy(xyz):
    """Flip x and y coordinates whether or not there is a z-coordinate"""
    xyz = list(xyz)
    xyz[0], xyz[1] = xyz[1], xyz[0]
    return tuple(xyz)


def save_DM_to_hdf5(dm, file):
    """
    Saves mesh information stored in the DM to HDF5 file
    If the file already exists, it is overwritten.
    """
    from petsc4py import PETSc
    file = str(file)
    if not file.endswith('.h5'):
        file += '.h5'
    ViewHDF5 = PETSc.Viewer()
    ViewHDF5.createHDF5(file, mode='w')
    ViewHDF5.view(obj=dm)
    ViewHDF5.destroy()
    return


def _create_dummy_frequencies(trips):
    """Create station stop frequencies."""
    for trip in trips:
        yield {'trip_id': trip['trip_id'], 'start_time': '04:30:00',
            'end_time': '08:30:00', 'headway_secs': '1200'}
        yield {'trip_id': trip['trip_id'], 'start_time': '08:30:00',
            'end_time': '20:30:00', 'headway_secs': '1800'}
        yield {'trip_id': trip['trip_id'], 'start_time': '20:30:00',
            'end_time': '25:30:00', 'headway_secs': '2800'}


def parse(atom_types_filename):
    """
    Parse ``atom_types`` file
    """
    d = {}
    with open(atom_types_filename) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            fields = line.split('#', 1)[0].split()
            d[fields[0].upper()] = fields[1]
    return d


@classmethod
def from_operating_mode(cls, operating_mode):
    """
        Class constructor.

        Args:
            operating_mode (:class:`.OperatingMode`): the operating mode that generates the exceptions.
        """
    return cls('Unsupported operating mode: ' + operating_mode.description)


def get_sintegra():
    """
        Gets an object that implements ISintegraData or None.
        """


@classmethod
def stop_cache_monitor(cls):
    """
        Stop the cache monitor thread. Blocks until the thread stops.
        """
    with cls._monitor_lock:
        cls._stop_thread.set()
        cls._monitor_thread.join()
        cls._monitor_thread = None


def get_active_tetrode(set_filename):
    """in the .set files it will say collectMask_X Y for each tetrode number to tell you if
    it is active or not. T1 = ch1-ch4, T2 = ch5-ch8, etc."""
    active_tetrode = []
    active_tetrode_str = 'collectMask_'
    with open(set_filename) as f:
        for line in f:
            if active_tetrode_str in line:
                tetrode_str, tetrode_status = line.split(' ')
                if int(tetrode_status) == 1:
                    tetrode_str.find('_')
                    tet_number = int(tetrode_str[tetrode_str.find('_') + 1:])
                    active_tetrode.append(tet_number)
    return active_tetrode


def GetAbsolutePPMError(t, m):
    """
    calculate theoretical (t) and measured (m) ppm
    """
    return abs((t - m) / t * 1000000.0)


def filter_based_on_query_coverage(query_length, query_start_index,
    query_stop_index, query_coverage_threshold):
    """
    Determine if read should be filtered based on query coverage threshold
    """
    if query_length > 1:
        query_coverage = (abs(query_stop_index - query_start_index) + 1
            ) / float(query_length) * 100.0
    else:
        query_coverage = query_coverage_threshold + 1.0
    filter = False
    if query_coverage < query_coverage_threshold:
        filter = True
    return filter


@classmethod
def pause(cls):
    """Stops on the next JavaScript statement.
        """
    return cls.build_send_payload('pause', {}), None


def encodeInto(x, r):
    """encode an integer using a 7-bit+continuation-bit encodeing into an existing list"""
    n = 0
    y = x
    while True:
        n += 1
        y >>= 15
        r.append(0)
        if y == 0:
            break
    v = n
    i = -1
    m = 0
    while n > 0:
        r[i] = x & 32767 | m
        x >>= 15
        i -= 1
        m = 32768
        n -= 1


def str_to_bool(s):
    """
    Converts the given string into a boolean.

    Values resulting in True:
    - a string representing an integer != 0
    - the string 'true' ignoring upper/lower case
    - the string 'y' or 'yes' ignoring upper/lower case

    Other values will result in False as return value.

    :param s: The string to convert
    :type s: str
    :return: A boolean value
    :rtype: bool
    """
    if isinstance(s, bool):
        return s
    if not isinstance(s, str):
        return False
    if s.lower() in ('true', 'yes', 'y'):
        return True
    try:
        i = int(s)
        if i != 0:
            return True
    except ValueError:
        pass
    return False


def check_name_test(value):
    """
    This function tests the text input widget.

    :param value: The widget value
    :type value: str
    :return: None
    """
    print('User name: {0}'.format(value))


def find_nested_attr(config, attr):
    """
    Takes a config dictionary and an attribute string as input and tries to
    find the attribute in the dictionary. The attribute may use dots to
    indicate levels of depth within the dictionary.

    Example:
    find_nested_attr({'one': {'two': {'three': 3}}}, 'one.two.three')
    --> 3
    """
    obj = config.copy()
    for section in attr.split('.'):
        obj = obj[section]
    return obj


@classmethod
def package_group_remove(cls, options):
    """Uninstall package groups remotely."""
    cls.command_sub = 'package-group remove'
    return cls.execute(cls._construct_command(options), output_format='csv')


@classmethod
def _clean(cls):
    """For testing purpose only"""
    with cls.__dict_lock:
        cls.__dict.clear()
        cls.__dict_nonweak.clear()
        cls.__dict_rev_cache.clear()


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

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

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


def __getitem__(uid):
    """Return the message with the uid `uid`."""


def reveal():
    """Reveal all hidden UV vertices

    """
    pass


def describe_identity_pool(IdentityPoolId=None):
    """
    Gets details about a particular identity pool, including the pool name, ID description, creation date, and current number of users.
    You must use AWS Developer credentials to call this API.
    See also: AWS API Documentation

    :example: response = client.describe_identity_pool(
        IdentityPoolId='string'
    )

    :type IdentityPoolId: string
    :param IdentityPoolId: [REQUIRED]
            An identity pool ID in the format REGION:GUID.

    :rtype: dict
    :return: {
        'IdentityPoolId': 'string',
        'IdentityPoolName': 'string',
        'AllowUnauthenticatedIdentities': True|False,
        'SupportedLoginProviders': {
            'string': 'string'
        },
        'DeveloperProviderName': 'string',
        'OpenIdConnectProviderARNs': [
            'string',
        ],
        'CognitoIdentityProviders': [
            {
                'ProviderName': 'string',
                'ClientId': 'string',
                'ServerSideTokenCheck': True|False
            },
        ],
        'SamlProviderARNs': [
            'string',
        ]
    }

    :returns:
    (string) --

    """
    pass


def _TMP_admissible_plane_tree_iterator(a, verbose=False):
    """
    Iterator through plane trees with at most nmax vertices.

    INPUT:

    - ``a`` - the angle at the vertices divided by pi.

    OUTPUT:

    - ``(t,n,l)`` - ``t`` is a tree, ``n`` its number of nodes and ``l`` its
      number of leaves.

    ALGORITHM:

    variables in the algorithm

    t : the current tree
    b : the current branch explored in the tree of trees
    n : number of nodes of t except the root
    l : number of leaves of t

    the tree is valid if 2n >= a and 2n-l <= a
    """
    t = [0]
    b = []
    n = 0
    l = 1
    while True:
        if verbose:
            print(t)
            print('n = %2d,   l = %2d' % (n, l))
        if 2 * n >= a and 2 * n - l <= a:
            if verbose:
                print('yield')
            t.append(0)
            yield t, n, l
            t.pop(-1)
        if n <= a and 2 * n - l < a:
            if verbose:
                print('go down')
                print('  append: %d' % (t[-1] + 1))
            t.append(t[-1] + 1)
            b.append(t[-1])
            n += 1
        else:
            if verbose:
                print('go up')
            while b and b[-1] == 1:
                if verbose:
                    print(' pop')
                b.pop(-1)
                t.pop(-1)
                n -= 1
                l -= 1
            if b == []:
                break
            if verbose:
                print(' modify last')
            if len(t) > 1 and t[-2] == t[-1] - 1:
                l += 1
            b[-1] -= 1
            t[-1] = b[-1]
        if verbose:
            print()


def merge_nodes(graph):
    """ merges nodes into single node if same neighbors

    Parameters
    ----------
    graph: nx.DiGraph

    Returns
    -------
    nx.DiGraph
    """
    neighbors2node = dict()
    nodes = set(graph.nodes())
    edges = set(graph.edges())
    new_g = graph.copy()
    for i in nodes:
        down = '|'.join(sorted(graph.successors(i)))
        up = '|'.join(sorted(graph.predecessors(i)))
        if (down, up) in neighbors2node:
            neighbors2node[down, up].add(i)
        else:
            neighbors2node[down, up] = {i}
    for node, neigh in neighbors2node.items():
        if len(neigh) > 1:
            print(node, neigh)
            new_name = '|'.join(sorted(neigh))
            for x in node[0].split('|'):
                if x != '':
                    for n in neigh:
                        if (x, n) in edges:
                            new_g.remove_edge(x, n)
                            new_g.add_edge(x, new_name, **graph.edge[x][n])
                            edges.remove((x, n))
            for x in node[1].split('|'):
                if x != '':
                    for n in neigh:
                        if (n, x) in edges:
                            new_g.remove_edge(n, x)
                            new_g.add_edge(new_name, x, **graph.edge[n][x])
                            edges.remove((n, x))
    print('{} nodes and {} edges'.format(len(graph.nodes), len(graph.edges)))
    print('{} nodes and {} edges'.format(len(new_g.nodes), len(new_g.edges)))
    for n in new_g.nodes():
        if len(new_g.successors(n)) == 0 and len(new_g.predecessors(n)) == 0:
            new_g.remove_node(n)
    print('{} nodes and {} edges'.format(len(new_g.nodes), len(new_g.edges)))
    return new_g


def reqany(container, first, *options):
    """ If the first option is set, at least one of the others is required. """
    if first is not None and container.get(first) is None:
        return
    for option in options:
        if container.get(option) is not None:
            return
    if first is None:
        raise ValueError('one of this option is required: %s' % ', '.join(
            options))
    raise ValueError('option %s requires one of: %s' % (first, ', '.join(
        options)))


@property
def is_dicotic(G):
    """
        Whether the Surreal number is dicotic or not. Only the Surreal 0 is dicotic.

        Returns
        -------
        dicotic : bool
            Whether this number is dicotic.
        """
    return G._n == 0


@staticmethod
def get_ovs_interfaceid(vif):
    """Returns the interface id to set for a given VIF.

        When a VIF is plugged for an Open vSwitch, it needs to have the
        interface ID set in the OVS metadata.  This returns what the
        appropriate interface id is.

        :param vif: The Nova network interface.
        """
    return vif.get('ovs_interfaceid') or vif['id']


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 startswith_strip(s, startswith='http://', ignorecase=True):
    """ Strip a prefix from the beginning of a string

    >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://')
    'TotalGood.com'
    >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False)
    'HTtp://TotalGood.com'
    """
    if ignorecase:
        if s.lower().startswith(startswith.lower()):
            return s[len(startswith):]
    elif s.endswith(startswith):
        return s[len(startswith):]
    return s


def get_charset(response, default='utf-8'):
    """Return encoding."""
    try:
        return response.info().get_param('charset', default)
    except AttributeError:
        content_type = response.headers['content-type']
        split_on = 'charset='
        if split_on in content_type:
            return content_type.split(split_on)[-1]
        else:
            return default


def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10):
    """
    sound is a pydub.AudioSegment
    silence_threshold in dB
    chunk_size in ms

    iterate over chunks until you find the first one with sound
    """
    trim_ms = 0
    assert chunk_size > 0
    while sound[trim_ms:trim_ms + chunk_size
        ].dBFS < silence_threshold and trim_ms < len(sound):
        trim_ms += chunk_size
    return trim_ms


def findRelationTokenChains(query, maxDepth=None, filter=None, targetQuery=
    None, targetFilter=None, queryFactory=None):
    """find tuples of relation tokens for searchTerms.
        - query is a dictionary of {indexName: token}
        - maxDepth is None or a positive integer that specifies maximum depth
          for transitive results.  None means that the transitiveMap will be
          followed until a cycle is detected.  It is a ValueError to provide a
          non-None depth if queryFactory is None and
          index.defaultTransitiveQueriesFactory is None.
        - filter is a an optional callable providing IFilter that determines
          whether relations will be traversed at all.
        - targetQuery is an optional query that specifies that only paths with
          final relations that match the targetQuery should be returned.
          It represents a useful subset of the jobs that can be done with the
          targetFilter.
        - targetFilter is an optional callable providing IFilter that
          determines whether a given path will be included in results (it will
          still be traversed)
        - optional queryFactory takes the place of the index's
          matching registered queryFactory, if any.
        """


def discard(obj, value):
    """Remove the specified value associated with the object.

        Comparisons are made with the IKeyReference hashes.

        If `value` is not set for `obj`, silently ignores.
        """


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


@staticmethod
def basic_header_words():
    """ The number of words that make up a basic header with no additional information """
    return 4


def _is_same_value_at_column(i, all_args):
    """ comparison from both ends so as to find opportunistically that the parameter is not the same everywhere"""
    left, right = 1, len(all_args) - 1
    value = all_args[0][i]
    while True:
        if value != all_args[left][i]:
            return False
        left += 1
        if value != all_args[right][i]:
            return False
        right -= 1
        if left > right:
            break
    return True


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

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

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


@classmethod
def restore_from(cls, file_request):
    """Restore a Criteria instance from the file request.

        This is used to restore the criteria for our file generation when loading a file
        request from the database.
        """
    raise NotImplementedError()


@classmethod
def get(cls, top, parent):
    """
        Get various attributes from the cdpAdjEp
        :param parent:
        :param top: the topSystem level json object
        :returns: list of cdpAdjEp objects
        """
    cls.check_parent(parent)
    result = []
    adjEp_data = top.get_subtree('cdpAdjEp', parent.attr['dn'])
    for adjEp_object in adjEp_data:
        adjEp = cls()
        adjEp._populate_from_attributes(adjEp_object['cdpAdjEp']['attributes'])
        adjEp.attr['dn'] = str(adjEp_object['cdpAdjEp']['attributes']['dn'])
        adjEp._parent = parent
        adjEp._parent.add_child(adjEp)
        result.append(adjEp)
    return result


def union_bounding_box(a: tuple, b: tuple) ->tuple:
    """
    Get the bounding box resulting of the union of two bounding boxes.

    :param a: Tuple defining a bounding box using the format (x, y, width, height)
    :param b: Tuple defining a bounding box using the format (x, y, width, height)
    :return:
    """
    x = min(a[0], b[0])
    y = min(a[1], b[1])
    w = max(a[0] + a[2], b[0] + b[2]) - x
    h = max(a[1] + a[3], b[1] + b[3]) - y
    return x, y, w, h


@classmethod
def subscribe(cls, handler):
    """Subscribes a handler function to the notification feed of this event.
        """
    cls.manager.subscribe(cls, handler)


def indent(block_of_text, indentation):
    """
    Helper function to indent a block of text.

    Take a block of text, an indentation string and return the indented block.
    """
    return '\n'.join(map(lambda x: indentation + x, block_of_text.split('\n')))


@classmethod
def get_default_config(cls) ->dict:
    """Default config getter."""
    return {'num_dup': 1, 'batch_size': 8, 'stage': 'train', 'resample':
        True, 'shuffle': False, 'sort': True, 'bin_size': 30, 'hist_mode':
        'LCH', 'compress_ratio_left': 1.0, 'compress_ratio_right': 1.0,
        'embedding_output_dim': 100}


def is_number(string):
    """
    Checks if string can be cast to a number
    """
    try:
        _ = float(string)
        return True
    except ValueError:
        return False


def _p_to_scalar(mat, p, p0=0.5):
    """
    Simple internal function that turns a p parameter for anp row sensitivity
    into the scalar value to multiply the row by.

    :param mat: The matrix that this p will be applied to.  As of this writing,
        it is not used in the calculation.

    :param p: The p-value to convert.  Should be a number between 0 and 1.

    :param p0: The fixed value, should be a number between 0 and 1 EXCLUSIVE

    :return: A list of two items.  The first is a boolean telling whether
        we scaled Up (True) or Down (False) and the second item is the scalar
        to multiply the row by.
    """
    if p < p0:
        return False, p / p0
    else:
        return True, (1 - p) / (1 - p0)


def slope_intercept(point1, point2):
    """Returns the slope and intercept between point1 and point2.

    Parameters
    ----------
    point1 : tuple
       e.g. (1.3, 4)

    point2 : tuple

    Output
    ------
      A tuple(slope, intercept)"""
    x0, y0 = point1
    x1, y1 = point2
    slope = (y1 - y0) / float(x1 - x0)
    intercept = y1 - slope * x1
    return slope, intercept


def _get_text(topnode):
    """Get the text values in the child nodes."""
    text = ''
    for node in topnode.childNodes:
        if node.nodeType == node.TEXT_NODE:
            text = text + node.data
    return text


def is_ip(s):
    """
    Check a string whether is a legal ip address.

    :type s: string
    :param s: None
    =======================
    :return:
        **Boolean**
    """
    try:
        tmp_list = s.split(':')
        s = tmp_list[0]
        if s == 'localhost':
            return True
        tmp_list = s.split('.')
        if len(tmp_list) != 4:
            return False
        else:
            for i in tmp_list:
                if int(i) < 0 or int(i) > 255:
                    return False
    except:
        return False
    return True


def _convert_write_row(row):
    """ Convert a row for write/delete event """
    return row


def write_wavetable(wavetable, filename):
    """ Write wavetable to an h2p oscillator file

        @param wavetable zwave.WaveTable : Wavetable
        @param filename str : File name to write to
    """
    table_size = wavetable.wave_len
    if table_size is None:
        return
    with open(filename, 'w') as osc_file:
        osc_file.write('#defaults=no\n')
        osc_file.write('#cm=OSC\n')
        osc_file.write('Wave=2\n')
        osc_file.write('<?\n')
        osc_file.write('\n')
        osc_file.write('float Wave[')
        osc_file.write(str(table_size))
        osc_file.write('];\n')
        osc_file.write('\n')
        for i, wave in enumerate(wavetable.get_waves()):
            if wave is None:
                continue
            wave_num = i + 1
            scaled_wave = wave * 0.999969
            osc_file.write('//table ')
            osc_file.write(str(wave_num))
            osc_file.write('\n')
            for index, value in enumerate(scaled_wave):
                osc_file.write('Wave[')
                osc_file.write(str(index))
                osc_file.write('] = ')
                osc_file.write('{0:.10f}'.format(value))
                osc_file.write(';\n')
            osc_file.write('Selected.WaveTable.set(')
            osc_file.write(str(wave_num))
            osc_file.write(', Wave);\n')
            osc_file.write('\n')
        osc_file.write('?>')


def smooth():
    """Apply weighted moving means to make selected F-Curves less bumpy

    """
    pass


def admin_list_groups_for_user(Username=None, UserPoolId=None, Limit=None,
    NextToken=None):
    """
    Lists the groups that the user belongs to.
    Requires developer credentials.
    See also: AWS API Documentation

    :example: response = client.admin_list_groups_for_user(
        Username='string',
        UserPoolId='string',
        Limit=123,
        NextToken='string'
    )

    :type Username: string
    :param Username: [REQUIRED]
            The username for the user.

    :type UserPoolId: string
    :param UserPoolId: [REQUIRED]
            The user pool ID for the user pool.

    :type Limit: integer
    :param Limit: The limit of the request to list groups.

    :type NextToken: string
    :param NextToken: An identifier that was returned from the previous call to this operation, which can be used to return the next set of items in the list.

    :rtype: dict
    :return: {
        'Groups': [
            {
                'GroupName': 'string',
                'UserPoolId': 'string',
                'Description': 'string',
                'RoleArn': 'string',
                'Precedence': 123,
                'LastModifiedDate': datetime(2015, 1, 1),
                'CreationDate': datetime(2015, 1, 1)
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def rename(d, pair_list):
    """mutator. given a dictionary `d` and a list of (old-name, new-name) pairs, renames old-name to new-name, if it exists"""
    for old, new in pair_list:
        if old in d:
            d[new] = d[old]
            del d[old]


def number_of_detections(img, detections):
    """Here we find the number of objects detected"""
    if len(detections) == 1:
        return '1 object detected'
    else:
        return '{} objects detected'.format(len(detections))


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 Head(num):
    """
    Display at most the first N of the model objects

    Example::
        self.olv.SetFilter(Filter.Head(1000))
    """
    return lambda modelObjects: modelObjects[:num]


def get_dialect_name(conn_string):
    """Get the dbms from the connection string.

    example:
    when connection string = 'oracle://scott:tiger@127.0.0.1:1521/sidname'
    it returns 'oracle'.
    """
    dialect = str(conn_string).split(':')[0]
    if '+' in dialect:
        dialect = dialect.split('+')[0]
    dialect = dialect.replace('postgresql', 'postgres')
    return dialect


def uniq(lst):
    """return lst with unique elements."""
    seen = []
    for _ in lst:
        if _ not in seen:
            seen.append(_)
            yield _


def get_identity_notification_attributes(Identities=None):
    """
    Given a list of verified identities (email addresses and/or domains), returns a structure describing identity notification attributes.
    This action is throttled at one request per second and can only get notification attributes for up to 100 identities at a time.
    For more information about using notifications with Amazon SES, see the Amazon SES Developer Guide .
    See also: AWS API Documentation

    Examples
    The following example returns the notification attributes for an identity:
    Expected Output:

    :example: response = client.get_identity_notification_attributes(
        Identities=[
            'string',
        ]
    )

    :type Identities: list
    :param Identities: [REQUIRED]
            A list of one or more identities. You can specify an identity by using its name or by using its Amazon Resource Name (ARN). Examples: user@example.com , example.com , arn:aws:ses:us-east-1:123456789012:identity/example.com .
            (string) --

    :rtype: dict
    :return: {
        'NotificationAttributes': {
            'string': {
                'BounceTopic': 'string',
                'ComplaintTopic': 'string',
                'DeliveryTopic': 'string',
                'ForwardingEnabled': True|False,
                'HeadersInBounceNotificationsEnabled': True|False,
                'HeadersInComplaintNotificationsEnabled': True|False,
                'HeadersInDeliveryNotificationsEnabled': True|False
            }
        }
    }

    """
    pass


def executeQuery(index):
    """Execute the query represented by this node against the index.

        The index argument must implement the IIndex interface.

        Return an IFBucket or IFBTree mapping document ids to scores
        (higher scores mean better results).

        May raise ParseTree.QueryError.
        """


def b_spline_gradient_image_filter(*args, **kwargs):
    """Procedural interface for BSplineGradientImageFilter"""
    import itk
    instance = itk.BSplineGradientImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


def _search_on_path(filenames):
    """Find file on system path."""
    from os.path import exists, abspath, join
    from os import pathsep, environ
    search_path = environ['PATH']
    paths = search_path.split(pathsep)
    for path in paths:
        for filename in filenames:
            if exists(join(path, filename)):
                return abspath(join(path, filename))


def type_object_attrgetter(obj, attr, *defargs):
    """
    This implements an improved attrgetter for type objects (i.e. classes)
    that can handle class attributes that are implemented as properties on
    a metaclass.

    Normally `getattr` on a class with a `property` (say, "foo"), would return
    the `property` object itself.  However, if the class has a metaclass which
    *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find
    the "foo" property on the metaclass and resolve it.  For the purposes of
    autodoc we just want to document the "foo" property defined on the class,
    not on the metaclass.

    For example::

        >>> class Meta(type):
        ...     @property
        ...     def foo(cls):
        ...         return 'foo'
        ...
        >>> class MyClass(metaclass=Meta):
        ...     @property
        ...     def foo(self):
        ...         ""\"Docstring for MyClass.foo property.""\"
        ...         return 'myfoo'
        ...
        >>> getattr(MyClass, 'foo')
        'foo'
        >>> type_object_attrgetter(MyClass, 'foo')
        <property at 0x...>
        >>> type_object_attrgetter(MyClass, 'foo').__doc__
        'Docstring for MyClass.foo property.'

    The last line of the example shows the desired behavior for the purposes
    of autodoc.
    """
    for base in obj.__mro__:
        if attr in base.__dict__:
            if isinstance(base.__dict__[attr], property):
                return base.__dict__[attr]
            break
    return getattr(obj, attr, *defargs)


def register_api(app, view, endpoint, url, pk='pk', pk_type='int'):
    """
    register_api(UserAPI, 'user_api', '/users/', pk='user_id')
    /users/ list user  post
    /users/1 get delete put
    """
    view_func = view.as_view(endpoint)
    app.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods
        =['GET'])
    app.add_url_rule(url, view_func=view_func, methods=['POST'])
    app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func,
        methods=['GET', 'PUT', 'DELETE'])


def get_event_details(event):
    """Extract event image and timestamp - image with no tag will be tagged as latest.

    :param dict event: start container event dictionary.
    :return tuple: (container image, last use timestamp).
    """
    image = str(event['from'] if ':' in event['from'] else event['from'] +
        ':latest')
    timestamp = event['time']
    return image, timestamp


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 _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def test_flac(archive, compression, cmd, verbosity, interactive):
    """Test a FLAC file."""
    return [cmd, '--test', archive]


def getEndpointMemos(batch):
    """Converts a batch to a pair of (lower, upper) endpoint memos.

        :return: A tuple of bytestrings suitable for inclusion in URLs.
        """


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

        :param DisabledDomainInvitesType val:
        :rtype: EventType
        """
    return cls('disabled_domain_invites', val)


def descriptionLists(orderedDictionary={}, sideBySide=False):
    """
    *A list of definitions.*

    **Key Arguments:**
        - ``orderedDictionary`` -- the ordered dictionary of the terms and their definitions
        - ``sideBySide`` -- Make terms and descriptions in
 line up side-by-side.

    **Return:**
        - ``descriptionLists``
    """
    termList = ''
    for k, v in orderedDictionary.iteritems():
        termList = (
            """%(termList)s

%(k)s

%(v)s

        """
             % locals())
    if sideBySide:
        sideBySide = 'dl-horizontal'
    else:
        sideBySide = ''
    descriptionLists = (
        """

            %(termList)s

    """
         % locals())
    return descriptionLists


def get_equiv_class(fsm, gamma, state):
    """
    Return the equivalence class for gamma state belongs to. The distributed
    knowledge based equivalence fo gamma containing state is returned.

    fsm -- the model
    gamma -- a set of agents of fsm
    """
    return fsm.equivalent_states(state, gamma) & fsm.reachable_states


@staticmethod
def _transfer_tensor(tensor):
    """ Static method to return any tensor to a numpy equivalent """
    return tensor.cpu().detach().numpy()


def merge_dicts(first_dict, *dicts):
    """
    Merge several dicts

    This function is needed for Python 2 support. It will be REMOVED on January 1, 2020.
    Python 3 alternative: x = {**a, **b}
    """
    new_dict = first_dict.copy()
    for dict_ in dicts:
        new_dict.update(dict_)
    return new_dict


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

        :param ConnectedTeamName val:
        :rtype: FederationStatusChangeAdditionalInfo
        """
    return cls('connected_team_name', val)


def damerau_levenshtein_distance(s1, s2):
    """
    Calculates an edit distance, for typo detection. Code based on :
    https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
    """
    d = {}
    string_1_length = len(s1)
    string_2_length = len(s2)
    for i in range(-1, string_1_length + 1):
        d[i, -1] = i + 1
    for j in range(-1, string_2_length + 1):
        d[-1, j] = j + 1
    for i in range(string_1_length):
        for j in range(string_2_length):
            if s1[i] == s2[j]:
                cost = 0
            else:
                cost = 1
            d[i, j] = min(d[i - 1, j] + 1, d[i, j - 1] + 1, d[i - 1, j - 1] +
                cost)
            if i and j and s1[i] == s2[j - 1] and s1[i - 1] == s2[j]:
                d[i, j] = min(d[i, j], d[i - 2, j - 2] + cost)
    return d[string_1_length - 1, string_2_length - 1]


def reshape_to_2d(arr):
    """
  Assumes a 3D Numpy array, and reshapes like

  arr.reshape((arr.shape[0], arr.shape[1]*arr.shape[2]))

  This is useful for converting processed data from `complex_to_power`
  and from `autocorrelation` into a 2D array for image analysis and display.

  """
    return arr.reshape((arr.shape[0], arr.shape[1] * arr.shape[2]))


def comparator(predicate):
    """Makes a comparator function out of a function that reports whether the first
element is less than the second"""
    return lambda a, b: predicate(a, b) * -1 + predicate(b, a) * 1


def mix_molecule_ff(ff_list, mixing_rule):
    """Mix molecule-molecule interactions in case of separate_interactions: return mixed ff_list"""
    from math import sqrt
    ff_mix = []
    for i, ffi in enumerate(ff_list):
        for ffj in ff_list[i:]:
            if ffi[1].lower() == ffj[1].lower() == 'lennard-jones':
                eps_mix = sqrt(ffi[2] * ffj[2])
                if mixing_rule == 'lorentz-berthelot':
                    sig_mix = 0.5 * (ffi[3] + ffj[3])
                elif mixing_rule == 'jorgensen':
                    sig_mix = sqrt(ffi[3] * ffj[3])
                ff_mix.append('{} {} lennard-jones {:.5f} {:.5f}'.format(
                    ffi[0], ffj[0], eps_mix, sig_mix))
            elif 'zero-potential' in [ffi[1], ffj[1]]:
                ff_mix.append('{} {} zero-potential'.format(ffi[0], ffj[0]))
            elif ffi[1].lower() == ffj[1].lower(
                ) == 'feynman-hibbs-lennard-jones':
                eps_mix = sqrt(ffi[2] * ffj[2])
                if mixing_rule == 'lorentz-berthelot':
                    sig_mix = 0.5 * (ffi[3] + ffj[3])
                elif mixing_rule == 'jorgensen':
                    sig_mix = sqrt(ffi[3] * ffj[3])
                reduced_mass = ffi[4]
                ff_mix.append(
                    '{} {} feynman-hibbs-lennard-jones {:.5f} {:.5f} {:.5f}'
                    .format(ffi[0], ffj[0], eps_mix, sig_mix, reduced_mass))
            else:
                raise NotImplementedError(
                    'FFBuilder is not able to mix different/unknown potentials.'
                    )
    return ff_mix


def draw_bbox(img, bbox, **kwarg):
    """draw bbox on copied img

    Parameters
    ----------
    img : PIL.Image
        image which you want to draw box on
    bbox : iterable
        [x_min, y_min, x_max, y_max]
        normalized coordinate. [0, 1]

    Returns
    -------
    c_img: PIL.Image
        drawn copied image
    """
    from PIL import ImageDraw
    img = img.copy()
    w, h = img.size
    draw = ImageDraw.Draw(img)
    draw.rectangle([bbox[0] * w, bbox[1] * h, bbox[2] * w, bbox[3] * h], **
        kwarg)
    del draw
    return img


def face_map_assign():
    """Assign faces to a face map

    """
    pass


@classmethod
def depsize(cls, v):
    """Checks that DEPEND has same shape as that dim

        Compares the size of variables specified in the variable
        attributes for `DEPEND
        <https://spdf.gsfc.nasa.gov/istp_guide/vattributes.html#DEPEND_0>`_
        and compares to the size of the corresponding dimension in
        this variable.

        Parameters
        ----------
        v : :class:`~spacepy.pycdf.Var`
            Variable to check

        Returns
        -------
        list of str
            Description of each validation failure.

        """
    rv = int(v.rv())
    errs = []
    if v.shape == (0,):
        if 'DEPEND_1' in v.attrs or 'DEPEND_2' in v.attrs:
            errs.append(
                'Do not expect DEPEND_1 or DEPEND_2 in 1 dimensional variable.'
                )
    for i in range(rv, len(v.shape)):
        depidx = i + 1 - rv
        target = v.shape[i]
        if not 'DEPEND_{}'.format(depidx) in v.attrs:
            continue
        d = v.attrs['DEPEND_{}'.format(depidx)]
        if d in v.cdf_file:
            dv = v.cdf_file[d]
        else:
            continue
        if dv.rv() != ('DEPEND_0' in dv.attrs):
            errs.append('DEPEND_{} {} is RV but has no DEPEND_0.'.format(
                depidx, d))
            continue
        if 'DEPEND_2' in dv.attrs:
            errs.append('Do not expect three layers of dependency.')
            continue
        elif 'DEPEND_1' in dv.attrs:
            dd = dv.attrs['DEPEND_1']
            if dd in v.cdf_file:
                ddv = v.cdf_file[dd]
            else:
                continue
            actual = list(dv.shape)
            for ii in actual:
                if ii in ddv.shape:
                    actual.remove(ii)
            if 'DEPEND_0' in dv.attrs:
                dd = dv.attrs['DEPEND_0']
                if dd[:5] != 'Epoch':
                    errs.append('Expect DEPEND_0 to be Epoch.')
                    continue
                if dd in v.cdf_file:
                    ddv = v.cdf_file[dd]
                else:
                    continue
                for ii in actual:
                    if ii in ddv.shape:
                        actual.remove(ii)
            if len(actual) != 1:
                errs.append(
                    'More complicated double dependency than taken into account.'
                    )
                continue
            else:
                actual = actual[0]
        else:
            actual = dv.shape[int(dv.rv())]
        if target != actual:
            errs.append('Dim {} sized {} but DEPEND_{} {} sized {}.'.format
                (i, target, depidx, d, actual))
    return errs


def _hosted_zones(route53):
    """Enumerates all Route53 hosted zones as tuples of id, name"""
    paginator = route53.get_paginator('list_hosted_zones')
    for result in paginator.paginate():
        for zone in result['HostedZones']:
            yield zone['Id'], zone['Name']


def get_bam_ref_name(bam_file):
    """Get first ref name in bam file"""
    import pysam
    samfile = pysam.AlignmentFile(bam_file, 'r')
    try:
        aln = samfile.fetch()
    except ValueError:
        return
    for a in aln:
        chr = samfile.get_reference_name(a.next_reference_id)
        if chr != None:
            break
    return chr


@staticmethod
def _verification_needed(cacert, insecure):
    """Return the verify parameter.

        The value of verify can be either True/False or a cacert.

        :param cacert None or path to CA cert file
        :param insecure truthy value to switch on SSL verification
        """
    if insecure is False or insecure is None:
        verify = cacert or True
    else:
        verify = False
    return verify


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

        :param ShowcaseChangeDownloadPolicyDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_change_download_policy_details', val)


@classmethod
def _package_installed(cls, package_info):
    """
        Try to find out whether the specified package is installed or not.

        If the installed state cannot be determined with certainty we assume
        it's installed.

        Args:
            package_info (package_info.PackageInfo):
                The package to check.

        Returns:
            True or False

        """
    return cls.installed_states.get(package_info.status, True)


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

        :param FileChangeCommentSubscriptionDetails val:
        :rtype: EventDetails
        """
    return cls('file_change_comment_subscription_details', val)


def save_hex(hex_file, path):
    """
    Given a string representation of a hex file, this function copies it to
    the specified path thus causing the device mounted at that point to be
    flashed.

    If the hex_file is empty it will raise a ValueError.

    If the filename at the end of the path does not end in '.hex' it will raise
    a ValueError.
    """
    if not hex_file:
        raise ValueError('Cannot flash an empty .hex file.')
    if not path.endswith('.hex'):
        raise ValueError('The path to flash must be for a .hex file.')
    with open(path, 'wb') as output:
        output.write(hex_file.encode('ascii'))


def is_response_to_head(response):
    """
    Checks whether the request of a response has been a HEAD-request.
    Handles the quirks of AppEngine.

    :param conn:
    :type conn: :class:`httplib.HTTPResponse`
    """
    method = response._method
    if isinstance(method, int):
        return method == 3
    return method.upper() == 'HEAD'


def eq_obj_slots(l, r):
    """
    Compares objects with __slots__ defined
    :param l:
    :param r:
    :return:
    """
    for f in l.__slots__:
        if getattr(l, f, None) != getattr(r, f, None):
            return False
    return True


def get_kernel_header_template():
    """
    Returns the OpenCL kernel header template,
    where constants and macros are defined.
    """
    return """
    #pragma OPENCL EXTENSION cl_khr_fp64 : enable
    #define DATA_TYPE_%(DATA_TYPE)s
    #define INIT_MAXVAL %(INIT_MAXVAL)i
    #define ITERATIONS %(ITERATIONS)i
    #define FILTER_HALF_Y_SIZE %(FILTER_HALF_Y_SIZE)i
    #define FILTER_HALF_Y_SIZE_PLUS_ONE %(FILTER_HALF_Y_SIZE_PLUS_ONE)i
    #define FILTER_HALF_X_SIZE %(FILTER_HALF_X_SIZE)i
    #define FILTER_HALF_X_SIZE_PLUS_ONE %(FILTER_HALF_X_SIZE_PLUS_ONE)i
    #define MEDIAN_PIVOT_SIZE %(MEDIAN_PIVOT_SIZE)i
    #define SHARED_WINDOW_WIDTH %(SHARED_WINDOW_WIDTH)i
    #define SHARED_WINDOW_HEIGHT %(SHARED_WINDOW_HEIGHT)i
    #define DATA_W %(DATA_W)i
    #define DATA_H %(DATA_H)i
    #define WORK_GROUP_W %(WORK_GROUP_W)i
    #define WORK_GROUP_H %(WORK_GROUP_H)i

    #define SHARED_WINDOW(y,x)  shared_window[(y)+FILTER_HALF_Y_SIZE][(x)+FILTER_HALF_X_SIZE]
    #define INPUT(y,x)          input[(y)*DATA_W + (x)]
    #define RESULT(y,x)         result[(y)*DATA_W + (x)]

    """


def __call__():
    """Return the name of the adapted field
        """


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

        :param SharedContentAddLinkExpiryDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_add_link_expiry_details', val)


@classmethod
def from_simple_list(cls, simple_list):
    """Return an instance of the ojbect using simple_list as its 'input'
        """
    raise NotImplementedError()


def default_context(plugin, context):
    """
    Return the default context for plugins rendered with a template, which
    simply is a single variable named ``plugin`` containing the plugin
    instance.
    """
    return {'plugin': plugin}


def get_input_addresses(unsigned_tx):
    """
    Helper function to get the addresses needed used in an unsigned transaction.
    You will next have to retrieve the keys for these addreses in order to sign.

    Depending on how they are generated, unsigned transactions often use
    inputs whose address would be hard to know in advance, hence this step.

    Note:
    - if the same address is used in multiple inputs, it will be returned multiple times
    - this funciton does not work for p2sh inputs
    """
    addresses = []
    for input_obj in unsigned_tx['tx']['inputs']:
        addresses.append(input_obj['addresses'][0])
    return addresses


def notice(msg):
    """ Print short notice message without newline. """
    print(msg, end='', flush=True)


def uninstall(context):
    """Uninstall script"""


def render(context, mimetype, content, filename=None, url=None):
    """Render an XHTML preview of the raw ``content`` in a
        `RenderingContext`.

        The `content` might be:
         * a `str` object
         * an `unicode` string
         * any object with a `read` method, returning one of the above

        It is assumed that the content will correspond to the given `mimetype`.

        Besides the `content` value, the same content may eventually
        be available through the `filename` or `url` parameters.
        This is useful for renderers that embed objects, using <object> or
        <img> instead of including the content inline.

        Can return the generated XHTML text as a single string or as an
        iterable that yields strings. In the latter case, the list will
        be considered to correspond to lines of text in the original content.

        """


def append_all(src_str, append, delimiter):
    """
    Add the append string into each split sub-strings of the
    first string(=src=). The split is performed into src string
    using the delimiter . E.g. appendAll("/a/b/,/c/b/,/c/d/", "ADD", ",")
    will return /a/b/ADD,/c/b/ADD,/c/d/ADD. A append string with null
    value is consider as an empty string. A delimiter string with value null
    is considered as no append in the string.
    """
    if not delimiter:
        return src_str
    if not append:
        append = ''
    split_str = src_str.split(delimiter)
    appended_list = []
    for split in split_str:
        appended_list.append(split + append)
    return delimiter.join(appended_list)


def period(freq):
    """
Convert array of frequencies to periods.
    """
    return 1.0 / freq


def icon_url():
    """Return unicode string: icon URL or empty string"""


def rolesOfPermission(permission):
    """Returns a permission to role mapping.
        """


@staticmethod
def _msg_to_value(msg):
    """
        Inverse of :meth:`Hyperparameters._value_to_msg`.

        Parameters
        ----------
        msg : HyperparameterValuesConfigBlob

        Returns
        -------
        value : int or float or str or None

        """
    return getattr(msg, msg.WhichOneof('value'), None)


def divide(Cb, Cs):
    """
    Looks at the color information in each channel and divides the blend color
    from the base color.
    """
    B = Cb / (Cs + 1e-06)
    B[B > 1] = 1
    return B


def foundation_shear_reduction_factor():
    """
    Returns the displacement reduction factor for soil-foundation shear deformation.
    :param cor_norm_rot:
    """
    return 0.76


@classmethod
def from_file(cls, filename, language=None):
    """
        Parse a file or filename into a :class:`Feature`.
        """
    return cls.parse(filename=filename, language=language)