def ordinalformat(number: int) ->str:
    """Convert a :class:`int` to the corresponding English ordinal :class:`str`.

    Parameters:
        number: the number to convert.

    Returns:
        The corresponding English `ordinal numeral <https://en.wikipedia.org/wiki/Ordinal_numeral>`_.

    Examples:
        ::

            >>> ordinalformat(1)
            "1st"
            >>> ordinalformat(2)
            "2nd"
            >>> ordinalformat(11)
            "11th"
            >>> ordinalformat(101)
            "101st"
            >>> ordinalformat(112)
            "112th"
            >>> ordinalformat(0)
            "0th"
    """
    if 10 <= number % 100 < 20:
        return f'{number}th'
    if number % 10 == 1:
        return f'{number}st'
    elif number % 10 == 2:
        return f'{number}nd'
    elif number % 10 == 3:
        return f'{number}rd'
    return f'{number}th'


def set_file_storage(source='local', **kwargs):
    """ Creates file storage depending

    Parameters
    ----------
    source: str
        Default is 'local' which will create
        file storage in the local environment
    kwargs: dict
        Contains data to setup S3 storage
    """
    pass


def validate_signature_ser(sig):
    """Checks that the serialized signature is a valid byte string.
    Args:
        seckey  (bytes):        signature
    Returns:
        (True):                 if sig is valid, otherwise error
    """
    if not isinstance(sig, bytes):
        raise ValueError('Invalid signature. Must be bytes.')
    return True


@staticmethod
def _linear_ranking(count, worst):
    """
        This applies the best and worst factors and assigns the selection
        probability to each rank.

        This returns a list of those probabilities.

        """
    best = 2.0 - worst
    scale_list = []
    i = 1.0
    count = float(count)
    while i < count + 1.0:
        value = worst + (best - worst) * (i - 1.0) / (count - 1.0)
        value /= count
        scale_list.append(value)
        i += 1.0
    return scale_list


@classmethod
def scopes(cls):
    """
        Return a list of valid/understood class scopes.
        Why do we need this? I believe it is not used anywhere.
        """
    return [cls.NONE, cls.ONE, cls.ALL]


def interleave(list1, list2, list1_start=0, list2_start=0, 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
      step: number of items to return before switching lists

    Returns:
      list item: current item in list

    Links:"""
    if len(list1) != len(list2):
        raise StopIteration
    length1 = len(list1)
    length2 = len(list2)
    length = min(length1, length2)
    list1_pos = list1_start
    list2_pos = list2_start
    for pos in range(0, length, step):
        for i in range(0, step):
            if list1_pos >= length1:
                list1_pos = 0
            yield list1[list1_pos]
            list1_pos += 1
        for i in range(0, step):
            if list2_pos >= length2:
                list2_pos = 0
            yield list2[list2_pos]
            list2_pos += 1


def parametersDicFull(parameters):
    """
    Build a dictionary from list of parameters.
    """
    dic = {}
    for p in parameters:
        dic[p[0]] = {'description': p[1], 'unit': p[2], 'default': p[3]}
    return dic


def bin_edges_to_centres(edges):
    """
    Translates edges of histogram bins to bin centres.
    """
    if edges.ndim == 1:
        steps = (edges[1:] - edges[:-1]) / 2
        return edges[:-1] + steps
    else:
        steps = (edges[1:, 1:] - edges[:-1, :-1]) / 2
        centres = edges[:-1, :-1] + steps
        return centres


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['source']
    if type == 'DB_BACKUP':
        return 'CreateDbHomeWithDbSystemIdFromBackupDetails'
    if type == 'NONE':
        return 'CreateDbHomeWithDbSystemIdDetails'
    if type == 'VM_CLUSTER_NEW':
        return 'CreateDbHomeWithVmClusterIdDetails'
    else:
        return 'CreateDbHomeBase'


@classmethod
def _validate_source_list(cls, source_list):
    """
        The "special" source values of 'self', 'unsafe-inline', 'unsafe-eval', and 'none'
        must be quoted! "'self'". Without quotes they will not work as intended.
        http://django-csp.readthedocs.org/en/latest/configuration.html

        This is slightly stricter than the W3 spec, in that it disallows sources with the same
        name as any of the reserved_source_expressions (eg. if self or none resolved to a
        server). Conversely, it stops the user adding a non-functional, un-quoted source.

        In the final string:
            Legal:   " 'self';", " 'self' "
            Illegal: " self;",   " self "

        @param value: list of source values, each of which will be checked
        """
    msg = (
        "You included a special value in your CSP, but did not wrap it in quotes. eg. %s should be '%s'"
        )
    for v in cls.unquoted_reserved_source_expressions:
        if v in source_list:
            raise ValueError(msg % (v, v))
    return source_list


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


def eval(this, vec):
    """A functional representation of the fit"""
    ans_ = 0
    for k, b in enumerate(this.coeffs):
        ans_ += b * this.symeval(this.basis_symbols[k], dom=vec)
    V = this.range_map['backward']
    ans = V(vec, ans_)
    return ans


def vector_add(vector1, vector2):
    """
    Adds one vector to another
    :param vector1: list(float, float, float)
    :param vector2: list(float, float, float)
    :return: list(float, float, float)
    """
    return [vector1[0] + vector2[0], vector1[1] + vector2[1], vector1[2] +
        vector2[2]]


def _setSamplingFromEmx(emxObj, img):
    """ Set the sampling rate from the pixelSpacing element. """
    img.setSamplingRate(emxObj.get('pixelSpacing__X'))


def max_tok_len(new, count, sofar):
    """
    In token batching scheme, the number of sequences is limited
    such that the total number of src/tgt tokens (including padding)
    in a batch <= batch_size
    """
    global max_src_in_batch, max_tgt_in_batch
    if count == 1:
        max_src_in_batch = 0
        max_tgt_in_batch = 0
    max_src_in_batch = max(max_src_in_batch, len(new.src[0]) + 2)
    max_tgt_in_batch = max(max_tgt_in_batch, len(new.tgt[0]) + 1)
    src_elements = count * max_src_in_batch
    tgt_elements = count * max_tgt_in_batch
    return max(src_elements, tgt_elements)


@classmethod
def remove_connection(cls, pid, connection):
    """Remove a connection from the pool, closing it if is open.

        :param str pid: The pool ID
        :param connection: The connection to remove
        :type connection: psycopg2.extensions.connection
        :raises: ConnectionNotFoundError

        """
    cls._ensure_pool_exists(pid)
    cls._pools[pid].remove(connection)


def infer(datum):
    """
    Returns the inferred data type
    """
    if datum is None or datum == '':
        return None
    try:
        int(datum)
        return 'integer'
    except (ValueError, TypeError):
        pass
    try:
        float(datum)
        return 'number'
    except (ValueError, TypeError):
        pass
    return 'string'


def read(nbytes: int) ->bytes:
    """Read at most ``nbytes``. Returns what was read."""


def psi_H_K_HCO3_HMW84(T, P):
    """c-c'-a: hydrogen potassium bicarbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def get_defaults(context):
    """
    Get the default values for a slice's members:
    (start for positive step, start for negative step,
     stop for positive step, stop for negative step, step)
    """
    maxint = (1 << context.address_size - 1) - 1
    return 0, maxint, maxint, -maxint - 1, 1


def write_embedded_list(data_list, save_path, sep=' '):
    """
    将一个嵌套的list写入文本中,一行写入一个list,list的元素使用sep连接
    :return:
    """
    with open(save_path, 'w') as w:
        if data_list is None or len(data_list) == 0:
            return
        for embedded_list in data_list:
            w.write(sep.join(embedded_list))
            w.write('\n')


def _fzerorise(data):
    """Find zerocrossings on rising edge of a filtered signal"""
    pos = data < 0
    return (pos[:-1] & ~pos[1:]).nonzero()[0]


def gte(value, other):
    """Checks if `value` is greater than or equal to `other`.

    Args:
        value (number): Value to compare.
        other (number): Other value to compare.

    Returns:
        bool: Whether `value` is greater than or equal to `other`.

    Example:

        >>> gte(5, 3)
        True
        >>> gte(3, 5)
        False
        >>> gte(5, 5)
        True

    .. versionadded:: 3.3.0
    """
    return value >= other


def update_association(AssociationId=None, Parameters=None, DocumentVersion
    =None, ScheduleExpression=None, OutputLocation=None, Name=None, Targets
    =None):
    """
    Updates an association. You can only update the document version, schedule, parameters, and Amazon S3 output of an association.
    See also: AWS API Documentation

    :example: response = client.update_association(
        AssociationId='string',
        Parameters={
            'string': [
                'string',
            ]
        },
        DocumentVersion='string',
        ScheduleExpression='string',
        OutputLocation={
            'S3Location': {
                'OutputS3Region': 'string',
                'OutputS3BucketName': 'string',
                'OutputS3KeyPrefix': 'string'
            }
        },
        Name='string',
        Targets=[
            {
                'Key': 'string',
                'Values': [
                    'string',
                ]
            },
        ]
    )

    :type AssociationId: string
    :param AssociationId: [REQUIRED]
            The ID of the association you want to update.

    :type Parameters: dict
    :param Parameters: The parameters you want to update for the association. If you create a parameter using Parameter Store, you can reference the parameter using {{ssm:parameter-name}}
            (string) --
            (list) --
            (string) --

    :type DocumentVersion: string
    :param DocumentVersion: The document version you want update for the association.

    :type ScheduleExpression: string
    :param ScheduleExpression: The cron expression used to schedule the association that you want to update.

    :type OutputLocation: dict
    :param OutputLocation: An Amazon S3 bucket where you want to store the results of this request.
            S3Location (dict) --An Amazon S3 bucket where you want to store the results of this request.
            OutputS3Region (string) --The Amazon S3 region where the association information is stored.
            OutputS3BucketName (string) --The name of the Amazon S3 bucket.
            OutputS3KeyPrefix (string) --The Amazon S3 bucket subfolder.

    :type Name: string
    :param Name: The name of the association document.

    :type Targets: list
    :param Targets: The targets of the association.
            (dict) --An array of search criteria that targets instances using a Key,Value combination that you specify. Targets is required if you don't provide one or more instance IDs in the call.
            Key (string) --User-defined criteria for sending commands that target instances that meet the criteria. Key can be tag:Amazon EC2 tagor InstanceIds. For more information about how to send commands that target instances using Key,Value parameters, see Executing a Command Using Systems Manager Run Command .
            Values (list) --User-defined criteria that maps to Key. For example, if you specified tag:ServerRole, you could specify value:WebServer to execute a command on instances that include Amazon EC2 tags of ServerRole,WebServer. For more information about how to send commands that target instances using Key,Value parameters, see Executing a Command Using Systems Manager Run Command .
            (string) --

    :rtype: dict
    :return: {
        'AssociationDescription': {
            'Name': 'string',
            'InstanceId': 'string',
            'Date': datetime(2015, 1, 1),
            'LastUpdateAssociationDate': datetime(2015, 1, 1),
            'Status': {
                'Date': datetime(2015, 1, 1),
                'Name': 'Pending'|'Success'|'Failed',
                'Message': 'string',
                'AdditionalInfo': 'string'
            },
            'Overview': {
                'Status': 'string',
                'DetailedStatus': 'string',
                'AssociationStatusAggregatedCount': {
                    'string': 123
                }
            },
            'DocumentVersion': 'string',
            'Parameters': {
                'string': [
                    'string',
                ]
            },
            'AssociationId': 'string',
            'Targets': [
                {
                    'Key': 'string',
                    'Values': [
                        'string',
                    ]
                },
            ],
            'ScheduleExpression': 'string',
            'OutputLocation': {
                'S3Location': {
                    'OutputS3Region': 'string',
                    'OutputS3BucketName': 'string',
                    'OutputS3KeyPrefix': 'string'
                }
            },
            'LastExecutionDate': datetime(2015, 1, 1),
            'LastSuccessfulExecutionDate': datetime(2015, 1, 1)
        }
    }

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

    """
    pass


def p_Inherit_true(p):
    """Inherit : inherit"""
    p[0] = True


def sunsky_preset_add(name: str='', remove_active: bool=False):
    """Add or remove a Sky & Atmosphere Preset

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


def almost_equal_floats(value_1: float, value_2: float, *, delta: float=1e-08
    ) ->bool:
    """
    Return True if two floats are almost equal
    """
    return abs(value_1 - value_2) <= delta


def filter_cannonical(df):
    """Retains only cannonical chromosomes in bed-like df."""
    df = df[df.loc[:, (0)].str.match('chr[0-9|X|Y]+[a|b]?$')]
    return df


def Convert2mAhg(c, mass=1.0):
    """Converts capacity in Ah to capacity in mAh/g.

    Args:
        c (float or numpy array): capacity in mA.
        mass (float): mass in mg.

    Returns:
        float: 1000000 * c / mass
    """
    return 1000000 * c / mass


def is_adjective(pos_tag):
    """Return ``True`` if ``pos_tag`` is ``ADJ``, False otherwise.

    :param pos_tag: Part of Speech tag
    :type pos_tag: string
    :return: True if POS is adjective
    :rtype: boolean
    """
    return pos_tag == 'ADJ'


def point_is_valid(point, dimensions):
    """Returns True if the coordinates of the point are within the bounds
       of the image, False otherwise. Parameter dimensions is a tuple
       (image_width, image_height)."""
    if point[0] >= 0 and point[1] >= 0 and point[0] < dimensions[0] and point[1
        ] < dimensions[1]:
        return True
    else:
        return False


def div(conteudo='', classe='', Identificador=''):
    """Retorna uma div utilizando as classes e ids informados pelo usuario """
    return "
%s
" % (str(classe), str(
        Identificador), str(conteudo))


@staticmethod
def GetVisualStudioName():
    """
		Retrieve the name value that will be show up in Visual Studio for a platform.  Must be a name that Visual Studio recognizes.

		:return: str
		"""
    pass


@classmethod
def val(C, value):
    """return a string with a value ready for inclusion in SQL text."""
    if isinstance(value, str):
        return f"'{value}'"
    if value is None:
        return 'NULL'
    elif value is True:
        return 'TRUE'
    elif value is False:
        return 'FALSE'
    else:
        return f'{value}'


def rssdate(t):
    """Returns a RSS-valid date without the year"""
    return t.strftime('%a, %d %b %Y %H:%M:%S %z')


@classmethod
def _get_xml_child_by_names(cls, node, names):
    """ Get the child of an XML element with a prefix and name

        Args:
            node (:obj:`libsbml.XMLNode`): XML node
            names (:obj:`list` of :obj:`XmlName`): names

        Returns:
            :obj:`libsbml.XMLNode`: child with prefix and name
        """
    for name in names:
        if not node:
            break
        node = cls._get_xml_child_by_name(node, name)
    return node


def strain_from_metric_difference(Ginit, Gfinal):
    """
    does not seem to work ...
    TODO to repair?
    """
    return 0.5 * (Gfinal - Ginit)


def context(text, position, level='paragraph'):
    """Get sentence or paragraph that surrounds the given position."""
    if level == 'sentence':
        pass
    elif level == 'paragraph':
        pass
    return ''


def _to_language(locale):
    """Convert locale name to language code if necessary.

    OpenID Connect locale needs to be converted to Django's language
    code. In general however, the differences between the locale names
    and language code are not very clear among different systems.

    For more information, refer to:
        http://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims
        https://docs.djangoproject.com/en/1.6/topics/i18n/#term-translation-string
    """
    return locale.replace('_', '-').lower()


def is_datetime_dtype(dtyp):
    """
    Returns True if the given dtype is a datetime dtype
    :param dtyp:
    :return:
    """
    return dtyp.kind == 'M'


def _release(rel):
    """Validity check for release parameter - must be an integer or
    rawhide.
    """
    if rel.isdigit() or rel.lower() == 'rawhide':
        return rel
    else:
        raise ValueError('Release must be integer or Rawhide.')


def getNext(fp):
    """
    Sometimes we need to decode, sometimes not
    """
    line = fp.readline()
    if isinstance(line, str):
        return line
    return line.decode('ascii')


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

    """
    pass


def dict_sets_to_lists(dict_):
    """change values from sets to sorted lists.

    Here is an example:
    >>> import pprint
    >>> d= {'a': set([1, 2]), 'b': set([1])}
    >>> ld= dict_sets_to_lists(d)
    >>> pprint.pprint(ld)
    {'a': [1, 2], 'b': [1]}
    """
    new = {}
    for k, v in dict_.items():
        new[k] = sorted(list(v))
    return new


def sync_frame_initializer(new_frame, reference_frame):
    """Set the initializers of the new_frame to be the same as the reference_frame,
    for both the default initializer and per-column initializers.

    Parameters
    ----------
    new_frame : Frame
        The frame to set initializers
    reference_frame : Frame
        The frame to copy initializers
    """
    new_frame._default_initializer = reference_frame._default_initializer
    new_frame._initializers = reference_frame._initializers


def output_units(un=None):
    """Enable or disable the output of units when printing.

    By default output of units is enabled.  Do nothing if un is None.
    When disabled (un is False) print of Magnitudes will produce only
    numbers.

    Return: True if output of units enabled, False otherwise.

    >>> print mg(2, 'day')
    2.0000 day
    >>> output_units(False)
    False
    >>> print mg(2, 'day').ounit('s')
    172800.0000
    """
    global _prn_units
    if un is not None:
        _prn_units = un
    return _prn_units


def compute_difficulty(rank):
    """

        normalized between 0 and 1
         the difficulty increases in steps of 0.01
         for every 500 ranks
         assumes a frequency list of 50K words

    :param rank:
    :return:
    """
    return rank // 500 / 100.0


def metadata_isdir(name):
    """Is the named metadata a directory?  (like ``os.path.isdir()``)"""


@staticmethod
def rateServiceTypeInResult(discoveryResponse):
    """Gives a quality rating for a given service type in a result, higher is better.

        Several UpnP devices reply to a discovery request with multiple responses with different service type
        announcements. To find the most specific one we need to be able rate the service types against each other.
        Usually this is an internal method and just exported for convenience reasons.

        :param DiscoveryResponse discoveryResponse: the response to rate
        :return: a rating of the quality of the given service type
        :rtype: int
        """
    if discoveryResponse is None:
        return 0
    serviceType = discoveryResponse.service
    if serviceType.startswith('urn:dslforum-org:device'):
        return 11
    if serviceType.startswith('urn:dslforum-org:service'):
        return 10
    if serviceType.startswith('urn:dslforum-org:'):
        return 9
    if serviceType.startswith('urn:schemas-upnp-org:device'):
        return 8
    if serviceType.startswith('urn:schemas-upnp-org:service'):
        return 7
    if serviceType.startswith('urn:schemas-upnp-org:'):
        return 6
    if serviceType.startswith('urn:schemas-'):
        return 5
    if serviceType.startswith('urn:'):
        return 4
    if serviceType.startswith('upnp:rootdevice'):
        return 3
    if serviceType.startswith('uuid:'):
        return 2
    return 1


@classmethod
def get_name(cls):
    """ Returns the name of the loss function.
		"""
    return 'mean_squared_error'


def with_metaclass(meta, base=object):
    """Create a base class with a metaclass."""
    return meta('NewBase', (base,), {})


def get_prop_spec(client_factory, spec_type, properties):
    """Builds the Property Spec Object."""
    prop_spec = client_factory.create('ns0:PropertySpec')
    prop_spec.type = spec_type
    prop_spec.pathSet = properties
    return prop_spec


def disconnect(obj, signal, slot):
    """Experimental function. Not part of the official API"""
    return obj._helper.disconnect(signal, slot)


@classmethod
def save_data(cls, data_set, mongo_collection, file_name=None):
    """
        save data to a mongodb database or to a file
        :param data_set : array()
        :param mongo_collection : mongodb collection
        :param file_name : str()
        :return Mongodb InsertOneResult or InsertManyResult
        todo: enable file_name option
        """
    if len(data_set) == 1:
        res = mongo_collection.insert_one(data_set[0])
        return res
    else:
        res = mongo_collection.insert_many(data_set)
        return res


def expand_year(year):
    """Convert 2-digit year to 4-digit year."""
    if year < 80:
        return 2000 + year
    else:
        return 1900 + year


def m2f(note):
    """Convert MIDI note number to frequency in Hertz.

    See https://en.wikipedia.org/wiki/MIDI_Tuning_Standard.

    """
    return 2 ** ((note - 69) / 12) * 440


def remove_prefix_including_first_slash_or_backslash(input_str):
    """
    >>> remove_prefix_including_first_slash_or_backslash('test')
    'test'
    >>> remove_prefix_including_first_slash_or_backslash('test/')
    ''
    >>> remove_prefix_including_first_slash_or_backslash('/test/')
    'test/'

    >>> remove_prefix_including_first_slash_or_backslash('test\\\\')
    ''
    >>> remove_prefix_including_first_slash_or_backslash('test/test2/test3')
    'test2/test3'
    >>> remove_prefix_including_first_slash_or_backslash('test\\test3\\test4')
    'test\\test3\\test4'

    """
    result = input_str
    if '\\' in input_str:
        result = input_str.split('\\', 1)[1]
    elif '/' in input_str:
        result = input_str.split('/', 1)[1]
    return result


def fpEQ(a, b):
    """
    Checks if floating point `a` is equal to floating point `b`.
    """
    return a == b


def Calc_Ref_ET(Surface_temp, sl_es_24, Rn_ref, air_dens, esat_24, eact_24,
    rah_grass, Psychro_c):
    """
    Function to calculate the reference evapotransporation
    """
    Lhv = (2.501 - 0.002361 * (Surface_temp - 273.15)) * 1000000.0
    LET_ref_24 = (sl_es_24 * Rn_ref + air_dens * 1004 * (esat_24 - eact_24) /
        rah_grass) / (sl_es_24 + Psychro_c * (1 + 70.0 / rah_grass))
    ETref_24 = LET_ref_24 / (Lhv * 1000) * 86400000
    return ETref_24, Lhv


def is_bit_set(value, bit):
    """
    Return True/False if the bit at offset >bit< is 1 or 0 in given value.

    bit 7 |      | bit 0
       ...10111101

    e.g.:

    >>> is_bit_set(0x01, bit=0) # 00000001
    True
    >>> is_bit_set(0xfd, bit=1) # 11111101
    False
    >>> is_bit_set(int('10000000', 2), bit=7)
    True
    >>> is_bit_set(int('01111111', 2), bit=7)
    False
    >>> is_bit_set(int('1111000011110000', 2), bit=11)
    False
    >>> is_bit_set(int('1111000011110000', 2), bit=12)
    True
    """
    return False if value & 2 ** bit == 0 else True


def on_logout(context, response):
    """ Manage response for request Logout.

        :param context: request context
        :param response: response received
        :return: None
        :type context: RequestFutureContext
    """
    context.remove_channel()


def current_user_email():
    """
    Returns the email address of the currently logged in user.
    Implement actual behavior by patching the function.
    """
    return 'guest@localhost'


def standardized_api_list(component):
    """
    Convert result dict to list just to have standardized API
    """
    keyword = 'componentResults'
    if not component:
        return component
    if not component[keyword]:
        return component
    results = dict(component)
    results[keyword] = []
    for key, value in component[keyword].iteritems():
        value['name'] = key
        results[keyword].append({'componentResult': value})
    return results


def chunked(data, chunksize):
    """
    Returns a list of chunks containing at most ``chunksize`` elements of data.
    """
    if chunksize < 1:
        raise ValueError('Chunksize must be at least 1!')
    if int(chunksize) != chunksize:
        raise ValueError('Chunksize needs to be an integer')
    res = []
    cur = []
    for e in data:
        cur.append(e)
        if len(cur) >= chunksize:
            res.append(cur)
            cur = []
    if cur:
        res.append(cur)
    return res


@staticmethod
def _tauband(generator, n, power=1):
    """
        Transformation: generator --> t^{power}(generator)

        Where:          generator * D = D * t(generator)
        Modifies a 2-element list in place. No error checks.

        >>> a = [1, 5]
        >>> Braid._tauband(a, 5)
        >>> a
        [1, 2]
        >>> Braid._tauband(a, 7, -3)
        >>> a
        [5, 6]
        """
    if power == 0:
        return
    generator[0] += power
    generator[1] += power
    positivity = generator[0] > generator[1]
    generator[0] = (generator[0] - 1) % n + 1
    generator[1] = (generator[1] - 1) % n + 1
    if positivity != (generator[0] > generator[1]):
        generator.reverse()


@staticmethod
def _get_parent_dn(dn):
    """
        Gets the dn of the parent object
        Meant to be overridden by inheriting classes.
        Raises exception if not overridden.

        :returns: string containing dn
        """
    return dn.split('/if-')[0]


def assign_value(Xj, Xk, csp, assignment):
    """Assign a value to Xk given Xj's (Xk's parent) assignment.
    Return the first value that satisfies the constraints."""
    parent_assignment = assignment[Xj]
    for val in csp.curr_domains[Xk]:
        if csp.constraints(Xj, parent_assignment, Xk, val):
            return val
    return None


def filter_group_minmax(dfg, col):
    """

    Returns all rows equal to min in col

    """
    return dfg[dfg[col] == dfg[col].min()]


def DER_SNR(flux):
    """
   DESCRIPTION This function computes the signal to noise ratio DER_SNR following the
               definition set forth by the Spectral Container Working Group of ST-ECF,
	       MAST and CADC.

               signal = median(flux)
               noise  = 1.482602 / sqrt(6) median(abs(2 flux_i - flux_i-2 - flux_i+2))
	       snr    = signal / noise
               values with padded zeros are skipped

   USAGE       snr = DER_SNR(flux)
   PARAMETERS  none
   INPUT       flux (the computation is unit independent)
   OUTPUT      the estimated signal-to-noise ratio [dimensionless]
   USES        numpy
   NOTES       The DER_SNR algorithm is an unbiased estimator describing the spectrum
	       as a whole as long as
               * the noise is uncorrelated in wavelength bins spaced two pixels apart
               * the noise is Normal distributed
               * for large wavelength regions, the signal over the scale of 5 or
	         more pixels can be approximated by a straight line

               For most spectra, these conditions are met.

   REFERENCES  * ST-ECF Newsletter, Issue #42:
               www.spacetelescope.org/about/further_information/newsletters/html/newsletter_42.html
               * Software:
	       www.stecf.org/software/ASTROsoft/DER_SNR/
   AUTHOR      Felix Stoehr, ST-ECF
               24.05.2007, fst, initial import
               01.01.2007, fst, added more help text
               28.04.2010, fst, return value is a float now instead of a numpy.float64
   """
    from numpy import array, where, median, abs
    flux = array(flux)
    flux = array(flux[where(flux != 0.0)])
    n = len(flux)
    if n > 4:
        signal = median(flux)
        noise = 0.6052697 * median(abs(2.0 * flux[2:n - 2] - flux[0:n - 4] -
            flux[4:n]))
        return float(signal / noise)
    else:
        return 0.0


def get_pub_set(cls, name):
    """ Returns standard pub/nonpub set name given a name. """
    if name == 'public':
        return 'public-good'
    elif name == 'nonpub':
        return 'nonpub-all'
    elif name == 'both':
        return 'both-goodall'
    elif name == 'nonpub-good':
        return 'nonpub-all'
    elif name == 'nonpub-bad':
        return 'nonpub-all'
    elif name == 'both-good':
        return 'both-goodall'
    elif name == 'both-bad':
        return 'both-badall'
    elif name in cls.pub_set_names:
        return name
    else:
        return cls.pub_set_default


def _median(d):
    """Returns the median key from histogram (as a dict with values=counts) of frequencies"""
    assert len(d)
    count = 0
    total = sum(d.values())
    for key in sorted(d.keys()):
        count += d[key]
        if count >= 0.5 * total:
            return key


def RenameColumns(df_old, renames):
    """
  Rename the column headers for a spark dataframe

  Parameters:
  -----------
  df_old : spark.DataFrame
      Initial Data Frame

  renames : list
      List of columns to rename, like:

  Returns:
  -------
  None

  Example:
  -----------
  df_new = ws.RenameColumns(df_old,renames)
  """
    df_new = df_old
    for rename in renames:
        df_new = df_new.withColumnRenamed(rename[0], rename[1])
    print('Column headers are renamed successfully...')
    return df_new


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

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

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


def force_send_message(unencrypted_message):
    """
    Send the message unencrypted
    """
    unencrypted_message.do_not_encrypt_this_message = True
    unencrypted_message.send()


def provides(varmap):
    """Return a minimal ``provides`` list from the setup vars.
    """
    try:
        return ['{} ({})'.format(varmap['name'], varmap['version'])]
    except KeyError:
        return [varmap['name']]


def indices(df):
    """Returns the list of named indices of the dataframe, ignoring any unnamed index."""
    a = list(df.index.names)
    return a if a != [None] else []


def get_parser():
    """Return the parser object for this script."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__, formatter_class=
        ArgumentDefaultsHelpFormatter)
    parser.add_argument('-n', dest='n', default=10, type=int, help=
        'Show TOP-N results')
    parser.add_argument('--port', dest='port', default=5000, type=int, help
        ='where should the webserver run')
    parser.add_argument('--use_segmenter', dest='use_segmenter', default=
        False, action='store_true', help=
        'try to segment the input for multiple symbol recognition')
    return parser


def _add_sensor_alias(cache, new_name, old_name):
    """Add an optional alias for single sensor in sensor cache."""
    try:
        cache[new_name] = cache.get(old_name, extract=False)
    except KeyError:
        pass


def argsort(seq, indices_only=False):
    """Returns the sorted indices and the sorted array (seq) if indices_only=False."""
    if indices_only:
        return sorted(range(len(seq)), key=seq.__getitem__)
    else:
        from operator import itemgetter
        return zip(*sorted(enumerate(seq), key=itemgetter(1)))


def logical_not(input):
    """Perform a logical not operation.  Equivalent to np.logical_not

    Parameters
    ----------
    input : Tensor
        The input

    Returns
    -------
    Tensor
        The result
    """
    pass


def duck_type_collection(specimen, default=None):
    """Given an instance or class, guess if it is or is acting as one of
    the basic collection types: list, set and dict.  If the __emulates__
    property is present, return that preferentially.
    """
    if hasattr(specimen, '__emulates__'):
        if specimen.__emulates__ is not None and issubclass(specimen.
            __emulates__, set):
            return set
        else:
            return specimen.__emulates__
    isa = isinstance(specimen, type) and issubclass or isinstance
    if isa(specimen, list):
        return list
    elif isa(specimen, set):
        return set
    elif isa(specimen, dict):
        return dict
    if hasattr(specimen, 'append'):
        return list
    elif hasattr(specimen, 'add'):
        return set
    elif hasattr(specimen, 'set'):
        return dict
    else:
        return default


def all_reads():
    """Reload all read nodes in the compositing script"""
    import nuke
    for node in nuke.allNodes():
        if node.Class() == 'Read':
            node.knob('reload').execute()


def count_bits(value):
    """Counts the number of bits set to 1 in an integer.

    For example::

        >>> count_bits(0b101111)
        5
        >>> count_bits(0xf)
        4
        >>> count_bits(8)
        1
        >>> count_bits(3)
        2

    :param int value: An integer.
    :rtype: integer
    :return: The count of bits set to 1.

    .. seealso:: http://wiki.python.org/moin/BitManipulation
    """
    count = 0
    while value:
        count += value & 1
        value >>= 1
    return count


def count_lt_zero(data):
    """
    Return unweighted count of negative data items.
    """
    return sum([(1) for item in data if item < 0])


@classmethod
def get_dict_value_as_float(cls, dict_IN, name_IN, default_IN=float(-1)):
    """
        Accepts dictionary, name, and optional default value (if no default
           provided, default is -1).  If dictionary or name missing, returns
           default.  If name not present in dictionary, returns default.  If name
           in dictionary, returns whatever is mapped to name, converted to a
           float through call to float().

        Parameters:
        - dict_IN - dictionary we are looking in.
        - name_IN - name we are looking for in dictionary.
        - default_IN (defaults to None) - default value to return if problem or not found in dict.

        Returns:
        - value_OUT - value mapped to name_IN in dict_IN, converted to int(), else the default value if problems or if not found in dict.
        """
    value_OUT = None
    value_OUT = cls.get_dict_value(dict_IN, name_IN, default_IN)
    if value_OUT != None:
        value_OUT = float(value_OUT)
    return value_OUT


def _is_sunder(name):
    """Returns True if a _sunder_ name, False otherwise."""
    return name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1
        ] != '_' and len(name) > 2


@staticmethod
def _wrap_columns(columns):
    """Transform pandas.MultiIndex into pandas.Index for the pandas.DataFrame columns.

        Notes:
            the libsonata.ElementsReader.get() returns tuple as columns for the data. For the
            soma reports it means: pandas.MultiIndex([(0, 0), (1, 0), ..., (last_node_id, 0)]).
            So we convert this into pandas.Index([0,1,..., last_node_id]).
        """
    return columns.levels[0]


def can_see_details(key):
    """Returns if the user has permission to see details of objects of the
        given feature"""


def getTitle():
    """Gives the title of this result field.
        """


def _get_existing_logical_drives(raid_adapter):
    """Collect existing logical drives on the server.

    :param raid_adapter: raid adapter info
    :returns: existing_logical_drives: get logical drive on server
    """
    existing_logical_drives = []
    logical_drives = raid_adapter['Server']['HWConfigurationIrmc']['Adapters'][
        'RAIDAdapter'][0].get('LogicalDrives')
    if logical_drives is not None:
        for drive in logical_drives['LogicalDrive']:
            existing_logical_drives.append(drive['@Number'])
    return existing_logical_drives


def clause_15_6_6_e_merging_flow_1(N: float, X: float, D: float, S_up:
    float, W_SE: float) ->tuple:
    """Calculates merging flow at final exit level in accordance with Figure 6 (1 of 3) in BD 9999:2017, page 68.
    Merging flow from stair with storey exit at final exit level.
    SI UNITS unless specified.

    :param N: is the number of people served by the final exit level storey exit.
    :param D: is the lesser distance from the final exit level storey exit or the lowest riser from the upward portion of the stair, in metres (m).
    :param S_up: is the stair width for the upward portion of the stair, in millimetres.
    :param W_SE: is the width of the final exit level storey exit, in millimetres.
    :param X: is the minimum door width per person (see 16.6 and Clause 18), in millimetres.
    :return W_FE: is the width of the final exit, in millimetres.
    """
    S_up *= 1000.0
    W_SE *= 1000.0
    X *= 1000.0
    condition_check = False
    if N > 60 and D < 2:
        condition_check = True
        W_FE = S_up + W_SE
    else:
        W_FE = N * X + 0.75 * S_up
    W_FE = max([W_FE, S_up])
    W_FE /= 1000.0
    return W_FE, condition_check


def bool_param(value, default=None):
    """Coverts string param into boolean"""
    if isinstance(value, bool):
        result = value
    else:
        value = '' if value is None else value.lower()
        if value in ('1', 'true', 'yes', 'y', 'on'):
            result = True
        elif value in ('0', 'false', 'no', 'n', 'off'):
            result = False
        else:
            result = default
    return result


def remove_dot_segments(path):
    """
    Algorithm from RFC 3986. urllib.parse has this algorithm, but it's hidden in urljoin()
    This is a stand-alone version. Since this is working on a non-relative url, path MUST begin with '/'
    """
    if path[0] != '/':
        return path
    segments = path.split('/')
    segments[1:-1] = filter(None, segments[1:-1])
    resolved_segments = []
    for s in segments[1:]:
        if s == '..':
            try:
                resolved_segments.pop()
            except IndexError:
                pass
        elif s == '.':
            continue
        else:
            resolved_segments.append(s)
    return '/' + '/'.join(resolved_segments)


@staticmethod
def properties_to_filter_out():
    """Return a list of properties to be removed from the event"""
    return []


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 select_unit(action, action_space, select_unit_act, select_unit_id):
    """Select a specific unit from the multi-unit selection."""
    del action_space
    select = action.action_ui.multi_panel
    select.type = select_unit_act
    select.unit_index = select_unit_id


def sizeof_fmt(num):
    """
    Handy formatting for human readable filesizes.

    From http://stackoverflow.com/a/1094933/1657047
    """
    for x in ['bytes', 'KB', 'MB', 'GB']:
        if num < 1024.0 and num > -1024.0:
            return '%3.1f %s' % (num, x)
        num /= 1024.0
    return '%3.1f %s' % (num, 'TB')


def words(zelf):
    """ get the arguments of the txt attribute. """
    if 'txt' in zelf:
        return zelf.txt.split()


def size(o, default=None):
    """Helper to return the len() of an object if it is available"""
    if hasattr(o, '__len__'):
        return len(o)
    return default


def pformat(obj, verbose=False):
    """Prettyprint an object.  Either use the `pretty` library or the
    builtin `pprint`.
    """
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj)


@classmethod
def set_toolbox_path(cls):
    """Update the mimodd_tool_conf.xml file installed as part of the
        package with an absolute tool_path to the package xml wrappers."""
    with open(cls.tool_conf_file, 'r', encoding='utf-8') as sample:
        template = sample.readlines()[1:]
    with open(cls.tool_conf_file, 'w', encoding='utf-8') as out:
        out.write('<toolbox tool_path="{0}">\n'.format(cls.
            pkg_galaxy_data_path))
        out.writelines(template)


@staticmethod
def iter_params():
    """return (ROL bits, ADD key)"""
    for rol_bits in range(1, 8):
        for add_key in range(1, 256):
            yield rol_bits, add_key


@staticmethod
def dtype(x):
    """Enforce a homogeneous float datatype."""
    return float(x)


def extrude_edges_move(MESH_OT_extrude_edges_indiv=None,
    TRANSFORM_OT_translate=None):
    """Extrude edges and move result

    :param MESH_OT_extrude_edges_indiv: Extrude Only Edges, Extrude individual edges only
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def intdiv(p, q):
    """ Integer divsions which rounds toward zero

    Examples
    --------
    >>> intdiv(3, 2)
    1
    >>> intdiv(-3, 2)
    -1
    >>> -3 // 2
    -2

    """
    r = p // q
    if r < 0 and q * r != p:
        r += 1
    return r


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

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


def standard_formats(workbook):
    """ the formats used in the spreadsheet """
    atomica_blue = '#98E0FA'
    optional_orange = '#FFA500'
    BG_COLOR = atomica_blue
    OPT_COLOR = optional_orange
    BORDER_COLOR = 'white'
    formats = {}
    formats['bold'] = workbook.add_format({'bold': 1})
    formats['center'] = workbook.add_format({'align': 'center'})
    formats['center_bold'] = workbook.add_format({'bold': 1, 'align': 'center'}
        )
    formats['rc_title'] = {}
    formats['rc_title']['right'] = {}
    formats['rc_title']['right']['T'] = workbook.add_format({'bold': 1,
        'align': 'right', 'text_wrap': True})
    formats['rc_title']['right']['F'] = workbook.add_format({'bold': 1,
        'align': 'right', 'text_wrap': False})
    formats['rc_title']['left'] = {}
    formats['rc_title']['left']['T'] = workbook.add_format({'bold': 1,
        'align': 'left', 'text_wrap': True})
    formats['rc_title']['left']['F'] = workbook.add_format({'bold': 1,
        'align': 'left', 'text_wrap': False})
    formats['unlocked'] = workbook.add_format({'locked': 0, 'bg_color':
        BG_COLOR, 'border': 1, 'border_color': BORDER_COLOR})
    formats['center_unlocked'] = workbook.add_format({'align': 'center',
        'locked': 0, 'bg_color': BG_COLOR, 'border': 1, 'border_color':
        BORDER_COLOR})
    formats['general'] = workbook.add_format({'locked': 0, 'num_format': 0,
        'bg_color': BG_COLOR, 'border': 1, 'border_color': BORDER_COLOR})
    formats['unlocked_boolean_true'] = workbook.add_format({'bg_color':
        OPT_COLOR})
    formats['unlocked_boolean_false'] = workbook.add_format({'bg_color':
        BG_COLOR})
    formats['not_required'] = workbook.add_format({'bg_color': '#EEEEEE',
        'border': 1, 'border_color': '#CCCCCC'})
    formats['white_bg'] = workbook.add_format({'bg_color': '#FFFFFF',
        'border': 1, 'border_color': '#CCCCCC'})
    formats['ignored'] = workbook.add_format({'pattern': 14})
    formats['warning'] = workbook.add_format({'bg_color': '#FF0000'})
    formats['ignored_warning'] = workbook.add_format({'pattern': 14,
        'bg_color': '#FF0000'})
    formats['ignored_not_required'] = workbook.add_format({'pattern': 14,
        'bg_color': '#EEEEEE', 'border': 1, 'border_color': '#CCCCCC'})
    return formats


def _vector_field(q, dotx_func, doty_func, x, y, Is):
    """
    Add the vector field of the x and y derivatives in phase space.

    Parameters
    ----------
    q : :class:`matplotlib.quiver.Quiver`
        Phase space quiver object.
    dotx_func : function
        User provided function giving :math:`\\dot{x} = f(x, y, Is(t))`.
    doty_func : function
        User provided function giving :math:`\\dot{y} = g(x, y, Is(t))`.
    x : :class:`numpy.ndarray`.
    y : :class:`numpy.ndarray`.
    Is : float
        Current (time dependent data).
    """
    q.set_UVC(dotx_func(x, y, Is), doty_func(x, y, Is))


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

        :param PaperDocTeamInviteType val:
        :rtype: EventType
        """
    return cls('paper_doc_team_invite', val)


def show_hide_actor(actor):
    """flips the visibility for an actor"""
    is_visible = actor.GetVisibility()
    actor.SetVisibility(not is_visible)
    actor.Modified()


def int_to_color(color_int):
    """
  Returns a color string from a 24bits integer
  """
    return '#{0:06x}'.format(color_int)


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


def read_source_script(filepath):
    """Read the contents of `filepath`

    Parameters
    ----------
    filepath: Str
        Absolute path to a Python file. Expected to end with '.py', or '.ipynb'

    Returns
    -------
    source: Str
        The contents of `filepath`"""
    if filepath.endswith('.ipynb'):
        with open(filepath, 'r') as f:
            from nbconvert import PythonExporter
            import nbformat
            notebook = nbformat.reads(f.read(), nbformat.NO_CONVERT)
            exporter = PythonExporter()
            source, _ = exporter.from_notebook_node(notebook)
    else:
        with open(filepath, 'r') as f:
            source = f.read()
    return source


def split_diffs(text):
    """Split up a diff output, which can potentially contain
    multiple diffs, into a list of Diff objects
    """
    arr = []
    for t in text:
        if t.startswith('diff') and len(arr) != 0:
            yield arr
            arr = [t]
        else:
            arr.append(t)
    yield arr


def select_driver(driver_name=None):
    """
        Choose and return an `IDBDriver`.

        The *driver_name* of "auto" is equivalent to a *driver_name* of
        `None` and means to choose the highest priority available driver.
        """


def getActiveCurrency():
    """returns the current currency"""


def p_col_expr_list_one(p):
    """col_expr_list : col_expr"""
    p[0] = [p[1]]


def add_arguments(parser):
    """
    Inject an arg into the user's parser. Intented to pair with
    :py:meth:`Auth.from_env_or_args`: after argparse parses the
    args, feed that the args namespace.
    """
    parser.add_argument('--osrc', type=str, help=
        'OpenStack parameters file that overrides envvars.')


def renumerate_article_sortorder(apps, schema_editor):
    """ Renumerate articles for consistent and guaranteed unique sortorder. """
    Message = apps.get_model('newsletter', 'Message')
    for message in Message.objects.all():
        for index, article in enumerate(message.articles.all()):
            article.sortorder = (index + 1) * 10
            article.save()


def fileFormatSampleFreq(sampleFreq: float) ->str:
    """Provide a consistent way to represent floating numbers in filenames

    Parameters
    ----------
    sampleFreq : float
        The sampling frequency

    Returns
    -------
    str
        Float converted for string for the purposes of a filename
    """
    sampleFreqStr: str = '{:.3f}'.format(sampleFreq)
    return sampleFreqStr.replace('.', '_')


@classmethod
def buildmap(cls, items):
    """Parse a list of alias (name, replacement) pairs into a dict of
        alias objects"""
    aliases = {}
    for decl, defn in items:
        a = cls.build(decl, defn)
        aliases[a.name] = a
    return aliases


def print_s(fmt_string, *formats):
    """Print function split out for mocking"""
    print(fmt_string % formats)


def uncomment_line(line, prefix):
    """Remove prefix (and space) from line"""
    if not prefix:
        return line
    if line.startswith(prefix + ' '):
        return line[len(prefix) + 1:]
    if line.startswith(prefix):
        return line[len(prefix):]
    return line


def _hprint(hlist):
    """takes an enumerated list of lines and prints number, tab, line
    """
    for i, line in hlist:
        print('{}\t{}'.format(i, line))


def subparser(subparsers):
    """Define the `kevlar split` command-line interface."""
    desc = 'Split partitioned reads into N output files.'
    subparser = subparsers.add_parser('split', description=desc)
    subparser.add_argument('infile', help=
        'input file; partitioned reads in augmented Fastq/Fasta format')
    subparser.add_argument('numfiles', type=int, help=
        'number of output files to create')
    subparser.add_argument('base', help='prefix of all output files')


def wrap_func_like_safe(func, func_like, *args, **kwargs):
    """
    Safe implementation for wrap_func_like(), attempts to use func_like(),
    if the shape keyword argument, falls back to func().
    """
    try:
        return func_like(*args, **kwargs)
    except TypeError:
        return func(*args, **kwargs)


def setup_argparser():
    """
    Returns an instance of argparse.ArgumentParser for git-guilt
    """
    import argparse
    parser = argparse.ArgumentParser(prog='git guilt', description=
        """
git-guilt is a custom tool written for git(1). It provides
information regarding the transfer of ownership between two
revisions of a repository.
        """
        .strip(), epilog=
        """
Please note that git-guilt needs git >= 1.7.2 in order to process binary files.
        """
        .strip())
    parser.add_argument('-e', '--email', action='store_true', help=
        "Causes git-guilt to report transfers of ownership using authors' email addresses instead of their names"
        )
    parser.add_argument('since', metavar='since', nargs='?', help=
        'The revision starting from which the transfer of blame should be reported'
        )
    parser.add_argument('until', metavar='until', nargs='?', help=
        'The revision until which the transfer of blame should be reported')
    return parser


def getSession(sessionInterface=None):
    """
        Look up the session associated with this request or create a new one if
        there is not one.

        @return: The L{Session} instance identified by the session cookie in
            the request, or the C{sessionInterface} component of that session
            if C{sessionInterface} is specified.
        """


def little_endian_to_int(b):
    """little_endian_to_int takes byte sequence as a little-endian number.
    Returns an integer"""
    return int.from_bytes(b, 'little')


def sizeof_fmt(num):
    """ Returns a human-friendly string when given a size in bytes """
    for x in ['bytes', 'kB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return '%3.1f %s' % (num, x)
        num /= 1024.0


def create_plane_track():
    """Create new plane track out of selected point tracks

    """
    pass


def distance_squared(a, b):
    """The square of the distance between two (x, y) points."""
    xA, yA = a
    xB, yB = b
    return (xA - xB) ** 2 + (yA - yB) ** 2


def _set_key2sl(key):
    """Convert a key part to a slice part."""
    if isinstance(key, int) or key is Ellipsis:
        return key
    elif isinstance(key, slice):
        if key.step is not None:
            raise ValueError('farray slice step is not supported')
        return key
    else:
        raise TypeError('expected int, slice, or ...')


def get_host_port(spec, default_port):
    """parse 'hostname:22' into a host and port, with the port optional"""
    args = (spec.split(':', 1) + [default_port])[:2]
    args[1] = int(args[1])
    return args[0], args[1]


def default_key_func(key, key_prefix, version):
    """
    Default function to generate keys.

    Constructs the key used by all other methods. By default it prepends
    the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
    function with custom key making behavior.
    """
    return '%s:%s:%s' % (key_prefix, version, key)


def do_purge_doc(app, env, docname):
    """ Clear markers for whether `docname` has seen a plot context reset
    """
    env.nbplot_reset_markers[docname] = False
    env.nbplot_flag_namespaces[docname] = env.config.nbplot_flags.copy()


@classmethod
def httpString(cls, languages):
    """
        Class method to convert a list of acceptable languages into a
        byte array.

        The byte array can be sent along with the Accept-Language http header
        (see RFC 2616).

        @param languages list of acceptable languages (list of strings)
        @return converted list (QByteArray)
        """
    processed = []
    qvalue = 1.0
    for language in languages:
        leftBracket = language.find('[')
        rightBracket = language.find(']')
        tag = language[leftBracket + 1:rightBracket]
        if not processed:
            processed.append(tag)
        else:
            processed.append('{0};q={1:.1f}'.format(tag, qvalue))
        if qvalue > 0.1:
            qvalue -= 0.1
    return ', '.join(processed)


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


@staticmethod
def _gen_initial_values(n_atoms, n_residues, n_segments):
    """Populate an initial empty data structure for this Attribute

        The only provided parameters are the "shape" of the Universe

        Eg for charges, provide np.zeros(n_atoms)
        """
    raise NotImplementedError('No default values')


@classmethod
def get_twitter_data(cls, request, ppm_id, handle):
    """
        Make a request to P2MD to fetch Twitter data and store it in PPM.
        """
    response = cls.post(request, f'/sources/api/twitter/{ppm_id}', {
        'handle': handle}, raw=True)
    return response.ok


def stream_details_from_catalog(catalog, stream_name):
    """
    Extract details for a single stream from the catalog
    """
    for stream_details in catalog.streams:
        if stream_details.tap_stream_id == stream_name:
            return stream_details
    return None


def is_undefined(obj):
    """Check if the object passed is undefined.  This does nothing more than
    performing an instance check against :class:`Undefined` but looks nicer.
    This can be used for custom filters or tests that want to react to
    undefined variables.  For example a custom default filter can look like
    this::

        def default(var, default=''):
            if is_undefined(var):
                return default
            return var
    """
    from nunavut.jinja.jinja2.runtime import Undefined
    return isinstance(obj, Undefined)


def system():
    """Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.

    An empty string is returned if the value cannot be determined.

    Returns
    -------
    str
        the system name.
    """
    import platform
    return platform.system()


def get_pending_vgroup(module, array):
    """ Get Deleted Volume Group"""
    vgroup = None
    for vgrp in array.list_vgroups(pending=True):
        if vgrp['name'] == module.params['vgroup'] and vgrp['time_remaining']:
            vgroup = vgrp
            break
    return vgroup


@staticmethod
def initialise_target(c, key):
    """
        Return a starting value for pressure and enthalpy at inlet.

        Parameters
        ----------
        c : tespy.connections.connection
            Connection to perform initialisation on.

        key : str
            Fluid property to retrieve.

        Returns
        -------
        val : float
            Starting value for pressure/enthalpy in SI units.

            .. math::

                val = \\begin{cases}
                5 \\cdot 10^5 & \\text{key = 'p'}\\\\
                5 \\cdot 10^5 & \\text{key = 'h'}
                \\end{cases}
        """
    if key == 'p':
        return 500000.0
    elif key == 'h':
        return 500000.0


def is_one_line_function_declaration_line(line: str) ->bool:
    """
    Check if line contains function declaration.
    """
    return 'def ' in line and '(' in line and '):' in line or ') ->' in line


@staticmethod
def slides_end_update(slides, others):
    """Update the end of slides accordinly to the start of others sectionings.

    Paramaters
    ----------
    slides: list
    others: list

    Returns
    -------
    slides: list
    """
    for slide in slides:
        for other in others:
            if slide['start'] < other['start'] and slide['end_next'] >= other[
                'start']:
                slide['end_next'] = other['start']
    return slides


def list_virtual_mfa_devices(AssignmentStatus=None, Marker=None, MaxItems=None
    ):
    """
    Lists the virtual MFA devices defined in the AWS account by assignment status. If you do not specify an assignment status, the action returns a list of all virtual MFA devices. Assignment status can be Assigned , Unassigned , or Any .
    You can paginate the results using the MaxItems and Marker parameters.
    See also: AWS API Documentation

    Examples
    The following command lists the virtual MFA devices that have been configured for the current account.
    Expected Output:

    :example: response = client.list_virtual_mfa_devices(
        AssignmentStatus='Assigned'|'Unassigned'|'Any',
        Marker='string',
        MaxItems=123
    )

    :type AssignmentStatus: string
    :param AssignmentStatus: The status (Unassigned or Assigned ) of the devices to list. If you do not specify an AssignmentStatus , the action defaults to Any which lists both assigned and unassigned virtual MFA devices.

    :type Marker: string
    :param Marker: Use this parameter only when paginating results and only after you receive a response indicating that the results are truncated. Set it to the value of the Marker element in the response that you received to indicate where the next call should start.

    :type MaxItems: integer
    :param MaxItems: (Optional) Use this only when paginating results to indicate the maximum number of items you want in the response. If additional items exist beyond the maximum you specify, the IsTruncated response element is true .
            If you do not include this parameter, it defaults to 100. Note that IAM might return fewer results, even when there are more results available. In that case, the IsTruncated response element returns true and Marker contains a value to include in the subsequent call that tells the service where to continue from.

    :rtype: dict
    :return: {
        'VirtualMFADevices': [
            {
                'SerialNumber': 'string',
                'Base32StringSeed': b'bytes',
                'QRCodePNG': b'bytes',
                'User': {
                    'Path': 'string',
                    'UserName': 'string',
                    'UserId': 'string',
                    'Arn': 'string',
                    'CreateDate': datetime(2015, 1, 1),
                    'PasswordLastUsed': datetime(2015, 1, 1)
                },
                'EnableDate': datetime(2015, 1, 1)
            },
        ],
        'IsTruncated': True|False,
        'Marker': 'string'
    }

    :returns:
    The user does not have a password
    The password exists but has never been used (at least not since IAM started tracking this information on October 20th, 2014
    there is no sign-in data associated with the user

    """
    pass


@staticmethod
def get_color_label():
    """Returns the default colorbar label
        """
    return None


def get_htdocs_dirs():
    """Return a list of directories with static resources (such as style
        sheets, images, etc.)

        Each item in the list must be a `(prefix, abspath)` tuple. The
        `prefix` part defines the path in the URL that requests to these
        resources are prefixed with.

        The `abspath` is the absolute path to the directory containing the
        resources on the local file system.
        """


def _CreateColorMap():
    """
    Creates a map from color to ESC color codes.
    """
    codes = {}
    _attrs = {'reset': '39;49;00m', 'bold': '01m', 'faint': '02m',
        'standout': '03m', 'underline': '04m', 'blink': '05m'}
    for _name, _value in _attrs.items():
        codes[_name] = '\x1b[' + _value
    _colors = [('black', 'darkgray'), ('darkred', 'red'), ('darkgreen',
        'green'), ('brown', 'yellow'), ('darkblue', 'blue'), ('purple',
        'fuchsia'), ('turqoise', 'teal'), ('lightgray', 'white')]
    for i, (dark, light) in enumerate(_colors):
        codes[dark] = '\x1b[%im' % (i + 30)
        codes[light] = '\x1b[%i;01m' % (i + 30)
    return codes


def laplaciandeform_bind(modifier: str=''):
    """Bind mesh to system in laplacian deform modifier

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


@classmethod
def fromkeys(cls, iterable, value=None):
    """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        """
    d = cls()
    for key in iterable:
        d[key] = value
    return d


@classmethod
def class_key(cls):
    """Nice order of classes."""
    return 3, 0, cls.__name__


def delete_file(filename):
    """
	Deletes a file if it exists.
	"""
    import os
    try:
        os.remove(filename)
    except OSError:
        pass
    return


def get_display_emails():
    """ Get whether it should display emails.
        """


@classmethod
def get_by_id(cls, context, id):
    """Return a specific object by its unique identifier."""


def getStatus():
    """Returns the current HTTP status code as an integer.
        """


@classmethod
def parse(cls, buff, offset):
    """
        Given a buffer and offset, returns the parsed value and new offset.

        Calls `parse()` on the given buffer for each sub-part in order and
        creates a new instance with the results.
        """
    values = {}
    for name, part in cls.parts:
        value, new_offset = part.parse(buff, offset)
        values[name] = value
        offset = new_offset
    return cls(**values), offset


@classmethod
def construct_index(cls, name):
    """
        Force the query to use a certain index

        Parameters
        ----------
        name : str

        Returns
        -------
        condition : :class:`.Condition`

        """
    c = cls()
    c.index_name = name
    return c


def alternating_values(initial_value=False):
    """
    Provides an infinite source of values alternating between :data:`True` and
    :data:`False`, starting wth *initial_value* (which defaults to
    :data:`False`). For example, to produce a flashing LED::

        from gpiozero import LED
        from gpiozero.tools import alternating_values
        from signal import pause

        red = LED(2)

        red.source_delay = 0.5
        red.source = alternating_values()

        pause()
    """
    value = initial_value
    while True:
        yield value
        value = not value


def diag_item_get_length(item):
    """Returns the item length according to the item_type

    :param item: item to look at
    :type item: :class:`SAPDiagItem`

    :return: the item length
    :rtype: ``int``
    """
    diag_item_sizes = {(1): 16, (2): 20, (3): 3, (7): 76, (8): 0, (9): 22,
        (10): 3, (11): 2, (12): 0, (16): item.item_length, (17): item.
        item_length4, (18): item.item_length4, (19): 2, (21): 36}
    return diag_item_sizes[item.item_type]


def cols_to_reduce_uniques(df, column_threshold_dict):
    """Reduce the number of unique values by creating a column of X values and the rest marked "Others".

    Args:
        df: Pandas dataframe.
        columns: Dictionary of column and threshold, i.e. {'col1' : 1000, 'col2' : 3000}

    Returns:
        Original dataframe with additional prefixed columns. The most dominant values in the column will
        be assigned their original value. The less dominant results will be assigned to Others, which can
        help visualise and model data in some cases.
    """
    for key, value in column_threshold_dict.items():
        counts = df[key].value_counts()
        others = set(counts[counts < value].index)
        df['reduce_' + key] = df[key].replace(list(others), 'Others')
    return df


def generate_aperture(xsize, ysize, xcenter, ycenter, radius):
    """Makes a mask (1 = inside aperture) for a circular aperture"""
    import numpy
    x, y = numpy.mgrid[0.5:xsize, 0.5:ysize]
    mask = ((x - xcenter) ** 2 + (y - ycenter) ** 2 <= radius ** 2) * 1
    return mask


def clone_plugin_data(dashboard_entry, request=None):
    """Clone plugin data of a dashboard entry."""
    if dashboard_entry:
        plugin = dashboard_entry.get_plugin(request=request)
        if plugin:
            plugin_data = plugin._clone_plugin_data(dashboard_entry)
            if plugin_data is None:
                plugin_data = dashboard_entry.plugin_data
            return plugin_data


def PrettyUserAgent(family, v1=None, v2=None, v3=None):
    """Pretty user agent string."""
    if v3:
        if v3[0].isdigit():
            return '%s %s.%s.%s' % (family, v1, v2, v3)
        else:
            return '%s %s.%s%s' % (family, v1, v2, v3)
    elif v2:
        return '%s %s.%s' % (family, v1, v2)
    elif v1:
        return '%s %s' % (family, v1)
    return family


def register(default):
    """Register utility"""


def wkt_vcs(vcs):
    """
    Compose a wkt VERTCS block from a Geosoft vcs string.

    .. versionadded:: 9.2
    """
    return 'VERTCS["' + vcs + '"]'


def release_branch_name(config):
    """
    build expected release branch name from current config

    """
    branch_name = '{0}{1}'.format(config.gitflow_release_prefix(), config.
        package_version())
    return branch_name


def get_event():
    """Return a Collection instance for events collection/table"""
    raise NotImplementedError()


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

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

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


def release_hosts(HostIds=None):
    """
    When you no longer want to use an On-Demand Dedicated Host it can be released. On-Demand billing is stopped and the host goes into released state. The host ID of Dedicated Hosts that have been released can no longer be specified in another request, e.g., ModifyHosts. You must stop or terminate all instances on a host before it can be released.
    When Dedicated Hosts are released, it make take some time for them to stop counting toward your limit and you may receive capacity errors when trying to allocate new Dedicated hosts. Try waiting a few minutes, and then try again.
    Released hosts will still appear in a  DescribeHosts response.
    See also: AWS API Documentation

    :example: response = client.release_hosts(
        HostIds=[
            'string',
        ]
    )

    :type HostIds: list
    :param HostIds: [REQUIRED]
            The IDs of the Dedicated Hosts you want to release.
            (string) --

    :rtype: dict
    :return: {
        'Successful': [
            'string',
        ],
        'Unsuccessful': [
            {
                'ResourceId': 'string',
                'Error': {
                    'Code': 'string',
                    'Message': 'string'
                }
            },
        ]
    }

    :returns:
    (string) --

    """
    pass


def create_topic_rule(ruleName=None, topicRulePayload=None):
    """
    Creates a rule. Creating rules is an administrator-level action. Any user who has permission to create rules will be able to access data processed by the rule.
    See also: AWS API Documentation

    :example: response = client.create_topic_rule(
        ruleName='string',
        topicRulePayload={
            'sql': 'string',
            'description': 'string',
            'actions': [
                {
                    'dynamoDB': {
                        'tableName': 'string',
                        'roleArn': 'string',
                        'operation': 'string',
                        'hashKeyField': 'string',
                        'hashKeyValue': 'string',
                        'hashKeyType': 'STRING'|'NUMBER',
                        'rangeKeyField': 'string',
                        'rangeKeyValue': 'string',
                        'rangeKeyType': 'STRING'|'NUMBER',
                        'payloadField': 'string'
                    },
                    'dynamoDBv2': {
                        'roleArn': 'string',
                        'putItem': {
                            'tableName': 'string'
                        }
                    },
                    'lambda': {
                        'functionArn': 'string'
                    },
                    'sns': {
                        'targetArn': 'string',
                        'roleArn': 'string',
                        'messageFormat': 'RAW'|'JSON'
                    },
                    'sqs': {
                        'roleArn': 'string',
                        'queueUrl': 'string',
                        'useBase64': True|False
                    },
                    'kinesis': {
                        'roleArn': 'string',
                        'streamName': 'string',
                        'partitionKey': 'string'
                    },
                    'republish': {
                        'roleArn': 'string',
                        'topic': 'string'
                    },
                    's3': {
                        'roleArn': 'string',
                        'bucketName': 'string',
                        'key': 'string',
                        'cannedAcl': 'private'|'public-read'|'public-read-write'|'aws-exec-read'|'authenticated-read'|'bucket-owner-read'|'bucket-owner-full-control'|'log-delivery-write'
                    },
                    'firehose': {
                        'roleArn': 'string',
                        'deliveryStreamName': 'string',
                        'separator': 'string'
                    },
                    'cloudwatchMetric': {
                        'roleArn': 'string',
                        'metricNamespace': 'string',
                        'metricName': 'string',
                        'metricValue': 'string',
                        'metricUnit': 'string',
                        'metricTimestamp': 'string'
                    },
                    'cloudwatchAlarm': {
                        'roleArn': 'string',
                        'alarmName': 'string',
                        'stateReason': 'string',
                        'stateValue': 'string'
                    },
                    'elasticsearch': {
                        'roleArn': 'string',
                        'endpoint': 'string',
                        'index': 'string',
                        'type': 'string',
                        'id': 'string'
                    }
                },
            ],
            'ruleDisabled': True|False,
            'awsIotSqlVersion': 'string'
        }
    )

    :type ruleName: string
    :param ruleName: [REQUIRED]
            The name of the rule.

    :type topicRulePayload: dict
    :param topicRulePayload: [REQUIRED]
            The rule payload.
            sql (string) -- [REQUIRED]The SQL statement used to query the topic. For more information, see AWS IoT SQL Reference in the AWS IoT Developer Guide .
            description (string) --The description of the rule.
            actions (list) -- [REQUIRED]The actions associated with the rule.
            (dict) --Describes the actions associated with a rule.
            dynamoDB (dict) --Write to a DynamoDB table.
            tableName (string) -- [REQUIRED]The name of the DynamoDB table.
            roleArn (string) -- [REQUIRED]The ARN of the IAM role that grants access to the DynamoDB table.
            operation (string) --The type of operation to be performed. This follows the substitution template, so it can be ${operation} , but the substitution must result in one of the following: INSERT , UPDATE , or DELETE .
            hashKeyField (string) -- [REQUIRED]The hash key name.
            hashKeyValue (string) -- [REQUIRED]The hash key value.
            hashKeyType (string) --The hash key type. Valid values are 'STRING' or 'NUMBER'
            rangeKeyField (string) --The range key name.
            rangeKeyValue (string) --The range key value.
            rangeKeyType (string) --The range key type. Valid values are 'STRING' or 'NUMBER'
            payloadField (string) --The action payload. This name can be customized.
            dynamoDBv2 (dict) --Write to a DynamoDB table. This is a new version of the DynamoDB action. It allows you to write each attribute in an MQTT message payload into a separate DynamoDB column.
            roleArn (string) --The ARN of the IAM role that grants access to the DynamoDB table.
            putItem (dict) --Specifies the DynamoDB table to which the message data will be written. For example:
            { 'dynamoDBv2': { 'roleArn': 'aws:iam:12341251:my-role' 'putItem': { 'tableName': 'my-table' } } }
            Each attribute in the message payload will be written to a separate column in the DynamoDB database.
            tableName (string) -- [REQUIRED]The table where the message data will be written

            lambda (dict) --Invoke a Lambda function.
            functionArn (string) -- [REQUIRED]The ARN of the Lambda function.
            sns (dict) --Publish to an Amazon SNS topic.
            targetArn (string) -- [REQUIRED]The ARN of the SNS topic.
            roleArn (string) -- [REQUIRED]The ARN of the IAM role that grants access.
            messageFormat (string) --The message format of the message to publish. Optional. Accepted values are 'JSON' and 'RAW'. The default value of the attribute is 'RAW'. SNS uses this setting to determine if the payload should be parsed and relevant platform-specific bits of the payload should be extracted. To read more about SNS message formats, see http://docs.aws.amazon.com/sns/latest/dg/json-formats.html refer to their official documentation.
            sqs (dict) --Publish to an Amazon SQS queue.
            roleArn (string) -- [REQUIRED]The ARN of the IAM role that grants access.
            queueUrl (string) -- [REQUIRED]The URL of the Amazon SQS queue.
            useBase64 (boolean) --Specifies whether to use Base64 encoding.
            kinesis (dict) --Write data to an Amazon Kinesis stream.
            roleArn (string) -- [REQUIRED]The ARN of the IAM role that grants access to the Amazon Kinesis stream.
            streamName (string) -- [REQUIRED]The name of the Amazon Kinesis stream.
            partitionKey (string) --The partition key.
            republish (dict) --Publish to another MQTT topic.
            roleArn (string) -- [REQUIRED]The ARN of the IAM role that grants access.
            topic (string) -- [REQUIRED]The name of the MQTT topic.
            s3 (dict) --Write to an Amazon S3 bucket.
            roleArn (string) -- [REQUIRED]The ARN of the IAM role that grants access.
            bucketName (string) -- [REQUIRED]The Amazon S3 bucket.
            key (string) -- [REQUIRED]The object key.
            cannedAcl (string) --The Amazon S3 canned ACL that controls access to the object identified by the object key. For more information, see S3 canned ACLs .
            firehose (dict) --Write to an Amazon Kinesis Firehose stream.
            roleArn (string) -- [REQUIRED]The IAM role that grants access to the Amazon Kinesis Firehost stream.
            deliveryStreamName (string) -- [REQUIRED]The delivery stream name.
            separator (string) --A character separator that will be used to separate records written to the Firehose stream. Valid values are: 'n' (newline), 't' (tab), 'rn' (Windows newline), ',' (comma).
            cloudwatchMetric (dict) --Capture a CloudWatch metric.
            roleArn (string) -- [REQUIRED]The IAM role that allows access to the CloudWatch metric.
            metricNamespace (string) -- [REQUIRED]The CloudWatch metric namespace name.
            metricName (string) -- [REQUIRED]The CloudWatch metric name.
            metricValue (string) -- [REQUIRED]The CloudWatch metric value.
            metricUnit (string) -- [REQUIRED]The metric unit supported by CloudWatch.
            metricTimestamp (string) --An optional Unix timestamp .
            cloudwatchAlarm (dict) --Change the state of a CloudWatch alarm.
            roleArn (string) -- [REQUIRED]The IAM role that allows access to the CloudWatch alarm.
            alarmName (string) -- [REQUIRED]The CloudWatch alarm name.
            stateReason (string) -- [REQUIRED]The reason for the alarm change.
            stateValue (string) -- [REQUIRED]The value of the alarm state. Acceptable values are: OK, ALARM, INSUFFICIENT_DATA.
            elasticsearch (dict) --Write data to an Amazon Elasticsearch Service domain.
            roleArn (string) -- [REQUIRED]The IAM role ARN that has access to Elasticsearch.
            endpoint (string) -- [REQUIRED]The endpoint of your Elasticsearch domain.
            index (string) -- [REQUIRED]The Elasticsearch index where you want to store your data.
            type (string) -- [REQUIRED]The type of document you are storing.
            id (string) -- [REQUIRED]The unique identifier for the document you are storing.

            ruleDisabled (boolean) --Specifies whether the rule is disabled.
            awsIotSqlVersion (string) --The version of the SQL rules engine to use when evaluating the rule.

    """
    pass


def bitwise_add(a: int, b: int) ->int:
    """Merge two binary masks together."""
    return a | b


@staticmethod
def get_connection_arguments_model():
    """
        This is needed so the BaseConnection can validate the provided
        model explicitly states the arguments to be passed on each
        send message.
        return = {
            'required_connection_arguments': {
                'required_connection_arg_1': type,
                'required_connection_arg_2': type,
            },
            'optional_connection_arguments': {
                'optional_connection_arg_1': type,
                'optional_connection_arg_2': type,
            },
        }
        """
    return {'required_connection_arguments': {},
        'optional_connection_arguments': {}}


def get_base_attr(klass, attr):
    """Retrieves a class attribute from one of the bases of self.

    Arguments:
        klass: The class you want to get the class base attribute from.

    Returns:
        The class attribute in question, or None if not found.
    """
    for base_ in klass.__bases__:
        if base_ == klass:
            continue
        if not hasattr(base_, attr):
            continue
        return getattr(base_, attr)


def parenthesise(_value):
    """Adds a parenthesis around a values."""
    return '(' + _value + ')'


@classmethod
def terminator(cls, id_):
    """Message which follows a EXECCOMMAND to make the server send
        the terminating responses.
        :returns: an :class:`RCONMessage` which represents an empty
            ``RESPONSE_VALUE``"""
    return cls(id_, cls.Type.RESPONSE_VALUE, b'')


def is_url(url: str) ->bool:
    """Return True if a string is a URL.

    >>> is_url("")
    False
    >>> is_url("  ")
    False
    >>> is_url("http://example.com")
    True
    """
    return url.startswith('http')


@staticmethod
def _get_name_from_dn(dn):
    """
        Get the instance name from the dn

        :param dn: string containing the distinguished name URL
        :return: string containing the name
        """
    name = dn.split('/if-')[1].split('/')[0]
    return name


def find_duplicates_in_array(array):
    """Runs through the array and returns the elements that contain
    more than one duplicate

    Args:
        array: The array to check for duplicates.

    Returns:
        Array of the elements that are duplicates. Returns empty list if
        there are no duplicates.
    """
    duplicates = []
    non_duplicates = []
    if len(array) != len(set(array)):
        for item in array:
            if item not in non_duplicates:
                non_duplicates.append(item)
            elif item in non_duplicates and item not in duplicates:
                duplicates.append(item)
    return duplicates


def yntobool(char):
    """ Interpret a char as Boolean. """
    if char == 'Y':
        return True
    elif char == 'N':
        return False
    else:
        raise Exception('Cannot interpret %s as boolean' % char)


def create_platform_version(PlatformName=None, PlatformVersion=None,
    PlatformDefinitionBundle=None, EnvironmentName=None, OptionSettings=None):
    """
    Create a new version of your custom platform.
    See also: AWS API Documentation

    :example: response = client.create_platform_version(
        PlatformName='string',
        PlatformVersion='string',
        PlatformDefinitionBundle={
            'S3Bucket': 'string',
            'S3Key': 'string'
        },
        EnvironmentName='string',
        OptionSettings=[
            {
                'ResourceName': 'string',
                'Namespace': 'string',
                'OptionName': 'string',
                'Value': 'string'
            },
        ]
    )

    :type PlatformName: string
    :param PlatformName: [REQUIRED]
            The name of your custom platform.

    :type PlatformVersion: string
    :param PlatformVersion: [REQUIRED]
            The number, such as 1.0.2, for the new platform version.

    :type PlatformDefinitionBundle: dict
    :param PlatformDefinitionBundle: [REQUIRED]
            The location of the platform definition archive in Amazon S3.
            S3Bucket (string) --The Amazon S3 bucket where the data is located.
            S3Key (string) --The Amazon S3 key where the data is located.

    :type EnvironmentName: string
    :param EnvironmentName: The name of the builder environment.

    :type OptionSettings: list
    :param OptionSettings: The configuration option settings to apply to the builder environment.
            (dict) --A specification identifying an individual configuration option along with its current value. For a list of possible option values, go to Option Values in the AWS Elastic Beanstalk Developer Guide .
            ResourceName (string) --A unique resource name for a time-based scaling configuration option.
            Namespace (string) --A unique namespace identifying the option's associated AWS resource.
            OptionName (string) --The name of the configuration option.
            Value (string) --The current value for the configuration option.

    :rtype: dict
    :return: {
        'PlatformSummary': {
            'PlatformArn': 'string',
            'PlatformOwner': 'string',
            'PlatformStatus': 'Creating'|'Failed'|'Ready'|'Deleting'|'Deleted',
            'PlatformCategory': 'string',
            'OperatingSystemName': 'string',
            'OperatingSystemVersion': 'string',
            'SupportedTierList': [
                'string',
            ],
            'SupportedAddonList': [
                'string',
            ]
        },
        'Builder': {
            'ARN': 'string'
        }
    }

    :returns:
    (string) --

    """
    pass


@classmethod
def from_primary_keys(cls, **pks):
    """ return the instance of the model from the primary keys

        :param **pks: dict {primary_key: value, ...}
        :rtype: instance of the model
        """
    where_clause = cls.get_where_clause_from_primary_keys(**pks)
    query = cls.query().filter(*where_clause)
    if query.count():
        return query.first()
    return None


@staticmethod
def actions():
    """Dictionary of actions that can be performed on object

        Returns:
            Dict[str, str]: Dictionary of actions that can be performed on object
        """
    return {'show': 'vocabulary_show', 'update': 'vocabulary_update',
        'create': 'vocabulary_create', 'delete': 'vocabulary_delete',
        'list': 'vocabulary_list'}


def check_structures_size(flow_struct_defined, flow_struct_loaded,
    id_struct_defined, id_struct_loaded, tcp_flow_struct_defined,
    tcp_flow_struct_loaded, udp_flow_struct_defined, udp_flow_struct_loaded):
    """ Function used to check loaded structures sizes againt defined ones """
    errors = []
    if flow_struct_defined != flow_struct_loaded:
        errors.append('ndpi_flow_struct')
    if id_struct_defined != id_struct_loaded:
        errors.append('ndpi_id_struct')
    if tcp_flow_struct_defined != tcp_flow_struct_loaded:
        errors.append('ndpi_tcp_flow_struct')
    if udp_flow_struct_defined != udp_flow_struct_loaded:
        errors.append('ndpi_udp_flow_struct')
    return errors


def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None,
    HttpMethod=None):
    """
    Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
            ClientMethod.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
            default, the http method is whatever is used in the method's model.

    """
    pass


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

        :param SharedFileMetadata val:
        :rtype: GetFileMetadataIndividualResult
        """
    return cls('metadata', val)


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


@classmethod
def generate_single_float_sql_eq(cls, column_name, filter_value):
    """Return tuple with sql and replacement.

        This function builds the sql partial and replacement dict for
        an equivalency match for a single float against a single
        column in the database.

        Args:
            column_name (str): Name of column in DB.
            filter_value (str or float): This is what we look for in the column.
                Coerced to float.

        Returns:
            tuple: Item 0 contains the SQL partial string. Item 1 contains
                the replacement dictionary.

        """
    sql = '{} = :{}'.format(column_name, column_name)
    replacement = {column_name: float(filter_value)}
    return sql, replacement


def treversed(*args, **kwargs):
    """Like reversed, but returns a tuple."""
    return tuple(reversed(*args, **kwargs))


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 list_policy_attachments(DirectoryArn=None, PolicyReference=None,
    NextToken=None, MaxResults=None, ConsistencyLevel=None):
    """
    Returns all of the ObjectIdentifiers to which a given policy is attached.
    See also: AWS API Documentation

    :example: response = client.list_policy_attachments(
        DirectoryArn='string',
        PolicyReference={
            'Selector': 'string'
        },
        NextToken='string',
        MaxResults=123,
        ConsistencyLevel='SERIALIZABLE'|'EVENTUAL'
    )

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

    :type PolicyReference: dict
    :param PolicyReference: [REQUIRED]
            The reference that identifies the policy 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

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

    :type MaxResults: integer
    :param MaxResults: The maximum number of items to be retrieved in a single call. This is an approximate number.

    :type ConsistencyLevel: string
    :param ConsistencyLevel: Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object.

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

    :returns:
    (string) --

    """
    pass


def read_dictionary(filename: str) ->list:
    """
    creates a list of words from a file containing all possible words

    Arguments:
    :param filename: a string containing the filename of the dictionary file
    """
    with open(filename) as dictionary_file:
        return dictionary_file.read().split()


def find_set_selected():
    """Find specified text and set as selected

    """
    pass


@classmethod
def get_member_lists_for_user(klass, user):
    """
        Returns an iterable of the visible member lists for a given USER
        """
    for l in klass.get_member_lists():
        if l.visible_to(user):
            yield l


def twoset_segment_metrics_to_list(twoset_metrics_results):
    """ Converting detailed event metric results to a list (position of each item is fixed)

    Argument:
        twoset_metrics_results (dictionary): as provided by the 1st item in the results of eval_events function

    Returns:
        list: Item order: 0. true positive rate, 1. deletion rate 2. fragmenting rate, 3. start underfill rate, 4. end underfill rate, 5. 1 - false positive rate, 6. insertion rate, 7. merge rate, 8. start overfill rate, 9. end overfill rate
    """
    return [twoset_metrics_results['tpr'], twoset_metrics_results['dr'],
        twoset_metrics_results['fr'], twoset_metrics_results['us'],
        twoset_metrics_results['ue'], 1 - twoset_metrics_results['fpr'],
        twoset_metrics_results['ir'], twoset_metrics_results['mr'],
        twoset_metrics_results['os'], twoset_metrics_results['oe']]


@staticmethod
def is_file(s3elem):
    """
        Return true is an s3 json element represents a valid file
        """
    try:
        key = s3elem['Key']
    except KeyError:
        return False
    name = key.rpartition('/')[-1]
    if not name:
        return False
    return True


def coord_to_grid(coord, die_size, grid_center):
    """
    Convert a panel coordinate to a grid value.

    Parameters
    ----------
    coord : tuple
        A 2-tuple of (x, y) floating point values for the panel coordinate

    die_size : tuple
        A 2-tuple of (x, y) floating point values for the die size

    grid_center : tuple
        A 2-tuple of (grid_x, grid_y) values that represents the origin of
        the wafer in grid coordinates.

    Returns
    -------
    (grid_x, grid_y) : tuple
        The grid coordinates. Also known as (column, row).
    """
    grid_x = int(round(grid_center[0] + coord[0] / die_size[0]))
    grid_y = int(round(grid_center[1] - coord[1] / die_size[1]))
    return grid_x, grid_y


@staticmethod
def quote_string_escape(in_data):
    """
        escapes quotes in given string

        :param in_data: input string
        :type in_data: str, unicode
        :return: input string with quotes escaped
        :rtype: str, unicode
        """
    return in_data.replace("'", "\\'")


def adapter_removal_parser(filename):
    """Parses output of AdapterRemoval software

    .. doctest::

        >>> from sequana import adapters, sequana_data
        >>> data = sequana_data("test_adapter_removal_output.txt", "testing")
        >>> results = adapters.adapter_removal_parser(data)
        >>> results["adapter1"]
        'AGATCGGAAGAGCACACGTCTGAACTCCAGTCACNNNNNNATCTCGTATGCCGTCTTCTGCTTG'

    """
    results = {}
    with open(filename, 'r') as fin:
        lines = fin.readlines()
        for line in lines:
            if line.startswith('  --adapter'):
                lhs, rhs = line.split(':')
                name = lhs.strip().replace('-', '')
                sequence = rhs.strip()
                results[name] = sequence
    return results


def bam_indexing(samtools, variable_name):
    """Will take a file variable name and a samtools path and will print
    bash code that will create a bam index using samtools """
    return ('# Indexing\n' + samtools + ' index $' + variable_name +
        ' >> $logFile 2>&1')