Parses a row from query results into an equivalent object.

    Args:
      schema: the array of fields defining the schema of the data.
      data: the JSON row from a query result.
    Returns:
      The parsed row object.
514642
def parse_row(schema, data):
    
    def parse_value(data_type, value):
      """Parses a value returned from a BigQuery response.

      Args:
        data_type: the type of the value as specified by the schema.
        value: the raw value to return (before casting to data_type).

      Returns:
        The value cast to the data_type.
      """
      if value is not None:
        if value == 'null':
          value = None
        elif data_type == 'INTEGER':
          value = int(value)
        elif data_type == 'FLOAT':
          value = float(value)
        elif data_type == 'TIMESTAMP':
          value = datetime.datetime.utcfromtimestamp(float(value))
        elif data_type == 'BOOLEAN':
          value = value == 'true'
        elif (type(value) != str):
          # TODO(gram): Handle nested JSON records
          value = str(value)
      return value

    row = {}
    if data is None:
      return row

    for i, (field, schema_field) in enumerate(zip(data['f'], schema)):
      val = field['v']
      name = schema_field['name']
      data_type = schema_field['type']
      repeated = True if 'mode' in schema_field and schema_field['mode'] == 'REPEATED' else False

      if repeated and val is None:
        row[name] = []
      elif data_type == 'RECORD':
        sub_schema = schema_field['fields']
        if repeated:
          row[name] = [Parser.parse_row(sub_schema, v['v']) for v in val]
        else:
          row[name] = Parser.parse_row(sub_schema, val)
      elif repeated:
        row[name] = [parse_value(data_type, v['v']) for v in val]
      else:
        row[name] = parse_value(data_type, val)

    return row
64517
def _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None):
  
  if not source.exists():
    return _get_data_from_empty_list(source, fields, first_row, count)
  if schema is None:
    schema = source.schema
  fields = get_field_list(fields, schema)
  gen = source.range(first_row, count) if count >= 0 else source
  rows = [{'c': [{'v': row[c]} if c in row else {} for c in fields]} for row in gen]
  return {'cols': _get_cols(fields, schema), 'rows': rows}, source.length
468634
def from_json(cls, data, json_schema_class=None):
        
        json_schema = cls.json_schema if json_schema_class is None else json_schema_class()
        return super(BlockVertex, cls).from_json(data=data, json_schema_class=json_schema.__class__)
602516
def ParseRow(header,
             row):
  
  precondition.AssertDictType(row, Text, Text)

  result = rdf_osquery.OsqueryRow()
  for column in header.columns:
    result.values.append(row[column.name])
  return result
938586
def _rows_from_json(values, schema):
    """"""
    from google.cloud.bigquery import Row

    field_to_index = _field_to_index_mapping(schema)
    return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in values]
758348
def load_schema(schema):
    
    with repo.Repo.db:
        repo.Repo.db.executescript(schema)
93833
def schema_from_context(context):
    """"""
    item_class = context.get('class')
    return (
        serializer_mapping[item_class] if item_class else BaseSchema,
        context.get('many', False)
    )
183484
function (Schema, data) {
		var schemaKey = _.keys(data)[0];

		var mainSchema = this._parseSchemaHashKey(Schema, schemaKey);

		iterate.recursiveEach(data[schemaKey], mainSchema, function (v, k, schema) {
			if (/^=+$/.test(k)) {
				schema.validate(v);
				return;
			}

			schema = this._parseAndAddField(Schema, k, schema);
			if (_.isArray(v)) {
				schema.validate(v);
				return;
			}

			return schema;
		}, this);

		return mainSchema;
	}
981521
def parse_row(line_num, line, header, column_idx, prev_fields, options)
      fields = LineParser::parse(line, options[:in_format], options[:split_on])
      return nil,nil if fields.compact == []
      if options[:pad_fields] and fields.size < header.size
        fields += [''] * (header.size - fields.size) 
      end
      fields = Formatter::strip_quotes(fields) if @strip_quotes
      fields = Formatter::transform_row_ids(@transform_ids, fields) if @transform_ids
      fields = Filter::apply_column_filter(fields,column_idx) 
      return nil,nil if fields.compact == []
      rowname = fields[0]
      data_fields = fields[@first_column..-1]
      if data_fields.size > 0
        return nil,nil if not Validator::valid_row?(line_num, data_fields, prev_fields)
        return nil,nil if not Filter::numeric(@num_filter,data_fields,header)
        return nil,nil if not Filter::generic(@filter,data_fields,header)
        (rowname, data_fields) = Rewrite::rewrite(@rewrite,rowname,data_fields)
      end
      return rowname, data_fields
    end
221933
def restore_row(self, row, schema):
        
        for index, field in enumerate(schema.fields):
            if field.type == 'datetime':
                row[index] = parse(row[index])
            if field.type == 'date':
                row[index] = parse(row[index]).date()
            if field.type == 'time':
                row[index] = parse(row[index]).time()
        return schema.cast_row(row)
90824
def parse_results(fields, data):
    
    master = []

    for record in data['records']:  # for each 'record' in response
        row = [None] * len(fields)  # create null list the length of number of columns
        for obj, value in record.iteritems():  # for each obj in record
            if not isinstance(value, (dict, list, tuple)):  # if not data structure
                if obj in fields:
                    row[fields.index(obj)] = ensure_utf(value)

            elif isinstance(value, dict) and obj != 'attributes':  # traverse down into object
                path = obj
                _traverse_results(value, fields, row, path)

        master.append(row)
    return master
1224964
def from_schema(cls, schema, *args, **kwargs):
        

        return cls(schema.get(u"id", u""), schema, *args, **kwargs)
721863
def raw(self, query: Any, data: Any = None):
        
        assert isinstance(query, str)

        conn = self.get_connection()
        items = []

        for schema_name in conn['data']:
            input_db = conn['data'][schema_name]
            try:
                # Ensures that the string contains double quotes around keys and values
                query = query.replace("'", "\"")
                criteria = json.loads(query)

                for key, value in criteria.items():
                    input_db = self._evaluate_lookup(key, value, False, input_db)

                items.extend(list(input_db.values()))

            except json.JSONDecodeError:
                # FIXME Log Exception
                raise Exception("Query Malformed")
            except KeyError:
                # We encountered a repository where the key was not found
                pass

        return items
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)
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)
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
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