def update_organizational_unit(OrganizationalUnitId=None, Name=None):
    """
    Renames the specified organizational unit (OU). The ID and ARN do not change. The child OUs and accounts remain in place, and any attached policies of the OU remain attached.
    This operation can be called only from the organization's master account.
    See also: AWS API Documentation

    :example: response = client.update_organizational_unit(
        OrganizationalUnitId='string',
        Name='string'
    )

    :type OrganizationalUnitId: string
    :param OrganizationalUnitId: [REQUIRED]
            The unique identifier (ID) of the OU that you want to rename. You can get the ID from the ListOrganizationalUnitsForParent operation.
            The regex pattern for an organizational unit ID string requires 'ou-' followed by from 4 to 32 lower-case letters or digits (the ID of the root that contains the OU) followed by a second '-' dash and from 8 to 32 additional lower-case letters or digits.

    :type Name: string
    :param Name: The new name that you want to assign to the OU.
            The regex pattern that is used to validate this parameter is a string of any of the characters in the ASCII character range.

    :rtype: dict
    :return: {
        'OrganizationalUnit': {
            'Id': 'string',
            'Arn': 'string',
            'Name': 'string'
        }
    }

    """
    pass


def _isnoneslice(v):
    """
    Checks if input is slice(None) object.
    """
    return isinstance(v, slice
        ) and v.start is None and v.stop is None and v.step is None


@staticmethod
def _transform_member(member, feature_compatibility):
    """Transforms a member into an object that will

            be processed by the templating system
        """
    return {'id': member.id, 'address': member.ip_address, 'protocol_port':
        member.protocol_port, 'weight': member.weight, 'enabled': member.
        enabled, 'subnet_id': member.subnet_id, 'operating_status': member.
        operating_status, 'monitor_address': member.monitor_address,
        'monitor_port': member.monitor_port, 'backup': member.backup}


def is_power2(n):
    """Check if an integer is a power of 2."""
    return (n > 0) & (n & n - 1 == 0)


def pg_exists(conn, name):
    """
    Does a postgres object exist?
    :rtype bool
    """
    return conn.execute('SELECT to_regclass(%s)', name).scalar() is not None


@classmethod
def get_fig_manager(cls, num):
    """
        If figure manager *num* exists, make it the active
        figure and return the manager; otherwise return *None*.
        """
    manager = cls.figs.get(num, None)
    if manager is not None:
        cls.set_active(manager)
    return manager


@classmethod
def to_xml(cls, enum_val):
    """
        Return the XML value of the enumeration value *enum_val*.
        """
    if enum_val not in cls._member_to_xml:
        raise ValueError("value '%s' not in enumeration %s" % (enum_val,
            cls.__name__))
    return cls._member_to_xml[enum_val]


@classmethod
def store(cls, server_url, association):
    """Create an Association instance"""
    raise NotImplementedError('Implement in subclass')


@classmethod
def createSender(cls, name, *args, **kwargs):
    """ Initialize an SMS sender.

        :param name: Name as registered in SmsSenderFactory:senders (e.g. 'Twilio')

        .. versionadded:: 3.2.0
        """
    return cls.senders[name](*args, **kwargs)


@classmethod
def list(cls, ignore=()):
    """Query to list all users."""
    statement = (
        "SELECT usename, datname, pg_encoding_to_char(encoding), datcollate FROM pg_catalog.pg_user LEFT JOIN pg_catalog.pg_database ON CONCAT(usename, '=CTc/os_admin') = ANY(datacl::text[]) WHERE (datistemplate ISNULL OR datistemplate = false)"
        )
    if ignore:
        for name in ignore:
            statement += " AND usename != '{name}'".format(name=name)
    return statement


def get_rfx_object(packetid):
    """Return the RFXObject with the packetid."""
    import RFXtrx as rfxtrxmod
    try:
        binarypacket = bytearray.fromhex(packetid)
    except ValueError:
        return None
    pkt = rfxtrxmod.lowlevel.parse(binarypacket)
    if pkt is None:
        return None
    if isinstance(pkt, rfxtrxmod.lowlevel.SensorPacket):
        obj = rfxtrxmod.SensorEvent(pkt)
    elif isinstance(pkt, rfxtrxmod.lowlevel.Status):
        obj = rfxtrxmod.StatusEvent(pkt)
    else:
        obj = rfxtrxmod.ControlEvent(pkt)
    return obj


def imagenet_benchmark_zoo_model_names():
    """ Get the names of all models naturally supported by this toolbox.

    Returns
    -------
    list of str
        The names of all models supported.

    """
    return ['vgg16', 'vgg19', 'alexnet', 'densenet121', 'densenet169',
        'densenet201', 'googlenet', 'inception_v3', 'mnasnet',
        'mobilenet_v2', 'resnet50', 'resnet101', 'resnet152',
        'resnext50_32x4d', 'shufflenet_V2', 'squeezenet1_0',
        'squeezenet1_1', 'wide_resnet50_2', 'wide_resnet101_2']


def downsample(N):
    """conditional that is true on every Nth sample"""
    global _downsample_N
    _downsample_N = (_downsample_N + 1) % N
    return _downsample_N == 0


def interleave_uneven(list1, list2, list1_start=0, list2_start=0,
    list1_step=1, list2_step=1):
    """ Given 2 lists interleave between each list every n steps
       optionally offset the start of either list but loop round so all results are returned.
    Args:
      list1: line start
      list2: line end
      list1_start: optionally offset start position of first list zero by default
      list2_start: optionally offset start position of second list zero by default
      list1_step: number of items to return before switching lists
      list2_step: number of items to return before switching lists

    Returns:
      list item: current item in list

    Links:"""
    length1 = len(list1) - 1
    length2 = len(list2) - 1
    length = length1 + length2
    list1_pos = list1_start
    list2_pos = list2_start
    pos = 0
    while pos < length:
        for i in range(0, list1_step):
            yield list1[list1_pos]
            list1_pos += 1
            if list1_pos > length1:
                list1_pos = 0
            pos += 1
        for i in range(0, list2_step):
            yield list2[list2_pos]
            list2_pos += 1
            if list2_pos > length2:
                list2_pos = 0
            pos += 1


def augment(note):
    """Augment a given note.

    Examples:
    >>> augment('C')
    'C#'
    >>> augment('Cb')
    'C'
    """
    if note[-1] != 'b':
        return note + '#'
    else:
        return note[:-1]


def _find(tokens, token, value):
    """Return the position of the last token with the same (token, value)
    pair supplied. The position is the one of the rightmost term.
    """
    for index, token_values in enumerate(reversed(tokens)):
        if (token, value) == token_values[:2]:
            return len(tokens) - index - 1
    raise ValueError('(token, value) pair not found')


@conf
def find_clangxx(conf):
    """
	Finds the program clang++, and executes it to ensure it really is clang++
	"""
    import os
    cxx = conf.find_program('clang++', var='CXX')
    if conf.options.clangxx_target_triple != None:
        conf.env.append_value('CXX', ['-target', conf.options.
            clangxx_target_triple])
    if conf.options.clangxx_sysroot != None:
        sysroot = str()
        if os.path.isabs(conf.options.clangxx_sysroot):
            sysroot = conf.options.clangxx_sysroot
        else:
            sysroot = os.path.normpath(os.path.join(os.getcwd(), conf.
                options.clangxx_sysroot))
        conf.env.append_value('CXX', ['--sysroot', sysroot])
    conf.get_cc_version(cxx, clang=True)
    conf.env.CXX_NAME = 'clang'


@classmethod
def get(cls, doctree):
    """Return the first slideconf node for the doctree."""
    conf_nodes = doctree.traverse(cls)
    if conf_nodes:
        return conf_nodes[0]


def p_namespace_name(p):
    """namespace_name : namespace_name NS_SEPARATOR STRING
                      | STRING
                      | ARRAY"""
    if len(p) == 4:
        p[0] = p[1] + p[2] + p[3]
    else:
        p[0] = p[1]


@classmethod
def register_rule(cls, **kwargs):
    """
        Use it as a class decorator::

            normalizer = Normalizer('grammar', 'config')
            @normalizer.register_rule(value='foo')
            class MyRule(Rule):
                error_code = 42
        """
    return cls._register_rule(**kwargs)


def check_array(array, check):
    """Checks if item is in array.

    Checks if an item has already been added to an array.

    Parameters
    ----------
    array: array-type
        The array to check.
    check: str
        The item to try and find.

    Returns
    -------
    bool
        true if the item is already present in the scatlen type array, false if not.
    """
    for i in range(0, len(array)):
        if check == array[i]:
            return True
    return False


def _join_abbreviated_names(lst):
    """Joins a list of name strings like ["J.", "Frank"] such that it adds a space if
    one of the two names is not abbreviated. See
    <https://english.stackexchange.com/a/105529/23644>.
    """
    if len(lst) == 0:
        return ''
    out = lst[0]
    last_ends_in_dot = lst[0][-1] == '.'
    for item in lst[1:]:
        ends_in_dot = item[-1] == '.'
        if last_ends_in_dot and ends_in_dot:
            out += item
        else:
            out += ' ' + item
        last_ends_in_dot = ends_in_dot
    return out


def delete_lifecycle_hook(LifecycleHookName=None, AutoScalingGroupName=None):
    """
    Deletes the specified lifecycle hook.
    If there are any outstanding lifecycle actions, they are completed first (ABANDON for launching instances, CONTINUE for terminating instances).
    See also: AWS API Documentation

    Examples
    This example deletes the specified lifecycle hook.
    Expected Output:

    :example: response = client.delete_lifecycle_hook(
        LifecycleHookName='string',
        AutoScalingGroupName='string'
    )

    :type LifecycleHookName: string
    :param LifecycleHookName: [REQUIRED]
            The name of the lifecycle hook.

    :type AutoScalingGroupName: string
    :param AutoScalingGroupName: [REQUIRED]
            The name of the Auto Scaling group for the lifecycle hook.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def fsplit(pred, objs):
    """Split a list into two classes according to the predicate."""
    t = []
    f = []
    for obj in objs:
        if pred(obj):
            t.append(obj)
        else:
            f.append(obj)
    return t, f


def is_error(code):
    """
    Default status error checking
    """
    code = str(code) if isinstance(code, int) else code
    return code.startswith('5') or code.startswith('4')


def add_change(id_, name, before, after):
    """Add change to the list of changes.
        """


def canonicalShape(shape):
    """Calculates a *canonical* shape, how the given ``shape`` should
    be presented. The shape is forced to be at least three dimensions,
    with any other trailing dimensions of length 1 ignored.
    """
    shape = list(shape)
    for i in reversed(range(len(shape))):
        if shape[i] == 1:
            shape = shape[:i]
        else:
            break
    if len(shape) < 3:
        shape = shape + [1] * (3 - len(shape))
    return shape


@classmethod
def _from_dict(cls, _dict):
    """Initialize a Field object from a json dictionary."""
    args = {}
    if 'field' in _dict or 'field_name' in _dict:
        args['field_name'] = _dict.get('field') or _dict.get('field_name')
    if 'type' in _dict or 'field_type' in _dict:
        args['field_type'] = _dict.get('type') or _dict.get('field_type')
    return cls(**args)


def iter_counts(seq, same=lambda a, b: a == b):
    """
    >>> list(iter_counts(('a', 'a', 'b', 'A', 'a', None, 'c')))
    [('a', 2), ('b', 1), ('A', 1), ('a', 1), (None, 1), ('c', 1)]
    >>> list(iter_counts(('a', 'a', 'b', 'A', 'a', 'c'), same=lambda a, b: a.upper()==b.upper()))
    [('a', 2), ('b', 1), ('A', 2), ('c', 1)]
    """
    it = iter(seq)
    try:
        prev = next(it)
    except StopIteration:
        return
    count = 1
    for el in it:
        if same(prev, el):
            count += 1
        else:
            yield prev, count
            prev = el
            count = 1
    yield prev, count


def _creation_options_for_cog(creation_options, source_profile, blocksize):
    """
    it uses the profile of the source raster, override anything using the creation_options
    and guarantees we will have tiled raster and blocksize
    """
    if not creation_options:
        creation_options = {}
    creation_options['blocksize'] = blocksize
    creation_options['tiled'] = True
    defaults = {'nodata': None, 'compress': 'lzw'}
    for key in ['nodata', 'compress']:
        if key not in creation_options:
            creation_options[key] = source_profile.get(key, defaults.get(key))
    return creation_options


@classmethod
def instance(cls, io_threads=1, shared_secret=None):
    """Returns a shared instance with the same shared secret, if there is one,
        otherwise creates it. If an instance already exists, io_threads will be ignored,
        otherwise it will be used in the new instance. Takes into account subclasses
        such that a subclass calling this method will always get back an instance of its
        own class"""
    try:
        return cls._instances[cls, shared_secret]
    except KeyError:
        instance = cls(io_threads, shared_secret=shared_secret)
        cls._instances[cls, shared_secret] = instance
        return instance


@classmethod
def _enforce_min_commissions(cls, commissions, nlvs):
    """
        Return a DataFrame of commissions after enforcing the min commission.
        """
    min_commissions = cls.MIN_COMMISSION / nlvs
    must_pay_min_commissions = (commissions > 0) & (commissions <
        min_commissions)
    commissions = commissions.where(must_pay_min_commissions == False,
        min_commissions)
    return commissions


def reduce_lists(d):
    """Replace single item lists in a dictionary with the single item."""
    for field in d:
        old_data = d[field]
        if len(old_data) == 1:
            d[field] = old_data[0]


def _collapse_sequences(matches):
    """Find sequences of lines.

    Given a sequence of [(line_in_a, line_in_b),]
    find regions where they both increment at the same time
    """
    answer = []
    start_a = start_b = None
    length = 0
    for i_a, i_b in matches:
        if (start_a is not None and i_a == start_a + length and i_b ==
            start_b + length):
            length += 1
        else:
            if start_a is not None:
                answer.append((start_a, start_b, length))
            start_a = i_a
            start_b = i_b
            length = 1
    if length != 0:
        answer.append((start_a, start_b, length))
    return answer


def dicts_get(s, *ds):
    """This helper functions allows for registering functions within a class that are no longer in scope at the time of registration

    `Source of this function <https://stackoverflow.com/questions/53678884/setting-imported-functions-as-members-in-a-static-dictionary>`_

    """
    for d in ds:
        if s in d:
            return d[s]
    raise NameError('name %s is not defined' % s)


def screen_out_path(input_fastq):
    """
    Determine the path to the output file created by fastq_screen given
    an input fastq file.

    :param str input_fastq: Path to input fastq or fastq.gz
    :returns: Path to fastq_screen output file
    """
    path_parts = input_fastq.split('.')
    if path_parts[-1] == 'gz':
        path_parts.pop()
    if path_parts[-1] in ['txt', 'seq', 'fastq', 'fq']:
        path_parts.pop()
    path_parts[-1] += '_screen'
    path_parts.append('txt')
    return '.'.join(path_parts)


def first(iterable, default=None, key=None):
    """
    Return first element of *iterable*.

    Return first element of *iterable* that evaluates to ``True``, else
    return ``None`` or optional *default*.

    >>> first([0, False, None, [], (), 42])
    42
    >>> first([0, False, None, [], ()]) is None
    True
    >>> first([0, False, None, [], ()], default='ohai')
    'ohai'
    >>> import re
    >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
    >>> m.group(1)
    'bc'

    The optional *key* argument specifies a one-argument predicate function
    like that used for *filter()*.  The *key* argument, if supplied, should be
    in keyword form. For example, finding the first even number in an iterable:

    >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
    4

    Contributed by Hynek Schlawack, author of `the original standalone module`_

    .. _the original standalone module: https://github.com/hynek/first
    """
    return next(filter(key, iterable), default)


def get_installed_tools():
    """Get list of installed scripts via ``pkg-resources``.

    See http://peak.telecommunity.com/DevCenter/PkgResources#convenience-api

    TODO: not sure if this will be useful ... maybe to check if the list
    of installed packages matches the available scripts somehow?
    """
    from pkg_resources import get_entry_map
    console_tools = get_entry_map('ctapipe')['console_scripts']
    return console_tools


@classmethod
def get(cls, project_id, recommendation_type=None):
    """
        Retrieves the default or specified by recommendation_type recommendation.

        Parameters
        ----------
        project_id : str
            The project's id.
        recommendation_type : enums.RECOMMENDED_MODEL_TYPE
            The type of recommendation to get. If None, returns the default recommendation.

        Returns
        -------
        recommended_model : ModelRecommendation

        """
    if recommendation_type is None:
        url = cls._base_recommended_path_template.format(project_id
            ) + 'recommendedModel/'
        return cls.from_location(url)
    else:
        recommendations = cls.get_all(project_id)
        return cls.get_recommendation(recommendations, recommendation_type)


def Error(message, toline):
    """
    This function display an error message. After such a message
    SpArtan must quit

    Paramters:
    ---------
    message:    str,Message to be displayed
    toline:     str,Carriage return or not before the message(Yes or No)

    Returns:
    -------

    """
    if toline == 'Yes':
        print('\n' + '\x1b[1m' + '\x1b[91m' + '[ERROR]:\t' + message +
            '\x1b[0m')
    else:
        print('\x1b[1m' + '\x1b[91m' + '[ERROR]:\t' + message + '\x1b[0m')


def _parse_dat_header(header_raw):
    """
    Parse point spectroscopy header.

    Each key-value pair is separated by '	' characters. Values may be
    further delimited by more '	' characters.

    Returns
    -------
    dict
        Parsed point spectroscopy header.
    """
    header_entries = header_raw.split('\r\n')
    header_entries = header_entries[:-3]
    header_dict = dict()
    for entry in header_entries:
        if entry[-1] == '\t':
            entry = entry[:-1]
        if '\t' not in entry:
            entry += '\t'
        key, val = entry.split('\t')
        header_dict[key] = val
    return header_dict


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

        :param PaperChangeMemberPolicyDetails val:
        :rtype: EventDetails
        """
    return cls('paper_change_member_policy_details', val)


def format_per_share_currency(value):
    """Format per-share currency, putting negative signs before dollar-sign"""
    try:
        formatted = '${0:,.2f}'.format(abs(float(value)))
        if float(value) < 0:
            formatted = '-%s' % formatted
    except:
        formatted = '--'
    return formatted


def connectTCP(host, port, factory, timeout=30, bindAddress=None):
    """
        Connect a TCP client.

        @param host: A hostname or an IPv4 or IPv6 address literal.

        @type host: L{bytes}

        @param port: a port number

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

        @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 None.

        @return: An object which provides L{IConnector}. This connector will
                 call various callbacks on the factory when a connection is
                 made, failed, or lost - see
                 L{ClientFactory<twisted.internet.protocol.ClientFactory>}
                 docs for details.
        """


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.stages.UnicodeNormalize'


def update_domain_entry(domainName=None, domainEntry=None):
    """
    Updates a domain recordset after it is created.
    See also: AWS API Documentation

    :example: response = client.update_domain_entry(
        domainName='string',
        domainEntry={
            'id': 'string',
            'name': 'string',
            'target': 'string',
            'type': 'string',
            'options': {
                'string': 'string'
            }
        }
    )

    :type domainName: string
    :param domainName: [REQUIRED]
            The name of the domain recordset to update.

    :type domainEntry: dict
    :param domainEntry: [REQUIRED]
            An array of key-value pairs containing information about the domain entry.
            id (string) --The ID of the domain recordset entry.
            name (string) --The name of the domain.
            target (string) --The target AWS name server (e.g., ns-111.awsdns-22.com. ).
            type (string) --The type of domain entry (e.g., SOA or NS ).
            options (dict) --The options for the domain entry.
            (string) --
            (string) --

    :rtype: dict
    :return: {
        'operations': [
            {
                'id': 'string',
                'resourceName': 'string',
                'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
                'createdAt': datetime(2015, 1, 1),
                'location': {
                    'availabilityZone': 'string',
                    'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
                },
                'isTerminal': True|False,
                'operationDetails': 'string',
                'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
                'status': 'NotStarted'|'Started'|'Failed'|'Completed',
                'statusChangedAt': datetime(2015, 1, 1),
                'errorCode': 'string',
                'errorDetails': 'string'
            },
        ]
    }

    """
    pass


def chiffre_barre_colonne(s, r, j):
    """
    Look into every number in column *j*,
    if the number in column *k* ``s[i][k]`` is not null,

    @param      s       current state of the sudoku
    @param      r       array ``r[n] == 0`` means number *n+1* is already taken on this column
    @param      j       column index (0 based)
    """
    for k in range(0, 9):
        if s[k][j] > 0:
            r[s[k][j] - 1] = 0


def _get_size(app_inst):
    """Helper method for getting the size of a backend object

    If app_inst is provided, we'll just parse the dict to get
    the size instead of making a separate http request
    """
    if 'data' in app_inst:
        app_inst = app_inst['data']
    sis = app_inst['storage_instances']
    found_si = sis[0]
    found_vol = found_si['volumes'][0]
    return found_vol['size']


def _residual(params, x, data, fit_func):
    """Residual function to minimize"""
    model = fit_func(x, params)
    return data - model


def mark(matched, chosen):
    """
    Populate list of chosen options based on output of get_matches
    """
    for m in matched:
        if chosen[m] == ' + ':
            chosen[m] = '   '
        elif chosen[m] == '   ':
            chosen[m] = ' + '
    return chosen


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

        :param SfFbUninviteType val:
        :rtype: EventType
        """
    return cls('sf_fb_uninvite', val)


def _class_name(obj):
    """Returns the full qualified class name of an object."""
    return '{0}.{1}'.format(obj.__module__, obj.__class__.__name__)


def setXPathDebug(newValue):
    """
        setXPathDebug - Function to change the global DEBUG for development.

            Will be removed / set to false for production release.

              @param newValue <bool> - True to enable debugging prints, False to disable them.
    """
    global _XPATH_DEBUG
    _XPATH_DEBUG = newValue


def xec(conn, s, data=None):
    """ conn is our connection object and is is statement commits use connector api
		if you want to manage commits and rollbacks """
    c = conn.cursor()
    c.execute(s, data)
    conn.commit()
    return c


def type_check_expr(value, kind):
    """ Type check the value of an expression.

    Parameters
    ----------
    value : object
        The value to type check.

    kind : type
        The allowed type of the value.

    """
    if not isinstance(kind, type):
        raise TypeError('%s is not a type' % kind)
    if not isinstance(value, kind):
        msg = "expression value has invalid type '%s'"
        raise TypeError(msg % type(value).__name__)


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 convert_watershed_names(name):
    """
    Convert watershed from topo.nc mask to existing snowav database version.

    """
    convert_list = ['Boise River Basin', 'Lakes Basin',
        'Merced River Basin', 'Kaweah River Basin', 'Kings River Basin']
    if name in convert_list:
        watershed = name.split(' ')[0]
    elif name == 'San Joaquin River Basin':
        watershed = 'San Joaquin'
    else:
        watershed = name
    return watershed


def SizeBenefitSurg(t):
    """Surgery benefit per policy"""
    return 0


def parse_solver_setting(s):
    """Parse a string containing a solver setting"""
    try:
        key, value = s.split('=', 1)
    except ValueError:
        key, value = s, 'yes'
    if key in ('rational', 'integer', 'quadratic'):
        value = value.lower() in ('1', 'yes', 'true', 'on')
    elif key in ('threads',):
        value = int(value)
    elif key in ('feasibility_tolerance', 'optimality_tolerance',
        'integrality_tolerance'):
        value = float(value)
    return key, value


@staticmethod
def p_read_write(p):
    """read_write : READ_WRITE"""
    p[0] = p[1]


def __to_int(val):
    """Convert val into an integer value."""
    try:
        return int(val)
    except (ValueError, TypeError):
        return 0


def window_new_main():
    """Create a new main window with its own workspace and scene selection

    """
    pass


@classmethod
def all(cls):
    """
        Returns all available objects from Slack API
        """
    items = cls._fetch_all()
    all = []
    for item in items:
        all.append(cls.from_item(item))
    return all


@classmethod
def clearBrowserCache(cls):
    """Clears browser cache.
        """
    return cls.build_send_payload('clearBrowserCache', {}), None


def _parse_source(source):
    """
    Parses the names-generator.go source to find adjectives and names.

    Parameters
    ----------
    source : str
        The source file to be parsed.

    Returns
    -------
    tuple(2)
        Two lists with [0] being adjectives and [1] being names.
    """
    collecting = False
    left = []
    right = []
    side = ''
    for line in source.splitlines():
        if '//' in line:
            continue
        if 'left' in line:
            collecting = True
            side = 'left'
            continue
        if 'right' in line:
            collecting = True
            side = 'right'
            continue
        if '}' in line:
            collecting = False
            side = ''
            continue
        if 'func GetRandomName' in line:
            break
        if collecting and '"' in line:
            cleaned_line = line.strip().replace('"', '').replace(',', '')
            if side == 'left':
                left.append(cleaned_line)
            if side == 'right':
                right.append(cleaned_line)
            continue
    return left, right


def label_loc(lon_a, lat_a, lon_b, lat_b):
    """Helper function for method info_plot of class Comlink
    """
    if lon_a < lon_b and lat_a < lat_b:
        x_a, y_a = lon_a - 0.025, lat_a - 0.005
        x_b, y_b = lon_b + 0.01, lat_b + 0.005
    elif lon_a < lon_b and lat_a > lat_b:
        x_a, y_a = lon_a - 0.025, lat_a + 0.005
        x_b, y_b = lon_b + 0.01, lat_b - 0.005
    elif lon_a > lon_b and lat_a > lat_b:
        x_a, y_a = lon_a + 0.01, lat_a + 0.005
        x_b, y_b = lon_b - 0.025, lat_b - 0.005
    elif lon_a > lon_b and lat_a < lat_b:
        x_a, y_a = lon_a + 0.01, lat_a - 0.005
        x_b, y_b = lon_b - 0.025, lat_b + 0.005
    xy = [x_a, y_a, x_b, y_b]
    return xy


def none_str(value, none_value=''):
    """Turn value into a string, special case None to empty string."""
    if value is None:
        return none_value
    else:
        return str(value)


def _format_syntax_error_message(exception):
    """Returns a nicely formatted SyntaxError message that emulates
    what the Python interpreter outputs, e.g.:

    > File "raven.py", line 3
    >   st.write('Hello world!!'))
    >                            ^
    > SyntaxError: invalid syntax

    Parameters
    ----------
    exception : SyntaxError

    Returns
    -------
    str

    """
    if exception.text:
        return (
            """File "%(filename)s", line %(lineno)d
  %(text)s
  %(caret_indent)s^
%(errname)s: %(msg)s"""
             % {'filename': exception.filename, 'lineno': exception.lineno,
            'text': exception.text.rstrip(), 'caret_indent': ' ' * max(
            exception.offset - 1, 0), 'errname': type(exception).__name__,
            'msg': exception.msg})
    return str(exception)


def get_pairs(word):
    """Return set of symbol pairs in a word.

    Word is represented as tuple of symbols (symbols being variable-length strings).
    """
    pairs = set()
    prev_char = word[0]
    for char in word[1:]:
        pairs.add((prev_char, char))
        prev_char = char
    return pairs


def interpretBoolean(s):
    """
    Interpret string as a boolean value.

    "0" and "False" are interpreted as False.  All other strings result in
    True.  Technically, only "0" and "1" values should be seen in UCI files.
    However, because of some string conversions in Python, we may encounter
    "False".
    """
    if s in ['0', 'False']:
        return False
    else:
        return True


def status(level, solved, err):
    """Calculate status from status and err."""
    if solved:
        if err:
            status = 'multiple solution'
        else:
            status = 'level ' + str(level)
    elif err:
        status = 'no solution'
    else:
        status = 'give up'
    return status


def top_screen_edge(desktop, rect):
    """ Get the y-coordinate of the effective top screen edge.

    Parameters
    ----------
    desktop : QDesktopWidget
        The desktop widget for the application.

    rect : QRect
        The rect of interest.

    Returns
    -------
    result : int
        the y-coordinate of the effective top screen edge.

    """
    p1 = rect.topLeft()
    p2 = rect.topRight()
    g1 = desktop.availableGeometry(p1)
    g2 = desktop.availableGeometry(p2)
    return max(p1.y(), g1.top(), g2.top())


def _HPERM_OP(a):
    """Clever bit manipulation."""
    t = (a << 18 ^ a) & 3435921408
    return a ^ t ^ t >> 18 & 16383


@staticmethod
def ParseTLE(filename):
    """

        Parses a TLE file of the given file name.

        Parameters:
            filename (str): Name of the TLE file.

        """
    outputArray = []
    tle = open(filename, 'r')
    firstLine = tle.readline()
    secondLine = tle.readline()
    outputArray.append(firstLine)
    outputArray.append(secondLine)
    tle.close()
    return outputArray


def load_data_from_file(data_path):
    """
    Load data from file
    :param data_path: input file path
    :return: sentences and labels
    Examples
    sentences = [['Hello', 'World'], ['Hello', 'World']]
    labels = [['B_W', 'I_W'], ['B_W', 'I_W']]
    """
    sentences = []
    labels = []
    with open(data_path, 'r') as fr:
        lines = fr.readlines()
        for line in lines:
            sent = []
            sent_labels = []
            for word in line.strip().split():
                syllables = word.split('_')
                for i, syllable in enumerate(syllables):
                    sent.append(syllable)
                    if i == 0:
                        sent_labels.append('B_W')
                    else:
                        sent_labels.append('I_W')
            sentences.append(sent)
            labels.append(sent_labels)
    return sentences, labels


@classmethod
def load_from_default(cls, name: str) ->None:
    """Sets the current instance of the page as the default to be loaded"""
    return cls.defaults.get(name).copy()


def hashable(data, v):
    """Determine whether `v` can be hashed."""
    try:
        data[v]
    except (TypeError, KeyError, IndexError):
        return False
    return True


def descending_sort(row):
    """
    Sorts (descending) the columns of a dataframe by value or a single row

    Args:
        row (Pandas.Series): a row of a pandas data frame

    Returns:
        (list): an array of column names
    """
    return row.sort_values(ascending=False).index.values


def objects(daterange=None, ticket=None, milestone=None, project=None,
    client=None):
    """ Returns a list of all contained time entries,
            optionally only for a given ticket, milestone, project or client
        """


def escape_string(s):
    """Escape a string as a literal value for use in an Xquery expression."""
    return s.replace('"', '""').replace('&', '&')


def _nonbreaking_spaces(match_obj):
    """
    Make spaces visible in HTML by replacing all `` `` with `` ``

    Call with a ``re`` match object.  Retain group 1, replace group 2
    with nonbreaking speaces.
    """
    spaces = ' ' * len(match_obj.group(2))
    return '%s%s' % (match_obj.group(1), spaces)


def __and__(i1, i2):
    """ Return the intersection of i1 and i2
        """
    return i1.__class__(i1.x & i2.x, i1.y & i2.y)


@staticmethod
def zipsafe(dist):
    """Returns whether or not we determine a distribution is zip-safe."""
    if hasattr(dist, 'egg_info') and dist.egg_info.endswith('EGG-INFO'):
        egg_metadata = dist.metadata_listdir('')
        return ('zip-safe' in egg_metadata and 'native_libs.txt' not in
            egg_metadata)
    else:
        return False


def restore_botocore_vendored_session_send():
    """Restores the original botocore vendored session send method"""
    try:
        from botocore.vendored.requests.sessions import Session as BotocoreVendoredSession
    except ImportError:
        pass
    else:
        if hasattr(BotocoreVendoredSession.send, '__wrapped__'):
            setattr(BotocoreVendoredSession, 'send',
                BotocoreVendoredSession.send.__wrapped__)


def inheritors(klass):
    """
    returns the inheritors of a class if it is loaded

    :return: a set of classes
    """
    subclasses = set()
    work = [klass]
    while work:
        parent = work.pop()
        for child in parent.__subclasses__():
            if child not in subclasses:
                subclasses.add(child)
                work.append(child)
    return subclasses


def axisheader2dic(header):
    """
    Convert an axisheader list into Sparky parameter axis dictionary.
    """
    dic = dict()
    dic['nucleus'] = str(header[0].decode()).strip('\x00')
    dic['spectral_shift'] = header[1]
    dic['npoints'] = header[2]
    dic['size'] = header[3]
    dic['bsize'] = header[4]
    dic['spectrometer_freq'] = header[5]
    dic['spectral_width'] = header[6]
    dic['xmtr_freq'] = header[7]
    dic['zero_order'] = header[8]
    dic['first_order'] = header[9]
    dic['first_pt_scale'] = header[10]
    dic['extended'] = header[11]
    return dic


def is_excluded_item(target):
    """Return true if target is excluded.
        """


def flatten(iter_of_iters):
    """
    Flatten an iterator of iterators into a single, long iterator, exhausting
    each subiterator in turn.

    >>> flatten([[1, 2], [3, 4]])
    [1, 2, 3, 4]

    """
    retval = []
    for val in iter_of_iters:
        retval.extend(val)
    return retval


def resolveDotted(dotted_or_ep):
    """ Resolve a dotted name or setuptools entry point to a callable.
    """
    from pkg_resources import EntryPoint
    return EntryPoint.parse('x=%s' % dotted_or_ep).resolve()


def get_xception_filename(key):
    """Rename tensor name to the corresponding Keras layer weight name.
    # Arguments
        key: tensor name in TF (determined by tf.variable_scope)
    """
    filename = str(key)
    filename = filename.replace('/', '_')
    filename = filename.replace('xception_65_', '')
    filename = filename.replace('decoder_', '', 1)
    filename = filename.replace('BatchNorm', 'BN')
    if 'Momentum' in filename:
        return None
    if 'entry_flow' in filename or 'exit_flow' in filename:
        filename = filename.replace('_unit_1_xception_module', '')
    elif 'middle_flow' in filename:
        filename = filename.replace('_block1', '')
        filename = filename.replace('_xception_module', '')
    filename = filename.replace('_weights', '_kernel')
    filename = filename.replace('_biases', '_bias')
    return filename + '.npy'


@staticmethod
def _is_resource_created(request):
    """Test if new resource is created.

        Args:
            request (dict): JSON resource received from a client.

        Returns:
            bool: True if a new resource is created.
        """
    method = request.method.lower()
    override = request.get_header('x-http-method-override', default=method)
    if (method == 'post' or override == 'post') or (method == 'put' or
        override == 'put'):
        return True
    return False


def preloaded_multi_mp_sgd_update(*data, **kwargs):
    """Update function for multi-precision Stochastic Gradient Descent (SDG) optimizer.

    It updates the weights using::

     weight = weight - learning_rate * (gradient + wd * weight)

    Defined in src/operator/contrib/preloaded_multi_sgd.cc:L140

    Parameters
    ----------
    data : Symbol[]
        Weights, gradients, learning rates and weight decays
    rescale_grad : float, optional, default=1
        Rescale gradient to grad = rescale_grad*grad.
    clip_gradient : float, optional, default=-1
        Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
    num_weights : int, optional, default='1'
        Number of updated weights.

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

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


def bind_required_kwargs(required_kwargs, obj, **kwargs):
    """ Method binds each element of ``required_kwargs`` to
    the input object ``obj``, or raises and exception for cases
    where a mandatory keyword argument was not passed to the
    ``obj`` constructor.

    Used throughout the package when a required keyword argument
    has no obvious default value.

    Parameters
    ----------
    required_kwargs : list
        List of strings of the keyword arguments that are required
        when instantiating the input ``obj``.

    obj : object
        The object being instantiated.

    Notes
    -----
    The `bind_required_kwargs` method assumes that each
    required keyword argument should be bound to ``obj``
    as attribute with the same name as the keyword.
    """
    for key in required_kwargs:
        if key in list(kwargs.keys()):
            setattr(obj, key, kwargs[key])
        else:
            class_name = obj.__class__.__name__
            msg = (key + ' is a required keyword argument ' +
                'to instantiate the ' + class_name + ' class')
            raise KeyError(msg)


def dist(x, y):
    """
    Calculate dist^2 between two points
    @param x: first point
    @param y: second point
    @return: distance^2
    """
    r = 0.0
    for i in range(3):
        r += (x[i] - y[i]) ** 2
    return r


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

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

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


def sftp(cluster, logdir, cmd, *args):
    """SFTP put a local file on cluster nodes"""
    src = args[0]
    if len(args) > 1:
        dst = args[1]
    else:
        dst = src
    cluster.sftp(src, dst)


def hr():
    """
    Print a horizontal line
    :return:
    """
    print('-' * 80)


def interleave(inter, f, seq):
    """Call f on each item in seq, calling inter() in between.
    """
    seq = iter(seq)
    try:
        f(next(seq))
    except StopIteration:
        pass
    else:
        for x in seq:
            inter()
            f(x)


def add_top_padding(box, extra_padding):
    """Increase the top padding of a box. This also translates the children.
    """
    box.padding_top += extra_padding
    for child in box.children:
        child.translate(dy=extra_padding)


def autolabel(rects, ax):
    """Attach a text label above each bar in *rects*, displaying its height"""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width(
            ) / 2, height), xytext=(0, 3), textcoords='offset points', ha=
            'center', va='bottom', color='blue')


def PMC(val):
    """PubMedCentralIdentifier"""
    return val


def getId():
    """ Return the id of the workflow definition.
        """


def is_financial_symbol(dct):
    """
    Helper function for serialization. True if contents
    of dct contains identifier for a FinancialSymbol object.
    """
    return '__financial_symbol__' in dct and dct['__financial_symbol__']


@classmethod
def iter_nice_to_pegasus(cls, nlist):
    """Return an iterator converting a sequence of 5-term nice coordinates
        to 4-term Pegasus coordinates.

        Note that this method does not depend on the size of the Pegasus
        lattice.
        """
    for n in nlist:
        yield cls.nice_to_pegasus(n)


@staticmethod
def _remove_options_parameters(args):
    """
        Removes options parameters.
        Returns a list of argument parameters only.
        """
    tmp_args = args[:]
    for arg in tmp_args:
        if arg.startswith('-'):
            index = tmp_args.index(arg)
            try:
                tmp_args.pop(index)
                tmp_args.pop(index)
            except IndexError:
                pass
            continue
    return tmp_args


def describe_account_limits(NextToken=None):
    """
    Retrieves your account's AWS CloudFormation limits, such as the maximum number of stacks that you can create in your account.
    See also: AWS API Documentation

    :example: response = client.describe_account_limits(
        NextToken='string'
    )

    :type NextToken: string
    :param NextToken: A string that identifies the next page of limits that you want to retrieve.

    :rtype: dict
    :return: {
        'AccountLimits': [
            {
                'Name': 'string',
                'Value': 123
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def xml_check_text_content(xml_doc_a, xml_doc_b, xpath):
    """Check for Text content."""
    if (xml_doc_a.nodeType == xml_doc_a.TEXT_NODE or xml_doc_a.nodeType ==
        xml_doc_a.CDATA_SECTION_NODE):
        if xml_doc_a.data != xml_doc_b.data:
            return False, 'Text Node data differs [%s] != [%s] at [%s]' % (
                xml_doc_a.data, xml_doc_b.data, xpath)
        return True, None
    return None, None


def _to_scala_map(sc, jm):
    """
    Convert a dict into a JVM Map.
    """
    return sc._jvm.PythonUtils.toScalaMap(jm)


def pad_packed_tensor(input, lengths, value, l_min=None):
    """Pads a packed batch of variable length tensors with given value.

    Parameters
    ----------
    input : Tensor
        The input tensor with shape :math:`(N, *)`
    lengths : list or tensor
        The array of tensor lengths (of the first dimension) :math:`L`.
        It should satisfy :math:`\\sum_{i=1}^{B}L_i = N`,
        where :math:`B` is the length of :math:`L`.
    value : float
        The value to fill in the tensor.
    l_min : int or None, defaults to None.
        The minimum length each tensor need to be padded to, if set to None,
        then there is no minimum length requirement.

    Returns
    -------
    Tensor
        The obtained tensor with shape :math:`(B, \\max(\\max_i(L_i), l_{min}), *)`
    """
    pass


def disable_validate_orthogonal():
    """
    Disable the validation whether the volume is orthogonal (so without gantry tilting or alike).
    This allows for converting gantry tilted data.
    The gantry tilting will be reflected in the affine matrix and not in the data
    USE WITH CAUTION!
    """
    global validate_orthogonal
    validate_orthogonal = False


def expireCookie(name, **kw):
    """Causes an HTTP cookie to be removed from the browser

        The response will include an HTTP header that will remove the cookie
        corresponding to "name" on the client, if one exists. This is
        accomplished by sending a new cookie with an expiration date
        that has already passed. Note that some clients require a path
        to be specified - this path must exactly match the path given
        when creating the cookie. The path can be specified as a keyword
        argument.
        If the value of a keyword argument is None, it will be ignored.
        """


def default_receive(diction):
    """
    The default fucntion called when network receives something
    :param diction: dict
    """
    print('MoteinoNetwork received: ' + str(diction) + ' from ' + diction[
        'SenderName'])


def setPersistentStateChanged(obj):
    """
    Explicitly marks a persistent object as changed.
    """
    try:
        obj._p_changed = True
    except AttributeError:
        pass


def env_vars(credentials):
    """Return the environment variables for configuring AWS SDK with the provided credentials"""
    return {'AWS_ACCESS_KEY_ID': credentials.access_key_id,
        'AWS_SECRET_ACCESS_KEY': credentials.secret_access_key,
        'AWS_SESSION_TOKEN': credentials.session_token}


def header_tpl(data):
    """Generates header file to import
    Output:
        #import "XYZUserInfo.h"
    """
    if not data['transform']:
        return None
    if data['transform']['type'] == 'BOOL':
        return None
    if data['class_name'] == 'NSArray':
        name = data['transform']['class']
    else:
        name = data['class_name']
    result = '#import "{}.h"'.format(name)
    return result


@classmethod
def get(cls, project_id, model_id):
    """ Retrieve a specific rating table model

        If the project does not have a rating table, a ClientError will occur.

        Parameters
        ----------
        project_id : str
            the id of the project the model belongs to
        model_id : str
            the id of the model to retrieve

        Returns
        -------
        model : RatingTableModel
            the model
        """
    url = 'projects/{}/ratingTableModels/{}/'.format(project_id, model_id)
    return cls.from_location(url)


def add_node(type: str='', use_transform: bool=False, settings: list=None):
    """Add a node to the active tree

    :param type: Node Type, Node type
    :type type: str
    :param use_transform: Use Transform, Start transform operator after inserting the node
    :type use_transform: bool
    :param settings: Settings, Settings to be applied on the newly created node
    :type settings: list
    """
    pass


def argsort(input, dim, descending):
    """Return the indices that would sort the input along the given dim.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The dim to sort along.
    descending : bool
        Controls the sorting order (False: ascending, True: descending)

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """


def queues(*events):
    """
        ordered mapping of processing queues for `events`

        @param *events: event labels
        """


def list_of_uints_to_uint(list_of_uints, width):
    """
    Convert a list of unsigned integers into a single unsigned integer.

    Args:
        `list_of_uints`: The list of integers.
        `width`: The width of each individual integer.

    >>> # Check that first is the least significant.
    >>> list_of_uints_to_uint(list_of_uints=[1, 0, 0], width=1)
    1
    >>> list_of_uints_to_uint(list_of_uints=[0, 0, 1], width=1)
    4
    >>> # Check for width of 2.
    >>> list_of_uints_to_uint(list_of_uints=[3, 2, 1], width=2)
    27
    """
    if None in list_of_uints:
        output = None
    else:
        output = 0
        f = pow(2, width)
        for v in reversed(list_of_uints):
            assert v < f
            output += v
            output *= f
        output //= f
    return output


@classmethod
def supports(cls, action_name):
    """Test if specified modification action is supported"""
    return action_name in cls.MODIFICATIONS


def get_versions():
    """
        Wait for a valid VERSION message to arrive, then return the peer's
        "versions" dictionary.  This dictionary comes from the ``versions=``
        argument to the peer's ``wormhole()`` constructor, and is meant to
        assist with capability-negotiation between the two peers.  In
        particular, the ``versions`` dictionary is delivered before either
        side has called ``send_message()``, so it can influence the first
        message sent to a peer that is too old to use that first message for
        negotiation purposes.

        If we receive any invalid encrypted message (such as what would
        happen if an attacker tried and failed to guess the wormhole code),
        this will instead errback with a ``WrongPasswordError``.

        :return: the verisions dictionary
        :rtype: ``Deferred[dict]``
        """


def plugins_by_name(pm):
    """
    Organize plugins by plugin name.

    Returns a dict where the key is the plugin name and the value is a list
    of all plugins that have that name.
    """
    plugins = {}
    for plugin in pm.plugins:
        if plugin.name not in plugins:
            plugins[plugin.name] = []
        plugins[plugin.name].append(plugin)
    return plugins


def _get_kind_for_file_id(tree, path, file_id):
    """Return the kind of a file-id or None if it doesn't exist."""
    if file_id is not None:
        return tree.kind(path)
    else:
        return None


def get_float_attr(node, attribute):
    """Cast an element attribute to a float or return None if not present"""
    attr = node.get(attribute)
    return None if attr is None else float(attr)


def mute_toggle():
    """Mute or un-mute selected strips

    """
    pass


def boxlist(s):
    """Boxes, row, and columns to scan."""
    boxlist = []
    for b in range(9):
        begin = [0, 3, 6, 27, 30, 33, 54, 57, 60][b]
        bo = []
        for i in (0, 1, 2, 9, 10, 11, 18, 19, 20):
            if s[begin + i] == 0:
                bo.append(begin + i)
        boxlist.append(bo)
    for i in range(9):
        line = []
        for j in range(9):
            if s[i * 9 + j] == 0:
                line.append(i * 9 + j)
        boxlist.append(line)
    for j in range(9):
        line = []
        for i in range(9):
            if s[i * 9 + j] == 0:
                line.append(i * 9 + j)
        boxlist.append(line)
    return boxlist


def walk_files(root_dir):
    """Iterates under all the files under root_dir, yielding their filepath."""
    import os
    for base_dir, dirs, filenames in os.walk(root_dir):
        for filename in filenames:
            yield os.path.join(base_dir, filename)


def parse_table_settings(s, l, t):
    """
    [headercolor: #cccccc, note: 'note']
    """
    result = {}
    if 'note' in t:
        result['note'] = t['note']
    if 'header_color' in t:
        result['header_color'] = t['header_color']
    return result


def item_activate(extend: bool=True, extend_range: bool=False, deselect_all:
    bool=False):
    """Handle mouse clicks to select and activate items

    :param extend: Extend, Extend selection for activation
    :type extend: bool
    :param extend_range: Extend Range, Select a range from active element
    :type extend_range: bool
    :param deselect_all: Deselect On Nothing, Deselect all when nothing under the cursor
    :type deselect_all: bool
    """
    pass


def search_by(cur, field, query, extent='whole', regexp=False,
    case_sensitive=False, frequent=False):
    """Main search function.  Return list of ent_seqs.

    Field in ('kanji', 'reading', 'gloss').
    Extent in ('whole', 'beginning', 'word', 'partial').
    """
    if regexp:
        operator = 'REGEXP ?'
        if extent == 'whole':
            query = '^' + query + '$'
        elif extent == 'beginning':
            query = '^' + query
        elif extent == 'word':
            query = '\\b' + query + '\\b'
    elif extent == 'word':
        operator = 'MATCH ?'
    else:
        operator = "LIKE ? ESCAPE '\\'"
        query = query.replace('\\', '\\\\')
        query = query.replace('%', '\\%')
        query = query.replace('_', '\\_')
        if extent == 'beginning':
            query = query + '%'
        elif extent == 'partial':
            query = '%' + query + '%'
    if field == 'kanji':
        table = 'kanjis'
        join = 'JOIN kanjis ON entries.ent_seq = kanjis.ent_seq'
    elif field == 'reading':
        table = 'readings'
        join = 'JOIN readings ON entries.ent_seq = readings.ent_seq'
    elif field == 'gloss':
        table = 'glosses'
        join = 'JOIN glosses ON entries.ent_seq = glosses.ent_seq'
    where_extra = ''
    if frequent:
        where_extra += 'AND entries.frequent = 1'
    cur.execute(
        '\nSELECT DISTINCT entries.ent_seq\nFROM entries\n  %s\nWHERE %s.%s %s\n%s\n;'
         % (join, table, field, operator, where_extra), [query])
    res = []
    for row in cur.fetchall():
        res.append(row[0])
    return res


def query_with_limit_offset(query, limit, offset):
    """Add limit and offset constraints to a SQLAlchemy query.

    :param Query query: A SQLAlchemy query.
    :param int limit: The limit to add. If None or 0, it will be skipped.
    :param int offset: The offset to add. If None or 0, it will be skipped.
    :returns Query: The updated query object.
    """
    if limit:
        query = query.limit(limit)
    if offset:
        query = query.offset(offset)
    return query


def val_to_bool(val):
    """Convert a single number to a boolean value."""
    val = str(val).strip().upper()
    try:
        return {'1': True, '1.0': True, 'TRUE': True, 'T': True, 'Y': True,
            'YES': True, '0': False, '0.0': False, 'FALSE': False, 'F':
            False, 'N': False, 'NO': False}[val]
    except KeyError:
        return None


@staticmethod
def get_file_info(codeobj):
    """Returns the file and line number of a code object.

            If the code object has a __file__ attribute (e.g. if
            it is a module), then the returned line number will
            be 0
        """
    fname = getattr(codeobj, '__file__', None)
    linenum = 0
    if fname is None:
        func_code = codeobj.__code__
        fname = func_code.co_filename
        linenum = func_code.co_firstlineno
    fname = fname.replace('.pyc', '.py')
    return fname, linenum


@classmethod
def api_list(cls):
    """
        Returns a URL that will produce a list of JSON objects
        of this class' type
        """
    return '/'.join(cls.api_endpoint.split('/')[:-1])


def bond_to_json(bond):
    """
    Return a JSON representation of `bond`.

    Parameters
    ----------
    bond : :class:`.Bond`
        The bond to serialize.

    Returns
    -------
    :class:`dict`
        A JSON representation of `bond`.

    """
    return bond.get_atom1().get_id(), bond.get_atom2().get_id(
        ), bond.get_order(), bond.get_periodicity()


def enclose_in_double_quote(word):
    """Enclose in duble quote

    >>> enclose_in_double_quote('para meter')
    '"para meter"'
    >>> enclose_in_double_quote('parameter')
    'parameter'
    """
    return '"{}"'.format(word) if ' ' in word else word


def update_typed_link_facet(SchemaArn=None, Name=None, AttributeUpdates=
    None, IdentityAttributeOrder=None):
    """
    Updates a  TypedLinkFacet . For more information, see Typed link .
    See also: AWS API Documentation

    :example: response = client.update_typed_link_facet(
        SchemaArn='string',
        Name='string',
        AttributeUpdates=[
            {
                'Attribute': {
                    'Name': 'string',
                    'Type': 'STRING'|'BINARY'|'BOOLEAN'|'NUMBER'|'DATETIME',
                    'DefaultValue': {
                        'StringValue': 'string',
                        'BinaryValue': b'bytes',
                        'BooleanValue': True|False,
                        'NumberValue': 'string',
                        'DatetimeValue': datetime(2015, 1, 1)
                    },
                    'IsImmutable': True|False,
                    'Rules': {
                        'string': {
                            'Type': 'BINARY_LENGTH'|'NUMBER_COMPARISON'|'STRING_FROM_SET'|'STRING_LENGTH',
                            'Parameters': {
                                'string': 'string'
                            }
                        }
                    },
                    'RequiredBehavior': 'REQUIRED_ALWAYS'|'NOT_REQUIRED'
                },
                'Action': 'CREATE_OR_UPDATE'|'DELETE'
            },
        ],
        IdentityAttributeOrder=[
            'string',
        ]
    )

    :type SchemaArn: string
    :param SchemaArn: [REQUIRED]
            The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns .

    :type Name: string
    :param Name: [REQUIRED]
            The unique name of the typed link facet.

    :type AttributeUpdates: list
    :param AttributeUpdates: [REQUIRED]
            Attributes update structure.
            (dict) --A typed link facet attribute update.
            Attribute (dict) -- [REQUIRED]The attribute to update.
            Name (string) -- [REQUIRED]The unique name of the typed link attribute.
            Type (string) -- [REQUIRED]The type of the attribute.
            DefaultValue (dict) --The default value of the attribute (if configured).
            StringValue (string) --A string data value.
            BinaryValue (bytes) --A binary data value.
            BooleanValue (boolean) --A Boolean data value.
            NumberValue (string) --A number data value.
            DatetimeValue (datetime) --A date and time value.
            IsImmutable (boolean) --Whether the attribute is mutable or not.
            Rules (dict) --Validation rules that are attached to the attribute definition.
            (string) --
            (dict) --Contains an Amazon Resource Name (ARN) and parameters that are associated with the rule.
            Type (string) --The type of attribute validation rule.
            Parameters (dict) --The minimum and maximum parameters that are associated with the rule.
            (string) --
            (string) --

            RequiredBehavior (string) -- [REQUIRED]The required behavior of the TypedLinkAttributeDefinition .
            Action (string) -- [REQUIRED]The action to perform when updating the attribute.

    :type IdentityAttributeOrder: list
    :param IdentityAttributeOrder: [REQUIRED]
            A range filter that you provide for multiple attributes. The ability to filter typed links considers the order that the attributes are defined on the typed link facet. When providing ranges to a typed link selection, any inexact ranges must be specified at the end. Any attributes that do not have a range specified are presumed to match the entire range. Filters are interpreted in the order of the attributes on the typed link facet, not the order in which they are supplied to any API calls.
            (string) --

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


@staticmethod
def get_br_key_with_new_link(br_key, new_bit_pos, new_kind):
    """
        Say new_bit_pos=2 and new_kind=True. This returns a new branch key
        with '2T' added to the end of the string br_key

        Parameters
        ----------
        br_key : str
        new_bit_pos : int
        new_kind : bool

        Returns
        -------
        str

        """
    x = str(new_bit_pos) + ('T' if new_kind else 'F')
    if br_key == 'pure':
        new_br_key = x
    else:
        new_br_key = br_key + x
    return new_br_key


def parse_zipcode(zipcode):
    """
    Take a zipcode and returns a split out zipcode and the +4 for the post office.

    :param zipcode: Zipcode
    :return: zipcode, zipcodeplus
    """
    zipcode = str(zipcode)
    plus = None
    if len(str(zipcode)) == 9:
        try:
            plus = int(zipcode[5:])
        except ValueError:
            plus = 0
        zipcode = zipcode[:5]
    try:
        zipcode = int(zipcode)
    except ValueError:
        return None, None
    return zipcode, plus


def data_type_dict():
    """Returns a dictionary from data type string to the data type.

    The dictionary should include at least:
    float16
    float32
    float64
    uint8
    int8
    int16
    int32
    int64

    This function will be called only *once* during the initialization fo the
    backend module. The returned dictionary will become the attributes of the
    backend module.

    Examples
    --------
    >>> import torch as th
    >>> def data_type_dict():
    >>>   return { 'float16' : th.float16, 'float32' : th.float32, ... }

    After the module is initialized.

    >>> import backend as F
    >>> F.float16  # this will point to torch.float16

    Returns
    -------
    dict of str to data type
        The data type dict.
    """
    pass


def escape_markup(text):
    """
    Escape markup characters found in the text. Intended to be used when markup
    text is activated on the Label::

        untrusted_text = escape_markup('Look at the example [1]')
        text = '[color=ff0000]' + untrusted_text + '[/color]'
        w = Label(text=text, markup=True)

    .. versionadded:: 1.3.0
    """
    return text.replace('&', '&').replace('[', '&bl;').replace(']', '&br;')


def reduce_func(nodes):
    """Collect messages and update node representations.

    Parameters
    ----------
    nodes : NodeBatch
        A batch of nodes.

    Returns
    -------
    dict mapping 'hv_new' to Float32 tensor of shape (V, K * T)
        Updated node representations. V for the number of nodes, K for the number of
        radial filters and T for the number of features to use
        (types of atomic number in the paper).
    """
    return {'hv_new': nodes.mailbox['m'].sum(1)}


def get_callable_name(c):
    """ Get a human-friendly name for the given callable.

    :param c: The callable to get the name for
    :type c: callable
    :rtype: unicode
    """
    if hasattr(c, 'name'):
        return str(c.name)
    elif hasattr(c, '__name__'):
        return str(c.__name__) + u'()'
    else:
        return str(c)


def render(navigate, crumbsmenu, **kwargs):
    """Generate and return HTML for breadcrumb widget.

        ``navigate``,
            List of tuples (name, url) providing the name of the bread-crumb
            and optional url.

        ``breadmenu``,
            Map of breadcrumb name, provided in ``navigate`` attribute, and a
            list of tuple (name, url). Each tuple is rendered as a menu-item.

        Optional keyword arguments,

        ``id``,
            If specified will be used as **id** attribute for the widget node.
        """


def nq_random_player(bot, state):
    """ Not-Quite-RandomPlayer that will move randomly but not stop or reverse. """
    legal_positions = bot.legal_positions[:]
    try:
        legal_positions.remove(bot.position)
    except ValueError:
        pass
    if len(legal_positions) > 1:
        if len(bot.track) >= 2:
            try:
                legal_positions.remove(bot.track[-2])
            except ValueError:
                pass
    if not legal_positions:
        return bot.position, state
    return bot.random.choice(legal_positions), state


def findRelationships(source=None, target=None, maxDepth=1, filter=None):
    """given source, target, or both, iterate over all relationship paths.

        maxDepth is the number of relationships through which the search
        should walk transitively.  It must be a positive integer.

        filter is an optional callable that takes a relationship and returns
        a boolean True value if it should be included, and a False if not.

        If a cycle is found, it is omitted by default.  if includeCycles is
        True, it returns the cycle in an ICircularRelationshipPath and then
        does not continue down the cycle.
        """


def _comparator_presence(_, tested_value):
    """
    Tests a filter which simply a joker, i.e. a value presence test
    """
    if tested_value is None:
        return False
    elif hasattr(tested_value, '__len__'):
        return len(tested_value) != 0
    return True


def attach_static_ip(staticIpName=None, instanceName=None):
    """
    Attaches a static IP address to a specific Amazon Lightsail instance.
    See also: AWS API Documentation

    :example: response = client.attach_static_ip(
        staticIpName='string',
        instanceName='string'
    )

    :type staticIpName: string
    :param staticIpName: [REQUIRED]
            The name of the static IP.

    :type instanceName: string
    :param instanceName: [REQUIRED]
            The instance name to which you want to attach the static IP address.

    :rtype: dict
    :return: {
        'operations': [
            {
                'id': 'string',
                'resourceName': 'string',
                'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
                'createdAt': datetime(2015, 1, 1),
                'location': {
                    'availabilityZone': 'string',
                    'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
                },
                'isTerminal': True|False,
                'operationDetails': 'string',
                'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
                'status': 'NotStarted'|'Started'|'Failed'|'Completed',
                'statusChangedAt': datetime(2015, 1, 1),
                'errorCode': 'string',
                'errorDetails': 'string'
            },
        ]
    }

    """
    pass


@classmethod
def get_type_name_ns(cls, interface):
    """Returns the type name with a namespace prefix, separated by a column.
        """
    if cls.get_namespace() != None:
        return '%s:%s' % (cls.get_namespace_prefix(interface), cls.
            get_type_name())


def weld():
    """Weld selected UV vertices together

    """
    pass


@classmethod
def make_traditional_coupler_at_port(cls, port, **kwargs):
    """
        Make a traditional coupler at a port.

        This function is identical to :func:`make_traditional_coupler`. Parameters of the port
        can also be overwritten via keyword arguments.

        :param port: The port at which the coupler shall be created.
        :type port: Port
        :param kwargs: Keyword arguments passed to :func:`make_traditional_coupler`.
        :return: The constructed traditional grating coupler.
        :rtype: GratingCoupler
        """
    if 'width' not in kwargs:
        kwargs['width'] = port.width
    if 'origin' not in kwargs:
        kwargs['origin'] = port.origin
    if 'angle' not in kwargs:
        kwargs['angle'] = port.angle
    return cls.make_traditional_coupler(**kwargs)


def max(input, dim):
    """Reduce max the input tensor along the given dim.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The reduce dim.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


@classmethod
def aggregate(cls, columns, kdims, function, **kwargs):
    """
        Aggregation currently not implemented.
        """
    raise NotImplementedError


@classmethod
def new(cls, values=None):
    """Create a new session for the transaction user and return the key."""
    if values is None:
        values = {}
    session, = cls.create([values])
    return session.key


@staticmethod
def get_logs_info(defaults):
    """Get the logs prefix and group names"""
    log_config = defaults['taskDefinition']['containerDefinitions'][0][
        'logConfiguration']
    logs_stream_prefix = log_config['options']['awslogs-stream-prefix']
    logs_group = log_config['options']['awslogs-group']
    return logs_stream_prefix, logs_group


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def changeByOne(coords):
    """
    Changes coordinates by 1 on the x axis (to move the plane forward 1)
    """
    for i in range(0, len(coords)):
        coords[i][0] = coords[i][0] + 1
    return coords


def do_express_checkout_payment(token, **kwargs):
    """ DoExpressCheckoutPayment """


def t_SITE_OPTION_SPACE(t):
    """site-option-space"""
    return t


def provider_parser(subparser):
    """Return the parser for this provider"""
    subparser.add_argument('--auth-password', help=
        'specify password for authentication (or login key for two-factor authentication)'
        )
    subparser.add_argument('--auth-username', help=
        'specify username for authentication')
    subparser.add_argument('--endpoint', help=
        'specify the DirectAdmin endpoint')


@staticmethod
def from_jacobian(jacobian_point):
    """ Converts from a Jacobian point to an affine representation.

        Args:
            jacobian_point (ECPointJacobian): The Jacobian point to convert.

        Returns:
            ECPointAffine: The affine representation.
        """
    return jacobian_point.to_affine()


def convert_to_codec_key(value):
    """
    Normalize code key value (encoding codecs must be lower case and must
    not contain any dashes).

    :param value: value to convert.
    """
    if not value:
        value = 'UTF-8'
    converted = value.replace('-', '_').lower()
    all_aliases = {'ascii': ['us_ascii', 'us', 'ansi_x3.4_1968', 'cp367',
        'csascii', 'ibm367', 'iso_ir_6', 'iso646_us', 'iso_646.irv:1991'],
        'utf-7': ['csunicode11utf7', 'unicode_1_1_utf_7',
        'unicode_2_0_utf_7', 'x_unicode_1_1_utf_7', 'x_unicode_2_0_utf_7'],
        'utf_8': ['unicode_1_1_utf_8', 'unicode_2_0_utf_8',
        'x_unicode_1_1_utf_8', 'x_unicode_2_0_utf_8'], 'utf_16': [
        'utf_16le', 'ucs_2', 'unicode', 'iso_10646_ucs2'], 'latin_1': [
        'iso_8859_1']}
    for key, aliases in all_aliases.items():
        if converted in aliases:
            return key
    return converted


@staticmethod
def swagger(result_schema):
    """
        given the schema of the inner
        result object, return back the
        swagger schema representation.
        """
    return result_schema


def cells_to_cellparm(ps):
    """Takes a list of `xds_parser` instances and writes the cell parameters to
    an instruction file `CELLPARM.INP` for the program `cellparm`."""
    with open('CELLPARM.INP', 'w') as f:
        for i, p in enumerate(ps):
            fn = p.filename
            cell = p.unit_cell
            ntot = p.d['total']['ntot']
            print(f'! {i: 3d} from {fn}', file=f)
            print(
                'UNIT_CELL_CONSTANTS= {:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f} WEIGHT= {ntot}'
                .format(*cell, ntot=ntot), file=f)


def formatDollarsCents(d, noneValue='', zeroValue='$0.00'):
    """Formats a number as a dollar and cent value with alternatives for None and 0."""
    if d is None:
        return noneValue
    elif d == 0:
        return zeroValue
    return '${:.2f}'.format(d)


def checklist_finder(frame_list, flight_number, date):
    """This automatically returns the relevant information for a given flight
    number."""
    b = 0
    for frame in frame_list:
        for column in frame.columns:
            if 'Checklist' in column:
                b = 1
                break
        if b != 0:
            break
    checklist_frame = frame
    for column in checklist_frame.columns:
        if 'flight number' in column.lower():
            flight_number_column = column
            break
    flight_number = float(flight_number)
    flight_number_filtered = checklist_frame[checklist_frame[
        flight_number_column] == flight_number]
    index = flight_number_filtered.index.values.tolist()
    times = flight_number_filtered[flight_number_filtered.columns[2]].tolist()
    rows = []
    for a in range(len(index)):
        if str(times[a]).split(' ')[0].replace('-', '') == str(date):
            rows.append(index[a])
    filtered_frame = flight_number_filtered[flight_number_filtered.index.
        isin(rows)]
    return filtered_frame


def argmax(attrs, inputs, cls):
    """Returns indices of the maximum values along an axis"""
    return 'argmax', attrs, inputs


def sql_list(val):
    """converts list or tuple into sql format list for 'is in' etc."""
    return len(val) == 1 and '(%s)' % repr(val[0]) or tuple(val)


@classmethod
def _is_dynamic(cls, name):
    """Check if method has been added dynamically.

        Args:
            name (str): The name of the method.

        Returns:
            (bool) True if the method has been added dynamically, false otherwise.
        """
    return name.startswith(cls.dynamic_prefix)


def int_to_charset(val, charset):
    """ Turn a non-negative integer into a string.

    >>> int_to_charset(0, B40_CHARS)
    '0'
    >>> int_to_charset(658093, B40_CHARS)
    'abcd'
    >>> int_to_charset(40, B40_CHARS)
    '10'
    >>> int_to_charset(149190078205533, B40_CHARS)
    'muneeb.id'
    >>> int_to_charset(-1, B40_CHARS)
    Traceback (most recent call last):
        ...
    ValueError: "val" must be a non-negative integer.
    """
    if val < 0:
        raise ValueError('"val" must be a non-negative integer.')
    if val == 0:
        return charset[0]
    output = ''
    while val > 0:
        val, digit = divmod(val, len(charset))
        output += charset[digit]
    return output[::-1]


def obj_or_id(parameter, param_name, object_types):
    """
    Accepts either an int (or long or str representation of an integer)
    or an object. If it is an int, return it. If it is an object and
    the object is of correct type, return the object's id. Otherwise,
    throw an exception.

    :param parameter: int, str, long, or object
    :param param_name: str
    :param object_types: tuple
    :rtype: int
    """
    from canvasapi.user import User
    try:
        return int(parameter)
    except (ValueError, TypeError):
        if User in object_types and parameter == 'self':
            return parameter
        for obj_type in object_types:
            if isinstance(parameter, obj_type):
                try:
                    return int(parameter.id)
                except Exception:
                    break
        obj_type_list = ','.join([obj_type.__name__ for obj_type in
            object_types])
        message = 'Parameter {} must be of type {} or int.'.format(param_name,
            obj_type_list)
        raise TypeError(message)


def _quadratic_bf(x):
    """
    Quadratic base-function for the model_objective

    Can't be a lambda because of parallelization
    :param x: x
    :return: (1-x)**2
    """
    return (1 - x) ** 2


def normalized_error(value_1, value_2, uncertainty, expansion_factor=1):
    """normalized error returns the  scalar normalized error (delta value/ (expansion_factor*uncertainty))"""
    return (value_2 - value_1) / (uncertainty * expansion_factor)


def parse_debug_value(value):
    """Resolve the given string value to a debug option.

    Can be used to deal with os environment variables, for example.
    """
    if value is None:
        return value
    value = value.lower()
    if value in ('true', '1'):
        return True
    elif value in ('false', '0'):
        return False
    elif value in ('merge',):
        return 'merge'
    else:
        raise ValueError()


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

        :param SharedLinkViewDetails val:
        :rtype: EventDetails
        """
    return cls('shared_link_view_details', val)


def map_get_values(map, key):
    """
    Retrieves the value of the map for the given key.
    The value is validated for type and in case it's not
    a list a list is created with the value.
    This way the method return value is always a list
    independently from the type of the original value.

    :type map: Dictionary
    :param map: The dictionary to be used.
    :type key: String
    :param key: The key to the value(s) to be retrieved.
    :rtype: List
    :return: The values(s) for the key.
    """
    values = map.get(key, [])
    values_type = type(values)
    if not values_type == list:
        values = [values]
    return values


def lineage(resource):
    """Yields the resource's lineage up to the root.

    This is a copy of Pyramid's lineage function to reduce dependencies.
    It assumes that parent resources are correctly set (which kalpa does).
    """
    while resource is not None:
        yield resource
        resource = resource.__parent__


def borate_LKB10(Sal):
    """Total borate in mol/kg-sw following LKB10."""
    return 0.0004326 * Sal / 35


def psi_H_Na_Cl_HMW84(T, P):
    """c-c'-a: hydrogen sodium chloride [HMW84]."""
    psi = -0.004
    valid = T == 298.15
    return psi, valid


def get_pyfile_header(pyfile):
    """
    Obtiene el nombre del fichero

    :param str pyfile: nombre completo de la ruta del fichero ``.py``
    :return: nombre del fichero
    :rtype: str

    .. code-block:: python

        >> get_pyfile_header('../a/c.py')
        'c'

    """
    return pyfile.split('.')[-1]


def show():
    """Removes all status messages and returns them for display.
        """


@staticmethod
def unzip_hints(rv):
    """Separate a list of (node, hints) into separate arrays."""
    rv = list(rv)
    if not rv:
        return [], []
    nodes, hints = zip(*rv)
    return list(nodes), list(hints)


def add121(x, y, z):
    """Add 3 numbers by weights of 1:2:1, i.e., x+2*y+z.

    :returns: the added number, x+2*y+z
    """
    return x + y + y + z


def get_fmt_results(results, limit=5, sep='::', fmt=None):
    """
    Return a list of formatted strings representation on a result dictionary.
    The elements of the key are divided by a separator string. The result is
    appended after the key between parentheses. Apply a format transformation
    to odd elements of the key if a fmt parameter is passed.
    """
    result_list = []
    for key in sorted(results, key=lambda x: results[x], reverse=True):
        if len(result_list) >= limit and results[key] <= 1:
            break
        if fmt is not None:
            fmtkey = []
            for i in range(len(key)):
                if i % 2 == 1:
                    fmtkey.append(fmt.format(key[i]))
                else:
                    fmtkey.append(key[i])
            result_list.append(u'{0}({1})'.format(sep.join(fmtkey), results
                [key]))
        else:
            result_list.append(u'{0}({1})'.format(sep.join(key), results[key]))
    else:
        return result_list
    if fmt is not None:
        result_list.append(fmt.format(u'[%d more skipped]' % (len(results) -
            len(result_list))))
    else:
        result_list.append(u'[%d more skipped]' % (len(results) - len(
            result_list)))
    return result_list


def createGeneToAabrhD(aabrhHardCoreL):
    """Create a dict where key corresponds to gene number and the
value at that location is the number of the aabrh group to which the
gene belongs. The aabrh groups are numbered, simply based on
the index where they occur in aabrhHardCoreL."""
    geneToAabrhD = {}
    for aabrhNum in range(len(aabrhHardCoreL)):
        for geneNum in aabrhHardCoreL[aabrhNum]:
            geneToAabrhD[geneNum] = aabrhNum
    return geneToAabrhD


def poll():
    """Called periodically to poll for projects"""


def insert_into_string(string, new_string, i):
    """Insert `new_string` into `string` at index `i`

    :type string: str
    :type new_string: str
    :type i: int
    :rtype: str
    """
    return string[:i] + new_string + string[i:]


def receive_v2_membership_report(group_state: 'GroupState'):
    """
    Received IGMP Membership Report packet regarding group GroupState
    """
    group_state.group_state_logger.debug(
        'Querier MembersPresent: receive_v2_membership_report')
    group_state.set_timer()


def per_device_batch_size(batch_size, num_gpus):
    """For multi-gpu, batch-size must be a multiple of the number of GPUs.
  Note that this should eventually be handled by DistributionStrategies
  directly. Multi-GPU support is currently experimental, however,
  so doing the work here until that feature is in place.
  Args:
    batch_size: Global batch size to be divided among devices. This should be
      equal to num_gpus times the single-GPU batch_size for multi-gpu training.
    num_gpus: How many GPUs are used with DistributionStrategies.
  Returns:
    Batch size per device.
  Raises:
    ValueError: if batch_size is not divisible by number of devices
  """
    if num_gpus <= 1:
        return batch_size
    remainder = batch_size % num_gpus
    if remainder:
        err = (
            'When running with multiple GPUs, batch size must be a multiple of the number of available GPUs. Found {} GPUs with a batch size of {}; try --batch_size={} instead.'
            .format(num_gpus, batch_size, batch_size - remainder))
        raise ValueError(err)
    return int(batch_size / num_gpus)


def delete_object(DirectoryArn=None, ObjectReference=None):
    """
    Deletes an object and its associated attributes. Only objects with no children and no parents can be deleted.
    See also: AWS API Documentation

    :example: response = client.delete_object(
        DirectoryArn='string',
        ObjectReference={
            'Selector': 'string'
        }
    )

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

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

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


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


def mapparms(old, new):
    """
    Linear map parameters between domains.

    Return the parameters of the linear map ``offset + scale*x`` that maps
    `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``.

    Parameters
    ----------
    old, new : array_like
        Domains. Each domain must (successfully) convert to a 1-d array
        containing precisely two values.

    Returns
    -------
    offset, scale : scalars
        The map ``L(x) = offset + scale*x`` maps the first domain to the
        second.

    See Also
    --------
    getdomain, mapdomain

    Notes
    -----
    Also works for complex numbers, and thus can be used to calculate the
    parameters required to map any line in the complex plane to any other
    line therein.

    Examples
    --------
    >>> from numpy.polynomial import polyutils as pu
    >>> pu.mapparms((-1,1),(-1,1))
    (0.0, 1.0)
    >>> pu.mapparms((1,-1),(-1,1))
    (-0.0, -1.0)
    >>> i = complex(0,1)
    >>> pu.mapparms((-i,-1),(1,i))
    ((1+1j), (1-0j))

    """
    oldlen = old[1] - old[0]
    newlen = new[1] - new[0]
    off = (old[1] * new[0] - old[0] * new[1]) / oldlen
    scl = newlen / oldlen
    return off, scl


def is_auto_field(field):
    """
    Test if a given field is an Auto-Field.

    :param DjangoField field: A reference to the given field.
    :rtype: boolean
    :returns:
        A boolean value that's true only if the given field is an Auto-Field.
    """
    return field.name == 'id' or hasattr(field, 'get_internal_type'
        ) and field.get_internal_type() == 'AutoField'


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


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def has_end_punc(text):
    """
    Determine whether the line ends with certain punctuations.
    If `True`, the line ends with other characters.
    """
    end = text.strip()[-1]
    punc = ['：', ';', '。', '？', '！', '；', '”', '）', '']
    if end not in punc:
        return True
    return False


def _prepareTime(time):
    """Get time in the proper shape
    ex : 174512 for 17h 45m 12s
    ex : 094023 for 09h 40m 23s"""
    time = str(time)
    time = '000000' + time
    time = time[len(time) - 6:]
    return time


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

    The ".dev0" means dirty.

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


@classmethod
def _latest_partition_from_df(cls, df):
    """Hive partitions look like ds={partition name}"""
    return df.ix[:, (0)].max().split('=')[1]


def get_unique_field_names(model):
    """
    Return all of the fields with "unique=True" for the model
    """
    fields = []
    for field in model._meta.fields:
        if field.unique:
            fields.append(field.name)
    return fields


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

        :param GroupAddMemberDetails val:
        :rtype: EventDetails
        """
    return cls('group_add_member_details', val)


@classmethod
def has_archiving(cls):
    """Returns whether it supports archiving items on the fetch process.

        :returns: this backend supports items archive
        """
    return True


def _getAction(subAssignments):
    """
	Given a group of assignments with same odID, find if this group is stationary/vertical/move.  Each will be treated differently in cesium and folium.

	Parameters
	----------
	subAssignments: :ref:`Assignments`
		An assignment dataframe with the same odID

	Return
	------
	string
		An enumerate string, out put can be 'stationary'/'vertical'/'move'
	"""
    if len(subAssignments) == 1:
        if subAssignments.iloc[0]['startLat'] == subAssignments.iloc[0][
            'endLat'] and subAssignments.iloc[0]['startLon'
            ] == subAssignments.iloc[0]['endLon'] and subAssignments.iloc[0][
            'startAltMeters'] == subAssignments.iloc[0]['endAltMeters']:
            action = 'stationary'
        elif subAssignments.iloc[0]['startLat'] == subAssignments.iloc[0][
            'endLat'] and subAssignments.iloc[0]['startLon'
            ] == subAssignments.iloc[0]['endLon'] and subAssignments.iloc[0][
            'startAltMeters'] != subAssignments.iloc[0]['endAltMeters']:
            action = 'vertical'
        else:
            action = 'move'
    else:
        action = 'move'
    return action


def equivilence(iterator, func):
    """
    Divides an iterator to groups, based on the function's result of every item in the iterator.
    Returns dict of lists.

    Example:
        >>> equivilence(range(10), lambda x: x % 3)
        >>>out>>> {0: [0, 3, 6, 9],
        >>>out>>>  1: [1, 4, 7],
        >>>out>>>  2: [2, 5, 8]}

    :param iterator: an iterator you wish to run on and divide into groups
    :type iterator: iterator
    :param func: a function to activate on each iterator item - its result decides the return dict's keys.
    :type func: function

    :rtype: dict of lists (lists are groups of original iterator)
    """
    return_dict = {}
    for item in iterator:
        return_dict.setdefault(func(item), []).append(item)
    return return_dict


def _jmomentsurfaceIntegrand(vz, vR, vT, R, z, df, sigmaR1, gamma, sigmaz1,
    n, m, o):
    """Internal function that is the integrand for the vmomentsurface mass integration"""
    return df(R, vR * sigmaR1, vT * sigmaR1 * gamma, z, vz * sigmaz1,
        use_physical=False, func=lambda x, y, z: x ** n * y ** m * z ** o)


def get_orig_function(f):
    """ Make use of the __wrapped__ attribute to find the original function
        of a decorated function. """
    try:
        while True:
            f = f.__wrapped__
    except AttributeError:
        return f


def generic_find_uq_constraint_name(table, columns, insp):
    """Utility to find a unique constraint name in alembic migrations"""
    for uq in insp.get_unique_constraints(table):
        if columns == set(uq['column_names']):
            return uq['name']


def total_seconds(delta):
    """Determines total seconds with python < 2.7 compat."""
    return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) *
        1000000.0) / 1000000.0


@classmethod
def _dynamo_to_python_attr(cls, dynamo_key):
    """
        Convert a DynamoDB attribute name to the internal Python name.

        This covers cases where an attribute name has been overridden via "attr_name".
        """
    return cls._dynamo_to_python_attrs.get(dynamo_key, dynamo_key)


def cherche_operateur(calcul, index):
    """**cherche_operateur**\\ (*calcul*\\ , *min_i*)

    Recherche le premier opérateur +, -, \\*, /, ^ dans la chaîne calcul à une position
    supérieure ou égale à min_i, sans expression régulière.

    :param calcul: le calcul à tester
    :type calcul: string
    :param min_i: position à partir de laquelle effectuer le test
    :type min_i: integer

    >>> from pyromaths.outils import Priorites3
    >>> Priorites3.cherche_operateur('-Polynome([[-4, 2]], "x")*6**2+3', 1)
    -
    >>> p = '-6*(-11)*(-5)'
    >>> Priorites3.cherche_operateur(p, 1)
    *
    >>> Priorites3.cherche_operateur(p, 0)
    -

    :rtype: string
    """
    operateur = ['**', '+', '-', '*', '/', '^']
    l = []
    for op in operateur:
        try:
            l.append(calcul[index:].index(op) + index)
        except:
            l.append(None)
    min_i = 0
    for i in range(1, len(l)):
        if l[i] is not None and (l[min_i] is None or l[i] < l[min_i]):
            min_i = i
    if l[min_i] != None:
        return operateur[min_i]
    else:
        return None


@staticmethod
def _count(column, df, value):
    """return the number of records in the DataFrame's column with a specific value"""
    return df.loc[df[column] == value, column].count()


def item(data, feed=None, service=None):
    """
    Format an text section page for a feed subscription using data found in
    its Opml feed entry and in its Rss file.

    @param data: Opml data
    @type data: dict
    @param feed: Rss data. Default dict.
    @type feed: dict
    @param service: Intialized soovee.regex object. Default None.
    @type service: obj
    @return:
    @rtype: basestring
    @raise TypeError: data or feed passed was not a dict
    """
    if not isinstance(data, dict) and not isinstance(feed, dict):
        raise TypeError('FormsItem missing dictionaries.')
    from soovee_lib.txtwrap import wraptext
    page = ['=' * 80, '\n'.join(wraptext('FEED TITLE: %s' % service.
        PRETITLE.sub('', data['title']))), '\n'.join(wraptext(
        'FEED PAGE: %s ' % data['htmlUrl']))]
    for episode in feed['eps']:
        audiofile = '%s (%.2f MB)' % (episode['title'], service.TOMB(
            episode['enclosure']['length']))
        subpage = ['\n'.join(wraptext('EPISODE AUDIOFILE: %s' % audiofile, 4))]
        page.append('\n'.join(subpage))
    return '\n'.join(page)


@classmethod
def join(cls, *names):
    """Join string components of key with supported separator."""
    return cls.SEPARATOR.join(names)


def UernPremRate():
    """Unearned Premium Rate"""
    return None


@classmethod
def get_connection_type(cls):
    """Return the connection backend used as string.

        Can be local, paramiko, ssh, docker, salt or ansible
        """
    return cls.NAME


def findNext(v, pos, pattern, bodyFlag=1):
    """
	findNext:	use string.find() to find a pattern in a Leo outline.

	v	 		the vnode to start the search.
	pos			the position within the body text of v to start the search.
	pattern		the search string.
	bodyFlag	true: search body text.  false: search headline text.

	returns a tuple (v,pos) showing where the match occured.
	returns (None,0) if no further match in the outline was found.

	Note: if (v,pos) is a tuple returned previously from findNext,
	findNext(v,pos+len(pattern),pattern) finds the next match.
	"""
    while v != None:
        if bodyFlag:
            s = v.bodyString()
        else:
            s = v.headString()
        pos = s.find(pattern, pos)
        if pos != -1:
            return v, pos
        v = v.threadNext()
        pos = 0
    return None, 0


def set_cache(cache, old_cache):
    """
    Use ``cache`` as the new cache for all open requests.
    Copies keys from old cache, and deletes them from the old cache.
    """
    for key in list(old_cache.keys()):
        cache[key] = old_cache[key]
        del old_cache[key]
    return cache


@classmethod
def from_pixel(cls, value):
    """Create RGB value from pillow getpixel() return value."""
    if isinstance(value, tuple):
        red, green, blue = value[:3]
    else:
        red, green, blue = [value] * 3
    return cls(red, green, blue)