Contains the validation routines that are to be executed as part of initialization by subclasses.
        When this method is being extended, the first line should always be: ```super().validate_schema_spec()```
327839
def validate_schema_spec(self) -> None:
        
        self.add_errors(
            validate_empty_attributes(self.fully_qualified_name, self._spec, *self._spec.keys()))
        self.add_errors(
            validate_python_identifier_attributes(self.fully_qualified_name, self._spec,
                                                  self.ATTRIBUTE_NAME))
907022
function Schema(options, descriptors) {

    if (!descriptors) {
        descriptors = options;
        options = null;
    }

    function opt(name, type) {
        var value = options[name];
        if (value !== undefined) {
            if (typeof value === type) return value;
            else throw new TypeError(current + 'options : ' + name + ': "' +
                value + '" is not of type [' + type + ']');
        }
        else return false;
    }

    var current = 'Schema: arguments: ',
        defaults = { required: false };

    if (hasValue(options)) {
        if (type(options) === 'object') {
            defaults.required = opt('required', 'boolean');
            if (opt('validator', 'function')) defaults.validator = options.validator;
        }
        else throw new TypeError(current + 'options: must be of type [object]');
    }

    current += 'descriptors: ';
    if (typeof descriptors !== 'object')
        throw new TypeError(current + 'must be of type [object]');
    if (!Array.isArray(descriptors)) {
        descriptors = this.toDescriptors(descriptors, defaults);
    }
    if (options && options.extends instanceof Schema) {
        descriptors = this.extendDescriptors(descriptors, options.extends.descriptors);
    }
    if (!descriptors.length)
        throw new TypeError(current + 'contains no values');
    else if (!(descriptors[0] instanceof Descriptor)) {
        throw new TypeError(current + 'must be instances of Descriptor class');
    }
    var instance = this;
    this.descriptors = descriptors;

}
51364
def validate_process_subtype(supertype_name, supertype, subtype_name, subtype):
    
    errors = []
    for item in supertype:
        # Ensure that the item exists in subtype and has the same schema.
        for subitem in subtype:
            if item['name'] != subitem['name']:
                continue

            for key in set(item.keys()) | set(subitem.keys()):
                if key in ('label', 'description'):
                    # Label and description can differ.
                    continue
                elif key == 'required':
                    # A non-required item can be made required in subtype, but not the
                    # other way around.
                    item_required = item.get('required', True)
                    subitem_required = subitem.get('required', False)

                    if item_required and not subitem_required:
                        errors.append("Field '{}' is marked as required in '{}' and optional in '{}'.".format(
                            item['name'],
                            supertype_name,
                            subtype_name,
                        ))
                elif item.get(key, None) != subitem.get(key, None):
                    errors.append("Schema for field '{}' in type '{}' does not match supertype '{}'.".format(
                        item['name'],
                        subtype_name,
                        supertype_name
                    ))

            break
        else:
            errors.append("Schema for type '{}' is missing supertype '{}' field '{}'.".format(
                subtype_name,
                supertype_name,
                item['name']
            ))

    return errors
95037
def validate(self, benchmarks):
        
        class_code = self.setup_src
        instance_creation = '\ninstance = {}'.format(self.stmt)
        for i, benchmark in enumerate(benchmarks):
            if not benchmark.result_validation:
                break

            validation_code = class_code + instance_creation + '\nvalidation_result = ' + benchmark.stmt
            validation_scope = {}
            exec(validation_code, validation_scope)
            # Store the result in the first function in the group.
            if i == 0:
                compare_against_function = benchmarks[0].callable.__name__
                compare_against_result = validation_scope['validation_result']
                logging.info('PyPerform: Validating group "{b.group}" against method '
                             '"{b.classname}.{b.callable.__name__}"'.format(b=benchmarks[0]))
            else:
                if compare_against_result == validation_scope['validation_result']:
                    logging.info('PyPerform: Validating {b.classname}.{b.callable.__name__}......PASSED!'
                                 .format(b=benchmark))
                else:
                    error = 'Results of functions {0} and {1} are not equivalent.\n{0}:\t {2}\n{1}:\t{3}'
                    raise ValidationError(error.format(compare_against_function, benchmark.callable.__name__,
                                              compare_against_result, validation_scope['validation_result']))
311227
def validate(data):
        
        try:
            return Schema(Validator.SCHEMA).validate(data)
        except SchemaError as exception:
            logging.getLogger(__name__).error(exception)
            return None
103276
def validate(ctx, schema, all_schemata):
    """"""

    database = ctx.obj['db']

    if schema is None:
        if all_schemata is False:
            log('No schema given. Read the help', lvl=warn)
            return
        else:
            schemata = database.objectmodels.keys()
    else:
        schemata = [schema]

    for schema in schemata:
        try:
            things = database.objectmodels[schema]
            with click.progressbar(things.find(), length=things.count(),
                                   label='Validating %15s' % schema) as object_bar:
                for obj in object_bar:
                    obj.validate()
        except Exception as e:

            log('Exception while validating:',
                schema, e, type(e),
                '\n\nFix this object and rerun validation!',
                emitter='MANAGE', lvl=error)

    log('Done')
1022352
def schemaNewValidCtxt(self):
        
        ret = libxml2mod.xmlSchemaNewValidCtxt(self._o)
        if ret is None:raise treeError('xmlSchemaNewValidCtxt() failed')
        __tmp = SchemaValidCtxt(_obj=ret)
        __tmp.schema = self
        return __tmp
1192326
def validate_items(self):
        
        logger.debug(fmt("Validating {}", self))
        from python_jsonschema_objects import classbuilder

        if self.__itemtype__ is None:
            return

        type_checks = self.__itemtype__
        if not isinstance(type_checks, (tuple, list)):
            # we were given items = {'type': 'blah'} ; thus ensure the type for all data.
            type_checks = [type_checks] * len(self.data)
        elif len(type_checks) > len(self.data):
            raise ValidationError(
                "{1} does not have sufficient elements to validate against {0}"
                .format(self.__itemtype__, self.data))

        typed_elems = []
        for elem, typ in zip(self.data, type_checks):
            if isinstance(typ, dict):
                for param, paramval in six.iteritems(typ):
                    validator = registry(param)
                    if validator is not None:
                        validator(paramval, elem, typ)
                typed_elems.append(elem)

            elif util.safe_issubclass(typ, classbuilder.LiteralValue):
                val = typ(elem)
                val.validate()
                typed_elems.append(val)
            elif util.safe_issubclass(typ, classbuilder.ProtocolBase):
                if not isinstance(elem, typ):
                    try:
                        if isinstance(elem, (six.string_types, six.integer_types, float)):
                            val = typ(elem)
                        else:
                            val = typ(**util.coerce_for_expansion(elem))
                    except TypeError as e:
                        raise ValidationError("'{0}' is not a valid value for '{1}': {2}"
                                              .format(elem, typ, e))
                else:
                    val = elem
                val.validate()
                typed_elems.append(val)

            elif util.safe_issubclass(typ, ArrayWrapper):
                val = typ(elem)
                val.validate()
                typed_elems.append(val)

            elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)):
                try:
                    if isinstance(elem, (six.string_types, six.integer_types, float)):
                        val = typ(elem)
                    else:
                        val = typ(**util.coerce_for_expansion(elem))
                except TypeError as e:
                    raise ValidationError("'{0}' is not a valid value for '{1}': {2}"
                                          .format(elem, typ, e))
                else:
                    val.validate()
                    typed_elems.append(val)

        self._dirty = False
        self._typed = typed_elems
        return typed_elems
934654
def validate():
    ''''''
    with current_app.test_request_context():
        schema = json.loads(json.dumps(api.__schema__))
    try:
        schemas.validate(schema)
        success('API specifications are valid')
    except schemas.SchemaValidationError as e:
        exit_with_error('API specifications are not valid', e)
919024
function validationPlugin(Schema) {
    var constructor = Schema.prototype.constructor;

    Schema.prototype.constructor = function (name, schema) {
        var key;
        var fieldDefinition;

        if (arguments.length === 1) {
            schema = arguments[0];
        }

        // call super constructor
        constructor.apply(this, arguments);

        this.validators = {};

        for (key in schema) {
            if (schema.hasOwnProperty(key)) {
                fieldDefinition = schema[key];
                this.validators[key] = [];

                // predefined validators
                if (fieldDefinition.required) {
                    this.validators[key].push(defaultValidators.required());
                }
                if (value(fieldDefinition.enum).typeOf(Array)) {
                    this.validators[key].push(defaultValidators.enum(fieldDefinition.enum));
                }

                if (value(fieldDefinition.min).typeOf(Number)) {
                    this.validators[key].push(defaultValidators.min(fieldDefinition.min));
                }

                if (value(fieldDefinition.max).typeOf(Number)) {
                    this.validators[key].push(defaultValidators.max(fieldDefinition.max));
                }

                if (value(fieldDefinition.minLength).typeOf(Number)) {
                    this.validators[key].push(defaultValidators.minLength(fieldDefinition.minLength));
                }

                if (value(fieldDefinition.maxLength).typeOf(Number)) {
                    this.validators[key].push(defaultValidators.maxLength(fieldDefinition.maxLength));
                }

                if (value(fieldDefinition.hasLength).typeOf(Number)) {
                    this.validators[key].push(defaultValidators.hasLength(fieldDefinition.hasLength));
                }

                // The matches validators works on all types, so we just check if the key is present
                if ("matches" in fieldDefinition) {
                    this.validators[key].push(defaultValidators.matches(fieldDefinition.matches));
                }

                // custom validators
                if (value(fieldDefinition.validate).typeOf(Function)) {
                    this.validators[key].push(fieldDefinition.validate);
                } else if (value(fieldDefinition.validate).typeOf(Array)) {
                    this.validators[key] = this.validators[key].concat(fieldDefinition.validate);
                }
            }
        }
    };

    /**
     * Validate if given model matches schema definition. Returns a promise with the validation result object
     * which contains the intermediate result of all synchronous validators.
     *
     * @param {Object} model
     * @param {Function=} callback
     * @returns {Promise}
     */
    Schema.prototype.validate = function (model, callback) {
        var self = this;
        var pending = 0;
        var result = {
            model: model,
            result: true,
            errors: {}
        };
        var promise;

        function handleFieldErrors(key, fieldErrors) {
            if (fieldErrors.length > 0) {
                result.result = false;
                result.errors[key] = fieldErrors;
            }
        }

        function doCallback() {
            callback(result);
        }

        if (value(model).notTypeOf(Object)) {
            throw new TypeError("Model must be an object");
        }

        if (!this.validators) {
            throw new Error("Validators not defined: Have you registered the validate plugin before any schema definitions?");
        }

        promise = new Promise(function (resolve) {
            function done() {
                if (typeof callback === "function") {
                    setTimeout(doCallback, 0);
                }
                resolve(result);
            }

            if (self.fields.length === 0) {
                done();
                return;
            }

            pending = self.fields.length;

            self.fields.forEach(function (key) {
                var fieldErrors = runValidation(self.validators[key], model[key], model, function onFieldValidation(fieldErrors) {
                    pending--;
                    handleFieldErrors(key, fieldErrors);

                    if (pending === 0) {
                        done();
                    }
                });

                handleFieldErrors(key, fieldErrors);
            });
        });
        // Attach intermediate result to promise
        promise.validation = result;

        return promise;
    };
}
874832
def check_method_requirements(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        error_message = "You must provide {error_field} in {cls} to get access to the default {method} method"
        error_data = {'cls': args[0].__class__.__name__, 'method': request.method.lower()}

        if request.method != 'DELETE':
            if not hasattr(args[0], 'schema'):
                error_data.update({'error_field': 'a schema class'})
                raise Exception(error_message.format(**error_data))

        return func(*args, **kwargs)
    return wrapper
557142
def validate(schema_file, config_file, deprecation):
    ''''''

    result = validator_from_config_file(config_file, schema_file)
    result.validate(error_on_deprecated=deprecation)

    for error in result.errors():
        click.secho('Error   : %s' % error, err=True, fg='red')

    for warning in result.warnings():
        click.secho('Warning : %s' % warning, err=True, fg='yellow')
844767
def validate(self, schema):
        
        try:
            validate(instance=self.to_dict(), schema=schema, cls=Draft4Validator)
        except ValidationError as e:
            raise ValidationError(_validate_err_template.format(VDOM_SCHEMA, e))
1254281
function Validation(schema, custom) {
		Inspection.prototype.constructor.call(this, schema, _merge(Validation.custom, custom));
		var _error = [];

		this._basicFields = Object.keys(_validationAttribut);
		this._customFields = Object.keys(this._custom);
		this.origin = null;

		this.report = function (message, code, reason) {
			var newErr = {
				code: code || this.userCode || null,
				reason: reason || 'unknown',
				message: this.userError || message || 'is invalid',
				property: this.userAlias ? (this.userAlias + ' (' + this._dumpStack() + ')') : this._dumpStack()
			};
			_error.push(newErr);
			return this;
		};

		this.result = function () {
			return {
				error: _error,
				valid: _error.length === 0,
				format: function () {
					if (this.valid === true) {
						return 'Candidate is valid';
					}
					return this.error.map(function (i) {
						return 'Property ' + i.property + ': ' + i.message;
					}).join('\n');
				}
			};
		};
	}
706136
def validate_python_identifier_attributes(fully_qualified_name: str, spec: Dict[str, Any],
                                          *attributes: str) -> List[InvalidIdentifierError]:
    
    errors: List[InvalidIdentifierError] = []

    checks: List[Tuple[Callable, InvalidIdentifierError.Reason]] = [
        (lambda x: x.startswith('_'), InvalidIdentifierError.Reason.STARTS_WITH_UNDERSCORE),
        (lambda x: x.startswith('run_'), InvalidIdentifierError.Reason.STARTS_WITH_RUN),
        (lambda x: not x.isidentifier(), InvalidIdentifierError.Reason.INVALID_PYTHON_IDENTIFIER),
    ]

    for attribute in attributes:
        if attribute not in spec or spec.get(ATTRIBUTE_INTERNAL, False):
            continue

        for check in checks:
            if check[0](spec[attribute]):
                errors.append(
                    InvalidIdentifierError(fully_qualified_name, spec, attribute, check[1]))
                break

    return errors
945488
def SchemaValidateCtxt(self, ctxt, options):
        
        if ctxt is None: ctxt__o = None
        else: ctxt__o = ctxt._o
        ret = libxml2mod.xmlTextReaderSchemaValidateCtxt(self._o, ctxt__o, options)
        return ret
812437
def validate(self, data, schema):
        '''
        '''
        try:
            return schema(data)
        except MultipleInvalid as ie:
            errors = []
            for error in ie.errors:
                if error.path:
                    field = '.'.join(str(p) for p in error.path)
                    path = error.path
                    value = data
                    while path:
                        attr = path.pop(0)
                        try:
                            if isinstance(value, (list, tuple)):
                                attr = int(attr)
                            value = value[attr]
                        except Exception:
                            value = None

                    txt = safe_unicode(error).replace('for dictionary value', '')
                    txt = txt.strip()
                    if isinstance(error, RequiredFieldInvalid):
                        msg = '[{0}] {1}'
                    else:
                        msg = '[{0}] {1}: {2}'
                    try:
                        msg = msg.format(field, txt, str(value))
                    except Exception:
                        msg = '[{0}] {1}'.format(field, txt)

                else:
                    msg = str(error)
                errors.append(msg)
            msg = '\n- '.join(['Validation error:'] + errors)
            raise HarvestValidationError(msg)