Fallback schema for field that isn't inspected properly by DRF
        and probably won't land in upstream canon due to its hacky nature only for doc purposes
501966
def fallback_schema_from_field(self, field):
        
        title = force_text(field.label) if field.label else ''
        description = force_text(field.help_text) if field.help_text else ''

        # since we can't really inspect dictfield and jsonfield, at least display object as type
        # instead of string
        if isinstance(field, (serializers.DictField, serializers.JSONField)):
            return coreschema.Object(
                properties={},
                title=title,
                description=description
            )
1194334
def reformat_schema(model):
    
    if not hasattr(model, 'schema'):
        return "Model '{}' does not have a schema".format(model)

    if 'properties' not in model.schema:
        return "Schema in unexpected format."

    ret = copy.deepcopy(model.schema['properties'])

    if 'type' in ret:
        del(ret['type'])

    for key in model.schema.get('required', []):
        if key in ret:
            ret[key]['required'] = True

    return ret
1289003
def _data2rec(schema, rec_data):
    '''
    
    '''
    try:
        rec_fields = rec_data.split(' ')
        # spaces in digest fields are allowed
        assert len(rec_fields) >= len(schema)
        if len(rec_fields) > len(schema):
            cutoff = len(schema) - 1
            rec_fields = rec_fields[0:cutoff] + [''.join(rec_fields[cutoff:])]

        if len(schema) == 1:
            res = _cast(rec_fields[0], next(iter(schema.values())))
        else:
            res = dict((
                (field_name, _cast(rec_field, rec_cast))
                for (field_name, rec_cast), rec_field in zip(schema.items(), rec_fields)
            ))
        return res
    except (AssertionError, AttributeError, TypeError, ValueError) as e:
        raise ValueError('Unable to cast "{0}" as "{2}": {1}'.format(
            rec_data,
            e,
            ' '.join(schema.keys())
        ))
860388
def __validate_required_fields(self, document):
        
        try:
            required = set(field for field, definition in self.schema.items()
                           if self._resolve_rules_set(definition).
                           get('required') is True)
        except AttributeError:
            if self.is_child and self.schema_path[-1] == 'schema':
                raise _SchemaRuleTypeError
            else:
                raise
        required -= self._unrequired_by_excludes
        missing = required - set(field for field in document
                                 if document.get(field) is not None or
                                 not self.ignore_none_values)

        for field in missing:
            self._error(field, errors.REQUIRED_FIELD)

        # At least on field from self._unrequired_by_excludes should be
        # present in document
        if self._unrequired_by_excludes:
            fields = set(field for field in document
                         if document.get(field) is not None)
            if self._unrequired_by_excludes.isdisjoint(fields):
                for field in self._unrequired_by_excludes - fields:
                    self._error(field, errors.REQUIRED_FIELD)
510115
function(schemaName, target, cb, options) {
  var schema  = SCHEMA[schemaName]
    , idField = schema._idField_
    , id      = target[idField]
    , options = options || {}

  if (typeof id == 'undefined' || id === '') {
    cb && cb(new Error('update ' + schemaName + ' failed: ID is not exist'))
    return
  }

  var key = schemaName + ':' + id

  client.hgetall(key, function(err, object) {
    if (!object && options.mode != 'insert') {
      cb && cb(err || new Error('update ' + key + ' failed: object doesn\'t exist'))
      return
    }

    filter(schemaName, target, function(err, result) {
      if (err || result === false) {
        cb && cb(err || new Error('update ' + schemaName + ' failed: invalid field value'))
        return
      }

      client.hmset(schemaName + ':' + id, target, function(err) {
        if (err) {
          cb && cb(err)
          return
        }

        filter(schemaName, target, cb, { FUNCS: COMMANDS, mode: options.mode, oldModel: object  })
      })
    }, { FUNCS: FILTERS, mode: options.mode, oldModel: object })

  })

}
1144722
def p_field(self, p):
        """"""
        has_annotations = len(p) > 5 and p[6] is not None
        has_docstring = len(p) > 5 and p[7] is not None
        has_anony_def = len(p) > 5 and p[8] is not None
        p[0] = AstField(
            self.path, p.lineno(1), p.lexpos(1), p[1], p[2])
        if p[3] is not None:
            if p[3] is NullToken:
                p[0].set_default(None)
            else:
                p[0].set_default(p[3])
        if has_annotations:
            p[0].set_annotations(p[6])
        if has_docstring:
            p[0].set_doc(p[7])
        if has_anony_def:
            p[8].name = p[2].name
            self.anony_defs.append(p[8])
1279251
def schema_term(self):
        """"""

        if not self.name:
            raise MetapackError("Resource for url '{}' doe not have name".format(self.url))

        t = self.doc.find_first('Root.Table', value=self.get_value('name'))
        frm = 'name'

        if not t:
            t = self.doc.find_first('Root.Table', value=self.get_value('schema'))
            frm = 'schema'

        if not t:
            frm = None

        return t
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
422633
def make_schema(fields, datefields=()):
    '''
    
    '''
    text_field = whoosh.fields.TEXT(analyzer=whoosh.analysis.SimpleAnalyzer())
    fields = dict.fromkeys(fields, text_field)
    if datefields:
        datefields = dict.fromkeys(datefields, whoosh.fields.DATETIME)
        fields.update(datefields)
    schema = whoosh.fields.Schema()
    for fieldname in fields:
        schema.add(fieldname, fields[fieldname])
    return schema
178224
function() {
				var doc = this;
				var outDoc = doc.toObject(); // Rely on the toObject() syntax to strip out rubbish

				doc.getOIDs().forEach(function(node) {
					switch (node.fkType) {
						case 'objectId':
							var oidLeaf = _.get(doc, node.docPath);
							if (_.isUndefined(oidLeaf)) return; // Ignore undefined

							if (!o.utilities.isObjectID(oidLeaf)) {
								if (_.has(oidLeaf, '_id')) { // Already populated?
									_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf._id));
								} else { // Convert to an OID
									_.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf));
								}
							}
							break;
						case 'objectIdArray':
							var oidLeaf = _.get(doc, node.schemaPath);
							_.set(outDoc, node.schemaPath, oidLeaf.map(function(leaf) {
								return o.utilities.isObjectID(leaf) ? leaf : o.utilities.objectID(leaf);
							}));
							break;
						default:
							return; // Ignore unsupported OID types
					}
				});

				return outDoc;
			}
485879
def to_match(self):
        """"""
        self.validate()

        mark_name, field_name = self.fold_scope_location.get_location_name()
        validate_safe_string(mark_name)

        template = u'$%(mark_name)s.%(field_name)s'
        template_data = {
            'mark_name': mark_name,
        }

        if field_name == COUNT_META_FIELD_NAME:
            template_data['field_name'] = 'size()'
        else:
            inner_type = strip_non_null_from_type(self.field_type.of_type)
            if GraphQLDate.is_same_type(inner_type):
                # Known OrientDB bug may cause trouble here, and incorrect data may be returned:
                # https://github.com/orientechnologies/orientdb/issues/7289
                template += '.format("' + STANDARD_DATE_FORMAT + '")'
            elif GraphQLDateTime.is_same_type(inner_type):
                # Known OrientDB bug may cause trouble here, and incorrect data may be returned:
                # https://github.com/orientechnologies/orientdb/issues/7289
                template += '.format("' + STANDARD_DATETIME_FORMAT + '")'

            template_data['field_name'] = field_name

        return template % template_data
1181610
def _validate_keyschema(self, schema, field, value):
        
        if isinstance(value, Mapping):
            validator = self._get_child_validator(
                document_crumb=field,
                schema_crumb=(field, 'keyschema'),
                schema=dict(((k, schema) for k in value.keys())))
            if not validator(dict(((k, k) for k in value.keys())),
                             normalize=False):
                self._drop_nodes_from_errorpaths(validator._errors,
                                                 [], [2, 4])
                self._error(field, errors.KEYSCHEMA, validator._errors)
937182
def _map_term_using_schema(master, path, term, schema_edges):
    
    output = FlatList()
    for k, v in term.items():
        dimension = schema_edges[k]
        if isinstance(dimension, Dimension):
            domain = dimension.getDomain()
            if dimension.fields:
                if is_data(dimension.fields):
                    # EXPECTING A TUPLE
                    for local_field, es_field in dimension.fields.items():
                        local_value = v[local_field]
                        if local_value == None:
                            output.append({"missing": {"field": es_field}})
                        else:
                            output.append({"term": {es_field: local_value}})
                    continue

                if len(dimension.fields) == 1 and is_variable_name(dimension.fields[0]):
                    # SIMPLE SINGLE-VALUED FIELD
                    if domain.getPartByKey(v) is domain.NULL:
                        output.append({"missing": {"field": dimension.fields[0]}})
                    else:
                        output.append({"term": {dimension.fields[0]: v}})
                    continue

                if AND(is_variable_name(f) for f in dimension.fields):
                    # EXPECTING A TUPLE
                    if not isinstance(v, tuple):
                        Log.error("expecing {{name}}={{value}} to be a tuple",  name= k,  value= v)
                    for i, f in enumerate(dimension.fields):
                        vv = v[i]
                        if vv == None:
                            output.append({"missing": {"field": f}})
                        else:
                            output.append({"term": {f: vv}})
                    continue
            if len(dimension.fields) == 1 and is_variable_name(dimension.fields[0]):
                if domain.getPartByKey(v) is domain.NULL:
                    output.append({"missing": {"field": dimension.fields[0]}})
                else:
                    output.append({"term": {dimension.fields[0]: v}})
                continue
            if domain.partitions:
                part = domain.getPartByKey(v)
                if part is domain.NULL or not part.esfilter:
                    Log.error("not expected to get NULL")
                output.append(part.esfilter)
                continue
            else:
                Log.error("not expected")
        elif is_data(v):
            sub = _map_term_using_schema(master, path + [k], v, schema_edges[k])
            output.append(sub)
            continue

        output.append({"term": {k: v}})
    return {"and": output}
1070679
def _get_schema_for_field(self, obj, field):
        """"""
        mapping = self._get_default_mapping(obj)
        if hasattr(field, '_jsonschema_type_mapping'):
            schema = field._jsonschema_type_mapping()
        elif '_jsonschema_type_mapping' in field.metadata:
            schema = field.metadata['_jsonschema_type_mapping']
        elif field.__class__ in mapping:
            pytype = mapping[field.__class__]
            if isinstance(pytype, basestring):
                schema = getattr(self, pytype)(obj, field)
            else:
                schema = self._from_python_type(
                    obj, field, pytype
                )
        else:
            raise ValueError('unsupported field type %s' % field)

        # Apply any and all validators that field may have
        for validator in field.validators:
            if validator.__class__ in FIELD_VALIDATORS:
                schema = FIELD_VALIDATORS[validator.__class__](
                    schema, field, validator, obj
                )
        return schema
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
970028
def _validate_valueschema(self, schema, field, value):
        
        schema_crumb = (field, 'valueschema')
        if isinstance(value, Mapping):
            validator = self._get_child_validator(
                document_crumb=field, schema_crumb=schema_crumb,
                schema=dict((k, schema) for k in value))
            validator(value, update=self.update, normalize=False)
            if validator._errors:
                self._drop_nodes_from_errorpaths(validator._errors, [], [2])
                self._error(field, errors.VALUESCHEMA, validator._errors)
1214725
function validateSchema(schema, throwOrLogError) {
  var $schema = schema.$schema;
  if ($schema !== undefined && typeof $schema != 'string')
    throw new Error('$schema must be a string');
  $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema) {
    this.logger.warn('meta-schema not available');
    this.errors = null;
    return true;
  }
  var valid = this.validate($schema, schema);
  if (!valid && throwOrLogError) {
    var message = 'schema is invalid: ' + this.errorsText();
    if (this._opts.validateSchema == 'log') this.logger.error(message);
    else throw new Error(message);
  }
  return valid;
}