Generate and evaluate random starts for Parameter objects.
967344
def _random_starts(fun,
                   parameters,
                   jac,
                   args,
                   nstarts,
                   random_state,
                   data_gen=None):
    """"""
    if nstarts < 1:
        raise ValueError("nstarts has to be greater than or equal to 1")

    # Check to see if there are any random parameter types
    anyrand = any(flatten(map_recursive(lambda p: p.is_random, parameters),
                  returns_shapes=False))

    if not anyrand:
        log.info("No random parameters, not doing any random starts")
        params = map_recursive(lambda p: p.value, parameters, output_type=list)
        return params

    log.info("Evaluating random starts...")

    # Deal with gradient returns from objective function
    if jac is True:
        call_fun = lambda *fargs: fun(*fargs)[0]
    else:  # No gradient returns or jac is callable
        call_fun = fun

    # Randomly draw parameters and evaluate function
    def fun_eval():
        batch = next(data_gen) if data_gen else ()
        params = map_recursive(lambda p: p.rvs(random_state), parameters,
                               output_type=list)
        obj = call_fun(*chain(params, batch, args))
        return obj, params

    # Test randomly drawn parameters
    sample_gen = (fun_eval() for _ in range(nstarts))
    obj, params = min(sample_gen, key=lambda t: t[0])

    log.info("Best start found with objective = {}".format(obj))

    return flatten(params, returns_shapes=False)
1285601
def map_init(interface, params):
    """"""
    import numpy as np
    import random
    np.random.seed(params['seed'])
    random.seed(params['seed'])
    return params
433399
private void initParameters()  {
		
		int idx = requestPath.indexOf("?");
		if(idx != -1){
			
			String strParams = null;
			try {
				strParams = URLDecoder.decode(requestPath.substring(idx+1), "UTF-8");
			} catch (UnsupportedEncodingException neverHappens) {
				/*URLEncoder:how not to use checked exceptions...*/
				throw new RuntimeException("Something went unexpectedly wrong while decoding a URL for a generator. ",
											neverHappens);
			}
			
			String[] params = strParams.split("&");
			for (int i = 0; i < params.length; i++) {
				String[] param = params[i].split("=");
				parameters.put(param[0], param[1]);
			}
		}else{ // No parameters
			parameters.clear();
		}
	}
1159874
private ArrayDBIDs initialSet(DBIDs sampleSet, int k, Random random) {
    return DBIDUtil.ensureArray(DBIDUtil.randomSample(sampleSet, k, random));
  }
364606
def __init_run(self, args, kwargs, extra_parameter_errors):
        """"""
        assert not self.active()
        self.__args = list(args)
        self.__kwargs = dict(kwargs)
        self.__extra_parameter_errors = extra_parameter_errors
        self.__args_count = len(args) + len(kwargs)
        self.__params_with_arguments = set()
        self.__stack = []
        self.__push_frame(None)
813623
public T[] generateRandomCandidate(Random rng)
    {
        T[] candidate = elements.clone();
        List<T> list = Arrays.asList(candidate);
        Collections.shuffle(list, rng);
        return list.toArray(candidate);
    }
877883
def generator(self, random, args):
        """"""
        locations = [i for i in range(len(self.weights))]
        random.shuffle(locations)
        return locations
1143534
def _generatePattern(numBits, totalSize):
    
    indices = random.sample(xrange(totalSize), numBits)
    return set(indices)
1353280
def generate(self):
        """"""

        ts=self.generate_tobs()
        noise=self.generate_noise(ts)
        
        rvs=[]
        for t,n in zip(ts, noise):
            rvs.append(n + np.sum(rv.rv_model(t, self.params), axis=0))

        return ts,rvs
612547
def p_generate_items(self, p):
        ''
        p[0] = p[1] + (p[2],)
        p.set_lineno(0, p.lineno(1))
1295837
def random_init_map(interface, state, label, inp):
    """"""
    import random
    out = interface.output(0)
    centers = {}

    for row in inp:
        row = row.strip().split(state["delimiter"])
        if len(row) > 1:
            x = [(0 if row[i] in state["missing_vals"] else float(row[i])) for i in state["X_indices"]]
            cluster = random.randint(0, state['k'] - 1)
            vertex = state['create'](x, 1.0)
            centers[cluster] = vertex if cluster not in centers else state["update"](centers[cluster], vertex)
    for cluster, values in centers.iteritems():
        out.add(cluster, values)
1228671
def initialize(self, params, repetition):
    
    self.name = params["name"]
    self.dataDir = params.get("datadir", "data")
    self.seed = params.get("seed", 42) + repetition

    torch.manual_seed(self.seed)
    np.random.seed(self.seed)
    random.seed(self.seed)

    # Training
    self.epochs = params.get("epochs", 1)
    self.batch_size = params.get("batch_size", 128)
    self.batches_in_epoch = params.get("batches_in_epoch", 100000)
    self.first_epoch_batch_size = params.get("first_epoch_batch_size",
                                             self.batch_size)
    self.batches_in_first_epoch = params.get("batches_in_first_epoch",
                                             self.batches_in_epoch)

    # Testing
    self.test_batch_size = params.get("test_batch_size", 1000)
    self.test_batches_in_epoch = params.get("test_batches_in_epoch", 100000)
    self.noise_values = map(float,
                            params.get("noise_values", "0.0, 0.1").split(", "))
    self.best_noise_score = 0.0
    self.best_epoch = -1

    # Optimizer
    self.optimizer_class = eval(params.get("optimizer", "torch.optim.SGD"))
    self.lr = params.get("learning_rate", 0.05)
    self.momentum = params.get("momentum", 0.9)
    self.weight_decay = params.get("weight_decay", 0.0)
    self.optimizer_params = eval(params.get("optimizer_params", "{}"))
    self.lr_scheduler_gamma = params.get("lr_scheduler_gamma", 0.9)
    self.loss_function = eval(params.get("loss_function",
                                         "torch.nn.functional.cross_entropy"))

    # Network parameters
    self.conv1_sparsity = params.get("conv1_sparsity", 1.0)
    self.network_type = params.get("network_type", "sparse")
    self.growth_rate = params.get("growth_rate", 12)
    self.nblocks = map(int,
                       params.get("nblocks", "6, 12, 24, 16").split(", "))
    self.k_inference_factor = params.get("k_inference_factor", 1.5)

    self.dense_sparsities = map(float,
                                params.get("dense_sparsities",
                                           "1.0, 1.0, 1.0, 1.0").split(", "))
    self.transition_sparsities = map(float,
                                     params.get("transition_sparsities",
                                                "0.1, 0.1, 0.2").split(", "))
    self.linear_sparsity = params.get("linear_sparsity", 0.0)
    self.linear_weight_sparsity = params.get("linear_weight_sparsity", 0.3)
    self.linear_n = params.get("linear_n", 500)
    self.avg_pool_size = params.get("avg_pool_size", 2)
    self.dense_c1_out_planes = params.get("dense_c1_out_planes", 4*self.growth_rate)
645558
private void initRandom() {
        try {
            random = new SecureRandom();
        } catch (Exception e) {
            log.warn("Could not generate SecureRandom for session-id randomness", e);
            random = new Random();
            weakRandom = true;
        }
    }
744532
def _random_helper(random, sampler, params, shape, dtype, kwargs):
    """"""
    if isinstance(params[0], Symbol):
        for i in params[1:]:
            assert isinstance(i, Symbol), \
                "Distribution parameters must all have the same type, but got " \
                "both %s and %s."%(type(params[0]), type(i))
        return sampler(*params, shape=shape, dtype=dtype, **kwargs)
    elif isinstance(params[0], numeric_types):
        for i in params[1:]:
            assert isinstance(i, numeric_types), \
                "Distribution parameters must all have the same type, but got " \
                "both %s and %s."%(type(params[0]), type(i))
        return random(*params, shape=shape, dtype=dtype, **kwargs)

    raise ValueError("Distribution parameters must be either Symbol or numbers, "
                     "but got %s."%type(params[0]))
1051976
protected void fillMissingParameters() {
    if (dest == null) {
      dest = Key.make();
    }
    if (seed == -1) {
      seed = new Random().nextLong();
      Log.info("Generated seed: " + seed);
    }
  }
407716
def generateImplicitParameters(cls, obj):
        
        if not hasattr(obj, 'version'):
            obj.add(ContentLine('VERSION', [], cls.versionString))
946009
def _random_x(self):
        """"""
        return (tuple(random.random() for _ in range(self.fmodel.dim_x)),)