http://channels.readthedocs.io/en/stable/asgi/www.html#response
354087
def get_message(self, more_content):
        '''
        
        '''
        return {
            'status': self.status,
            'content': self.body,
            'headers': self._parse_headers(),
            'more_content': more_content
        }
1252464
function() {
      var waitForLoaded = this.waitForLoaded;

      /** Index page. */
      app.get("/", function(request, response) {
        response.render("index", { hostname: hostname, port: port });
      });

      /** Send an open request, url is provided via query parameter url. */
      app.get("/open/*", function(request, response) {
        var url     = request.query.url,
            timeout = parseInt(request.query.timeout, 10) || TIMEOUT,
            id, entry, waitCallback;

        if (url) {
          if ( !connections) {
            console.log("   error -".red, "No browsers connected to open".yellow, url);
            return response.json({ success: false, error: "No browsers connected to open " + url });
          }

          // broadcast clear request for the first time
          if ( !clear && !Object.keys(urlData).length) {
            io.sockets.emit("clear");
            clear = true;
          }

          id    = crypto.createHash("md5").update(url).digest("hex");
          entry = { type: "open", success: true, id: id, url: url, timeout: timeout };
          io.sockets.emit("open", entry);
          urlData[id]  = { id: id, timeout: timeout, url: url, counter: connections };

          setTimeout(waitForLoaded(id, url, entry, response), WAIT_TIMEOUT);
          console.log("   info  -".cyan, "open".yellow, JSON.stringify(entry));
        } else {
          response.json({ success: false, error: "Invalid url" });
        }
      });

      /** Send a close request, url is provided via query parameter url. */
      app.get("/close/*", function(request, response) {
        var url = request.query.url, id, entry;

        if (url) {
          id    = crypto.createHash("md5").update(url).digest("hex");
          if (urlData[id]) {
            entry = { type: "close", id: id, url: url };
            io.sockets.emit("close", entry);
            console.log("   info  -".cyan, "close".yellow, JSON.stringify(entry));
            delete urlData[id];
          }
        } else {
          entry = {};
        }
        response.json(entry);
      });

      /** Send clear request to all browsers - close all open urls. */
      app.get("/clear/*", function(request, response) {
        io.sockets.emit("clear");
        console.log("   info  -".cyan, "clear".yellow);
        response.json({ success: true });
      });

      /** Return number of connections connecting to InsFrame */
      app.get("/connections", function(request, response) {
        response.json({ connections: connections });
      });
    }
332053
def respond_json(ctx, data, code = None, headers = [], json_dumps_default = None, jsonp = None):
    
    if isinstance(data, collections.Mapping):
        # Remove null properties as recommended by Google JSON Style Guide.
        data = type(data)(
            (name, value)
            for name, value in data.iteritems()
            if value is not None
            )
        error = data.get('error')
        if isinstance(error, collections.Mapping):
            error = data['error'] = type(error)(
                (name, value)
                for name, value in error.iteritems()
                if value is not None
                )
    else:
        error = None
    if jsonp:
        content_type = 'application/javascript; charset=utf-8'
    else:
        content_type = 'application/json; charset=utf-8'
    if error:
        code = code or error['code']
        assert isinstance(code, int)
        response = webob.exc.status_map[code](headers = headers)
        response.content_type = content_type
        if code == 204:  # No content
            return response
        if error.get('code') is None:
            error['code'] = code
        if error.get('message') is None:
            title = errors_title.get(code)
            title = ctx._(title) if title is not None else response.status
            error['message'] = title
    else:
        response = ctx.req.response
        response.content_type = content_type
        if code is not None:
            response.status = code
        response.headers.update(headers)
    # try:
    #     text = json.dumps(data, encoding = 'utf-8', ensure_ascii = False, indent = 2)
    # except UnicodeDecodeError:
    #     text = json.dumps(data, ensure_ascii = True, indent = 2)

    if json_dumps_default is None:
        text = json.dumps(data)
    else:
        text = json.dumps(data, default = json_dumps_default)
    text = unicode(text)
    if jsonp:
        text = u'{0}({1})'.format(jsonp, text)
    response.text = text
    return response
82094
def ReceiveSOAP(self, readerclass=None, **kw):
        '''
        '''
        if self.ps: return self.ps
        if not self.IsSOAP():
            raise TypeError(
                'Response is "%s", not "text/xml"' % self.reply_headers.type)
        if len(self.data) == 0:
            raise TypeError('Received empty response')

        self.ps = ParsedSoap(self.data, 
                        readerclass=readerclass or self.readerclass, 
                        encodingStyle=kw.get('encodingStyle'))

        if self.sig_handler is not None:
            self.sig_handler.verify(self.ps)

        return self.ps
971125
def _ok(self, packets=None, headers=None, b64=False):
        """"""
        if packets is not None:
            if headers is None:
                headers = []
            if b64:
                headers += [('Content-Type', 'text/plain; charset=UTF-8')]
            else:
                headers += [('Content-Type', 'application/octet-stream')]
            return {'status': '200 OK',
                    'headers': headers,
                    'response': payload.Payload(packets=packets).encode(b64)}
        else:
            return {'status': '200 OK',
                    'headers': [('Content-Type', 'text/plain')],
                    'response': b'OK'}
924347
def displayResponse(request, openid_response):
    
    s = getServer(request)

    # Encode the response into something that is renderable.
    try:
        webresponse = s.encodeResponse(openid_response)
    except EncodingError, why:
        # If it couldn't be encoded, display an error.
        text = why.response.encodeToKVForm()
        return direct_to_template(
            request,
            'server/endpoint.html',
            {'error': cgi.escape(text)})

    # Construct the appropriate django framework response.
    r = http.HttpResponse(webresponse.body)
    r.status_code = webresponse.code

    for header, value in webresponse.headers.iteritems():
        r[header] = value

    return r
982234
function(link, cb){
            var options = {
                host: urlArr.hostname,
                port: urlArr.port,
                path: urlArr.path+"?link="+encodeURIComponent(link),
                method: 'GET'
            };
            
            var getRequest = protocol.request(options, function(res){
                var result = "";
                
                if(res.statusCode === 200){
                    res.on('error', function(error) {
                        if(typeof cb === "function")
                            cb(error);
                    });

                    res.on('data', function (chunk) {
                        result += chunk;
                    });

                    res.on('end', function (chunk) {
                        if(typeof cb === "function"){
                            var resultObj = JSON.parse(result);
                            var err = (resultObj.status === "error") ? resultObj["msg"] : null
                            cb(err, resultObj);
                        }                        
                    });
                }
                else{
                    if(typeof cb === "function")
                        cb("Request return HTTP "+res.statusCode);
                }
            });
            
            getRequest.end();
        }
97737
def html_with_encoding(self, url, timeout=None, encoding="utf-8"):
        
        response = self.get_response(url, timeout=timeout)
        if response:
            return self.decoder.decode(response.content, encoding)[0]
        else:
            return None
168642
function (res_obj, data, conn) {

		// check if we should return empty response
		if (typeof res_obj === 'undefined') {
			SR.REST.reply(res, {});
			return true;
		}

		// check for special case processing (SR_REDIRECT)
		if (res_obj[SR.Tags.UPDATE] === 'SR_REDIRECT' && res_obj[SR.Tags.PARA] && res_obj[SR.Tags.PARA].url) {

			var url = res_obj[SR.Tags.PARA].url;
			LOG.warn('redirecting to: ' + url, l_name);

			/*
			res.writeHead(302, {
				'Location': url
			});
			res.end();
			*/

			// redirect by page 
			// TODO: merge with same code in FB.js
			var page =
				'<html><body><script>\n' +
				'if (navigator.appName.indexOf("Microsoft") != -1)\n' +
				'    window.top.location.href="' + url + '";\n' +
				'else\n' +
				'	 top.location.href="' + url + '";\n' +
				'</script></body></html>\n';

			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.end(page);

			return true;
		}
		
		// check for special case processing (SR_HTML)
		if (res_obj[SR.Tags.UPDATE] === 'SR_HTML' && res_obj[SR.Tags.PARA].page) {
			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.end(res_obj[SR.Tags.PARA].page);
			return true;
		}

		// check for special case processing (SR_DOWNLOAD)
		if (res_obj[SR.Tags.UPDATE] === 'SR_DOWNLOAD' && res_obj[SR.Tags.PARA].data && res_obj[SR.Tags.PARA].filename) {

			var filename = res_obj[SR.Tags.PARA].filename;
			LOG.warn('allow client to download file: ' + filename, l_name);

			var data = res_obj[SR.Tags.PARA].data;
			res.writeHead(200, {
				'Content-Type': 'application/octet-stream',
				'Content-Disposition': 'attachment; filename=' + filename,
				'Content-Length': data.length
			});
			res.end(data);
			return true;
		}

		// check for special case processing (SR_RESOURCE)
		if (res_obj[SR.Tags.UPDATE] === 'SR_RESOURCE' && res_obj[SR.Tags.PARA].address) {

			var file = res_obj[SR.Tags.PARA].address;
						
			// check if resource exists & its states
			SR.fs.stat(file, function (err, stats) {
										
				var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
				
				if (err) {			
					LOG.error(err, l_name);
					res.writeHead(404, resHeader);
					res.end();
					return;
				}
				
				var extFilename = file.match(/[\W\w]*\.([\W\w]*)/)[1];
				if (typeof extFilename === 'string')
					extFilename = extFilename.toLowerCase();
				
				// default to 200 status
				var resStatus = 200;
				resHeader['Accept-Ranges'] = 'bytes';
				resHeader['Cache-Control'] = 'no-cache';
				resHeader['Content-Length'] = stats.size;
				
				if (l_extList[extFilename]) {
					resHeader['Content-Type'] = l_extList[extFilename];
				};
				
				var start = undefined;
				var end = undefined;
				
				// check if request range exists (e.g., streaming media such as webm/mp4) to return 206 status
				// see: https://delog.wordpress.com/2011/04/25/stream-webm-file-to-chrome-using-node-js/						
				if (req.headers.range) {
					var range = req.headers.range.split(/bytes=([0-9]*)-([0-9]*)/);
					resStatus = 206;
					
					start = parseInt(range[1] || 0);
					end = parseInt(range[2] || stats.size - 1);
					
					if (start > end) {
						LOG.error('stream file start > end. start: ' + start + ' end: ' + end, l_name);
						var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
						res.writeHead(404, resHeader);
						res.end();
						return;  // abnormal if we've reached here
					}
					
					LOG.debug('requesting bytes ' + start + ' to ' + end + ' for file: ' + file, l_name);
							 
					resHeader['Connection'] = 'close';
					resHeader['Content-Length'] = end - start + 1;
					resHeader['Content-Range'] = 'bytes ' + start + '-' + end + '/' + stats.size;
					resHeader['Transfer-Encoding'] = 'chunked';
				} 
				// otherwise assume it's a regular file
				else if (l_directExt.hasOwnProperty(extFilename)) {
					// NOTE: code below will cause the file be downloaded in a "Save As.." format
					// (instead of being displayed directly), we only want this behavior for certain file types (such as .zip)				
					var filename = file.replace(/^.*[\\\/]/, '')
					LOG.warn('requesting a file: ' + filename, l_name);
					resHeader['Content-Disposition'] = 'attachment; filename=' + filename;
				}
				
				LOG.sys('SR_RESOURCE header:', l_name);
				LOG.sys(resHeader);
				res.writeHead(resStatus, resHeader);

				// start streaming
				SR.fs.createReadStream(file, {
					flags: 'r',
					start: start,
					end: end
				}).pipe(res);			
			});
			
			return true;
		}

		var origin = _getOrigin(req);

		// send back via res object if hadn't responded yet
		if (res.headersSent === false) {
			// NOTE: cookie may be undefined;
			SR.REST.reply(res, data, {
				origin: origin,
				cookie: cookie
			});
		}
		else {
			LOG.error('HTTP request has already responded (cannot respond twice)', l_name);
			LOG.stack();
		}

		return true;
	}
18138
function parseGitHubTrendingRepos(err, body) {
    if (err) { return tubesio.finish(err); }

    // Load the raw HTML into a cheerio object so we can traverse
    // the data using CSS selectors ala jQuery.
    var $ = cheerio.load(body),
        result = {
            title: $('title').text(),
            trending: []
        };

    // Iterate over the trending repositories extracting the names
    // and hyperlinks.
    $('#trending-repositories > ol > li').each(function (i, e) {
        result.trending.push({
            name: us.trim($(e).find('h3').text()),
            href: 'https://github.com' + $(e).find('a').last().attr('href')
        });
    });

    // Return our results object
    tubesio.finish(result); 
}
655708
function(serverResponse, {bidderRequest}) {
    serverResponse = serverResponse.body;
    const bids = [];
    if (!serverResponse || serverResponse.error) {
      let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`;
      if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; }
      utils.logError(errorMessage);
      return bids;
    }

    if (serverResponse.tags) {
      serverResponse.tags.forEach(serverBid => {
        const rtbBid = getRtbBid(serverBid);
        if (rtbBid) {
          if (rtbBid.cpm !== 0 && includes(this.supportedMediaTypes, rtbBid.ad_type)) {
            const bid = newBid(serverBid, rtbBid, bidderRequest);
            bid.mediaType = parseMediaType(rtbBid);
            bids.push(bid);
          }
        }
      });
    }

    if (serverResponse.debug && serverResponse.debug.debug_info) {
      let debugHeader = 'AppNexus Debug Auction for Prebid\n\n'
      let debugText = debugHeader + serverResponse.debug.debug_info
      debugText = debugText
        .replace(/(<td>|<th>)/gm, '\t') // Tables
        .replace(/(<\/td>|<\/th>)/gm, '\n') // Tables
        .replace(/^<br>/gm, '') // Remove leading <br>
        .replace(/(<br>\n|<br>)/gm, '\n') // <br>
        .replace(/<h1>(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1
        .replace(/<h[2-6]>(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers
        .replace(/(<([^>]+)>)/igm, ''); // Remove any other tags
      utils.logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction');
      utils.logMessage(debugText);
    }

    return bids;
  }
967946
def html?
      fetch_headers unless fetched_headers?
      response = @get_response || @head_response
      return false if fetch_failed?
      return false unless response
      return false unless response.success?
      return false unless response["content-type"]
      response["content-type"].include? "text/html"
    end
291457
def reply_bytes(self, request):
        """"""
        flags = struct.pack("<I", self._flags)
        payload_type = struct.pack("<b", 0)
        payload_data = bson.BSON.encode(self.doc)
        data = b''.join([flags, payload_type, payload_data])

        reply_id = random.randint(0, 1000000)
        response_to = request.request_id

        header = struct.pack(
            "<iiii", 16 + len(data), reply_id, response_to, OP_MSG)
        return header + data
255268
async function _html(req, res) {
  const { queueName, queueHost, state } = req.params;
  const {Queues} = req.app.locals;
  const queue = await Queues.get(queueName, queueHost);
  const basePath = req.baseUrl;
  if (!queue) return res.status(404).render('dashboard/templates/queueNotFound', {basePath, queueName, queueHost});

  if (!isValidState(state, queue.IS_BEE)) return res.status(400).json({ message: `Invalid state requested: ${state}` });

  let jobCounts;
  if (queue.IS_BEE) {
    jobCounts = await queue.checkHealth();
    delete jobCounts.newestJob;
  } else {
    jobCounts = await queue.getJobCounts();
  }

  const page = parseInt(req.query.page, 10) || 1;
  const pageSize = parseInt(req.query.pageSize, 10) || 100;

  const startId = (page - 1) * pageSize;
  const endId = startId + pageSize - 1;

  let jobs;
  if (queue.IS_BEE) {
    const page = {};

    if (['failed', 'succeeded'].includes(state)) {
      page.size = pageSize;
    } else {
      page.start = startId;
      page.end = endId;
    }

    jobs = await queue.getJobs(state, page);

    // Filter out Bee jobs that have already been removed by the time the promise resolves
    jobs = jobs.filter((job) => job);
  } else {
    jobs = await queue[`get${_.capitalize(state)}`](startId, endId);
  }

  let pages = _.range(page - 6, page + 7)
    .filter((page) => page >= 1);
  while (pages.length < 12) {
    pages.push(_.last(pages) + 1);
  }
  pages = pages.filter((page) => page <= _.ceil(jobCounts[state] / pageSize));

  return res.render('dashboard/templates/queueJobsByState', {
    basePath,
    queueName,
    queueHost,
    state,
    jobs,
    jobsInStateCount: jobCounts[state],
    disablePagination: queue.IS_BEE && (state === 'succeeded' || state === 'failed'),
    currentPage: page,
    pages,
    pageSize,
    lastPage: _.last(pages)
  });
}
1302902
function(xhr) {
    var response = {
        headers: {},
        statusCode: xhr.status
    };

    var headerPairs = xhr.getAllResponseHeaders().split('\u000d\u000a');
    for (var i = 0; i < headerPairs.length; i++) {
        var headerPair = headerPairs[i],
            index = headerPair.indexOf('\u003a\u0020');

        if (index > 0) {
            var key = headerPair.substring(0, index);
            var val = headerPair.substring(index + 2);
            response.headers[key.toLowerCase()] = val;
        }
    }

    return response;
}
415043
def get_response(self, environ=None):
        """"""
        response = super(SameContentException, self).get_response(
            environ=environ
        )
        if self.etag is not None:
            response.set_etag(self.etag)
        if self.last_modified is not None:
            response.headers['Last-Modified'] = http_date(self.last_modified)
        return response
255681
def curl
      puts "fetching #{@uri.to_s}".green.on_black
      start_time = Time.now
      begin
        c = @c
        c.url = @uri.to_s
        c.perform
        end_time = Time.now
        case c.response_code
        when 200 then
          page = Page.new(@uri, response_code: c.response_code,
                                response_head: c.header_str,
                                response_body: c.body_str,
                                response_time: ((end_time-start_time)*1000).round,
                                crawled_time: (Time.now.to_f*1000).to_i)
        when 300..307 then
          page = Page.new(@uri, response_code: c.response_code,
                                response_head: c.header_str,
                                response_body: c.body_str,
                                response_time: ((end_time-start_time)*1000).round,
                                redirect_url:  c.redirect_url)
        when 404 then
          page = Page.new(@uri, response_code: c.response_code,
                                response_time: ((end_time-start_time)*1000).round)
        end
      rescue Exception => e
        puts e.inspect
        puts e.backtrace
      end
    end