Get nearest target for each origin
177789
def _get_target_nearest(self):
        """"""
        reps_query = """
             SELECT DISTINCT ON(g2.cartodb_id)
                 g1.cartodb_id As origin_id,
                 g2.the_geom,
                 g2.cartodb_id + {maxorigin} as cartodb_id,
                 g2.the_geom_webmercator
             FROM {origin_table} As g1, {target_table} As g2
             ORDER BY g2.cartodb_id, g1.the_geom <-> g2.the_geom
        """.format(
            maxorigin=self.origins.index.max(),
            origin_table=self.origin_table,
            target_table=self.target_table
        )

        nearest_reps = self.context.query(
            reps_query,
            decode_geom=True
        )

        nearest_reps = gpd.GeoDataFrame(nearest_reps, geometry='geometry')
        init_labels = nearest_reps['origin_id'].values

        # update with new information
        self.targets['labels'] = init_labels
        logging.info('nearest targets retrieved')

        return nearest_reps
479480
def nearbys(radius = 20, options = {})
      return nil unless geocoded?
      options.merge!(:exclude => self) unless send(self.class.primary_key).nil?
      self.class.near(self, radius, options)
    end
966799
def closest(self, coords=[], **kwargs):
        
        if kwargs and coords:
            raise ValueError("Specify coordinate using as either a list "
                             "keyword arguments not both")
        if kwargs:
            coords = []
            getter = []
            for k, v in kwargs.items():
                idx = self.get_dimension_index(k)
                if np.isscalar(v):
                    coords.append((0, v) if idx else (v, 0))
                else:
                    if isinstance(v, list):
                        coords = [(0, c) if idx else (c, 0) for c in v]
                    if len(coords) not in [0, len(v)]:
                        raise ValueError("Length of samples must match")
                    elif len(coords):
                        coords = [(t[abs(idx-1)], c) if idx else (c, t[abs(idx-1)])
                                  for c, t in zip(v, coords)]
                getter.append(idx)
        else:
            getter = [0, 1]
        getter = itemgetter(*sorted(getter))
        if len(coords) == 1:
            coords = coords[0]
        if isinstance(coords, tuple):
            return getter(self.closest_cell_center(*coords))
        else:
            return [getter(self.closest_cell_center(*el)) for el in coords]
328785
def _get_target_index(self):
        """"""
        return (self.index + self.source_window * (not self.overlapping) +
                self.offset)
1105164
def nearest_point(x, y, pts, mode='random'):
    
    dists = (pts.T[0] - x) ** 2 + (pts.T[1] - y) ** 2
    fx = dists.argmin()
    mindist = dists[fx]
    other_fx = np.where(mindist == dists)[0]
    if len(other_fx) > 0:
        if mode == 'random':
            np.random.shuffle(other_fx)
            fx = other_fx[0]
        if mode == 'all':
            fx = other_fx
        if mode == 'first':
            fx = fx
    return fx, mindist
51934
async def _nearest(
            self,
            kind: str,
            latitude: Union[float, str] = None,
            longitude: Union[float, str] = None) -> dict:
        """"""
        params = {}
        if latitude and longitude:
            params.update({'lat': str(latitude), 'lon': str(longitude)})

        data = await self._request(
            'get', 'nearest_{0}'.format(kind), params=params)
        return data['data']
828209
function findClosestPointOnSpecialAttractor(x,y) {
  var nSpecialAttractor = specialAttractors.length;
  var currentMinDistance = 0;
  var currentSpecialAttractor;
  var ox = 0;
  var oy = 0;
  for(var a=0; a<nSpecialAttractor; a++) {
    var specialAttractor = specialAttractors[a];
    var closestSegmentPoint = distanceToSegment(specialAttractor.x1, specialAttractor.y1, specialAttractor.x2, specialAttractor.y2, x, y);
    if(a == 0 || (closestSegmentPoint.distance) < currentMinDistance) {
      currentMinDistance = closestSegmentPoint.distance;
      currentSpecialAttractor = specialAttractor;
      ox = closestSegmentPoint.originX;
      oy = closestSegmentPoint.originY;
    }
  }
  return {
    distance: currentMinDistance,
    specialAttractor: currentSpecialAttractor,
    originX: ox,
    originY: oy
  }
}
718071
def edge_by_target(self):
        """"""
        if self._edge_by_target is None:
            self._edge_by_target = reverse_edge_by_source_dict(self._edge_by_source_id,
                                                               self._nexson_tree['^ot:rootNodeId'])
        return self._edge_by_target
650516
def get_closest(self, lon, lat, depth=0):
        
        xyz = spherical_to_cartesian(lon, lat, depth)
        min_dist, idx = self.kdtree.query(xyz)
        return self.objects[idx], min_dist
386338
def _find_neighbors(self, inst):
        
        # Make a vector of distances between target instance (inst) and all others
        dist_vect = []
        for j in range(self._datalen):
            if inst != j:
                locator = [inst, j]
                if inst < j:
                    locator.reverse()
                dist_vect.append(self._distance_array[locator[0]][locator[1]])
            else:
                # Ensures that target instance is never selected as neighbor.
                dist_vect.append(sys.maxsize)

        dist_vect = np.array(dist_vect)

        # Identify neighbors-------------------------------------------------------
        """ NN for Binary Endpoints: """
        if self._class_type == 'binary':
            nn_list = []
            match_count = 0
            miss_count = 0
            for nn_index in np.argsort(dist_vect):
                if self._y[inst] == self._y[nn_index]:  # Hit neighbor identified
                    if match_count >= self.n_neighbors:
                        continue
                    nn_list.append(nn_index)
                    match_count += 1
                else:  # Miss neighbor identified
                    if miss_count >= self.n_neighbors:
                        continue
                    nn_list.append(nn_index)
                    miss_count += 1

                if match_count >= self.n_neighbors and miss_count >= self.n_neighbors:
                    break

        elif self._class_type == 'multiclass':
            nn_list = []
            match_count = 0
            miss_count = dict.fromkeys(self._label_list, 0)
            for nn_index in np.argsort(dist_vect):
                if self._y[inst] == self._y[nn_index]:  # Hit neighbor identified
                    if match_count >= self.n_neighbors:
                        continue
                    nn_list.append(nn_index)
                    match_count += 1
                else:
                    for label in self._label_list:
                        if self._y[nn_index] == label:
                            if miss_count[label] >= self.n_neighbors:
                                continue
                            nn_list.append(nn_index)
                            miss_count[label] += 1

                if match_count >= self.n_neighbors and all(v >= self.n_neighbors for v in miss_count.values()):
                    break
        else:
            nn_list = []
            match_count = 0
            miss_count = 0
            for nn_index in np.argsort(dist_vect):
                if abs(self._y[inst]-self._y[nn_index]) < self._labels_std:  # Hit neighbor identified
                    if match_count >= self.n_neighbors:
                        continue
                    nn_list.append(nn_index)
                    match_count += 1
                else:  # Miss neighbor identified
                    if miss_count >= self.n_neighbors:
                        continue
                    nn_list.append(nn_index)
                    miss_count += 1

                if match_count >= self.n_neighbors and miss_count >= self.n_neighbors:
                    break
        return np.array(nn_list)
1371169
def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False,
                                 usev=False):
        """"""
        return self.find_closest_trackpoint(R,vR,vT,z,vz,phi,
                                            interp=interp,xy=xy,
                                            usev=usev)
1125497
def calculate_sources(self, targets):
    """"""
    sources = set()
    for target in targets:
      sources.update(
        source for source in target.sources_relative_to_buildroot()
        if source.endswith(self._PYTHON_SOURCE_EXTENSION)
      )
    return sources
96416
function findClosestPoint (sources, target) {
  const distances = [];
  let minDistance;

  sources.forEach(function (source, index) {
    const d = distance(source, target);

    distances.push(d);

    if (index === 0) {
      minDistance = d;
    } else {
      minDistance = Math.min(d, minDistance);
    }
  });

  const index = distances.indexOf(minDistance);


  return sources[index];
}
640031
function getNearestDataPoint2(mouseY) {
            let adjustedMouseY = mouseY - margin.bottom,
                epsilon = yScale.bandwidth(),
                nearest = [];

            layers.map(function (data) {
                let found = data.values.find((d2) => Math.abs(adjustedMouseY >= yScale(d2[nameLabel])) && Math.abs(adjustedMouseY - yScale(d2[nameLabel]) <= epsilon * 2));

                if (found) {
                    found.values = data.values;
                    found.key = found.name;
                    nearest.push(found)
                }
            });

            return nearest.length ? nearest[0] : undefined;
        }
1004012
function findArcHeight(distance, radius, maxArcHeight, greaterThan180) {
    var heightOptions = [];
    heightOptions.push(radius + Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2)));
    heightOptions.push(radius - Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2)));

    if(greaterThan180){
        return closestButNotGreaterThan(heightOptions, maxArcHeight);
    }
    else{
        return closestToZero(heightOptions, maxArcHeight);
    }
}
640118
def _get_crop_target(target_px:Union[int,TensorImageSize], mult:int=None)->Tuple[int,int]:
    ""
    target_r,target_c = tis2hw(target_px)
    return _round_multiple(target_r,mult),_round_multiple(target_c,mult)
1018487
def _iter_coords(nsls):
    """"""
    # First convert all slices to ranges
    ranges = list()
    for nsl in nsls:
        if isinstance(nsl, int):
            ranges.append(range(nsl, nsl+1))
        else:
            ranges.append(range(nsl.start, nsl.stop))
    # Iterate through all matching coordinates
    yield from itertools.product(*ranges)