Make a Schema object from the given spec.

  The input and output types of this function are super unclear, and are held together by ponies,
  wishes, duct tape, and a load of tests. See the comments for horrific entertainment.
511535
def make_schema_from(value, env):
  

  # So this thing may not need to evaluate anything[0]
  if isinstance(value, framework.Thunk):
    value = framework.eval(value, env)

  # We're a bit messy. In general, this has evaluated to a Schema object, but not necessarily:
  # for tuples and lists, we still need to treat the objects as specs.
  if isinstance(value, schema.Schema):
    return value

  if framework.is_tuple(value):
    # If it so happens that the thing is a tuple, we need to pass in the data in a bit of a
    # different way into the schema factory (in a dictionary with {fields, required} keys).
    return schema_spec_from_tuple(value)

  if framework.is_list(value):
    # [0] This list may contain tuples, which oughta be treated as specs, or already-resolved schema
    # objects (as returned by 'int' and 'string' literals). make_schema_from
    # deals with both.
    return schema.from_spec([make_schema_from(x, env) for x in value])

  raise exceptions.EvaluationError('Can\'t make a schema from %r' % value)
1269530
def get_schema_spec(self, key):
    """"""
    member_node = self._ast_node.member.get(key, None)
    if not member_node:
      return schema.AnySchema()

    s = framework.eval(member_node.member_schema, self.env(self))
    if not isinstance(s, schema.Schema):
      raise ValueError('Node %r with schema node %r should evaluate to Schema, got %r' % (member_node, member_node.member_schema, s))
    return s
879727
function model(spec) {
  var schema = lodash.cloneDeep(spec);

  delete schema.id;

  schema = transform(schema, {
    removeFormats: true,
  });

  return schema;
}
1198797
function dict(schema, defaults, options) {
  if (kindOf(schema) !== 'array' || schema.length !== 2) {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Dict structs must be defined as an array with two elements, but you passed: ${schema}`
      )
    } else {
      throw new Error(`Invalid schema: ${schema}`)
    }
  }

  const obj = scalar('object', undefined, options)
  const keys = any(schema[0], undefined, options)
  const values = any(schema[1], undefined, options)
  const name = 'dict'
  const type = `dict<${keys.type},${values.type}>`
  const validate = value => {
    const resolved = resolveDefaults(defaults)
    value = resolved ? { ...resolved, ...value } : value
    const [error] = obj.validate(value)

    if (error) {
      error.type = type
      return [error]
    }

    const ret = {}
    const errors = []

    for (let k in value) {
      const v = value[k]
      const [e, r] = keys.validate(k)

      if (e) {
        const allE = e.errors || [e]
        allE.forEach(singleE => {
          singleE.path = [k].concat(singleE.path)
          singleE.data = value
          errors.push(singleE)
        })
        continue
      }

      k = r
      const [e2, r2] = values.validate(v)

      if (e2) {
        const allE2 = e2.errors || [e2]
        allE2.forEach(singleE => {
          singleE.path = [k].concat(singleE.path)
          singleE.data = value
          errors.push(singleE)
        })
        continue
      }

      ret[k] = r2
    }

    if (errors.length) {
      const first = errors[0]
      first.errors = errors
      return [first]
    }

    return [undefined, ret]
  }

  return new Kind(name, type, validate)
}
617661
def build_schema(schema: Schema) -> Mapping[str, Any]:
    
    builder = Schemas(build_parameter=build_parameter)
    return builder.build(schema)
1220556
def get_response_example(self, resp_spec):
        
        if 'schema' in resp_spec.keys():
            if '$ref' in resp_spec['schema']:  # Standard definition
                definition_name = self.get_definition_name_from_ref(resp_spec['schema']['$ref'])
                return self.definitions_example[definition_name]
            elif 'items' in resp_spec['schema'] and resp_spec['schema']['type'] == 'array':  # Array
                if '$ref' in resp_spec['schema']['items']:
                    definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items']['$ref'])
                else:
                    if 'type' in resp_spec['schema']['items']:
                        definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items'])
                        return [definition_name]
                    else:
                        logging.warn("No item type in: " + resp_spec['schema'])
                        return ''
                return [self.definitions_example[definition_name]]
            elif 'type' in resp_spec['schema']:
                return self.get_example_from_prop_spec(resp_spec['schema'])
        else:
            return ''
814109
function func(schema, defaults, options) {
  if (kindOf(schema) !== 'function') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Function structs must be defined as a function, but you passed: ${schema}`
      )
    } else {
      throw new Error(`Invalid schema: ${schema}`)
    }
  }

  const name = 'function'
  const type = '<function>'
  const validate = (value = resolveDefaults(defaults), data) => {
    const result = schema(value, data)
    let failure = { path: [], reason: null }
    let isValid

    switch (kindOf(result)) {
      case 'boolean': {
        isValid = result
        break
      }
      case 'string': {
        isValid = false
        failure.reason = result
        break
      }
      case 'object': {
        isValid = false
        failure = { ...failure, ...result }
        break
      }
      default: {
        if (process.env.NODE_ENV !== 'production') {
          throw new Error(
            `Validator functions must return a boolean, an error reason string or an error reason object, but you passed: ${schema}`
          )
        } else {
          throw new Error(`Invalid result: ${result}`)
        }
      }
    }

    return isValid
      ? [undefined, value]
      : [{ type, value, data: value, ...failure }]
  }

  return new Kind(name, type, validate)
}
511953
def _fill_schemas_from_definitions(self, obj):
        
        if obj.get('definitions'):
            self.schemas.clear()
            all_of_stack = []
            for name, definition in obj['definitions'].items():
                if 'allOf' in definition:
                    all_of_stack.append((name, definition))
                else:
                    self.schemas.create_schema(
                        definition, name, SchemaTypes.DEFINITION, root=self)
            while all_of_stack:
                name, definition = all_of_stack.pop(0)
                self.schemas.create_schema(
                    definition, name, SchemaTypes.DEFINITION, root=self)
395488
public static <T> Schema<T> createFrom(MappedSchema<T> ms, 
            Instantiator<T> instantiator, 
            Factory vf, 
            Predicate.Factory pf, 
            String ... args)
    {
        return vf.create(ms.typeClass, ms.fields, ms.fieldsByNumber, 
                ms.fieldsByName, instantiator, pf, args);
    }
541923
function compile(schema, _meta) {
  var schemaObj = this._addSchema(schema, undefined, _meta);
  return schemaObj.validate || this._compile(schemaObj);
}
383692
function (schema) {
		if (!schema.key || schema.key === 'base' || !Array.isArray(schema.fields)) {
			return null;
			// throw exception?
		}
		// store it for later reference
		Schemas[schema.key] = schema;
		// add this schema to the NPC object so we can use it as a constructor
		// this could overwrite is that ok?
		const Base = NPC[schema.key] = function () {
			// in case we add something to NPC constructor that we need to call?
			// NPC.Base.call(this);
		};
		Base.prototype = new NPC.Base();
		Base.prototype.constructor = Base;
		Base.prototype.schema = schema.key;
		Base.prototype.fields = [];
		Base.prototype.helpers = {};
		
		// initialize schema properties...
		schema.fields.forEach((f) => {
			let default_ = null;
			switch (f.type) {
				case 'string':
				case 'text':
					default_ = '';
					break;
				case 'array':
					default_ = [];
					break;
				case 'number':
				case 'modifier':
					default_ = 0;
					break;
				case undefined:
					// ?
					break;
			}
			Base.prototype.fields[f.key] = default_;
		});
		
		if (!schema.helpers || typeof schema.helpers !== 'object') { return; }
		const helpers = Object.keys(schema.helpers);
		helpers.forEach((h) => {
			// if (typeof schema.helpers[h] === 'function') {
			//	Base.prototype.helpers[h] = schema.helpers[h];
			// }
			// create a function from the array
			Base.prototype.helpers[h] = new Function(...schema.helpers[h]);
		});
	}
1096737
def build(self, schema: Schema) -> Mapping[str, Any]:
        
        fields = list(self.iter_fields(schema))

        properties = {
            field.name: self.build_parameter(field)
            for name, field in fields
        }

        result = dict(
            type="object",
            properties=properties,
        )

        required_fields = [
            name
            for name, field in fields
            if field.required and not field.allow_none
        ]

        if required_fields:
            result["required"] = required_fields

        return result
366484
function buildSchema(jsObj, key) {
  if (jsObj === undefined) return null;

  var type = typeOf(jsObj);
  switch (type) {
    case "array":
      {
        let schema = {
          type: "list",
          detail: buildSchema(jsObj[0])
        };
        key && (schema.name = key);
        return schema;
      }
    case "object":
      {
        let schema = {
          type: "map",
          detail: []
        };
        key && (schema.name = key);
        let keys = Object.keys(jsObj);
        for (var i in keys) {
          let key = keys[i];
          if (jsObj[key] !== undefined) {
            schema.detail.push(buildSchema(jsObj[key], key));
          }
        }
        return schema;
      }
    case "null":
    case "string":
    case "number":
    case "date":
    case "boolean":
      {
        let schema = {
          type: type
        };
        key && (schema.name = key);
        return schema;
      }
    default:
      throw Error("Unacceptable type : " + type);
  }
}
1156908
def build_schema(
    source: Union[str, Source],
    assume_valid=False,
    assume_valid_sdl=False,
    no_location=False,
    experimental_fragment_variables=False,
) -> GraphQLSchema:
    """"""
    return build_ast_schema(
        parse(
            source,
            no_location=no_location,
            experimental_fragment_variables=experimental_fragment_variables,
        ),
        assume_valid=assume_valid,
        assume_valid_sdl=assume_valid_sdl,
    )
439408
def schemaParse(self):
        
        ret = libxml2mod.xmlSchemaParse(self._o)
        if ret is None:raise parserError('xmlSchemaParse() failed')
        __tmp = Schema(_obj=ret)
        return __tmp
14499
def state_schema(module=''):
    '''
    
    '''
    specs = state_argspec(module)

    schemas = []
    for state_mod, state_spec in specs.items():
        schemas.append(_argspec_to_schema(state_mod, state_spec))

    return schemas
1361745
function SchemaObjectInstanceFactory(schema, options) {
        // Represents an actual instance of an object.
        class SchemaObjectInstance {
            // Extend instance factory.
            static extend(extendSchema, extendOptions = {}) {
                // Extend requires reflection.
                if (_isProxySupported === false) {
                    throw new Error('[schema-object] Extending object requires --harmony flag.');
                }

                // Merge schema and options together.
                const mergedSchema = _.merge({}, schema, extendSchema);
                const mergedOptions = _.merge({}, options, extendOptions);

                // Allow method and constructor to call `this.super()`.
                const methodHomes = ['methods', 'constructors'];
                for (const methodHome of methodHomes) {
                    // Ensure object containing methods exists on both provided and original options.
                    if (_.size(options[methodHome]) && _.size(extendOptions[methodHome])) {
                        // Loop through each method in the original options.
                        // It's not necessary to bind `this.super()` for options that didn't already exist.
                        _.each(options[methodHome], (method, name) => {
                            // The original option may exist, but was it extended?
                            if (extendOptions[methodHome][name]) {
                                // Extend method by creating a binding that takes the `this` context given and adds `self`.
                                // `self` is a reference to the original method, also bound to the correct `this`.
                                mergedOptions[methodHome][name] = function () {
                                    this[_privateKey]._reservedFields.super = () => {
                                        return method.apply(this, arguments);
                                    };
                                    const ret = extendOptions[methodHome][name].apply(this, arguments);
                                    delete this[_privateKey]._reservedFields.super;
                                    return ret;
                                };
                            }
                        });
                    }
                }

                return new SchemaObject(mergedSchema, mergedOptions);
            }

            // Construct new instance pre-populated with values.
            constructor(values, _root) {
                // Object used to store internals.
                const _private = this[_privateKey] = {};

                //
                _private._root = options.inheritRootThis ? _root || this : this;

                // Object with getters and setters bound.
                _private._getset = this;

                // Public version of ourselves.
                // Overwritten with proxy if available.
                _private._this = this;

                // Object used to store raw values.
                const obj = _private._obj = {};

                // Schema as defined by constructor.
                _private._schema = schema;

                // Errors, retrieved with getErrors().
                _private._errors = [];

                // Options need to be accessible. Shared across ALL INSTANCES.
                _private._options = options;

                // Reserved keys for storing internal properties accessible from outside.
                _private._reservedFields = {};

                // Normalize schema properties to allow for shorthand declarations.
                _.each(schema, (properties, index) => {
                    schema[index] = normalizeProperties.call(this, properties, index);
                });

                // Define getters/typecasts based off of schema.
                _.each(schema, (properties, index) => {
                    // Use getter / typecast to intercept and re-route, transform, etc.
                    defineGetter.call(_private._getset, index, properties);
                    defineSetter.call(_private._getset, index, properties);
                });

                // Proxy used as interface to object allows to intercept all access.
                // Without Proxy we must register individual getter/typecasts to put any logic in place.
                // With Proxy, we still use the individual getter/typecasts, but also catch values that aren't in the schema.
                if (_isProxySupported === true) {
                    const proxy = this[_privateKey]._this = new Proxy(this, {
                        // Ensure only public keys are shown.
                        ownKeys: (target) => {
                            return Object.keys(this.toObject());
                        },

                        // Return keys to iterate.
                        enumerate: (target) => {
                            return Object.keys(this[_privateKey]._this)[Symbol.iterator]();
                        },

                        // Check to see if key exists.
                        has: (target, key) => {
                            return !!_private._getset[key];
                        },

                        // Ensure correct prototype is returned.
                        getPrototypeOf: () => {
                            return _private._getset;
                        },

                        // Ensure readOnly fields are not writeable.
                        getOwnPropertyDescriptor: (target, key) => {
                            return {
                                value: proxy[key],
                                writeable: !schema[key] || schema[key].readOnly !== true,
                                enumerable: true,
                                configurable: true
                            };
                        },

                        // Intercept all get calls.
                        get: (target, name, receiver) => {
                            // First check to see if it's a reserved field.
                            if (_reservedFields.includes(name)) {
                                return this[_privateKey]._reservedFields[name];
                            }

                            // Support dot notation via lodash.
                            if (options.dotNotation && typeof name === 'string' && name.indexOf('.') !== -1) {
                                return _.get(this[_privateKey]._this, name);
                            }

                            // Use registered getter without hitting the proxy to avoid creating an infinite loop.
                            return this[name];
                        },

                        // Intercept all set calls.
                        set: (target, name, value, receiver) => {
                            // Support dot notation via lodash.
                            if (options.dotNotation && typeof name === 'string' && name.indexOf('.') !== -1) {
                                return _.set(this[_privateKey]._this, name, value);
                            }

                            // Find real keyname if case sensitivity is off.
                            if (options.keysIgnoreCase && !schema[name]) {
                                name = getIndex.call(this, name);
                            }

                            if (!schema[name]) {
                                if (options.strict) {
                                    // Strict mode means we don't want to deal with anything not in the schema.
                                    // TODO: SetterError here.
                                    return true;
                                } else {
                                    // Add index to schema dynamically when value is set.
                                    // This is necessary for toObject to see the field.
                                    addToSchema.call(this, name, {
                                        type: 'any'
                                    });
                                }
                            }

                            // This hits the registered setter but bypasses the proxy to avoid an infinite loop.
                            this[name] = value;

                            // Necessary for Node v6.0. Prevents error: 'set' on proxy: trap returned falsish for property 'string'".
                            return true;
                        },

                        // Intercept all delete calls.
                        deleteProperty: (target, property) => {
                            this[property] = undefined;
                            return true;
                        }
                    });
                }

                // Populate schema defaults into object.
                _.each(schema, (properties, index) => {
                    if (properties.default !== undefined) {
                        // Temporarily ensure readOnly is turned off to prevent the set from failing.
                        const readOnly = properties.readOnly;
                        properties.readOnly = false;
                        this[index] = _.isFunction(properties.default) ? properties.default.call(this) : properties.default;
                        properties.readOnly = readOnly;
                    }
                });

                // Call default constructor.
                _private._options.constructors.default.call(this, values);

                // May return actual object instance or Proxy, depending on harmony support.
                return _private._this;
            }

            // Populate values.
            populate(values) {
                for (const key in values) {
                    this[_privateKey]._this[key] = values[key];
                }
            }

            // Clone and return SchemaObject.
            clone() {
                return new SchemaObjectInstance(this.toObject(), this[_privateKey]._root);
            }

            // Return object without getter/typecasts, extra properties, etc.
            toObject() {
                const options = this[_privateKey]._options;
                let getObj = {};

                // Populate all properties in schema.
                _.each(this[_privateKey]._schema, (properties, index) => {
                    // Do not write values to object that are marked as invisible.
                    if (properties.invisible) {
                        return;
                    }

                    // Fetch value through the public interface.
                    let value = this[_privateKey]._this[index];

                    // Do not write undefined values to the object because of strange behavior when using with MongoDB.
                    // MongoDB will convert undefined to null and overwrite existing values in that field.
                    if (value === undefined && options.setUndefined !== true) {
                        return;
                    }

                    // Clone objects so they can't be modified by reference.
                    if (_.isObject(value)) {
                        if (value._isSchemaObject) {
                            value = value.toObject();
                        } else if (value._isSchemaArray) {
                            value = value.toArray();
                        } else if (_.isArray(value)) {
                            value = value.splice(0);
                        } else if (_.isDate(value)) {
                            // https://github.com/documentcloud/underscore/pull/863
                            // _.clone doesn't work on Date object.
                            getObj[index] = new Date(value.getTime());
                        } else {
                            value = _.clone(value);
                        }

                        // Don't write empty objects or arrays.
                        if (!_.isDate(value) && !options.setUndefined && !_.size(value)) {
                            return;
                        }
                    }

                    // Write to object.
                    getObj[index] = value;
                });

                // If options contains toObject, pass through before returning final object.
                if (_.isFunction(options.toObject)) {
                    getObj = options.toObject.call(this, getObj);
                }

                return getObj;
            }

            // toJSON is an interface used by JSON.stringify.
            // Return the raw object if called.
            toJSON() {
                return this.toObject();
            }

            // Clear all values.
            clear() {
                _.each(this[_privateKey]._schema, (properties, index) => {
                    clearField.call(this[_privateKey]._this, index, properties);
                });
            }

            // Get all errors.
            getErrors() {
                const errors = [];
                for (let error of this[_privateKey]._errors) {
                    error = _.cloneDeep(error);
                    error.schemaObject = this;
                    errors.push(error);
                }

                _.each(this[_privateKey]._schema, (properties, index) => {
                    let required = properties.required;
                    let message = `${index} is required but not provided`;

                    //If required is an array, set custom message
                    if (Array.isArray(required)) {
                      message = required[1] || message;
                      required = required[0];
                    }
                    //Skip if required does not exist
                    if (!required) {
                        return;
                    }
                    //Skip if required is a function, but returns false
                    else if (typeof required === 'function' && !required.call(this)) {
                        return;
                    }

                    //Skip if property has a value, is a boolean set to false, or if it's falsy and falsy values are allowed
                    if (
                      this[index] ||
                      typeof this[index] === 'boolean' ||
                      this[_privateKey]._options.allowFalsyValues && this[index] !== undefined
                    ) {
                      return;
                    }

                    const error = new SetterError(message, this[index], this[index], properties);
                    error.schemaObject = this;
                    errors.push(error);
                });

                // Look for sub-SchemaObjects.
                for (const name in this[_privateKey]._schema) {
                    const field = this[_privateKey]._schema[name];
                    if (field.type === 'object' && typeof field.objectType === 'function') {
                        const subErrors = this[name].getErrors();
                        for (const subError of subErrors) {
                            subError.fieldSchema.name = `${name}.${subError.fieldSchema.name}`;
                            subError.schemaObject = this;
                            errors.push(subError);
                        }
                    }
                }

                return errors;
            }

            // Clear all errors
            clearErrors() {
                this[_privateKey]._errors.length = 0;

                // Look for sub-SchemaObjects.
                for (const name in this[_privateKey]._schema) {
                    const field = this[_privateKey]._schema[name];
                    if (field.type === 'object' && typeof field.objectType === 'function') {
                        this[name].clearErrors();
                    }
                }
            }

            // Has errors?
            isErrors() {
                return this.getErrors().length > 0;
            }

            // Used to detect instance of schema object internally.
            _isSchemaObject() {
                return true;
            }
        }

        // Add custom methods to factory-generated class.
        _.each(options.methods, (method, key) => {
            if (SchemaObjectInstance.prototype[key]) {
                throw new Error(`Cannot overwrite existing ${key} method with custom method.`);
            }
            SchemaObjectInstance.prototype[key] = method;
        });

        return SchemaObjectInstance;
    }