Generate a quantum program to roll a die of n faces.
426162
def die_program(number_of_sides):
    
    prog = Program()
    n_qubits = qubits_needed(number_of_sides)
    ro = prog.declare('ro', 'BIT', n_qubits)
    # Hadamard initialize.
    for q in range(n_qubits):
        prog.inst(H(q))
    # Measure everything.
    for q in range(n_qubits):
        prog.measure(q, ro[q])
    return prog
1082076
def x_rolls(self, number, count=0, func=sum):
        '''
        '''
        for x in range(number):
            yield self.roll(count, func)
416456
def run_and_measure_payload(quil_program, qubits, trials, random_seed):
    """"""
    if not quil_program:
        raise ValueError("You have attempted to run an empty program."
                         " Please provide gates or measure instructions to your program.")

    if not isinstance(quil_program, Program):
        raise TypeError("quil_program must be a Quil program object")
    qubits = validate_qubit_list(qubits)
    if not isinstance(trials, integer_types):
        raise TypeError("trials must be an integer")

    payload = {"type": TYPE_MULTISHOT_MEASURE,
               "qubits": list(qubits),
               "trials": trials,
               "compiled-quil": quil_program.out()}

    if random_seed is not None:
        payload['rng-seed'] = random_seed

    return payload
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]
3737
def make_oracle(input_qubits, output_qubit, x_bits):
    """"""
    # Make oracle.
    # for (1, 1) it's just a Toffoli gate
    # otherwise negate the zero-bits.
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
    yield(cirq.TOFFOLI(input_qubits[0], input_qubits[1], output_qubit))
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
1240988
def determinize(m):
    """"""
    if not m.is_finite():
        raise TypeError("machine must be a finite automaton")

    transitions = collections.defaultdict(lambda: collections.defaultdict(set))
    alphabet = set()
    for transition in m.get_transitions():
        [[lstate], read] = transition.lhs
        [[rstate]] = transition.rhs
        if len(read) > 1:
            raise NotSupportedException("multiple input symbols on transition not supported")
        if len(read) == 1:
            alphabet.add(read[0])
        transitions[lstate][tuple(read)].add(rstate)

    class Set(frozenset):
        def __str__(self):
            return "{{{}}}".format(",".join(map(str, sorted(self))))
        def _repr_html_(self):
            return "{{{}}}".format(",".join(x._repr_html_() for x in sorted(self)))

    def eclosure(states):
        """Find epsilon-closure of set of states"""
        states = set(states)
        frontier = set(states)
        while len(frontier) > 0:
            lstate = frontier.pop()
            for rstate in transitions[lstate][()]:
                if rstate not in states:
                    states.add(rstate)
                    frontier.add(rstate)
        return states

    dm = FiniteAutomaton()

    start_state = Set(eclosure([m.get_start_state()]))
    dm.set_start_state(start_state)

    frontier = {start_state}
    visited = set()
    while len(frontier) > 0:
        lstates = frontier.pop()
        if lstates in visited:
            continue
        visited.add(lstates)
        dtransitions = collections.defaultdict(set)
        for lstate in lstates:
            for read in alphabet:
                dtransitions[read] |= transitions[lstate][(read,)]
        for read in alphabet:
            rstates = Set(eclosure(dtransitions[read]))
            dm.add_transition([[lstates], read], [[rstates]])
            frontier.add(rstates)

    accept_states = set(m.get_accept_states())
    for states in visited:
        if len(states & accept_states) > 0:
            dm.add_accept_state(states)

    return dm
469218
def _setup_exercise(game_interface: GameInterface, ex: Exercise, seed: int) -> Optional[Result]:
    
    rng = random.Random()
    rng.seed(seed)
    try:
        game_state = ex.setup(rng)
    except Exception as e:
        return Result(ex, seed, FailDueToExerciseException(e, traceback.format_exc()))
    game_interface.set_game_state(game_state)
36693
def generate(str, alg):
    """"""
    img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
    hashcode = hash_input(str, alg)
    pixelmap = setup_pixelmap(hashcode)
    draw_image(pixelmap, img)
    return img
294391
def roll(vari, shift, axis=None):
    """"""
    if isinstance(vari, Poly):
        core = vari.A.copy()
        for key in vari.keys:
            core[key] = roll(core[key], shift, axis)
        return Poly(core, vari.dim, None, vari.dtype)

    return numpy.roll(vari, shift, axis)
29764
def create(deg, p=0.75, mode='x', tags=None):
    
    return RandomRotate(deg, p, mode, tags)
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
1134930
function deterministicGenerateK(curve, hash, d, checkSig, nonce) {
    enforceType("Buffer", hash);
    enforceType(BigInteger, d);

    if (nonce) {
        hash = sha256(Buffer.concat([hash, Buffer.alloc(nonce)]));
    }

    // sanity check
    assert.equal(hash.length, 32, "Hash must be 256 bit");

    var x = d.toBuffer(32);
    var k = Buffer.alloc(32);
    var v = Buffer.alloc(32);

    // Step B
    v.fill(1);

    // Step C
    k.fill(0);

    // Step D
    k = HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k);

    // Step E
    v = HmacSHA256(v, k);

    // Step F
    k = HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k);

    // Step G
    v = HmacSHA256(v, k);

    // Step H1/H2a, ignored as tlen === qlen (256 bit)
    // Step H2b
    v = HmacSHA256(v, k);

    var T = BigInteger.fromBuffer(v);

    // Step H3, repeat until T is within the interval [1, n - 1]
    while (T.signum() <= 0 || T.compareTo(curve.n) >= 0 || !checkSig(T)) {
        k = HmacSHA256(Buffer.concat([v, new Buffer([0])]), k);
        v = HmacSHA256(v, k);

        // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
        // Step H2b again
        v = HmacSHA256(v, k);

        T = BigInteger.fromBuffer(v);
    }

    return T;
}
1242795
def make_data(n,width):
    """"""
    x = dict([(i,100*random.random()) for i in range(1,n+1)])
    y = dict([(i,100*random.random()) for i in range(1,n+1)])
    c = {}
    for i in range(1,n+1):
        for j in range(1,n+1):
            if j != i:
                c[i,j] = distance(x[i],y[i],x[j],y[j])

    e = {1:0}
    l = {1:0}
    start = 0
    delta = int(76.*math.sqrt(n)/n * width)+1
    for i in range(1,n):
        j = i+1
        start += c[i,j]
        e[j] = max(start-delta,0)
        l[j] = start + delta

    return c,x,y,e,l
1253802
def x_rolls(self, number, count=0):
        '''
        '''
        for x in range(number):
            yield super(FuncRoll, self).roll(count, self._func)
1021418
def roll_sd(input, window, scale = 1.0, ddof = 0):
    ''''''
    nobs, i, j, sx, sxx = 0,0,0,0.,0.
    N = len(input)
    sqrt = np.sqrt

    if window > N:
        raise ValueError('Out of bound')

    output = np.ndarray(N-window+1,dtype=input.dtype)

    for val in input[:window]:
        if val == val:
            nobs += 1
            sx += val
            sxx += val*val

    nn = nobs - ddof
    output[j] = NaN if nn<=0 else sqrt(scale * (sxx - sx*sx/nobs) / nn)

    for val in input[window:]:
        prev = input[j]
        if prev == prev:
            sx -= prev
            sxx -= prev*prev
            nobs -= 1

        if val == val:
            nobs += 1
            sx += val
            sxx += val*val

        j += 1
        nn = nobs - ddof
        output[j] = NaN if nn<=0 else sqrt(scale * (sxx - sx*sx/nobs) / nn)

    return output
1198817
def quniform(low, high, q, random_state):
    '''
    
    '''
    return np.round(uniform(low, high, random_state) / q) * q
237531
def main(argv=None):
    """"""
    args = docopt.docopt(__doc__, argv=argv, version=__version__)
    verbose = bool(args['--verbose'])

    f_roll = dice.roll
    kwargs = {}

    if args['--min']:
        f_roll = dice.roll_min
    elif args['--max']:
        f_roll = dice.roll_max

    if args['--max-dice']:
        try:
            kwargs['max_dice'] = int(args['--max-dice'])
        except ValueError:
            print("Invalid value for --max-dice: '%s'" % args['--max-dice'])
            exit(1)

    expr = ' '.join(args['<expression>'])

    try:
        roll, kwargs = f_roll(expr, raw=True, return_kwargs=True, **kwargs)

        if verbose:
            print('Result: ', end='')

        print(str(roll.evaluate_cached(**kwargs)))

        if verbose:
            print('Breakdown:')
            print(dice.utilities.verbose_print(roll, **kwargs))
    except DiceBaseException as e:
        print('Whoops! Something went wrong:')
        print(e.pretty_print())
        exit(1)