custom Floyd-Rivest selection algorithm: sort ids and coords so that [left..k-1] items are smaller than k-th item (on either x or y axis)
350710
function select(ids, coords, k, left, right, axis) {

    while (right > left) {
        if (right - left > 600) {
            const n = right - left + 1;
            const m = k - left + 1;
            const z = Math.log(n);
            const s = 0.5 * Math.exp(2 * z / 3);
            const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
            const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
            const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
            select(ids, coords, k, newLeft, newRight, axis);
        }

        const t = coords[2 * k + axis];
        let i = left;
        let j = right;

        swapItem(ids, coords, left, k);
        if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);

        while (i < j) {
            swapItem(ids, coords, i, j);
            i++;
            j--;
            while (coords[2 * i + axis] < t) i++;
            while (coords[2 * j + axis] > t) j--;
        }

        if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
        else {
            j++;
            swapItem(ids, coords, j, right);
        }

        if (j <= k) left = j + 1;
        if (k <= j) right = j - 1;
    }
}
465968
private static final int bestPivot(int rank, int m1, int m2, int m3, int m4, int m5) {
    if(rank < m1) {
      return m1;
    }
    if(rank > m5) {
      return m5;
    }
    if(rank < m2) {
      return m2;
    }
    if(rank > m4) {
      return m4;
    }
    return m3;
  }
1287004
def select(yerrs, amps, amp_errs, widths):
    
    keep_1 = np.logical_and(amps < 0, widths > 1)
    keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps))
    keep = np.logical_and(keep_1, keep_2)
    return keep
327665
function createKVSortedIndex(value, allowAsterisk) {
        var index = kv2List(value, 1, allowAsterisk);
        index.sort(descSorterByKOrName);
        return index;
    }
595224
private static void sort (double[] coords1, int length1,
                              double[] coords2, int length2, int[] array) {
        int temp;
        int length = length1 + length2;
        double x1, y1, x2, y2;

        for (int i = 1; i < length; i++) {
            if (array[i - 1] < length1) {
                x1 = coords1[2 * array[i - 1]];
                y1 = coords1[2 * array[i - 1] + 1];
            } else {
                x1 = coords2[2 * (array[i - 1] - length1)];
                y1 = coords2[2 * (array[i - 1] - length1) + 1];
            }
            if (array[i] < length1) {
                x2 = coords1[2 * array[i]];
                y2 = coords1[2 * array[i] + 1];
            } else {
                x2 = coords2[2 * (array[i] - length1)];
                y2 = coords2[2 * (array[i] - length1) + 1];
            }
            int j = i;
            while (j > 0 && compare(x1, y1, x2, y2) <= 0) {
                temp = array[j];
                array[j] = array[j - 1];
                array[j - 1] = temp;
                j--;
                if (j > 0) {
                    if (array[j - 1] < length1) {
                        x1 = coords1[2 * array[j - 1]];
                        y1 = coords1[2 * array[j - 1] + 1];
                    } else {
                        x1 = coords2[2 * (array[j - 1] - length1)];
                        y1 = coords2[2 * (array[j - 1] - length1) + 1];
                    }
                    if (array[j] < length1) {
                        x2 = coords1[2 * array[j]];
                        y2 = coords1[2 * array[j] + 1];
                    } else {
                        x2 = coords2[2 * (array[j] - length1)];
                        y2 = coords2[2 * (array[j] - length1) + 1];
                    }
                }
            }
        }
    }
1242754
def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, axis=-1, mode='interp', cval=0.0):
    '''
    
    '''
    # linearly interpolate missing values before filtering
    x = np.ma.masked_invalid(pd.Series(x).interpolate())

    try:
        # start filtering from the first non-zero value since these won't be addressed by
        # the interpolation above
        ind = np.isfinite(x).nonzero()[0][0]
        x[ind:] = signal.savgol_filter(x[ind:], window_length, polyorder, deriv,
                                       delta, axis, mode, cval)
    except IndexError:
        pass
    return np.ma.masked_invalid(x)
631661
def fill_array(dstarr, order, r, g, b, a):
    
    # TODO: can we make this more efficient?
    dtype = dstarr.dtype
    maxv = np.iinfo(dtype).max
    bgval = dict(A=int(maxv * a), R=int(maxv * r), G=int(maxv * g),
                 B=int(maxv * b))
    bgtup = tuple([bgval[order[i]] for i in range(len(order))])
    if dtype is np.uint8 and len(bgtup) == 4:
        # optimiztion
        bgtup = np.array(bgtup, dtype=dtype).view(np.uint32)[0]
        dstarr = dstarr.view(np.uint32)

    dstarr[..., :] = bgtup
1241241
private int[] makeVertexDeltas(float[] vertices, SortableVertex[] sortVertices, Grid grid) {
        int vc = sortVertices.length;

        // Vertex scaling factor
        float scale = 1.0f / vertexPrecision;

        float prevGridIndex = 0x7fffffff;
        int prevDeltaX = 0;
        int[] intVertices = new int[vc * CTM_POSITION_ELEMENT_COUNT];
        for (int i = 0; i < vc; ++i) {
            // Get grid box origin
            int gridIdx = sortVertices[i].gridIndex;
            float[] gridOrigin = gridIdxToPoint(grid, gridIdx);

            // Get old vertex coordinate index (before vertex sorting)
            int oldIdx = sortVertices[i].originalIndex;

            // Store delta to the grid box origin in the integer vertex array. For the
            // X axis (which is sorted) we also do the delta to the previous coordinate
            // in the box.
            int deltaX = (int) floor(scale * (vertices[oldIdx * 3] - gridOrigin[0]) + 0.5f);
            if (gridIdx == prevGridIndex) {
                intVertices[i * 3] = deltaX - prevDeltaX;
            } else {
                intVertices[i * 3] = deltaX;
            }

            intVertices[i * 3 + 1] = (int) floor(scale * (vertices[oldIdx * 3 + 1] - gridOrigin[1]) + 0.5f);
            intVertices[i * 3 + 2] = (int) floor(scale * (vertices[oldIdx * 3 + 2] - gridOrigin[2]) + 0.5f);

            prevGridIndex = gridIdx;
            prevDeltaX = deltaX;
        }

        return intVertices;
    }
382543
function partition(left, right)
    {
      var pivot = map.values[ Math.floor((right + left) / 2) ];
      var i = left;
      var j = right;

      while (i <= j)
      {
        while (comparator( map.values[i], pivot ) < 0)
        {
          i++;
        }
        while (comparator( map.values[j], pivot ) > 0)
        {
          j--;
        }

        if (i <= j)
        {
          swap( map.values, i, j );
          swap( map.keys, i, j );
          i++;
          j--;
        }
      }

      return i;
    }
291272
function sortByFirst(valueArrays) {
  const firstValues = valueArrays[0];
  const indices = sortedIndices(firstValues);
  return valueArrays.map(function(values) {
    return indices.map(function(sortedIndex) {
      return values[sortedIndex];
    });
  });
}
561770
def sorted_index(values, x):
    
    i = bisect_left(values, x)
    j = bisect_right(values, x)
    return values[i:j].index(x) + i
250901
private double[] calculateMaximumSlope( BitMatrix analizedMatrix, RandomIter pitRandomIter, WritableRandomIter tcaRandomIter,
            int col, int row ) {
        double[] maxSlopeData = new double[10];
        int n = 1, m = 1;

        double dirmax = 0f, e1min = -9999f, e2min = -9999f;

        analizedMatrix.mark(col, row);
        tcaRandomIter.setSample(col, row, 0, 1);
        double pendmax = 0f;
        maxSlopeData[3] = pitRandomIter.getSampleDouble(col, row, 0);
        /*
         * per ogni triangolo calcolo la pendenza massima e la direzione di
         * deflusso reale.
         */
        for( int j = 0; j <= 7; j++ ) {
            n = tri[j][0];
            m = tri[j][1];

            maxSlopeData[4] = pitRandomIter.getSampleDouble(col + order[n][1], row + order[n][0], 0);
            maxSlopeData[5] = pitRandomIter.getSampleDouble(col + order[m][1], row + order[m][0], 0);
            /*
             * verifico che i punti attorno al pixel considerato non siano
             * novalue. In questo caso trascuro il triangolo.
             */
            if (!isNovalue(maxSlopeData[4]) && !isNovalue(maxSlopeData[5])) {
                calculateMaxSlopeAndDirection4Triangles(maxSlopeData);
                if (maxSlopeData[1] > pendmax) {
                    dirmax = maxSlopeData[2];
                    pendmax = maxSlopeData[1];
                    /* - direzione cardinale */
                    maxSlopeData[7] = tri[j][0];
                    /* - direzione diagonale */
                    maxSlopeData[8] = tri[j][1];
                    /* - segno del triangolo */
                    maxSlopeData[9] = tri[j][2];
                    /*
                     * - quote del triangolo avente pendenza
                     * maggiore
                     */
                    e1min = maxSlopeData[4];
                    /*
                     * non necessariamente sono le quote
                     * minime.
                     */
                    e2min = maxSlopeData[5];
                }
            }
        }
        maxSlopeData[1] = pendmax;
        maxSlopeData[2] = dirmax;
        maxSlopeData[4] = e1min;
        maxSlopeData[5] = e2min;

        return maxSlopeData;
    }
776503
def sortkey(x):
    """"""
    r = x[1] / 255.
    g = x[2] / 255.
    b = x[3] / 255.
    cmax = max(r, g, b)
    V = str(int(round(cmax * 100))).zfill(3)
    cmin = min(r, g, b)
    delta = cmax - cmin
    if delta == 0:
        hue = 0
    elif cmax == r:
        hue = 60. * (((g - b)/delta) % 6)
    elif cmax == g:
        hue = 60. * (((b - r)/delta) + 2)
    else:
        hue = 60. * (((r - g)/delta) + 4)
        
    H = str(int(round(hue))).zfill(3)
    
    if cmax == 0:
        sat = 0
    else:
        sat = delta / cmax
    S = str(int(round(sat  * 100))).zfill(3)

    return H + S + V
786792
function improveRankOrdering(g, fixed, movable) {
    var weights = rankWeights(g, fixed, movable);

    var result = [];

    var layer = movable.slice(0);
    
    // Move fixed nodes into the result array first
    for (var i = 0; i < layer.length; ++i) {
      var u = layer[i];
      if (weights[u] === -1) {
        result[i] = u;
        layer[i] = null;
      }
    }

    layer.sort(function(x, y) { return (x ? weights[x] : -1) - (y ? weights[y] : -1); });

    var nextIdx = 0;
    for (var i = 0; i < layer.length; ++i) {
      if (layer[i] !== null) {
        while (result[nextIdx] !== undefined) {
          ++nextIdx;
        }
        result[nextIdx] = layer[i];
      }
    }

    return result;
  }
880828
def get_idx_rect(index_list):
    """"""
    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))
    return ( min(rows), max(rows), min(cols), max(cols) )
832345
private void quicksort(short[] a, int[] indexes, int left, int right) {
        if (right <= left)
            return;
        int i = partition(a, indexes, left, right);
        quicksort(a, indexes, left, i - 1);
        quicksort(a, indexes, i + 1, right);
    }
1170846
function ( pivot ) {

	/**
	 * Searches an element in a sorted array.
	 *
	 * @returns {(int, int)} a tuple where the first element is 1
	 * iff the item was found, and the second element is the place
	 * where the element should be inserted to keep the
	 * array sorted.
	 */

	var pivotsearch = function( delta, a, i, j, k ){

		var p, d;

		if ( i === j ) {
			return [0, i];
		}

		p = pivot( delta, a, i, j, k );
		d = delta( k, a[p] );


		if ( d === 0 ) {
			return [1, p];
		}

		else if ( d < 0 ) {
			return pivotsearch( delta, a, i, p, k );
		}

		else {
			return pivotsearch( delta, a, p + 1, j, k );
		}

	};

	return pivotsearch;

}