Generator for sequential numeric numbers.
193752
def id_generator(start=0):
    
    count = start
    while True:
        send_value = (yield count)
        if not send_value is None:
            if send_value < count:
                raise ValueError('Values from ID generator must increase '
                                 'monotonically (current value: %d; value '
                                 'sent to generator: %d).'
                                 % (count, send_value))
            count = send_value
        else:
            count += 1
788966
def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]:
        """"""
        # Capture the last sequence wildcard for every level of operation nesting on a stack
        # Used to add backtracking edges in case the "match" fails later
        last_wildcards = [None]
        # Generate a fail state for every level of nesting to backtrack to a sequence wildcard in a parent Expression
        # in case no match can be found
        fail_states = [None]
        operand_counts = [0]
        root = state = _State()
        states = {root.id: root}

        for term in flatterm:
            if operand_counts[-1] >= 0:
                operand_counts[-1] += 1

            # For wildcards, generate a chain of #min_count Wildcard edges
            # If the wildcard is unbounded (fixed_size = False),
            # add a wildcard self loop at the end
            if isinstance(term, Wildcard):
                # Generate a chain of #min_count Wildcard edges
                for _ in range(term.min_count):
                    state = cls._create_child_state(state, Wildcard)
                    states[state.id] = state
                # If it is a sequence wildcard, add a self loop
                if not term.fixed_size:
                    state[Wildcard] = state
                    last_wildcards[-1] = state
                    operand_counts[-1] = -1
            else:
                state = cls._create_child_state(state, term)
                states[state.id] = state
                if is_operation(term):
                    fail_state = None
                    if last_wildcards[-1] or fail_states[-1]:
                        last_fail_state = (
                            fail_states[-1]
                            if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
                        )
                        if term.arity.fixed_size:
                            fail_state = _State()
                            states[fail_state.id] = fail_state
                            new_fail_states = [fail_state]
                            for _ in range(term.arity.min_count):
                                new_fail_state = _State()
                                states[new_fail_state.id] = new_fail_state
                                fail_state[Wildcard] = new_fail_state
                                fail_state = new_fail_state
                                new_fail_states.append(new_fail_state)
                            fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
                            fail_state = new_fail_states
                        else:
                            fail_state = _State()
                            states[fail_state.id] = fail_state
                            fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
                            fail_state[Wildcard] = fail_state
                    fail_states.append(fail_state)
                    last_wildcards.append(None)
                    operand_counts.append(0)
                elif term == OPERATION_END:
                    fail_states.pop()
                    last_wildcards.pop()
                    operand_counts.pop()

            if last_wildcards[-1] != state:
                if last_wildcards[-1]:
                    state[EPSILON] = last_wildcards[-1]
                elif fail_states[-1]:
                    last_fail_state = (
                        fail_states[-1]
                        if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
                    )
                    state[EPSILON] = last_fail_state

        state.payload = [final_label]

        return cls._convert_nfa_to_dfa(root, states)
299449
def ScreenGenerator(nfft, r0, nx, ny):
    """"""
    while 1:
        layers = GenerateTwoScreens(nfft, r0)
        for iLayer in range(2):
            for iy in range(int(nfft/ny)):
                for ix in range(int(nfft/nx)):
                    yield layers[iLayer][iy*ny:iy*ny+ny, ix*nx:ix*nx+nx]
537855
def generator(self, random, args):
        """"""
        if self.duplicates:
            max_count = [self.capacity // item[0] for item in self.items]
            return [random.randint(0, m) for m in max_count]
        else:
            return [random.choice([0, 1]) for _ in range(len(self.items))]
844439
def make_data(n,m):
    """"""
    I = range(1,n+1)
    J = range(1,m+1)
    x,y,w = {},{},{}
    for i in I:
        x[i] = random.randint(0,100)
        y[i] = random.randint(0,100)
        w[i] = random.randint(1,5)
    return I,J,x,y,w
1097496
def generate(self, num_to_generate, starting_place):
        """"""
        res = []
        activ = starting_place[None, :]
        index = activ.__getattribute__(self.argfunc)(1)
        item = self.weights[index]
        for x in range(num_to_generate):
            activ = self.forward(item, prev_activation=activ)[0]
            index = activ.__getattribute__(self.argfunc)(1)
            res.append(index)
            item = self.weights[index]

        return res
589261
private void doGenerateIncrements() {
		if(increments != null) {
			return;	// Nothing to do
		}

		// Create random number sequence generator
		MersenneTwister mersenneTwister = new MersenneTwister(seed);

		// Allocate memory
		double[][][] incrementsArray = new double[timeDiscretization.getNumberOfTimeSteps()][jumpIntensities.length][numberOfPaths];

		// Pre-calculate Poisson distributions
		PoissonDistribution[][] poissonDistribution = new PoissonDistribution[timeDiscretization.getNumberOfTimeSteps()][jumpIntensities.length];
		for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
			for(int factorIndex=0; factorIndex<jumpIntensities.length; factorIndex++) {
				poissonDistribution[timeIndex][factorIndex] = new PoissonDistribution(timeDiscretization.getTimeStep(timeIndex)*jumpIntensities[factorIndex]);
			}
		}


		/*
		 * Generate independent increments.
		 *
		 * The inner loop goes over time and factors.
		 * MersenneTwister is known to generate "independent" increments in 623 dimensions.
		 * Since we want to generate independent streams (paths), the loop over path is the outer loop.
		 */
		for(int pathIndex=0; pathIndex<numberOfPaths; pathIndex++) {
			for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
				for(int factorIndex=0; factorIndex<jumpIntensities.length; factorIndex++) {
					double uniformIncrement = mersenneTwister.nextDouble();
					double numberOfJumps = poissonDistribution[timeIndex][factorIndex].inverseCumulativeDistribution(uniformIncrement);

					incrementsArray[timeIndex][factorIndex][pathIndex] = numberOfJumps;
				}
			}
		}

		// Allocate memory for RandomVariable wrapper objects.
		increments = new RandomVariableInterface[timeDiscretization.getNumberOfTimeSteps()][jumpIntensities.length];

		// Wrap the values in RandomVariable objects
		for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
			double time = timeDiscretization.getTime(timeIndex+1);
			for(int factor=0; factor<jumpIntensities.length; factor++) {
				increments[timeIndex][factor] =
						randomVariableFactory.createRandomVariable(time, incrementsArray[timeIndex][factor]);
			}
		}
	}
1246104
def batch(input_iter, batch_size=32):
  """"""
  input_iter = iter(input_iter)
  next_ = list(itertools.islice(input_iter, batch_size))
  while next_:
    yield next_
    next_ = list(itertools.islice(input_iter, batch_size))
924975
def batch_iter(data, batch_size, num_epochs):
    """"""
    data = np.array(data)
    data_size = len(data)
    num_batches_per_epoch = int(len(data)/batch_size) + 1
    for epoch in range(num_epochs):
        # Shuffle the data at each epoch
        shuffle_indices = np.random.permutation(np.arange(data_size))
        shuffled_data = data[shuffle_indices]
        for batch_num in range(num_batches_per_epoch):
            start_index = batch_num * batch_size
            end_index = min((batch_num + 1) * batch_size, data_size)
            yield shuffled_data[start_index:end_index]
1354111
def gridrange(start, end, step):
    """"""
    for x in frange(start.real, end.real, step.real):
        for y in frange(start.imag, end.imag, step.imag):
            yield x + y * 1j
1020595
def generate_batches(sequence, batch_len=1, allow_partial=True, ignore_errors=True, verbosity=1):
    
    it = iter(sequence)
    last_value = False
    # An exception will be thrown by `.next()` here and caught in the loop that called this iterator/generator
    while not last_value:
        batch = []
        for n in range(batch_len):
            try:
                batch += (next(it),)
            except StopIteration:
                last_value = True
                if batch:
                    break
                else:
                    raise StopIteration
            except Exception:
                # 'Error: new-line character seen in unquoted field -
                # do you need to open the file in universal-newline mode?'
                if verbosity > 0:
                    print_exc()
                if not ignore_errors:
                    raise
        yield batch
37439
function createComputations1000to1(n, sources) {
    for (var i = 0; i < n; i++) {
        createComputation1000(sources, i * 1000);
    }
}
160598
def Recurrent(step_model):
    """"""
    ops = step_model.ops

    def recurrent_fwd(seqs, drop=0.0):
        lengths = [len(X) for X in seqs]
        X, size_at_t, unpad = ops.square_sequences(seqs)
        Y = ops.allocate((X.shape[0], X.shape[1], step_model.nO))
        cell_drop = ops.get_dropout_mask((len(seqs), step_model.nO), 0.0)
        hidden_drop = ops.get_dropout_mask((len(seqs), step_model.nO), 0.0)
        out_drop = ops.get_dropout_mask((len(seqs), step_model.nO), 0.0)
        backprops = [None] * max(lengths)
        state = step_model.weights.get_initial_state(len(seqs))
        for t in range(max(lengths)):
            state = list(state)
            size = size_at_t[t]
            Xt = X[t, :size]
            state[0] = state[0][:size]
            state[1] = state[1][:size]
            if cell_drop is not None:
                state[0] *= cell_drop
            if hidden_drop is not None:
                state[1] *= hidden_drop
            inputs = (state, Xt)
            (state, Y[t, :size]), backprops[t] = step_model.begin_update(inputs)
            if out_drop is not None:
                Y[t, :size] *= out_drop
        outputs = unpad(Y)

        def recurrent_bwd(d_outputs, sgd=None):
            dY, size_at_t, unpad = step_model.ops.square_sequences(d_outputs)
            d_state = [
                step_model.ops.allocate((dY.shape[1], step_model.nO)),
                step_model.ops.allocate((dY.shape[1], step_model.nO)),
            ]
            updates = {}

            def gather_updates(weights, gradient, key=None):
                updates[key] = (weights, gradient)

            dX = step_model.ops.allocate(
                (dY.shape[0], dY.shape[1], step_model.weights.nI)
            )
            for t in range(max(lengths) - 1, -1, -1):
                if out_drop is not None:
                    dY[t] *= out_drop
                d_state_t, dXt = backprops[t]((d_state, dY[t]), sgd=gather_updates)
                d_state[0][: d_state_t[0].shape[0]] = d_state_t[0]
                d_state[1][: d_state_t[1].shape[0]] = d_state_t[1]
                dX[t, : dXt.shape[0]] = dXt
                if cell_drop is not None:
                    d_state[0] *= cell_drop
                if hidden_drop is not None:
                    d_state[1] *= hidden_drop
            d_cell, d_hidden = d_state
            step_model.weights.d_initial_cells += d_cell.sum(axis=0)
            step_model.weights.d_initial_hiddens += d_hidden.sum(axis=0)
            if sgd is not None:
                for key, (weights, gradient) in updates.items():
                    sgd(weights, gradient, key=key)
            return unpad(dX)

        return outputs, recurrent_bwd

    model = wrap(recurrent_fwd, step_model)
    model.nO = step_model.nO
    return model
750014
def random_flip(sequence,rnum=None):
  """"""
  randin = rnum
  if not randin: randin = RandomSource()
  if randin.random() < 0.5:
    return rc(sequence)
  return sequence
796785
def _choice(rand_gen: Callable[[], float], sequence: Sequence[T]) -> T:
    
    return sequence[int(rand_gen() * len(sequence))]
724387
def generate_permutations(elements, n):
    
    c = [0] * n
    yield elements
    i = 0
    while i < n:
        if c[i] < i:
            if i % 2 == 0:
                elements[0], elements[i] = elements[i], elements[0]
            else:
                elements[c[i]], elements[i] = elements[i], elements[c[i]]
            yield elements
            c[i] += 1
            i = 0
        else:
            c[i] = 0
            i += 1
1062197
def chunks(data, n):
    """"""
    for i in range(0, len(data), n):
        yield data[i:i+n]