This function is called when the application has provided a response
        and needs it to be sent to the client.
1994
def confirmation(self, apdu):
        """"""
        if _debug: ServerSSM._debug("confirmation %r", apdu)

        # check to see we are in the correct state
        if self.state != AWAIT_RESPONSE:
            if _debug: ServerSSM._debug("    - warning: not expecting a response")

        # abort response
        if (apdu.apduType == AbortPDU.pduType):
            if _debug: ServerSSM._debug("    - abort")

            self.set_state(ABORTED)

            # send the response to the device
            self.response(apdu)
            return

        # simple response
        if (apdu.apduType == SimpleAckPDU.pduType) or (apdu.apduType == ErrorPDU.pduType) or (apdu.apduType == RejectPDU.pduType):
            if _debug: ServerSSM._debug("    - simple ack, error, or reject")

            # transaction completed
            self.set_state(COMPLETED)

            # send the response to the device
            self.response(apdu)
            return

        # complex ack
        if (apdu.apduType == ComplexAckPDU.pduType):
            if _debug: ServerSSM._debug("    - complex ack")

            # save the response and set the segmentation context
            self.set_segmentation_context(apdu)

            # the segment size is the minimum of the size of the largest packet
            # that can be delivered to the client and the largest it can accept
            if (not self.device_info) or (self.device_info.maxNpduLength is None):
                self.segmentSize = self.maxApduLengthAccepted
            else:
                self.segmentSize = min(self.device_info.maxNpduLength, self.maxApduLengthAccepted)
            if _debug: ServerSSM._debug("    - segment size: %r", self.segmentSize)

            # compute the segment count
            if not apdu.pduData:
                # always at least one segment
                self.segmentCount = 1
            else:
                # split into chunks, maybe need one more
                self.segmentCount, more = divmod(len(apdu.pduData), self.segmentSize)
                if more:
                    self.segmentCount += 1
            if _debug: ServerSSM._debug("    - segment count: %r", self.segmentCount)

            # make sure we support segmented transmit if we need to
            if self.segmentCount > 1:
                if _debug: ServerSSM._debug("    - segmentation required, %d segments", self.segmentCount)

                # make sure we support segmented transmit
                if self.segmentationSupported not in ('segmentedTransmit', 'segmentedBoth'):
                    if _debug: ServerSSM._debug("    - server can't send segmented responses")
                    abort = self.abort(AbortReason.segmentationNotSupported)
                    self.response(abort)
                    return

                # make sure client supports segmented receive
                if not self.segmented_response_accepted:
                    if _debug: ServerSSM._debug("    - client can't receive segmented responses")
                    abort = self.abort(AbortReason.segmentationNotSupported)
                    self.response(abort)
                    return

                # make sure we dont exceed the number of segments in our response
                # that the client said it was willing to accept in the request
                if (self.maxSegmentsAccepted is not None) and (self.segmentCount > self.maxSegmentsAccepted):
                    if _debug: ServerSSM._debug("    - client can't receive enough segments")
                    abort = self.abort(AbortReason.apduTooLong)
                    self.response(abort)
                    return

            # initialize the state
            self.segmentRetryCount = 0
            self.initialSequenceNumber = 0
            self.actualWindowSize = None

            # send out the first segment (or the whole thing)
            if self.segmentCount == 1:
                self.response(apdu)
                self.set_state(COMPLETED)
            else:
                self.response(self.get_segment(0))
                self.set_state(SEGMENTED_RESPONSE, self.segmentTimeout)

        else:
            raise RuntimeError("invalid APDU (4)")
389915
protected function send_response() {

        //Check that the returned values are valid
        try {
            if ($this->function->returns_desc != null) {
                $validatedvalues = external_api::clean_returnvalue($this->function->returns_desc, $this->returns);
            } else {
                $validatedvalues = null;
            }
        } catch (Exception $ex) {
            $exception = $ex;
        }

        if (!empty($exception)) {
            $response =  $this->generate_error($exception);
        } else {
            //We can now convert the response to the requested REST format
            if ($this->restformat == 'json') {
                $response = json_encode($validatedvalues);
            } else {
                $response = '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
                $response .= '<RESPONSE>'."\n";
                $response .= self::xmlize_result($validatedvalues, $this->function->returns_desc);
                $response .= '</RESPONSE>'."\n";
            }
        }

        $this->send_headers();
        echo $response;
    }
958880
def send_response(self, code, message=None, size='-'):
        
        # pylint: disable-msg=W0221
        if self._to_log or LOG.isEnabledFor(logging.DEBUG):
            self.log_request(code, size)

        if message is None:
            if code in self.responses:
                message = self.responses[code][0]
            else:
                message = ''

        if self.request_version != 'HTTP/0.9':
            self.wfile.write("%s %d %s\r\n" %
                             ("HTTP/1.1", code, message))
        self.send_header('Server', self.version_string())
        self.send_header('Date', self.date_time_string())
239730
def send_response(self, code, message=None):
        """"""
        self.log_request(code)
        if message is None:
            message = code in self.responses and self.responses[code][0] or ""
        if self.request_version != "HTTP/0.9":
            hdr = "%s %d %s\r\n" % (self.protocol_version, code, message)
            self.wfile.write(hdr.encode("ascii"))
532782
function clientError(err, res) {
  log('error', err.message, { stack: err.stack });
  // They know it's a 400 already, we don't need to repeat the fact that its an error.
  const message = removePrefix(err.message, ':'),
    code = 400;

  sendDefaultResponseForCode(code, message, res);
}
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 ]);
  }
804976
private void sendSomeRequests() {
		ResponseListener responseListener = new MyResponseListener();

		sendCustomUrlRequest(responseListener);
		sendAutoRetryRequest(responseListener);
		downloadImage(responseListener);
		uploadData(responseListener);
		uploadFile(responseListener);
		uploadText(responseListener);
	}
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();
  }
}
773066
function reply(req, res, opts) {
  opts = opts || {};

  return function(statusCode, body) {
    var call = { args: [].slice.call(arguments) };

    // handle single argument replies
    if (typeof statusCode === 'string') {
      body = { message: statusCode };
      statusCode = 200;
    } else if (statusCode instanceof Error) {
      body = statusCode;
      statusCode = 500;
    }

    // handle error objects in replies
    if (body instanceof Error) {
      if (typeof body.statusCode === 'number') {
        statusCode = body.statusCode;
      }
      if (body.expose) {
        body = body.toJSON ? body.toJSON() : { message: body.message };
      } else {
        body = undefined;
      }
    }

    // default message
    if (body === undefined) {
      body = { message: http.STATUS_CODES[statusCode] || 'unknown response' };
    }

    call.statusCode = statusCode;
    call.body = body;

    // allow user to override body before sending
    if (req.sf.responseMessage) {
      call = req.sf.responseMessage(call);

      if (!call) {
        debug('responseMessage handled reply');
        return;
      }

      statusCode = call.statusCode;
      body = call.body;
    }

    var length = 0;
    var type;

    if (body !== undefined) {
      if (Buffer.isBuffer(body)) {
        length = body.length;
      } else if (res.sf && res.sf.produce) {
        type = res.sf.produce.mime;
        body = res.sf.produce.encoder(body);
        length = Buffer.byteLength(body, CHARSET);
      } else {
        type = 'application/json';
        body = encoder[type](body);
        length = Buffer.byteLength(body, CHARSET);
      }
    }

    var noContent = statusCode === 204 || statusCode === 304;

    if (!noContent && !res.headersSent) {
      if (type && !res.getHeader('content-type') ||
        res.getHeader('content-type') !== type) {
        res.setHeader('content-type', type + '; charset=' + CHARSET);
      }

      if (!res.getHeader('content-length') ||
        res.getHeader('content-length') !== length) {
        res.setHeader('content-length', length);
      }

      // add etag header if not already set
      if (opts.etag && body && body.length && !res.getHeader('etag') &&
          req.method === 'GET' && Math.floor(statusCode / 100) === 2) {
        var etag = crypto.createHash('md5').update(body).digest('hex');
        res.setHeader('etag', etag);
      }

      // if cache is fresh set status code to 304
      if (fresh(req.headers, res._headers)) {
        statusCode = 304;
        noContent = true;
      }

      if (noContent) {
        res.removeHeader('content-type');
        res.removeHeader('content-length');
        res.removeHeader('transfer-encoding');
      }
    }

    if (noContent) body = '';

    res.statusCode = statusCode;

    return res.end(req.method === 'HEAD' ? null : body);
  };
}
480381
def _send(self, method, route, data, params, **kwargs):
        """"""
        route = self._fmt_route(route, params)
        log(_("sending {} request to {}").format(method.upper(), route))
        try:
            self.response = getattr(self._client, method.lower())(route, data=data, **kwargs)
        except BaseException as e:  # Catch all exceptions thrown by app
            log(_("exception raised in application: {}: {}").format(type(e).__name__, e))
            raise Failure(_("application raised an exception (rerun with --log for more details)"))
        return self
775746
function() {
        // Send request
        var sendRequest = function() {
          debug('Calling: %s, retry: %s', entry.name, attempts - 1);
          // Make request and handle response or error
          return makeRequest(
            that,
            entry.method,
            url,
            payload,
            query
          ).then(function(res) {
            // If request was successful, accept the result
            debug('Success calling: %s, (%s retries)',
              entry.name, attempts - 1);
            if (monitor) {
              var d = process.hrtime(start);
              monitor.measure([entry.name, 'success'], d[0] * 1000 + d[1] / 1000000);
              monitor.count([entry.name, 'success']);
            }
            if (!_.includes(res.headers['content-type'], 'application/json') || !res.body) {
              debug('Empty response from server: call: %s, method: %s', entry.name, entry.method);
              return undefined;
            }
            return res.body;
          }, function(err) {
            // If we got a response we read the error code from the response
            var res = err.response;
            if (res) {
              // Decide if we should retry
              if (attempts <= that._options.retries &&
                  res.status >= 500 &&  // Check if it's a 5xx error
                  res.status < 600) {
                debug('Error calling: %s now retrying, info: %j',
                  entry.name, res.body);
                return retryRequest();
              }
              // If not retrying, construct error object and reject
              debug('Error calling: %s NOT retrying!, info: %j',
                entry.name, res.body);
              var message = 'Unknown Server Error';
              if (res.status === 401) {
                message = 'Authentication Error';
              }
              if (res.status === 500) {
                message = 'Internal Server Error';
              }
              err = new Error(res.body.message || message);
              err.body = res.body;
              err.code = res.body.code || 'UnknownError';
              err.statusCode = res.status;
              if (monitor) {
                var d = process.hrtime(start);

                var state = 'client-error';
                if (res.statusCode >= 500) {
                  state = 'server-error';
                }
                monitor.measure([entry.name, state], d[0] * 1000 + d[1] / 1000000);
                monitor.count([entry.name, state]);
              }
              throw err;
            }

            // Decide if we should retry
            if (attempts <= that._options.retries) {
              debug('Request error calling %s (retrying), err: %s, JSON: %s',
                entry.name, err, err);
              return retryRequest();
            }
            debug('Request error calling %s NOT retrying!, err: %s, JSON: %s',
              entry.name, err, err);
            if (monitor) {
              var d = process.hrtime(start);
              monitor.measure([entry.name, 'connection-error'], d[0] * 1000 + d[1] / 1000000);
              monitor.count([entry.name, 'connection-error']);
            }
            throw err;
          });
        };

        // Increment attempt count, but track how many we had before.
        attempts += 1;

        // If this is the first retry, ie we haven't retried yet, we make the
        // request immediately
        if (attempts === 1) {
          return sendRequest();
        } else {
          var delay;
          // First request is attempt = 1, so attempt = 2 is the first retry
          // we subtract one to get exponents: 1, 2, 3, 4, 5, ...
          delay = Math.pow(2, attempts - 1) * that._options.delayFactor;
          // Apply randomization factor
          var rf = that._options.randomizationFactor;
          delay *= Math.random() * 2 * rf + 1 - rf;
          // Always limit with a maximum delay
          delay = Math.min(delay, that._options.maxDelay);
          // Sleep then send the request
          return new Promise(function(accept) {
            setTimeout(accept, delay);
          }).then(function() {
            return sendRequest();
          });
        }
      }
1022456
def send_response(self, body, set_content_type=True):
        
        settings = get_settings(self.application, force_instance=True)
        handler = settings[self.get_response_content_type()]
        content_type, data_bytes = handler.to_bytes(body)
        if set_content_type:
            self.set_header('Content-Type', content_type)
            self.add_header('Vary', 'Accept')
        self.write(data_bytes)
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket
1121033
function apiResponded(apiResponse) {
      // Convert XML to JS object
      var parser = new xml2js.Parser({explicitArray:false});
      parser.parseString(apiResponse, function (err, result) {
        // If the method processes the response, give it back
        // Otherwise call the original callback

        if(typeof a.processor !== 'undefined')
          a.processor(result.response, a.callback);
        else
          a.callback(result.response);
      });


    }
81726
public void processResponse(ResponseEvent response) {
    ClientTransaction trans = response.getClientTransaction();
    if (trans == null) {
      return;
    }

    SipTransaction sip_trans = null;

    synchronized (respTransactions) {
      sip_trans = (SipTransaction) respTransactions.get(trans);
    }

    if (sip_trans == null) {
      return;
    }

    if (response.getResponse().getStatusCode() > 199) {
      synchronized (respTransactions) {
        respTransactions.remove(trans);
      }
    }

    // check for listener handling
    MessageListener listener = sip_trans.getClientListener();
    if (listener != null) {
      listener.processEvent(response);
      return;
    }

    // if no listener, use the default blocking mechanism
    synchronized (sip_trans.getBlock()) {
      sip_trans.getEvents().addLast(response);
      sip_trans.getBlock().notifyEvent();
    }
  }
492689
private void completeCall(ClientResponseImpl response) {
        // if we're keeping track, calculate result size
        if (m_perCallStats.samplingProcedure()) {
            m_perCallStats.setResultSize(response.getResults());
        }
        m_statsCollector.endProcedure(response.getStatus() == ClientResponse.USER_ABORT,
                                      (response.getStatus() != ClientResponse.USER_ABORT) &&
                                      (response.getStatus() != ClientResponse.SUCCESS),
                                      m_perCallStats);
        // allow the GC to collect per-call stats if this proc isn't called for a while
        m_perCallStats = null;

        // send the response to the caller
        // must be done as IRM to CI mailbox for backpressure accounting
        response.setClientHandle(m_clientHandle);
        InitiateResponseMessage irm = InitiateResponseMessage.messageForNTProcResponse(m_ciHandle,
                                                                                       m_ccxn.connectionId(),
                                                                                       response);
        m_mailbox.deliver(irm);

        m_ntProcService.handleNTProcEnd(ProcedureRunnerNT.this);
    }
80663
def send_response(self, response):
        
        response_bytes = response.encode(config.CODEC)
        log.debug("About to send reponse: %r", response_bytes)
        self.socket.send(response_bytes)