def from_formatted_lines(lines):
    """
    Return text from a list of `lines` strings using the Debian
    Description rules for handling line prefixes and continuations.
    """
    if not lines:
        return lines
    text = [lines[0].strip()]
    for line in lines[1:]:
        line = line.rstrip()
        if line.startswith('  '):
            text.append(line[1:])
        elif line == ' .':
            text.append('')
        elif line.startswith(' .'):
            text.append(line[2:])
        elif line.startswith(' '):
            text.append(line.strip())
        else:
            text.append(line.strip())
    return '\n'.join(text).strip()


def update_sequence(session, table_name, sequence_name=None):
    """
    On insert with given id, PostgreSQL does not update the sequence
    for autoincrement. Thus tables with defaults cannot use autoincremented
    PK anymore. Thus, the sequence is set to the current value
    """
    if sequence_name is None:
        sequence_name = '%s_id_seq' % table_name
    sql = "SELECT setval('%s', (SELECT MAX(id) from %s), true);" % (
        sequence_name, table_name)
    res = session.execute(sql)
    return res.scalar()


def is_numeric(obj):
    """Check whether object is a number or not, include numpy number, etc."""
    try:
        float(obj)
        return True
    except (TypeError, ValueError):
        return False


@classmethod
def on_mapping_configuration_finished(cls, controller):
    """
    Callback function that is triggered, when the configuration of a controller is complete

    :param controller:              the controller that was configured
    :type controller:               steuer.Controller
    """
    print('EVENT:' + 'controller type {0} configuration finished'.format(
        controller.name))


def clear():
    """ Clear all values from the dictionary """


@classmethod
def as_attenuation(cls, vrms=1, **kwargs):
    """
        Allows levels to be specified in dB attenuation
        """
    return cls.from_spl([0, 100000.0], [0, 0], vrms, **kwargs)


def trace_path(x0, y0, v, f, s, t0, p):
    """x0, y0 impact position in mm, v, f, s are vectors of the ray and fast
    and slow directions in lab frame, t0 is thickness in mm and p pixel size in
    mm"""
    import math
    n = f.cross(s)
    a = v.angle(n)
    t = t0 / math.cos(a)
    dx = t0 * v.dot(f) / v.dot(n)
    dy = t0 * v.dot(s) / v.dot(n)
    x1 = x0 + dx
    y1 = y0 + dy
    nx0 = x0 / p
    nx1 = x1 / p
    ny0 = y0 / p
    ny1 = y1 / p
    pixels = []
    if abs(dy) > abs(dx):
        if dy > 0:
            start, end, step = int(ny0), int(ny1) + 1, 1
            d0, d1 = 0, 1
        else:
            start, end, step = int(ny0), int(ny1) - 1, -1
            d0, d1 = -1, 0
        m = dx / dy
        s = int(round(m / abs(m))) * step
        pixels = []
        for j in range(start, end, step):
            if j == start:
                l0 = ny0
            else:
                l0 = j + d0 * step
            if j == end - step:
                l1 = ny1
            else:
                l1 = j + d1 * step
            m0 = nx0 + (l0 - ny0) * m
            m1 = nx0 + (l1 - ny0) * m
            c = int(m0) if s < 0 else int(m1)
            if int(m1) != int(m0):
                l2 = l0 + (c - m0) / m
                _s = p * math.sqrt((l2 - l0) ** 2 + (c - m0) ** 2) / math.sin(a
                    )
                pixels.append((int(m0), int(l0), _s))
                _s = p * math.sqrt((l1 - l2) ** 2 + (m1 - c) ** 2) / math.sin(a
                    )
                pixels.append((int(m1), int(l0), _s))
            else:
                _s = p * math.sqrt((l1 - l0) ** 2 + (m1 - m0) ** 2) / math.sin(
                    a)
                pixels.append((int(c), int(l0), _s))
    else:
        if dx > 0:
            start, end, step = int(nx0), int(nx1) + 1, 1
            d0, d1 = 0, 1
        else:
            start, end, step = int(nx0), int(nx1) - 1, -1
            d0, d1 = -1, 0
        m = dy / dx
        s = int(round(m / abs(m))) * step
        for j in range(start, end, step):
            if j == start:
                l0 = nx0
            else:
                l0 = j + d0 * step
            if j == end - step:
                l1 = nx1
            else:
                l1 = j + d1 * step
            m0 = ny0 + (l0 - nx0) * m
            m1 = ny0 + (l1 - nx0) * m
            c = int(m0) if s < 0 else int(m1)
            if int(m1) != int(m0):
                l2 = l0 + (c - m0) / m
                _s = p * math.sqrt((l2 - l0) ** 2 + (c - m0) ** 2) / math.sin(a
                    )
                pixels.append((int(l0), int(m0), _s))
                _s = p * math.sqrt((l1 - l2) ** 2 + (m1 - c) ** 2) / math.sin(a
                    )
                pixels.append((int(l0), int(m1), _s))
            else:
                _s = p * math.sqrt((l1 - l0) ** 2 + (m1 - m0) ** 2) / math.sin(
                    a)
                pixels.append((int(l0), int(c), _s))
    return pixels


def buckle_thickness(D_o, P_p, sig_y):
    """
    Number [m], Number [Pa], Number [Pa] -> Number [m]

    Returns the nominal buckle thickness based on the propagation pressure.

    Considers the worst case maximum external pressure and ignores internal
    pressure.

    Equation (G.21)
    """
    return D_o * (P_p / (10.7 * sig_y)) ** (4 / 9)


def replace_accumulated_errors(track, logs, log):
    """Replace accumulated track errors."""
    for error in logs[0].track_errors:
        if track in log.track_errors[error]:
            continue
        for i, original_track in enumerate(logs[0].track_errors[error]):
            if track == original_track:
                logs[0].track_errors[error].pop(i)


@classmethod
def supported(cls, conn):
    """Return whether GSS MIC authentication is supported"""
    return conn.gss_mic_auth_supported()


def bottom_arrow_path(x, y, offset):
    """ x,y is the final point
    """
    d = [('m', x, y - 2 * offset), (0, offset), (offset, 0), (-offset,
        offset), (-offset, -offset), (offset, 0), 'z']
    return d


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 _set_from(slot, val):
    """Connect a :class:`~madgui.util.collections.Bool` to the given slot.
    This is used to keep the state of ``QAction.checked`` and ``.enabled``
    properties synchronized."""
    if val is not None:
        try:
            cur = val()
            val.changed.connect(slot)
        except TypeError:
            cur = val
        slot(cur)


def get_filters(filters):
    """Return the rsync options for the given filters."""
    arguments = []
    for filter_ in filters:
        if len(filter_) > 1:
            raise Exception('Filter must contain only one entry: {}'.format
                (filter_))
        if 'exclude' in filter_:
            arguments += ['--exclude', filter_['exclude']]
        elif 'include' in filter_:
            arguments += ['--include', filter_['include']]
        else:
            raise Exception('Filter must contain include or exclude: {}'.
                format(filter_))
    return arguments


@classmethod
def factory(cls, global_config, **local_config):
    """Used for paste app factories in paste.deploy config files.

        Any local configuration (that is, values under the [app:APPNAME]
        section of the paste config) will be passed into the `__init__` method
        as kwargs.

        A hypothetical configuration would look like:

            [app:wadl]
            latest_version = 1.3
            paste.app_factory = nova.api.fancy_api:Wadl.factory

        which would result in a call to the `Wadl` class as

            import nova.api.fancy_api
            fancy_api.Wadl(latest_version='1.3')

        You could of course re-implement the `factory` method in subclasses,
        but using the kwarg passing it shouldn't be necessary.

        """
    return cls(**local_config)


def parse_bool(value):
    """
    >>> parse_bool(1)
    True
    >>> parse_bool('off')
    False
    >>> parse_bool('foo')
    """
    value = str(value).lower()
    if value in ('on', 'true', 'yes', '1'):
        return True
    if value in ('off', 'false', 'no', '0'):
        return False


def sort_urls(urls):
    """
    Order URLs by extension.
    This function accepts a list of URLs and orders them by their extension.
    CSS files are sorted to the start of the list, then JS, then everything
    else.
    """
    order = {'css': 0, 'js': 1}
    urls.sort(key=lambda x: order.get(x.rsplit('.')[-1].lower(), 2))
    return urls


@classmethod
def fieldset_with_legend(cls, legend_text):
    """Returns an XPath to find a FieldSet with the given `legend_text`.

        .. versionadded:: 3.2
        """
    return cls(
        '//fieldset[legend[normalize-space(node())=normalize-space("%s")]]' %
        legend_text)


def datetime_to_int(date_object):
    """
    Convert a datetime object to an integer value.
    :param date_object: a datetime object
    :return: an integer value
    """
    return int(date_object.strftime('%s'))


def undouble_unicode_escape(value):
    """Work around a unicode bug somewhere in the PloneLDAP stack
    that results in some values being doubly unicode encoded.
    """
    if isinstance(value, str):
        return value
    try:
        return value.encode('raw_unicode_escape').decode('utf-8')
    except UnicodeDecodeError:
        return value
    except Exception:
        return value


def render_review_comment(review):
    """
    Allows tweaks such as markdown rendering.
    """
    return review.comment


def extract_header(msg_or_header):
    """Given a message or header, return the header."""
    if not msg_or_header:
        return {}
    try:
        h = msg_or_header['header']
    except KeyError:
        try:
            h = msg_or_header['msg_id']
        except KeyError:
            raise
        else:
            h = msg_or_header
    if not isinstance(h, dict):
        h = dict(h)
    return h


def padl(text, n, c):
    """
    left pad of text with character c
    """
    text = str(text)
    return str(c) * (n - len(text)) + text


def stroke_trim():
    """Trim selected stroke to first loop or intersection

    """
    pass


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 _a_encode_list(values, mapping):
    """
    [1,2,3] --> ['3', 'l', '1', 'i', '1', '1', 'i', '2', '1', 'i', '3']
    """
    assert isinstance(values, list), 'VALUE has invalid type: %s' % type(values
        )
    encoded = [str(len(values)).encode('UTF-8'), b'l']
    extend = encoded.extend
    for value in values:
        extend(mapping[type(value).__name__](value, mapping))
    return encoded


@staticmethod
def from_b58check(private_key):
    """ Decodes a Base58Check encoded private-key.

        Args:
            private_key (str): A Base58Check encoded private key.

        Returns:
            PrivateKey: A PrivateKey object
        """
    raise NotImplementedError


def encode_value_in_name(value, name, max_name_len=20):
    ' Return `name` as fixed-length string, appending `value` as string.\n\n    Form output from `name` if `value <= 1` else `name` + ``\x00`` +\n    str(value).\n\n    Return output as fixed length string length `max_name_len`, padded with\n    ``\x00``.\n\n    This function also verifies that the modified length of name is less than\n    `max_name_len`.\n\n    Parameters\n    ----------\n    value : int\n        Integer value to encode.\n    name : str\n        Name to which we may append an ascii / latin-1 representation of\n        `value`.\n    max_name_len : int, optional\n        Maximum length of byte string that output can have.\n\n    Returns\n    -------\n    encoded_name : bytes\n        Name maybe followed by ``\x00`` and ascii / latin-1 representation of\n        `value`, padded with ``\x00`` bytes.\n    '
    if len(name) > max_name_len:
        msg = ("Data information named '{0}' is too long (max {1} characters.)"
            .format(name, max_name_len))
        raise ValueError(msg)
    encoded_name = name if value <= 1 else name + '\x00' + str(value)
    if len(encoded_name) > max_name_len:
        msg = (
            "Data information named '{0}' is too long (need to be less than {1} characters when storing more than one value for a given data information."
            .format(name, max_name_len - (len(str(value)) + 1)))
        raise ValueError(msg)
    return encoded_name.ljust(max_name_len, '\x00').encode('latin1')


def tidy_eggs_list(eggs_list):
    """Tidy the given eggs list
    """
    tmp = []
    for line in eggs_list:
        line = line.lstrip().rstrip()
        line = line.replace("'", '')
        line = line.replace(',', '')
        if line.endswith('site-packages'):
            continue
        tmp.append(line)
    return tmp


def read_td_job(job_id, engine, index_col=None, parse_dates=None):
    """Read Treasure Data job result into a DataFrame.

    Returns a DataFrame corresponding to the result set of the job.
    This method waits for job completion if the specified job is still running.
    Optionally provide an index_col parameter to use one of the columns as
    the index, otherwise default integer index will be used.

    Parameters
    ----------
    job_id : integer
        Job ID.
    engine : QueryEngine
        Handler returned by create_engine.
    index_col : string, optional
        Column name to use as index for the returned DataFrame object.
    parse_dates : list or dict, optional
        - List of column names to parse as dates
        - Dict of {column_name: format string} where format string is strftime
          compatible in case of parsing string times or is one of (D, s, ns, ms, us)
          in case of parsing integer timestamps

    Returns
    -------
    DataFrame
    """
    job = engine.connection.client.job(job_id)
    r = engine.get_result(job, wait=True)
    return r.to_dataframe(index_col=index_col, parse_dates=parse_dates)


def check_tag_for_hint(hint, tag_value):
    """return true if hint in tag value"""
    if hint.lower() in tag_value.lower():
        return True
    return False


@classmethod
def get_ad_service_config_interface_for_provider(cls, provider_name):
    """
        Staticmethod, returns the config interface for a given ad
        service provider name

        @param provider_name: str, one of enum
            parselmouth.constants.ParselmouthProviders
        @return: child(parselmouth.config.ParselmouthConfig)
        """
    config_interface = cls.ProviderConfigInterfaceMap.get(provider_name)
    if not config_interface:
        raise ValueError(
            'There is no config interface defined for provider: %s' %
            provider_name)
    return config_interface


def _plural(num):
    """Return 's' if plural.
    """
    if num == 1:
        s = ''
    else:
        s = 's'
    return s


def parse_proxy(proxy_str):
    """Parses proxy address user:pass@host:port into a dict suitable for httplib2"""
    proxy_dict = {}
    if proxy_str is None:
        return
    if '@' in proxy_str:
        user_pass, host_port = proxy_str.split('@')
    else:
        user_pass, host_port = '', proxy_str
    if ':' in host_port:
        host, port = host_port.split(':')
        proxy_dict['proxy_host'], proxy_dict['proxy_port'] = host, int(port)
    if ':' in user_pass:
        proxy_dict['proxy_user'], proxy_dict['proxy_pass'] = user_pass.split(
            ':')
    return proxy_dict


def list_applied_schema_arns(DirectoryArn=None, NextToken=None, MaxResults=None
    ):
    """
    Lists schemas applied to a directory.
    See also: AWS API Documentation

    :example: response = client.list_applied_schema_arns(
        DirectoryArn='string',
        NextToken='string',
        MaxResults=123
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The ARN of the directory you are listing.

    :type NextToken: string
    :param NextToken: The pagination token.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to retrieve.

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

    :returns:
    (string) --

    """
    pass


def p_declaration_1(t):
    """declaration : type_specifier ID"""
    t[1].id = t[2]
    t[0] = t[1]


def check_for_dev_uniqueness(builders):
    """
    Check that no device appears in more than one of the given list of
    builders.

    :param builders: a list of :class:`swift.common.ring.builder.RingBuilder`
        instances
    :raises ValueError: if the same device is found in more than one builder
    """
    builder2devs = []
    for i, builder in enumerate(builders):
        dev_set = set()
        for dev in builder._iter_devs():
            ip, port, device = dev['ip'], dev['port'], dev['device']
            for j, (other_builder, devs) in enumerate(builder2devs):
                if (ip, port, device) in devs:
                    raise ValueError(
                        'Duplicate ip/port/device combination %s/%s/%s found in builders at indexes %s and %s'
                         % (ip, port, device, j, i))
            dev_set.add((ip, port, device))
        builder2devs.append((builder, dev_set))


def add_tags_to_resource(ResourceId=None, Tags=None):
    """
    Adds or overwrites one or more tags for the specified directory. Each directory can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique to each resource.
    See also: AWS API Documentation

    :example: response = client.add_tags_to_resource(
        ResourceId='string',
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type ResourceId: string
    :param ResourceId: [REQUIRED]
            Identifier (ID) for the directory to which to add the tag.

    :type Tags: list
    :param Tags: [REQUIRED]
            The tags to be assigned to the directory.
            (dict) --Metadata assigned to a directory consisting of a key-value pair.
            Key (string) -- [REQUIRED]Required name of the tag. The string value can be Unicode characters and cannot be prefixed with 'aws:'. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').
            Value (string) -- [REQUIRED]The optional value of the tag. The string value can be Unicode characters. The string can contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


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

    The ".dev0" means dirty.

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


@staticmethod
def _has_trips(data):
    """
        Returns True if the data contains trips
        :param dict data: The response data as provided by self.__request
        :return bool:
        """
    return len(data.get('payload', {}).get('data', {}).get('trips', [])) > 0


def data_from_json(js, manager):
    """Deserialize a Javascript date."""
    return js


@staticmethod
def max_overlap_pair(skylines):
    """
        Find a pair of skylines with maximum overlap.

        Parameters
        ----------
        skylines: list
            A list of `SkyLine` instances.

        Returns
        -------
        max_pair: tuple
            Pair of `SkyLine` objects with max overlap
            among given *skylines*. If no overlap found,
            return `None`. These are *not* copies.

        """
    max_pair = None
    max_overlap_area = 0.0
    for i in range(len(skylines) - 1):
        curr_s = skylines[i]
        next_s, i_area = curr_s.find_max_overlap(skylines[i + 1:])
        if i_area > max_overlap_area:
            max_overlap_area = i_area
            max_pair = curr_s, next_s
    return max_pair


def mergeBaseline(ant1, ant2, shift=16):
    """
    Merge two stand ID numbers into a single baseline using the specified bit
    shift size.
    """
    return ant1 << shift | ant2


@staticmethod
def format_sizeof(num, suffix='', divisor=1000):
    """
        Formats a number (greater than unity) with SI Order of Magnitude
        prefixes.

        Parameters
        ----------
        num  : float
            Number ( >= 1) to format.
        suffix  : str, optional
            Post-postfix [default: ''].
        divisor  : float, optionl
            Divisor between prefixes [default: 1000].

        Returns
        -------
        out  : str
            Number with Order of Magnitude SI unit postfix.
        """
    for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 999.5:
            if abs(num) < 99.95:
                if abs(num) < 9.995:
                    return '{0:1.2f}'.format(num) + unit + suffix
                return '{0:2.1f}'.format(num) + unit + suffix
            return '{0:3.0f}'.format(num) + unit + suffix
        num /= divisor
    return '{0:3.1f}Y'.format(num) + suffix


def parse_gerber_number(strnumber, frac_digits):
    """
    Parse a single number of Gerber coordinates.

    :param strnumber: String containing a number in decimal digits
    from a coordinate data block, possibly with a leading sign.
    :type strnumber: str
    :param frac_digits: Number of digits used for the fractional
    part of the number
    :type frac_digits: int
    :return: The number in floating point.
    :rtype: float
    """
    return int(strnumber) * 10 ** -frac_digits


@classmethod
def fokker_planck(cls, epsilon=1.0, n_eigenpairs=10, **kwargs
    ) ->'DiffusionMaps':
    """Instantiate new model to approximate Fokker-Planck operator.

        Returns
        -------
        DiffusionMaps
            new instance
        """
    return cls(epsilon=epsilon, n_eigenpairs=n_eigenpairs, is_stochastic=
        True, alpha=0.5, **kwargs)


@classmethod
def _alias_uid(cls, alias=None):
    """Return an unique uid string.

        if alias is given, return it as a String
        """
    if alias is None:
        cls._alias += 1
        alias = cls._alias
    return str(alias)


def log2floor(n):
    """
    Returns the exact value of floor(log2(n)).
    No floating point calculations are used.
    Requires positive integer type.
    """
    assert n > 0
    return n.bit_length() - 1


@staticmethod
def get_length(x):
    """Return total packet length."""
    datalen = x._.data.length
    return datalen + 32


def allocate_mid(mids):
    """
    Allocate a MID which has not been used yet.
    """
    i = 0
    while True:
        mid = str(i)
        if mid not in mids:
            mids.add(mid)
            return mid
        i += 1


def commit(transactionid):
    """STOMP commit command.

    Do whatever is required to make the series of actions
    permanent for this transactionid.

    transactionid:
        This is the id that all actions in this transaction.

    """
    return 'COMMIT\ntransaction: %s\n\n\x00\n' % transactionid


def restore_signal(uni_signal, channels):
    """ Uniformize a signal between 0.0 and 1.0
        Requires every channel to have bounds, or be discretized.
    """
    signal = {}
    for c in channels:
        factor = 1.0
        if c.bounds[0] != c.bounds[1]:
            assert c.bounds[0] < c.bounds[1]
            factor = c.bounds[1] - c.bounds[0]
        signal[c.name] = uni_signal[c.name] * factor + c.bounds[0]
    return signal


@staticmethod
def p_compu_method_conversion_type(p):
    """compu_method_conversion_type : TAB_INTP
                             | TAB_NOINTP
                             | TAB_VERB
                             | RAT_FUNC
                             | FORM
                             | IDENTICAL
                             | LINEAR"""
    p[0] = p[1]


def multiply_two_numbers(x, y):
    """Multiply two numbers.
    """
    return x * y


def create_network_interface(SubnetId=None, Description=None,
    PrivateIpAddress=None, Groups=None, PrivateIpAddresses=None,
    SecondaryPrivateIpAddressCount=None, Ipv6Addresses=None,
    Ipv6AddressCount=None, DryRun=None):
    """
    Creates a network interface in the specified subnet.
    For more information about network interfaces, see Elastic Network Interfaces in the Amazon Virtual Private Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example creates a network interface for the specified subnet.
    Expected Output:

    :example: response = client.create_network_interface(
        SubnetId='string',
        Description='string',
        PrivateIpAddress='string',
        Groups=[
            'string',
        ],
        PrivateIpAddresses=[
            {
                'PrivateIpAddress': 'string',
                'Primary': True|False
            },
        ],
        SecondaryPrivateIpAddressCount=123,
        Ipv6Addresses=[
            {
                'Ipv6Address': 'string'
            },
        ],
        Ipv6AddressCount=123,
        DryRun=True|False
    )

    :type SubnetId: string
    :param SubnetId: [REQUIRED]
            The ID of the subnet to associate with the network interface.

    :type Description: string
    :param Description: A description for the network interface.

    :type PrivateIpAddress: string
    :param PrivateIpAddress: The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary).

    :type Groups: list
    :param Groups: The IDs of one or more security groups.
            (string) --

    :type PrivateIpAddresses: list
    :param PrivateIpAddresses: One or more private IPv4 addresses.
            (dict) --Describes a secondary private IPv4 address for a network interface.
            PrivateIpAddress (string) -- [REQUIRED]The private IPv4 addresses.
            Primary (boolean) --Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary.

    :type SecondaryPrivateIpAddressCount: integer
    :param SecondaryPrivateIpAddressCount: The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses .
            The number of IP addresses you can assign to a network interface varies by instance type. For more information, see IP Addresses Per ENI Per Instance Type in the Amazon Virtual Private Cloud User Guide .

    :type Ipv6Addresses: list
    :param Ipv6Addresses: One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses.
            (dict) --Describes an IPv6 address.
            Ipv6Address (string) --The IPv6 address.

    :type Ipv6AddressCount: integer
    :param Ipv6AddressCount: The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting.

    :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 .

    :rtype: dict
    :return: {
        'NetworkInterface': {
            'NetworkInterfaceId': 'string',
            'SubnetId': 'string',
            'VpcId': 'string',
            'AvailabilityZone': 'string',
            'Description': 'string',
            'OwnerId': 'string',
            'RequesterId': 'string',
            'RequesterManaged': True|False,
            'Status': 'available'|'attaching'|'in-use'|'detaching',
            'MacAddress': 'string',
            'PrivateIpAddress': 'string',
            'PrivateDnsName': 'string',
            'SourceDestCheck': True|False,
            'Groups': [
                {
                    'GroupName': 'string',
                    'GroupId': 'string'
                },
            ],
            'Attachment': {
                'AttachmentId': 'string',
                'InstanceId': 'string',
                'InstanceOwnerId': 'string',
                'DeviceIndex': 123,
                'Status': 'attaching'|'attached'|'detaching'|'detached',
                'AttachTime': datetime(2015, 1, 1),
                'DeleteOnTermination': True|False
            },
            'Association': {
                'PublicIp': 'string',
                'PublicDnsName': 'string',
                'IpOwnerId': 'string',
                'AllocationId': 'string',
                'AssociationId': 'string'
            },
            'TagSet': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ],
            'PrivateIpAddresses': [
                {
                    'PrivateIpAddress': 'string',
                    'PrivateDnsName': 'string',
                    'Primary': True|False,
                    'Association': {
                        'PublicIp': 'string',
                        'PublicDnsName': 'string',
                        'IpOwnerId': 'string',
                        'AllocationId': 'string',
                        'AssociationId': 'string'
                    }
                },
            ],
            'Ipv6Addresses': [
                {
                    'Ipv6Address': 'string'
                },
            ],
            'InterfaceType': 'interface'|'natGateway'
        }
    }

    """
    pass


def get_model(cls):
    """Return the router's model or None."""
    return cls.router.model if cls.router else None


def get_homopol_run(var):
    """
    Return the largest contiguous homopolymer run of the variant allele,
    or None if it isn't present in the VCF.
    """
    return var.INFO.get('HRun')


def _merge_dicts_of_sets(current, new):
    """Merge the elements of `new` into `current` (via set union).

    Both `new` and `current` must be `dict`s whose values are `set`s.
    This modifies `current`.

    """
    for key in new:
        if key in current:
            current[key] |= new[key]
        else:
            current[key] = new[key]


def xsqlofa(values, table, cols, addcol=[], sameval=[]):
    """ returns operation and values for cursor.execute """
    cols = cols.split(',')
    psql = 'insert into ' + table + '('
    sql = ''
    params = []
    for i in cols:
        psql = psql + i.strip() + ','
    if len(addcol) > 0:
        for i in range(len(addcol)):
            psql = psql + addcol[i] + ','
    psql = psql[0:-1]
    psql = psql + ') values ('
    for j in range(len(cols)):
        x = '%s'
        sql = sql + '"' + x + '"' + ','
    sql = psql + sql[0:-1] + ')'
    for i in values:
        for j in range(len(cols)):
            if j < len(i):
                x = str(i[j])
            else:
                x = ''
            params.append(x)
        if len(addcol) > 0:
            for i in range(len(addcol)):
                params.append(sameval[i])
    return sql, params


def select_link_viewer(NODE_OT_select=None, NODE_OT_link_viewer=None):
    """Select node and link it to a viewer node

    :param NODE_OT_select: Select, Select the node under the cursor
    :param NODE_OT_link_viewer: Link to Viewer Node, Link to viewer node
    """
    pass


def mdev_uuid2name(mdev_uuid):
    """Convert an mdev uuid (of the form 8-4-4-4-12) to a name (of the form
    mdev_<uuid_with_underscores>).
    """
    return 'mdev_' + mdev_uuid.replace('-', '_')


def get_yad_version():
    """Extract version number from yad, if it is available."""
    try:
        import sh
        from sh import yad
        from io import StringIO
        buffer = StringIO()
        try:
            yad('--version', _out=buffer)
        except sh.ErrorReturnCode_252:
            pass
        return buffer.getvalue()
    except Exception:
        return 'None'


def GetExecutingScriptHash():
    """
    Get the hash of the script ( smart contract ) which is currently being executed

    - Note: This method is implemented inside the Neo Virtual Machine.

    :return: the hash of the script ( smart contract ) which is currently being executed
    :rtype: bytearray
    """
    pass


def validate_proto_enum(value_name, value, enum_name, enum, subset=None):
    """Helper function to validate an enum against the proto enum wrapper."""
    enum_value = None
    if value not in enum.keys() and value not in enum.values():
        raise Exception(
            '{name}={value} not in {enum_name} enum! Please try any of {options}.'
            .format(name=value_name, value=str(value), enum_name=enum_name,
            options=str(enum.keys())))
    if value in enum.keys():
        enum_value = enum.Value(value)
    else:
        enum_value = value
    if subset:
        resolved_subset = []
        for element in subset:
            if element in enum.keys():
                resolved_subset.append(enum.Value(element))
            elif element in enum.values():
                resolved_subset.append(element)
            else:
                raise Exception('Subset element {element} not in {enum_name}!'
                    .format(element=element, enum_name=enum_name))
        if enum_value not in resolved_subset:
            raise Exception('{name}={value} not in subset {subset}!'.format
                (name=value_name, value=enum_value, subset=resolved_subset))
    return enum_value


@classmethod
def from_port_request(cls, context, port_uuid, port_resource_request):
    """Init the group from the resource request of a neutron port

        :param context: the request context
        :param port_uuid: the port requesting the resources
        :param port_resource_request: the resource_request attribute of the
                                      neutron port
        For example:

            port_resource_request = {
                "resources": {
                    "NET_BW_IGR_KILOBIT_PER_SEC": 1000,
                    "NET_BW_EGR_KILOBIT_PER_SEC": 1000},
                "required": ["CUSTOM_PHYSNET_2",
                             "CUSTOM_VNIC_TYPE_NORMAL"]
            }
        """
    obj = cls(context=context, use_same_provider=True, resources=
        port_resource_request['resources'], required_traits=set(
        port_resource_request.get('required', [])), requester_id=port_uuid)
    obj.obj_set_defaults()
    return obj


@staticmethod
def concat_url(endpoint, url):
    """Concatenate endpoint and final URL.

        E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
        "http://keystone/v2.0/tokens".

        :param endpoint: the base URL
        :param url: the final URL
        """
    return '%s/%s' % (endpoint.rstrip('/'), url.strip('/'))


def Crop(*data, **kwargs):
    """

    .. note:: `Crop` is deprecated. Use `slice` instead.

    Crop the 2nd and 3rd dim of input data, with the corresponding size of h_w or
    with width and height of the second input symbol, i.e., with one input, we need h_w to
    specify the crop height and width, otherwise the second input symbol's size will be used

    Defined in src/operator/crop.cc:L50
    This function support variable length of positional input.

    Parameters
    ----------
    data : Symbol or Symbol[]
        Tensor or List of Tensors, the second input will be used as crop_like shape reference
    offset : Shape(tuple), optional, default=[0,0]
        crop offset coordinate: (y, x)
    h_w : Shape(tuple), optional, default=[0,0]
        crop height and width: (h, w)
    center_crop : boolean, optional, default=0
        If set to true, then it will use be the center_crop,or it will crop using the shape of crop_like

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

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


@staticmethod
def p_display_identifier(p):
    """display_identifier : DISPLAY_IDENTIFIER IDENT"""
    p[0] = p[2]


def normalize_ext(ext):
    """
    Add a dot to normalize extension: .css not css
    """
    if ext[0] != '.':
        ext = '.' + ext
    return ext


def ec2_security_group_test_id(ec2_security_group):
    """A getter fn for test ids for EC2 security groups"""
    return '{0[GroupId]} {0[GroupName]}'.format(ec2_security_group)


@classmethod
def on_after_tests(cls):
    """
        Run after run the tests for the element
        """
    pass


@classmethod
def sort(cls, columns, by=[], reverse=False):
    """
        Cubes are assumed to be sorted by default.
        """
    return columns


def parse_host_port(address, default_port=None):
    """
    Interpret a string as a host:port pair.
    An IPv6 address MUST be escaped if accompanied by a port,
    because otherwise ambiguity ensues: 2001:db8:85a3::8a2e:370:7334
    means both [2001:db8:85a3::8a2e:370:7334] and
    [2001:db8:85a3::8a2e:370]:7334.

    >>> parse_host_port('server01:80')
    ('server01', 80)
    >>> parse_host_port('server01')
    ('server01', None)
    >>> parse_host_port('server01', default_port=1234)
    ('server01', 1234)
    >>> parse_host_port('[::1]:80')
    ('::1', 80)
    >>> parse_host_port('[::1]')
    ('::1', None)
    >>> parse_host_port('[::1]', default_port=1234)
    ('::1', 1234)
    >>> parse_host_port('2001:db8:85a3::8a2e:370:7334', default_port=1234)
    ('2001:db8:85a3::8a2e:370:7334', 1234)

    """
    if address[0] == '[':
        _host, _port = address[1:].split(']')
        host = _host
        if ':' in _port:
            port = _port.split(':')[1]
        else:
            port = default_port
    elif address.count(':') == 1:
        host, port = address.split(':')
    else:
        host = address
        port = default_port
    return host, None if port is None else int(port)


def format(text, *args, **kw):
    """
    Format a string using the string formatting operator and/or :meth:`str.format()`.

    :param text: The text to format (a string).
    :param args: Any positional arguments are interpolated into the text using
                 the string formatting operator (``%``). If no positional
                 arguments are given no interpolation is done.
    :param kw: Any keyword arguments are interpolated into the text using the
               :meth:`str.format()` function. If no keyword arguments are given
               no interpolation is done.
    :returns: The text with any positional and/or keyword arguments
              interpolated (a string).

    The implementation of this function is so trivial that it seems silly to
    even bother writing and documenting it. Justifying this requires some
    context :-).

    **Why format() instead of the string formatting operator?**

    For really simple string interpolation Python's string formatting operator
    is ideal, but it does have some strange quirks:

    - When you switch from interpolating a single value to interpolating
      multiple values you have to wrap them in tuple syntax. Because
      :func:`format()` takes a `variable number of arguments`_ it always
      receives a tuple (which saves me a context switch :-). Here's an
      example:

      >>> from humanfriendly.text import format
      >>> # The string formatting operator.
      >>> print('the magic number is %s' % 42)
      the magic number is 42
      >>> print('the magic numbers are %s and %s' % (12, 42))
      the magic numbers are 12 and 42
      >>> # The format() function.
      >>> print(format('the magic number is %s', 42))
      the magic number is 42
      >>> print(format('the magic numbers are %s and %s', 12, 42))
      the magic numbers are 12 and 42

    - When you interpolate a single value and someone accidentally passes in a
      tuple your code raises a :exc:`~exceptions.TypeError`. Because
      :func:`format()` takes a `variable number of arguments`_ it always
      receives a tuple so this can never happen. Here's an example:

      >>> # How expecting to interpolate a single value can fail.
      >>> value = (12, 42)
      >>> print('the magic value is %s' % value)
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      TypeError: not all arguments converted during string formatting
      >>> # The following line works as intended, no surprises here!
      >>> print(format('the magic value is %s', value))
      the magic value is (12, 42)

    **Why format() instead of the str.format() method?**

    When you're doing complex string interpolation the :meth:`str.format()`
    function results in more readable code, however I frequently find myself
    adding parentheses to force evaluation order. The :func:`format()` function
    avoids this because of the relative priority between the comma and dot
    operators. Here's an example:

    >>> "{adjective} example" + " " + "(can't think of anything less {adjective})".format(adjective='silly')
    "{adjective} example (can't think of anything less silly)"
    >>> ("{adjective} example" + " " + "(can't think of anything less {adjective})").format(adjective='silly')
    "silly example (can't think of anything less silly)"
    >>> format("{adjective} example" + " " + "(can't think of anything less {adjective})", adjective='silly')
    "silly example (can't think of anything less silly)"

    The :func:`compact()` and :func:`dedent()` functions are wrappers that
    combine :func:`format()` with whitespace manipulation to make it easy to
    write nice to read Python code.

    .. _variable number of arguments: https://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists
    """
    if args:
        text %= args
    if kw:
        text = text.format(**kw)
    return text


def withdraw():
    """
    Create a withdrawal
    """
    raise NotImplemented


def clipboard_paste():
    """Pastes nodes from the clipboard to the active node tree

    """
    pass


def fix_slice(slice_, shape):
    """Return a normalized slice.

    This function returns a slice so that it has the same length of `shape`,
    and no negative indexes, if possible.

    This is based on this document:

        http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

    """
    if not isinstance(slice_, tuple):
        slice_ = slice_,
    expand = len(shape) - len(slice_)
    out = []
    for s in slice_:
        if s is Ellipsis:
            out.extend((slice(None),) * (expand + 1))
            expand = 0
        else:
            out.append(s)
    slice_ = tuple(out) + (slice(None),) * expand
    out = []
    for s, n in zip(slice_, shape):
        if isinstance(s, int):
            if s < 0:
                s += n
            out.append(s)
        else:
            k = s.step or 1
            i = s.start
            if i is None:
                i = 0
            elif i < 0:
                i += n
            j = s.stop
            if j is None or j > n:
                j = n
            elif j < 0:
                j += n
            out.append(slice(i, j, k))
    return tuple(out)


def literal_str_representer(dumper, data):
    """Used to create yaml block style indicator"""
    return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')


def edit(enabled=None):
    """Modifies an existing conditional modifier.

        None values leave the respective parameter unchanged.
        """


def abort_if_false(ctx, param, value):
    """Abort command is value is False."""
    if not value:
        ctx.abort()


def ind2sub(array_shape, ind):
    """
    Equivalent to the same-named function in Matlab (Except that Matlab is Fortran-styled indexing)
    :param array_shape:
    :param rows:
    :param cols:
    :return:
    """
    ind[ind < 0] = -1
    ind[ind >= array_shape[0] * array_shape[1]] = -1
    rows = ind.astype('int') // array_shape[1]
    cols = ind % array_shape[1]
    return rows, cols


@classmethod
def _decref(cls, store):
    """ Record that a client is finished using the specified store. """
    try:
        val = cls._stores[store]
        if val == 1:
            cls._close(store)
            del cls._stores[store]
        else:
            cls._stores[store] = val - 1
    except KeyError:
        pass


def get_action_text(action):
    """
    Get a text respresentation of the Action
    :param action: Model, Action model instance
    :returns: String, text description of an Activity Action
    """
    context = {'actor': action.actor, 'verb': action.verb, 'action': action
        .action, 'target': action.target, 'timestamp': action.time_ago}
    if action.target:
        return '{actor} {verb} {action} to {target} {timestamp}'.format(**
            context)
    if action.action:
        return '{actor} {verb} {action} {timestamp}'.format(**context)
    return '{actor} {verb} {timestamp}'.format(**context)


def Haider_Levenspiel(Re):
    """Calculates drag coefficient of a smooth sphere using the method in
    [1]_ as described in [2]_.

    .. math::
        C_D=\\frac{24}{Re}(1+0.1806Re^{0.6459})+\\left(\\frac{0.4251}{1
        +\\frac{6880.95}{Re}}\\right)

    Parameters
    ----------
    Re : float
        Particle Reynolds number of the sphere using the surrounding fluid
        density and viscosity, [-]

    Returns
    -------
    Cd : float
        Drag coefficient [-]

    Notes
    -----
    Range is Re <= 2E5
    An improved version of this correlation is in Brown and Lawler.

    Examples
    --------
    >>> Haider_Levenspiel(200.)
    0.7959551680251666

    References
    ----------
    .. [1] Haider, A., and O. Levenspiel. "Drag Coefficient and Terminal
       Velocity of Spherical and Nonspherical Particles." Powder Technology
       58, no. 1 (May 1989): 63-70. doi:10.1016/0032-5910(89)80008-7.
    .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz
       Ahmadi. "Development of Empirical Models with High Accuracy for
       Estimation of Drag Coefficient of Flow around a Smooth Sphere: An
       Evolutionary Approach." Powder Technology 257 (May 2014): 11-19.
       doi:10.1016/j.powtec.2014.02.045.
    """
    return 24.0 / Re * (1 + 0.1806 * Re ** 0.6459) + 0.4251 / (1 + 6880.95 / Re
        )


def copy_db_cluster_parameter_group(SourceDBClusterParameterGroupIdentifier
    =None, TargetDBClusterParameterGroupIdentifier=None,
    TargetDBClusterParameterGroupDescription=None, Tags=None):
    """
    Copies the specified DB cluster parameter group.
    See also: AWS API Documentation

    Examples
    This example copies a DB cluster parameter group.
    Expected Output:

    :example: response = client.copy_db_cluster_parameter_group(
        SourceDBClusterParameterGroupIdentifier='string',
        TargetDBClusterParameterGroupIdentifier='string',
        TargetDBClusterParameterGroupDescription='string',
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type SourceDBClusterParameterGroupIdentifier: string
    :param SourceDBClusterParameterGroupIdentifier: [REQUIRED]
            The identifier or Amazon Resource Name (ARN) for the source DB cluster parameter group. For information about creating an ARN, see Constructing an RDS Amazon Resource Name (ARN) .
            Constraints:
            Must specify a valid DB cluster parameter group.
            If the source DB cluster parameter group is in the same region as the copy, specify a valid DB parameter group identifier, for example my-db-cluster-param-group , or a valid ARN.
            If the source DB parameter group is in a different region than the copy, specify a valid DB cluster parameter group ARN, for example arn:aws:rds:us-east-1:123456789012:cluster-pg:custom-cluster-group1 .

    :type TargetDBClusterParameterGroupIdentifier: string
    :param TargetDBClusterParameterGroupIdentifier: [REQUIRED]
            The identifier for the copied DB cluster parameter group.
            Constraints:
            Cannot be null, empty, or blank
            Must contain from 1 to 255 alphanumeric characters or hyphens
            First character must be a letter
            Cannot end with a hyphen or contain two consecutive hyphens
            Example: my-cluster-param-group1

    :type TargetDBClusterParameterGroupDescription: string
    :param TargetDBClusterParameterGroupDescription: [REQUIRED]
            A description for the copied DB cluster parameter group.

    :type Tags: list
    :param Tags: A list of tags.
            (dict) --Metadata assigned to an Amazon RDS resource consisting of a key-value pair.
            Key (string) --A key is the required name of the tag. The string value can be from 1 to 128 Unicode characters in length and cannot be prefixed with 'aws:' or 'rds:'. The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').
            Value (string) --A value is the optional value of the tag. The string value can be from 1 to 256 Unicode characters in length and cannot be prefixed with 'aws:' or 'rds:'. The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').

    :rtype: dict
    :return: {
        'DBClusterParameterGroup': {
            'DBClusterParameterGroupName': 'string',
            'DBParameterGroupFamily': 'string',
            'Description': 'string',
            'DBClusterParameterGroupArn': 'string'
        }
    }

    """
    pass


@classmethod
def all_stop(cls):
    """ Stop every task started within this registry

		:return: None
		"""
    for task_tag in cls.registry_storage().tags():
        cls.stop_task(task_tag)


def registerProducer(producer, streaming):
    """A producer is being hooked up to this consumer. The consumer only
        has to handle a single producer. It should send .pauseProducing and
        .resumeProducing messages to the producer when it wants to stop or
        resume the flow of data. 'streaming' will be set to True because the
        producer is always a PushProducer.
        """


def group_trans_by_budget_line(trans):
    """
    Group transactions by the budget line.

    :param trans: The transactions to group.
    :returns: A dictionary mapping budget line to a list of transactions.
    """
    transgrp = {}
    for t in trans:
        transgrp.setdefault(t.budget, []).append(t)
    return transgrp


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

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

        :returns: a kwargs dict to pass to the initializer
        """
    import piff
    kwargs = config_output.copy()
    if 'stats' in config_output:
        stats = piff.Stats.process(kwargs.pop('stats'), logger=logger)
        kwargs['stats_list'] = stats
    return kwargs


def migrate_network_fields(apps, schema_editor):
    """
    Migrate new Network fields.
    """
    Network = apps.get_model('nsot', 'Network')
    Network_temp = apps.get_model('nsot', 'Network_temp')
    for net in Network.objects.iterator():
        net_tmp = Network_temp.objects.create(network_address=net.
            network_address, broadcast_address=net.broadcast_address,
            prefix_length=net.prefix_length, ip_version=net.ip_version,
            is_ip=net.is_ip, id=net.resource_ptr_id, parent_id=net.
            parent_id, _attributes_cache=net._attributes, site=net.site)


@classmethod
def get_service_name(cls):
    """returns the canonical name of the service (which is its first
        alias)"""
    return cls.get_service_aliases()[0]


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


@classmethod
def __class_attribute(cls, data, attribute, cl, *args, **kwargs):
    """Return the attribute from the JSON data and instantiate the class.

        "param dict data: dictionary used to put together the model or None
        "param str attribute: key of the attribute
        :param class cl: class that will be instantiated
        :returns: instantiated class or None
        :rtype: object or None
        """
    value = cls._get_attribute(data, attribute)
    if value:
        return cl(value, *args, **kwargs)
    return value


def delfpl(jobj, fpl):
    """
        y = {'c': {'b': 200}}
        delfpl(y,['c','b'])
        >>>{'c': {}}
    """
    this = jobj
    for i in range(0, fpl.__len__() - 1):
        key = fpl[i]
        this = this.__getitem__(key)
    this.__delitem__(fpl[-1])
    return jobj


def call_all_update_funs(update_funs, values_dict):
    """Call all the functions."""
    for f in update_funs:
        f(values_dict)


def decode_validate_token(token, sv, api):
    """This tries to be a general function to decode and validade any token.
    Receives a token, a SignerVerifier and an API.
    """
    if not token:
        api.abort(400, 'Error: No token received!')
    try:
        decoded = sv.decode(token)
    except sv.ExpiredSignatureError:
        api.abort(400, 'Error: Expired token!')
    except sv.DecodeError:
        api.abort(400, 'Error: Token decode error!')
    except:
        raise
    for fields in ['username', 'type', 'exp']:
        if fields not in decoded.keys():
            api.abort(400, 'Error: Malformed token! No: %s' % fields)
    return decoded


def multires_reshape(modifier: str=''):
    """Copy vertex coordinates from other object

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    """
    pass


def get_urlpath(cls):
    """Return the urlname."""
    return cls.urlname


@classmethod
def _unescape_dict_keys(cls, data: dict) ->dict:
    """Recursively unescape all keys in a dict."""
    ret = {}
    for key, value in data.items():
        key = cls._unescape_key(key)
        if isinstance(value, dict):
            value = cls._unescape_dict_keys(value)
        ret[key] = value
    return ret


def DeactivateInstanceDisks(r, instance):
    """
    Deactivates an instance's disks.

    @type instance: string
    @param instance: Instance name
    @return: job id
    """
    return r.request('put', '/2/instances/%s/deactivate-disks' % instance)


def _create_network(list_consecutive_links_up, outlet):
    """
    This function reads a CSV file containing the hydrological connectivity of a given network.
    It can only read CSV file containing the headers 'WaterBody' and 'NeighbourUp'.

    :param list_consecutive_links_up: list of tuples for each couple of connected WaterBodies
    :type list_consecutive_links_up: list
    :param outlet: name of the outlet WaterBody
    :type outlet: list
    :return: a dictionary with key: waterbody, val: tup(code of node downstream, code of node upstream)
    :rtype: dict
    """
    list_nodes = list()
    dict_consecutive_links_down = dict()
    dict_link_to_node_down = dict()
    dict_link_and_surrounding_nodes = dict()
    future_rivers = list()
    for tup in list_consecutive_links_up:
        dict_consecutive_links_down[tup[1]] = tup[0]
    river_outlet = [outlet]
    node_code = 0
    dict_link_to_node_down[outlet] = '%04d' % node_code
    list_nodes.append('%04d' % node_code)
    rivers = river_outlet[:]
    while rivers:
        for river in rivers:
            node_code += 1
            list_nodes.append('%04d' % node_code)
            dict_link_and_surrounding_nodes[river] = dict_link_to_node_down[
                river], '%04d' % node_code
            for key in dict_consecutive_links_down:
                if dict_consecutive_links_down[key] == river:
                    dict_link_to_node_down[key] = '%04d' % node_code
                    future_rivers.append(key)
        del rivers[:]
        rivers = future_rivers[:]
        del future_rivers[:]
    return dict_link_and_surrounding_nodes, list_nodes


def min_max_normalize(img):
    """Centre and normalize a given array.

    Parameters
    ----------
    img : numpy.ndarray
        Input image

    """
    min_img = img.min()
    max_img = img.max()
    return (img - min_img) / (max_img - min_img)


def ann(dic, data):
    """
    Fourier Analysis by Neural Net
    """
    raise NotImplementedError


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


@staticmethod
def deriv(n, sig, alp, dg, dh1, dh2, dh3, _bin, nu):
    """The derivatives of the operator function at x=0"""
    dh1[0] = 0.5 * 1.0j * sig
    exp1 = -0.5
    dh2[0] = alp
    exp2 = -1
    dh3[0] = -2 * nu
    exp3 = -1
    for i in range(1, n):
        dh1[i] = dh1[i - 1] * exp1
        exp1 -= 1
        dh2[i] = dh2[i - 1] * exp2
        exp2 -= 1
        dh3[i] = -nu * dh3[i - 1] * exp3
        exp3 -= 1
    dg[0] = 1
    dg[1] = dh1[0] + dh2[0] + dh3[0]
    for i in range(1, n):
        dg[i + 1] = dh1[i] + dh2[i] + dh3[i]
        for j in range(i):
            dg[i + 1] += _bin[i, j] * (dh1[j] + dh2[j] + dh3[j]) * dg[i - j]
    return dg, dh1, dh2, dh3


def rev(node):
    """Obtain the revision number given a binary node.

        Raises ``error.LookupError`` if the node is not known.
        """


def normal_cfn(coefficient, friction):
    """Usage: Find normal force using coefficient and friction"""
    return friction / coefficient


def sql_between(query=None, values_list=None):
    """
    Transform the list in values_list to be used as a between statement of the SQL.
    Example:
        values_list = ['2018-01-01', '2018-02-02']
        query = 'select * from database where sql_between(' date', date_int)'

        "select * from database where date between '2018-01-01' and '2018-02-02')"

    :param query: Query header with the first part of the query
    :param values_list: list to be used in a between statement
    :return: query concatenated with values_list as a between statement
    """
    if values_list is None:
        return ''
    if len(values_list) != 2:
        raise Exception(
            'To use sql_between values_list must be of two positions')
    if not isinstance(values_list, list):
        values_list = [values_list]
    if isinstance(values_list[0], int) or isinstance(values_list[1], int):
        between_query = query + ' between ' + str(values_list[0]
            ) + ' and ' + str(values_list[1])
    else:
        between_query = query + " between '" + values_list[0
            ] + "' and '" + values_list[1] + "'"
    return between_query


def check_float(string):
    """
    Helper function for checking if a string can be converted to a float.

    :param string: string to be verified as a float
    :returns: True if the string can be converted to a float, False otherwise
    """
    try:
        float(string)
        return True
    except ValueError:
        return False


@staticmethod
def could_be_optimized():
    """Return answer if it is still possible to optimize that stage."""
    raise NotImplementedError


def filter_by_hardware_interface(ctrl_list, hardware_interface,
    match_substring=False):
    """
    Filter controller state list by controller hardware interface.

    @param ctrl_list: Controller state list
    @type ctrl_list: [controller_manager_msgs/ControllerState]
    @param hardware_interface: Controller hardware interface
    @type hardware_interface: str
    @param match_substring: Set to True to allow substring matching
    @type match_substring: bool
    @return: Controllers matching the specified hardware interface
    @rtype: [controller_manager_msgs/ControllerState]
    """
    list_out = []
    for ctrl in ctrl_list:
        for resource_set in ctrl.claimed_resources:
            if match_substring:
                if hardware_interface in resource_set.hardware_interface:
                    list_out.append(ctrl)
                    break
            elif resource_set.hardware_interface == hardware_interface:
                list_out.append(ctrl)
                break
    return list_out


def all_static_pos(datas):
    """
        Pasrse a sequence of strings containing information about static
        objects' position coordinates.

        Input:
        `datas`     # A sequence of strings in '{id}:{id}_Static;{x};{y};{z}',
                    # where x, y, z are integer values of static objects'
                    # coordinates. Example:
                    # [
                    #     "0:0_Static;100;200;300",
                    #     "1:1_Static;100;200;300",
                    # ]

        Output:
        A sequence of objects containing information about static objects'
        names and coordinates.
        """


def connectSSL(host, port, factory, contextFactory, timeout=30, bindAddress
    =None):
    """
        Connect a client Protocol to a remote SSL socket.

        @param host: a host name

        @param port: a port number

        @param factory: a L{twisted.internet.protocol.ClientFactory} instance

        @param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.

        @param timeout: number of seconds to wait before assuming the
                        connection has failed.

        @param bindAddress: a (host, port) tuple of local address to bind to,
                            or C{None}.

        @return: An object which provides L{IConnector}.
        """


def get_history():
    """Get console input history in list.
        """


def get_mpl_rcParams(mplobj, profile=None, usetex=False, fontfamily=
    'sans-serif', aspectratio=None):
    """Set matplotlib rcParams dictionary with custom plot profile settings.

    Parameters
    ----------
    mplobj : py:mod:`matplotlib` module instance
    profile : str, optional
        custom plot profile settings to use.
    usetex : bool, optional
    fontfamily : {'sans-serif', 'serif'}, optional
    aspectratio : float, optional

    Returns
    -------
    figkwargs : dict

    """
    figkwargs = {}
    if fontfamily not in ('sans-serif', 'serif'):
        fontfamily = 'sans-serif'
    mplobj.rcParams['font.family'] = fontfamily
    if usetex:
        mplobj.rcParams['text.usetex'] = True
        if fontfamily == 'sans-serif':
            mplobj.rcParams['font.sans-serif'] = ['Arial', 'Helvetica']
            mplobj.rcParams['text.latex.preamble'] = [
                '\\usepackage{sfmath,amsmath,amssymb,latexsym}']
        else:
            mplobj.rcParams['text.latex.preamble'] = [
                '\\usepackage{amsmath,amssymb,latexsym}']
    else:
        mplobj.rcParams['text.usetex'] = False
        if fontfamily == 'sans-serif':
            mplobj.rcParams['font.sans-serif'] = ['Arial', 'Helvetica']
    if profile == 'custom':
        figkwargs['xdim'] = figkwargs['ydim'] = 20
        figkwargs['cbar.label.fontsize'] = 40
        figkwargs['contour.label.fontsize'] = 44
        figkwargs['annotation.fontsize'] = 20
        figkwargs['marker.scale.factor'] = 2
        figkwargs['legend.marker.scale.factor'] = 0.5
        figkwargs['labelpad'] = 20
        figkwargs['title.fontsize'] = 52
        figkwargs['text.label.fontsize'] = 42
        figkwargs['tick.width'] = 5
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 3
        figkwargs['inset.axes.markersize'] = 15
        figkwargs['inset.axes.fontsize'] = 32
        figkwargs['inset.axes.labelsize'] = 36
        figkwargs['inset.axes.labelpad'] = 10
        figkwargs['inset.axes.tick.major.size'] = 10
        figkwargs['inset.axes.tick.minor.size'] = 6
        figkwargs['inset.axes.tick.width'] = 3
        mplobj.rcParams['font.family'] = 'serif'
        mplobj.rcParams['font.size'] = 48
        mplobj.rcParams['legend.fontsize'] = 46
        mplobj.rcParams['legend.labelspacing'] = 1
        mplobj.rcParams['axes.linewidth'] = 5.0
        mplobj.rcParams['lines.linewidth'] = 6.0
        mplobj.rcParams['lines.markersize'] = 25
        mplobj.rcParams['xtick.major.size'] = 20
        mplobj.rcParams['xtick.minor.size'] = 10
        mplobj.rcParams['xtick.major.width'] = 5
        mplobj.rcParams['xtick.minor.width'] = 5
        mplobj.rcParams['xtick.major.pad'] = 12
        mplobj.rcParams['xtick.minor.pad'] = 12
        mplobj.rcParams['ytick.major.size'] = 20
        mplobj.rcParams['ytick.minor.size'] = 10
        mplobj.rcParams['ytick.major.width'] = 5
        mplobj.rcParams['ytick.minor.width'] = 5
        mplobj.rcParams['ytick.major.pad'] = 12
        mplobj.rcParams['ytick.minor.pad'] = 12
    elif profile == 'ipynb-inline':
        figkwargs['xdim'] = figkwargs['ydim'] = 12
        figkwargs['cbar.label.fontsize'] = 14
        figkwargs['contour.label.fontsize'] = 20
        figkwargs['annotation.fontsize'] = 12
        figkwargs['tiny.annotation.fontsize'] = 8
        figkwargs['text.fontsize'] = 5
        figkwargs['tiny.text.fontsize'] = 3
        figkwargs['marker.scale.factor'] = 1
        figkwargs['labelpad'] = 5
        figkwargs['legend.marker.scale.factor'] = 1
        figkwargs['legend.fontsize'] = 20
        figkwargs['title.fontsize'] = 20
        figkwargs['dropshadow.offset.x'] = 3
        figkwargs['dropshadow.offset.y'] = -6
        figkwargs['text.label.fontsize'] = 20
        figkwargs['tick.major.size'] = 12
        figkwargs['tick.minor.size'] = 6
        figkwargs['tick.width'] = 2
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 1
        figkwargs['inset.axes.markersize'] = 8
        figkwargs['inset.axes.marker.scale.factor'] = 0.5
        figkwargs['inset.axes.fontsize'] = 16
        figkwargs['inset.axes.labelsize'] = 16
        figkwargs['inset.axes.labelpad'] = 1
        figkwargs['inset.axes.legend.fontsize'] = 8
        figkwargs['inset.axes.annotation.fontsize'] = 12
        figkwargs['inset.axes.tiny.annotation.fontsize'] = 3
        figkwargs['inset.axes.text.fontsize'] = 4
        figkwargs['inset.axes.tiny.text.fontsize'] = 3
        figkwargs['inset.axes.tick.major.size'] = 6
        figkwargs['inset.axes.tick.minor.size'] = 3
        figkwargs['inset.axes.tick.width'] = 1
        figkwargs['inset.axes.tick.labelsize'] = 16
        figkwargs['inset.axes.tick.labelpad'] = 0.3
        mplobj.rcParams['font.size'] = 24
        mplobj.rcParams['axes.labelsize'] = 28
        mplobj.rcParams['legend.fontsize'] = 22
        mplobj.rcParams['legend.borderpad'] = 0.5
        mplobj.rcParams['legend.markerscale'] = 1.0
        mplobj.rcParams['legend.labelspacing'] = 0.25
        mplobj.rcParams['legend.handlelength'] = 1.25
        mplobj.rcParams['legend.handleheight'] = 1.0
        mplobj.rcParams['legend.handletextpad'] = 0.25
        mplobj.rcParams['legend.borderaxespad'] = 0.125
        mplobj.rcParams['axes.linewidth'] = 2
        mplobj.rcParams['lines.linewidth'] = 3
        mplobj.rcParams['lines.markersize'] = 8
        mplobj.rcParams['lines.markeredgewidth'] = 1.5
        mplobj.rcParams['xtick.direction'] = 'out'
        mplobj.rcParams['xtick.major.size'] = 12
        mplobj.rcParams['xtick.minor.size'] = 6
        mplobj.rcParams['xtick.major.width'] = 2
        mplobj.rcParams['xtick.minor.width'] = 2
        mplobj.rcParams['xtick.major.pad'] = 4
        mplobj.rcParams['xtick.minor.pad'] = 4
        mplobj.rcParams['ytick.direction'] = 'out'
        mplobj.rcParams['ytick.major.size'] = 12
        mplobj.rcParams['ytick.minor.size'] = 6
        mplobj.rcParams['ytick.major.width'] = 2
        mplobj.rcParams['ytick.minor.width'] = 2
        mplobj.rcParams['ytick.major.pad'] = 4
        mplobj.rcParams['ytick.minor.pad'] = 4
    elif profile == 'kgraph':
        figkwargs['xdim'] = figkwargs['ydim'] = 4
        figkwargs['cbar.label.fontsize'] = 7
        figkwargs['contour.label.fontsize'] = 10
        figkwargs['annotation.fontsize'] = 6
        figkwargs['tiny.annotation.fontsize'] = 4
        figkwargs['text.fontsize'] = 2.5
        figkwargs['tiny.text.fontsize'] = 1.5
        figkwargs['marker.scale.factor'] = 0.3
        figkwargs['labelpad'] = 2.5
        figkwargs['legend.marker.scale.factor'] = 1.0
        figkwargs['legend.fontsize'] = 10.5
        figkwargs['title.fontsize'] = 10
        figkwargs['dropshadow.offset.x'] = 1.5
        figkwargs['dropshadow.offset.y'] = -3
        figkwargs['text.label.fontsize'] = 10
        figkwargs['tick.major.size'] = 6
        figkwargs['tick.minor.size'] = 3
        figkwargs['tick.width'] = 1
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 0.5
        figkwargs['inset.axes.markersize'] = 4
        figkwargs['inset.axes.marker.scale.factor'] = 0.25
        figkwargs['inset.axes.fontsize'] = 6
        figkwargs['inset.axes.labelsize'] = 7
        figkwargs['inset.axes.labelpad'] = 0.5
        figkwargs['inset.axes.legend.fontsize'] = 4
        figkwargs['inset.axes.annotation.fontsize'] = 6
        figkwargs['inset.axes.tiny.annotation.fontsize'] = 1.5
        figkwargs['inset.axes.text.fontsize'] = 2
        figkwargs['inset.axes.tiny.text.fontsize'] = 1.5
        figkwargs['inset.axes.tick.major.size'] = 3
        figkwargs['inset.axes.tick.minor.size'] = 1.5
        figkwargs['inset.axes.tick.width'] = 0.5
        figkwargs['inset.axes.tick.labelsize'] = 5
        figkwargs['inset.axes.tick.labelpad'] = 0.15
        mplobj.rcParams['font.size'] = 12
        mplobj.rcParams['axes.labelsize'] = 14
        mplobj.rcParams['legend.fontsize'] = 12
        mplobj.rcParams['legend.borderpad'] = 0.5
        mplobj.rcParams['legend.markerscale'] = 1.0
        mplobj.rcParams['legend.labelspacing'] = 0.25
        mplobj.rcParams['legend.handlelength'] = 1.25
        mplobj.rcParams['legend.handleheight'] = 1.0
        mplobj.rcParams['legend.handletextpad'] = 0.25
        mplobj.rcParams['legend.borderaxespad'] = 0.5
        mplobj.rcParams['axes.linewidth'] = 1
        mplobj.rcParams['lines.linewidth'] = 1.5
        mplobj.rcParams['lines.markersize'] = 4.0
        mplobj.rcParams['lines.markeredgewidth'] = 0.75
        mplobj.rcParams['xtick.direction'] = 'out'
        mplobj.rcParams['xtick.major.size'] = 6
        mplobj.rcParams['xtick.minor.size'] = 3
        mplobj.rcParams['xtick.major.width'] = 1
        mplobj.rcParams['xtick.minor.width'] = 1
        mplobj.rcParams['xtick.major.pad'] = 2
        mplobj.rcParams['xtick.minor.pad'] = 2
        mplobj.rcParams['ytick.direction'] = 'out'
        mplobj.rcParams['ytick.major.size'] = 6
        mplobj.rcParams['ytick.minor.size'] = 3
        mplobj.rcParams['ytick.major.width'] = 1
        mplobj.rcParams['ytick.minor.width'] = 1
        mplobj.rcParams['ytick.major.pad'] = 2.5
        mplobj.rcParams['ytick.minor.pad'] = 2.5
    elif profile == 'kgraph-wide':
        figkwargs['xdim'] = 12
        figkwargs['ydim'] = 3
        figkwargs['cbar.label.fontsize'] = 7
        figkwargs['contour.label.fontsize'] = 10
        figkwargs['annotation.fontsize'] = 6
        figkwargs['tiny.annotation.fontsize'] = 4
        figkwargs['text.fontsize'] = 2.5
        figkwargs['tiny.text.fontsize'] = 1.5
        figkwargs['marker.scale.factor'] = 0.3
        figkwargs['labelpad'] = 4
        figkwargs['legend.marker.scale.factor'] = 1.0
        figkwargs['legend.fontsize'] = 10.5
        figkwargs['title.fontsize'] = 10
        figkwargs['dropshadow.offset.x'] = 1.5
        figkwargs['dropshadow.offset.y'] = -3
        figkwargs['text.label.fontsize'] = 10
        figkwargs['tick.major.size'] = 6
        figkwargs['tick.minor.size'] = 3
        figkwargs['tick.width'] = 1
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 1
        figkwargs['inset.axes.markersize'] = 4
        figkwargs['inset.axes.marker.scale.factor'] = 0.25
        figkwargs['inset.axes.fontsize'] = 6
        figkwargs['inset.axes.labelsize'] = 7
        figkwargs['inset.axes.labelpad'] = 0.5
        figkwargs['inset.axes.legend.fontsize'] = 4
        figkwargs['inset.axes.annotation.fontsize'] = 6
        figkwargs['inset.axes.tiny.annotation.fontsize'] = 1.5
        figkwargs['inset.axes.text.fontsize'] = 2
        figkwargs['inset.axes.tiny.text.fontsize'] = 1.5
        figkwargs['inset.axes.tick.major.size'] = 3
        figkwargs['inset.axes.tick.minor.size'] = 1.5
        figkwargs['inset.axes.tick.width'] = 0.5
        figkwargs['inset.axes.tick.labelsize'] = 5
        figkwargs['inset.axes.tick.labelpad'] = 0.15
        mplobj.rcParams['font.size'] = 16
        mplobj.rcParams['axes.labelsize'] = 18
        mplobj.rcParams['legend.fontsize'] = 16
        mplobj.rcParams['legend.borderpad'] = 0.5
        mplobj.rcParams['legend.markerscale'] = 1.0
        mplobj.rcParams['legend.labelspacing'] = 0.25
        mplobj.rcParams['legend.handlelength'] = 1.25
        mplobj.rcParams['legend.handleheight'] = 1.0
        mplobj.rcParams['legend.handletextpad'] = 0.25
        mplobj.rcParams['legend.borderaxespad'] = 0.125
        mplobj.rcParams['axes.linewidth'] = 2
        mplobj.rcParams['lines.linewidth'] = 3
        mplobj.rcParams['lines.markersize'] = 4.0
        mplobj.rcParams['lines.markeredgewidth'] = 0.75
        mplobj.rcParams['xtick.direction'] = 'out'
        mplobj.rcParams['xtick.major.size'] = 7
        mplobj.rcParams['xtick.minor.size'] = 4
        mplobj.rcParams['xtick.major.width'] = 2
        mplobj.rcParams['xtick.minor.width'] = 2
        mplobj.rcParams['xtick.major.pad'] = 4
        mplobj.rcParams['xtick.minor.pad'] = 4
        mplobj.rcParams['ytick.direction'] = 'out'
        mplobj.rcParams['ytick.major.size'] = 7
        mplobj.rcParams['ytick.minor.size'] = 4
        mplobj.rcParams['ytick.major.width'] = 2
        mplobj.rcParams['ytick.minor.width'] = 2
        mplobj.rcParams['ytick.major.pad'] = 4
        mplobj.rcParams['ytick.minor.pad'] = 4
    elif profile == 'paper':
        figkwargs['xdim'] = figkwargs['ydim'] = 4
        figkwargs['cbar.label.fontsize'] = 7
        figkwargs['contour.label.fontsize'] = 10
        figkwargs['annotation.fontsize'] = 3
        figkwargs['ax.annotation.fontsize'] = 3
        figkwargs['text.fontsize'] = 3
        figkwargs['tiny.text.fontsize'] = 1.5
        figkwargs['marker.scale.factor'] = 0.3
        figkwargs['labelpad'] = 3
        figkwargs['legend.marker.scale.factor'] = 1.0
        figkwargs['legend.fontsize'] = 4
        figkwargs['title.fontsize'] = 10
        figkwargs['dropshadow.offset.x'] = 1.5
        figkwargs['dropshadow.offset.y'] = -3
        figkwargs['text.label.fontsize'] = 10
        figkwargs['tick.major.size'] = 4
        figkwargs['tick.minor.size'] = 2
        figkwargs['tick.width'] = 1
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 1
        figkwargs['inset.axes.markersize'] = 2
        figkwargs['inset.axes.marker.scale.factor'] = 0.2
        figkwargs['inset.axes.fontsize'] = 4
        figkwargs['inset.axes.labelsize'] = 6
        figkwargs['inset.axes.labelpad'] = 1.5
        figkwargs['inset.axes.annotation.fontsize'] = 6
        figkwargs['inset.axes.tiny.annotation.fontsize'] = 1.5
        figkwargs['inset.axes.text.fontsize'] = 6
        figkwargs['inset.axes.tiny.text.fontsize'] = 1.5
        figkwargs['inset.axes.legend.fontsize'] = 3
        figkwargs['inset.axes.tick.major.size'] = 2.5
        figkwargs['inset.axes.tick.minor.size'] = 1.5
        figkwargs['inset.axes.tick.width'] = 0.75
        figkwargs['inset.axes.tick.labelsize'] = 5
        figkwargs['inset.axes.tick.labelpad'] = 0.25
        mplobj.rcParams['font.size'] = 10
        mplobj.rcParams['axes.labelsize'] = 12
        mplobj.rcParams['legend.fontsize'] = 6
        mplobj.rcParams['legend.labelspacing'] = 0.4
        mplobj.rcParams['axes.linewidth'] = 1
        mplobj.rcParams['lines.linewidth'] = 1.5
        mplobj.rcParams['lines.markersize'] = 4.0
        mplobj.rcParams['lines.markeredgewidth'] = 0.75
        mplobj.rcParams['xtick.major.size'] = 4
        mplobj.rcParams['xtick.minor.size'] = 2
        mplobj.rcParams['xtick.major.width'] = 1
        mplobj.rcParams['xtick.minor.width'] = 1
        mplobj.rcParams['xtick.major.pad'] = 2
        mplobj.rcParams['xtick.minor.pad'] = 2
        mplobj.rcParams['ytick.major.size'] = 4
        mplobj.rcParams['ytick.minor.size'] = 2
        mplobj.rcParams['ytick.major.width'] = 1
        mplobj.rcParams['ytick.minor.width'] = 1
        mplobj.rcParams['ytick.major.pad'] = 2
        mplobj.rcParams['ytick.minor.pad'] = 2
    elif profile in ('2-col', '2-column', 'double-column'):
        figkwargs['xdim'] = figkwargs['ydim'] = 8
        figkwargs['cbar.label.fontsize'] = 14
        figkwargs['contour.label.fontsize'] = 20
        figkwargs['annotation.fontsize'] = 12
        figkwargs['tiny.annotation.fontsize'] = 8
        figkwargs['text.fontsize'] = 5
        figkwargs['tiny.text.fontsize'] = 3
        figkwargs['marker.scale.factor'] = 0.6
        figkwargs['labelpad'] = 5
        figkwargs['legend.marker.scale.factor'] = 1.0
        figkwargs['legend.fontsize'] = 21
        figkwargs['title.fontsize'] = 20
        figkwargs['dropshadow.offset.x'] = 3
        figkwargs['dropshadow.offset.y'] = -6
        figkwargs['text.label.fontsize'] = 20
        figkwargs['tick.major.size'] = 12
        figkwargs['tick.minor.size'] = 6
        figkwargs['tick.width'] = 2
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 1
        figkwargs['inset.axes.markersize'] = 8
        figkwargs['inset.axes.marker.scale.factor'] = 0.5
        figkwargs['inset.axes.fontsize'] = 12
        figkwargs['inset.axes.labelsize'] = 14
        figkwargs['inset.axes.labelpad'] = 1
        figkwargs['inset.axes.legend.fontsize'] = 8
        figkwargs['inset.axes.annotation.fontsize'] = 12
        figkwargs['inset.axes.tiny.annotation.fontsize'] = 3
        figkwargs['inset.axes.text.fontsize'] = 4
        figkwargs['inset.axes.tiny.text.fontsize'] = 3
        figkwargs['inset.axes.tick.major.size'] = 6
        figkwargs['inset.axes.tick.minor.size'] = 3
        figkwargs['inset.axes.tick.width'] = 1
        figkwargs['inset.axes.tick.labelsize'] = 10
        figkwargs['inset.axes.tick.labelpad'] = 0.3
        mplobj.rcParams['font.size'] = 24
        mplobj.rcParams['axes.labelsize'] = 28
        mplobj.rcParams['legend.fontsize'] = 24
        mplobj.rcParams['legend.borderpad'] = 0.5
        mplobj.rcParams['legend.markerscale'] = 1
        mplobj.rcParams['legend.labelspacing'] = 0.25
        mplobj.rcParams['legend.handlelength'] = 1.25
        mplobj.rcParams['legend.handleheight'] = 1
        mplobj.rcParams['legend.handletextpad'] = 0.25
        mplobj.rcParams['legend.borderaxespad'] = 0.125
        mplobj.rcParams['axes.linewidth'] = 2
        mplobj.rcParams['lines.linewidth'] = 3
        mplobj.rcParams['lines.markersize'] = 8
        mplobj.rcParams['lines.markeredgewidth'] = 1.5
        mplobj.rcParams['xtick.direction'] = 'out'
        mplobj.rcParams['xtick.major.size'] = 10
        mplobj.rcParams['xtick.minor.size'] = 5
        mplobj.rcParams['xtick.major.width'] = 2
        mplobj.rcParams['xtick.minor.width'] = 2
        mplobj.rcParams['xtick.major.pad'] = 4
        mplobj.rcParams['xtick.minor.pad'] = 4
        mplobj.rcParams['ytick.direction'] = 'out'
        mplobj.rcParams['ytick.major.size'] = 10
        mplobj.rcParams['ytick.minor.size'] = 5
        mplobj.rcParams['ytick.major.width'] = 2
        mplobj.rcParams['ytick.minor.width'] = 2
        mplobj.rcParams['ytick.major.pad'] = 4
        mplobj.rcParams['ytick.minor.pad'] = 4
    elif profile == 'tiny':
        figkwargs['xdim'] = figkwargs['ydim'] = 2
        figkwargs['cbar.label.fontsize'] = 4
        figkwargs['contour.label.fontsize'] = 5
        figkwargs['annotation.fontsize'] = 1.5
        figkwargs['ax.annotation.fontsize'] = 1.5
        figkwargs['marker.scale.factor'] = 0.175
        figkwargs['legend.marker.scale.factor'] = 1.0
        figkwargs['legend.fontsize'] = 2
        figkwargs['labelpad'] = 1.5
        figkwargs['title.fontsize'] = 5
        figkwargs['dropshadow.offset.x'] = 0.75
        figkwargs['dropshadow.offset.y'] = -1.5
        figkwargs['text.label.fontsize'] = 6
        figkwargs['tick.major.size'] = 2
        figkwargs['tick.minor.size'] = 1
        figkwargs['tick.width'] = 0.5
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 0.5
        figkwargs['inset.axes.markersize'] = 1
        figkwargs['inset.axes.marker.scale.factor'] = 0.1
        figkwargs['inset.axes.fontsize'] = 2
        figkwargs['inset.axes.labelsize'] = 3
        figkwargs['inset.axes.labelpad'] = 0.75
        figkwargs['inset.axes.legend.fontsize'] = 1.5
        figkwargs['inset.axes.tick.major.size'] = 1.25
        figkwargs['inset.axes.tick.minor.size'] = 0.75
        figkwargs['inset.axes.tick.width'] = 0.375
        figkwargs['inset.axes.tick.labelsize'] = 2.5
        figkwargs['inset.axes.tick.labelpad'] = 0.125
        mplobj.rcParams['font.size'] = 5
        mplobj.rcParams['axes.labelsize'] = 7
        mplobj.rcParams['legend.fontsize'] = 3
        mplobj.rcParams['legend.labelspacing'] = 0.2
        mplobj.rcParams['axes.linewidth'] = 0.5
        mplobj.rcParams['lines.linewidth'] = 1.0
        mplobj.rcParams['lines.markersize'] = 2.0
        mplobj.rcParams['lines.markeredgewidth'] = 0.25
        mplobj.rcParams['xtick.major.size'] = 2
        mplobj.rcParams['xtick.minor.size'] = 1.25
        mplobj.rcParams['xtick.major.width'] = 0.5
        mplobj.rcParams['xtick.minor.width'] = 0.5
        mplobj.rcParams['xtick.major.pad'] = 1.25
        mplobj.rcParams['xtick.minor.pad'] = 1.25
        mplobj.rcParams['ytick.major.size'] = 2
        mplobj.rcParams['ytick.minor.size'] = 1.25
        mplobj.rcParams['ytick.major.width'] = 0.5
        mplobj.rcParams['ytick.minor.width'] = 0.5
        mplobj.rcParams['ytick.major.pad'] = 1.25
        mplobj.rcParams['ytick.minor.pad'] = 1.25
    elif profile == 'print':
        figkwargs['xdim'] = figkwargs['ydim'] = 10
        figkwargs['cbar.label.fontsize'] = 18
        figkwargs['contour.label.fontsize'] = 22
        figkwargs['annotation.fontsize'] = 10
        figkwargs['ax.annotation.fontsize'] = 8
        figkwargs['marker.scale.factor'] = 0.8
        figkwargs['labelpad'] = 10
        figkwargs['title.fontsize'] = 28
        figkwargs['legend.marker.scale.factor'] = 0.5
        figkwargs['legend.fontsize'] = 16
        figkwargs['dropshadow.offset.x'] = 4
        figkwargs['dropshadow.offset.y'] = -6
        figkwargs['text.label.fontsize'] = 20
        figkwargs['tick.major.size'] = 4
        figkwargs['tick.minor.size'] = 2
        figkwargs['tick.width'] = 1.5
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 1.5
        figkwargs['inset.axes.markersize'] = 8
        figkwargs['inset.axes.marker.scale.factor'] = 0.5
        figkwargs['inset.axes.fontsize'] = 10
        figkwargs['inset.axes.labelsize'] = 14
        figkwargs['inset.axes.labelpad'] = 3
        figkwargs['inset.axes.legend.fontsize'] = 8
        figkwargs['inset.axes.tick.major.size'] = 6
        figkwargs['inset.axes.tick.minor.size'] = 4
        figkwargs['inset.axes.tick.width'] = 1.5
        figkwargs['inset.axes.tick.labelsize'] = 12
        figkwargs['inset.axes.tick.labelpad'] = 1
        mplobj.rcParams['font.size'] = 22
        mplobj.rcParams['axes.labelsize'] = 24
        mplobj.rcParams['legend.fontsize'] = 15
        mplobj.rcParams['legend.labelspacing'] = 0.4
        mplobj.rcParams['axes.linewidth'] = 2
        mplobj.rcParams['lines.linewidth'] = 3.0
        mplobj.rcParams['lines.markersize'] = 12.5
        mplobj.rcParams['lines.markeredgewidth'] = 1.0
        mplobj.rcParams['xtick.major.size'] = 10
        mplobj.rcParams['xtick.minor.size'] = 5
        mplobj.rcParams['xtick.major.width'] = 2
        mplobj.rcParams['xtick.minor.width'] = 2
        mplobj.rcParams['xtick.major.pad'] = 8
        mplobj.rcParams['xtick.minor.pad'] = 8
        mplobj.rcParams['ytick.major.size'] = 10
        mplobj.rcParams['ytick.minor.size'] = 5
        mplobj.rcParams['ytick.major.width'] = 2
        mplobj.rcParams['ytick.minor.width'] = 2
        mplobj.rcParams['ytick.major.pad'] = 8
        mplobj.rcParams['ytick.minor.pad'] = 8
    elif profile == 'poster':
        figkwargs['xdim'] = figkwargs['ydim'] = 20
        figkwargs['cbar.label.fontsize'] = 40
        figkwargs['contour.label.fontsize'] = 44
        figkwargs['annotation.fontsize'] = 20
        figkwargs['ax.annotation.fontsize'] = 14
        figkwargs['marker.scale.factor'] = 1
        figkwargs['legend.marker.scale.factor'] = 1
        figkwargs['legend.fontsize'] = 36
        figkwargs['labelpad'] = 20
        figkwargs['title.fontsize'] = 52
        figkwargs['text.label.fontsize'] = 42
        figkwargs['tick.major.size'] = 20
        figkwargs['tick.minor.size'] = 10
        figkwargs['tick.width'] = 5
        figkwargs['tick.major.width'] = figkwargs['tick.width']
        figkwargs['tick.minor.width'] = figkwargs['tick.width']
        figkwargs['inset.axes.linewidth'] = 3
        figkwargs['inset.axes.markersize'] = 15
        figkwargs['inset.axes.fontsize'] = 32
        figkwargs['inset.axes.labelsize'] = 36
        figkwargs['inset.axes.labelpad'] = 10
        figkwargs['inset.axes.tick.major.size'] = 10
        figkwargs['inset.axes.tick.minor.size'] = 6
        figkwargs['inset.axes.tick.width'] = 3
        mplobj.rcParams['font.family'] = 'sans-serif'
        mplobj.rcParams['font.size'] = 48
        mplobj.rcParams['axes.labelsize'] = 50
        mplobj.rcParams['legend.fontsize'] = 36
        mplobj.rcParams['legend.labelspacing'] = 0.4
        mplobj.rcParams['axes.linewidth'] = 5.0
        mplobj.rcParams['lines.linewidth'] = 6.0
        mplobj.rcParams['lines.markersize'] = 25
        mplobj.rcParams['lines.markeredgewidth'] = 3.0
        mplobj.rcParams['xtick.major.size'] = 20
        mplobj.rcParams['xtick.minor.size'] = 10
        mplobj.rcParams['xtick.major.width'] = 5
        mplobj.rcParams['xtick.minor.width'] = 5
        mplobj.rcParams['xtick.major.pad'] = 12
        mplobj.rcParams['xtick.minor.pad'] = 12
        mplobj.rcParams['ytick.major.size'] = 20
        mplobj.rcParams['ytick.minor.size'] = 10
        mplobj.rcParams['ytick.major.width'] = 5
        mplobj.rcParams['ytick.minor.width'] = 5
        mplobj.rcParams['ytick.major.pad'] = 12
        mplobj.rcParams['ytick.minor.pad'] = 12
    else:
        figkwargs['xdim'] = figkwargs['ydim'] = 8
        figkwargs['cbar.label.fontsize'] = 12
        figkwargs['contour.label.fontsize'] = 12
        figkwargs['annotation.fontsize'] = 10
        figkwargs['marker.scale.factor'] = 0.2
        figkwargs['legend.marker.scale.factor'] = 1
        figkwargs['labelpad'] = 5
        figkwargs['title.fontsize'] = 12
        figkwargs['text.label.fontsize'] = 12
        figkwargs['inset.axes.linewidth'] = 1
        figkwargs['inset.axes.markersize'] = 1
        figkwargs['inset.axes.fontsize'] = 8
        figkwargs['inset.axes.labelsize'] = 10
        figkwargs['inset.axes.labelpad'] = 2
        figkwargs['inset.axes.tick.major.size'] = 3
        figkwargs['inset.axes.tick.minor.size'] = 1
        figkwargs['inset.axes.tick.width'] = 1
        mplobj.rcParams['font.size'] = 12
        mplobj.rcParams['axes.labelsize'] = 14
        mplobj.rcParams['legend.fontsize'] = 12
        mplobj.rcParams['legend.labelspacing'] = 0.8
        mplobj.rcParams['axes.linewidth'] = 1.0
        mplobj.rcParams['lines.linewidth'] = 1.0
        mplobj.rcParams['lines.markersize'] = 1.0
        mplobj.rcParams['xtick.minor.size'] = 2
        mplobj.rcParams['xtick.major.size'] = 4
        mplobj.rcParams['xtick.major.width'] = 2
        mplobj.rcParams['xtick.minor.width'] = 2
        mplobj.rcParams['xtick.major.pad'] = 3
        mplobj.rcParams['xtick.minor.pad'] = 3
        mplobj.rcParams['xtick.labelsize'] = 'small'
        mplobj.rcParams['ytick.major.size'] = 4
        mplobj.rcParams['ytick.minor.size'] = 2
        mplobj.rcParams['ytick.major.width'] = 2
        mplobj.rcParams['ytick.minor.width'] = 2
        mplobj.rcParams['ytick.major.pad'] = 3
        mplobj.rcParams['ytick.minor.pad'] = 3
        mplobj.rcParams['ytick.labelsize'] = 'small'
    if isinstance(aspectratio, (int, float)):
        figkwargs['ydim'] /= aspectratio
    return figkwargs


def parsePermission3Char(permission):
    """
    'rwx' 形式のアクセス権限文字列 permission を8進数形式に変換する

    :return:
    :rtype: int
    """
    if len(permission) != 3:
        raise ValueError(permission)
    permission_int = 0
    if permission[0] == 'r':
        permission_int += 4
    if permission[1] == 'w':
        permission_int += 2
    if permission[2] == 'x':
        permission_int += 1
    return permission_int


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

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

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


@staticmethod
def concat_url(endpoint, url):
    """Concatenate endpoint and final URL.

        E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
        "http://keystone/v2.0/tokens".

        :param endpoint: the base URL
        :param url: the final URL
        """
    return '%s/%s' % (endpoint.rstrip('/'), url.strip('/'))


def boolean_validator(ns, value):
    """
    Boolean validator. Raises ValueError if input isn't a boolean string.

    :param pypsi.namespace.Namespace ns: active namespace
    :param value: input value
    :returns bool: validated value
    """
    if isinstance(value, bool):
        return value
    if isinstance(value, str):
        t = value.lower()
        if t in ('true', 't', '1', 'y', 'yes'):
            return True
        if t in ('false', 'f', '0', 'n', 'no'):
            return False
    raise ValueError('Value is not true or false')


@classmethod
def __str__(cls):
    """
        A string representation of the Collection

        :return: str
        """
    return '<%s>' % cls.__name__


def rfc822():
    """Return the date in RFC 822 format"""


def increment_index(builder, val):
    """
    Increment an index *val*.
    """
    one = val.type(1)
    return builder.add(val, one, flags=['nsw'])


def identify_co2_emissions_v1(co2_emissions, params_initial_guess):
    """
    Identifies instantaneous CO2 emission vector [CO2g/s].

    :param co2_emissions:
        CO2 instantaneous emissions vector [CO2g/s].
    :type co2_emissions: numpy.array

    :param params_initial_guess:
        Initial guess of co2 emission model params.
    :type params_initial_guess: dict

    :return:
        The instantaneous CO2 emission vector [CO2g/s], rescaling scores
        (i.e., mean, std, and number of perturbations) [-], and the identified
        initial guess of co2 emission model params.
    :rtype: numpy.array, tuple[float], dict
    """
    return co2_emissions, (1.0, 0, 0), params_initial_guess


@classmethod
def one(cls, *args):
    """Get one resource."""
    rv = None
    if cls.__key__ == ('id',):
        msg = 'The keys does not ensure the uniqueness of an instance.'
        query = 'SELECT id, obj FROM %s WHERE id = ?' % cls.__tablename__
        c = cls._session().cursor()
        for row in c.execute(query, args):
            if rv is not None:
                raise NotImplementedError(msg)
            rv = cls._deserialize(*row)
    else:
        rv = super().one(*args)
    return rv


def extract_with_context(lst, pred, before_context, after_context):
    """Extract URL and context from a given chunk.

    """
    rval = []
    start = 0
    length = 0
    while start < len(lst):
        usedfirst = False
        usedlast = False
        while start + length < len(lst
            ) and length < before_context + 1 and not pred(lst[start + length]
            ):
            length += 1
        while start + length < len(lst) and not pred(lst[start + length]):
            start += 1
        if start + length == len(lst):
            break
        while start + length < len(lst) and pred(lst[start + length]):
            extendlength = 1
            while (extendlength < after_context + 1 and start + length +
                extendlength < len(lst) and not pred(lst[start + length +
                extendlength])):
                extendlength += 1
            length += extendlength
            if start + length < len(lst) and not pred(lst[start + length]):
                extendlength = 1
                while (extendlength < before_context and start + length +
                    extendlength < len(lst) and not pred(lst[start + length +
                    extendlength])):
                    extendlength += 1
                if start + length + extendlength < len(lst) and pred(lst[
                    start + length + extendlength]):
                    length += extendlength
        if length > 0 and start + length <= len(lst):
            if start == 0:
                usedfirst = True
            if start + length == len(lst):
                usedlast = True
            rval.append((lst[start:start + length], usedfirst, usedlast))
        start += length
        length = 0
    return rval


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


def IsEmptyString(s):
    """
    Tells if a string is empty.

    @param      s       string
    @return             boolean
    """
    if s is None:
        return True
    return len(s) == 0


def simplify(name):
    """Removes duplicates in names of the form 'name1|name2', and sorts elements."""
    return '|'.join(sorted(set(name.split('|'))))