Compress a file.
510682
private int compress(String argv[], Configuration conf) throws IOException {
    int i = 0;
    String cmd = argv[i++];
    String srcf = argv[i++];
    String dstf = argv[i++];

    Path srcPath = new Path(srcf);
    FileSystem srcFs = srcPath.getFileSystem(getConf());
    Path dstPath = new Path(dstf);
    FileSystem dstFs = dstPath.getFileSystem(getConf());

    // Create codec
    CompressionCodecFactory factory = new CompressionCodecFactory(conf);
    CompressionCodec codec = factory.getCodec(dstPath);
    if (codec == null) {
      System.err.println(cmd.substring(1) + ": cannot find compression codec for "
          + dstf);
      return 1;
    }

    // open input stream
    InputStream in = srcFs.open(srcPath);

    // Create compression stream
    OutputStream out = dstFs.create(dstPath);
    out = codec.createOutputStream(out);

    IOUtils.copyBytes(in, out, conf, true);

    return 0;
  }
1248691
def compress(func):
    """"""
    def wrapper(*args, **kwargs):
        """Wrapper that take one function and return the compressed result."""
        ret = func(*args, **kwargs)
        logger.debug('Receive {} {} request with header: {}'.format(
            request.method,
            request.url,
            ['{}: {}'.format(h, request.headers.get(h)) for h in request.headers.keys()]
        ))
        if 'deflate' in request.headers.get('Accept-Encoding', ''):
            response.headers['Content-Encoding'] = 'deflate'
            ret = deflate_compress(ret)
        else:
            response.headers['Content-Encoding'] = 'identity'
        return ret

    def deflate_compress(data, compress_level=6):
        """Compress given data using the DEFLATE algorithm"""
        # Init compression
        zobj = zlib.compressobj(compress_level,
                                zlib.DEFLATED,
                                zlib.MAX_WBITS,
                                zlib.DEF_MEM_LEVEL,
                                zlib.Z_DEFAULT_STRATEGY)

        # Return compressed object
        return zobj.compress(b(data)) + zobj.flush()

    return wrapper
113763
public static void compress(int format, Resource[] sources, Resource target, int mode) throws IOException {

	if (format == FORMAT_ZIP) compressZip(sources, target, null);
	else if (format == FORMAT_TAR) compressTar(sources, target, mode);
	else if (format == FORMAT_TGZ) compressTGZ(sources, target, mode);
	else if (format == FORMAT_TBZ2) compressTBZ2(sources, target, mode);

	else throw new IOException("can't compress in given format");
    }
680702
def decompress(self, data):
		""""""

		decompressed = ""
		pos = 0
		while pos < len(data):
			currentChar = data[pos]
			if currentChar != self.referencePrefix:
				decompressed += currentChar
				pos += 1
			else:
				nextChar = data[pos + 1]
				if nextChar != self.referencePrefix:
					distance = self.__decodeReferenceInt(data[pos + 1 : pos + 3], 2)
					length = self.__decodeReferenceLength(data[pos + 3])
					start = len(decompressed) - distance - length
					end = start + length
					decompressed += decompressed[start : end]
					pos += self.minStringLength - 1
				else:
					decompressed += self.referencePrefix
					pos += 2

		return decompressed
374549
public static File compress(CompressionMethod _method, String _sourceFile, String _outputFileName) {
    	if (_method == null || _sourceFile == null) {
    		return null;
    	}

        File inputFile = new File(_sourceFile);

        if (!inputFile.exists()) {
            return null;
        }

        byte[] buffer = new byte[1024];
        try {
        	Constructor<? extends DeflaterOutputStream> constructor = _method.getOutputStreamClass().getConstructor(OutputStream.class);
        	if (constructor != null) {
        		DeflaterOutputStream compressOutputStream = constructor.newInstance(new FileOutputStream(_outputFileName));
	            try (FileInputStream in = new FileInputStream(_sourceFile)) {
	                int len;
	                while ((len = in.read(buffer)) > 0) {
	                    compressOutputStream.write(buffer, 0, len);
	                }

	                in.close();

	                compressOutputStream.finish();
	                compressOutputStream.close();
	                return new File(_outputFileName);
	            }
        	}
        } catch (IOException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException _ex) {
            LOGGER.error("Cannot uncompress file: ", _ex);
        }
        return null;

    }
334664
public final void compress(ByteBuffer src, ByteBuffer dest) {
    final int cpLen = compress(src, src.position(), src.remaining(), dest, dest.position(), dest.remaining());
    src.position(src.limit());
    dest.position(dest.position() + cpLen);
  }
919467
public void compress(String path)
	{
		try {

			File fileToArchive = new File(path);

			BufferedInputStream input = new BufferedInputStream(new FileInputStream(fileToArchive));

			File archivedFile = new File(fileToArchive.getName() + ".bz2");
			archivedFile.createNewFile();

			FileOutputStream fos = new FileOutputStream(archivedFile);
			BufferedOutputStream bufStr = new BufferedOutputStream(fos);
			// added bzip2 prefix
			fos.write("BZ".getBytes());
			CBZip2OutputStream bzip2 = new CBZip2OutputStream(bufStr);

			while (input.available() > 0) {
				int size = COMPRESSION_CACHE;

				if (input.available() < COMPRESSION_CACHE) {
					size = input.available();
				}
				byte[] bytes = new byte[size];

				input.read(bytes);

				bzip2.write(bytes);
			}
			bzip2.close();
			bufStr.close();
			fos.close();
			input.close();

		}
		catch (IOException e) {
			e.printStackTrace();
		}

	}
394498
public static void compress(String fileName, String compressedFileName, String password) {
		try {
			ZipParameters zipParameters = new ZipParameters();
			zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
			zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
			if (password != null) {
				zipParameters.setEncryptFiles(true);
				zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
				zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
				zipParameters.setPassword(password);
			}
			String destinationZipFilePath = compressedFileName;
			ZipFile zipFile = new ZipFile(destinationZipFilePath);
			zipFile.addFile(new File(fileName), zipParameters);
		} catch (ZipException e) {
			JKExceptionUtil.handle(e);
		}
	}
385061
public static void compressTar(Resource[] sources, Resource target, int mode) throws IOException {
	compressTar(sources, IOUtil.toBufferedOutputStream(target.getOutputStream()), mode);
    }
816228
def compress(data, compresslevel=9):
    
    buf = io.BytesIO()
    with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f:
        f.write(data)
    return buf.getvalue()
975629
public void compress(ByteBuffer src, ByteBuffer dest) {
    final int compressedLength = compress(src, src.position(), src.remaining(), dest, dest.position(), dest.remaining());
    src.position(src.limit());
    dest.position(dest.position() + compressedLength);
  }
623707
protected function _compress()
    {
        $start = microtime(true);
        $this->info( '  Trying to compress files' );
        // code

        $config    = $this->config;
        $exclude   = $config['files']['exclude'];
        $archiver  = $config['archiver'];
        if ( !empty( $config['files']['archiver'] ) )
        {
            $archiver = $config['files']['archiver'];
        }

        /*
         * OPTION Date-Directories
         */
        if ( $config['use_date_directory'] )
        {
            $backupDir = $this->config['backupDir'] . $this->date;
            $filepath  = $backupDir . '/' . $this->dfilename;
            $filename  = $this->dfilename;
        }
        else
        {
            $backupDir = $this->config['backupDir'];
            $filepath  = $backupDir . '/' .  $this->filename;
            $filename  = $this->filename;
        }

        /*
         * DO COMPRESS
         * Exclude info
         */
        
        $_excluded = '';
        if ( !empty( $exclude ) )
        {
            foreach( $exclude as $e )
            {
                switch( $archiver )
                {
                    case 'tar.gzip':
                        $_excluded .= " --exclude='" . str_replace( base_path() . '/', null, $e ) . "'";
                    break;
                    case 'zip':
                        $_excluded .= " -x '*" . str_replace( base_path() . '/', null, $e ) . "/*'";
                    break;
                    case 'rar':
                        $_excluded .= " -x*" . str_replace( base_path() . '/', null, addslashes( $e ) ) . '\*';
                    break;
                }
            }
        }

        $cmd = [];
        $cmd[] = 'cd ' . base_path();
        switch( $archiver )
        {
            default:
            case 'tar.gzip':
                $_extension     = '.tar.gz ';
                $cmd[]          = 'tar '. $_excluded .' -czvf ' . str_replace( base_path() . '/', null,  $filepath ) . $_extension . ' -C ' . base_path() . ' .';
            break;
            case 'zip':
                $_extension     = '.zip ';
                $cmd[]          = 'zip -r9 ' . $filepath. $_extension . ' ./ ' . $_excluded;
            break;
            case 'rar':
                $_extension     = '.rar ';
                $cmd[]          = 'rar a -r -ep1 -m5 ' . $filepath.$_extension . './' . $_excluded;
            break;
        }
        $this->_runCmd( $cmd );

        // code
        $time = microtime(true)-$start;
        $this->warn( '  Backup filename is ' . $filename.$_extension );
        $this->warn( '                  at ' . str_replace( base_path() . '/', null, $backupDir ) );
    }
1229618
def create_gzip (archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    if len(filenames) > 1:
        raise util.PatoolError('multi-file compression not supported in Python gzip')
    try:
        with gzip.GzipFile(archive, 'wb') as gzipfile:
            filename = filenames[0]
            with open(filename, 'rb') as srcfile:
                data = srcfile.read(READ_SIZE_BYTES)
                while data:
                    gzipfile.write(data)
                    data = srcfile.read(READ_SIZE_BYTES)
    except Exception as err:
        msg = "error creating %s: %s" % (archive, err)
        raise util.PatoolError(msg)
    return None
894092
def get_xritdecompress_outfile(stdout):
    """"""
    outfile = b''
    for line in stdout:
        try:
            k, v = [x.strip() for x in line.split(b':', 1)]
        except ValueError:
            break
        if k == b'Decompressed file':
            outfile = v
            break

    return outfile
837943
public void compress ()
    {
        for (Iterator<CountEntry<K>> it = _backing.values().iterator(); it.hasNext(); ) {
            if (it.next().count == 0) {
                it.remove();
            }
        }
    }
81416
def compress(self):
        """"""
        for ast_token in self.ast_tokens:
            if type(ast_token) in self.dispatcher:  # pylint: disable=unidiomatic-typecheck
                self.dispatcher[type(ast_token)](ast_token)
            else:
                self.dispatcher['default'](ast_token)
1328171
public static File compressFileGzip(String _sourceFile, String _outputFileName) {
        return compress(CompressionMethod.GZIP, _sourceFile, _outputFileName);
    }