REST payload for :py:func:`ForestConnection._qvm_run`
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
490392
def response(self, data, rest):
        '''
        '''
        self.connection.write(data)
        data = data[:-len(self.separator)]
        # If we get a QUIT message, close the connection
        # Used by the test suite.
        if data == b'QUIT':
            self.connection.close()
        return data
458034
def rest(self, token, endpoint=None, timeout=None):
        """"""
        from . import rest
        return rest.SignalFxRestClient(
            token=token,
            endpoint=endpoint or self._api_endpoint,
            timeout=timeout or self._timeout)
1244613
def call(self, my_args=None):
        
        LOGGER.debug("rest.Requester.call")
        if my_args is None:
            raise exceptions.ArianeConfError('requester call arguments')
        if 'http_operation' not in my_args or my_args['http_operation'] is None or not my_args['http_operation']:
            raise exceptions.ArianeConfError('requester call http_operation')
        if 'operation_path' not in my_args or my_args['operation_path'] is None:  # can be empty
            raise exceptions.ArianeConfError('requester call operation_path')
        if 'parameters' not in my_args:
            my_args['parameters'] = None

        if my_args['http_operation'] is "GET":
            if my_args['parameters'] is None:
                response = self.session.get(self.base_url + self.repository_path + my_args['operation_path'])
            else:
                response = self.session.get(self.base_url + self.repository_path + my_args['operation_path'],
                                            params=my_args['parameters'])
        elif my_args['http_operation'] is "POST":
            if my_args['parameters'] is not None:
                response = self.session.post(self.base_url + self.repository_path + my_args['operation_path'],
                                             params=my_args['parameters'])
            else:
                raise exceptions.ArianeConfError('parameters argument is mandatory for http POST request')
        else:
            raise exceptions.ArianeNotImplemented(my_args['http_operation'])

        if response.status_code is 200:
            try:
                return DriverResponse(
                    rc=0,
                    error_message=response.reason,
                    response_content=response.json()
                )
            except ValueError as e:
                return DriverResponse(
                    rc=0,
                    error_message=response.reason,
                    response_content=response.text
                )
        else:
            return DriverResponse(
                rc=response.status_code,
                error_message=response.reason,
                response_content=response.text
            )
940243
def __perform_rest_call(self, requestURL, params=None, headers=None, restType='GET', body=None):
        
        auth, headers = self.__prepare_gprest_call(requestURL, params=params, headers=headers, restType=restType, body=body)
        if restType == 'GET':
            r = requests.get(requestURL, auth=auth, headers=headers, params=params)
        elif restType == 'PUT':
            r = requests.put(requestURL, data=body, auth=auth, headers=headers, params=params)
        elif restType == 'POST':
            r = requests.post(requestURL, data=body, auth=auth, headers=headers, params=params)
        elif restType == 'DELETE':
            r = requests.delete(requestURL, auth=auth, headers=headers, params=params)
        resp = self.__process_gprest_response(r, restType=restType)
        return resp
229473
def get_payload(self):
        
        temp = self.get_uri_as_list()
        query_string = temp[4]
        if query_string == "":
            return None  # Bad request error code
        query_string_as_list = str.split(query_string, "=")
        return query_string_as_list[1]
532747
def recv(self, buffersize, flags=0):
        '''
        
        '''
        _,_,data = self._recv(buffersize)
        return data
1099811
def _qvm_get_version_info(self) -> dict:
        
        response = post_json(self.session, self.sync_endpoint, {'type': 'version'})
        split_version_string = response.text.split()
        try:
            qvm_version = split_version_string[0]
        except ValueError:
            raise TypeError(f'Malformed version string returned by the QVM: {response.text}')
        return qvm_version
1161977
def RESTrequest(*args, **kwargs):
    """"""
    verbose = kwargs.get('verbose', False)
    force_download = kwargs.get('force', False)
    save = kwargs.get('force', True)

    # so you can copy paste from kegg
    args = list(chain.from_iterable(a.split('/') for a in args))
    args = [a for a in args if a]
    request = 'http://rest.kegg.jp/' + "/".join(args)
    print_verbose(verbose, "richiedo la pagina: " + request)
    filename = "KEGG_" + "_".join(args)
    try:
        if force_download:
            raise IOError()
        print_verbose(verbose, "loading the cached file " + filename)
        with open(filename, 'r') as f:
            data = pickle.load(f)
    except IOError:
        print_verbose(verbose, "downloading the library,it may take some time")
        import urllib2
        try:
            req = urllib2.urlopen(request)
            data = req.read()
            if save:
                with open(filename, 'w') as f:
                    print_verbose(verbose, "saving the file to " + filename)
                    pickle.dump(data, f)
        # clean the error stacktrace
        except urllib2.HTTPError as e:
            raise e
    return data
508625
def _sge_get_mem(xmlstring, queue_name):
    
    rootxml = ET.fromstring(xmlstring)
    my_machine_dict = {}
    # on some machines rootxml.tag looks like "{...}qhost" where the "{...}" gets prepended to all attributes
    rootTag = rootxml.tag.rstrip("qhost")
    for host in rootxml.findall(rootTag + 'host'):
        # find all hosts supporting queues
        for queues in host.findall(rootTag + 'queue'):
            # if the user specified queue matches that in the xml:
            if not queue_name or any(q in queues.attrib['name'] for q in queue_name.split(",")):
                my_machine_dict[host.attrib['name']] = {}
                # values from xml for number of processors and mem_total on each machine
                for hostvalues in host.findall(rootTag + 'hostvalue'):
                    if('mem_total' == hostvalues.attrib['name']):
                        if hostvalues.text.lower().endswith('g'):
                            multip = 1
                        elif hostvalues.text.lower().endswith('m'):
                            multip = 1 / float(1024)
                        elif hostvalues.text.lower().endswith('t'):
                            multip = 1024
                        else:
                            raise Exception("Unrecognized suffix in mem_tot from SGE")
                        my_machine_dict[host.attrib['name']]['mem_total'] = \
                                float(hostvalues.text[:-1]) * float(multip)
                break
    return my_machine_dict
195620
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM':
        

        assert self.status in ['connected', 'done']
        prog = quil_to_program(str(binary))

        self._prog = prog
        self.program = binary
        self.status = 'loaded'

        return self
70264
def rest_get(url, timeout, show_error=False):
    ''''''
    try:
        response = requests.get(url, timeout=timeout)
        return response
    except Exception as exception:
        if show_error:
            print_error(exception)
        return None
1132028
def __publish(self, qmsg):
        """"""
        with self.__seqnum_lock:
            seqnum = self.__seqnum
            self.__seqnum = (self.__seqnum + 1) % _SEQ_WRAP_SIZE
        #
        innermsg = ubjdumpb(qmsg.inner_msg)
        clevel = COMP_NONE
        if len(innermsg) >= self.__comp_size:
            logger.debug('Compressing payload')
            try:
                innermsg = COMPRESSORS[self.__comp_default].compress(innermsg)
            except KeyError:
                logger.warning('Unknown compression method %s, not compressing', self.__comp_default)
            else:
                clevel = self.__comp_default

        p = {W_SEQ: seqnum,
             W_MESSAGE: innermsg,
             W_HASH: self.__make_hash(innermsg, self.__token, seqnum),
             W_COMPRESSION: clevel}
        msg = ubjdumpb(p)

        # do not send messages exceeding size limit
        if len(msg) > self.__max_encoded_length:
            self.__request_except(qmsg.requestId, ValueError("Message Payload too large %d > %d"
                                                             % (len(msg), self.__max_encoded_length)))
            return False

        self.__amqplink.send(msg, content_type='application/ubjson')
        if DEBUG_ENABLED:
            p[W_MESSAGE] = qmsg.inner_msg
            logger.debug(decode_sent_msg('decode_sent_msg', p))
        # Callback any debuggers
        self.__fire_callback(_CB_DEBUG_SEND, msg)
        #
        return True
324628
def run_ut_py3_qemu():
    """"""
    from vmcontrol import VM
    with VM() as vm:
        qemu_provision(vm.ssh_port)
        logging.info("execute tests")
        qemu_ssh(vm.ssh_port, "./runtime_functions.py", "run_ut_python3_qemu_internal")
        qemu_rsync_to_host(vm.ssh_port, "*.xml", "mxnet")
        logging.info("copied to host")
        logging.info("tests finished, vm shutdown.")
        vm.shutdown()
356919
def _run_and_measure(self, quil_program, qubits, trials, random_seed) -> np.ndarray:
        
        payload = run_and_measure_payload(quil_program, qubits, trials, random_seed)
        response = post_json(self.session, self.sync_endpoint + "/qvm", payload)
        return np.asarray(response.json())
233991
def wrap_flask_restful_resource(
    fun: Callable, flask_restful_api: FlaskRestfulApi, injector: Injector
) -> Callable:
    
    # The following fragment of code is copied from flask_restful project

    """
    Copyright (c) 2013, Twilio, Inc.
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    - Redistributions of source code must retain the above copyright notice, this
      list of conditions and the following disclaimer.
    - Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    - Neither the name of the Twilio, Inc. nor the names of its contributors may be
      used to endorse or promote products derived from this software without
      specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    """

    @functools.wraps(fun)
    def wrapper(*args: Any, **kwargs: Any) -> Any:
        resp = fun(*args, **kwargs)
        if isinstance(resp, Response):  # There may be a better way to test
            return resp
        data, code, headers = flask_response_unpack(resp)
        return flask_restful_api.make_response(data, code, headers=headers)

    # end of flask_restful code

    return wrapper
603797
def experiment_status(args):
    ''''''
    nni_config = Config(get_config_filename(args))
    rest_port = nni_config.get_config('restServerPort')
    result, response = check_rest_server_quick(rest_port)
    if not result:
        print_normal('Restful server is not running...')
    else:
        print(json.dumps(json.loads(response.text), indent=4, sort_keys=True, separators=(',', ':')))