Create a whoosh.fields.Schema object from a list of field names.
    All fields will be set as TEXT fields. If datefields is supplied,
    additionally create DATETIME fields with those names
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
463646
public static List<FieldMetadata> getFieldMetadata(Schema schema) {
    List<Field> superclassFields = Arrays.asList(Weaver.getWovenFields(schema.getClass().getSuperclass()));

    List<FieldMetadata> fields = new ArrayList<>();
    // Fields up to but not including Schema
    for (Field field : Weaver.getWovenFields(schema.getClass())) {
      FieldMetadata fmd = FieldMetadata.createIfApiAnnotation(schema, field, superclassFields);
      if (null != fmd) // skip transient or other non-annotated fields
        fields.add(fmd);  // NOTE: we include non-JSON fields here; remove them later if we don't want them
    }
    return fields;
  }
655601
function buildField (args, field, form, model, schema, isArrayField) {
    // create field title from schema or property name
    var title = schema && schema.title
        ? schema.title
        : changeCase.titleCase(field.property)
    // set field title
    field.title = title
    // set label if labels are enabled
    if (form.labels && args.label !== false) {
        field.label = title
        // delete so wont be merged over placeholder
        if (args.label === true) {
            delete args.label
        }
    }
    // set placeholder if placeholders enabled
    if (form.placeholders || args.placeholder !== false) {
        field.placeholder = title
        // delete so wont be merged over placeholder
        if (args.placeholder === true) {
            delete args.placeholder
        }
    }
    // set immutable property on field - field will be disabled/readonly after
    // initial value is set
    if (model.columns[field.property] && model.columns[field.property].immutable) {
        field.immutable = true
    }
    // if property has schema then use schema to populate default values
    if (schema) {
        // if schema is an array then need to create sub fields for elements
        if (schema.type === 'array') {
            // do not allow nested arrays
            assert.ok(!isArrayField, 'nested arrays not supported')
            // build field that is array of fields
            return buildArrayField(args, field, form, model, schema)
        }
        // if schema has enum then default to select type
        else if (schema.enum) {
            field.inputType = 'select'
            field.options = _.map(schema.enum, value => {
                // by default use enum values as both key and value
                var option = {
                    title: value,
                    value: value,
                }
                // set selected flag for default value
                if (schema.default && schema.default === value) {
                    option.selected = true
                }
                return option
            })
        }
        // if value is boolean then default to checkbox
        else if (schema.type === 'boolean') {
            field.inputType = 'checkbox'
            // set default value
            field.value = schema.default
        }
        // otherwise use text
        else {
            field.inputType = 'text'
            // set default value
            field.value = schema.default
        }
        // if schema has pattern apply to field
        if (schema.pattern) {
            field.pattern = schema.pattern
        }
        // use schema description
        field.description = schema.description
        // store schema type on field since multiple schema types may map
        // to the same input type but need to be handled differently
        field.schemaType = schema.type
    }
    // property does not have schema
    else {
        // if property does not have schema then it must have input type
        assert.ok(inputTypes[args.inputType], `field without schema must have inputType ${model.name} ${field.property}`)
    }
    // set id for input
    field.id = model.path+'-'+field.property
    // set name for input as the modelName[property]
    field.name = model.name+'['+field.property+']'
    // merge args over default set for field
    _.merge(field, args)
    // if ckeditor flag is set on field then set for form
    if (field.ckeditor) {
        form.ckeditor = true
    }
    // return built field
    return field
}
1284217
def create_model(cls, data: dict, fields=None):
        '''
        
        '''
        if fields is None:
            fields = set(cls._fields.keys())
        else:
            if not isinstance(fields, set):
                fields = set(fields)
        new_keys = set(data.keys()) - fields
        if new_keys:
            for new_key in new_keys:
                del data[new_key]
        return cls(data)
47628
def schema(ctx, schema):
    
    data = yaml.load(schema)
    if not isinstance(data, (list, tuple)):
        data = [data]
    with click.progressbar(data, label=schema.name) as bar:
        for schema in bar:
            ctx.obj['grano'].schemata.upsert(schema)
145943
def create_db_schema(cls, cur, schema_name):
        
        create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
        cur.execute(create_schema_script)
959872
def extract_fields(cls, schema):
        
        # -- BASED-ON: parse.Parser._generate_expression()
        for part in parse.PARSE_RE.split(schema):
            if not part or part == '{{' or part == '}}':
                continue
            elif part[0] == '{':
                # this will be a braces-delimited field to handle
                yield cls.parse(part)
1092132
def set_fields(self, fields=None, *fields_args, **fields_kwargs):
        
        if fields_args:
            fields = [fields]
            fields.extend(fields_args)
            for field_name in fields:
                self.set_field(field_name)

        elif fields_kwargs:
            fields = make_dict(fields, fields_kwargs)
            for field_name, field_val in fields.items():
                self.set_field(field_name, field_val)

        else:
            if isinstance(fields, Mapping):
                for field_name, field_val in fields.items():
                    self.set_field(field_name, field_val)

            else:
                for field_name in fields:
                    self.set_field(field_name)

        return self
164646
def _schema(self, path, obj, app):
        
        if path.startswith('#/definitions'):
            last_token = jp_split(path)[-1]
            if app.version == '1.2':
                obj.update_field('name', scope_split(last_token)[-1])
            else:
                obj.update_field('name', last_token)
391091
function createUnitField(data, schema) {
    data = data || [];
    let partialField;

    switch (schema.type) {
    case FieldType.MEASURE:
        switch (schema.subtype) {
        case MeasureSubtype.CONTINUOUS:
            partialField = new PartialField(schema.name, data, schema, new ContinuousParser());
            return new Continuous(partialField, `0-${data.length - 1}`);
        default:
            partialField = new PartialField(schema.name, data, schema, new ContinuousParser());
            return new Continuous(partialField, `0-${data.length - 1}`);
        }
    case FieldType.DIMENSION:
        switch (schema.subtype) {
        case DimensionSubtype.CATEGORICAL:
            partialField = new PartialField(schema.name, data, schema, new CategoricalParser());
            return new Categorical(partialField, `0-${data.length - 1}`);
        case DimensionSubtype.TEMPORAL:
            partialField = new PartialField(schema.name, data, schema, new TemporalParser(schema));
            return new Temporal(partialField, `0-${data.length - 1}`);
        case DimensionSubtype.BINNED:
            partialField = new PartialField(schema.name, data, schema, new BinnedParser());
            return new Binned(partialField, `0-${data.length - 1}`);
        default:
            partialField = new PartialField(schema.name, data, schema, new CategoricalParser());
            return new Categorical(partialField, `0-${data.length - 1}`);
        }
    default:
        partialField = new PartialField(schema.name, data, schema, new CategoricalParser());
        return new Categorical(partialField, `0-${data.length - 1}`);
    }
}
264063
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder):  # noqa: C901
    """"""
    _validate_schema(schema, placeholder)
    tags = []
    fields = []
    ts = None
    meas = meas
    for k, t in schema.items():
        if t is MEASUREMENT:
            meas = f"{{i.{k}}}"
        elif t is TIMEINT:
            ts = f"{{i.{k}}}"
        elif t is TIMESTR:
            if pd:
                ts = f"{{pd.Timestamp(i.{k} or 0).value}}"
            else:
                ts = f"{{dt_to_int(str_to_dt(i.{k}))}}"
        elif t is TIMEDT:
            if pd:
                ts = f"{{pd.Timestamp(i.{k} or 0).value}}"
            else:
                ts = f"{{dt_to_int(i.{k})}}"
        elif t is TAG:
            tags.append(f"{k}={{str(i.{k}).translate(tag_escape)}}")
        elif t is TAGENUM:
            tags.append(f"{k}={{getattr(i.{k}, 'name', i.{k} or None)}}")
        elif t in (FLOAT, BOOL):
            fields.append(f"{k}={{i.{k}}}")
        elif t is INT:
            fields.append(f"{k}={{i.{k}}}i")
        elif t is STR:
            fields.append(f"{k}=\\\"{{str(i.{k}).translate(str_escape)}}\\\"")
        elif t is ENUM:
            fields.append(f"{k}=\\\"{{getattr(i.{k}, 'name', i.{k} or None)}}\\\"")
        else:
            raise SchemaError(f"Invalid attribute type {k!r}: {t!r}")
    extra_tags = extra_tags or {}
    for k, v in extra_tags.items():
        tags.append(f"{k}={v}")
    if placeholder:
        fields.insert(0, f"_=true")

    sep = ',' if tags else ''
    ts = f' {ts}' if ts else ''
    fmt = f"{meas}{sep}{','.join(tags)} {','.join(fields)}{ts}"
    if rm_none:
        # Has substantial runtime impact. Best avoided if performance is critical.
        # First field can't be removed.
        pat = r',\w+="?None"?i?'
        f = eval('lambda i: re.sub(r\'{}\', "", f"{}").encode()'.format(pat, fmt))
    else:
        f = eval('lambda i: f"{}".encode()'.format(fmt))
    f.__doc__ = "Returns InfluxDB line protocol representation of user-defined class"
    f._args = dict(meas=meas, schema=schema, rm_none=rm_none,
                   extra_tags=extra_tags, placeholder=placeholder)
    return f
348185
def _from_nested_schema(self, obj, field):
        """"""
        if isinstance(field.nested, basestring):
            nested = get_class(field.nested)
        else:
            nested = field.nested

        name = nested.__name__
        outer_name = obj.__class__.__name__
        only = field.only
        exclude = field.exclude

        # If this is not a schema we've seen, and it's not this schema,
        # put it in our list of schema defs
        if name not in self._nested_schema_classes and name != outer_name:
            wrapped_nested = self.__class__(nested=True)
            wrapped_dumped = wrapped_nested.dump(
                nested(only=only, exclude=exclude)
            )

            # Handle change in return value type between Marshmallow
            # versions 2 and 3.
            if marshmallow.__version__.split('.', 1)[0] >= '3':
                self._nested_schema_classes[name] = wrapped_dumped
            else:
                self._nested_schema_classes[name] = wrapped_dumped.data
            self._nested_schema_classes.update(
                wrapped_nested._nested_schema_classes
            )

        # and the schema is just a reference to the def
        schema = {
            'type': 'object',
            '$ref': '#/definitions/{}'.format(name)
        }

        # NOTE: doubled up to maintain backwards compatibility
        metadata = field.metadata.get('metadata', {})
        metadata.update(field.metadata)

        for md_key, md_val in metadata.items():
            if md_key == 'metadata':
                continue
            schema[md_key] = md_val

        if field.many:
            schema = {
                'type': ["array"] if field.required else ['array', 'null'],
                'items': schema,
            }

        return schema
561358
def get_dates(schema):
    """"""
    dates = [config.LAST_UPDATED, config.DATE_CREATED]
    for field, field_schema in schema.items():
        if field_schema['type'] == 'datetime':
            dates.append(field)
    return dates
154264
function buildFields (model, fields) {
    //  build list of fields from columns and properties properties
    if (!fields) {
        fields = _.keys(model.extraColumns)
        // if model has schema and properties
        if (model.schemaData) {
            fields = _.uniq( fields.concat( _.keys(model.schemaData.properties) ) )
        }
        // add create time field
        fields.push(metaFields.createTime)
        // add actions field
        fields.push(metaFields.actions)
    }
    // process fields
    fields = _.map(fields, field => {
        // if field is a string the build object
        if (typeof field === 'string') {
            // if field is a meta column then add spec
            if (metaFields[field]) {
                return metaFields[field]
            }
            // create spec
            else {
                field = {
                    property: field,
                }
            }
        }
        // create default label if label not set
        if (!field.title) {
            // use property name converted to upper case first words
            field.title = changeCase.titleCase(field.property)
        }
        // get column for property (if any)
        var column = model.columns[field.property]
        // if field is column then set properties based on column
        if (column) {
            // if column has index allow filter and search on column
            if (column.index || column.unique) {
                field.orderAscIcon = 'sort-alpha-asc'
                field.orderAscUrl = './?orderColumn='+field.property+'&orderDirection=ASC'
                field.orderDescIcon = 'sort-alpha-desc'
                field.orderDescUrl = './?orderColumn='+field.property+'&orderDirection=DESC'
                field.searchBy = true
                field.searchIcon =  'search'
            }
        }
        // return field spec
        return field
    })
    // return formatted fields
    return fields
}
380645
def convert_schemas(d, definitions=None):
    
    if Schema is None:
        raise RuntimeError('Please install marshmallow and apispec')

    if definitions is None:
        definitions = {}
    definitions.update(d.get('definitions', {}))

    new = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = convert_schemas(v, definitions)
        if isinstance(v, (list, tuple)):
            new_v = []
            for item in v:
                if isinstance(item, dict):
                    new_v.append(convert_schemas(item, definitions))
                else:
                    new_v.append(item)
            v = new_v
        if inspect.isclass(v) and issubclass(v, Schema):
            definitions[v.__name__] = schema2jsonschema(v)
            ref = {
                "$ref": "#/definitions/{0}".format(v.__name__)
            }
            if k == 'parameters':
                new[k] = schema2parameters(v)
                new[k][0]['schema'] = ref
            else:
                new[k] = ref
        else:
            new[k] = v

    # This key is not permitted anywhere except the very top level.
    if 'definitions' in new:
        del new['definitions']

    return new
726707
def set_fields_from_request(obj, request):
    
    schema = obj.Schema()
    # fields contains all schema-valid field values from the request.
    fields = {}
    for fieldname, value in request.items():
        if fieldname not in schema:
            continue
        field = schema[fieldname]
        widget = field.getWidgetName()
        if widget in ["ReferenceWidget"]:
            brains = []
            if value:
                brains = resolve_request_lookup(obj, request, fieldname)
                if not brains:
                    logger.warning(
                        "JSONAPI: Can't resolve reference: {} {}"
                        .format(fieldname, value))
                    return []
            if schema[fieldname].multiValued:
                value = [b.UID for b in brains] if brains else []
            else:
                value = brains[0].UID if brains else None
        fields[fieldname] = value
    # Write fields.
    for fieldname, value in fields.items():
        field = schema[fieldname]
        fieldtype = field.getType()
        if fieldtype == 'Products.Archetypes.Field.BooleanField':
            if value.lower() in ('0', 'false', 'no') or not value:
                value = False
            else:
                value = True
        elif fieldtype in ['Products.ATExtensions.field.records.RecordsField',
                           'Products.ATExtensions.field.records.RecordField']:
            try:
                value = eval(value)
            except:
                logger.warning(
                    "JSONAPI: " + fieldname + ": Invalid "
                    "JSON/Python variable")
                return []
        mutator = field.getMutator(obj)
        if mutator:
            mutator(value)
        else:
            field.set(obj, value)
    obj.reindexObject()
    return fields.keys()
753945
def _get_field_mapping(self, schema):
        
        if 'mapping' in schema:
            return schema['mapping']
        elif schema['type'] == 'dict' and 'schema' in schema:
            return self._get_mapping(schema['schema'])
        elif schema['type'] == 'list' and 'schema' in schema.get('schema', {}):
            return self._get_mapping(schema['schema']['schema'])
        elif schema['type'] == 'datetime':
            return {'type': 'date'}
        elif schema['type'] == 'string' and schema.get('unique'):
            return {'type': 'string', 'index': 'not_analyzed'}