Compute entity via columns.

@param m
the m
@param isRelation
the is relation
@param relations
the relations
@param entities
the entities
@param qResults
the q results
769770
protected void computeEntityViaColumns(EntityMetadata m, boolean isRelation, List<String> relations,
        List<Object> entities, Map<ByteBuffer, List<Column>> qResults) {
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());

        EntityType entityType = metaModel.entity(m.getEntityClazz());

        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

        for (ByteBuffer key : qResults.keySet()) {
            onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key);
        }
    }
768217
private void addRelationName(Relation rField)
    {
        if (rField != null && !rField.isRelatedViaJoinTable())
        {
            String relationName = getJoinColumnName(rField.getProperty());
            if (rField.getProperty().isAnnotationPresent(PrimaryKeyJoinColumn.class))
            {
                relationName = this.getIdAttribute().getName();
            }

            addToRelationNameCollection(relationName);
        }
    }
1209582
private void addJoinTable(List<Relation> relations)
    {
        for (Relation relation : relations)
        {
            if (relation.getType().equals(ForeignKey.MANY_TO_MANY) && relation.isRelatedViaJoinTable())
            {
                String joinTableName = relation.getJoinTableMetadata().getJoinTableName();
                String hTableName = HBaseUtils.getHTableName(databaseName, joinTableName);
                HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(hTableName));
                tableDescriptor.addFamily(new HColumnDescriptor(joinTableName));
                createOrUpdateTable(hTableName, tableDescriptor);
            }
        }
    }
1136374
protected function eagerLoadRelations(array $entities)
    {
        if (empty($entities)) {
            return;
        }

        if ($this->class === null) {
            throw new LogicException('A class must be specified for Eager Loading using the `asClass` method.');
        }

        foreach ($this->with as $method) {
            $relation = $this->getRelation($entities[0], $method);
            $relation->addEagerConstraints($entities);
            $relationEntities = $relation->getEager();
            /** @var Model $entity */
            foreach ($entities as $entity) {
                $id = $entity->getId();
                $entity->setRelationEntities($method, isset($relationEntities[$id]) ? $relationEntities[$id] : null);
            }
        }
    }
548537
private static void getForeignKeys(DatabaseMetaData md, DatabaseRelationDefinition relation, DBMetadata metadata) throws SQLException {

		QuotedIDFactory idfac = metadata.getQuotedIDFactory();

		RelationID relationId = relation.getID();
		try (ResultSet rs = md.getImportedKeys(null, relationId.getSchemaName(), relationId.getTableName())) {
            extractForeignKeys(relation, metadata, idfac, rs);
        }
        catch (Exception ex) {
            try (ResultSet rs = md.getImportedKeys(relationId.getSchemaName(),null, relationId.getTableName())) {
                extractForeignKeys(relation, metadata, idfac, rs);
            }
        }
	}
860369
private List populateData(EntityMetadata m, List<KeySlice> keySlices, List<Object> entities, boolean isRelational,
            List<String> relationNames)
    {
        try
        {
            if (m.getType().isSuperColumnFamilyMetadata())
            {
                List<Object> rowKeys = ThriftDataResultHelper.getRowKeys(keySlices, m);

                Object[] rowIds = rowKeys.toArray();
                entities.addAll(findAll(m.getEntityClazz(), null, rowIds));
            }
            else
            {
                for (KeySlice keySlice : keySlices)
                {
                    byte[] key = keySlice.getKey();
                    List<ColumnOrSuperColumn> coscList = keySlice.getColumns();

                    List<Column> columns = ThriftDataResultHelper.transformThriftResult(coscList,
                            ColumnFamilyType.COLUMN, null);
                    Object e = null;
                    Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);
                    e = dataHandler.populateEntity(new ThriftRow(id, m.getTableName(), columns,
                            new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),
                            new ArrayList<CounterSuperColumn>(0)), m, KunderaCoreUtils.getEntity(e), relationNames,
                            isRelational);
                    entities.add(e);
                }
            }
        }
        catch (Exception e)
        {

            log.error("Error while populating data for relations of column family {}, Caused by: .", m.getTableName(),
                    e);
            throw new KunderaException(e);
        }
        return entities;
    }
1360165
protected void importRelations() {

        if (m_importedRelations.isEmpty()) {
            return;
        }

        m_report.println(Messages.get().container(Messages.RPT_START_IMPORT_RELATIONS_0), I_CmsReport.FORMAT_HEADLINE);

        int i = 0;
        Iterator<Entry<String, List<CmsRelation>>> it = m_importedRelations.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, List<CmsRelation>> entry = it.next();
            String resourcePath = entry.getKey();
            List<CmsRelation> relations = entry.getValue();

            m_report.print(
                org.opencms.report.Messages.get().container(
                    org.opencms.report.Messages.RPT_SUCCESSION_2,
                    String.valueOf(i + 1),
                    String.valueOf(m_importedRelations.size())),
                I_CmsReport.FORMAT_NOTE);

            m_report.print(
                Messages.get().container(
                    Messages.RPT_IMPORTING_RELATIONS_FOR_2,
                    resourcePath,
                    new Integer(relations.size())),
                I_CmsReport.FORMAT_NOTE);
            m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

            boolean withErrors = false;
            Iterator<CmsRelation> itRelations = relations.iterator();
            while (itRelations.hasNext()) {
                CmsRelation relation = itRelations.next();
                try {
                    // Add the relation to the resource
                    m_cms.importRelation(
                        m_cms.getSitePath(relation.getSource(m_cms, CmsResourceFilter.ALL)),
                        m_cms.getSitePath(relation.getTarget(m_cms, CmsResourceFilter.ALL)),
                        relation.getType().getName());
                } catch (CmsException e) {
                    m_report.addWarning(e);
                    withErrors = true;
                    if (LOG.isWarnEnabled()) {
                        LOG.warn(e.getLocalizedMessage());
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
            if (!withErrors) {
                m_report.println(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                    I_CmsReport.FORMAT_OK);
            } else {
                m_report.println(
                    org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_FAILED_0),
                    I_CmsReport.FORMAT_ERROR);
            }
            i++;
        }

        m_report.println(Messages.get().container(Messages.RPT_END_IMPORT_RELATIONS_0), I_CmsReport.FORMAT_HEADLINE);
    }
649058
@Override
    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        // required in case of associated entities.
        List ls = onQuery(m, client);
        return setRelationEntities(ls, client, m);
    }
763808
@Override
	public void cacheResult(
		List<CommerceDiscountUserSegmentRel> commerceDiscountUserSegmentRels) {
		for (CommerceDiscountUserSegmentRel commerceDiscountUserSegmentRel : commerceDiscountUserSegmentRels) {
			if (entityCache.getResult(
						CommerceDiscountUserSegmentRelModelImpl.ENTITY_CACHE_ENABLED,
						CommerceDiscountUserSegmentRelImpl.class,
						commerceDiscountUserSegmentRel.getPrimaryKey()) == null) {
				cacheResult(commerceDiscountUserSegmentRel);
			}
			else {
				commerceDiscountUserSegmentRel.resetOriginalValues();
			}
		}
	}
315744
public void setEntities(java.util.Collection<InventoryResultEntity> entities) {
        if (entities == null) {
            this.entities = null;
            return;
        }

        this.entities = new com.amazonaws.internal.SdkInternalList<InventoryResultEntity>(entities);
    }
122477
protected function cacheRelation($results, $relation)
    {
        $cache = $this->parentMapper->getEntityCache();

        $cache->cacheLoadedRelationResult($this->parent->getEntityKeyName(), $relation, $results, $this);
    }
664623
protected void computePDists(Relation<O> relation, KNNQuery<O> knn, WritableDoubleDataStore pdists) {
    // computing PRDs
    FiniteProgress prdsProgress = LOG.isVerbose() ? new FiniteProgress("pdists", relation.size(), LOG) : null;
    for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
      final KNNList neighbors = knn.getKNNForDBID(iditer, kreach + 1); // +
                                                                       // query
                                                                       // point
      // use first kref neighbors as reference set
      int ks = 0;
      double ssum = 0.;
      for(DoubleDBIDListIter neighbor = neighbors.iter(); neighbor.valid() && ks < kreach; neighbor.advance()) {
        if(DBIDUtil.equal(neighbor, iditer)) {
          continue;
        }
        final double d = neighbor.doubleValue();
        ssum += d * d;
        ks++;
      }
      double pdist = ks > 0 ? FastMath.sqrt(ssum / ks) : 0.;
      pdists.putDouble(iditer, pdist);
      LOG.incrementProcessed(prdsProgress);
    }
    LOG.ensureCompleted(prdsProgress);
  }
1208603
@Override
    public List find(List<IndexClause> ixClause, EntityMetadata m, boolean isRelation, List<String> relations,
            int maxResult, List<String> columns)
    {
        Selector selector = clientFactory.getSelector(pool);

        SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, Integer.MAX_VALUE);
        if (columns != null && !columns.isEmpty())
        {
            slicePredicate = Selector.newColumnsPredicate(columns.toArray(new String[] {}));
        }

        List<Object> entities = new ArrayList<Object>();
        if (ixClause.isEmpty())
        {
            if (m.isCounterColumnType())
            {
                try
                {
                    IPooledConnection connection = getConnection();
                    org.apache.cassandra.thrift.Cassandra.Client thriftClient = connection.getAPI();
                    List<KeySlice> ks = thriftClient.get_range_slices(new ColumnParent(m.getTableName()),
                            slicePredicate, Selector.newKeyRange("", "", maxResult), getConsistencyLevel());
                    connection.release();
                    entities = onCounterColumn(m, isRelation, relations, ks);
                }
                catch (InvalidRequestException irex)
                {
                    log.error("Error during executing find, Caused by: .", irex);
                    throw new PersistenceException(irex);
                }
                catch (UnavailableException uex)
                {
                    log.error("Error during executing find, Caused by: .", uex);
                    throw new PersistenceException(uex);
                }
                catch (TimedOutException tex)
                {
                    log.error("Error during executing find, Caused by: .", tex);
                    throw new PersistenceException(tex);
                }
                catch (TException tex)
                {
                    log.error("Error during executing find, Caused by: .", tex);
                    throw new PersistenceException(tex);
                }
            }
            else
            {
                if (m.getType().isSuperColumnFamilyMetadata())
                {
                    Map<Bytes, List<SuperColumn>> qResults = selector.getSuperColumnsFromRows(m.getTableName(),
                            selector.newKeyRange("", "", maxResult), slicePredicate, getConsistencyLevel());
                    entities = new ArrayList<Object>(qResults.size());

                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                            m.getPersistenceUnit());

                    EntityType entityType = metaModel.entity(m.getEntityClazz());

                    List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

                    for (Bytes key : qResults.keySet())
                    {
                        onSuperColumn(m, isRelation, relations, entities, qResults.get(key), key.getBytes());
                    }
                }
                else
                {
                    Map<Bytes, List<Column>> qResults = selector.getColumnsFromRows(m.getTableName(),
                            selector.newKeyRange("", "", maxResult), slicePredicate, getConsistencyLevel());
                    entities = new ArrayList<Object>(qResults.size());
                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                            m.getPersistenceUnit());

                    EntityType entityType = metaModel.entity(m.getEntityClazz());

                    List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();
                    for (Bytes key : qResults.keySet())
                    {
                        onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key.getBytes());
                    }
                }

            }
        }
        else
        {
            entities = new ArrayList<Object>();
            for (IndexClause ix : ixClause)
            {
                Map<Bytes, List<Column>> qResults = selector.getIndexedColumns(m.getTableName(), ix, slicePredicate,
                        getConsistencyLevel());

                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                        m.getPersistenceUnit());

                EntityType entityType = metaModel.entity(m.getEntityClazz());

                List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

                for (Bytes key : qResults.keySet())
                {
                    onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key.getBytes());
                }
            }
        }
        return entities;
    }
953487
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class clazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);
        List<Object> entities = null;
        if (isCql3Enabled(m))
        {
            entities = findByRelationQuery(m, colName, colValue, clazz, dataHandler);
        }
        else
        {
            Selector selector = clientFactory.getSelector(pool);
            SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, 10000);
            IndexClause ix = Selector.newIndexClause(
                    Bytes.EMPTY,
                    10000,
                    Selector.newIndexExpression(colName, IndexOperator.EQ,
                            Bytes.fromByteArray(PropertyAccessorHelper.getBytes(colValue))));
            Map<Bytes, List<Column>> qResults;
            try
            {
                qResults = selector.getIndexedColumns(m.getTableName(), ix, slicePredicate, getConsistencyLevel());
            }
            catch (PelopsException e)
            {
                log.warn("Error while retrieving entities for given column {} for class {}.", colName, clazz);
                return entities;
            }
            entities = new ArrayList<Object>(qResults.size());
            // iterate through complete map and populateData
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());

            EntityType entityType = metaModel.entity(m.getEntityClazz());

            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

            if (subManagedType.isEmpty())
            {
                entities = populateData(m, qResults, entities, false, m.getRelationNames(), dataHandler);
            }
            else
            {
                for (AbstractManagedType subEntity : subManagedType)
                {
                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            subEntity.getJavaType());
                    entities = populateData(subEntityMetadata, qResults, entities, false,
                            subEntityMetadata.getRelationNames(), dataHandler);
                }
            }

        }
        return entities;
    }
40890
public CollectionResult<double[]> run(Database database, Relation<O> relation, Relation<?> lrelation) {
    final DistanceQuery<O> distQuery = database.getDistanceQuery(relation, getDistanceFunction());
    final int qk = k + (includeSelf ? 0 : 1);
    final KNNQuery<O> knnQuery = database.getKNNQuery(distQuery, qk);

    MeanVarianceMinMax[] mvs = MeanVarianceMinMax.newArray(k);

    final DBIDs ids = DBIDUtil.randomSample(relation.getDBIDs(), sampling, random);

    FiniteProgress objloop = LOG.isVerbose() ? new FiniteProgress("Computing nearest neighbors", ids.size(), LOG) : null;
    // sort neighbors
    for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
      KNNList knn = knnQuery.getKNNForDBID(iter, qk);
      Object label = lrelation.get(iter);

      int positive = 0, i = 0;
      for(DBIDIter ri = knn.iter(); i < k && ri.valid(); ri.advance()) {
        if(!includeSelf && DBIDUtil.equal(iter, ri)) {
          // Do not increment i.
          continue;
        }
        positive += match(label, lrelation.get(ri)) ? 1 : 0;
        final double precision = positive / (double) (i + 1);
        mvs[i].put(precision);
        i++;
      }
      LOG.incrementProcessed(objloop);
    }
    LOG.ensureCompleted(objloop);

    // Transform Histogram into a Double Vector array.
    Collection<double[]> res = new ArrayList<>(k);
    for(int i = 0; i < k; i++) {
      final MeanVarianceMinMax mv = mvs[i];
      final double std = mv.getCount() > 1. ? mv.getSampleStddev() : 0.;
      res.add(new double[] { i + 1, mv.getMean(), std, mv.getMin(), mv.getMax(), mv.getCount() });
    }
    return new CollectionResult<>("Average Precision", "average-precision", res);
  }
44723
public static double[][] relationAsMatrix(final Relation<? extends NumberVector> relation, ArrayDBIDs ids) {
    final int rowdim = ids.size();
    final int coldim = dimensionality(relation);
    double[][] mat = new double[rowdim][coldim];
    int r = 0;
    for(DBIDArrayIter iter = ids.iter(); iter.valid(); iter.advance(), r++) {
      NumberVector vec = relation.get(iter);
      double[] row = mat[r];
      for(int c = 0; c < coldim; c++) {
        row[c] = vec.doubleValue(c);
      }
    }
    assert (r == rowdim);
    return mat;
  }
928754
private void setRelationToEntity(Object entity, Object relationEntity, Relation relation)
    {
        if (relation.getTargetEntity().isAssignableFrom(getEntity(relationEntity).getClass()))
        {

            if (relation.isUnary())
            {
                PropertyAccessorHelper.set(entity, relation.getProperty(), getEntity(relationEntity));
            }
            else
            {
                Object associationObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());
                if (associationObject == null || ProxyHelper.isProxyOrCollection(associationObject))
                {
                    associationObject = PropertyAccessorHelper.getCollectionInstance(relation.getProperty());
                    PropertyAccessorHelper.set(entity, relation.getProperty(), associationObject);
                }

                ((Collection) associationObject).add(getEntity(relationEntity));
            }
        }
    }