Parse the application schema from the given application row.
514747
private ApplicationDefinition loadAppRow(Tenant tenant, Map<String, String> colMap) {
        ApplicationDefinition appDef = new ApplicationDefinition();
        String appSchema = colMap.get(COLNAME_APP_SCHEMA);
        if (appSchema == null) {
            return null;    // Not a real application definition row
        }
        String format = colMap.get(COLNAME_APP_SCHEMA_FORMAT);
        ContentType contentType = Utils.isEmpty(format) ? ContentType.TEXT_XML : new ContentType(format);
        String versionStr = colMap.get(COLNAME_APP_SCHEMA_VERSION);
        int schemaVersion = Utils.isEmpty(versionStr) ? CURRENT_SCHEMA_LEVEL : Integer.parseInt(versionStr);
        if (schemaVersion > CURRENT_SCHEMA_LEVEL) {
            m_logger.warn("Skipping schema with advanced version: {}", schemaVersion);
            return null;
        }
        try {
            appDef.parse(UNode.parse(appSchema, contentType));
        } catch (Exception e) {
            m_logger.warn("Error parsing schema for application '" + appDef.getAppName() + "'; skipped", e);
            return null;
        }
        appDef.setTenantName(tenant.getName());
        return appDef;
    }
212319
def parse_text(text: str, schema: dict) -> Any:
    
    try:
        data = json.loads(text)
        jsonschema.validate(data, schema)
    except (TypeError, json.decoder.JSONDecodeError):
        raise jsonschema.ValidationError("Could not parse json")

    return data
758348
def load_schema(schema):
    
    with repo.Repo.db:
        repo.Repo.db.executescript(schema)
1262216
def _infer_schema(row, names=None):
    """"""
    if isinstance(row, dict):
        items = sorted(row.items())

    elif isinstance(row, (tuple, list)):
        if hasattr(row, "__fields__"):  # Row
            items = zip(row.__fields__, tuple(row))
        elif hasattr(row, "_fields"):  # namedtuple
            items = zip(row._fields, tuple(row))
        else:
            if names is None:
                names = ['_%d' % i for i in range(1, len(row) + 1)]
            elif len(names) < len(row):
                names.extend('_%d' % i for i in range(len(names) + 1, len(row) + 1))
            items = zip(names, row)

    elif hasattr(row, "__dict__"):  # object
        items = sorted(row.__dict__.items())

    else:
        raise TypeError("Can not infer schema for type: %s" % type(row))

    fields = [StructField(k, _infer_type(v), True) for k, v in items]
    return StructType(fields)
727124
def _read_schema(self):
        """"""
        cache_filename = os.path.join(
            CACHE_ROOT, "%s.smt" % self._representation)
        log.info("Attempting to read local schema at %s" % cache_filename)
        try:
            if time.time() - os.stat(cache_filename).st_mtime > CACHE_EXPIRY:
                log.warning("Cache expired, re-pulling")
                self._pull_schema_definition(cache_filename)
        except OSError:
            log.warning("Local schema not found. Pulling from web.")
            self._pull_schema_definition(cache_filename)
        else:
            log.info("Success")

        return cache_filename
176746
private Database readSingleSchemaFile(DatabaseIO reader, File schemaFile)
    {
        Database model = null;

        if (!schemaFile.isFile())
        {
            log("Path "+schemaFile.getAbsolutePath()+" does not denote a schema file", Project.MSG_ERR);
        }
        else if (!schemaFile.canRead())
        {
            log("Could not read schema file "+schemaFile.getAbsolutePath(), Project.MSG_ERR);
        }
        else
        {
            try
            {
                model = reader.read(schemaFile);
                log("Read schema file "+schemaFile.getAbsolutePath(), Project.MSG_INFO);
            }
            catch (Exception ex)
            {
                throw new BuildException("Could not read schema file "+schemaFile.getAbsolutePath()+": "+ex.getLocalizedMessage(), ex);
            }
        }
        return model;
    }
1224964
def from_schema(cls, schema, *args, **kwargs):
        

        return cls(schema.get(u"id", u""), schema, *args, **kwargs)
919090
public JSONObject parseJSONSchema(JSONObject schema) throws Exception {
        JSONObject json = new JSONObject();
        String name = "";
        JSONObject properties = schema;

        // Check if key 'properties' exists
        if (schema.has("properties")) {
            // Obtain properties
            properties = schema.getJSONObject("properties");
        }

        // Obtain all keys and iterate through them
        Iterator<?> keys = properties.keys();
        while (keys.hasNext()) {
            // Obtain key
            String key = keys.next().toString();
            // Obtain value of key
            JSONObject element = properties.getJSONObject(key);
            // Check if value contain properties
            // If it DOESN'T CONTAIN properties
            if (!element.has("properties")) {
                // Check if it has default value
                if (element.has("default")) {
                    // Add element with the default value assigned
                    json.put(key, element.get("default"));
                // If it doesn't have default value, we assign a default value depending on the type
                } else {
                    switch (element.getString("type")) {
                        case "string":
                            json.put(key, "");
                            break;
                        case "boolean":
                            json.put(key, false);
                            break;
                        case "number": case "integer":
                            json.put(key, 0);
                            break;
                        default:
                            Assertions.fail("type not expected");
                    }
                }
            // If it CONTAINS properties
            } else {
                // Recursive call, keep evaluating json
                json.put(key, parseJSONSchema(element));
            }
        }

        return json;
    }
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
92813
private void loadSchema() {
        m_logger.info("Loading schema for application: {}", m_config.app);
        m_client = new Client(m_config.host, m_config.port, m_config.getTLSParams());
        m_client.setCredentials(m_config.getCredentials());
        m_session = m_client.openApplication(m_config.app); // throws if unknown app
        m_appDef = m_session.getAppDef();
        if (m_config.optimize) {
            computeLinkFanouts();
        }
    }
672401
public static Schema parseSchemaFromFile(Path filePath, FileSystem fs) throws IOException {
    Preconditions.checkArgument(fs.exists(filePath), filePath + " does not exist");

    try (FSDataInputStream in = fs.open(filePath)) {
      return new Schema.Parser().parse(in);
    }
  }
776747
def _parse_schema(schema, method):
    
    if method and schema.get('readOnly', False):
        return _READONLY_PROPERTY

    # allOf: Must be valid against all of the subschemas
    if 'allOf' in schema:
        schema_ = copy.deepcopy(schema['allOf'][0])
        for x in schema['allOf'][1:]:
            _dict_merge(schema_, x)

        return _parse_schema(schema_, method)

    # anyOf: Must be valid against any of the subschemas
    # TODO(stephenfin): Handle anyOf

    # oneOf: Must be valid against exactly one of the subschemas
    if 'oneOf' in schema:
        # we only show the first one since we can't show everything
        return _parse_schema(schema['oneOf'][0], method)

    if 'enum' in schema:
        # we only show the first one since we can't show everything
        return schema['enum'][0]

    schema_type = schema.get('type', 'object')

    if schema_type == 'array':
        # special case oneOf so that we can show examples for all possible
        # combinations
        if 'oneOf' in schema['items']:
            return [
                _parse_schema(x, method) for x in schema['items']['oneOf']]

        return [_parse_schema(schema['items'], method)]

    if schema_type == 'object':
        if method and all(v.get('readOnly', False)
                          for v in schema['properties'].values()):
            return _READONLY_PROPERTY

        results = []
        for name, prop in schema.get('properties', {}).items():
            result = _parse_schema(prop, method)
            if result != _READONLY_PROPERTY:
                results.append((name, result))

        return collections.OrderedDict(results)

    if (schema_type, schema.get('format')) in _TYPE_MAPPING:
        return _TYPE_MAPPING[(schema_type, schema.get('format'))]

    return _TYPE_MAPPING[(schema_type, None)]
458307
function getSchema(connection) {
  connection.maxRows = 1000000;
  return runQuery(SCHEMA_SQL, connection).then(queryResult =>
    formatSchemaQueryResults(queryResult)
  );
}
132286
function extractFromRow(row, context, asString)
{
  var map    = row._arrayProcessedColumns;
  var values = row.values;

  // get the value
  var columnIndex = this.getIndex();
  var ret = values[columnIndex];

  // if we want the value as a string, and the column is of type variant, and we
  // haven't already processed the value before, we don't need to process the
  // value, so only process if none of the aforementioned conditions are true
  if (!(asString && this.isVariant() && !map[columnIndex]))
  {
    // if the column value has not been processed yet, process it, put it back
    // in the values array, and remember that the value has been processed
    if (!map[columnIndex])
    {
      if (ret !== null)
      {
        ret = values[columnIndex] =
            context.convert(values[columnIndex], this, context);
      }
      map[columnIndex] = true;
    }

    // use the appropriate extraction function depending on whether
    // we want the value or a string representation of the value
    var extractFn = !asString ? context.toValue : context.toString;
    ret = extractFn(ret);
  }

  return ret;
}
158375
private void storeApplicationSchema(ApplicationDefinition appDef) {
        String appName = appDef.getAppName();
        Tenant tenant = Tenant.getTenant(appDef);
        DBTransaction dbTran = DBService.instance(tenant).startTransaction();
        dbTran.addColumn(SchemaService.APPS_STORE_NAME, appName, COLNAME_APP_SCHEMA, appDef.toDoc().toJSON());
        dbTran.addColumn(SchemaService.APPS_STORE_NAME, appName, COLNAME_APP_SCHEMA_FORMAT, ContentType.APPLICATION_JSON.toString());
        dbTran.addColumn(SchemaService.APPS_STORE_NAME, appName, COLNAME_APP_SCHEMA_VERSION, Integer.toString(CURRENT_SCHEMA_LEVEL));
        DBService.instance(tenant).commit(dbTran);
    }
711970
@Override
  protected Schema fetchSchemaByKey(String key) throws SchemaRegistryException {
    String schemaUrl = KafkaAvroSchemaRegistry.this.url + GET_RESOURCE_BY_ID + key;

    GetMethod get = new GetMethod(schemaUrl);

    int statusCode;
    String schemaString;
    HttpClient httpClient = this.borrowClient();
    try {
      statusCode = httpClient.executeMethod(get);
      schemaString = get.getResponseBodyAsString();
    } catch (IOException e) {
      throw new SchemaRegistryException(e);
    } finally {
      get.releaseConnection();
      this.httpClientPool.returnObject(httpClient);
    }

    if (statusCode != HttpStatus.SC_OK) {
      throw new SchemaRegistryException(
          String.format("Schema with key %s cannot be retrieved, statusCode = %d", key, statusCode));
    }

    Schema schema;
    try {
      schema = new Schema.Parser().parse(schemaString);
    } catch (Throwable t) {
      throw new SchemaRegistryException(String.format("Schema with ID = %s cannot be parsed", key), t);
    }

    return schema;
  }
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)