### zipResults

Zips all the files in the data/ directory and sends the archive

@param {object} req The request object from Express
@param {object} res The respond object from Express
@param {object} gameInfo The game info as in channel
329868
function zipResults(req, res, gameInfo) {
    var archiver, archive;

    archiver = require('archiver');
    archive = archiver('zip');

    archive.on('error', function(err) {
        res.status(500).send({error: err.message});
    });

    res.attachment(gameInfo.info.name + '-data_' +
                   new Date().toISOString() + '.zip');
    archive.pipe(res);
    archive.directory(path.join(gameInfo.dir, 'data'), 'data');
    archive.finalize();
}
583748
private void doResults(HttpServletRequest req, HttpServletResponse resp) throws IOException, JsonGenerationException, JsonMappingException
  {
    Map<String, Object> result = new HashMap<String, Object>();

    String requestIds = req.getParameter("ids");
    if (!isEmpty(requestIds))
    {
      List<Map<String, Object>> requests = new ArrayList<Map<String, Object>>();
      for (String requestId : requestIds.split(","))
      {
        requestId = requestId.trim();
        @SuppressWarnings("unchecked")
        Map<String, Object> requestData = (Map<String, Object>) ms.get(String.format(MiniProfilerFilter.MEMCACHE_KEY_FORMAT_STRING, requestId));
        if (requestData != null)
        {
          Map<String, Object> request = new HashMap<String, Object>();
          request.put("id", requestId);
          request.put("redirect", requestData.get("redirect"));
          request.put("requestURL", requestData.get("requestURL"));
          request.put("timestamp", requestData.get("timestamp"));
          request.put("profile", requestData.get("profile"));
          if (requestData.containsKey("appstatsId"))
          {
            Map<String, Object> appstatsMap = MiniProfilerAppstats.getAppstatsDataFor((String) requestData.get("appstatsId"), maxStackFrames);
            request.put("appstats", appstatsMap != null ? appstatsMap : null);
          } else
          {
            request.put("appstats", null);
          }
          requests.add(request);
        }
      }
      result.put("ok", true);
      result.put("requests", requests);
    } else
    {
      result.put("ok", false);
    }

    resp.setContentType("application/json");
    resp.setHeader("Cache-Control", "no-cache");

    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.writeValue(resp.getOutputStream(), result);
  }
167212
function(req, res) {
        if (!searchIdx) return res();
        var results = searchIdx.search(req.term)
          .map(function(result) {
            return {
              label: files[result.ref].title,
              value: files[result.ref]
            };
          });

        res(results);
      }
1334168
function zipDirectory(directories, dest, callback) {
        var archive = archiver.create('zip', {gzip: false});

        // Where to write the file
        var destStream = fs.createWriteStream(dest);

        archive.on('error', function(err) {
            this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Archiving failed', err));
        });

        archive.on('entry', function(file) {
            // do nothing
        });

        destStream.on('error', function(err) {
            this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'WriteStream failed', err));
        });

        destStream.on('close', function() {
            var size = archive.pointer();
            gutil.log(PLUGIN_NAME, gutil.colors.green('Created ' + dest + ' (' + size + ' bytes)'));
            callback();
        });

        archive.pipe(destStream);

        directories.forEach(function(directory) {
            if (fs.lstatSync(directory.src).isDirectory()) {
              archive.directory(directory.src, directory.dest);
            } else {
              this.emit('error', new gutil.PluginError(PLUGIN_NAME, directory.src + ' is not a valid directory'));
              return;
            }
        });

        archive.finalize();
    }
404420
private void listArchive(Archive archive,
                               RelativeDirectory subdirectory,
                               Set<JavaFileObject.Kind> fileKinds,
                               boolean recurse,
                               ListBuffer<JavaFileObject> resultList) {
        // Get the files directly in the subdir
        List<String> files = archive.getFiles(subdirectory);
        if (files != null) {
            for (; !files.isEmpty(); files = files.tail) {
                String file = files.head;
                if (isValidFile(file, fileKinds)) {
                    resultList.append(archive.getFileObject(subdirectory, file));
                }
            }
        }
        if (recurse) {
            for (RelativeDirectory s: archive.getSubdirectories()) {
                if (subdirectory.contains(s)) {
                    // Because the archive map is a flat list of directories,
                    // the enclosing loop will pick up all child subdirectories.
                    // Therefore, there is no need to recurse deeper.
                    listArchive(archive, s, fileKinds, false, resultList);
                }
            }
        }
    }
1064345
function (info, cb) {
            // Default to a binary request
            var options = info.src;
            var dest = info.dest;

            // Request the url
            var req = request(options);

            // On error, callback
            req.on('error', cb);

            // On response, callback for writing out the stream
            req.on('response', function handleResponse (res) {
                // Assert the statusCode was good
                var statusCode = res.statusCode;
                if (statusCode < 200 || statusCode >= 300) {
                  return cb(new Error('Fetching ' + JSON.stringify(options) + ' failed with HTTP status code ' + statusCode));
                }

                // Otherwise, write out the content
                var destdir = path.dirname(dest);
                grunt.file.mkdir(destdir);
                var writeStream = fs.createWriteStream(dest);
                // Use `req` as the source of data https://github.com/request/request/blob/v2.51.1/request.js#L1255-L1267
                // DEV: This is to pipe out gunzipped data
                var dataStream = req;
                dataStream.pipe(writeStream);

                // When the stream errors or completes, exit
                writeStream.on('error', cb);
                writeStream.on('close', cb);
            });
        }
1123042
function makeRequest () {
    request = self.request.apply(null, args);
    requestMiddleware.use(request);
    request.on("response", function (response) {
      var contentEncoding, gzipper;

      //Only cache successful responses
      if (response.statusCode >= 200 && response.statusCode < 300) {
        response.on('error', function (error) {
          self.handleError(error);
        });
        fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) {
          if (error) self.handleError(error);
        });

        responseWriter = fs.createWriteStream(self.cacheDirectory + key);

        responseWriter.on('error', function (error) {
          self.handleError(error);
        });

        contentEncoding = response.headers['content-encoding'] || '';
        contentEncoding = contentEncoding.trim().toLowerCase();

        if (contentEncoding === 'gzip') {
          response.on('error', function (error) {
            responseWriter.end();
          });
          response.pipe(responseWriter);
        } else {
          gzipper = zlib.createGzip();
          response.on('error', function (error) {
            gzipper.end();
          });
          gzipper.on('error', function (error) {
            self.handleError(error);
            responseWriter.end();
          });
          responseWriter.on('error', function (error) {
            response.unpipe(gzipper);
            gzipper.end();
          });
          response.pipe(gzipper).pipe(responseWriter);
        }
      }
    });
    self.emit("request", args[0]);
  }
505633
function(req, res) {
            var models = [];
            for (modelName in onmModelDictionary) {
                models.push({
                    modelName: modelName,
                    modelPackage: onmModelDictionary[modelName].package
                });
            }
            res.send(200, models);
        }
1085153
function execute(req, res) {
  var proxy = req.exec ? req.exec.proxy : this.proxy;
  res.send(null, proxy(req, res));
}
1347703
function(operation, res) {
      var that = this;
      var method = res.req.method;

      return operation.then(function(doc) {
        if (method === 'POST') {
          if (that._path && (that._key || that._index)) {
            res.header('Location', '/' + that._path + '/' + doc[that._key || that._index]);
          }

          return res.status(201).json(doc);
        }

        return res.status(200).json(doc);
      }, function(err) {
        console.error(err.message);

        if (method === 'POST' || method === 'PUT') {
          return res.status(409).end();
        }

        if (method === 'GET') {
          res.status(404).end();
        }

        return res.status(500).end();
      });
    }
1013323
function execute(req, res) {
  var value = req.db.getKey(req.args[0], req);
  if(value === undefined) return res.send(null, null);
  var buf = dump(
    {value: value}, value.rtype || Constants.TYPE_NAMES.STRING, null);
  res.send(null, buf);
}
259474
function(req, res) {
            var name = req.params.name;
            var time = parseInt(req.params.time);
            if (!time && time !== 0) {
                return res.send(400, "invalid timestamp.");
            }
            var messages = [];
            this.readMessages(name, time, function(message) {
                if (message) {
                    messages.push(message);
                } else {
                    res.send(messages);
                }
            })
        }
802278
function execute(req, res) {
  Persistence.save(this.state.store, this.state.conf);
  res.send(null, Constants.OK);
}
1043811
function shouldCompress (req, res) {
  var type = res.getHeader('Content-Type')

  if (type === undefined || !compressible(type)) {
    debug('%s not compressible', type)
    return false
  }

  return true
}
285310
function handleUpdate(req, res) {
	var id = req.params.id;
	var value = req.params.value;
	addCache(id, value);
	data = {id:id, value:value};
	console.log('Update:', id, value, data);
	io.sockets.emit('update', data);	// or broadcastJSONUpdate
	res.send(value);
}
465187
function (req, res) {
		LOG.warn('handle_request');

		// attach custom res methods (borrowed from express)
		res = UTIL.mixin(res, response);

		LOG.sys('HTTP req received, header', 'SR.REST');
		LOG.sys(req.headers, 'SR.REST');
		
		var content_type = req.headers['content-type'];

		// NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly
		if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { 
			LOG.warn('parsing form request...', 'SR.REST');
			route(req, res);
			return;
		}
		
		// temp buffer for incoming request
		var data = '';
		var JSONobj = undefined;
		
		req.on('data', function (chunk) {
			data += chunk;
		});

		req.on('end', function () {
			
			var JSONobj = undefined;
			
			try {
				if (data !== '') {
						
					if (content_type.startsWith('application/x-www-form-urlencoded')) {
						JSONobj = qs.parse(data);
					} else if (content_type.startsWith('application/json')) {
						JSONobj = UTIL.convertJSON(decodeURIComponent(data));
					} else if (content_type.startsWith('application/sdp')) {
						JSONobj = data;
					} else {
						var msg = 'content type not known: ' + content_type;
						LOG.warn(msg, 'SR.REST');
						SR.REST.reply(res, msg);
						//res.writeHead(200, {'Content-Type': 'text/plain'});
						//res.end(msg);
						return;
					}
				}
			} catch (e) {
				var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type;
				LOG.error(msg, 'SR.REST');
				//res.writeHead(200, {'Content-Type': 'text/plain'});
				//res.end(msg);
				SR.REST.reply(res, msg);
				return;
			}

			route(req, res, JSONobj);
		})
	}
219757
function execute(req, res) {
  res.send(null, this.info.toString(req.args[0] ? '' + req.args[0] : null));
}