Decorator which runs validation on a callable's arguments and its return
    value. Pass a schema for the kwargs and for the return value. Positional
    arguments are not supported.
435156
def validate_call(kwargs, returns, is_method=False):
    
    def decorator(func):
        @wraps(func)
        def inner(*passed_args, **passed_kwargs):
            # Enforce no positional args
            # first argument of instance method and class method is always positonal so we need
            # to make expception for them. Static methods are still validated according to standard rules
            # this check happens before methods are bound, so instance method is still a regular function
            max_allowed_passed_args_len = 0
            if is_method and type(func) in (types.FunctionType, classmethod):
                max_allowed_passed_args_len = 1

            if len(passed_args) > max_allowed_passed_args_len:
                raise PositionalError('You cannot call this with positional arguments.')
            # Validate keyword arguments
            validate(kwargs, passed_kwargs, 'keyword arguments')
            # Call callable
            return_value = func(*passed_args, **passed_kwargs)
            # Validate return value
            validate(returns, return_value, 'return value')
            return return_value
        inner.__wrapped__ = func
        # caveat: checking for f.__validated__ will only work if @validate_call
        # is not masked by other decorators except for @classmethod or @staticmethod
        inner.__validated__ = True
        return inner
    return decorator
991878
def _call_function(name, returner=None, **kwargs):
    '''
    
    '''
    argspec = salt.utils.args.get_function_argspec(__salt__[name])

    # func_kw is initialized to a dictionary of keyword arguments the function to be run accepts
    func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):],  # pylint: disable=incompatible-py3-code
                   argspec.defaults or []))

    # func_args is initialized to a list of positional arguments that the function to be run accepts
    func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])]
    arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False
    for funcset in reversed(kwargs.get('func_args') or []):
        if not isinstance(funcset, dict):
            # We are just receiving a list of args to the function to be run, so just append
            # those to the arg list that we will pass to the func.
            arg_type.append(funcset)
        else:
            for kwarg_key in six.iterkeys(funcset):
                # We are going to pass in a keyword argument. The trick here is to make certain
                # that if we find that in the *args* list that we pass it there and not as a kwarg
                if kwarg_key in func_args:
                    kw_to_arg_type[kwarg_key] = funcset[kwarg_key]
                    continue
                else:
                    # Otherwise, we're good and just go ahead and pass the keyword/value pair into
                    # the kwargs list to be run.
                    func_kw.update(funcset)
    arg_type.reverse()
    for arg in func_args:
        if arg in kw_to_arg_type:
            arg_type.append(kw_to_arg_type[arg])
    _exp_prm = len(argspec.args or []) - len(argspec.defaults or [])
    _passed_prm = len(arg_type)
    missing = []
    if na_type and _exp_prm > _passed_prm:
        for arg in argspec.args:
            if arg not in func_kw:
                missing.append(arg)
    if missing:
        raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing)))
    elif _exp_prm > _passed_prm:
        raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format(
            _exp_prm, _passed_prm))

    mret = __salt__[name](*arg_type, **func_kw)
    if returner is not None:
        returners = salt.loader.returners(__opts__, __salt__)
        if returner in returners:
            returners[returner]({'id': __opts__['id'], 'ret': mret,
                                 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)})

    return mret
740741
def validate_fields(func):
    """"""
    @functools.wraps(func)
    def decorated(instance, *args, **kwargs):
        """The decorator function."""
        data = request.get_json(force=True, silent=True)
        if not data:
            raise BadRequestException('No data received from request')
        for key in data:
            if key not in (
                    instance.__model__.required() +
                    instance.__model__.optional()):
                raise BadRequestException('Unknown field [{}]'.format(key))
        missing = set(instance.__model__.required()) - set(data)
        if missing:
            message = 'The following required fields are missing: ' + ', '.join(missing)
            raise BadRequestException(message)
        return func(instance, *args, **kwargs)
    return decorated
121117
def generate_type_validator(type_, **kwargs):
    
    if is_non_string_iterable(type_):
        types = tuple(type_)
    else:
        types = (type_,)
    # support x-nullable since Swagger 2.0 doesn't support null type
    # (see https://github.com/OAI/OpenAPI-Specification/issues/229)
    if kwargs.get('x-nullable', False) and NULL not in types:
        types = types + (NULL,)
    return functools.partial(validate_type, types=types)
930004
def restrict_args(func, *args, **kwargs):
    '''
    
    '''
    callargs = getargspec(func)
    if not callargs.varargs:
        args = args[0:len(callargs.args)]
    return func(*args, **kwargs)
375042
def validate(raw_schema, target=None, **kwargs):
    
    schema = schema_validator(raw_schema, **kwargs)
    if target is not None:
        validate_object(target, schema=schema, **kwargs)
604707
def _validate(self, value):
        
        errors = []
        kwargs = {}
        for validator in self.validators:
            try:
                r = validator(value)
                if not isinstance(validator, Validator) and r is False:
                    self.fail('validator_failed')
            except ValidationError as err:
                kwargs.update(err.kwargs)
                if isinstance(err.messages, dict):
                    errors.append(err.messages)
                else:
                    errors.extend(err.messages)
        if errors:
            raise ValidationError(errors, **kwargs)
871141
def validate(obj, schema):
        
        if isinstance(obj, str):
            obj = json.loads(obj)
        return JsonValidator(schema)._validate(obj)
452096
def use_schema(schema, list_view=False, locations=None):
    

    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            use_args_wrapper = parser.use_args(schema, locations=locations)
            # Function wrapped with use_args
            func_with_args = use_args_wrapper(func)
            ret = func_with_args(*args, **kwargs)
            # Serialize and jsonify the return value
            return jsonify(schema.dump(ret, many=list_view).data)

        return wrapped

    return decorator
12207
def _convert_errors(func):
    
    cast_Invalid = lambda e: Invalid(
        u"{message}, expected {expected}".format(
            message=e.message,
            expected=e.expected)
        if e.expected != u'-none-' else e.message,
        e.path,
        six.text_type(e))

    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except good.SchemaError as e:
            raise SchemaError(six.text_type(e))
        except good.MultipleInvalid as ee:
            raise MultipleInvalid([cast_Invalid(e) for e in ee])
        except good.Invalid as e:
            # Since voluptuous throws MultipleInvalid almost always -- we follow the same pattern...
            raise MultipleInvalid([cast_Invalid(e)])
    return wrapper
910988
def validate(self, value=_undefined, name=None):
        
        if self.optional:
            if value is _undefined or value is None:
                if self.default is None:
                    return None
                elif util.is_function(self.default):
                    value = self.default()
                else:
                    value = self.default
        elif value is _undefined:
            if name is not None:
                name_msg = "argument `{}`".format(name)
            else:
                name_msg = "unnamed argument"
            raise TypeError("Missing required value for {}".format(name_msg))

        return self.validator(value)
120056
def class_check_para(**kw):
    
    try:
        def decorator(f):
            def new_f(*args):
                if "accepts" in kw:
                    assert len(args) == len(kw["accepts"]) + 1
                    arg_types = tuple(map(type, args[1:]))
                    if arg_types != kw["accepts"]:
                        msg = decorator_info(f.__name__, kw["accepts"],
                                             arg_types, 0)
                        print('TypeWarning: ', msg)
                        raise TypeError(msg)
                result = f(*args)
                if "returns" in kw:
                    res_type = type(result)
                    if res_type != kw["returns"]:
                        msg = decorator_info(f.__name__, (kw["returns"],),
                                             (res_type,), 1)
                        print('TypeWarning: ', msg)
                        raise TypeError(msg)
                return result

            new_f.__name__ = f.__name__
            return new_f

        return decorator
    except KeyError as ke:
        raise KeyError(ke.message + "is not a valid keyword argument")
    except TypeError as te:
        raise TypeError(te.message)
1062629
def validate_func_factory(validator_class: Any) -> ValidateFunc:
    
    def validate_func(schema: AnyMapping, pure_data: AnyMapping) -> AnyMapping:
        """Validate schema with given data.

        :param schema: Schema representation to use.
        :param pure_data: Pure data to validate.
        """
        return validator_class(schema).validate(pure_data)
    return validate_func
638977
def _select_helper(args, kwargs):
    
    if len(args) > 1:
        raise TypeError("select accepts at most ONE positional argument.")

    if len(args) > 0 and len(kwargs) > 0:
        raise TypeError("select accepts EITHER a positional argument, OR keyword arguments (not both).")

    if len(args) == 0 and len(kwargs) == 0:
        raise TypeError("select requires EITHER a positional argument, OR keyword arguments.")

    if args:
        arg = args[0]
        if isinstance(arg, dict):
            selector = arg
        elif isinstance(arg, string_types):
            selector = dict(name=arg)
        elif isinstance(arg, type) and issubclass(arg, Model):
            selector = {"type": arg}
        else:
            raise TypeError("selector must be a dictionary, string or plot object.")

    elif 'selector' in kwargs:
        if len(kwargs) == 1:
            selector = kwargs['selector']
        else:
            raise TypeError("when passing 'selector' keyword arg, not other keyword args may be present")

    else:
        selector = kwargs

    return selector
219504
def validate_take_with_convert(convert, args, kwargs):
    

    if isinstance(convert, ndarray) or convert is None:
        args = (convert,) + args
        convert = True

    validate_take(args, kwargs, max_fname_arg_count=3, method='both')
    return convert
1356865
def callable_check(func, arg_count=1, arg_value=None, allow_none=False):
        """"""
        if func is None:
            if not allow_none:
                raise ValueError('callable cannot be None')
        elif not arg_checker(func, *[arg_value for _ in range(arg_count)]):
            raise ValueError('callable %s invalid (for %d arguments)' % (func, arg_count))
401012
def validate_key(func):
    

    @wraps(func)
    def wrapper(self, key, *args, **kwargs):
        if posixpath.sep in key:
            raise ValueError('Keys cannot contains slashes')

        return func(self, key, *args, **kwargs)

    return wrapper