serve gzip file if exists and is valid
511226
function tryServeWithGzip() {
      fs.stat(gzippedFile, (err, stat) => {
        if (!err && stat.isFile()) {
          hasGzipId12(gzippedFile, (gzipErr, isGzip) => {
            if (!gzipErr && isGzip) {
              file = gzippedFile;
              serve(stat);
            } else {
              statFile();
            }
          });
        } else {
          statFile();
        }
      });
    }
1154938
function serve(res, file, maxAge) {
  log.debug(`Serving: ${ file }`)
  res.status(200)
    .set('Cache-Control', `max-age=${ maxAge }`)
    .sendFile(file, err => {
      if (err) {
        log.error(err)
        res.status(err.status).end()
        return
      }
    })
}
1315782
def _gzip_open_handle(handle):
    """""""
    import gzip
    if sys.version_info[0] > 2:
        import io
        handle = io.TextIOWrapper(gzip.GzipFile(fileobj=handle), encoding="UTF-8")
    else:
        handle = gzip.GzipFile(fileobj=handle)
    return handle
916718
def call(env)
      # Only process get requests
      if env['REQUEST_METHOD'] == 'GET'
        request = Rack::Request.new(env)

        # See if client accepts gzip encoding
        if Rack::Utils.select_best_encoding(%w(gzip identity), request.accept_encoding) == 'gzip'
          # Check if compressed version exists in assets directory
          compressed_path = env['PATH_INFO'] + '.gz'
          if compressed_path.start_with?(@asset_prefix) && (match = @file_handler.match?(compressed_path))
            # Use FileHandler to serve up the gzipped file, then strip the .gz suffix
            path = env["PATH_INFO"] = match
            status, headers, body = @file_handler.call(env)
            path = env["PATH_INFO"] = env["PATH_INFO"].chomp('.gz')

            # Set the Vary HTTP header.
            vary = headers["Vary"].to_s.split(",").map(&:strip)
            unless vary.include?("*") || vary.include?("Accept-Encoding")
              headers["Vary"] = vary.push("Accept-Encoding").join(",")
            end

            # Add encoding and type
            headers['Content-Encoding'] = 'gzip'
            headers['Content-Type'] = Rack::Mime.mime_type(File.extname(path), 'text/plain')

            # Update cache-control to add directive telling Rack::Deflate to leave it alone.
            cache_control = headers['Cache-Control'].try(:to_s).try(:downcase)
            if cache_control.nil?
              headers['Cache-Control'] = 'no-transform'
            elsif !cache_control.include?('no-transform')
              headers['Cache-Control'] += ', no-transform'
            end

            body.close if body.respond_to?(:close)
            return [status, headers, body]
          end
        end
      end

      @app.call(env)
    end
1302474
def is_valid_file(path):
    '''  '''
    return os.path.exists(path) and os.path.isfile(path)
248676
function safegetzipfile(zip, file) {
	var k = keys(zip.files);
	var f = file.toLowerCase(), g = f.replace(/\//g,'\\');
	for(var i=0; i<k.length; ++i) {
		var n = k[i].toLowerCase();
		if(f == n || g == n) return zip.files[k[i]];
	}
	return null;
}
17462
def ensure_file(url, path, md5sum=None):
    

    if not os.path.isfile(path) or (md5sum and md5sum != file_md5(path)):
        download_file(url, path)
757229
def open_file(self, filename):
        """"""
        try:
            if filename.endswith('.gz'):
                self.blob_file = gzip.open(filename, 'rb')
            else:
                self.blob_file = open(filename, 'rb')
        except TypeError:
            log.error("Please specify a valid filename.")
            raise SystemExit
        except IOError as error_message:
            log.error(error_message)
            raise SystemExit
414035
def open_as_needed(filename):
    
    if hasattr(filename, 'read'):
        return filename

    if filename.endswith('.bz2'):
        return bz2.BZ2File(filename, 'rb')
    elif filename.endswith('.gz'):
        return gzip.GzipFile(filename, 'rb')
    else:
        return open(filename, 'rb')
1177865
def gzip_open_to(fin_gz, fout):
    """"""
    with gzip.open(fin_gz, 'rb') as zstrm:
        with  open(fout, 'wb') as ostrm:
            ostrm.write(zstrm.read())
    assert os.path.isfile(fout), "COULD NOT GUNZIP({G}) TO FILE({F})".format(G=fin_gz, F=fout)
    os.remove(fin_gz)
463673
def _compress_content(self, content):
        """"""
        zbuf = StringIO()
        zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
        zfile.write(content.read())
        zfile.close()
        content.file = zbuf
        return content
416931
def must_open(filename, mode="r", checkexists=False, skipcheck=False, \
            oappend=False):
    
    if isinstance(filename, list):
        assert "r" in mode

        if filename[0].endswith((".gz", ".bz2")):
            filename = " ".join(filename)  # allow opening multiple gz/bz2 files
        else:
            import fileinput
            return fileinput.input(filename)

    if filename.startswith("s3://"):
        from jcvi.utils.aws import pull_from_s3
        filename = pull_from_s3(filename)

    if filename in ("-", "stdin"):
        assert "r" in mode
        fp = sys.stdin

    elif filename == "stdout":
        assert "w" in mode
        fp = sys.stdout

    elif filename == "stderr":
        assert "w" in mode
        fp = sys.stderr

    elif filename == "tmp" and mode == "w":
        from tempfile import NamedTemporaryFile
        fp = NamedTemporaryFile(delete=False)

    elif filename.endswith(".gz"):
        if 'r' in mode:
            cmd = "gunzip -c {0}".format(filename)
            fp = popen(cmd, debug=False)
        elif 'w' in mode:
            import gzip
            fp = gzip.open(filename, mode)

    elif filename.endswith(".bz2"):
        if 'r' in mode:
            cmd = "bzcat {0}".format(filename)
            fp = popen(cmd, debug=False)
        elif 'w' in mode:
            import bz2
            fp = bz2.BZ2File(filename, mode)

    else:
        if checkexists:
            assert mode == "w"
            overwrite = (not op.exists(filename)) if skipcheck \
                        else check_exists(filename, oappend)
            if overwrite:
                if oappend:
                    fp = open(filename, "a")
                else:
                    fp = open(filename, "w")
            else:
                logging.debug("File `{0}` already exists. Skipped."\
                        .format(filename))
                return None
        else:
            fp = open(filename, mode)

    return fp
555656
def _check_if_zipped(self, path):
        

        filename = get_file(path).split('.')

        if filename[-1] in ['bz', 'bz2', 'gz']:
            return True

        return False
908997
def open_file(filename, as_text=False):
    """"""
    if filename.lower().endswith('.gz'):
        if as_text:
            return gzip.open(filename, 'rt')
        else:
            return gzip.open(filename, 'rb')
    else:
        if as_text:
            return open(filename, 'rt')
        else:
            return open(filename, 'rb')
607015
def pack_gzip(params, ctxt, scope, stream, coord):
    
    if len(params) == 0:
        raise errors.InvalidArguments(coord, "{} args".format(len(params)), "at least one argument")
    
    built = utils.binary("")
    for param in params:
        if isinstance(param, pfp.fields.Field):
            built += param._pfp__build()
        else:
            built += param
    
    return zlib.compress(built)
53980
def _gzip_open_filename(handle):
    """"""
    import gzip
    if sys.version_info[0] > 2:
        handle = gzip.open(handle, mode='rt', encoding="UTF-8")
    else:
        handle = gzip.open(handle)
    return handle
621175
def freader(filename, gz=False, bz=False):
    

    filecheck(filename)
    if filename.endswith('.gz'):
        gz = True
    elif filename.endswith('.bz2'):
        bz = True

    if gz:
        return gzip.open(filename, 'rb')
    elif bz:
        return bz2.BZ2File(filename, 'rb')
    else:
        return io.open(filename, 'rb')