Gets or creates the APElectionMeta object for the given row of
        AP data.
549493
def get_or_create_ap_election_meta(self, row, election):
        
        APElectionMeta.objects.get_or_create(
            ap_election_id=row["raceid"], election=election
        )
873402
static <T extends FunctionMeta> T createAttributeFunctionMeta(Class<T> metaClass, String formula, IDataModel model) throws Exception {
        T meta = (T) metaClass.newInstance().parse(formula);
        meta.setDataModelId(model.getDataModelId());
        if (meta.getName() == null) { meta.setName(model.getName()); }

        return meta;
    }
627178
function buildItem(parentAttrNode, row, context) {
    const item = {};

    if (context.primaryKey === null) resolvePrimaryKey(row, context);

    Object.keys(parentAttrNode.attributes).forEach(attrName => {
        const attrNode = parentAttrNode.attributes[attrName];

        if (context.selectedInternalLevel > 0) {
            if (!attrNode.selectedInternal) return;
            if (!attrNode.selectedInternal[context.selectedInternalLevel - 1]) return;
        } else if (!attrNode.selected) return;

        if (attrNode.attributes) {
            const subContext = Object.assign({}, context);
            subContext.attrPath = context.attrPath.concat([attrName]);

            if (attrNode.dataSources) {
                // resource context:
                subContext.resourceAttrNode = attrNode;
                subContext.primaryKey = null;
                subContext.secondaryRows = null;

                let rawResult;
                let keys;
                let keyIsNull = true;
                let parentKeyRow = row;

                if (
                    attrNode.parentDataSource &&
                    attrNode.parentDataSource !== context.resourceAttrNode.primaryDataSource
                ) {
                    parentKeyRow = context.secondaryRows[attrNode.parentDataSource];
                }

                if (parentKeyRow) {
                    rawResult = getResult(attrNode, attrNode.joinVia || attrNode.primaryDataSource, subContext);
                    keys = rawResult.parentKey.map(keyAttr => {
                        if (typeof parentKeyRow[keyAttr] === 'undefined') {
                            /*
                            // TODO: Strict mode?
                            throw new DataError(`Sub-resource "${subContext.attrPath.join('.')}" ` +
                                misses keyattribute "${keyAttr}" in parent result ` +
                                `(DataSource "${context.resourceAttrNode.primaryDataSource}")`);
                            */
                        } else if (parentKeyRow[keyAttr] !== null) {
                            keyIsNull = false;
                        }
                        return parentKeyRow[keyAttr];
                    });
                }

                if (keyIsNull) {
                    keys = [];
                } else if (!rawResult.multiValuedParentKey) {
                    // normal and composite parentKey: "keys" is a string (as array) afterwards:
                    keys = [keys.join(keySeparator)];
                } else {
                    // dereference parentKey array (key length must be 1 when multiValued)
                    // but "keys" is still an array (multiValued) afterwards:
                    keys = keys[0];

                    if (!Array.isArray(keys)) {
                        throw new DataError(
                            `Sub-resource "${subContext.attrPath.join('.')}" ` +
                                `multiValued key attribute "${rawResult.parentKey[0]}" ` +
                                'in parent result is not an array ' +
                                `(DataSource "${context.resourceAttrNode.primaryDataSource}")`
                        );
                    }
                }

                let secondaryRows = null;
                if (attrNode.joinVia) {
                    let primaryRawResult = null; // set on demand to avoid errors for empty results
                    const joinViaKeys = [];
                    secondaryRows = {};

                    keys.forEach(key => {
                        let joinViaRows = rawResult.indexedData[key];
                        if (!joinViaRows) return;

                        if (rawResult.uniqueChildKey) joinViaRows = [joinViaRows];

                        joinViaRows.forEach(joinViaRow => {
                            primaryRawResult =
                                primaryRawResult || getResult(attrNode, attrNode.primaryDataSource, subContext);

                            let childKeyIsNull = true;
                            const childKey = primaryRawResult.parentKey
                                .map(keyAttr => {
                                    if (typeof joinViaRow[keyAttr] === 'undefined') {
                                        throw new DataError(
                                            `Sub-resource "${subContext.attrPath.join('.')}" ` +
                                                `misses key attribute "${keyAttr}" in joinVia result ` +
                                                `(DataSource "${attrNode.joinVia}")`
                                        );
                                    } else if (joinViaRow[keyAttr] !== null) {
                                        childKeyIsNull = false;
                                    }
                                    return joinViaRow[keyAttr];
                                })
                                .join(keySeparator);

                            if (!childKeyIsNull) {
                                joinViaKeys.push(childKey);

                                secondaryRows[childKey] = {};
                                secondaryRows[childKey][attrNode.joinVia] = joinViaRow;
                            }
                        });
                    });

                    rawResult = primaryRawResult;
                    keys = joinViaKeys;
                }

                const subItem = [];
                keys.forEach(key => {
                    const subRow = rawResult.indexedData[key];
                    if (!subRow) {
                        // ignore
                    } else {
                        subContext.secondaryRows = secondaryRows ? secondaryRows[key] : null;

                        if (!rawResult.uniqueChildKey) {
                            subRow.forEach(singleSubRow => subItem.push(buildItem(attrNode, singleSubRow, subContext)));
                        } else {
                            subItem.push(buildItem(attrNode, subRow, subContext));
                        }
                    }
                });

                item[attrName] = attrNode.many ? subItem : subItem[0] || null;
            } else {
                // nested-attribute context:
                item[attrName] = buildItem(attrNode, row, subContext);
            }
        } else {
            item[attrName] = buildAttribute(attrNode, row, context);
        }
    });

    // Extension: "item"
    if (parentAttrNode.resourceName) {
        const resource = context.api.getResource(parentAttrNode.resourceName);
        if (resource && resource.extensions && resource.extensions.item) {
            resource.extensions.item({
                item,
                row,
                secondaryRows: context.secondaryRows,
                request: context.request,
                getAttribute: attribute => getAttribute(attribute || [], parentAttrNode),
                getResult: (attrNode, dataSourceName) =>
                    getResult(
                        attrNode || parentAttrNode,
                        dataSourceName || (attrNode || parentAttrNode).primaryDataSource,
                        context
                    ),
                buildItem: attributes => {
                    const maxRecursionLevel = 20;

                    function selectInternal(level, isSelected) {
                        attributes.forEach(attribute => {
                            let attrNode = parentAttrNode;
                            attribute.forEach(attrName => {
                                if (!(attrNode.attributes && attrNode.attributes[attrName])) {
                                    let attrStr = attribute.join('.');
                                    throw new ImplementationError(
                                        `item-extension/buildItem: Unknown attribute "${attrStr}"`
                                    );
                                }
                                attrNode = attrNode.attributes[attrName];

                                if (!attrNode.selectedInternal) {
                                    // we use a flag per recursion level to handle recursive buildItem calls independently
                                    attrNode.selectedInternal = new Array(maxRecursionLevel).fill(false);
                                }
                                attrNode.selectedInternal[level - 1] = isSelected;
                            });
                        });
                    }

                    const subContext = Object.assign({}, context);
                    subContext.selectedInternalLevel++;

                    if (subContext.selectedInternalLevel > maxRecursionLevel) {
                        let attrStr = attributes.map(attribute => attribute.join('.')).join(',');
                        throw new ImplementationError(
                            `item-extension/buildItem: Recursion depth for "${attrStr}" too big`
                        );
                    }

                    selectInternal(subContext.selectedInternalLevel, true);
                    const internalItem = buildItem(parentAttrNode, row, subContext);
                    selectInternal(subContext.selectedInternalLevel, false);

                    return internalItem;
                }
            });
        }
    }

    context.primaryKey = null; // clear primaryKey cache for next row

    return item;
}
830603
def initialize_object(B, res, row):
    
    B = get_backend()
    field_groups = FieldGroups(B.get_concrete(res))

    try:
        obj = B.get_object(B.get_concrete(res), row['id'])
    except B.object_missing_error(B.get_concrete(res)):
        tbl = B.get_concrete(res)
        obj = tbl()

    # Set attributes, refs
    for fname, field in field_groups['scalars'].items():
        value = row.get(fname, getattr(obj, fname, None))
        value = B.convert_field(obj.__class__, fname, value)
        setattr(obj, fname, value)
    # _debug('res, row: %s, %s', res, row)

    # Already-fetched, and id-only refs
    fetched, dangling = defaultdict(dict), defaultdict(set)

    # To handle subrows that might be shallow (id) or deep (dict)
    def _handle_subrow(R, subrow):
        if isinstance(subrow, dict):
            pk = subrow['id']
            fetched[R][pk] = subrow
        else:
            pk = subrow
            dangling[R].add(pk)
        return pk

    for fname, field in field_groups['one_refs'].items():
        fieldres = _field_resource(B, B.get_concrete(res), fname)
        key = field.column
        subrow = row.get(key)
        if subrow is None:  # e.g. use "org" if "org_id" is missing
            key = fname
            subrow = row[key]
        pk = _handle_subrow(fieldres, subrow)
        setattr(obj, key, pk)

    for fname, field in field_groups['many_refs'].items():
        fieldres = _field_resource(B, B.get_concrete(res), fname)
        pks = [
            _handle_subrow(fieldres, subrow) for subrow in row.get(fname, [])
        ]

    return obj, fetched, dangling
1252258
function ResultSet(metadata, rows) {
  this.rows = [];
  this.metadata = metadata;
  for (var i = 0; i < rows.length; i++) {
    this.rows.push(new Row(metadata.columnSpecs, rows[i]));
  }
}
25655
def _get_meta(self, row, col):
        
        if self.meta is None:
            logging.error("unable to get meta: empty section")
            return {}

        if not row in self._get_row_hdrs() or\
            not col in self._get_col_hdrs():
            logging.error("unable to get meta: cell [%s,%s] does not exist"
                          % (row, col))
            return {}

        meta_str = self.meta[col][self.irt[row]]
        try:
            meta = ast.literal_eval(meta_str)
            if isinstance(meta, dict):
                return meta
        except (SyntaxError, ValueError), e:
            logging.error("unable to parse meta string - %s: %s"
                          % (meta_str, e))

        return {}
1065892
private function enhanceRowEvolutionMetaData(&$metadata, $dataTable)
    {
        // prepare result array for metrics
        $metricsResult = array();
        foreach ($metadata['metrics'] as $metric => $name) {
            $metricsResult[$metric] = array('name' => $name);

            if (!empty($metadata['logos'][$metric])) {
                $metricsResult[$metric]['logo'] = $metadata['logos'][$metric];
            }
        }
        unset($metadata['logos']);

        $subDataTables = $dataTable->getDataTables();
        if (empty($subDataTables)) {
            throw new \Exception("Unexpected state: row evolution API call returned empty DataTable\\Map.");
        }

        $firstDataTable = reset($subDataTables);
        $this->checkDataTableInstance($firstDataTable);
        $firstDataTableRow = $firstDataTable->getFirstRow();

        $lastDataTable = end($subDataTables);
        $this->checkDataTableInstance($lastDataTable);
        $lastDataTableRow = $lastDataTable->getFirstRow();

        // Process min/max values
        $firstNonZeroFound = array();
        foreach ($subDataTables as $subDataTable) {
            // $subDataTable is the report for one period, it has only one row
            $firstRow = $subDataTable->getFirstRow();
            foreach ($metadata['metrics'] as $metric => $label) {
                $value = $firstRow ? floatval($firstRow->getColumn($metric)) : 0;
                if ($value > 0) {
                    $firstNonZeroFound[$metric] = true;
                } else if (!isset($firstNonZeroFound[$metric])) {
                    continue;
                }
                if (!isset($metricsResult[$metric]['min'])
                    || $metricsResult[$metric]['min'] > $value
                ) {
                    $metricsResult[$metric]['min'] = $value;
                }
                if (!isset($metricsResult[$metric]['max'])
                    || $metricsResult[$metric]['max'] < $value
                ) {
                    $metricsResult[$metric]['max'] = $value;
                }
            }
        }

        // Process % change between first/last values
        foreach ($metadata['metrics'] as $metric => $label) {
            $first = $firstDataTableRow ? floatval($firstDataTableRow->getColumn($metric)) : 0;
            $last = $lastDataTableRow ? floatval($lastDataTableRow->getColumn($metric)) : 0;

            // do not calculate evolution if the first value is 0 (to avoid divide-by-zero)
            if ($first == 0) {
                continue;
            }

            $change = CalculateEvolutionFilter::calculate($last, $first, $quotientPrecision = 0);
            $change = CalculateEvolutionFilter::prependPlusSignToNumber($change);
            $metricsResult[$metric]['change'] = $change;
        }

        $metadata['metrics'] = $metricsResult;
    }
753497
@Override
  public <T> CpoClass getMetaClass(T obj) throws CpoException {
    CpoClass cpoClass = null;
    String className;
    String requestedName;
    List<Class<?>> classList = new ArrayList<>();
    Class<?> requestedClass;

    if (obj != null) {
      requestedClass = obj.getClass();
      classList.add(requestedClass);
      requestedName = requestedClass.getName();
      className = requestedName;
      cpoClass = classMap.get(className);

      while (cpoClass == null && !classList.isEmpty()) {
        classList = getSuperClasses(classList);
        for (Class<?> clazz : classList) {
          className = clazz.getName();
          cpoClass = classMap.get(className);
          if (cpoClass != null)
            break;
        }
      }
      if (cpoClass == null) {
        throw new CpoException("No Metadata found for class:" + requestedName);
      }
    }

    return cpoClass;
  }
549173
private static ClassMetadata getClassMetadata(final Class cls, final Map /* <Class,ClassMetadata> */metadataMap,
                                                  final ClassAccessPrivilegedAction caAction,
                                                  final FieldAccessPrivilegedAction faAction) {
        if (null == cls) {
            return null;
        }

        ClassMetadata result;
        synchronized (metadataMap) {
            result = (ClassMetadata) metadataMap.get(cls);
        }
        if (result != null) {
            return result;
        }

        int primitiveFieldCount = 0;
        int shellSize = OBJECT_SHELL_SIZE; // java.lang.Object shell
        final List /* Field */refFields = new LinkedList();

        final Field[] declaredFields;
        try {
            caAction.setContext(cls);
            declaredFields = (Field[]) AccessController.doPrivileged(caAction);
        } catch (PrivilegedActionException pae) {
            throw new RuntimeException("could not access declared fields of class " + cls.getName() + ": "
                                       + pae.getException());
        }

        for (int f = 0; f < declaredFields.length; ++f) {
            final Field field = declaredFields[f];
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            /*
             * Can't do that: HashMap data is transient, for example... if (Modifier.isTransient(field.getModifiers()))
             * { shellSize += OBJREF_SIZE; continue; }
             */

            final Class fieldType = field.getType();
            if (fieldType.isPrimitive()) {
                // memory alignment ignored:
                shellSize += sizeofPrimitiveType(fieldType);
                ++primitiveFieldCount;
            } else {
                // prepare for graph traversal later:
                if (!field.isAccessible()) {
                    try {
                        faAction.setContext(field);
                        AccessController.doPrivileged(faAction);
                    } catch (PrivilegedActionException pae) {
                        throw new RuntimeException("could not make field " + field + " accessible: "
                                                   + pae.getException());
                    }
                }

                // memory alignment ignored:
                shellSize += OBJREF_SIZE;
                refFields.add(field);
            }
        }

        // recurse into superclass:
        final ClassMetadata superMetadata = getClassMetadata(cls.getSuperclass(), metadataMap, caAction, faAction);
        if (superMetadata != null) {
            primitiveFieldCount += superMetadata.m_primitiveFieldCount;
            shellSize += superMetadata.m_shellSize - OBJECT_SHELL_SIZE;
            refFields.addAll(Arrays.asList(superMetadata.m_refFields));
        }

        final Field[] _refFields = new Field[refFields.size()];
        refFields.toArray(_refFields);

        result = new ClassMetadata(primitiveFieldCount, shellSize, _refFields);
        synchronized (metadataMap) {
            metadataMap.put(cls, result);
        }

        return result;
    }
748875
def get_or_create_party(self, row):
        
        if row["party"] in ["Dem", "GOP"]:
            aggregable = False
        else:
            aggregable = True

        defaults = {"label": row["party"], "aggregate_candidates": aggregable}

        party, created = government.Party.objects.get_or_create(
            ap_code=row["party"], defaults=defaults
        )

        return party
728013
@Nullable
	public <T> T getMeta(Class<?> metaType) {
		if (meta != null && deserializer != null) {
			return (T) deserializer.convertValue(meta, metaType);
		}

		return null;
	}
776790
private function buildBodyRowAttr($entity, Metadata $meta)
    {
        $attr = [];

        foreach ($meta->getConfiguration()['index_view_row_attr'] as $property) {
            $attr['data-'.$property] = $this->propertyAccessor->getValue($entity, $property);
        }

        return $attr;
    }
484120
private ResultSetMetaData getMetaData() {

        if (metadata == null) {
            try {
                metadata = resultSet.getMetaData();
            } catch (SQLException e) {
                throw new FacesException(e);
            }
        }
        return (metadata);

    }
725599
function getMeta(key) {
  return baseQuery(key)
    .select('meta')
    .where('id', key)
    .then(pullValFromRows(key, 'meta'));
}
994853
private void populatePartialRow(PartialRow row, EntityMetadata entityMetadata, Object entity)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(entityMetadata.getPersistenceUnit());
        Class entityClazz = entityMetadata.getEntityClazz();
        EntityType entityType = metaModel.entity(entityClazz);
        Set<Attribute> attributes = entityType.getAttributes();
        Iterator<Attribute> iterator = attributes.iterator();
        iterateAndPopulateRow(row, entity, metaModel, iterator);
    }
1018334
private void returnMetadata(Buffer buffer) {
        Callback<SketchMetadata> callback = getFirstCallback(BeanMessageID.BL_GET_META);
        if (callback != null) {
            callback.onResult(SketchMetadata.fromPayload(buffer));
        }
    }
529298
public <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, DataRow<SuperColumn> tr) throws Exception
    {

        // Instantiate a new instance
        E e = null;

        // Set row-key. Note:

        // Get a name->field map for super-columns
        Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
        Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();
        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap, superColumnNameToFieldMap,
                kunderaMetadata);

        Collection embeddedCollection = null;
        Field embeddedCollectionField = null;
        for (SuperColumn sc : tr.getColumns())
        {
            if (e == null)
            {
                // Instantiate a new instance
                e = clazz.newInstance();

                // Set row-key.
                PropertyAccessorHelper.setId(e, m, tr.getId());
            }

            String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, sc.getName());
            String scNamePrefix = null;

            if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)
            {
                scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);
                embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);
                embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);
                Object embeddedObject = populateEmbeddedObject(sc, m);
                embeddedCollection.add(embeddedObject);
                PropertyAccessorHelper.set(e, embeddedCollectionField, embeddedCollection);
            }
            else
            {
                boolean intoRelations = false;
                if (scName.equals(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME))
                {
                    intoRelations = true;
                }

                for (Column column : sc.getColumns())
                {
                    if (column != null)
                    {
                        String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
                        byte[] value = column.getValue();

                        if (value == null)
                        {
                            continue;
                        }

                        if (intoRelations)
                        {
                            String foreignKeys = PropertyAccessorFactory.STRING.fromBytes(String.class, value);
                            Set<String> keys = MetadataUtils.deserializeKeys(foreignKeys);
                        }
                        else
                        {
                            // set value of the field in the bean
                            Field field = columnNameToFieldMap.get(name);
                            Object embeddedObject = PropertyAccessorHelper.getObject(e, scName);
                            PropertyAccessorHelper.set(embeddedObject, field, value);
                        }
                    }
                }
            }
        }

        if (log.isInfoEnabled())
        {
            log.info("Returning entity {} for class {}", e, clazz);
        }
        return e;
    }