Import schema as <types/> content.
500437
def import_schema(self, definitions, d):
        """"""
        if not definitions.types:
            root = Element("types", ns=wsdlns)
            definitions.root.insert(root)
            types = Types(root, definitions)
            definitions.types.append(types)
        else:
            types = definitions.types[-1]
        types.root.append(d.root)
        log.debug("imported (XSD):\n%s", d.root)
380063
def load(self, schemafile=None):
        """"""
        if schemafile is not None:
            self._schemafile = schemafile

        try:
            self.data = json.load(open(self._schemafile))
        except (IOError, ValueError), e:
            msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'"
            raise jsonschema.SchemaError(msg)

        self.loaded = True
292117
def db_schema(db, table):
  
  typedict = [('int', int), ('double', float),
              ('timestamp', datetime),
              ('date', date), ('time', dttime),
              ('text', str), ('char', str)]
  ret = {}
  q = '''select column_name, data_type
          from information_schema.columns
          where table_name = %s;'''
  #q = """select c.name, c.type from sys.columns as c, sys.tables as t where table_id = t.id and t.name = %s;"""
  # and data_type != 'date' and position('time' in data_type) =
  # 0 and column_name != 'humidity'
  for row in query(db, q, (table,)):
      name, dtype = tuple( row[:2] )
      name = str(name)
      for tn, tt in typedict:
          if tn in dtype:
              ret[name] = tt
              break
      if name not in ret:
          msg = "can't find type of %s\t%s"
          raise RuntimeError(msg % (name, dtype))
  return ret
211313
def _get_cols(fields, schema):
  
  typemap = {
    'STRING': 'string',
    'INT64': 'number',
    'INTEGER': 'number',
    'FLOAT': 'number',
    'FLOAT64': 'number',
    'BOOL': 'boolean',
    'BOOLEAN': 'boolean',
    'DATE': 'date',
    'TIME': 'timeofday',
    'DATETIME': 'datetime',
    'TIMESTAMP': 'datetime'
  }
  cols = []
  for col in fields:
    if schema:
      f = schema[col]
      t = 'string' if f.mode == 'REPEATED' else typemap.get(f.data_type, 'string')
      cols.append({'id': f.name, 'label': f.name, 'type': t})
    else:
      # This will only happen if we had no rows to infer a schema from, so the type
      # is not really important, except that GCharts will choke if we pass such a schema
      # to a chart if it is string x string so we default to number.
      cols.append({'id': col, 'label': col, 'type': 'number'})
  return cols
1188735
private Resource loadSchemas(Definition definition) throws WSDLException, IOException, TransformerException, TransformerFactoryConfigurationError {
        Types types = definition.getTypes();
        Resource targetXsd = null;
        Resource firstSchemaInWSDL = null;

        if (types != null) {
            List<?> schemaTypes = types.getExtensibilityElements();
            for (Object schemaObject : schemaTypes) {
                if (schemaObject instanceof SchemaImpl) {
                    SchemaImpl schema = (SchemaImpl) schemaObject;
                    inheritNamespaces(schema, definition);

                    addImportedSchemas(schema);
                    addIncludedSchemas(schema);

                    if (!importedSchemas.contains(getTargetNamespace(schema))) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        Source source = new DOMSource(schema.getElement());
                        Result result = new StreamResult(bos);

                        TransformerFactory.newInstance().newTransformer().transform(source, result);
                        Resource schemaResource = new ByteArrayResource(bos.toByteArray());

                        importedSchemas.add(getTargetNamespace(schema));
                        schemaResources.add(schemaResource);

                        if (definition.getTargetNamespace().equals(getTargetNamespace(schema)) && targetXsd == null) {
                            targetXsd = schemaResource;
                        } else if (targetXsd == null && firstSchemaInWSDL == null) {
                            firstSchemaInWSDL = schemaResource;
                        }
                    }
                } else {
                    log.warn("Found unsupported schema type implementation " + schemaObject.getClass());
                }
            }
        }

        for (Object imports : definition.getImports().values()) {
            for (Import wsdlImport : (Vector<Import>)imports) {
                String schemaLocation;
                URI locationURI = URI.create(wsdlImport.getLocationURI());
                if (locationURI.isAbsolute()) {
                    schemaLocation = wsdlImport.getLocationURI();
                } else {
                    schemaLocation = definition.getDocumentBaseURI().substring(0, definition.getDocumentBaseURI().lastIndexOf('/') + 1) + wsdlImport.getLocationURI();
                }

                loadSchemas(getWsdlDefinition(new FileSystemResource(schemaLocation)));
            }
        }

        if (targetXsd == null) {
            // Obviously no schema resource in WSDL did match the targetNamespace, just use the first schema resource found as main schema
            if (firstSchemaInWSDL != null) {
                targetXsd = firstSchemaInWSDL;
            } else if (!CollectionUtils.isEmpty(schemaResources)) {
                targetXsd = schemaResources.get(0);
            }
        }

        return targetXsd;
    }
26553
def import_definitions(self, definitions, d):
        """"""
        definitions.types += d.types
        definitions.messages.update(d.messages)
        definitions.port_types.update(d.port_types)
        definitions.bindings.update(d.bindings)
        self.imported = d
        log.debug("imported (WSDL):\n%s", d)
482544
def to_schema(self):
        
        types = set()
        generated_schemas = []
        for schema_generator in self._schema_generators:
            generated_schema = schema_generator.to_schema()
            if len(generated_schema) == 1 and 'type' in generated_schema:
                types.add(generated_schema['type'])
            else:
                generated_schemas.append(generated_schema)

        if types:
            if len(types) == 1:
                (types,) = types
            else:
                types = sorted(types)
            generated_schemas = [{'type': types}] + generated_schemas
        if len(generated_schemas) == 1:
            (result_schema,) = generated_schemas
        elif generated_schemas:
            result_schema = {'anyOf': generated_schemas}
        else:
            result_schema = {}

        return result_schema
1076998
def config_schema(self):
        """"""
        from rez.config import _plugin_config_dict
        d = _plugin_config_dict.get(self.type_name, {})

        for name, plugin_class in self.plugin_classes.iteritems():
            if hasattr(plugin_class, "schema_dict") \
                    and plugin_class.schema_dict:
                d_ = {name: plugin_class.schema_dict}
                deep_update(d, d_)
        return dict_to_schema(d, required=True, modifier=expand_system_vars)
303914
def tx_schema(self, **kwargs):
    
    for s in self.schema.schema: 
      tx = self.tx(s, **kwargs)
576768
def do_schema(self, line):
        
        args = self.getargs(line)

        if not args:
            for k in sorted(self.schema):
                print "%s\t%s" % (k, self.schema[k])
        elif args[0] == "--clear":
            self.schema.clear()
        else:
            fname = args[0]
            ftype = args[1]

            if not ftype in VALID_TYPES:
                print "invalid type: use %s" % list(VALID_TYPES)
            else:
                self.schema[fname] = ftype
784963
def fields_to_dtypes(schema):
    
    datetime_types = ['date', 'datetime']
    datetime_fields = {
        f['name']: _TABLE_SCHEMA_DTYPE_MAPPING.get(f['type'], 'object')
        for f in schema['fields']
        if f['type'] in datetime_types}

    other_fields = {
        f['name']: _TABLE_SCHEMA_DTYPE_MAPPING.get(f['type'], 'object')
        for f in schema['fields']
        if f['type'] not in datetime_types}

    return {'dates': datetime_fields, 'other': other_fields}
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);
    }
404042
def schema():
        """"""
        return Schema({
            'script': And(Or(type(' '), type(u' ')), len),
            Optional('title', default=''): str,
            Optional('model', default={}): {Optional(And(str, len)): object},
            Optional('env', default={}): {Optional(And(str, len)): And(str, len)},
            Optional('item', default=None): object,
            Optional('dry_run', default=False): bool,
            Optional('debug', default=False): bool,
            Optional('strict', default=False): bool,
            Optional('variables', default={}): {
                Optional(And(Or(type(' '), type(u' ')), len, Regex(r'([a-zA-Z][_a-zA-Z]*)'))):
                    Or(type(' '), type(u' '))
            },
            Optional('temporary_scripts_path', default=''): Or(type(''), type(u'')),
            Optional('internal', default=False): bool
        })
350723
def configure(self, *args, **kwargs):
        """"""

        self.version = kwargs['schema_version']
        self.namespace = kwargs['namespace']
        self.backend = get(kwargs['type'])(*args, **kwargs)
        self.context = kwargs.pop('schema_context', {})
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
764300
def get_schema(self, table, with_headers=False):
        """"""
        f = self.fetch('desc ' + wrap(table))
        if not isinstance(f[0], list):
            f = [f]

        # Replace None with ''
        schema = [['' if col is None else col for col in row] for row in f]

        # If with_headers is True, insert headers to first row before returning
        if with_headers:
            schema.insert(0, ['Column', 'Type', 'Null', 'Key', 'Default', 'Extra'])
        return schema
877204
def setup_schema(command, conf, vars):
    """"""
    # Load the models

    # <websetup.websetup.schema.before.model.import>
    from depotexample import model
    # <websetup.websetup.schema.after.model.import>

    
    # <websetup.websetup.schema.before.metadata.create_all>
    print("Creating tables")
    model.metadata.create_all(bind=config['tg.app_globals'].sa_engine)
    # <websetup.websetup.schema.after.metadata.create_all>
    transaction.commit()
    print('Initializing Migrations')
    import alembic.config, alembic.command
    alembic_cfg = alembic.config.Config()
    alembic_cfg.set_main_option("script_location", "migration")
    alembic_cfg.set_main_option("sqlalchemy.url", config['sqlalchemy.url'])
    alembic.command.stamp(alembic_cfg, "head")