Create a Flatson instance from a schemafile
166763
def from_schemafile(cls, schemafile):
        
        with open(schemafile) as f:
            return cls(json.load(f))
417115
def field_singleton_schema(  # noqa: C901 (ignore complexity)
    field: Field,
    *,
    by_alias: bool,
    model_name_map: Dict[Type['main.BaseModel'], str],
    schema_overrides: bool = False,
    ref_prefix: Optional[str] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
    

    ref_prefix = ref_prefix or default_prefix
    definitions: Dict[str, Any] = {}
    if field.sub_fields:
        return field_singleton_sub_fields_schema(
            field.sub_fields,
            by_alias=by_alias,
            model_name_map=model_name_map,
            schema_overrides=schema_overrides,
            ref_prefix=ref_prefix,
        )
    if field.type_ is Any:
        return {}, definitions  # no restrictions
    if is_callable_type(field.type_):
        raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.')
    f_schema: Dict[str, Any] = {}
    if issubclass(field.type_, Enum):
        f_schema.update({'enum': [item.value for item in field.type_]})  # type: ignore
        # Don't return immediately, to allow adding specific types
    for field_name, schema_name in validation_attribute_to_schema_keyword.items():
        field_value = getattr(field.type_, field_name, None)
        if field_value is not None:
            if field_name == 'regex':
                field_value = field_value.pattern
            f_schema[schema_name] = field_value
    for type_, t_schema in field_class_to_schema_enum_enabled:
        if issubclass(field.type_, type_):
            f_schema.update(t_schema)
            break
    # Return schema, with or without enum definitions
    if f_schema:
        return f_schema, definitions
    for type_, t_schema in field_class_to_schema_enum_disabled:
        if issubclass(field.type_, type_):
            return t_schema, definitions
    # Handle dataclass-based models
    field_type = field.type_
    if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), main.BaseModel):
        field_type = cast(Type['dataclasses.DataclassType'], field_type)
        field_type = field_type.__pydantic_model__
    if issubclass(field_type, main.BaseModel):
        sub_schema, sub_definitions = model_process_schema(
            field_type, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix
        )
        definitions.update(sub_definitions)
        if not schema_overrides:
            model_name = model_name_map[field_type]
            definitions[model_name] = sub_schema
            return {'$ref': f'{ref_prefix}{model_name}'}, definitions
        else:
            return sub_schema, definitions
    raise ValueError(f'Value not declarable with JSON Schema, field: {field}')
948576
def resolve_schema_instance(schema):
    
    if isinstance(schema, type) and issubclass(schema, marshmallow.Schema):
        return schema()
    if isinstance(schema, marshmallow.Schema):
        return schema
    try:
        return marshmallow.class_registry.get_class(schema)()
    except marshmallow.exceptions.RegistryError:
        raise ValueError(
            "{!r} is not a marshmallow.Schema subclass or instance and has not"
            " been registered in the Marshmallow class registry.".format(schema)
        )
861207
def create_schema(self, check_if_exists=False, sync_schema=True,
                      verbosity=1):
        

        # safety check
        connection = connections[get_tenant_database_alias()]
        _check_schema_name(self.schema_name)
        cursor = connection.cursor()

        if check_if_exists and schema_exists(self.schema_name):
            return False

        fake_migrations = get_creation_fakes_migrations()

        if sync_schema:
            if fake_migrations:
                # copy tables and data from provided model schema
                base_schema = get_tenant_base_schema()
                clone_schema = CloneSchema()
                clone_schema.clone_schema(base_schema, self.schema_name)

                call_command('migrate_schemas',
                             tenant=True,
                             fake=True,
                             schema_name=self.schema_name,
                             interactive=False,
                             verbosity=verbosity)
            else:
                # create the schema
                cursor.execute('CREATE SCHEMA %s' % self.schema_name)
                call_command('migrate_schemas',
                             tenant=True,
                             schema_name=self.schema_name,
                             interactive=False,
                             verbosity=verbosity)

        connection.set_schema_to_public()
106337
private Schema createSchema(JAXBContext context) throws IOException, SAXException {
        // This is surprisingly faffy for something that has a generateSchema method! This will only produce
        // a Result object, of which a schema result is not possible but you can produce dom results that
        // can be converted into dom sources to be read by the schema factory. As you can define multiple
        // namespaces you need to have a list of these.
        final List<DOMResult> schemaDomResults = new ArrayList<DOMResult>();

        // First use the context to create the schema dom objects
        context.generateSchema(new SchemaOutputResolver() {

            @Override
            public Result createOutput(String namespaceUri, String suggestedFileName)
                            throws IOException {
                DOMResult domResult = new DOMResult();
                domResult.setSystemId(suggestedFileName);
                schemaDomResults.add(domResult);
                return domResult;
            }
        });

        // convert to a form that can be used by the schema factory
        DOMSource[] schemaDomSources = new DOMSource[schemaDomResults.size()];
        for (int i = 0; i < schemaDomResults.size(); i++) {
            DOMSource domSource = new DOMSource(schemaDomResults.get(i).getNode());
            schemaDomSources[i] = domSource;
        }

        // Finally create the schema
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaDomSources);
        return schema;
    }
610538
def convert(schema):
    """"""
    # pylint: disable=too-many-return-statements,too-many-branches
    if isinstance(schema, vol.Schema):
        schema = schema.schema

    if isinstance(schema, Mapping):
        val = []

        for key, value in schema.items():
            description = None
            if isinstance(key, vol.Marker):
                pkey = key.schema
                description = key.description
            else:
                pkey = key

            pval = convert(value)
            pval['name'] = pkey
            if description is not None:
                pval['description'] = description

            if isinstance(key, (vol.Required, vol.Optional)):
                pval[key.__class__.__name__.lower()] = True

                if key.default is not vol.UNDEFINED:
                    pval['default'] = key.default()

            val.append(pval)

        return val

    if isinstance(schema, vol.All):
        val = {}
        for validator in schema.validators:
            val.update(convert(validator))
        return val

    if isinstance(schema, (vol.Clamp, vol.Range)):
        val = {}
        if schema.min is not None:
            val['valueMin'] = schema.min
        if schema.max is not None:
            val['valueMax'] = schema.max
        return val

    if isinstance(schema, vol.Length):
        val = {}
        if schema.min is not None:
            val['lengthMin'] = schema.min
        if schema.max is not None:
            val['lengthMax'] = schema.max
        return val

    if isinstance(schema, vol.Datetime):
        return {
            'type': 'datetime',
            'format': schema.format,
        }

    if isinstance(schema, vol.In):
        if isinstance(schema.container, Mapping):
            return {
                'type': 'select',
                'options': list(schema.container.items()),
            }
        return {
            'type': 'select',
            'options': [(item, item) for item in schema.container]
        }

    if schema in (vol.Lower, vol.Upper, vol.Capitalize, vol.Title, vol.Strip):
        return {
            schema.__name__.lower(): True,
        }

    if isinstance(schema, vol.Coerce):
        schema = schema.type

    if schema in TYPES_MAP:
        return {'type': TYPES_MAP[schema]}

    raise ValueError('Unable to convert schema: {}'.format(schema))
855760
def to_s
      parts = FIELDS.flat_map do |field|
        [dump_extra_diffs(field),
         dump_missing_diffs(field),
         dump_mismatch_diffs(field)]
      end

      [
        "Table #{@table_name} does not match the expected schema.\n\n",
        parts.compact.join("\n"),
        "\nYou may disable schema checks by passing :disable => true to model_",
        "schema or by setting the ENV variable #{DISABLE_MODEL_SCHEMA_KEY}=1.\n"
      ].join
    end
49233
public static StructType fromSchema(Schema schema) {
        StructField[] structFields = new StructField[schema.numColumns()];
        for (int i = 0; i < structFields.length; i++) {
            switch (schema.getColumnTypes().get(i)) {
                case Double:
                    structFields[i] = new StructField(schema.getName(i), DataTypes.DoubleType, false, Metadata.empty());
                    break;
                case Integer:
                    structFields[i] =
                                    new StructField(schema.getName(i), DataTypes.IntegerType, false, Metadata.empty());
                    break;
                case Long:
                    structFields[i] = new StructField(schema.getName(i), DataTypes.LongType, false, Metadata.empty());
                    break;
                case Float:
                    structFields[i] = new StructField(schema.getName(i), DataTypes.FloatType, false, Metadata.empty());
                    break;
                default:
                    throw new IllegalStateException(
                                    "This api should not be used with strings , binary data or ndarrays. This is only for columnar data");
            }
        }
        return new StructType(structFields);
    }
284299
function buildSimpleExample(type, example) {
    // The values in schemaOrType refer to the type names of Swagger types
    if (type === 'string') {
        return typeof example === 'string' ? example : '';
    }
    else if (type === 'integer' || type === 'float' || type === 'number') {
        return typeof example === 'number' ? example : 0;
    }
    else if (type === 'boolean') {
        return typeof example === 'boolean' ? example : false;
    }
    else if (type === 'array') {
        return Array.isArray(example) ? example : [];
    }
    else if (type === 'object') {
        return typeof example === 'object' ? example : {};
    }
    else {
        return null;
    }
}
324231
def get_schema(schema_type):
    '''
    '''

    schema_file = "{}-schema.json".format(schema_type)
    file_path = os.path.join(_default_schema_dir, schema_file)

    if not os.path.isfile(file_path):
        raise RuntimeError('Schema file \'{}\' does not exist, is not readable, or is not a file'.format(file_path))

    return fileio.read_schema(file_path)
772172
public static Schema.Field[] flatSchema(Schema s) {
    List<Schema.Field> fields = s.getFields();
    Schema.Field[] flatSchema = new Schema.Field[fields.size()];
    int cnt = 0;
    for (Schema.Field f : fields) {
      if (isSupportedSchema(f.schema())) {
        flatSchema[cnt] = f;
        cnt++;
      }
    }
    // Return resized array
    return cnt != flatSchema.length ? Arrays.copyOf(flatSchema, cnt) : flatSchema;
  }
23110
def schema_from_table(table, schema=None):
    
    schema = schema if schema is not None else {}
    pairs = []
    for name, column in table.columns.items():
        if name in schema:
            dtype = dt.dtype(schema[name])
        else:
            dtype = dt.dtype(
                getattr(table.bind, 'dialect', SQLAlchemyDialect()),
                column.type,
                nullable=column.nullable,
            )
        pairs.append((name, dtype))
    return sch.schema(pairs)
283074
def _get_schema_file(extension, path):
        
        for file in os.listdir(path):
            if file.endswith(extension):
                return os.path.join(path, file)
323534
function (model, data, action, options) {
                var schema = model.schema,
                    schemaDefinition,
                    schemaType,
                    value,
                    factory,
                    newData = {};

                // convert top level properties to Models respective to there schema
                for (var key in schema) {
                    if (schema.hasOwnProperty(key)) {

                        schemaDefinition = schema[key];
                        schemaType = schemaDefinition.type;
                        value = this._getValueForKey(data, key, schemaType, schemaDefinition);

                        factory = null;
                        var typeResolver,
                            entity,
                            i,
                            list;
                        if (schemaType instanceof Array) {
                            if (schemaType.length === 1) {
                                typeResolver = schemaType[0];
                            } else if (schemaType.length === 0) {
                                this.log('ModelFactory for ListItem for "' + key + '" not defined', 'warn');
                                factory = Entity;
                            } else {
                                throw "Cannot determinate ModelFactory. Multiple factories defined for '" + key + "'.";
                            }

                            if (typeResolver instanceof Function) {
                                factory = typeResolver;
                                typeResolver = null;
                            }

                            if (value && value instanceof Array) {
                                // only create the list if items are there
                                list = newData[key] = new List();

                                for (i = 0; i < value.length; i++) {

                                    if (typeResolver) {
                                        factory = typeResolver.resolve(value[i], key);
                                    }

                                    if ((factory && factory.classof(Entity))) {
                                        entity = this.$dataSource._getContext(factory, model, value[i]).createEntity(factory, this._getIdForValue(value[i], factory));
                                        if (entity instanceof Entity && !(entity instanceof Model)) {
                                            entity.$parent = model;
                                            entity.$parentEntity = model;
                                        }
                                        entity.set(this._parseModel(entity, value[i], action, options));

                                        list.add(entity);
                                    } else {
                                        list.add(value[i]);
                                    }

                                }
                            }


                        } else if (Collection && schemaType.classof(Collection)) {
                            var contextForChildren = this.$dataSource._getContext(schemaType, model, value);
                            if (contextForChildren) {
                                if (model.$[key] instanceof Collection) {
                                    newData[key] = model.$[key];
                                    list = model.$[key];
                                } else {
                                    list = newData[key] = contextForChildren.createCollection(schemaType, (value instanceof Object) && !(value instanceof Array) ? value : null);
                                    list.$parent = contextForChildren.$contextModel;
                                }
                                if (value && value instanceof Array) {
                                    list.reset(this.parseCollection(list, value, action, options));
                                }

                            }
                        } else if (schemaType === Date && value && !(value instanceof Date)) {
                            newData[key] = moment(value, this.$dataSource.$.dateFormat).toDate();
                        } else if (schemaType.classof(Entity)) {
                            var id;
                            if (value && schemaType instanceof TypeResolver) {
                                factory = schemaType.resolve(value, key);
                            } else {
                                factory = schemaType || Entity;
                            }

                            if (!(factory && factory.classof(Entity))) {
                                throw "Factory for type '" + key + "' isn't an instance of Entity";
                            }

                            if (factory.classof(Model) && factory.prototype.$isDependentObject) {
                                id = key;
                                value = value || {};
                            } else if (value) {
                                id = this._getIdForValue(value, factory);
                            }
                            if (value) {
                                newData[key] = entity = this.$dataSource._getContext(factory, model, value).createEntity(factory, id);
                                if (entity instanceof Entity && !(entity instanceof Model)) {
                                    entity.$parent = model;
                                    entity.$parentEntity = model;
                                }
                                entity.set(this._parseModel(entity, value, action, options));
                            }

                        }
                    }
                }

                // add all values that are not defined in schema ...
                _.defaults(newData, data);

                return model.parse(newData);
            }
267918
def _ConvertToCanonicalSqlDict(self, schema, raw_dict, prefix=""):
    """"""
    flattened_dict = {}
    for k, v in iteritems(raw_dict):
      if isinstance(v, dict):
        flattened_dict.update(
            self._ConvertToCanonicalSqlDict(
                schema, v, prefix="%s%s." % (prefix, k)))
      else:
        field_name = prefix + k
        flattened_dict[field_name] = schema[field_name].convert_fn(v)
    return flattened_dict
1331413
public Schema createSchema(SAXSource source, PropertyMap properties) throws IOException, SAXException, IncorrectSchemaException {
    SchemaPatternBuilder spb = new SchemaPatternBuilder();
    SAXResolver resolver = ResolverFactory.createResolver(properties);
    ErrorHandler eh = properties.get(ValidateProperty.ERROR_HANDLER);
    DatatypeLibraryFactory dlf = properties.get(RngProperty.DATATYPE_LIBRARY_FACTORY);
    if (dlf == null) {
      //Create a new Data Type Library Loader
      dlf = new DatatypeLibraryLoader();
    }
    try {
      Pattern start = SchemaBuilderImpl.parse(createParseable(source, resolver, eh, properties), eh, dlf, spb,
          properties.contains(WrapProperty.ATTRIBUTE_OWNER));
      //Wrap the pattern
      return wrapPattern2(start, spb, properties);
    }
    catch (IllegalSchemaException e) {
      throw new IncorrectSchemaException();
    }
  }
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)