Make sure key is a valid python attribute
168311
def normalise_key(self, key):
        """"""
        key = key.replace('-', '_')
        if key.startswith("noy_"):
            key = key[4:]
        return key
790854
def make_compare(key, value, obj):
    ""
    if '__' not in key:
        # If no __ exists, default to doing an "exact" comparison
        key, comp = key, 'exact'
    else:
        key, comp = key.rsplit('__', 1)
    # Check if comp is valid
    if hasattr(Compare, comp):
        return getattr(Compare, comp)(key, value, obj)
    raise AttributeError("No comparison '%s'" % comp)
447985
def valid_id(opts, id_):
    '''
    
    '''
    try:
        if any(x in id_ for x in ('/', '\\', str('\0'))):
            return False
        return bool(clean_path(opts['pki_dir'], id_))
    except (AttributeError, KeyError, TypeError, UnicodeDecodeError):
        return False
923049
def _validate_key(self, key):
        
        if key == () and len(self.kdims) == 0: return ()
        key = util.wrap_tuple(key)
        assert len(key) == len(self.kdims)
        for ind, val in enumerate(key):
            kdim = self.kdims[ind]
            low, high = util.max_range([kdim.range, kdim.soft_range])
            if util.is_number(low) and util.isfinite(low):
                if val < low:
                    raise KeyError("Key value %s below lower bound %s"
                                   % (val, low))
            if util.is_number(high) and util.isfinite(high):
                if val > high:
                    raise KeyError("Key value %s above upper bound %s"
                                   % (val, high))
169545
def check_valid_keys(self, obj):
        
        invalid_keys = [
            x for x in obj if x not in self.defaults
        ]
        if invalid_keys:
            raise ValueError(
                "No such model parameters: %s. Valid parameters are: %s"
                % (" ".join(invalid_keys),
                    " ".join(self.defaults)))
1317840
def _safe_attr(attr, camel_killer=False, replacement_char='x'):
    """"""
    allowed = string.ascii_letters + string.digits + '_'

    attr = _safe_key(attr)

    if camel_killer:
        attr = _camel_killer(attr)

    attr = attr.replace(' ', '_')

    out = ''
    for character in attr:
        out += character if character in allowed else "_"
    out = out.strip("_")

    try:
        int(out[0])
    except (ValueError, IndexError):
        pass
    else:
        out = '{0}{1}'.format(replacement_char, out)

    if out in kwlist:
        out = '{0}{1}'.format(replacement_char, out)

    return re.sub('_+', '_', out)
361147
def validate_key(key: str):
        
        if "//" in key:
            raise DoubleSlashKeyError(key)
        elif normpath(key) != key:
            raise NonNormalisedKeyError(key)
307062
def _check_key(key, allow_unicode_keys, key_prefix=b''):
    """"""
    if allow_unicode_keys:
        if isinstance(key, six.text_type):
            key = key.encode('utf8')
    elif isinstance(key, VALID_STRING_TYPES):
        try:
            if isinstance(key, bytes):
                key = key.decode().encode('ascii')
            else:
                key = key.encode('ascii')
        except (UnicodeEncodeError, UnicodeDecodeError):
            raise MemcacheIllegalInputError("Non-ASCII key: '%r'" % key)

    key = key_prefix + key
    parts = key.split()

    if len(key) > 250:
        raise MemcacheIllegalInputError("Key is too long: '%r'" % key)
    # second statement catches leading or trailing whitespace
    elif len(parts) > 1 or parts[0] != key:
        raise MemcacheIllegalInputError("Key contains whitespace: '%r'" % key)
    elif b'\00' in key:
        raise MemcacheIllegalInputError("Key contains null: '%r'" % key)

    return key
797543
def check_key(key, allowed):
    

    if key in allowed:
        return True

    for pattern in allowed:
        if fnmatch(key, pattern):
            return True

    return False
1046842
def _assert_valid_key(self, name):
    """"""
    if name not in self._measurements:
      raise NotAMeasurementError('Not a measurement', name, self._measurements)
731257
def dictionary_validator(key_type, value_type):
    """"""

    def _validate_dictionary(instance, attribute, value):
        # pylint: disable=unused-argument
        """Validate that a dictionary is structured as expected.

        :raises TypeError: if ``value`` is not a dictionary
        :raises TypeError: if ``value`` keys are not all of ``key_type`` type
        :raises TypeError: if ``value`` values are not all of ``value_type`` type
        """
        if not isinstance(value, dict):
            raise TypeError('"{}" must be a dictionary'.format(attribute.name))

        for key, data in value.items():
            if not isinstance(key, key_type):
                raise TypeError(
                    '"{name}" dictionary keys must be of type "{type}"'.format(name=attribute.name, type=key_type)
                )

            if not isinstance(data, value_type):
                raise TypeError(
                    '"{name}" dictionary values must be of type "{type}"'.format(name=attribute.name, type=value_type)
                )

    return _validate_dictionary
740323
def validate_attr(self, append):
        """"""
        if append:
            existing_fields = getattr(self.attrs, self.kind_attr, None)
            if (existing_fields is not None and
                    existing_fields != list(self.values)):
                raise ValueError("appended items do not match existing items"
                                 " in table!")

            existing_dtype = getattr(self.attrs, self.dtype_attr, None)
            if (existing_dtype is not None and
                    existing_dtype != self.dtype):
                raise ValueError("appended items dtype do not match existing "
                                 "items dtype in table!")
1101445
def validate(self):
        """"""

        for key, req in self.stored().items():
            val = getattr(self, key)
            req.validate(val)

        # Run checks defined in __checkers__
        self._run_checks()
806565
def py_to_couch_validate(key, val):
    
    if key not in RESULT_ARG_TYPES:
        raise CloudantArgumentError(116, key)
    # pylint: disable=unidiomatic-typecheck
    # Validate argument values and ensure that a boolean is not passed in
    # if an integer is expected
    if (not isinstance(val, RESULT_ARG_TYPES[key]) or
            (type(val) is bool and int in RESULT_ARG_TYPES[key])):
        raise CloudantArgumentError(117, key, RESULT_ARG_TYPES[key])
    if key == 'keys':
        for key_list_val in val:
            if (not isinstance(key_list_val, RESULT_ARG_TYPES['key']) or
                    type(key_list_val) is bool):
                raise CloudantArgumentError(134, RESULT_ARG_TYPES['key'])
    if key == 'stale':
        if val not in ('ok', 'update_after'):
            raise CloudantArgumentError(135, val)
225994
def make_valid_xml_name(key, attr):
    """"""
    LOG.info('Inside make_valid_xml_name(). Testing key "%s" with attr "%s"' % (
        unicode_me(key), unicode_me(attr))
    )
    key = escape_xml(key)
    attr = escape_xml(attr)
    
    # pass through if key is already valid
    if key_is_valid_xml(key):
        return key, attr
        
    # prepend a lowercase n if the key is numeric
    if key.isdigit():
        return 'n%s' % (key), attr
        
    # replace spaces with underscores if that fixes the problem
    if key_is_valid_xml(key.replace(' ', '_')):
        return key.replace(' ', '_'), attr
        
    # key is still invalid - move it into a name attribute
    attr['name'] = key
    key = 'key'
    return key, attr
389631
def is_valid_python(code, reraise=True, ipy_magic_workaround=False):
    
    import ast
    try:
        if ipy_magic_workaround:
            code = '\n'.join(['pass' if re.match(r'\s*%[a-z]*', line) else line for line in code.split('\n')])
        ast.parse(code)
    except SyntaxError:
        if reraise:
            import utool as ut
            print('Syntax Error')
            ut.print_python_code(code)
            raise
        return False
    return True
279936
def _has_valid_tuple(self, key):
        
        for i, k in enumerate(key):
            if i >= self.obj.ndim:
                raise IndexingError('Too many indexers')
            try:
                self._validate_key(k, i)
            except ValueError:
                raise ValueError("Location based indexing can only have "
                                 "[{types}] types"
                                 .format(types=self._valid_types))