Determine if a python datum is an instance of a schema.
501539
def validate_ex(expected_schema,                  # type: Schema
                datum,                            # type: Any
                identifiers=None,                 # type: List[Text]
                strict=False,                     # type: bool
                foreign_properties=None,          # type: Set[Text]
                raise_ex=True,                    # type: bool
                strict_foreign_properties=False,  # type: bool
                logger=_logger,                   # type: logging.Logger
                skip_foreign_properties=False     # type: bool
                ):
    # type: (...) -> bool
    """"""

    if not identifiers:
        identifiers = []

    if not foreign_properties:
        foreign_properties = set()

    schema_type = expected_schema.type

    if schema_type == 'null':
        if datum is None:
            return True
        else:
            if raise_ex:
                raise ValidationException(u"the value is not null")
            else:
                return False
    elif schema_type == 'boolean':
        if isinstance(datum, bool):
            return True
        else:
            if raise_ex:
                raise ValidationException(u"the value is not boolean")
            else:
                return False
    elif schema_type == 'string':
        if isinstance(datum, six.string_types):
            return True
        elif isinstance(datum, bytes):
            datum = datum.decode(u"utf-8")
            return True
        else:
            if raise_ex:
                raise ValidationException(u"the value is not string")
            else:
                return False
    elif schema_type == 'int':
        if (isinstance(datum, six.integer_types)
                and INT_MIN_VALUE <= datum <= INT_MAX_VALUE):
            return True
        else:
            if raise_ex:
                raise ValidationException(u"`%s` is not int" % vpformat(datum))
            else:
                return False
    elif schema_type == 'long':
        if ((isinstance(datum, six.integer_types))
                and LONG_MIN_VALUE <= datum <= LONG_MAX_VALUE):
            return True
        else:
            if raise_ex:
                raise ValidationException(
                    u"the value `%s` is not long" % vpformat(datum))
            else:
                return False
    elif schema_type in ['float', 'double']:
        if (isinstance(datum, six.integer_types)
                or isinstance(datum, float)):
            return True
        else:
            if raise_ex:
                raise ValidationException(
                    u"the value `%s` is not float or double" % vpformat(datum))
            else:
                return False
    elif isinstance(expected_schema, avro.schema.EnumSchema):
        if expected_schema.name == "Any":
            if datum is not None:
                return True
            else:
                if raise_ex:
                    raise ValidationException(u"'Any' type must be non-null")
                else:
                    return False
        if not isinstance(datum, six.string_types):
            if raise_ex:
                raise ValidationException(
                    u"value is a %s but expected a string" % (type(datum).__name__))
            else:
                return False
        if expected_schema.name == "Expression":
            if "$(" in datum or "${" in datum:
                return True
            if raise_ex:
                raise ValidationException(u"value `%s` does not contain an expression in the form $() or ${}" % datum)
            else:
                return False
        if datum in expected_schema.symbols:
            return True
        else:
            if raise_ex:
                raise ValidationException(u"the value %s is not a valid %s, expected %s%s" % (vpformat(datum), expected_schema.name,
                                                                                              "one of " if len(
                                                                                                  expected_schema.symbols) > 1 else "",
                                                                                              "'" + "', '".join(expected_schema.symbols) + "'"))
            else:
                return False
    elif isinstance(expected_schema, avro.schema.ArraySchema):
        if isinstance(datum, MutableSequence):
            for i, d in enumerate(datum):
                try:
                    sl = SourceLine(datum, i, ValidationException)
                    if not validate_ex(expected_schema.items, d, identifiers,
                                       strict=strict,
                                       foreign_properties=foreign_properties,
                                       raise_ex=raise_ex,
                                       strict_foreign_properties=strict_foreign_properties,
                                       logger=logger,
                                       skip_foreign_properties=skip_foreign_properties):
                        return False
                except ValidationException as v:
                    if raise_ex:
                        raise sl.makeError(
                            six.text_type("item is invalid because\n%s" % (indent(str(v)))))
                    else:
                        return False
            return True
        else:
            if raise_ex:
                raise ValidationException(u"the value %s is not a list, expected list of %s" % (
                    vpformat(datum), friendly(expected_schema.items)))
            else:
                return False
    elif isinstance(expected_schema, avro.schema.UnionSchema):
        for s in expected_schema.schemas:
            if validate_ex(s, datum, identifiers, strict=strict, raise_ex=False,
                           strict_foreign_properties=strict_foreign_properties,
                           logger=logger, skip_foreign_properties=skip_foreign_properties):
                return True

        if not raise_ex:
            return False

        errors = []  # type: List[Text]
        checked = []
        for s in expected_schema.schemas:
            if isinstance(datum, MutableSequence) and not isinstance(s, avro.schema.ArraySchema):
                continue
            elif isinstance(datum, MutableMapping) and not isinstance(s, avro.schema.RecordSchema):
                continue
            elif (isinstance(  # type: ignore
                    datum, (bool, six.integer_types, float, six.string_types))
                    and isinstance(s, (avro.schema.ArraySchema,
                                       avro.schema.RecordSchema))):
                continue
            elif datum is not None and s.type == "null":
                continue

            checked.append(s)
            try:
                validate_ex(s, datum, identifiers, strict=strict,
                            foreign_properties=foreign_properties,
                            raise_ex=True,
                            strict_foreign_properties=strict_foreign_properties,
                            logger=logger, skip_foreign_properties=skip_foreign_properties)
            except ClassValidationException as e:
                raise
            except ValidationException as e:
                errors.append(six.text_type(e))
        if bool(errors):
            raise ValidationException(bullets(["tried %s but\n%s" % (friendly(
                checked[i]), indent(errors[i])) for i in range(0, len(errors))], "- "))
        else:
            raise ValidationException("value is a %s, expected %s" % (
                type(datum).__name__, friendly(expected_schema)))

    elif isinstance(expected_schema, avro.schema.RecordSchema):
        if not isinstance(datum, MutableMapping):
            if raise_ex:
                raise ValidationException(u"is not a dict")
            else:
                return False

        classmatch = None
        for f in expected_schema.fields:
            if f.name in ("class",):
                d = datum.get(f.name)
                if not d:
                    if raise_ex:
                        raise ValidationException(
                            u"Missing '%s' field" % (f.name))
                    else:
                        return False
                if expected_schema.name != d:
                    if raise_ex:
                        raise ValidationException(
                            u"Expected class '%s' but this is '%s'" % (expected_schema.name, d))
                    else:
                        return False
                classmatch = d
                break

        errors = []
        for f in expected_schema.fields:
            if f.name in ("class",):
                continue

            if f.name in datum:
                fieldval = datum[f.name]
            else:
                try:
                    fieldval = f.default
                except KeyError:
                    fieldval = None

            try:
                sl = SourceLine(datum, f.name, six.text_type)
                if not validate_ex(f.type, fieldval, identifiers, strict=strict,
                                   foreign_properties=foreign_properties,
                                   raise_ex=raise_ex,
                                   strict_foreign_properties=strict_foreign_properties,
                                   logger=logger, skip_foreign_properties=skip_foreign_properties):
                    return False
            except ValidationException as v:
                if f.name not in datum:
                    errors.append(u"missing required field `%s`" % f.name)
                else:
                    errors.append(sl.makeError(u"the `%s` field is not valid because\n%s" % (
                        f.name, indent(str(v)))))

        for d in datum:
            found = False
            for f in expected_schema.fields:
                if d == f.name:
                    found = True
            if not found:
                sl = SourceLine(datum, d, six.text_type)
                if d not in identifiers and d not in foreign_properties and d[0] not in ("@", "$"):
                    if (d not in identifiers and strict) and (
                            d not in foreign_properties and strict_foreign_properties and not skip_foreign_properties) and not raise_ex:
                        return False
                    split = urllib.parse.urlsplit(d)
                    if split.scheme:
                        if not skip_foreign_properties:
                            err = sl.makeError(u"unrecognized extension field `%s`%s.%s"
                                               % (d,
                                                  " and strict_foreign_properties checking is enabled"
                                                  if strict_foreign_properties else "",
                                                  "\nForeign properties from $schemas:\n  %s" % "\n  ".join(sorted(foreign_properties))
                                                  if len(foreign_properties) > 0 else ""))
                            if strict_foreign_properties:
                                errors.append(err)
                            elif len(foreign_properties) > 0:
                                logger.warning(strip_dup_lineno(err))
                    else:
                        err = sl.makeError(u"invalid field `%s`, expected one of: %s" % (
                            d, ", ".join("'%s'" % fn.name for fn in expected_schema.fields)))
                        if strict:
                            errors.append(err)
                        else:
                            logger.warning(err)

        if bool(errors):
            if raise_ex:
                if classmatch:
                    raise ClassValidationException(bullets(errors, "* "))
                else:
                    raise ValidationException(bullets(errors, "* "))
            else:
                return False
        else:
            return True
    if raise_ex:
        raise ValidationException(u"Unrecognized schema_type %s" % schema_type)
    else:
        return False
1373024
def validate(data, schema, defined_keys=False):
    
    if isinstance(data, dict):
        validator = Validator(data, schema, defined_keys=defined_keys)
        validator.validate()
    else:
        raise TypeError('expected data to be of type dict, but got: %s' % type(data))
259938
def _is_primitive(thing):
        """"""
        primitive = (int, str, bool, float)
        return isinstance(thing, primitive)
1003966
def schema(self):
        
        if self.key_type is None:
            return "%s %s" % (self.name, self.data_type)
        else:
            return "%s %s %s KEY" % (self.name, self.data_type, self.key_type)
87803
def isdefined(obj, force_import=False, namespace=None):
    """"""
    if namespace is None:
        namespace = locals()
    attr_list = obj.split('.')
    base = attr_list.pop(0)
    if len(base) == 0:
        return False
    if base not in builtins.__dict__ and base not in namespace:
        if force_import:
            try:
                module = __import__(base, globals(), namespace)
                if base not in globals():
                    globals()[base] = module
                namespace[base] = module
            except Exception:
                return False
        else:
            return False
    for attr in attr_list:
        try:
            attr_not_found = not hasattr(eval(base, namespace), attr)
        except (SyntaxError, AttributeError):
            return False
        if attr_not_found:
            if force_import:
                try:
                    __import__(base+'.'+attr, globals(), namespace)
                except (ImportError, SyntaxError):
                    return False
            else:
                return False
        base += '.'+attr
    return True
520124
def is_dictlist(data):
    '''
    
    '''
    if isinstance(data, list):
        for element in data:
            if isinstance(element, dict):
                if len(element) != 1:
                    return False
            else:
                return False
        return True
    return False
1307806
def _verify(self, path_prefix=None):
        """"""
        for field, spec in self.doc_spec.iteritems():
            path = self._append_path(path_prefix, field)

            # Standard dict-based spec
            if isinstance(spec, dict):
                self._verify_field_spec(spec, path)
            else:
                raise SchemaFormatException("Invalid field definition for {}", path)
1262216
def _infer_schema(row, names=None):
    """"""
    if isinstance(row, dict):
        items = sorted(row.items())

    elif isinstance(row, (tuple, list)):
        if hasattr(row, "__fields__"):  # Row
            items = zip(row.__fields__, tuple(row))
        elif hasattr(row, "_fields"):  # namedtuple
            items = zip(row._fields, tuple(row))
        else:
            if names is None:
                names = ['_%d' % i for i in range(1, len(row) + 1)]
            elif len(names) < len(row):
                names.extend('_%d' % i for i in range(len(names) + 1, len(row) + 1))
            items = zip(names, row)

    elif hasattr(row, "__dict__"):  # object
        items = sorted(row.__dict__.items())

    else:
        raise TypeError("Can not infer schema for type: %s" % type(row))

    fields = [StructField(k, _infer_type(v), True) for k, v in items]
    return StructType(fields)
34020
def _is_reference(arg):
    '''
    
    '''
    return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), six.string_types)
959042
def is_timestamp(instance):
    """"""
    if not isinstance(instance, (int, str)):
        return True
    return datetime.fromtimestamp(int(instance))
1361134
def is_number(dtype):
    """"""
    return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \
           or ('short' in dtype.name)
1101139
def _validated(self, values):
        """"""
        if self.length != len(values):
            raise NotValid(
                "%r does not have exactly %d values. (Got %d.)" % (
                    values, self.length, len(values)))
        return type(self.schemas)(
            self.schemas[i].validate(v) for i, v in enumerate(values))
1010314
def _determine_keys(dictionary):
    """"""
    optional = {}
    defaults = {}
    mandatory = {}
    types = {}
    for key, value in dictionary.items():
        if isinstance(key, Optional):
            optional[key.value] = parse_schema(value)
            if isinstance(value, BaseSchema) and\
                    value.default is not UNSPECIFIED:
                defaults[key.value] = (value.default, value.null_values)
            continue  # pragma: nocover

        if type(key) is type:
            types[key] = parse_schema(value)
            continue

        mandatory[key] = parse_schema(value)
    return mandatory, optional, types, defaults
461387
def validate_schema(schema_name):
    """"""
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            instance = args[0]
            try:
                instance.validator(instance.schemas[schema_name]).validate(request.get_json())
            except ValidationError, e:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.BAD_SCHEMA,
                                                       e.message)
                instance.logger.error("Invalid Schema", ret_dict)
                return jsonify(ret_dict), 400
            instance.logger.debug("Schema is valid")
            return f(*args, **kw)
        return wrapper
    return decorator
54458
public boolean schemaEquals(Object obj) {
		return equals(obj) && Arrays.equals(fieldNames, ((RowTypeInfo) obj).fieldNames);
	}
381301
def rhn_schema_version(context):
    
    if context.content:
        content = context.content
        if len(content) == 1 and 'No such' not in content[0]:
            ver = content[0].strip()
            if ver:
                return ver
482842
function SchemaType (path, options, instance) {
  this.path = path;
  this.instance = instance;
  this.validators = [];
  this.setters = [];
  this.getters = [];
  this.options = options;
  this._index = null;
  this.selected;

  for (var i in options) if (this[i] && 'function' == typeof this[i]) {
    // { unique: true, index: true }
    if ('index' == i && this._index) continue;

    var opts = Array.isArray(options[i])
      ? options[i]
      : [options[i]];

    this[i].apply(this, opts);
  }
}