Draw random samples and only save those that satisfy constraints
        Finish when required number of samples is generated
773564
def get_samples_with_constraints(self, init_points_count):
        
        samples = np.empty((0, self.space.dimensionality))

        while samples.shape[0] < init_points_count:
            domain_samples = self.get_samples_without_constraints(init_points_count)
            valid_indices = (self.space.indicator_constraints(domain_samples) == 1).flatten()
            if sum(valid_indices) > 0:
                valid_samples = domain_samples[valid_indices,:]
                samples = np.vstack((samples,valid_samples))

        return samples[0:init_points_count,:]
1191163
def draw(self):
        '''
        
        '''
        observed_arr = self.noise_sampler.generate()
        _ = self.__encoder_decoder_controller.encoder.inference(observed_arr)
        arr = self.__encoder_decoder_controller.encoder.get_feature_points()
        return arr
1220426
public static void sampleWithoutReplacement(int[] array, int numArgClasses, Random rand) {
    int[] temp = new int[numArgClasses];
    for (int i = 0; i < temp.length; i++) {
      temp[i] = i;
    }
    shuffle(temp, rand);
    System.arraycopy(temp, 0, array, 0, array.length);
  }
440427
def _sample_without_replacement(n, r, out):
    
    k = r.shape[0]

    # Logic taken from random.sample in the standard library
    pool = np.arange(n)
    for j in range(k):
        idx = int(np.floor(r[j] * (n-j)))  # np.floor returns a float
        out[j] = pool[idx]
        pool[idx] = pool[n-j-1]
910013
def sample(self, n=100, seed=None):
        
        if n < 1:
            raise ValueError("Number of samples must be larger than 0, got '%g'" % n)

        if seed is None:
            seed = random.randint(0, 2 ** 32)

        if self.mode == 'spark':
            result = asarray(self.values.tordd().values().takeSample(False, n, seed))

        else:
            basedims = [self.shape[d] for d in self.baseaxes]
            inds = [unravel_index(int(k), basedims) for k in random.rand(n) * prod(basedims)]
            result = asarray([self.values[tupleize(i) + (slice(None, None),)] for i in inds])

        return self._constructor(result, index=self.index)
1085158
def get_draws(fit, variables=None, ignore=None):
    """"""
    if ignore is None:
        ignore = []
    if fit.mode == 1:
        msg = "Model in mode 'test_grad'. Sampling is not conducted."
        raise AttributeError(msg)

    if fit.mode == 2 or fit.sim.get("samples") is None:
        msg = "Fit doesn't contain samples."
        raise AttributeError(msg)

    dtypes = infer_dtypes(fit)

    if variables is None:
        variables = fit.sim["pars_oi"]
    elif isinstance(variables, str):
        variables = [variables]
    variables = list(variables)

    for var, dim in zip(fit.sim["pars_oi"], fit.sim["dims_oi"]):
        if var in variables and np.prod(dim) == 0:
            del variables[variables.index(var)]

    ndraws = [s - w for s, w in zip(fit.sim["n_save"], fit.sim["warmup2"])]
    nchain = len(fit.sim["samples"])

    # check if the values are in 0-based (<=2.17) or 1-based indexing (>=2.18)
    shift = 1
    if any(fit.sim["dims_oi"]):
        # choose variable with lowest number of dims > 1
        par_idx = min((dim, i) for i, dim in enumerate(fit.sim["dims_oi"]) if dim)[1]
        offset = int(sum(map(np.product, fit.sim["dims_oi"][:par_idx])))
        par_offset = int(np.product(fit.sim["dims_oi"][par_idx]))
        par_keys = fit.sim["fnames_oi"][offset : offset + par_offset]
        shift = len(par_keys)
        for item in par_keys:
            _, shape = item.replace("]", "").split("[")
            shape_idx_min = min(int(shape_value) for shape_value in shape.split(","))
            if shape_idx_min < shift:
                shift = shape_idx_min
        # If shift is higher than 1, this will probably mean that Stan
        # has implemented sparse structure (saves only non-zero parts),
        # but let's hope that dims are still corresponding the full shape
        shift = int(min(shift, 1))

    var_keys = OrderedDict((var, []) for var in fit.sim["pars_oi"])
    for key in fit.sim["fnames_oi"]:
        var, *tails = key.split("[")
        loc = [Ellipsis]
        for tail in tails:
            loc = []
            for i in tail[:-1].split(","):
                loc.append(int(i) - shift)
        var_keys[var].append((key, loc))

    shapes = dict(zip(fit.sim["pars_oi"], fit.sim["dims_oi"]))

    variables = [var for var in variables if var not in ignore]

    data = OrderedDict()

    for var in variables:
        if var in data:
            continue
        keys_locs = var_keys.get(var, [(var, [Ellipsis])])
        shape = shapes.get(var, [])
        dtype = dtypes.get(var)

        ndraw = max(ndraws)
        ary_shape = [nchain, ndraw] + shape
        ary = np.empty(ary_shape, dtype=dtype, order="F")
        for chain, (pyholder, ndraw) in enumerate(zip(fit.sim["samples"], ndraws)):
            axes = [chain, slice(None)]
            for key, loc in keys_locs:
                ary_slice = tuple(axes + loc)
                ary[ary_slice] = pyholder.chains[key][-ndraw:]
        data[var] = ary

    return data
564883
def _sample_item(self, **kwargs):
        """"""
        if self.replace:
            # Can sample from any of the items
            loc = np.random.choice(self._n_items)
        else:
            # Can only sample from items that have not been seen
            # Find ids that haven't been seen yet
            not_seen_ids = np.where(np.isnan(self.cached_labels_))[0]
            loc = np.random.choice(not_seen_ids)
        return loc, 1, {}
696378
def make_data(n,prob):
    
    V = range(1,n+1)
    E = [(i,j) for i in V for j in V if i < j and random.random() < prob]
    return V,E
52361
def random_samples(self, n):
        
        samples = self.samples
        inds = rand.randint(len(samples),size=int(n))

        newsamples = samples.iloc[inds]
        newsamples.reset_index(inplace=True)
        return newsamples
58910
def _get_sample_select(samples, keep):
    """"""
    k = np.ones_like(samples, dtype=bool)
    if keep is not None:
        k = np.array([s in keep for s in samples], dtype=bool)
        if np.sum(k) == 0:
            logger.warning("No samples matched the keep list")
    return k
942048
def _rand_init(x_bounds, x_types, selection_num_starting_points):
    '''
    
    '''
    return [lib_data.rand(x_bounds, x_types) for i \
                    in range(0, selection_num_starting_points)]
699422
function sample(test, asap, minDuration, sampleSize, done) {
    var count = 0;
    var totalDuration = 0;
    var sampleDurations = [];
    next();
    function next() {
        measure(function (done) {
            test(asap, done);
        }, function (error, results, duration) {
            if (error) {
                done(error);
            }
            if (sampleDurations.length < sampleSize) {
                sampleDurations.push(duration);
            } else if (Math.random() < 1 / count) {
                sampleDurations.splice(Math.floor(Math.random() * sampleDurations.length), 1);
                sampleDurations.push(duration);
            }
            totalDuration += duration;
            count++;
            if (totalDuration >= minDuration) {
                done(null, {
                    name: test.name,
                    subjectName: asap.name,
                    count: count,
                    totalDuration: totalDuration,
                    averageFrequency: count / totalDuration,
                    averageDuration: totalDuration / count,
                    averageOpsHz: count / totalDuration,
                    sampleDurations: sampleDurations
                });
            } else {
                next();
            }
        });
    }
}
1035591
def draw_random(obj, **kwds):
    
    while True:
        for k, v in six.iteritems(kwds):
            obj.parents[k] = v.next()
        yield obj.random()
1223617
def _sampleFromVertices(self):
    
    coordinates = [
      self.dimensions[0] / 2. * random.choice([-1, 1]),
      self.dimensions[1] / 2. * random.choice([-1, 1]),
      self.dimensions[2] / 2. * random.choice([-1, 1]),
    ]
    return coordinates
311907
def generate_samples(label, num_splits, sampler):
    
    def listify(x):
        return x if isinstance(x, list) else [x]
    label_splits = listify(label.split(num_splits, axis=0))
    prob_samples = []
    prob_targets = []
    samples = []
    for label_split in label_splits:
        label_split_2d = label_split.reshape((-1,1))
        sampled_value = sampler.draw(label_split_2d)
        sampled_classes, exp_cnt_true, exp_cnt_sampled = sampled_value
        samples.append(sampled_classes.astype(np.float32))
        prob_targets.append(exp_cnt_true.astype(np.float32).reshape((-1,1)))
        prob_samples.append(exp_cnt_sampled.astype(np.float32))
    return samples, prob_samples, prob_targets
580441
def run_checks(number_samples, k_choices):
        
        assert isinstance(k_choices, int), \
            "Number of optimal trajectories should be an integer"

        if k_choices < 2:
            raise ValueError(
                "The number of optimal trajectories must be set to 2 or more.")
        if k_choices >= number_samples:
            msg = "The number of optimal trajectories should be less than the \
                    number of samples"
            raise ValueError(msg)
422034
def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100):
    '''
    
    '''
    outputs = None

    if check_feasibility(x_bounds, lowerbound, upperbound) is True:
        # Order parameters by their range size. We want the smallest range first,
        # because the corresponding parameter has less numbers to choose from
        x_idx_sorted = []
        for i, _ in enumerate(x_bounds):
            if x_types[i] == "discrete_int":
                x_idx_sorted.append([i, len(x_bounds[i])])
            elif (x_types[i] == "range_int") or (x_types[i] == "range_continuous"):
                x_idx_sorted.append([i, math.floor(x_bounds[i][1] - x_bounds[i][0])])
        x_idx_sorted = sorted(x_idx_sorted, key=itemgetter(1))

        for _ in range(max_retries):
            budget_allocated = 0
            outputs = [None] * len(x_bounds)

            for i, _ in enumerate(x_idx_sorted):
                x_idx = x_idx_sorted[i][0]
                # The amount of unallocated space that we have
                budget_max = upperbound - budget_allocated
                # NOT the Last x that we need to assign a random number
                if i < (len(x_idx_sorted) - 1):
                    if x_bounds[x_idx][0] <= budget_max:
                        if x_types[x_idx] == "discrete_int":
                            # Note the valid integer
                            temp = []
                            for j in x_bounds[x_idx]:
                                if j <= budget_max:
                                    temp.append(j)
                            # Randomly pick a number from the integer array
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]

                        elif (x_types[x_idx] == "range_int") or \
                                    (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(x_bounds[x_idx][0],
                                                            min(x_bounds[x_idx][-1], budget_max))

                else:
                    # The last x that we need to assign a random number
                    randint_lowerbound = lowerbound - budget_allocated
                    randint_lowerbound = 0 if randint_lowerbound < 0 else randint_lowerbound

                    # This check:
                    # is our smallest possible value going to overflow the available budget space,
                    # and is our largest possible value going to underflow the lower bound
                    if (x_bounds[x_idx][0] <= budget_max) and \
                            (x_bounds[x_idx][-1] >= randint_lowerbound):
                        if x_types[x_idx] == "discrete_int":
                            temp = []
                            for j in x_bounds[x_idx]:
                                # if (j <= budget_max) and (j >= randint_lowerbound):
                                if randint_lowerbound <= j <= budget_max:
                                    temp.append(j)
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]
                        elif (x_types[x_idx] == "range_int") or \
                                (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(randint_lowerbound,
                                                            min(x_bounds[x_idx][1], budget_max))
                if outputs[x_idx] is None:
                    break
                else:
                    budget_allocated += outputs[x_idx]
            if None not in outputs:
                break
    return outputs