Catch all requests, if any are for .less files, recompile on the fly and
send back a CSS response
489842
function(req, res, next) {
        var parsed = require("url").parse(req.url);
        if (parsed.pathname.match(/\.less$/)) {
            return less(parsed.pathname).then(function(o) {
                res.setHeader("Content-Type", "text/css");
                res.end(o.css);
            });
        }
        next();
    }
1296698
function(url, done) {
  var receive = function(res) {
    if (res.statusCode != 200) {
      var msg = 'Failed to load ' + url + '\n' +
        'HTTP responce status code: ' + res.statusCode
      printError(msg)
      done(new Error(msg))
    } else {
      var content = ''
      res
        .on('end', function() {
          done(null, content)
        })
        .on('readable', function() {
          var chunk = res.read()
          content += chunk.toString()
        })
    }
  }

  try {
    require(url.indexOf('https') === 0 ? 'https' : 'http').get(url, receive).on('error', done)
  } catch (e) {
    done(e)
  }
}
774929
function processFile() {
  const options = {};
  return (file, callback) => {
    const data = csso.minify(file.data, options).css;
    async.nextTick(callback, null, Object.assign({}, file, { data }));
  };
}
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();
  }
}
1035812
function respond(res, code, data) {
		return res.status(code).send(data || http.STATUS_CODES[code]);
	}
55302
function processNormalizedResponse(normalized, req, res){
  if(!delay){
    // stash normalized in cache and return normalized
    console.log('\n\nDone!\n\n')
    if(!req.session.media_cache) req.session.media_cache = normalized
    // console.dir(req.session.media_cache)
    return res.json(normalized)
  }
  else{
    setTimeout(function(){
      // We have to check again for delay due to race conditions.
      if(delay) return processNormalizedResponse(normalized, req, res)
    },10)
  }
}
956800
function readCSSFile(files = []) {

		if (OPTIONS.verbose) { console.log(info('Input - CSS File : ' + files[readCSSFileCount])); }

		if (validUrl.isUri(files[readCSSFileCount])) {
			request({
				url: files[readCSSFileCount],
				method: "GET"
			}, function(err, headRes, body) {
				if (headRes !== undefined) {
					var size = headRes.headers['content-length'];
					
					if (size == undefined || size == 0) {
						filesizeKB = kiloByteLength(body);
					} else {
						filesizeKB = size/1000;	
					}
				} else {
					var size = kiloByteLength(body);
					filesizeKB = size/1000;
				}

				
				stats.files.css.push({
					"filename" : files[readCSSFileCount],
					"filesizeKB" : filesizeKB
				});
				stats.before.totalFileSizeKB += filesizeKB;

			});
		} else {
			filesizeKB = getFilesizeInKiloBytes(files[readCSSFileCount]);

			stats.files.css.push({
				"filename" : files[readCSSFileCount],
				"filesizeKB" : filesizeKB
			});
			stats.before.totalFileSizeKB += filesizeKB;
		}


		summary.files.input.push(files[readCSSFileCount]);


		if (validUrl.isUri(files[readCSSFileCount])) {
			
		  request(files[readCSSFileCount], function (err, response, body) {

		  	if (response === undefined) {

		  		//try again
		  		request(files[readCSSFileCount], function (err, response, body) {

		  			if (response.statusCode == 200) {
				    	dataCSSIn.push(body);

				    	readCSSFileCount += 1;

							if (readCSSFileCount < files.length) {

								CPEVENTS.emit('CSS_READ_AGAIN');	
							} else {

								CPEVENTS.emit('CSS_READ_END');
							}

				    } else {
							CPEVENTS.emit('CSS_READ_ERROR');
							console.log(error("CSS File read error: check your CSS files and please try again."));
							console.log(err)
							process.exit(1);
				    }

		  		});


		  	} else if (response.statusCode == 200) {
		    	dataCSSIn.push(body);

		    	readCSSFileCount += 1;

					if (readCSSFileCount < files.length) {

						CPEVENTS.emit('CSS_READ_AGAIN');	
					} else {

						CPEVENTS.emit('CSS_READ_END');
					}

		    } else {
					CPEVENTS.emit('CSS_READ_ERROR');
					console.log(error("CSS File read error: check your CSS files and please try again."));
					console.log(err)
					process.exit(1);
		    }
			});

		} else {


			readStream = fs.createReadStream(files[readCSSFileCount], 'utf8');

			readStream.on('data', function(chunk) { 
				dataCSSIn.push(chunk);

			}).on('end', function() {
				readCSSFileCount += 1;
				if (readCSSFileCount < files.length) {

					CPEVENTS.emit('CSS_READ_AGAIN');	
				} else {
					CPEVENTS.emit('CSS_READ_END');
				}
				
			}).on('error', function(e) {
				CPEVENTS.emit('CSS_READ_ERROR');
				console.log(error("CSS File read error: Something went wrong while reading the file(s), check your CSS files and please try again."));
				console.log(e);
				process.exit(1);
			});

		} //end of url check
	}
614926
function (name, req, onLoad, config) {
//>>excludeStart("exclude", pragmas.optimizeSave);
			var that = this,
				url = req.toUrl(name);

			// load content (css code)
			text.get(url, function (data) {

				if (config.isBuild) {
					// in build-time: remember path to from generic.css to baseDir
					if (!_genericCssToRootPath) {
						_genericCssToRootPath = config.genericCssToRootPath;
					}

					_buildMap[name] = { path: url, data: data, write: config.writeGenericCss };

				} else {
					// in runtime (non-optimized): include css as style tag into document's head
					var imports = [],
						css = _replaceCssRelativeUrls(data, url, imports);

					if (imports.length) {
						// the css file has @import directives, we have to load each imported css-file explicitly,
						// as browsers support @import directives only at the beginning of style tag.
						var ctx = {
							name: name,
							css: css,
							waiting: imports.length,
							loaded: {}
						};
						imports.forEach(function (url) {
							console.log("DEBUG: Loading css-file from @import: " + url);
							text.get(url, function (data) {
								var importUrl;
								ctx.loaded[url] = data;
								ctx.waiting -= 1;
								if (ctx.waiting === 0) {
									// last script has been loaded
									for(importUrl in ctx.loaded) {
										ctx.css = ctx.css.replace("/*>>import: " + url + "*/", ctx.loaded[url]);
									}
									that.helper.appendCssToPage(ctx.css, ctx.name);
									onLoad();
								}
							});
							return;
						});
					} else {
						that.helper.appendCssToPage(css, name);
					}
				}
				onLoad();
				return;
			});
//>>excludeEnd("exclude");
			onLoad();
		}
892519
def handle_purge(environ, start_response):
    
    from utils import is_valid_security, get_cached_files
    from settings import DEBUG
    server = environ['SERVER_NAME']
    try:
        request_uri = get_path(environ)
        path_and_query = request_uri.lstrip("/")
        query_string = environ.get('QUERY_STRING', '')
        if is_valid_security('PURGE', query_string):
            cached_files = get_cached_files(path_and_query, server)
            for i in cached_files:
                try:
                    os.remove(i)
                except OSError as e:
                    return do_500(environ, start_response, e.message)
            start_response("204 No Content", [])
            return []
        else:
            return do_405(environ, start_response)
    except Http404 as e:
        return do_404(environ, start_response, e.message, DEBUG)
476378
function (err, res) {
      if (err) {
        cb(err)
      } else {
        res.stats.includedFiles.forEach(function (file) {
          compiler.emit('dependency', file)
        })
        cb(null, res.css.toString())
      }
    }
489468
def _handle_response(self, url, res, suppress_empty=True):
        
        result = Connection._handle_response(self, url, res, suppress_empty)
        if 'X-Rate-Limit-Time-Reset-Ms' in res.headers:
            self.rate_limit = dict(ms_until_reset=int(res.headers['X-Rate-Limit-Time-Reset-Ms']),
                                   window_size_ms=int(res.headers['X-Rate-Limit-Time-Window-Ms']),
                                   requests_remaining=int(res.headers['X-Rate-Limit-Requests-Left']),
                                   requests_quota=int(res.headers['X-Rate-Limit-Requests-Quota']))
            if self.rate_limiting_management:
                if self.rate_limiting_management['min_requests_remaining'] >= self.rate_limit['requests_remaining']:
                    if self.rate_limiting_management['wait']:
                        sleep(ceil(float(self.rate_limit['ms_until_reset']) / 1000))
                    if self.rate_limiting_management.get('callback_function'):
                        callback = self.rate_limiting_management['callback_function']
                        args_dict = self.rate_limiting_management.get('callback_args')
                        if args_dict:
                            callback(args_dict)
                        else:
                            callback()

        return result
101551
async function reprime(dir) {
  // start the new files and mtimes caches (eventually to replace the ones on the object)
  const files = {};
  const mtimes = {};

  // define resursive function to load directory contents
  let totalSize = 0;
  const load = dirName => Promise.map(sander.readdir(dirName), async _name => {
    const name = path.resolve(dirName, _name);
    const relativeName = path.relative(dir._absolutePath, name);

    // find out when the file last changed on disk
    const stat = await sander.lstat(name);
    const diskMtime = stat.mtime.getTime();

    // find out when our cached copy last changed (if any)
    const lastKnownMtime = dir._mtimes.get(relativeName);

    if (stat.isFile()) {
      // skip this file if it's excluded by the matcher
      if (!dir._match(relativeName)) return;

      // get the cached content (if any)
      const cachedContent = dir._files.get(relativeName);

      // decide what we're going to go with (the one from the cache or the one on disk)
      let content;
      let mtime;
      // console.log('\nfile', name);
      // console.log('  lastKnownMtime', lastKnownMtime);
      // console.log('       diskMtime', diskMtime);
      // console.log();

      if (cachedContent && diskMtime <= lastKnownMtime) {
        // cached file exists and is new enough; use it
        // console.log('cache hit!!', relativeName);
        mtime = lastKnownMtime;
        content = cachedContent;
      }
      else {
        // no cached file (or too old); read the file from disk
        // console.log('cache miss:', relativeName);
        mtime = diskMtime;
        content = await sander.readFile(name);
      }

      // verify adding this file doesn't take us over the filesize limit
      totalSize += content.length;
      if (totalSize > dir._limit) {
        throw new Error(
          `Contents of directory exceed ${prettyBytes(dir._limit)} limit: ${dir._absolutePath}`
          );
      }

      // update the new caches with this file's content and mtime
      files[relativeName] = content;
      mtimes[relativeName] = mtime;
    }

    // if it's a directory, recurse into it
    else if (stat.isDirectory()) await load(name);

    // if it's something weird, error out
    else throw new Error(`Not a file or directory: ${name}`);
  });

  // start recursive load
  try {
    await load(dir._absolutePath);
  }
  catch (error) {
    // create the base directory if it doesn't exist
    if (error.code === 'ENOENT' && error.path === dir._absolutePath) {
      await sander.mkdir(dir._absolutePath);
    }
    else throw error;
  }

  // save the new caches and note that the directory has been primed
  /* eslint-disable no-param-reassign */
  dir._files = Immutable.Map(files);
  dir._mtimes = Immutable.Map(mtimes);
  dir._primed = true;
  /* eslint-enable no-param-reassign */
}
323812
def compile(lessfile, cssfile)
      import_paths = options[:import_paths].unshift(File.dirname(lessfile))
      parser = ::Less::Parser.new paths: import_paths, filename: lessfile
      File.open(lessfile, 'r') do |infile|
        File.open(cssfile, 'w') do |outfile|
          tree = parser.parse(infile.read)
          outfile << tree.to_css(compress: options[:compress], yuicompress: options[:yuicompress])
        end
      end
      true
    rescue StandardError => e
      Compat::UI.info "Guard::Less: Compiling #{lessfile} failed with message: #{e.message}"
      false
    end
94333
def run_all
      Compat::UI.info 'Guard::Less: compiling all files'
      files = Dir.glob('**/*.*')
      paths = Compat.matching_files(self, files).uniq
      run(paths)
    end
1245170
function parseHttpResponse(options, filesWithHash) {
    if (options.verbose) {
        _utils.logger.info('Parsing HTTP responses...');
    }
    var promises = [];
    var _iteratorNormalCompletion5 = true;
    var _didIteratorError5 = false;
    var _iteratorError5 = undefined;

    try {
        for (var _iterator5 = filesWithHash[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
            var fileWithHash = _step5.value;

            if (fileWithHash.subtitlesPresent) continue;
            var p = (0, _utils.XML2JSON)(options, fileWithHash).catch(function (err) {
                if (options.verbose) {
                    _utils.logger.info('Error in HTTP response: ', err.err);
                }
                return err.fileWithHash;
            });
            promises.push(p);
        }
    } catch (err) {
        _didIteratorError5 = true;
        _iteratorError5 = err;
    } finally {
        try {
            if (!_iteratorNormalCompletion5 && _iterator5.return) {
                _iterator5.return();
            }
        } finally {
            if (_didIteratorError5) {
                throw _iteratorError5;
            }
        }
    }

    return Promise.all(promises);
}
800126
function _processExportResponse(csvs, res, next) {
  var zip = archiver('zip');

  // convert csv entries to in-memory zip file and stream response
  res.setHeader('Content-type', 'application/zip');
  res.setHeader('Content-disposition', 'attachment; filename=submissions.zip');
  zip.pipe(res);

  for (var form in csvs) { // eslint-disable-line guard-for-in
    var csv = csvs[form];
    zip.append(csv, {name: form + '.csv'});
  }

  var respSent = false;
  zip.on('error', function(err) {
    logger.error("_processExportResponse ", {error: err});
    if (err) {
      if (!respSent) {
        respSent = true;
        return next(err);
      }
    }
  });

  zip.finalize(function(err) {
    if (err) {
      logger.error("_processExportResponse finalize", {error: err});
      if (!respSent) {
        respSent = true;
        return next(err);
      }

      logger.debug("_processExportResponse finalize headers sent");
    }

    logger.debug("_processExportResponse finalize finished");
  });
}
1274578
function match(re) {
        const m = re.exec(css);

        if (m) {
            css = css.slice(m[0].length);

            return m;
        }
    }