Add cand to cur's heap neighbors with distance

@param cur Current object
@param cand Neighbor candidate
@param distance Distance
@return {@code true} if it was a new neighbor.
493064
private boolean add(DBIDRef cur, DBIDRef cand, double distance) {
    KNNHeap neighbors = store.get(cur);
    if(neighbors.contains(cand)) {
      return false;
    }
    double newKDistance = neighbors.insert(distance, cand);
    return (distance <= newKDistance);
  }
243566
@Override
	protected void checkBestDistance(KdTree.Node node, P target) {
		double distanceSq = distance.distance((P)node.point,target);
		if( distanceSq <= bestDistanceSq ) {
			if( bestNode == null || distanceSq < bestDistanceSq ) {
				bestDistanceSq = distanceSq;
				bestNode = node;
			}
		}
	}
162832
def neighbors2(self, distance, chain_residue, atom = None, resid_list = None):

        #atom = " CA "
        ''''''

        if atom == None:     # consider all atoms
            lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types]
        else:                # consider only given atoms
            lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types and line[12:16] == atom]

        shash = spatialhash.SpatialHash(distance)

        for line in lines:
            pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
            shash.insert(pos, line[21:26])

        neighbor_list = []
        for line in lines:
            resid = line[21:26]
            if resid == chain_residue:
                pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))

                for data in shash.nearby(pos, distance):
                    if data[1] not in neighbor_list:
                        neighbor_list.append(data[1])
                neighbor_list.sort()
        return neighbor_list
1259647
protected void expandClusterOrder(DBID ipt, ClusterOrder order, DistanceQuery<V> dq, FiniteProgress prog) {
    UpdatableHeap<OPTICSHeapEntry> heap = new UpdatableHeap<>();
    heap.add(new OPTICSHeapEntry(ipt, null, Double.POSITIVE_INFINITY));
    while(!heap.isEmpty()) {
      final OPTICSHeapEntry current = heap.poll();
      DBID currPt = current.objectID;
      order.add(currPt, current.reachability, current.predecessorID);
      processed.add(currPt);
      double coredist = inverseDensities.doubleValue(currPt);
      for(DBIDIter it = neighs.get(currPt).iter(); it.valid(); it.advance()) {
        if(processed.contains(it)) {
          continue;
        }
        double nrdist = dq.distance(currPt, it);
        if(coredist > nrdist) {
          nrdist = coredist;
        }
        if(reachDist.doubleValue(it) == UNDEFINED_DISTANCE) {
          reachDist.put(it, nrdist);
        }
        else if(nrdist < reachDist.doubleValue(it)) {
          reachDist.put(it, nrdist);
        }
        heap.add(new OPTICSHeapEntry(DBIDUtil.deref(it), currPt, nrdist));
      }
      LOG.incrementProcessed(prog);
    }
  }
1229406
public float distance(INDArray arr1, INDArray arr2) {
        if (scalars == null)
            scalars = new ThreadLocal<>();

        if (Nd4j.scalar(0.0f).equals(scalars.get()))
            scalars.set(Nd4j.scalar(0.0));

        switch (similarityFunction) {
            case "jaccard":
                float ret7 = Nd4j.getExecutioner()
                        .execAndReturn(new JaccardDistance(arr1, arr2, scalars.get()))
                        .getFinalResult().floatValue();
                return invert ? -ret7 : ret7;
            case "hamming":
                float ret8 = Nd4j.getExecutioner()
                        .execAndReturn(new HammingDistance(arr1, arr2, scalars.get()))
                        .getFinalResult().floatValue();
                return invert ? -ret8 : ret8;
            case "euclidean":
                float ret = Nd4j.getExecutioner()
                        .execAndReturn(new EuclideanDistance(arr1, arr2, scalars.get()))
                        .getFinalResult().floatValue();
                return invert ? -ret : ret;
            case "cosinesimilarity":
                float ret2 = Nd4j.getExecutioner()
                        .execAndReturn(new CosineSimilarity(arr1, arr2, scalars.get()))
                        .getFinalResult().floatValue();
                return invert ? -ret2 : ret2;
            case "cosinedistance":
                float ret6 = Nd4j.getExecutioner()
                        .execAndReturn(new CosineDistance(arr1, arr2, scalars.get()))
                        .getFinalResult().floatValue();
                return invert ? -ret6 : ret6;
            case "manhattan":
                float ret3 = Nd4j.getExecutioner()
                        .execAndReturn(new ManhattanDistance(arr1, arr2, scalars.get()))
                        .getFinalResult().floatValue();
                return invert ? -ret3 : ret3;
            case "dot":
                float dotRet = (float) Nd4j.getBlasWrapper().dot(arr1, arr2);
                return invert ? -dotRet : dotRet;
            default:
                float ret4 = Nd4j.getExecutioner()
                        .execAndReturn(new EuclideanDistance(arr1, arr2, scalars.get()))
                        .getFinalResult().floatValue();
                return invert ? -ret4 : ret4;

        }
    }
888806
private boolean cDelete(Bounds[] in, int[] from, int[] to, boolean canRestore) throws ConstraintNotFound, MalformedSimpleDistanceConstraint {
		for (int i = 0; i < in.length; i++) {
			//Conversion
			long min = in[i].min;
			long max = in[i].max;
			if (in[i].max == Long.MAX_VALUE - 1) max = H-O;
			if (in[i].min == Long.MIN_VALUE + 1) min = -1 * (H - O);
			in[i] = new Bounds(min,max);

			SimpleDistanceConstraint con = tPoints[from[i]].getOut(to[i]);

			if (con == null) {
				throw new ConstraintNotFound(String.format("Interval %s, from %d, to %d", in[i].toString(), from[i], to[i]));
			}

			if (con.getCounter() == 1) { 
				if (con.removeInterval(in[i])) tPoints[from[i]].setOut(to[i],null);
				else throw new MalformedSimpleDistanceConstraint(con, 1);
			}
			else if (!con.removeInterval(in[i])) throw new MalformedSimpleDistanceConstraint(con, 2);
		}

		if (!canRestore) fromScratchDistanceMatrixComputation();
		else {
			logger.finest("QuickRestoring distance matrix, no propagation");
			if (backupDMatrixSimple) restoreDMatrix();
		}

		for (int j = 0; j < MAX_USED+1; j++)
			if (tPoints[j].isUsed() == true) {
				tPoints[j].setLowerBound(sum(-distance[j][0],O));
				tPoints[j].setUpperBound(sum(distance[0][j],O));
			}

		return true;
	}
627347
private SimilarityMatrix computeSimilarityMatrixImage(Relation<O> relation, DBIDIter iter) {
    ArrayModifiableDBIDs order = DBIDUtil.newArray(relation.size());
    for(; iter.valid(); iter.advance()) {
      order.add(iter);
    }
    if(order.size() != relation.size()) {
      throw new IllegalStateException("Iterable result doesn't match database size - incomplete ordering?");
    }
    DistanceQuery<O> dq = distanceFunction.instantiate(relation);
    final int size = order.size();

    // When the logging is in the outer loop, it's just 2*size (providing enough
    // resolution)
    final int ltotal = 2 * size; // size * (size + 1);
    FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Similarity Matrix Image", ltotal, LOG) : null;

    // Note: we assume that we have an efficient distance cache available,
    // since we are using 2*O(n*n) distance computations.
    DoubleMinMax minmax = new DoubleMinMax();
    {
      DBIDArrayIter id1 = order.iter();
      DBIDArrayIter id2 = order.iter();
      for(; id1.valid(); id1.advance()) {
        id2.seek(id1.getOffset());
        for(; id2.valid(); id2.advance()) {
          final double dist = dq.distance(id1, id2);
          if(!Double.isNaN(dist) && !Double.isInfinite(dist) /* && dist > 0.0 */) {
            if(!skipzero || dist > 0.0) {
              minmax.put(dist);
            }
          }
        }
        LOG.incrementProcessed(prog);
      }
    }

    double zoom = minmax.getMax() - minmax.getMin();
    if(zoom > 0.0) {
      zoom = 1. / zoom;
    }
    LinearScaling scale = new LinearScaling(zoom, -minmax.getMin() * zoom);
    BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    {
      DBIDArrayIter id1 = order.iter();
      DBIDArrayIter id2 = order.iter();
      for(int x = 0; x < size && id1.valid(); x++, id1.advance()) {
        id2.seek(id1.getOffset());
        for(int y = x; y < size && id2.valid(); y++, id2.advance()) {
          double ddist = dq.distance(id1, id2);
          if(ddist > 0.0) {
            ddist = scale.getScaled(ddist);
          }
          // Apply extra scaling
          if(scaling != null) {
            ddist = scaling.getScaled(ddist);
          }
          int dist = 0xFF & (int) (255 * ddist);
          int col = 0xff000000 | (dist << 16) | (dist << 8) | dist;
          img.setRGB(x, y, col);
          img.setRGB(y, x, col);
        }
        LOG.incrementProcessed(prog);
      }
    }
    LOG.ensureCompleted(prog);

    return new SimilarityMatrix(img, relation, order);
  }
475881
private void computeDistances(ModifiableDoubleDBIDList nlist, DBIDIter query, final DistanceQuery<O> distQuery, Relation<O> relation) {
    nlist.clear();
    O qo = relation.get(query);
    for(DBIDIter ri = relation.iterDBIDs(); ri.valid(); ri.advance()) {
      if(!includeSelf && DBIDUtil.equal(ri, query)) {
        continue;
      }
      double dist = distQuery.distance(qo, ri);
      if(dist != dist) { /* NaN */
        dist = Double.POSITIVE_INFINITY;
      }
      nlist.add(dist, ri);
    }
    nlist.sort();
  }
1334992
@Override
  public double distance(NumberVector v1, NumberVector v2) {
    if(v1.getDimensionality() != v2.getDimensionality()) {
      throw new IllegalArgumentException("Different dimensionality of FeatureVectors\n  " + "first argument: " + v1 + "\n  " + "second argument: " + v2);
    }

    double sqrDist = 0;
    for(int d = BitsUtil.nextSetBit(dimensions, 0); d >= 0; d = BitsUtil.nextSetBit(dimensions, d + 1)) {
      final double delta = v1.doubleValue(d) - v2.doubleValue(d);
      sqrDist += delta * delta;
    }
    return FastMath.sqrt(sqrDist);
  }
1353340
private static Geometry computeSingleSideBuffer(Geometry geometry, double distance, BufferParameters bufferParameters){
        bufferParameters.setSingleSided(true);
        return BufferOp.bufferOp(geometry, distance, bufferParameters);
    }
1124753
private boolean fromScratchDistanceMatrixComputation() {
		logger.fine("Propagating (cube) with (#TPs,#cons) = (" + this.MAX_USED + "," + this.theNetwork.getConstraints().length + ") (call num.: " + (++cubePropCount) + ")");
		//*
		//This code is not tested thoroughly but seems to work
		for (int i = 0; i < MAX_USED+1; i++) {
			for (int j = i; j < MAX_USED+1; j++) {
				if (i != j) {
					long dij = H;//APSPSolver.INF;
					long dji = H;//APSPSolver.INF;

					if(tPoints[i].getOut(j) != null) {
						dij = Math.min(dij, +tPoints[i].getOut(j).getMaximum());
						dji = Math.min(dji, -tPoints[i].getOut(j).getMinimum());
					}
					if(tPoints[j].getOut(i) != null) {
						dij = Math.min(dij, -tPoints[j].getOut(i).getMinimum());
						dji = Math.min(dji, +tPoints[j].getOut(i).getMaximum());
					}

					if(-dji > +dij) {
						return false;
					}

					distance[i][j] = dij;
					distance[j][i] = dji;

				}
				else distance[i][j] = 0;
			}
		}

		for (int k = 0; k < MAX_USED+1; k++) {
			if (tPoints[k].isUsed() == true) {
				for (int i = 0; i < MAX_USED+1; i++) {
					if (tPoints[i].isUsed() == true) {
						for (int j = 0; j < MAX_USED+1; j++) { 
							if (tPoints[j].isUsed() == true) {
								long temp = sum(distance[i][k],distance[k][j]);
								if (distance[i][j] > temp)
									distance[i][j] = temp;
							}
							if (i == j && distance[i][j] < 0) return false;
						}
					}
				}
			}
		}

		return true;
	}
1314320
public final void setMinDragDistance(final float minDragDistance) {
        if (minDragDistance != 0) {
            Condition.INSTANCE.ensureSmaller(minDragDistance, -threshold,
                    "The minimum drag distance must be smaller than " + -threshold);
        }

        this.minDragDistance = minDragDistance;
    }
1273800
public void setMaxDistance (float distance)
    {
        if (_maxDistance != distance) {
            AL10.alSourcef(_id, AL10.AL_MAX_DISTANCE, _maxDistance = distance);
        }
    }
247774
public double sqrMaxDistance(Envelope2D other) {
		if (isEmpty() || other.isEmpty())
			return NumberUtils.TheNaN;

		double dist = 0;
		Point2D[] points = new Point2D[4];
		queryCorners(points);
		Point2D[] points_o = new Point2D[4];
		other.queryCorners(points_o);
		for (int i = 0; i < 4; i++) {
			for (int j = 0; j < 4; j++) {
				double d = Point2D.sqrDistance(points[i], points_o[j]);
				if (d > dist) {
					dist = d;
				}
			}
		}

		return dist;
	}
801367
public double distance(final Coordinate c) {
        final double dx = getX() - c.getX();
        final double dy = getY() - c.getY();
        return Math.sqrt(dx * dx + dy * dy);
    }
800597
public void addExample(DistanceInstance answeredQuery) {
		MyMultiDistanceInstance di = asMultiDistanceInstance( answeredQuery );
		for (int i=0; i<innerLearners.length; i++) {
			innerLearners[i].addExample( di.get(i) );
		}
		comboAddExample( di );
	}
925603
@SuppressWarnings({ "cast", "unchecked" })
  public static <O extends SpatialComparable> RangeQuery<O> getRangeQuery(AbstractRStarTree<?, ?, ?> tree, SpatialDistanceQuery<O> distanceQuery, Object... hints) {
    // Can we support this distance function - spatial distances only!
    SpatialPrimitiveDistanceFunction<? super O> df = distanceQuery.getDistanceFunction();
    if(EuclideanDistanceFunction.STATIC.equals(df)) {
      return (RangeQuery<O>) new EuclideanRStarTreeRangeQuery<>(tree, (Relation<NumberVector>) distanceQuery.getRelation());
    }
    return new RStarTreeRangeQuery<>(tree, distanceQuery.getRelation(), df);
  }