Apply distance implementation if specified
506329
def _append_distances(self, v, distance, candidates):
        
        if distance:
            # Normalize vector (stored vectors are normalized)
            nv = unitvec(v)
            candidates = [(x[0], x[1], self.distance.distance(x[0], nv)) for x
                            in candidates]

        return candidates
413999
public void setDistanceFunction(DistanceFunction df) throws Exception {
    if (!(df instanceof EuclideanDistance))
      throw new Exception("KDTree currently only works with "
          + "EuclideanDistanceFunction.");
    m_DistanceFunction = m_EuclideanDistance = (EuclideanDistance) df;
  }
738226
private PolynomialApproximation approximateKnnDistances(double[] knnDistances) {
    StringBuilder msg = new StringBuilder();

    // count the zero distances (necessary of log-log space is used)
    int k_0 = 0;
    if(settings.log) {
      for(int i = 0; i < settings.kmax; i++) {
        double dist = knnDistances[i];
        if(dist == 0) {
          k_0++;
        }
        else {
          break;
        }
      }
    }

    double[] x = new double[settings.kmax - k_0];
    double[] y = new double[settings.kmax - k_0];

    for(int k = 0; k < settings.kmax - k_0; k++) {
      if(settings.log) {
        x[k] = FastMath.log(k + k_0);
        y[k] = FastMath.log(knnDistances[k + k_0]);
      }
      else {
        x[k] = k + k_0;
        y[k] = knnDistances[k + k_0];
      }
    }

    PolynomialRegression regression = new PolynomialRegression(y, x, settings.p);
    PolynomialApproximation approximation = new PolynomialApproximation(regression.getEstimatedCoefficients());

    if(LOG.isDebugging()) {
      msg.append("approximation ").append(approximation);
      LOG.debugFine(msg.toString());
    }
    return approximation;

  }
389613
function agnes(data, options) {
                options = Object.assign({}, defaultOptions$5, options);
                var len = data.length;
                var distance = data;//If source
                if (!options.isDistanceMatrix) {
                    distance = src$3(data, options.disFunc);
                }


                // allows to use a string or a given function
                if (typeof options.kind === 'string') {
                    switch (options.kind) {
                        case 'single':
                            options.kind = simpleLink;
                            break;
                        case 'complete':
                            options.kind = completeLink;
                            break;
                        case 'average':
                            options.kind = averageLink;
                            break;
                        case 'centroid':
                            options.kind = centroidLink;
                            break;
                        case 'ward':
                            options.kind = wardLink;
                            break;
                        default:
                            throw new RangeError('Unknown kind of similarity');
                    }
                } else if (typeof options.kind !== 'function') {
                    throw new TypeError('Undefined kind of similarity');
                }

                var list = new Array(len);
                for (var i = 0; i < distance.length; i++) {
                    list[i] = new ClusterLeaf_1(i);
                }
                var min = 10e5,
                    d = {},
                    dis = 0;

                while (list.length > 1) {
                    // calculates the minimum distance
                    d = {};
                    min = 10e5;
                    for (var j = 0; j < list.length; j++) {
                        for (var k = j + 1; k < list.length; k++) {
                            var fdistance, sdistance;
                            if (list[j] instanceof ClusterLeaf_1) {
                                fdistance = [list[j].index];
                            } else {
                                fdistance = new Array(list[j].index.length);
                                for (var e = 0; e < fdistance.length; e++) {
                                    fdistance[e] = list[j].index[e].index;
                                }
                            }
                            if (list[k] instanceof ClusterLeaf_1) {
                                sdistance = [list[k].index];
                            } else {
                                sdistance = new Array(list[k].index.length);
                                for (var f = 0; f < sdistance.length; f++) {
                                    sdistance[f] = list[k].index[f].index;
                                }
                            }
                            dis = options.kind(fdistance, sdistance, distance).toFixed(4);
                            if (dis in d) {
                                d[dis].push([list[j], list[k]]);
                            } else {
                                d[dis] = [[list[j], list[k]]];
                            }
                            min = Math.min(dis, min);
                        }
                    }
                    // cluster dots
                    var dmin = d[min.toFixed(4)];
                    var clustered = new Array(dmin.length);
                    var aux,
                        count = 0;
                    while (dmin.length > 0) {
                        aux = dmin.shift();
                        for (var q = 0; q < dmin.length; q++) {
                            var int = dmin[q].filter(function (n) {
                                //noinspection JSReferencingMutableVariableFromClosure
                                return aux.indexOf(n) !== -1;
                            });
                            if (int.length > 0) {
                                var diff = dmin[q].filter(function (n) {
                                    //noinspection JSReferencingMutableVariableFromClosure
                                    return aux.indexOf(n) === -1;
                                });
                                aux = aux.concat(diff);
                                dmin.splice(q--, 1);
                            }
                        }
                        clustered[count++] = aux;
                    }
                    clustered.length = count;

                    for (var ii = 0; ii < clustered.length; ii++) {
                        var obj = new Cluster_1();
                        obj.children = clustered[ii].concat();
                        obj.distance = min;
                        obj.index = new Array(len);
                        var indCount = 0;
                        for (var jj = 0; jj < clustered[ii].length; jj++) {
                            if (clustered[ii][jj] instanceof ClusterLeaf_1) {
                                obj.index[indCount++] = clustered[ii][jj];
                            } else {
                                indCount += clustered[ii][jj].index.length;
                                obj.index = clustered[ii][jj].index.concat(obj.index);
                            }
                            list.splice((list.indexOf(clustered[ii][jj])), 1);
                        }
                        obj.index.length = indCount;
                        list.push(obj);
                    }
                }
                return list[0];
            }
576330
public static boolean isAngularDistance(AbstractMaterializeKNNPreprocessor<?> kNN) {
    DistanceFunction<?> distanceFunction = kNN.getDistanceQuery().getDistanceFunction();
    return CosineDistanceFunction.class.isInstance(distanceFunction) //
        || ArcCosineDistanceFunction.class.isInstance(distanceFunction);
  }
720294
def distance2_to(self, other: "Point2"):
        """"""
        assert isinstance(other, Point2)
        return (self[0] - other[0]) ** 2 + (self[1] - other[1]) ** 2
568897
def vector_distance(v1, v2):
    """"""
    dist = 0
    for dim in v1:
        for x in v1[dim]:
            dd = int(v1[dim][x]) - int(v2[dim][x])
            dist = dist + dd**2
    return dist
1335604
def apply(self, mapping):
        """"""
        self.output.seek(0)
        self.output.truncate(0)
        self.interpreter.string(self.template, locals=mapping)
        return self.output.getvalue()
662733
def _editdistance(a, b):
        
        r0 = range(0, len(b) + 1)
        r1 = [0] * (len(b) + 1)

        for i in range(0, len(a)):
            r1[0] = i + 1

            for j in range(0, len(b)):
                c = 0 if a[i] is b[j] else 1
                r1[j + 1] = min(r1[j] + 1, r0[j + 1] + 1, r0[j] + c)

            r0 = r1[:]

        return r1[len(b)]
516614
def contain(descriptors, target_descriptor):
    """"""
    for descriptor in descriptors:
        if edit_distance(descriptor, target_descriptor) < 1e-5:
            return True
    return False
713988
private void assertSortedByDistance(DoubleDBIDList results) {
    // TODO: sort results instead?
    double dist = -1.0;
    boolean sorted = true;
    for(DoubleDBIDListIter it = results.iter(); it.valid(); it.advance()) {
      double qr = it.doubleValue();
      if(qr < dist) {
        sorted = false;
      }
      dist = qr;
    }
    if(!sorted) {
      try {
        ModifiableDoubleDBIDList.class.cast(results).sort();
      }
      catch(ClassCastException | UnsupportedOperationException e) {
        LoggingUtil.warning("WARNING: results not sorted by distance!", e);
      }
    }
  }
367360
def distanceToMesh(self, actor, signed=False, negate=False):
        '''
        
        '''
        poly1 = self.polydata()
        poly2 = actor.polydata()
        df = vtk.vtkDistancePolyDataFilter()
        df.SetInputData(0, poly1)
        df.SetInputData(1, poly2)
        if signed:
            df.SignedDistanceOn()
        if negate:
            df.NegateDistanceOn()
        df.Update()
        
        scals = df.GetOutput().GetPointData().GetScalars()
        poly1.GetPointData().AddArray(scals)

        poly1.GetPointData().SetActiveScalars(scals.GetName())
        rng = scals.GetRange()
        self.mapper.SetScalarRange(rng[0], rng[1])
        self.mapper.ScalarVisibilityOn()
        return self
1235618
def fit_for_distance(self):
        
        for prop in self.properties.keys():
            if prop in self.ic.bands:
                return True
        return False
1355934
private int hammingDistance(BinarySolution solutionOne, BinarySolution solutionTwo) {
    int distance = 0;
    for (int i = 0; i < problem.getNumberOfVariables(); i++) {
      distance += hammingDistance(solutionOne.getVariableValue(i), solutionTwo.getVariableValue(i));
    }

    return distance;
  }
516622
private void checkDistanceFunction(SpatialPrimitiveDistanceFunction<? super O> distanceFunction) {
    if(!settings.distanceFunction.equals(distanceFunction)) {
      throw new IllegalArgumentException("Parameter distanceFunction must be an instance of " + this.distanceQuery.getClass() + ", but is " + distanceFunction.getClass());
    }
  }
141118
def map(self, key, value):
        
        try:
            image = imfeat.resize_image(imfeat.image_fromstring(value, {'type': 'numpy', 'mode': 'bgr', 'dtype': 'uint8'}),
                                        100, 100)
        except:
            hadoopy.counter('DATA_ERRORS', 'ImageLoadError')
            return

        # Distance metric
        diff = image - self.target_image
        dist = np.sum(diff * diff)

        # Output
        if dist < self.min_dist:
            self.min_dist = dist
            self.min_key = key
            self.min_value = value
158300
function distanceToFurthestCorner(x, y, rect) {
    var /** @type {?} */ distX = Math.max(Math.abs(x - rect.left), Math.abs(x - rect.right));
    var /** @type {?} */ distY = Math.max(Math.abs(y - rect.top), Math.abs(y - rect.bottom));
    return Math.sqrt(distX * distX + distY * distY);
}