Minimizing of joins.
        Left/right and inner join of the same condition is only inner join.
542867
def _minimize_joins(self):
        
        joins_group = []
        for join in self._joins:
            append_new = True
            for join_group in joins_group:
                if join_group[0]['table'] == join['table'] and join_group[0]['ons'] == join['ons']:
                    join_group.append(join)
                    append_new = False
                    break
            if append_new:
                joins_group.append([join])

        self._joins = []
        for joins in joins_group:
            if len(joins) > 1 and any(bool(join['type'] == INNER_JOIN) for join in joins):
                joins[0]['type'] = INNER_JOIN
                self._joins.append(joins[0])
            elif len(joins) > 1 and all(join['type'] == joins[0]['type'] for join in joins):
                self._joins.append(joins[0])
            else:
                self._joins.extend(joins)
90651
private LeftJoinNode updateRightNodesAndLJ(LeftJoinNode leftJoinNode,
                                               DataNodeAndSubstitution rightComponent,
                                               Optional<ImmutableExpression> newLJCondition,
                                               Optional<DataNode> proposedRightDataNode,
                                               QueryTreeComponent treeComponent) {
        rightComponent.constructionNode
                .ifPresent(n -> treeComponent.replaceNodeByChild(n, Optional.empty()));
        rightComponent.filterNode
                .ifPresent(n -> treeComponent.replaceNodeByChild(n, Optional.empty()));
        proposedRightDataNode
                .ifPresent(n -> treeComponent.replaceNode(rightComponent.dataNode, n));
        LeftJoinNode newLeftJoinNode = leftJoinNode.changeOptionalFilterCondition(newLJCondition);
        treeComponent.replaceNode(leftJoinNode, newLeftJoinNode);

        return newLeftJoinNode;
    }
661377
private String constructDuplicatePathSql(SqlgGraph sqlgGraph, List<LinkedList<SchemaTableTree>> subQueryLinkedLists, Set<SchemaTableTree> leftJoinOn) {
        StringBuilder singlePathSql = new StringBuilder("\nFROM (");
        int count = 1;
        SchemaTableTree lastOfPrevious = null;
        for (LinkedList<SchemaTableTree> subQueryLinkedList : subQueryLinkedLists) {
            SchemaTableTree firstOfNext = null;
            boolean last = count == subQueryLinkedLists.size();
            if (!last) {
                //this is to get the next SchemaTable to join to
                LinkedList<SchemaTableTree> nextList = subQueryLinkedLists.get(count);
                firstOfNext = nextList.getFirst();
            }
            SchemaTableTree firstSchemaTableTree = subQueryLinkedList.getFirst();

            String sql;
            if (last) {
                //only the last step must have dropStep as true. As only the outer select needs only an ID in the select
                sql = constructSinglePathSql(sqlgGraph, true, subQueryLinkedList, lastOfPrevious, null, leftJoinOn, false);
            } else {
                sql = constructSinglePathSql(sqlgGraph, true, subQueryLinkedList, lastOfPrevious, firstOfNext);
            }
            singlePathSql.append(sql);
            if (count == 1) {
                singlePathSql.append("\n) a").append(count++).append(" INNER JOIN (");
            } else {
                //join the last with the first
                singlePathSql.append("\n) a").append(count).append(" ON ");
                singlePathSql.append(constructSectionedJoin(sqlgGraph, lastOfPrevious, firstSchemaTableTree, count));
                if (count++ < subQueryLinkedLists.size()) {
                    singlePathSql.append(" INNER JOIN (");
                }
            }
            lastOfPrevious = subQueryLinkedList.getLast();
        }
        singlePathSql.append(constructOuterOrderByClause(sqlgGraph, subQueryLinkedLists));
        String result = "SELECT\n\t" + constructOuterFromClause(subQueryLinkedLists);
        return result + singlePathSql;
    }
232530
public JoinDescription nested(JoinDescription... joins) {
        for (JoinDescription join : joins) {
            join.parent = this;
            join.alias(J.path(this.getAlias(), join.getOriginalAlias()));
            addJoin(join);

            reAliasChildren(join);
        }

        return this;
    }
822583
def _set_join(self, query=None):
        
        if not query:
            query = self._query

        base_table = self._related.get_table()

        key = '%s.%s' % (base_table, self._related.get_key_name())

        query.join(self._table, key, '=', self.get_other_key())

        return self
264798
def left_joins(*args)
			return self if args.compact.blank?

			relation = clone

			args.flatten!

			#	args could be just a single symbol
			#		...could be an array of symbols (
			#		...could be a hash (joins(:address => :address_type))
			#		...could be a string (SQL)

			#	here I really am just expecting an array of model names as a symbols

			#	this only works if the primary and foreign keys are conventional

			#	@klass (or its reader klass() ) is the calling class (Organization)
			#	@table (or its reader table() ) is the calling class's Arel::Table


#	StudySubject
# scope :join_patients, joins(
#   Arel::Nodes::OuterJoin.new(Patient.arel_table,Arel::Nodes::On.new(
#     self.arel_table[:id].eq(Patient.arel_table[:study_subject_id]))))
# scope :join_patients, left_joins(:patient)	#	WORKS

#	Organization
# scope :without_sample_location, joins(
#   Arel::Nodes::OuterJoin.new(
#     SampleLocation.arel_table,Arel::Nodes::On.new(
#       self.arel_table[:id].eq(SampleLocation.arel_table[:organization_id]))))
# scope :without_sample_location, left_joins(:sample_location)	#	WORKS
#
#	Organization has one Sample Location

# scope :without_hospital, joins(
#   Arel::Nodes::OuterJoin.new(
#     Hospital.arel_table,Arel::Nodes::On.new(
#       self.arel_table[:id].eq(Hospital.arel_table[:organization_id]))))
# scope :without_hospital, left_joins(:hospital)	#	WORKS

#	Organization has one Hospital


#		@zip_codes = ZipCode.joins(
#			Arel::Nodes::OuterJoin.new(County.arel_table,Arel::Nodes::On.new(
#				ZipCode.arel_table[:county_id].eq(County.arel_table[:id]))))
#
#		@zip_codes = ZipCode.left_joins(:county) #??? backwards? won't work?

#	ZipCode belongs to County



#	doesn't work on has_one or has_many ... :through


			args.each do |arg|	#	no, I'm not a pirate
				reflection = klass.reflections[arg]
				joining_model = reflection.klass
#
#	:has_one and probably :has_many	( BUT NOT :belongs_to )
#
				relation.joins_values += [
					Arel::Nodes::OuterJoin.new(
						joining_model.arel_table,
( reflection.macro == :belongs_to ) ?
						Arel::Nodes::On.new(
							table[ reflection.foreign_key ].eq(
#								joining_model.arel_table[ :id ]
								joining_model.arel_table[ reflection.options[:primary_key] || :id ]
							)
						) :
						Arel::Nodes::On.new(
							table[:id].eq(		#	won't ALWAYS be :id
								joining_model.arel_table[ reflection.foreign_key ]
							)
						)

					)
				]




			end	#	args.each do |arg|	#	no, I'm not a pirate

			relation
		end
1212474
private NodeCentricOptimizationResults<InnerJoinNode> applyOptimization(IntermediateQuery query,
                                                                                     QueryTreeComponent treeComponent,
                                                                                     InnerJoinNode topJoinNode,
                                                                                     ConcreteProposal proposal)
            throws EmptyQueryException {
        /*
         * First, add and remove non-top nodes
         */
        proposal.getDataNodesToRemove()
                .forEach(treeComponent::removeSubTree);

        return updateJoinNodeAndPropagateSubstitution(query, treeComponent, topJoinNode, proposal);
    }
545773
function _join() {
    var sql = '',
        i = -1,
        joins = this.grouped.join;
    if (!joins) {
      return '';
    }
    while (++i < joins.length) {
      var join = joins[i];
      if (i > 0) {
        sql += ' ';
      }
      if (join.joinType === 'raw') {
        sql += this.formatter.unwrapRaw(join.table);
      } else {
        sql += join.joinType + ' join ' + this.formatter.wrap(join.table);
        var ii = -1;
        while (++ii < join.clauses.length) {
          var clause = join.clauses[ii];
          sql += ' ' + (ii > 0 ? clause[0] : clause[1]) + ' ';
          sql += this.formatter.wrap(clause[2]);
          if (clause[3]) {
            sql += ' ' + this.formatter.operator(clause[3]);
          }
          if (clause[4]) {
            sql += ' ' + this.formatter.wrap(clause[4]);
          }
        }
      }
    }
    return sql;
  }
1115492
private DataContainer innerJoin(DataContainer left, DataContainer right, Optional<BooleanExpression> joinCondition) {
        return crossJoin(left, right, joinCondition, JoinType.INNER);
    }
550859
private DataContainer crossJoin(DataContainer left, DataContainer right, Optional<BooleanExpression> joinCondition, JoinType joinType) {
        final List<DataRow> leftRows = left.getRows();
        final List<DataRow> rightRows = right.getRows();
        final Set<Integer> matchedIndexes = new HashSet<>();

        boolean isLeftJoin = joinType == JoinType.LEFT;
        boolean isRightJoin = joinType == JoinType.RIGHT;
        int leftColumnsCount = left.getColumnNames().size();
        int rightColumnsCount = right.getColumnNames().size();

        DataContainer dataContainer = mergeContainerColumns(left, right);
        crossProduct(leftRows, rightRows, DataRow::getValues, (indexesPair, newRowValues) -> {
            DataRow dataRow = new DataRow(dataContainer, newRowValues);
            if (!joinCondition.isPresent() || expressionEvaluator.evaluateAs(joinCondition.get(), dataRow, Boolean.class)) {
                dataContainer.addRow(dataRow);
                if (isLeftJoin) {
                    matchedIndexes.add(indexesPair.getFirst());
                }
                if (isRightJoin) {
                    matchedIndexes.add(indexesPair.getSecond());
                }
            }
        });

        if (isLeftJoin || isRightJoin) {
            int rowsCount = isLeftJoin ? leftRows.size() : rightRows.size();
            for (int i = 0; i <= rowsCount - 1; i++) {
                if (!matchedIndexes.contains(i)) {
                    DataRow rowWithNulls = new DataRow(
                            dataContainer,
                            rowWithNullsValues(leftRows, leftColumnsCount, rightRows, rightColumnsCount, i, isLeftJoin)
                    );
                    dataContainer.addRow(rowWithNulls);
                }
            }
        }
        return dataContainer;
    }
1157084
@SuppressWarnings("unchecked")
    protected boolean join(int i, int j) {
        if (((Comparable<? super K>) array[j]).compareTo(array[i]) < 0) {
            K tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
            reverse.flip(j);
            return false;
        }
        return true;
    }
986725
private boolean kNNABOD(Database db, Relation<V> relation, DBIDs ids, WritableDoubleDataStore abodvalues, DoubleMinMax minmaxabod) {
    DistanceQuery<V> dq = db.getDistanceQuery(relation, SquaredEuclideanDistanceFunction.STATIC);
    KNNQuery<V> knnq = db.getKNNQuery(dq, DatabaseQuery.HINT_OPTIMIZED_ONLY);
    boolean squared = true;
    if(knnq == null) {
      dq = db.getDistanceQuery(relation, EuclideanDistanceFunction.STATIC);
      knnq = db.getKNNQuery(dq, DatabaseQuery.HINT_OPTIMIZED_ONLY);
      if(knnq == null) {
        return false;
      }
      squared = false;
    }
    SimilarityQuery<V> lk = db.getSimilarityQuery(relation, LinearKernelFunction.STATIC);
    int k1 = k + 1; // We will get the query point back by the knnq.

    MeanVariance s = new MeanVariance();
    for(DBIDIter pA = ids.iter(); pA.valid(); pA.advance()) {
      KNNList nl = knnq.getKNNForDBID(pA, k1);
      double simAA = lk.similarity(pA, pA);

      s.reset();
      DoubleDBIDListIter iB = nl.iter(), iC = nl.iter();
      for(; iB.valid(); iB.advance()) {
        double dAB = iB.doubleValue();
        double simAB = lk.similarity(pA, iB);
        if(!(dAB > 0.)) {
          continue;
        }
        for(iC.seek(iB.getOffset() + 1); iC.valid(); iC.advance()) {
          double dAC = iC.doubleValue();
          double simAC = lk.similarity(pA, iC);
          if(!(dAC > 0.)) {
            continue;
          }
          // Exploit bilinearity of scalar product:
          // <B-A, C-A> = <B, C-A> - <A,C-A>
          // = <B,C> - <B,A> - <A,C> + <A,A>
          double simBC = lk.similarity(iB, iC);
          double numerator = simBC - simAB - simAC + simAA;
          if(squared) {
            double div = 1. / (dAB * dAC);
            s.put(numerator * div, FastMath.sqrt(div));
          }
          else {
            double sqrtdiv = 1. / (dAB * dAC);
            s.put(numerator * sqrtdiv * sqrtdiv, sqrtdiv);
          }
        }
      }
      final double abof = s.getNaiveVariance();
      minmaxabod.put(abof);
      abodvalues.putDouble(pA, abof);
    }
    return true;
  }
976370
public static Node createAndCondition(Node left, Node right) {
		checkNode(left, IN, AND, OR);
		checkNode(right, IN, AND, OR);
		return new Condition(Node.Type.AND, left, right);
	}
682026
def minimise_xyz(xyz):
    """"""
    x, y, z = xyz
    m = max(min(x, y), min(max(x, y), z))
    return (x-m, y-m, z-m)
421109
def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
          left_as='left', right_as='right'):
    
    return join(left, right, how, key, left_key, right_key,
                join_fn=make_union_join(left_as, right_as))
488245
public static List<JoinDescription> unrollChildrenJoins(Collection<JoinDescription> joins) {
        List<JoinDescription> collection = new LinkedList<>();

        for (JoinDescription joinDescription : joins) {
            unrollChildrenInternal(joinDescription, collection);
        }

        return collection;
    }
669178
@Override
    public NodeCentricOptimizationResults<InnerJoinNode> apply(InnerJoinOptimizationProposal proposal, IntermediateQuery query,
                                                               QueryTreeComponent treeComponent)
            throws InvalidQueryOptimizationProposalException, EmptyQueryException {

        InnerJoinNode originalTopJoinNode = proposal.getFocusNode();

        ImmutableList<JoinOrFilterNode> filterOrJoinNodes = extractFilterAndInnerJoinNodes(originalTopJoinNode, query);

        QueryNode parentNode = query.getParent(originalTopJoinNode).get();

        Optional<ImmutableExpression> optionalAggregatedFilterCondition;
        try {
            optionalAggregatedFilterCondition = joinExtractionUtils.extractFoldAndOptimizeBooleanExpressions(filterOrJoinNodes);
        }
        /*
         * The filter condition cannot be satisfied --> the join node and its sub-tree is thus removed from the tree.
         * Returns no join node.
         */
        catch (UnsatisfiableExpressionException e) {

            EmptyNode replacingEmptyNode = iqFactory.createEmptyNode(query.getVariables(originalTopJoinNode));
            treeComponent.replaceSubTree(originalTopJoinNode, replacingEmptyNode);

            // Converts it into a NodeCentricOptimizationResults<InnerJoinNode>
            return new NodeCentricOptimizationResultsImpl<>(query, Optional.of(replacingEmptyNode));
        }

        /*
         * If something has changed
         */
        if ((filterOrJoinNodes.size() > 1)
                || (!optionalAggregatedFilterCondition.equals(originalTopJoinNode.getOptionalFilterCondition()))) {
            /*
             * Optimized join node
             */
            InnerJoinNode newJoinNode = iqFactory.createInnerJoinNode(optionalAggregatedFilterCondition);

            Optional<ArgumentPosition> optionalPosition = treeComponent.getOptionalPosition(parentNode, originalTopJoinNode);
            treeComponent.replaceNodesByOneNode(ImmutableList.<QueryNode>copyOf(filterOrJoinNodes), newJoinNode, parentNode,
                    optionalPosition);

            return new NodeCentricOptimizationResultsImpl<>(query, newJoinNode);
        }
        else {
            return new NodeCentricOptimizationResultsImpl<>(query, originalTopJoinNode);
        }
    }