Returns a validator annotation (parameter or property decorator)
543099
function typeAnnotation(type) {
    return (target, key, index) => {
        const classAnnotationsStore = container.get(AnnotationsServiceName.ClassAnnotationsStore);
        const classTypesStore = container.get(TypesServiceName.ClassTypesStore);
        if (index === undefined) {
            // property
            classAnnotationsStore.addPropertyAnnotation(target.constructor, key, Type, { type });
            classTypesStore.setPropertyType(target.constructor, key, type);
        }
        else {
            // method parameter
            classAnnotationsStore.addMethodParameterAnnotation(target.constructor, key, index, Type, { type });
            classTypesStore.setMethodParameterType(target.constructor, key, index, type);
        }
    };
}
353858
private static MessageInterpolator getMessageInterpolatorFromValidator(Validator validator) {
        
        if(!(validator instanceof ValidatorImpl)) {
            return null;
        }
        
        try {
            Field field = ValidatorImpl.class.getDeclaredField("messageInterpolator");
            field.setAccessible(true);
            
            MessageInterpolator interpolator = (MessageInterpolator)field.get(validator);
            return interpolator;
            
        } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
            throw new IllegalStateException("fail reflect MessageInterpolrator from ValidatorImpl.", e);
        }
        
    }
578397
def _validate_annotation(self, annotation):
        ''''''
        required_keys = set(self._required_keys)
        keys = set(key for key, val in annotation.items() if val)
        missing_keys = required_keys.difference(keys)
        if missing_keys:
            error = 'Annotation missing required fields: {0}'.format(
                missing_keys)
            raise AnnotationError(error)
212173
def Maybe(validator):
    
    @wraps(Maybe)
    def built(value):
        if value != None:
            return validator(value)
    return built
113229
function(prop, val){
        var validator = this.getValidator(prop),
            pass = true;

        if (validator) {
            pass = validator(val);
        }

        return pass;
    }
190498
public AnnotationValidator createAnnotationValidator(ValidateWith validateWithAnnotation) {
        AnnotationValidator validator = VALIDATORS_FOR_ANNOTATION_TYPES.get(validateWithAnnotation);
        if (validator != null) {
            return validator;
        }

        Class<? extends AnnotationValidator> clazz = validateWithAnnotation.value();
        try {
            AnnotationValidator annotationValidator = clazz.newInstance();
            VALIDATORS_FOR_ANNOTATION_TYPES.putIfAbsent(validateWithAnnotation, annotationValidator);
            return VALIDATORS_FOR_ANNOTATION_TYPES.get(validateWithAnnotation);
        } catch (Exception e) {
            throw new RuntimeException("Exception received when creating AnnotationValidator class " + clazz.getName(), e);
        }
    }
167587
def any_validator(obj, validators, **kwargs):
    
    if not len(validators) > 1:
        raise ValueError(
            "any_validator requires at least 2 validator.  Only got "
            "{0}".format(len(validators))
        )
    errors = ErrorDict()
    for key, validator in validators.items():
        try:
            validator(obj, **kwargs)
        except ValidationError as err:
            errors[key] = err.detail
        else:
            break
    else:
        if len(errors) == 1:
            # Special case for a single error.  Just raise it as if it was the
            # only validator run.
            error = errors.values()[0]
            raise ValidationError(error)
        else:
            # Raise all of the errors with the key namespaces.
            errors.raise_()
1238741
def decorate_with_checker(func: CallableT) -> CallableT:
    """"""
    assert not hasattr(func, "__preconditions__"), \
        "Expected func to have no list of preconditions (there should be only a single contract checker per function)."

    assert not hasattr(func, "__postconditions__"), \
        "Expected func to have no list of postconditions (there should be only a single contract checker per function)."

    assert not hasattr(func, "__postcondition_snapshots__"), \
        "Expected func to have no list of postcondition snapshots (there should be only a single contract checker " \
        "per function)."

    sign = inspect.signature(func)
    param_names = list(sign.parameters.keys())

    # Determine the default argument values.
    kwdefaults = dict()  # type: Dict[str, Any]

    # Add to the defaults all the values that are needed by the contracts.
    for param in sign.parameters.values():
        if param.default != inspect.Parameter.empty:
            kwdefaults[param.name] = param.default

    def wrapper(*args, **kwargs):
        """Wrap func by checking the preconditions and postconditions."""
        preconditions = getattr(wrapper, "__preconditions__")  # type: List[List[Contract]]
        snapshots = getattr(wrapper, "__postcondition_snapshots__")  # type: List[Snapshot]
        postconditions = getattr(wrapper, "__postconditions__")  # type: List[Contract]

        resolved_kwargs = _kwargs_from_call(param_names=param_names, kwdefaults=kwdefaults, args=args, kwargs=kwargs)

        if postconditions:
            if 'result' in resolved_kwargs:
                raise TypeError("Unexpected argument 'result' in a function decorated with postconditions.")

            if 'OLD' in resolved_kwargs:
                raise TypeError("Unexpected argument 'OLD' in a function decorated with postconditions.")

        # Assert the preconditions in groups. This is necessary to implement "require else" logic when a class
        # weakens the preconditions of its base class.
        violation_err = None  # type: Optional[ViolationError]
        for group in preconditions:
            violation_err = None
            try:
                for contract in group:
                    _assert_precondition(contract=contract, resolved_kwargs=resolved_kwargs)
                break
            except ViolationError as err:
                violation_err = err

        if violation_err is not None:
            raise violation_err  # pylint: disable=raising-bad-type

        # Capture the snapshots
        if postconditions:
            old_as_mapping = dict()  # type: MutableMapping[str, Any]
            for snap in snapshots:
                # This assert is just a last defense.
                # Conflicting snapshot names should have been caught before, either during the decoration or
                # in the meta-class.
                assert snap.name not in old_as_mapping, "Snapshots with the conflicting name: {}"
                old_as_mapping[snap.name] = _capture_snapshot(a_snapshot=snap, resolved_kwargs=resolved_kwargs)

            resolved_kwargs['OLD'] = _Old(mapping=old_as_mapping)

        # Execute the wrapped function
        result = func(*args, **kwargs)

        if postconditions:
            resolved_kwargs['result'] = result

            # Assert the postconditions as a conjunction
            for contract in postconditions:
                _assert_postcondition(contract=contract, resolved_kwargs=resolved_kwargs)

        return result  # type: ignore

    # Copy __doc__ and other properties so that doctests can run
    functools.update_wrapper(wrapper=wrapper, wrapped=func)

    assert not hasattr(wrapper, "__preconditions__"), "Expected no preconditions set on a pristine contract checker."
    assert not hasattr(wrapper, "__postcondition_snapshots__"), \
        "Expected no postcondition snapshots set on a pristine contract checker."
    assert not hasattr(wrapper, "__postconditions__"), "Expected no postconditions set on a pristine contract checker."

    # Precondition is a list of condition groups (i.e. disjunctive normal form):
    # each group consists of AND'ed preconditions, while the groups are OR'ed.
    #
    # This is necessary in order to implement "require else" logic when a class weakens the preconditions of
    # its base class.
    setattr(wrapper, "__preconditions__", [])
    setattr(wrapper, "__postcondition_snapshots__", [])
    setattr(wrapper, "__postconditions__", [])

    return wrapper
1023737
def annotate(*args, **kwargs):
    """"""
    def decorator(f):
        if not hasattr(f, '__annotations__'):
            f.__annotations__ = kwargs.copy()
        else:
            f.__annotations__.update(kwargs)

        if args:
            if len(args) != 1:
                raise ValueError('annotate supports only a single argument.')
            f.__annotations__['return'] = args[0]
        return f

    return decorator
836300
@Nullable
    private static DecoratorAndOrder userDefinedDecorator(Annotation annotation) {
        // User-defined decorator MUST be annotated with @DecoratorFactory annotation.
        final DecoratorFactory d =
                findFirstDeclared(annotation.annotationType(), DecoratorFactory.class).orElse(null);
        if (d == null) {
            return null;
        }

        // In case of user-defined decorator, we need to create a new decorator from its factory.
        @SuppressWarnings("unchecked")
        final DecoratorFactoryFunction<Annotation> factory = getInstance(d, DecoratorFactoryFunction.class);

        // If the annotation has "order" attribute, we can use it when sorting decorators.
        int order = 0;
        try {
            final Method method = Iterables.getFirst(getMethods(annotation.annotationType(),
                                                                withName("order")), null);
            if (method != null) {
                final Object value = method.invoke(annotation);
                if (value instanceof Integer) {
                    order = (Integer) value;
                }
            }
        } catch (Throwable ignore) {
            // A user-defined decorator may not have an 'order' attribute.
            // If it does not exist, '0' is used by default.
        }
        return new DecoratorAndOrder(annotation, factory.newDecorator(annotation), order);
    }
555432
public static Constraint fromAnnotation(Annotation anno) {
		if (anno instanceof Min) {
			return min(((Min) anno).value());
		} else if (anno instanceof Max) {
			return max(((Max) anno).value());
		} else if (anno instanceof Size) {
			return size(((Size) anno).min(), ((Size) anno).max());
		} else if (anno instanceof Digits) {
			return digits(((Digits) anno).integer(), ((Digits) anno).fraction());
		} else if (anno instanceof Pattern) {
			return pattern(((Pattern) anno).regexp());
		} else {
			return new Constraint(VALIDATORS.get(anno.annotationType()),
					simplePayload(VALIDATORS.get(anno.annotationType()))) {
						public boolean isValid(Object actualValue) {
							return true;
						}
					};
		}
	}
294037
public String mapValidationAnnotation(String annotation, String defaultAnnotation) {
		String key = "validation.annotation." + toFirstUpper(annotation);
		if (hasProperty(key)) {
			return getProperty(key);
		} else {
			return defaultAnnotation;
		}
	}
469375
def validate_return_value(self, retval):
        '''
        
        '''

        if self.__return_annotation is None:
            return

        if not self.__is_valid(retval, self.__return_annotation):
            func_name = self.__function.__name__
            msg = self.RET_TYPE_ERROR_MESSAGE.format(
                func_name,
                self.__format_expectation(self.__return_annotation),
                retval.__class__.__name__
            )
            raise TypesafetyError(msg)
431528
private static void collectDecorators(List<DecoratorAndOrder> list, List<Annotation> annotations) {
        if (annotations.isEmpty()) {
            return;
        }

        // Respect the order of decorators which is specified by a user. The first one is first applied
        // for most of the cases. But if @Decorator and user-defined decorators are specified in a mixed order,
        // the specified order and the applied order can be different. To overcome this problem, we introduce
        // "order" attribute to @Decorator annotation to sort decorators. If a user-defined decorator
        // annotation has "order" attribute, it will be also used for sorting.
        for (final Annotation annotation : annotations) {
            if (annotation instanceof Decorator) {
                final Decorator d = (Decorator) annotation;
                list.add(new DecoratorAndOrder(d, newDecorator(d), d.order()));
                continue;
            }

            if (annotation instanceof Decorators) {
                final Decorator[] decorators = ((Decorators) annotation).value();
                for (final Decorator d : decorators) {
                    list.add(new DecoratorAndOrder(d, newDecorator(d), d.order()));
                }
                continue;
            }

            DecoratorAndOrder udd = userDefinedDecorator(annotation);
            if (udd != null) {
                list.add(udd);
                continue;
            }

            // If user-defined decorators are repeatable and they are specified more than once.
            try {
                final Method method = Iterables.getFirst(getMethods(annotation.annotationType(),
                                                                    withName("value")), null);
                assert method != null : "No 'value' method is found from " + annotation;
                final Annotation[] decorators = (Annotation[]) method.invoke(annotation);
                for (final Annotation decorator : decorators) {
                    udd = userDefinedDecorator(decorator);
                    if (udd == null) {
                        break;
                    }
                    list.add(udd);
                }
            } catch (Throwable ignore) {
                // The annotation may be a container of a decorator or may be not, so we just ignore
                // any exception from this clause.
            }
        }
    }
1054129
def returns(schema):
    
    validate = parse(schema).validate

    @decorator
    def validating(func, *args, **kwargs):
        ret = func(*args, **kwargs)
        validate(ret, adapt=False)
        return ret
    return validating
1128927
def _get_type_description(annotation):
    '''
    
    '''
    if annotation is _empty:
        return None, None
    elif callable(annotation):
        return annotation, None
    elif isinstance(annotation, str):
        return None, annotation
    elif isinstance(annotation, tuple):
        try:
            arg1, arg2 = annotation
        except ValueError as e:
            raise AnnotationError(annotation) from e
        else:
            if callable(arg1) and isinstance(arg2, str):
                return arg1, arg2
            elif isinstance(arg1, str) and callable(arg2):
                return arg2, arg1

    raise AnnotationError(annotation)
645828
def _has_annotation(annotation, value):
    

    def matches_property_name(fun):
        """ return true if fun is a callable that has the correct annotation with value """
        return callable(fun) and hasattr(fun, annotation) \
               and getattr(fun, annotation) is value
    return matches_property_name