Compress route return data with gzip compression
501813
def compress(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if ('gzip' in bottle.request.headers.get('Accept-Encoding', '') and
                isinstance(result, string_type) and
                len(result) > 1024):
            if isinstance(result, unicode):
                result = result.encode('utf-8')
            tmp_fo = BytesIO()
            with gzip.GzipFile(mode='wb', fileobj=tmp_fo) as gzip_fo:
                gzip_fo.write(result)
            result = tmp_fo.getvalue()
            bottle.response.add_header('Content-Encoding', 'gzip')
        return result
    return wrapper
1128199
function compression (options) {
  var opts = options || {}

  // options
  var filter = opts.filter || shouldCompress
  var threshold = bytes.parse(opts.threshold)

  if (threshold == null) {
    threshold = 1024
  }

  return function compression (req, res, next) {
    var ended = false
    var length
    var listeners = []
    var stream

    var _end = res.end
    var _on = res.on
    var _write = res.write

    // flush
    res.flush = function flush () {
      if (stream) {
        stream.flush()
      }
    }

    // proxy

    res.write = function write (chunk, encoding) {
      if (ended) {
        return false
      }

      if (!this._header) {
        this._implicitHeader()
      }

      return stream
        ? stream.write(toBuffer(chunk, encoding))
        : _write.call(this, chunk, encoding)
    }

    res.end = function end (chunk, encoding) {
      if (ended) {
        return false
      }

      if (!this._header) {
        // estimate the length
        if (!this.getHeader('Content-Length')) {
          length = chunkLength(chunk, encoding)
        }

        this._implicitHeader()
      }

      if (!stream) {
        return _end.call(this, chunk, encoding)
      }

      // mark ended
      ended = true

      // write Buffer for Node.js 0.8
      return chunk
        ? stream.end(toBuffer(chunk, encoding))
        : stream.end()
    }

    res.on = function on (type, listener) {
      if (!listeners || type !== 'drain') {
        return _on.call(this, type, listener)
      }

      if (stream) {
        return stream.on(type, listener)
      }

      // buffer listeners for future stream
      listeners.push([type, listener])

      return this
    }

    function nocompress (msg) {
      debug('no compression: %s', msg)
      addListeners(res, _on, listeners)
      listeners = null
    }

    onHeaders(res, function onResponseHeaders () {
      // determine if request is filtered
      if (!filter(req, res)) {
        nocompress('filtered')
        return
      }

      // determine if the entity should be transformed
      if (!shouldTransform(req, res)) {
        nocompress('no transform')
        return
      }

      // vary
      vary(res, 'Accept-Encoding')

      // content-length below threshold
      if (Number(res.getHeader('Content-Length')) < threshold || length < threshold) {
        nocompress('size below threshold')
        return
      }

      var encoding = res.getHeader('Content-Encoding') || 'identity'

      // already encoded
      if (encoding !== 'identity') {
        nocompress('already encoded')
        return
      }

      // head
      if (req.method === 'HEAD') {
        nocompress('HEAD request')
        return
      }

      // compression method
      var accept = accepts(req)
      var method = accept.encoding(['gzip', 'deflate', 'identity'])

      // we really don't prefer deflate
      if (method === 'deflate' && accept.encoding(['gzip'])) {
        method = accept.encoding(['gzip', 'identity'])
      }

      // negotiation failed
      if (!method || method === 'identity') {
        nocompress('not acceptable')
        return
      }

      // compression stream
      debug('%s compression', method)
      stream = method === 'gzip'
        ? zlib.createGzip(opts)
        : zlib.createDeflate(opts)

      // add buffered listeners to stream
      addListeners(stream, stream.on, listeners)

      // header fields
      res.setHeader('Content-Encoding', method)
      res.removeHeader('Content-Length')

      // compression
      stream.on('data', function onStreamData (chunk) {
        if (_write.call(res, chunk) === false) {
          stream.pause()
        }
      })

      stream.on('end', function onStreamEnd () {
        _end.call(res)
      })

      _on.call(res, 'drain', function onResponseDrain () {
        stream.resume()
      })
    })

    next()
  }
}
567286
def zlib_compress(data):
    
    if PY3K:
        if isinstance(data, str):
            return zlib.compress(bytes(data, 'utf-8'))
        return zlib.compress(data)
    return zlib.compress(data)
101974
public void compress() {
        IoBuffer tmp = IoBuffer.allocate(0);
        tmp.setAutoExpand(true);
        byte[] tmpData = new byte[data.limit()];
        data.position(0);
        data.get(tmpData);
        try (DeflaterOutputStream deflater = new DeflaterOutputStream(tmp.asOutputStream(), new Deflater(Deflater.BEST_COMPRESSION))) {
            deflater.write(tmpData);
            deflater.finish();
        } catch (IOException e) {
            //docs state that free is optional
            tmp.free();
            throw new RuntimeException("could not compress data", e);
        }
        data.free();
        data = tmp;
        data.flip();
        prepareIO();
    }
1184678
def gzip(str)
      io = StringIO.new
      gz = Zlib::GzipWriter.new(io, Zlib::BEST_COMPRESSION)
      gz.mtime = 1
      gz << str
      gz.finish
      io.string
    end
138630
def compress(self, data_list):
        
        data = {}
        if data_list:
            return dict(
                (f.name, data_list[i]) for i, f in enumerate(self.form))
        return data
916169
def _tls_compress(self, s):
        
        alg = self.tls_session.wcs.compression
        return alg.compress(s)
583443
def bz2_compress_stream(src, level=9):
    
    compressor = bz2.BZ2Compressor(level)
    for block in src:
        encoded = compressor.compress(block)
        if encoded:
            yield encoded
    yield compressor.flush()
292135
def gzip_uncompress(data, truncated=False):
    '''
    '''
    decompressor = SimpleGzipDecompressor()
    inflated_data = decompressor.decompress(data)

    if not truncated:
        inflated_data += decompressor.flush()

    return inflated_data
452661
def compress_txn_outputs(txn_outputs):
    '''
    
    '''
    result_dict = {}
    outputs = (output for output in txn_outputs if output.get('address'))
    for txn_output in outputs:
        if txn_output['address'] in result_dict:
            result_dict[txn_output['address']] += txn_output['value']
        else:
            result_dict[txn_output['address']] = txn_output['value']
    return result_dict
745280
function gzip(data) {
  var unit8Array = new Uint8Array(toBuffer(data));
  return new Buffer(pako.gzip(unit8Array));
}
1129771
def compress_repr(self) -> str:
        
        string = super().compress_repr()
        if string in ('?', '[]'):
            return string
        if string is None:
            values = self.values
        else:
            values = [int(string)]
        invmap = {value: key for key, value in
                  self.CONSTANTS.items()}
        result = ', '.join(
            invmap.get(value, repr(value)) for value in values)
        if len(self) > 255:
            result = f'[{result}]'
        return result
1010027
def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None):
    
    comp = LZMACompressor(format, check, preset, filters)
    return comp.compress(data) + comp.flush()
352375
def _compress(self, cmd):
        """"""
        compressor = COMPRESSORS.get(self.compressor)
        if compressor is None:
            return cmd
        compress_cmd = compressor['compress']
        return "{} | {}".format(compress_cmd, cmd)
1269641
function decompress(compressedSize, b) {
	"use strict";
	var n = 0,
		r = 0,
		f = 0,
		s = 8,
		p = s,
		i = 0;
	var dst = new Buffer(compressedSize);
	var d = 12;
	var aa = new Int32Array(256);
	while (s < dst.length) {
		if (!i) {
			f = b[d++];
			i = 1;
		}
		if (f & i) {
			r = aa[b[d++]];
			dst[s++] = dst[r++];
			dst[s++] = dst[r++];
			n = 0xff & b[d++];
			for (var m = 0; m < n; m++) {
				dst[s + m] = dst[r + m];
			}
		} else {
			dst[s++] = b[d++];
		}
		while (p < (s - 1)) {
			aa[dst[p] ^ dst[p + 1]] = p++;
		}
		if (f & i) {
			p = (s += n);
		}
		i *= 2;
		if (i === 256) {
			i = 0;
		}
	}
	return dst;
}
493433
async function pakoUnzip(inputData) {
  let strm
  let pos = 0
  let i = 0
  const chunks = []
  let inflator
  do {
    const remainingInput = inputData.slice(pos)
    inflator = new Inflate()
    strm = inflator.strm
    inflator.push(remainingInput, Z_SYNC_FLUSH)
    if (inflator.err) throw new Error(inflator.msg)

    pos += strm.next_in
    chunks[i] = Buffer.from(inflator.result)
    i += 1
  } while (strm.avail_in)

  const result = Buffer.concat(chunks)
  return result
}
805
def compress(self, d=DEFAULT):
        """"""
        if d is DEFAULT:
            d = self
        if isinstance(d, list):
            l = [v for v in (self.compress(v) for v in d)]
            try:
                return list(set(l))
            except TypeError:
                # list contains not hashables
                ret = []
                for i in l:
                    if i not in ret:
                        ret.append(i)
                return ret
        elif isinstance(d, type(self)):
            return type(self)({k: v for k, v in ((k, self.compress(v)) for k, v in d.items())})
        elif isinstance(d, dict):
            return {k: v for k, v in ((k, self.compress(v)) for k, v in d.items())}
        return d