Run when get response from browser.
777437
def on_response(self, msg: Dict[str, str]) -> None:
        """"""
        response = msg.get('data', False)
        if response:
            task = self.__tasks.pop(msg.get('reqid'), False)
            if task and not task.cancelled() and not task.done():
                task.set_result(msg.get('data'))
828264
function onHeaders(ev, status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType) {
    if (resourceType !== 'mainFrame') return;

    let headerArray = [];

    Object.keys(headers).forEach(name => {
      headers[name].forEach(value => {
        headerArray.push({ name, value });
      });
    });

    response = {
      url: newUrl,
      method,
      status: statusCode,
      contentType: headers['content-type'][0],
      headers: headerArray
    };

    notify([ 'header event', status, newUrl, oldUrl, statusCode, method, referrer, headers, resourceType ]);
  }
474826
def process_response(self, request, response, resource, req_succeeded):
        """"""
        sid = request.cookies.get(self.cookie_name, None)
        if sid is None or not self.store.exists(sid):
            sid = self.generate_sid()

        self.store.set(sid, request.context.get(self.context_name, {}))
        response.set_cookie(self.cookie_name, sid, expires=self.cookie_expires, max_age=self.cookie_max_age,
                            domain=self.cookie_domain, path=self.cookie_path, secure=self.cookie_secure,
                            http_only=self.cookie_http_only)
644930
function runHooks(request, response, hooks) {
    var promise = Promise.resolve();
    for (var i = 0; i < hooks.length; i++) {
      promise = promise.then(hooks[i].bind(this, request, response));
    }
    return promise;
  }
888733
function onRequest(request, response) {
  var filename = path.join(__dirname, request.url);

  // Serving server.js from cache. Useful for microbenchmarks.
  if (request.url === cachedUrl) {
    if (response.push) {
      // Also push down the client js, since it's possible if the requester wants
      // one, they want both.
      var push = response.push('/client.js');
      push.writeHead(200);
      fs.createReadStream(path.join(__dirname, '/client.js')).pipe(push);
    }
    response.end(cachedFile);
  }

  // Reading file from disk if it exists and is safe.
  else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) {
    response.writeHead(200);
    var fileStream = fs.createReadStream(filename);
    fileStream.pipe(response);
    fileStream.on('finish',response.end);
  }

  // Example for testing large (boundary-sized) frames.
  else if (request.url === "/largeframe") {
    response.writeHead(200);
    var body = 'a';
    for (var i = 0; i < 14; i++) {
      body += body;
    }
    body = body + 'a';
    response.end(body);
  }

  // Otherwise responding with 404.
  else {
    response.writeHead(404);
    response.end();
  }
}
208653
public function run() {
		// Setup our default error route responders
		$this->setup_error_routes();

		// To always be RESTful, create a last-hit route responder to respond in our designated format ALWAYS
		Router::route( function( $request, $response, $service, $matches ) {
			// ALWAYS respond with our formatting function
			Router::app()->api_respond();
		});

		// Finally, call "dispatch" to have our App's Router route the request appropriately
		Router::dispatch(
			substr(
				$_SERVER['REQUEST_URI'],
				strlen( rtrim( $this->config['app-meta']['base_url'], '/' ) ) // Remove a potential trailing slash
			)
		);
	}
1034201
def run(): # pragma: no cover
    """"""
    out_file, out_format, arguments = parse()
    user, key = arguments.pop('user', None), arguments.pop('key', None)
    if not user or not key:
        sys.stderr.write('Credentials are required to perform API calls.\n')
        sys.exit(1)

    api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'),
              rate_limit=arguments.pop('rate_limit'))
    response = getattr(api, arguments.pop('api_call'))(**arguments)
    output = str(getattr(response, out_format) if out_format != 'list' else response.as_list())
    out_file.write(output if output.endswith('\n') else output + '\n')
1256581
def run():
    """"""
    parser = OptionParser(version='%prog {0}'.format(__version__))
    parser.add_option('-a', '--addr', default='localhost',
                      help=('The address or host to listen on. Specify -a '
                            '0.0.0.0 to listen on all addresses. '
                            'Default: localhost'))
    parser.add_option('-p', '--port', type='int', default='10101',
                      help=('The port to listen for requests on. '
                            'Default: 10101'))
    options, _ = parser.parse_args()
    try:
        server = ThreadingTCPServer((options.addr, options.port),
                                    RequestHandler)
    except (socket.error, socket.gaierror) as exc:  # Handle bind errors
        print(exc)
        sys.exit(1)
    print('Listening on {0} port {1}'.format(options.addr, options.port))
    try:
        server.serve_forever()  # pylint: disable=E1101
    except KeyboardInterrupt:
        server.socket.close()  # pylint: disable=E1101
        RequestHandler.http.close()
        print('Goodbye!')
854230
def run(self):
        """"""
        while True:
            result = json.loads(self.ws.recv())
            if result["cmd"] == "chat" and not result["nick"] == self.nick:
                for handler in list(self.on_message):
                    handler(self, result["text"], result["nick"])
            elif result["cmd"] == "onlineAdd":
                self.online_users.append(result["nick"])
                for handler in list(self.on_join):
                    handler(self, result["nick"])
            elif result["cmd"] == "onlineRemove":
                self.online_users.remove(result["nick"])
                for handler in list(self.on_leave):
                    handler(self, result["nick"])
            elif result["cmd"] == "onlineSet":
                for nick in result["nicks"]:
                    self.online_users.append(nick)
12926
function processResponse( xhr ){
    var responseText = xhr.responseText,
        status       = xhr.status,
        statusText,
        data;

    if ( !xhr ) {
        throw new Error( $.getString( "Errors.Security" ) );
    } else if ( xhr.status !== 200 && xhr.status !== 0 ) {
        status     = xhr.status;
        statusText = ( status == 404 ) ?
            "Not Found" :
            xhr.statusText;
        throw new Error( $.getString( "Errors.Status", status, statusText ) );
    }

    if( responseText.match(/\s*<.*/) ){
        try{
        data = ( xhr.responseXML && xhr.responseXML.documentElement ) ?
            xhr.responseXML :
            $.parseXml( responseText );
        } catch (e){
            data = xhr.responseText;
        }
    }else if( responseText.match(/\s*[\{\[].*/) ){
        try{
          data = $.parseJSON(responseText);
        } catch(e){
          data =  responseText;
        }
    }else{
        data = responseText;
    }
    return data;
}
201620
def process_response(self, request, response):
        """"""
        profiler = getattr(request, 'profiler', None)
        if profiler:
            profiler.close()
            params = request.REQUEST
            stats = hotshot.stats.load(request.statsfile.name)
            queries = connection.queries
            if (params.get('show_queries', False)
                and params.get('show_stats', '1') == '1'):
                response = display_queries(request, stats, queries)
            else:
                response = display_stats(request, stats, queries)
        return response
339587
def execute(self):
        
        self.response = SolrResponse.load_http_response(
            self.session.get(self.HTTP_ENDPOINT, params=self.query)
        )

        # ADS will apply a ceiling to 'rows' and re-write the query
        # This code checks if that happened by comparing the reponse
        # "rows" with what we sent in our query
        # references https://github.com/andycasey/ads/issues/45
        recv_rows = int(self.response.responseHeader.get("params", {}).get("rows"))
        if recv_rows != self.query.get("rows"):
            self._query['rows'] = recv_rows
            warnings.warn("Response rows did not match input rows. "
                          "Setting this query's rows to {}".format(self.query['rows']))

        self._articles.extend(self.response.articles)
        if self._query.get('start') is not None:
            self._query['start'] += self._query['rows']
        elif self._query.get('cursorMark') is not None:
            self._query['cursorMark'] = self.response.json.get("nextCursorMark")

        self._highlights.update(self.response.json.get("highlighting", {}))
543420
function onResponse( repo, idx ) {
		/**
		* FUNCTION: onResponse( error, response, body )
		*	Callback invoked upon receiving a request response.
		*
		* @private
		* @param {Error|Null} error - error object
		* @param {Object} response - HTTP response object
		* @param {String} body - response body
		* @returns {Void}
		*/
		return function onResponse( error, response, body ) {
			if ( eFLG ) {
				return;
			}
			debug( 'Response received for repository `%s` (%d).', repo, idx );
			if ( arguments.length === 1 ) {
				eFLG = true;
				debug( 'Encountered an application-level error for repository `%s` (%d): %s', repo, idx, error.message );
				return clbk( error );
			}
			if ( error ) {
				debug( 'Failed to resolve file for repository `%s` (%d): %s', repo, idx, error.message );
				out.failures[ repo ] = error.message;
				fcount += 1;
			} else {
				debug( 'Successfully resolved file for repository `%s` (%d).', repo, idx );
				out.data[ repo ] = body;
				scount += 1;
			}
			count += 1;
			debug( 'Request %d of %d complete.', count, len );
			next();
		}; // end FUNCTION onResponse()
	}
314434
def do_GET(self):
    """"""
    if not self._client_allowed():
      return

    try:
      (_, _, path, query, _) = urlsplit(self.path)
      params = parse_qs(query)
      # Give each handler a chance to respond.
      for prefix, handler in self._GET_handlers:
        if self._maybe_handle(prefix, handler, path, params):
          return
      # If no path specified, default to showing the list of all runs.
      if path == '/':
        self._handle_runs('', {})
        return

      content = 'Invalid GET request {}'.format(self.path).encode('utf-8'),
      self._send_content(content, 'text/html', code=400)
    except (IOError, ValueError):
      pass
678232
def after_request(self, response):
        
        if response is not None and request is not None:
            # When used as response processor, only run if we are requesting
            # anything but a static resource.
            if request.endpoint in [None, "static"]:
                return response
        self.compile()
        return response
1168149
def process_response(self, req, resp, resource):
        
        if 'result' not in req.context:
            return
        req.context['result']['is_login'] = 'user_id' in req.env['session']
        if settings.DEBUG:
            req.context['result']['_debug_queries'] = sys._debug_db_queries
            sys._debug_db_queries = []
        if resp.body is None and req.context['result']:
            resp.body = json.dumps(req.context['result'])

        try:
            log.debug("RESPONSE: %s" % resp.body)
        except:
            log.exception("ERR: RESPONSE CANT BE LOGGED ")
156653
def do_GET(self):
        """"""
        logging.debug("New GET request.")

        query = parse_qs(urlparse(self.path).query)
        command = query['command'][0].split(' ')
        async = bool(int(query.get('async', [False])[0]))
        output = run_command(command, asynchronous=async)

        self.respond(output)