Builds a Request for the specified event batch
192138
@Nullable
    private Request makeRequest(List<MobileEventJson> batch) throws IOException {
        if (batch.isEmpty()) {
            return null;
        }

        Sift.Config config = configProvider.getConfig();

        if (config == null) {
            Log.d(TAG, "Missing Sift.Config object");
            return null;
        }

        if (config.accountId == null || config.beaconKey == null || config.serverUrlFormat == null) {
            Log.d(TAG, "Missing account ID, beacon key, and/or server URL format");
            return null;
        }

        if (batch.isEmpty()) {
            Log.d(TAG, "Batch is null or empty");
            return null;
        }

        URL url = new URL(String.format(config.serverUrlFormat, config.accountId));

        final String encodedBeaconKey = Base64.encodeToString(
                config.beaconKey.getBytes(US_ASCII), Base64.NO_WRAP);

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "Basic " + encodedBeaconKey);
        headers.put("Accept", "application/json");
        headers.put("Content-Encoding", "gzip");
        headers.put("Content-Type", "application/json");

        ListRequestJson request = new ListRequestJson()
                .withData(Collections.<Object>unmodifiableList(batch));

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        OutputStream gzip = new GZIPOutputStream(os);
        Writer writer = new OutputStreamWriter(gzip, UTF8);
        Sift.GSON.toJson(request, writer);
        writer.close();

        Log.d(TAG, String.format("Built HTTP request for batch of size %d", batch.size()));

        return new Request.Builder()
                .withMethod("PUT")
                .withUrl(url)
                .withHeaders(headers)
                .withBody(os.toByteArray())
                .build();
    }
1162378
def batch!(operations, request_options = {})
      res = batch(operations, request_options)
      res['taskID'].each do |index, taskID|
        wait_task(index, taskID, WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
      end
    end
629321
def _build_request(self, type, commands):
        '''
        
        '''
        request = {}
        headers = {
            'content-type': 'application/json',
        }
        if self.nxargs['connect_over_uds']:
            user = self.nxargs['cookie']
            headers['cookie'] = 'nxapi_auth=' + user + ':local'
            request['url'] = self.NXAPI_UDS_URI_PATH
        else:
            request['url'] = '{transport}://{host}:{port}{uri}'.format(
                transport=self.nxargs['transport'],
                host=self.nxargs['host'],
                port=self.nxargs['port'],
                uri=self.NXAPI_REMOTE_URI_PATH,
            )

        if isinstance(commands, (list, set, tuple)):
            commands = ' ; '.join(commands)
        payload = {}
        payload['ins_api'] = {
            'version': self.NXAPI_VERSION,
            'type': type,
            'chunk': '0',
            'sid': '1',
            'input': commands,
            'output_format': 'json',
        }
        request['headers'] = headers
        request['payload'] = json.dumps(payload)
        request['opts'] = {
            'http_request_timeout': self.nxargs['timeout']
        }
        log.info('request: %s', request)
        return request
1040629
def insert_request_to_batch(self, request):
        '''
        
        '''
        self.validate_request_table(request)
        self.validate_request_partition_key(request)
        self.validate_request_row_key(request)
        self.batch_requests.append(request)
292066
def process_events(args):
    """"""
    client = EventsClient.from_config()
    client.set_debug(True)
    if args.get:
        response = client.get_events()
    elif args.flush:
        response = client.flush_events()
    return response
78015
def get_event(self,
                  request,
                  tag='',
                  matcher=prefix_matcher.__func__,
                  callback=None,
                  timeout=None
                  ):
        '''
        
        '''
        # if the request finished, no reason to allow event fetching, since we
        # can't send back to the client
        if request._finished:
            future = Future()
            future.set_exception(TimeoutException())
            return future

        future = Future()
        if callback is not None:
            def handle_future(future):
                tornado.ioloop.IOLoop.current().add_callback(callback, future)
            future.add_done_callback(handle_future)
        # add this tag and future to the callbacks
        self.tag_map[(tag, matcher)].append(future)
        self.request_map[request].append((tag, matcher, future))

        if timeout:
            timeout_future = tornado.ioloop.IOLoop.current().call_later(timeout, self._timeout_future, tag, matcher, future)
            self.timeout_map[future] = timeout_future

        return future
766115
def exec_event_handler(self, event, transactional=False):
        """"""
        # QUESTION: Should we raise an exception if `event` is not in some
        # known event-type list?

        callbacks = self._options.get('callbacks', {})

        handler = callbacks.get(event)

        if not handler:
            raise Exception('Handler not defined!!!')

        handler.start(transactional=transactional)
609105
def build_request_chain(sequence, context)
      sequence.reverse.reduce(nil) do |successor, item|
        item.build_middleware(context, successor)
      end
    end
762226
def request(self, cmd, *args, **kwargs):
        
        params = {'action': cmd}
        #TODO: serialize the kwargs?
        params.update(kwargs)
        return self.__request(self.url, params)
731708
def query_events(resource_root, query_str=None):
  
  params = None
  if query_str:
    params = dict(query=query_str)
  return call(resource_root.get, EVENTS_PATH, ApiEventQueryResult,
      params=params)
593029
def build_batch(cls, size, **kwargs):
        
        return [cls.build(**kwargs) for _ in range(size)]
1108378
def on_next_request(self, py_db, request):
        '''
        
        '''
        arguments = request.arguments  # : :type arguments: NextArguments
        thread_id = arguments.threadId

        if py_db.get_use_libraries_filter():
            step_cmd_id = CMD_STEP_OVER_MY_CODE
        else:
            step_cmd_id = CMD_STEP_OVER

        self.api.request_step(py_db, thread_id, step_cmd_id)

        response = pydevd_base_schema.build_response(request)
        return NetCommand(CMD_RETURN, 0, response, is_json=True)
1273708
function BatchRequest(env, batchParams, key) {
	ApiRequest.call(this, env);
	this.queueKey = key;
	this.batchParams = batchParams;
	this.reqType = 'Batch request';

	this.batchText = JSON.stringify(batchParams);
	var apiargs = {
		format: 'json',
		formatversion: 2,
		action: 'parsoid-batch',
		batch: this.batchText,
	};

	this.requestOptions = {
		method: 'POST',
		followRedirect: true,
		uri: env.conf.wiki.apiURI,
		timeout: env.conf.parsoid.timeouts.mwApi.batch,
	};

	// Use multipart form encoding to get more efficient transfer if the gain
	// will be larger than the typical overhead.
	if (encodeURIComponent(apiargs.batch).length - apiargs.batch.length > 600) {
		this.requestOptions.formData = apiargs;
	} else {
		this.requestOptions.form = apiargs;
	}

	this.request(this.requestOptions);
}
1315984
def make_request(url, method='GET', headers=None, timeout=30, **kwargs):
    """"""
    headers = headers or {}
    headers['User-Agent'] = 'treeherder/{}'.format(settings.SITE_HOSTNAME)
    # Work around bug 1305768.
    if 'queue.taskcluster.net' in url:
        headers['x-taskcluster-skip-cache'] = 'true'
    response = requests.request(method,
                                url,
                                headers=headers,
                                timeout=timeout,
                                **kwargs)

    if response.history:
        params = {
            'url': url,
            'redirects': len(response.history),
            'duration': sum(r.elapsed.total_seconds() for r in response.history)
        }
        newrelic.agent.record_custom_event('RedirectedRequest', params=params)

    response.raise_for_status()
    return response
143196
def _construct_event(flask_request, port, binary_types):
        

        identity = ContextIdentity(source_ip=flask_request.remote_addr)

        endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint)
        method = flask_request.method

        request_data = flask_request.get_data()

        request_mimetype = flask_request.mimetype

        is_base_64 = LocalApigwService._should_base64_encode(binary_types, request_mimetype)

        if is_base_64:
            LOG.debug("Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda.")
            request_data = base64.b64encode(request_data)

        if request_data:
            # Flask does not parse/decode the request data. We should do it ourselves
            request_data = request_data.decode('utf-8')

        context = RequestContext(resource_path=endpoint,
                                 http_method=method,
                                 stage="prod",
                                 identity=identity,
                                 path=endpoint)

        event_headers = dict(flask_request.headers)
        event_headers["X-Forwarded-Proto"] = flask_request.scheme
        event_headers["X-Forwarded-Port"] = str(port)

        # APIGW does not support duplicate query parameters. Flask gives query params as a list so
        # we need to convert only grab the first item unless many were given, were we grab the last to be consistent
        # with APIGW
        query_string_dict = LocalApigwService._query_string_params(flask_request)

        event = ApiGatewayLambdaEvent(http_method=method,
                                      body=request_data,
                                      resource=endpoint,
                                      request_context=context,
                                      query_string_params=query_string_dict,
                                      headers=event_headers,
                                      path_parameters=flask_request.view_args,
                                      path=flask_request.path,
                                      is_base_64_encoded=is_base_64)

        event_str = json.dumps(event.to_dict())
        LOG.debug("Constructed String representation of Event to invoke Lambda. Event: %s", event_str)
        return event_str
741120
def run_request(name='default', **kwargs):
    '''
    
    '''
    req = check_request()
    if name not in req:
        return {}
    n_req = req[name]
    if 'mods' not in n_req or 'kwargs' not in n_req:
        return {}
    req[name]['kwargs'].update(kwargs)
    if 'test' in n_req['kwargs']:
        n_req['kwargs'].pop('test')
    if req:
        ret = apply_(n_req['mods'], **n_req['kwargs'])
        try:
            os.remove(os.path.join(__opts__['cachedir'], 'req_state.p'))
        except (IOError, OSError):
            pass
        return ret
    return {}
714081
def _submit_batch(self, url, batch):
        """"""
        # TODO: validate column_name
        batch_parts = batch.parts()

        guid = ""
        headers = {
            'User-Agent': 'kentik-python-api/0.1',
            'Content-Type': 'application/json',
            'X-CH-Auth-Email': self.api_email,
            'X-CH-Auth-API-Token': self.api_token
        }

        # submit each part
        last_part = dict()
        for batch_part in batch_parts:
            # submit
            resp = requests.post(url, headers=headers, data=batch_part.build_json(guid))

            # print the HTTP response to help debug
            print(resp.text)

            # break out at first sign of trouble
            resp.raise_for_status()
            last_part = resp.json()
            guid = last_part['guid']
            if guid is None or len(guid) == 0:
                raise RuntimeError('guid not found in batch response')

        return last_part