Return random combinations of indices for a square matrix of size n
    records. For a discussion of how this works see
    http://stackoverflow.com/a/14839010/98080
486726
def randomPairs(n_records, sample_size):
    
    n = int(n_records * (n_records - 1) / 2)

    if sample_size >= n:
        random_pairs = numpy.arange(n, dtype='uint')
    else:
        try:
            random_pairs = numpy.array(random.sample(range(n), sample_size),
                                       dtype='uint')
        except OverflowError:
            return randomPairsWithReplacement(n_records, sample_size)

    b = 1 - 2 * n_records

    root = (-b - 2 * numpy.sqrt(2 * (n - random_pairs) + 0.25)) / 2

    i = numpy.floor(root).astype('uint')
    j = numpy.rint(random_pairs + i * (b + i + 2) / 2 + 1).astype('uint')

    return zip(i, j)
884366
def ndim(n, *args, **kwargs):
    
    thunk = kwargs.get("thunk", lambda: random.random())
    if not args: 
        return [thunk() for i in range(n)]
    A = [] 
    for i in range(n):
        A.append( ndim(*args, thunk=thunk) ) 
    return A
311851
def get_matrix(self, indices):
        """"""
        new = numpy.empty(self.samples1.shape)
        for idx in range(len(indices)):
            if indices[idx]:
                new[idx] = self.samples1[idx]
            else:
                new[idx] = self.samples2[idx]

        if self.poly:
            new = self.poly(*new)
        return new
306395
def matrix_to_blockmatrix(self, blocksize):
        
        if self.get_width() % blocksize or self.get_height() % blocksize:
            raise ValueError("Number of rows and columns have to be evenly dividable by blocksize")
        selfBlocks = []
        for columnIndex in range(0, self.get_width() - 1, blocksize):
            for rowIndex in range(0, self.get_height() - 1, blocksize):
                currentBlock = []
                for blockRows in self.get_array(False)[columnIndex:columnIndex + blocksize]:
                    currentBlock += blockRows[rowIndex:rowIndex + blocksize]
                selfBlocks.append(Matrix(blocksize, blocksize, currentBlock, rowBased=False))
        return Matrix(self.get_width() / blocksize, self.get_height() / blocksize, selfBlocks, rowBased=False)
396986
public static SparseMatrix random(int rows, int columns, double density, Random random) {
        return CRSMatrix.random(rows, columns, density, random);
    }
1027436
def _sample_rows(self, X, Y, sample_shape, seed):
        
        if sample_shape[0] is None or X.shape[0] <= sample_shape[0]:
            X_sample, Y_sample = X, Y
        elif Y is None:
            np.random.seed(seed)
            row_indices = np.random.choice(
                X.shape[0], size=sample_shape[0], replace=False
            )
            X_sample, Y_sample = X.iloc[row_indices], Y
        else:
            drop_size = X.shape[0] - sample_shape[0]
            sample_size = sample_shape[0]
            sss = StratifiedShuffleSplit(
                n_splits=2, test_size=drop_size, train_size=sample_size, random_state=seed
            )
            row_indices, _ = next(sss.split(X, Y))
            X_sample, Y_sample = X.iloc[row_indices], Y.iloc[row_indices]
        return (X_sample, Y_sample)
713467
def resample(self,N):
        
        inds = rand.randint(len(self.samples),size=N)
        return self.samples[inds]
394095
def randsample(vec, nr_samples, with_replacement = False):
    
    if not with_replacement:
        return np.random.permutation(vec)[0:nr_samples]
    else:
        return np.asarray(vec)[np.random.randint(0, len(vec), nr_samples)]
685534
private void randomPermute(int[] permute) {
        for (int i = 0; i < indexVectorSize; i++)
            permute[i] = i;
        for (int i = indexVectorSize - 1; i > 0; i--) {
            int w = (int) Math.floor(Math.random() * (i+1));
            int temp = permute[w];
            permute[w] = permute[i];
            permute[i] = permute[w];
        }
    }
902492
def generate_random_table(self):
        
        table = list(range(0, self.n))
        random.shuffle(table)
        return table
88159
def build_permutation_matrix(permutation):
    
    matrix = lil_matrix((len(permutation), len(permutation)))
    column = 0
    for row in permutation:
        matrix[row, column] = 1
        column += 1
    return matrix
1163099
def generate_evenly_distributed_data_sparse(dim = 2000,
                                            num_active = 40,
                                            num_samples = 1000):
  
  indices = [numpy.random.choice(dim, size = num_active, replace = False)
      for _ in range(num_samples)]
  data = SM32()

  data.reshape(0, dim)
  for row in indices:
    data.addRowNZ(row, [1]*num_active)

  # data.reshape(num_samples, dim)
  # for sample, datapoint in enumerate(indices):
  #   for index in datapoint:
  #     data[sample, index] = 1.

  return data
621613
def nice_indices(arr):
    '''
    
    '''
    # surprisingly, this is slower for very small (and very large) inputs:
    # u,f,i = np.unique(arr,return_index=True,return_inverse=True)
    # arr[:] = np.arange(u.shape[0])[np.argsort(f)][i]
    ids = collections.defaultdict(count().__next__)
    for idx,x in enumerate(arr):
        arr[idx] = ids[x]
    return arr
993858
def random_sample(col, n=5, filters=None):
    
    pipeline = list()
    if filters is not None:
        pipeline.append({"$match": filters})
    pipeline.append({"$sample": {"size": n}})
    return list(col.aggregate(pipeline))
1330755
def _next_sample_index(self):
        
        return self.rng.choice(self.n_streams,
                               p=(self.stream_weights_ /
                                  self.weight_norm_))
572414
def p(i, sample_size, weights):
        

        # Determine the initial pick values
        weight_i = weights[i]
        weights_sum = sum(weights)

        # Build a list of weights that don't contain the weight `i`. This list will
        # be used to build the possible picks before weight `i`.
        other_weights = list(weights)
        del other_weights[i]

        # Calculate the probability
        probability_of_i = 0
        for picks in range(0, sample_size):

            # Build the list of possible permutations for this pick in the sample
            permutations = list(itertools.permutations(other_weights, picks))

            # Calculate the probability for this permutation
            permutation_probabilities = []
            for permutation in permutations:

                # Calculate the probability for each pick in the permutation
                pick_probabilities = []
                pick_weight_sum = weights_sum

                for pick in permutation:
                    pick_probabilities.append(pick / pick_weight_sum)

                    # Each time we pick we update the sum of the weight the next
                    # pick is from.
                    pick_weight_sum -= pick

                # Add the probability of picking i as the last pick
                pick_probabilities += [weight_i / pick_weight_sum]

                # Multiply all the probabilities for the permutation together
                permutation_probability = reduce(
                    lambda x, y: x * y, pick_probabilities
                    )
                permutation_probabilities.append(permutation_probability)

            # Add together all the probabilities for all permutations together
            probability_of_i += sum(permutation_probabilities)

        return probability_of_i
85351
public static Matrix random(int M, int N) {
        Matrix A = new Matrix(M, N);
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                A.data[i][j] = Math.random();
            }
        }
        return A;
    }