Validate a Bech32 string, and determine HRP and data.
6576
def bech32_decode(bech):
    """"""
    if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
            (bech.lower() != bech and bech.upper() != bech)):
        return None, None
    bech = bech.lower()
    pos = bech.rfind('1')
    if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
        return None, None
    if not all(x in CHARSET for x in bech[pos+1:]):
        return None, None
    hrp = bech[:pos]
    data = [CHARSET.find(x) for x in bech[pos+1:]]
    if not bech32_verify_checksum(hrp, data):
        return None, None
    return hrp, data[:-6]
1326694
def decode(addr):
    """"""
    hrpgot, data = bech32_decode(addr)
    # if hrpgot != hrp:
    if hrpgot not in BECH32_VERSION_SET:
        return (None, None)
    decoded = convertbits(data[1:], 5, 8, False)
    if decoded is None or len(decoded) < 2 or len(decoded) > 40:
        return (None, None)
    if data[0] > 16:
        return (None, None)
    if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
        return (None, None)
    return (data[0], decoded)
398394
def validate(self):
        """"""
        if not isinstance(self.fields, dict):
            raise TypeError(u'Expected dict fields, got: {} {}'.format(
                type(self.fields).__name__, self.fields))

        for key, value in six.iteritems(self.fields):
            validate_safe_string(key)
            if not isinstance(value, Expression):
                raise TypeError(
                    u'Expected Expression values in the fields dict, got: '
                    u'{} -> {}'.format(key, value))
512246
def input_validate_str(string, name, max_len=None, exact_len=None):
    
    if type(string) is not str:
        raise pyhsm.exception.YHSM_WrongInputType(name, str, type(string))
    if max_len != None and len(string) > max_len:
        raise pyhsm.exception.YHSM_InputTooLong(name, max_len, len(string))
    if exact_len != None and len(string) != exact_len:
        raise pyhsm.exception.YHSM_WrongInputSize(name, exact_len, len(string))
    return string
1313899
def __CheckValid(self, value):
        ""
        val = self.__val
        self.is_valid = True
        try:
            val = set_float(value)
            if self.__min is not None and (val < self.__min):
                self.is_valid = False
                val = self.__min
            if self.__max is not None and (val > self.__max):
                self.is_valid = False
                val = self.__max
        except:
            self.is_valid = False
        self.__bound_val = self.__val = val
        fgcol, bgcol = self.fgcol_valid, self.bgcol_valid
        if not self.is_valid:
            fgcol, bgcol = self.fgcol_invalid, self.bgcol_invalid

        self.SetForegroundColour(fgcol)
        self.SetBackgroundColour(bgcol)
        self.Refresh()
549578
def _validate_int(name, value, limits=(), strip='%'):
    '''
    
    '''
    comment = ''
    # Must be integral
    try:
        if isinstance(value, string_types):
            value = value.strip(' ' + strip)
        value = int(value)
    except (TypeError, ValueError):
        comment += '{0} must be an integer '.format(name)
    # Must be in range
    else:
        if len(limits) == 2:
            if value < limits[0] or value > limits[1]:
                comment += '{0} must be in the range [{1[0]}, {1[1]}] '.format(name, limits)
    return value, comment
63916
def validate_appname_or_none(option, value):
    """"""
    if value is None:
        return value
    validate_string(option, value)
    # We need length in bytes, so encode utf8 first.
    if len(value.encode('utf-8')) > 128:
        raise ValueError("%s must be <= 128 bytes" % (option,))
    return value
1317141
def _validate_timeout(seconds: float):
    """"""
    val = int(seconds * 1000)
    assert 60000 <= val <= 4294967294, "Bad value: {}".format(val)
    return val
383959
def validate(self, ip, **kwargs):
        """"""
        
        if ip is None:
            return False

        ip = stringify(ip)

        if self.IPV4_REGEX.match(ip):

            try:
                socket.inet_pton(socket.AF_INET, ip)
                return True
            except AttributeError:  # no inet_pton here, sorry
                try:
                    socket.inet_aton(ip)
                except socket.error:
                    return False
                return ip.count('.') == 3
            except socket.error:  # not a valid address
                return False

        if self.IPV6_REGEX.match(ip):
            try:
                socket.inet_pton(socket.AF_INET6, ip)
            except socket.error:  # not a valid address
                return False
            return True
70195
def is_valid(self, qstr=None):
        """"""
        if qstr is None:
            qstr = self.currentText()
        return QUrl(qstr).isValid()
679366
def validate(self):
        """"""
        errors = []
        app = errors.append

        if not self.hint_cores >= self.mpi_procs * self.omp_threads >= self.min_cores:
            app("self.hint_cores >= mpi_procs * omp_threads >= self.min_cores not satisfied")

        if self.omp_threads > self.hw.cores_per_node:
            app("omp_threads > hw.cores_per_node")

        if self.mem_per_proc > self.hw.mem_per_node:
            app("mem_mb >= self.hw.mem_per_node")

        if not self.max_mem_per_proc >= self.mem_per_proc >= self.min_mem_per_proc:
            app("self.max_mem_per_proc >= mem_mb >= self.min_mem_per_proc not satisfied")

        if self.priority <= 0:
            app("priority must be > 0")

        if not (1 <= self.min_cores <= self.hw.num_cores >= self.hint_cores):
            app("1 <= min_cores <= hardware num_cores >= hint_cores not satisfied")

        if errors:
            raise self.Error(str(self) + "\n".join(errors))
592260
def _validate(self):
        
        if self.data_format is FormatType.PYTHON:
            self.data = self.raw_data
        elif self.data_format is FormatType.JSON:
            self._validate_json()
        elif self.data_format is FormatType.YAML:
            self._validate_yaml()
343814
def validate(config):
    '''
    
    '''

    # Configuration for load beacon should be a list of dicts
    if not isinstance(config, list):
        return False, ('Configuration for load beacon must be a list.')
    else:
        _config = {}
        list(map(_config.update, config))

        if 'emitatstartup' in _config:
            if not isinstance(_config['emitatstartup'], bool):
                return False, ('Configuration for load beacon option '
                               'emitatstartup must be a boolean.')

        if 'onchangeonly' in _config:
            if not isinstance(_config['onchangeonly'], bool):
                return False, ('Configuration for load beacon option '
                               'onchangeonly must be a boolean.')

        if 'averages' not in _config:
            return False, ('Averages configuration is required'
                           ' for load beacon.')
        else:

            if not any(j in ['1m', '5m', '15m'] for j
                       in _config.get('averages', {})):
                return False, ('Averages configuration for load beacon '
                               'must contain 1m, 5m or 15m items.')

            for item in ['1m', '5m', '15m']:
                if not isinstance(_config['averages'][item], list):
                    return False, ('Averages configuration for load beacon: '
                                   '1m, 5m and 15m items must be '
                                   'a list of two items.')
                else:
                    if len(_config['averages'][item]) != 2:
                        return False, ('Configuration for load beacon: '
                                       '1m, 5m and 15m items must be '
                                       'a list of two items.')

    return True, 'Valid beacon configuration'
1203709
def __validate_datetime_string(self):
        

        try:
            try:
                StrictVersion(self._value)
                raise TypeConversionError(
                    "invalid datetime string: version string found {}".format(self._value)
                )
            except ValueError:
                pass
        except TypeError:
            raise TypeConversionError("invalid datetime string: type={}".format(type(self._value)))
192600
def verify(path):
        """"""
        valid = False
        try:
            h5 = h5py.File(path, mode="r")
            qpi0 = h5["qpi_0"]
        except (OSError, KeyError):
            pass
        else:
            if ("qpimage version" in qpi0.attrs and
                "phase" in qpi0 and
                "amplitude" in qpi0 and
                "bg_data" in qpi0["phase"] and
                    "bg_data" in qpi0["amplitude"]):
                valid = True
        return valid
916748
def isPe32(self):
        
        if self.ntHeaders.optionalHeader.magic.value == consts.PE32:
            return True
        return False
103760
def validate_text(value):
    """"""
    possible_transform = ['axes', 'fig', 'data']
    validate_transform = ValidateInStrings('transform', possible_transform,
                                           True)
    tests = [validate_float, validate_float, validate_str,
             validate_transform, dict]
    if isinstance(value, six.string_types):
        xpos, ypos = rcParams['texts.default_position']
        return [(xpos, ypos, value, 'axes', {'ha': 'right'})]
    elif isinstance(value, tuple):
        value = [value]
    try:
        value = list(value)[:]
    except TypeError:
        raise ValueError("Value must be string or list of tuples!")
    for i, val in enumerate(value):
        try:
            val = tuple(val)
        except TypeError:
            raise ValueError(
                "Text must be an iterable of the form "
                "(x, y, s[, trans, params])!")
        if len(val) < 3:
            raise ValueError(
                "Text tuple must at least be like [x, y, s], with floats x, "
                "y and string s!")
        elif len(val) == 3 or isinstance(val[3], dict):
            val = list(val)
            val.insert(3, 'data')
            if len(val) == 4:
                val += [{}]
            val = tuple(val)
        if len(val) > 5:
            raise ValueError(
                "Text tuple must not be longer then length 5. It can be "
                "like (x, y, s[, trans, params])!")
        value[i] = (validate(x) for validate, x in zip(tests, val))
    return value