Ping the QPU by submitting a single-qubit problem.
546211
def ping(config_file, profile, solver_def, json_output, request_timeout, polling_timeout):
    """"""

    now = utcnow()
    info = dict(datetime=now.isoformat(), timestamp=datetime_to_timestamp(now), code=0)

    def output(fmt, **kwargs):
        info.update(kwargs)
        if not json_output:
            click.echo(fmt.format(**kwargs))

    def flush():
        if json_output:
            click.echo(json.dumps(info))

    try:
        _ping(config_file, profile, solver_def, request_timeout, polling_timeout, output)
    except CLIError as error:
        output("Error: {error} (code: {code})", error=str(error), code=error.code)
        sys.exit(error.code)
    except Exception as error:
        output("Unhandled error: {error}", error=str(error))
        sys.exit(127)
    finally:
        flush()
1198817
def quniform(low, high, q, random_state):
    '''
    
    '''
    return np.round(uniform(low, high, random_state) / q) * q
1031710
def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False):
    
    delay = None

    try:  # One could use UDP here, but it's obscure
        mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
    except socket.error as e:
        print("failed. (socket error: '%s')" % e.args[1])
        raise  # raise the original error

    my_ID = os.getpid() & 0xFFFF

    sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, packet_size)
    if sentTime == None:
        mySocket.close()
        return delay

    myStats.pktsSent += 1

    recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout)

    mySocket.close()

    if recvTime:
        delay = (recvTime - sentTime) * 1000
        if not quiet:
            print("%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms" % (
                dataSize, socket.inet_ntoa(struct.pack("!I", iphSrcIP)), icmpSeqNumber, iphTTL, delay)
                  )
        myStats.pktsRcvd += 1
        myStats.totTime += delay
        if myStats.minTime > delay:
            myStats.minTime = delay
        if myStats.maxTime < delay:
            myStats.maxTime = delay
    else:
        delay = None
        print("Request timed out.")

    return delay
233658
def loop_misc(self):
        """"""
        if self._sock is None and self._ssl is None:
            return MQTT_ERR_NO_CONN

        now = time.time()
        self._check_keepalive()
        if self._last_retry_check+1 < now:
            # Only check once a second at most
            self._message_retry_check()
            self._last_retry_check = now

        if self._ping_t > 0 and now - self._ping_t >= self._keepalive:
            # client->ping_t != 0 means we are waiting for a pingresp.
            # This hasn't happened in the keepalive time so we should disconnect.
            if self._ssl:
                self._ssl.close()
                self._ssl = None
            elif self._sock:
                self._sock.close()
                self._sock = None

            self._callback_mutex.acquire()
            if self._state == mqtt_cs_disconnecting:
                rc = MQTT_ERR_SUCCESS
            else:
                rc = 1
            if self.on_disconnect:
                self._in_callback = True
                self.on_disconnect(self, self._userdata, rc)
                self._in_callback = False
            self._callback_mutex.release()
            return MQTT_ERR_CONN_LOST

        return MQTT_ERR_SUCCESS
78542
def _disjoint_qubits(op1: ops.Operation, op2: ops.Operation) -> bool:
    """"""
    return not set(op1.qubits) & set(op2.qubits)
165390
def run(self,shots=1,targetT=0.02,verbose=False):
		
		if self.qubo != []:
			self.qi()
		J = self.reJ()
		N = len(J)

		itetemp = 100
		Rtemp = 0.75

		self.E = []
		qq = []
		for i in range(shots):
			T = self.Ts
			q = np.random.choice([-1,1],N)
			EE = []
			EE.append(Ei(q,self.J)+self.ep)
			while T>targetT:
				x_list = np.random.randint(0, N, itetemp)
				for x in x_list:
					q2 = np.ones(N)*q[x]
					q2[x] = 1
					dE = -2*sum(q*q2*J[:,x])

					if dE < 0 or np.exp(-dE/T) > np.random.random_sample():
						q[x] *= -1
				EE.append(Ei(q,self.J)+self.ep)
				T *= Rtemp
			self.E.append(EE)
			qtemp = (np.asarray(q,int)+1)/2
			qq.append([int(s) for s in qtemp])
			if verbose == True:
				print(i,':',[int(s) for s in qtemp])
			if shots == 1:
				qq = qq[0]
		if shots == 1:
			self.E = self.E[0]
		return qq
506537
def main(option, problem):
    """"""
    # No problem given (or given option ignores the problem argument)
    if problem == 0 or option in {skip, verify_all}:
        # Determine the highest problem number in the current directory
        files = problem_glob()
        problem = max(file.num for file in files) if files else 0

        # No Project Euler files in current directory (no glob results)
        if problem == 0:
            # Generate the first problem file if option is appropriate
            if option not in {cheat, preview, verify_all}:
                msg = "No Project Euler files found in the current directory."
                click.echo(msg)
                option = generate

            # Set problem number to 1
            problem = 1

        # --preview and no problem; preview the next problem
        elif option is preview:
            problem += 1

        # No option and no problem; generate next file if answer is
        # correct (verify() will exit if the solution is incorrect)
        if option is None:
            verify(problem)
            problem += 1
            option = generate

    # Problem given but no option; decide between generate and verify
    elif option is None:
        option = verify if Problem(problem).glob else generate

    # Execute function based on option
    option(problem)
    sys.exit(0)
159456
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False):
        '''

        '''
        if self.config['api_key'] is None:
            raise ValueError('config api_key is undefined')

        if offset or self.config.get('offset', None):
            self.offset = offset or self.config.get('offset', None)

        self._start()

        while True:
            try:
                response = self.get_updates(poll_timeout, self.offset)
                if response.get('ok', False) is False:
                    raise ValueError(response['error'])
                else:
                    self.process_updates(response)
            except Exception as e:
                print('Error: Unknown Exception')
                print(e)
                if debug:
                    raise e
                else:
                    time.sleep(cooldown)
864850
async def handle_client_ping(self, client_addr, _: Ping):
        
        await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
459608
def pyquil_to_tk(prog: Program) -> Circuit:
    
    reg_name = None
    qubits = prog.get_qubits()
    n_qubits = max(qubits) + 1
    tkc = Circuit(n_qubits)
    for i in prog.instructions:
        if isinstance(i, Gate):
            name = i.name
            try:
                optype = _known_quil_gate[name]
            except KeyError as error:
                raise NotImplementedError("Operation not supported by tket: " + str(i)) from error
            if len(i.params) == 0:
                tkc.add_operation(optype, [q.index for q in i.qubits])
            else:
                params = [p/PI for p in i.params]
                op = tkc._get_op(optype,len(i.qubits),len(i.qubits),params)
                tkc._add_operation(op, [q.index for q in i.qubits])
        elif isinstance(i, Measurement):
            if not i.classical_reg:
                raise NotImplementedError("Program has no defined classical register for measurement on qubit: ", i.qubits[0])
            reg = i.classical_reg
            if reg_name and reg_name != reg.name:
                raise NotImplementedError("Program has multiple classical registers: ", reg_name, reg.name)
            reg_name = reg.name
            op = tkc._get_op(OpType.Measure,1,1,str(reg.offset))
            tkc._add_operation(op, [i.qubit.index])
        elif isinstance(i, Declare):
            continue
        elif isinstance(i, Pragma):
            continue
        elif isinstance(i, Halt):
            return tkc
        else:
            raise NotImplementedError("Pyquil instruction is not a gate: " + str(i))
    return tkc
191192
function probe(addr, config) {
    // Do not reassign function argument
    var _config = config || {};

    // Convert callback base system command to promise base
    var deferred = Q.defer();

    // Spawn a ping process
    var ping = null;
    var platform = os.platform();
    try {
        var argumentBuilder = builderFactory.createBuilder(platform);
        ping = cp.spawn(
            builderFactory.getExecutablePath(platform, _config.v6),
            argumentBuilder.getResult(addr, _config)
        );
    } catch (err) {
        deferred.reject(err);
        return deferred.promise;
    }

    // Initial parser
    var parser = parserFactory.createParser(platform, _config);

    // Register events from system ping
    ping.once('error', function () {
        var err = new Error(
            util.format(
                'ping.probe: %s. %s',
                'there was an error while executing the ping program. ',
                'Check the path or permissions...'
            )
        );
        deferred.reject(err);
    });

    // Cache all lines from the system ping
    var outstring = [];
    ping.stdout.on('data', function (data) {
        outstring.push(String(data));
    });

    // Parse lines we have on closing system ping
    ping.once('close', function () {
        // Merge lines we have and split it by \n
        var lines = outstring.join('').split('\n');

        // Parse line one by one
        __.each(lines, parser.eat, parser);

        // Get result
        var ret = parser.getResult();

        deferred.resolve(ret);
    });

    return deferred.promise;
}
971960
def _qvm_run(self, quil_program, classical_addresses, trials,
                 measurement_noise, gate_noise, random_seed) -> np.ndarray:
        
        payload = qvm_run_payload(quil_program, classical_addresses, trials,
                                  measurement_noise, gate_noise, random_seed)
        response = post_json(self.session, self.sync_endpoint + "/qvm", payload)

        ram = response.json()

        for k in ram.keys():
            ram[k] = np.array(ram[k])

        return ram
315846
function CheckInputPacket(tx, index, coin, flags) {
  Packet.call(this);
  this.tx = tx || null;
  this.index = index;
  this.coin = coin || null;
  this.flags = flags != null ? flags : null;
}
469454
function handleCipherSuccess(opts, err) {
  console.log(chalk.green(
    '\nSuccess: ' + opts.input + ' → ' + opts.output + '\n'
  ));
}
1070461
def relabel(self, qubits: Qubits) -> 'State':
        """"""
        return State(self.vec.tensor, qubits, self._memory)
960179
def _interactive_resolve(self, pair):
        """"""
        if self.resolve_all:
            if self.verbose >= 5:
                self._print_pair_diff(pair)
            return self.resolve_all

        resolve = self.options.get("resolve", "skip")
        assert resolve in ("remote", "ask", "skip")

        if resolve == "ask" or self.verbose >= 5:
            self._print_pair_diff(pair)

        if resolve in ("remote", "skip"):
            # self.resolve_all = resolve
            return resolve

        # RED = ansi_code("Fore.LIGHTRED_EX")
        M = ansi_code("Style.BRIGHT") + ansi_code("Style.UNDERLINE")
        R = ansi_code("Style.RESET_ALL")

        # self._print_pair_diff(pair)

        self._inc_stat("interactive_ask")

        while True:
            prompt = (
                "Use "
                + M
                + "R"
                + R
                + "emote, "
                + M
                + "S"
                + R
                + "kip, "
                + M
                + "B"
                + R
                + "inary compare, "
                + M
                + "H"
                + R
                + "elp? "
            )

            r = compat.console_input(prompt).strip()
            if r in ("h", "H", "?"):
                print("The following keys are supported:")
                print("  'b': Binary compare")
                print("  'r': Download remote file")
                print("  's': Skip this file (leave both targets unchanged)")
                print(
                    "Hold Shift (upper case letters) to apply choice for all "
                    "remaining conflicts."
                )
                print("Hit Ctrl+C to abort.")
                continue
            elif r in ("B", "b"):
                self._compare_file(pair.local, pair.remote)
                continue
            elif r in ("R", "S"):
                r = self._resolve_shortcuts[r.lower()]
                self.resolve_all = r
                break
            elif r in ("r", "s"):
                r = self._resolve_shortcuts[r]
                break

        return r
514850
def qvm_run_payload(quil_program, classical_addresses, trials,
                    measurement_noise, gate_noise, 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")
    classical_addresses = prepare_register_list(classical_addresses)
    if not isinstance(trials, integer_types):
        raise TypeError("trials must be an integer")

    payload = {"type": TYPE_MULTISHOT,
               "addresses": classical_addresses,
               "trials": trials,
               "compiled-quil": quil_program.out()}

    if measurement_noise is not None:
        payload["measurement-noise"] = measurement_noise
    if gate_noise is not None:
        payload["gate-noise"] = gate_noise
    if random_seed is not None:
        payload['rng-seed'] = random_seed

    return payload