auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void display(final PatchSetPublishDetail r) { descBlock.display(r.getChange(), r.getPatchSetInfo(), r.getAccounts()); if (r.getChange().getStatus().isOpen()) { initApprovals(r, approvalPanel); } if (lastState != null && patchSetId.equals(lastState.patchSetId)) { message.setText(lastState.message); } draftsPanel.clear(); if (!r.getDrafts().isEmpty()) { draftsPanel.add(new SmallHeading(Util.C.headingPatchComments())); Panel panel = null; String priorFile = ""; for (final PatchLineComment c : r.getDrafts()) { final Patch.Key patchKey = c.getKey().getParentKey(); final String fn = patchKey.get(); if (!fn.equals(priorFile)) { panel = new FlowPanel(); panel.addStyleName("gerrit-PatchComments"); draftsPanel.add(panel); panel.add(new PatchLink.SideBySide(fn, new PatchSetKeys(patchKey))); priorFile = fn; } Label m; m = new DoubleClickLinkLabel(patchKey); m.setText(Util.M.lineHeader(c.getLine())); m.setStyleName("gerrit-LineHeader"); panel.add(m); m = new DoubleClickLinkLabel(patchKey); SafeHtml.set(m.getElement(), LineCommentPanel.toSafeHtml(c)); m.setStyleName("gerrit-PatchLineComment"); panel.add(m); } } }

Target:
private void display(final PatchSetPublishDetail r) { descBlock.display(r.getChange(), r.getPatchSetInfo(), r.getAccounts()); if (r.getChange().getStatus().isOpen()) { initApprovals(r, approvalPanel); } if (lastState != null && patchSetId.equals(lastState.patchSetId)) { message.setText(lastState.message); } draftsPanel.clear(); if (!r.getDrafts().isEmpty()) { draftsPanel.add(new SmallHeading(Util.C.headingPatchComments())); Panel panel = null; String priorFile = ""; for (final PatchLineComment c : r.getDrafts()) { final Patch.Key patchKey = c.getKey().getParentKey(); final String fn = patchKey.get(); if (!fn.equals(priorFile)) { panel = new FlowPanel(); panel.addStyleName("gerrit-PatchComments"); draftsPanel.add(panel); panel.add(new PatchLink.SideBySide(fn, patchKey, 0, null )); priorFile = fn; } Label m; m = new DoubleClickLinkLabel(patchKey); m.setText(Util.M.lineHeader(c.getLine())); m.setStyleName("gerrit-LineHeader"); panel.add(m); m = new DoubleClickLinkLabel(patchKey); SafeHtml.set(m.getElement(), LineCommentPanel.toSafeHtml(c)); m.setStyleName("gerrit-PatchLineComment"); panel.add(m); } } }
Source:
private GovukOrganisation.Details getBranding() { String custodianId = requestContext.getRegister().getRegistry(); return client.target("<LINK_0>" + custodianId) .request() .get(GovukOrganisation.class) .getDetails(); }

Target:
private Optional<GovukOrganisation.Details> getBranding() { Optional<GovukOrganisation> organisation = organisationClient.getOrganisation(requestContext.getRegister().getRegistry()); return organisation.map(GovukOrganisation::getDetails); }
Source:
public void testAMShutdownOnRMCallback() { YarnConfiguration yarnConfiguration = mock(YarnConfiguration.class); SamzaAppMasterMetrics metrics = mock(SamzaAppMasterMetrics.class); Config config = mock(Config.class); AMRMClientAsync asyncClient = mock(AMRMClientAsync.class); YarnAppState yarnAppState = new YarnAppState(0, mock(ContainerId.class), "host", 8080, 8081); SamzaYarnAppMasterLifecycle lifecycle = mock(SamzaYarnAppMasterLifecycle.class); SamzaYarnAppMasterService service = mock(SamzaYarnAppMasterService.class); NMClientAsync asyncNMClient = mock(NMClientAsync.class); ClusterResourceManager.Callback callback = mock(ClusterResourceManager.Callback.class); YarnClusterResourceManager yarnClusterResourceManager = new YarnClusterResourceManager(asyncClient, asyncNMClient, callback, yarnAppState, lifecycle, service, metrics, yarnConfiguration, config); yarnClusterResourceManager.onShutdownRequest(); verify(lifecycle, times(1)).onShutdown(SamzaApplicationState.SamzaAppStatus.FAILED); verify(asyncClient, times(1)).stop(); verify(asyncNMClient, times(1)).stop(); verify(service, times(1)).onShutdown(); verify(metrics, times(1)).stop(); }

Target:
public void testAMShutdownOnRMCallback() throws IOException, YarnException { YarnConfiguration yarnConfiguration = mock(YarnConfiguration.class); SamzaAppMasterMetrics metrics = mock(SamzaAppMasterMetrics.class); Config config = mock(Config.class); AMRMClientAsync asyncClient = mock(AMRMClientAsync.class); YarnAppState yarnAppState = new YarnAppState(0, mock(ContainerId.class), "host", 8080, 8081); SamzaYarnAppMasterLifecycle lifecycle = Mockito.spy(new SamzaYarnAppMasterLifecycle(512, 2, mock(SamzaApplicationState.class), yarnAppState, asyncClient)); SamzaYarnAppMasterService service = mock(SamzaYarnAppMasterService.class); NMClientAsync asyncNMClient = mock(NMClientAsync.class); ClusterResourceManager.Callback callback = mock(ClusterResourceManager.Callback.class); YarnClusterResourceManager yarnClusterResourceManager = new YarnClusterResourceManager(asyncClient, asyncNMClient, callback, yarnAppState, lifecycle, service, metrics, yarnConfiguration, config); yarnClusterResourceManager.onShutdownRequest(); verify(lifecycle, times(1)).onShutdown(SamzaApplicationState.SamzaAppStatus.FAILED); verify(asyncClient, times(1)).unregisterApplicationMaster(FinalApplicationStatus.FAILED, null, null); verify(asyncClient, times(1)).stop(); verify(asyncNMClient, times(1)).stop(); verify(service, times(1)).onShutdown(); verify(metrics, times(1)).stop(); }
Source:
private Host resolveSite(final PageContext context, final HttpServletRequest request) throws DotDataException, DotSecurityException { final User user = context.getUser(); final PageMode mode = context.getPageMode(); Host site = this.getHostFromRequest(request, user, mode); if (site == null) { site = this.getHostFromSession(request, user, mode); } System.out.println("site = " + site); System.out.println("request = " + request.getServerName()); return site != null ? site : this.hostAPI.resolveHostName(request.getServerName(), user, mode.respectAnonPerms) ; }

Target:
private Host resolveSite(final PageContext context, final HttpServletRequest request) throws DotDataException, DotSecurityException { final User user = context.getUser(); final PageMode mode = context.getPageMode(); Optional<Host> optionalSite = this.getHostFromRequest(request, user, mode); if (!optionalSite.isPresent()) { optionalSite = this.getHostFromSession(request, user, mode); } return optionalSite.isPresent() ? optionalSite.get() : this.hostAPI.resolveHostName(request.getServerName(), user, mode.respectAnonPerms) ; }
Source:
public void removeTasksOlderThan(final long timestamp) { connector.retryWithHandle( (HandleCallback<Void>) handle -> { DateTime createdTime = DateTimes.utc(timestamp); log.info("Deleting tasks before [%s] and inactive at metastore.", createdTime.toString()); handle.createStatement( StringUtils.format( getSqlRemoveLogsOlderThan(), logTable, entryTable ) ) .bind("created_date", createdTime.toString()) .execute(); handle.createStatement( StringUtils.format( "DELETE FROM %s WHERE created_date < :created_date AND active = false", entryTable ) ) .bind("created_date", createdTime.toString()) .execute(); return null; } ); }

Target:
public void removeTasksOlderThan(final long timestamp) { DateTime dateTime = DateTimes.utc(timestamp); connector.retryWithHandle( (HandleCallback<Void>) handle -> { handle.createStatement(getSqlRemoveLogsOlderThan()) .bind("date_time", dateTime.toString()) .execute(); handle.createStatement( StringUtils.format( "DELETE FROM %s WHERE created_date < :date_time AND active = false", entryTable ) ) .bind("date_time", dateTime.toString()) .execute(); return null; } ); }
Source:
protected String getCommitID(String repositoryId, Version version) { RefsApi refsApi = new RefsApi(apiClient); try { Branch branch = refsApi.repositoriesUsernameRepoSlugRefsBranchesNameGet(repositoryId.split("/")[0], version.getReference(), repositoryId.split("/")[1]); if (branch != null) { return branch.getTarget().getHash(); } } catch (ApiException e) { LOG.error(gitUsername + ": apiexception on reading branch commitid" + e.getMessage()); } try { Tag tag = refsApi.repositoriesUsernameRepoSlugRefsTagsNameGet(repositoryId.split("/")[0], version.getReference(), repositoryId.split("/")[1]); if (tag != null) { return tag.getTarget().getHash(); } } catch (ApiException e) { LOG.error(gitUsername + ": apiexception on reading tag commitid" + e.getMessage()); } return null; }

Target:
protected String getCommitID(String repositoryId, Version version) { RefsApi refsApi = new RefsApi(apiClient); try { Branch branch = refsApi.repositoriesUsernameRepoSlugRefsBranchesNameGet(repositoryId.split("/")[0], version.getReference(), repositoryId.split("/")[1]); if (branch != null) { return branch.getTarget().getHash(); } } catch (ApiException ex) { LOG.error(gitUsername + ": apiexception on reading branch commitid", ex); } try { Tag tag = refsApi.repositoriesUsernameRepoSlugRefsTagsNameGet(repositoryId.split("/")[0], version.getReference(), repositoryId.split("/")[1]); if (tag != null) { return tag.getTarget().getHash(); } } catch (ApiException ex) { LOG.error(gitUsername + ": apiexception on reading tag commitid", ex); } return null; }
Source:
public Pair<T, K> getPair() { return pair == null ? new Pair<T, K>(null, null) : pair; }

Target:
private Pair<T, K> getPair() { if (pair == null) { pair = new Pair<T, K>(null, null); } return pair; }
Source:
public BAMIndexer(final OutputStream output, final SAMFileHeader fileHeader) { if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) { throw new SAMException("BAM file be coordinate-sorted for indexing."); } numReferences = fileHeader.getSequenceDictionary().size(); indexBuilder = new BAMIndexBuilder(fileHeader.getSequenceDictionary()); outputWriter = new BinaryBAMIndexWriter(numReferences, output); }

Target:
public BAMIndexer(final OutputStream output, final SAMFileHeader fileHeader) { this(fileHeader, numRefs -> new BinaryBAMIndexWriter(numRefs, output)); }
Source:
public void testAggregationsSum() { String formula = "fn:sum({{" + TERM_1 + "}})"; final Map<String, Object> terms = new HashMap<>(); final HashMap<String, List<Object>> data = new HashMap<>(); final List<Object> termData = new ArrayList<>(); termData.add(new BigDecimal(5.5)); termData.add(new BigDecimal(45)); termData.add(new BigDecimal(12.2)); data.put(wrapTerm(String.valueOf(TERM_1)), termData); formula = replaceDelimiters(formula); this.processor.setData(data); String result = this.processor.evaluateFormula(formula, terms); Assert.assertEquals("Should evaluate avg function", "62.7", result); formula = "fn:sum({{" + TERM_1 + "}}, {{PH_M_cm}})"; final List<Object> term2Data = new ArrayList<>(); term2Data.add(new BigDecimal(14.23)); term2Data.add(new BigDecimal(134.12)); data.put(wrapTerm("PH_M_cm"), term2Data); formula = replaceDelimiters(formula); this.processor = new DerivedVariableProcessor(); this.processor.setData(data); result = this.processor.evaluateFormula(formula, terms); Assert.assertEquals("Should evaluate avg function", "211.05", result); }

Target:
public void testAggregationsSum() { String formula = "fn:sum({{" + TERM_1 + "}})"; final Map<String, Object> terms = new HashMap<>(); final HashMap<String, List<Object>> data = new HashMap<>(); final List<Object> termData = new ArrayList<>(); termData.add(new BigDecimal(5.5)); termData.add(new BigDecimal(45)); termData.add(new BigDecimal(12.2)); data.put(wrapTerm(String.valueOf(TERM_1)), termData); formula = replaceDelimiters(formula); this.processor.setData(data); String result = this.processor.evaluateFormula(formula, terms); Assert.assertEquals("Should evaluate sum function", "62.7", result); formula = "fn:sum({{" + TERM_1 + "}}, {{PH_M_cm}})"; final List<Object> term2Data = new ArrayList<>(); term2Data.add(new BigDecimal(14.23)); term2Data.add(new BigDecimal(134.12)); data.put(wrapTerm("PH_M_cm"), term2Data); formula = replaceDelimiters(formula); this.processor = new DerivedVariableProcessor(); this.processor.setData(data); result = this.processor.evaluateFormula(formula, terms); Assert.assertEquals("Should evaluate sum function", "211.05", result); }
Source:
public static void snapshotOnVersionChange() throws IOException { String previous = getPreviousVersionString(); String next = FBUtilities.getReleaseVersionString(); RateLimiter snapshotRateLimiter = RateLimiter.create(DatabaseDescriptor.getSnapshotLinksPerSecond() == 0 ? Double.MAX_VALUE : DatabaseDescriptor.getSnapshotLinksPerSecond()); if (!previous.equals(NULL_VERSION.toString()) && !previous.equals(next)) { logger.info("Detected version upgrade from to {}, snapshotting system keyspaces", previous, next); String snapshotName = Keyspace.getTimestampedSnapshotName(format("upgrade-%s-%s", previous, next)); for (String keyspace : SchemaConstants.LOCAL_SYSTEM_KEYSPACE_NAMES) Keyspace.open(keyspace).snapshot(snapshotName, null, false, snapshotRateLimiter); } }

Target:
public static void snapshotOnVersionChange() throws IOException { String previous = getPreviousVersionString(); String next = FBUtilities.getReleaseVersionString(); if (!previous.equals(NULL_VERSION.toString()) && !previous.equals(next)) { logger.info("Detected version upgrade from to {}, snapshotting system keyspaces", previous, next); String snapshotName = Keyspace.getTimestampedSnapshotName(format("upgrade-%s-%s", previous, next)); for (String keyspace : SchemaConstants.LOCAL_SYSTEM_KEYSPACE_NAMES) Keyspace.open(keyspace).snapshot(snapshotName, null, false, null); } }
Source:
public boolean execute() throws Exception { String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); QName varName = new QName("archive", "active-archive"); SrampArchive archive = (SrampArchive) getContext().getVariable(varName); if (archive == null) { print(Messages.i18n.format("NO_ARCHIVE_OPEN")); return false; } else if (archivePathArg.endsWith(File.separator)) { print(Messages.i18n.format("Archive.Path.Arg.should.not.contain.slash.end")); return false; } else { boolean success = archive.removeEntry(archivePathArg); if (success) { print(Messages.i18n.format("RemoveEntry.EntryDeleted")); } else { print(Messages.i18n.format("RemoveEntry.NoEntryFound", archivePathArg)); } } return true; }

Target:
public boolean execute() throws Exception { super.initialize(); String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); if (!validate(archivePathArg)) { return false; } else { boolean success = archive.removeEntry(archivePathArg); if (success) { print(Messages.i18n.format("RemoveEntry.EntryDeleted")); } else { print(Messages.i18n.format("RemoveEntry.NoEntryFound", archivePathArg)); } } return true; }
Source:
public void serialEvent(SerialPortEvent portEvent) { try { logger.debug("Received serial port event " + portEvent.toString() + ":" + portEvent.getEventType()); logger.trace("RXTX library CPU load workaround, sleep forever"); Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { logger.warn("Unable to notify", e); } }

Target:
public void serialEvent(SerialPortEvent portEvent) { try { logger.debug("Received serial port event '{}':'{}'", portEvent.toString(), portEvent.getEventType()); logger.trace("RXTX library CPU load workaround, sleep forever"); Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { logger.warn("Unable to notify", e); } }
Source:
public void cleanup() throws IdGenerationException { return; }

Target:
public void cleanup() { return; }
Source:
public Boolean forAll(Collection<Object> collection, LambdaValue lambda) { Boolean result = Boolean.TRUE; if (collection != null && lambda == null) { result = Boolean.FALSE; } else { for (Object input : collection) { try { if (!Boolean.TRUE.equals(lambda.eval(new Object[] {input }))) { result = Boolean.FALSE; break; } } catch (Exception e) { result = Boolean.FALSE; break; } } } return result; }

Target:
public Boolean forAll(Collection<Object> collection, LambdaValue lambda) { Boolean result = Boolean.TRUE; if (collection == null || lambda == null) { result = Boolean.FALSE; } else { for (Object input : collection) { try { if (!Boolean.TRUE.equals(lambda.eval(new Object[] {input }))) { result = Boolean.FALSE; break; } } catch (Exception e) { result = Boolean.FALSE; break; } } } return result; }
Source:
private void onButtonClick() { if (isSensorAvailable) { Intent intent = new Intent(getContext(), BearingActivity.class); waitingForDataRegistry.waitForData(getFormEntryPrompt().getIndex()); ((Activity) getContext()).startActivityForResult(intent, RequestCodes.BEARING_CAPTURE); } else { binding.bearingButton.setEnabled(false); ToastUtils.showLongToast(R.string.bearing_lack_of_sensors); binding.answerText.setBackground(textBackground); binding.answerText.setFocusable(true); binding.answerText.setFocusableInTouchMode(true); binding.answerText.requestFocus(); } }

Target:
private void onButtonClick() { if (areSensorsAvailable()) { Intent intent = new Intent(getContext(), BearingActivity.class); ((Activity) getContext()).startActivityForResult(intent, RequestCodes.BEARING_CAPTURE); waitingForDataRegistry.waitForData(getFormEntryPrompt().getIndex()); } else { ToastUtils.showLongToast(R.string.bearing_lack_of_sensors); binding.bearingButton.setEnabled(false); binding.answerText.setBackground(new EditText(getContext()).getBackground()); binding.answerText.setFocusable(true); binding.answerText.setFocusableInTouchMode(true); binding.answerText.requestFocus(); } }
Source:
public static void main(String[] args) throws Exception { Nd4j.setDataType(DataBuffer.Type.FLOAT); Cifar cf = new Cifar(); CifarDataSetIterator cifar = new CifarDataSetIterator(batchSize, numSamples, new int[] {height, width, channels}, preProcessCifar, true); CifarDataSetIterator cifarEval = new CifarDataSetIterator(batchSize, 10000, new int[] {height, width, channels}, preProcessCifar, false); MultiLayerNetwork model = cf.trainModelByCifarWithNet(); UIServer uiServer = UIServer.getInstance(); StatsStorage statsStorage = new InMemoryStatsStorage(); uiServer.attach(statsStorage); model.setListeners(new StatsListener( statsStorage), new ScoreIterationListener(freIterations), new EvaluativeListener(cifarEval, 1000)); labelStr = String.join(",", cifar.getLabels().toArray(new String[cifar.getLabels().size()])); model.fit(cifar, epochs); cf.testModelByUnkownImage(model); cf.saveModel(model, "trainModelByCifarWithAlexNet_model.json"); }

Target:
public static void main(String[] args) throws Exception { Cifar cf = new Cifar(); Cifar10DataSetIterator cifar = new Cifar10DataSetIterator(batchSize, new int[]{height, width}, DataSetType.TRAIN, null, seed); Cifar10DataSetIterator cifarEval = new Cifar10DataSetIterator(batchSize, new int[]{height, width}, DataSetType.TEST, null, seed); MultiLayerNetwork model = cf.getModel(); UIServer uiServer = UIServer.getInstance(); StatsStorage statsStorage = new FileStatsStorage(new File(System.getProperty("java.io.tmpdir"), "ui-stats.dl4j")); uiServer.attach(statsStorage); model.setListeners(new StatsListener( statsStorage), new ScoreIterationListener(50), new EvaluativeListener(cifarEval, 1, InvocationType.EPOCH_END)); model.fit(cifar, epochs); log.info("Saving model..."); model.save(new File(System.getProperty("java.io.tmpdir"), "cifarmodel.dl4j.zip"), true); System.exit(0); }
Source:
private void resolve(Resource resource, IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor); resource.eSetDeliver(false); final List<EObject> roots = ((InternalEList<EObject>)resource.getContents()).basicList(); final Iterator<EObject> resourceContent = roots.iterator(); resource.getContents().clear(); SubMonitor subMonitor = progress.newChild(roots.size()); while (resourceContent.hasNext()) { final EObject eObject = resourceContent.next(); resolveCrossReferences(eObject); final TreeIterator<EObject> childContent = basicEAllContents(eObject); SubMonitor childMonitor = subMonitor.newChild(0); while (childContent.hasNext()) { progress.setWorkRemaining(10000); final EObject child = childContent.next(); if (child.eIsProxy()) { final URI proxyURI = ((InternalEObject)child).eProxyURI(); getResource(proxyURI.trimFragment(), false); } else { resolveCrossReferences(child); } childMonitor.worked(1); } subMonitor.worked(1); } resource.getContents().addAll(roots); }

Target:
private void resolve(Resource resource, IProgressMonitor monitor) { resource.eSetDeliver(false); final List<EObject> roots = ((InternalEList<EObject>)resource.getContents()).basicList(); final Iterator<EObject> resourceContent = roots.iterator(); resource.getContents().clear(); SubMonitor subMonitor = SubMonitor.convert(monitor, roots.size()); while (resourceContent.hasNext()) { final EObject eObject = resourceContent.next(); resolveCrossReferences(eObject); final TreeIterator<EObject> childContent = basicEAllContents(eObject); SubMonitor childMonitor = subMonitor.newChild(1); while (childContent.hasNext()) { childMonitor.setWorkRemaining(10000); final EObject child = childContent.next(); if (child.eIsProxy()) { final URI proxyURI = ((InternalEObject)child).eProxyURI(); getResource(proxyURI.trimFragment(), false); } else { resolveCrossReferences(child); } childMonitor.worked(1); } } resource.getContents().addAll(roots); }
Source:
private static void insertConcurrent(CqlSession session) throws InterruptedException { PreparedStatement pst = session.prepare( insertInto("examples", "tbl_sample_kv") .value("id", bindMarker("id")) .value("value", bindMarker("value")) .build()); AtomicInteger insertsCounter = new AtomicInteger(); Set<String> threads = new ConcurrentSkipListSet<>(); ExecutorService executor = Executors.newFixedThreadPool(CONCURRENCY_LEVEL); for (int i = 0; i < TOTAL_NUMBER_OF_INSERTS; i++) { SEMAPHORE.acquire(); final int counter = i; CompletableFuture.supplyAsync( () -> { insertsCounter.incrementAndGet(); threads.add(Thread.currentThread().getName()); ResultSet executeRequest; try { executeRequest = session.execute( pst.bind().setUuid("id", UUID.randomUUID()).setInt("value", counter)); } finally { REQUEST_LATCH.countDown(); SEMAPHORE.release(); } return executeRequest; }, executor); } REQUEST_LATCH.await(); System.out.println( String.format( "Finished executing %s queries with a concurrency level of %s.", insertsCounter.get(), threads.size())); executor.shutdown(); }

Target:
private static void insertConcurrent(CqlSession session) throws InterruptedException { PreparedStatement pst = session.prepare( insertInto("examples", "tbl_sample_kv") .value("id", bindMarker("id")) .value("value", bindMarker("value")) .build()); AtomicInteger insertsCounter = new AtomicInteger(); ExecutorService executor = Executors.newFixedThreadPool(CONCURRENCY_LEVEL); for (int i = 0; i < TOTAL_NUMBER_OF_INSERTS; i++) { SEMAPHORE.acquire(); final int counter = i; executor.submit( () -> { try { session.execute(pst.bind().setUuid("id", UUID.randomUUID()).setInt("value", counter)); insertsCounter.incrementAndGet(); } catch (Throwable t) { t.printStackTrace(); } finally { REQUEST_LATCH.countDown(); SEMAPHORE.release(); } }); } REQUEST_LATCH.await(); System.out.println( String.format( "Finished executing %s queries with a concurrency level of %s.", insertsCounter.get(), CONCURRENCY_LEVEL)); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); }
Source:
public CompletionStage<Void> putAllAsync(@Nonnull K key, @Nonnull Collection<? extends V> value) { checkTrueUnsupportedOperation(isClusterVersionGreaterOrEqual(Versions.V4_1), MINIMUM_VERSION_ERROR_4_1); InternalCompletableFuture<Void> future = new InternalCompletableFuture<>(); Map<Data, Data> dataMap = new HashMap<>(); Collection<Data> dataCollection = CollectionUtil .objectToDataCollection(value, getNodeEngine().getSerializationService()); dataMap.put(toData(key), toData(dataCollection)); putAllInternal(dataMap, future); return future; }

Target:
public CompletionStage<Void> putAllAsync(@Nonnull K key, @Nonnull Collection<? extends V> value) { checkTrueUnsupportedOperation(isClusterVersionGreaterOrEqual(Versions.V4_1), MINIMUM_VERSION_ERROR_4_1); InternalCompletableFuture<Void> future = new InternalCompletableFuture<>(); Map<Data, Data> dataMap = new HashMap<>(); Collection<Data> dataCollection = CollectionUtil .objectToDataCollection(value, getNodeEngine().getSerializationService()); dataMap.put(toData(key), toData(new DataCollection(dataCollection))); putAllInternal(dataMap, future); return future; }
Source:
@Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); }

Target:
@Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); }
Source:
public ThrottledStorageComponent(StorageComponent delegate, MeterRegistry registry, int minConcurrency, int maxConcurrency, int maxQueueSize) { this.delegate = Objects.requireNonNull(delegate); Limit limit = Gradient2Limit.newBuilder() .minLimit(minConcurrency) .initialLimit(minConcurrency) .maxConcurrency(maxConcurrency) .queueSize(0) .build(); this.limiter = new Builder().limit(limit).build(); this.executor = new ThreadPoolExecutor(limit.getLimit(), limit.getLimit(), 0, TimeUnit.DAYS, createQueue(maxQueueSize), new ThottledThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); limit.notifyOnChange(new ThreadPoolExecutorResizer(executor)); if (registry != null) { ActuateThrottleMetrics metrics = new ActuateThrottleMetrics(registry); metrics.bind(executor); metrics.bind(limiter); } }

Target:
public ThrottledStorageComponent(StorageComponent delegate, MeterRegistry registry, int minConcurrency, int maxConcurrency, int maxQueueSize) { this.delegate = Objects.requireNonNull(delegate); Limit limit = Gradient2Limit.newBuilder() .minLimit(minConcurrency) .initialLimit( minConcurrency) .maxConcurrency(maxConcurrency) .queueSize(0) .build(); this.limiter = new Builder().limit(limit).build(); this.executor = new ThreadPoolExecutor(limit.getLimit(), limit.getLimit(), 0, TimeUnit.DAYS, createQueue(maxQueueSize), new ThottledThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); limit.notifyOnChange(new ThreadPoolExecutorResizer(executor)); ActuateThrottleMetrics metrics = new ActuateThrottleMetrics(registry); metrics.bind(executor); metrics.bind(limiter); }
Source:
public void close() throws IOException { super.close(); if (delegate != null) { delegate.close(); } }

Target:
public void close() throws IOException { if (delegate != null) { delegate.close(); } }
Source:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { if (successMessage != null && !successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { if (failMessage != null && !failMessage.isEmpty()) { printError(failMessage); } } return success; }); }

Target:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { if (!successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { printError(failMessage); } return success; }); }
Source:
public static boolean initialize(Context context) { CrashReporter.context = context; preferences = PreferenceManager.getDefaultSharedPreferences(context); setIsCrashReportEnabled(BuildConfig.CRASHLYTICS_CRASH_REPORT_ENABLED); isCrashlyticsInitialized = false; if (isAnonymousReportEnabled() && isCrashReportEnabled) { Fabric.with(context, new Crashlytics()); Log.d(TAG, "INITIALIZED!"); isCrashlyticsInitialized = true; return true; } Log.d(TAG, "INITIALIZATION FAILED! [ Anonymous Report : " + isAnonymousReportEnabled() + " Crash Report : " + isCrashReportEnabled + " ]"); isCrashlyticsInitialized = false; return false; }

Target:
public static boolean initialize(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); if (isReportingEnabled()) { Crashlytics crashlyticsKit = new Crashlytics.Builder() .core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()) .build(); Fabric.with(context, crashlyticsKit); Log.d(TAG, "INITIALIZED!"); return true; } Log.d(TAG, "INITIALIZATION FAILED! [ Anonymous Report : " + isAnonymousReportEnabled() + " Crash Report : " + isCrashReportEnabled + " ]"); return false; }
Source:
public void handle(final ArtifactEvent event) { final Repository repository = getRepository(event); if (!RepositoryLayoutEnum.MAVEN_2.getLayout().equals(repository.getLayout())) { return; } if (event.getType() != ArtifactEventTypeEnum.EVENT_ARTIFACT_FILE_STORED.getType()) { return; } try { mavenIndexGroupRepositoryComponent.updateGroupsContaining(event.getStorageId(), event.getRepositoryId(), event.getPath()); } catch (final IOException e) { logger.error("Unable to update parent group repositories indexes of file " + event.getPath() + " of repository " + event.getRepositoryId(), e); } }

Target:
public void handle(final ArtifactEvent event) { final Repository repository = getRepository(event); if (!Maven2LayoutProvider.ALIAS.equals(repository.getLayout())) { return; } if (event.getType() != ArtifactEventTypeEnum.EVENT_ARTIFACT_FILE_STORED.getType()) { return; } try { mavenIndexGroupRepositoryComponent.updateGroupsContaining(event.getStorageId(), event.getRepositoryId(), event.getPath()); } catch (final IOException e) { logger.error("Unable to update parent group repositories indexes of file " + event.getPath() + " of repository " + event.getRepositoryId(), e); } }
Source:
private void onLoginClick() { if (!PrefUtils.isSignedIn(this)) { mDrawerLayout.closeDrawer(Gravity.LEFT); if (getGoogleApiClient().isConnected()) { disconnectGoogleApiClient(); } PrefUtils.setSignedIn(this); createConnectedGoogleApiClient(); } }

Target:
private void onLoginClick() { if (!PrefUtils.isSignedIn(this)) { mDrawerLayout.closeDrawer(Gravity.LEFT); PrefUtils.setSignedIn(GdgNavDrawerActivity.this); recreateGoogleApiClientIfNeeded(); getGoogleApiClient().connect(); } }
Source:
private Supplier<List<CassandraHealthMetricMeasurement>> getCassandraHealthMetricMeasurements() { return () -> cassandraHealthMetrics.get().stream().map(metric -> ImmutableCassandraHealthMetricMeasurement.builder() .currentValue(cassandraMetricClient.getMetric( metric.type(), metric.name(), metric.attribute(), metric.additionalParams())) .lowerLimit(metric.lowerLimit()) .upperLimit(metric.upperLimit()) .build()) .collect(Collectors.toList()); }

Target:
private Supplier<Collection<? extends CassandraHealthMetricMeasurement>> getCassandraHealthMetricMeasurements() { return cassandraHealthMetrics::getCassandraHealthMetricMeasurements; }
Source:
public void restore() { for (Context context : contexts) { try { context.restore(); } catch (Exception e) { EmbeddedLogger.ROOT_LOGGER.failedToRestoreContext(e, context); } } }

Target:
public void restore() { for (int i = (contexts.size() - 1); i >= 0; i--) { final Context context = contexts.get(i); try { context.restore(); } catch (Exception e) { EmbeddedLogger.ROOT_LOGGER.failedToRestoreContext(e, context); } } }
Source:
public Integer invoke(File base, VirtualChannel channel) throws IOException { if (!base.exists()) { return 0; } assert target.channel == null; final File dest = new File(target.remote); final AtomicInteger count = new AtomicInteger(); scanner.scan(base, reading(new FileVisitor() { private boolean exceptionEncountered; @Override public void visit(File f, String relativePath) throws IOException { if (f.isFile()) { File target = new File(dest, relativePath); mkdirsE(target.getParentFile()); Path targetPath = fileToPath(writing(target)); if(!exceptionEncountered) { try { Files.copy(fileToPath(f), targetPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { exceptionEncountered = true; } } if(exceptionEncountered) { Files.copy(fileToPath(f), targetPath, StandardCopyOption.REPLACE_EXISTING); } count.incrementAndGet(); } } @Override public boolean understandsSymlink() { return true; } @Override public void visitSymlink(File link, String target, String relativePath) throws IOException { try { mkdirsE(new File(dest, relativePath).getParentFile()); writing(new File(dest, target)); Util.createSymlink(dest, target, relativePath, TaskListener.NULL); } catch (InterruptedException x) { throw new IOException(x); } count.incrementAndGet(); } })); return count.get(); }

Target:
public Integer invoke(File base, VirtualChannel channel) throws IOException { if (!base.exists()) { return 0; } assert target.channel == null; final File dest = new File(target.remote); final AtomicInteger count = new AtomicInteger(); scanner.scan(base, reading(new FileVisitor() { private boolean exceptionEncountered; private boolean logMessageShown; @Override public void visit(File f, String relativePath) throws IOException { if (f.isFile()) { File target = new File(dest, relativePath); mkdirsE(target.getParentFile()); Path targetPath = fileToPath(writing(target)); exceptionEncountered = exceptionEncountered || !tryCopyWithAttributes(f, targetPath); if (exceptionEncountered) { Files.copy(fileToPath(f), targetPath, StandardCopyOption.REPLACE_EXISTING); if (!logMessageShown) { LOGGER.log(Level.INFO, "JENKINS-52325: Jenkins failed to retain attributes when copying to {0}, so proceeding without attributes.", dest.getAbsolutePath()); logMessageShown = true; } } count.incrementAndGet(); } } private boolean tryCopyWithAttributes(File f, Path targetPath) { try { Files.copy(fileToPath(f), targetPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOGGER.log(Level.FINE, "Unable to copy: {0}", e.getMessage()); return false; } return true; } @Override public boolean understandsSymlink() { return true; } @Override public void visitSymlink(File link, String target, String relativePath) throws IOException { try { mkdirsE(new File(dest, relativePath).getParentFile()); writing(new File(dest, target)); Util.createSymlink(dest, target, relativePath, TaskListener.NULL); } catch (InterruptedException x) { throw new IOException(x); } count.incrementAndGet(); } })); return count.get(); }
Source:
protected void configure() { bind(TSOChannelHandler.class).in(Singleton.class); bind(TSOStateManager.class).to(TSOStateManagerImpl.class).in(Singleton.class); if (config.getTimestampTypeEnum() == TIMESTAMP_TYPE.WORLD_TIME) { bind(TimestampOracle.class).to(CurrentTimestampOracleImpl.class).in(Singleton.class); } else { bind(TimestampOracle.class).to(TimestampOracleImpl.class).in(Singleton.class); } bind(Panicker.class).to(SystemExitPanicker.class).in(Singleton.class); install(new BatchPoolModule(config)); install(new DisruptorModule(config)); }

Target:
protected void configure() { bind(TSOChannelHandler.class).in(Singleton.class); bind(TSOStateManager.class).to(TSOStateManagerImpl.class).in(Singleton.class); if (config.getTimestampTypeEnum() == TIMESTAMP_TYPE.WORLD_TIME) { bind(TimestampOracle.class).to(WorldClockOracleImpl.class).in(Singleton.class); } else { bind(TimestampOracle.class).to(TimestampOracleImpl.class).in(Singleton.class); } bind(Panicker.class).to(SystemExitPanicker.class).in(Singleton.class); install(new BatchPoolModule(config)); install(new DisruptorModule(config)); }
Source:
private int calculateNextBatchSize() { int positionCount = currentPage.getPositionCount(); int totalEntries = 0; for (int i = currentPosition; i < positionCount; i++) { int currentEntry = maxEntries[i]; if (totalEntries + currentEntry >= MAX_ROWS_PER_BLOCK) { currentBatchTotalEntries = (i == currentPosition ? currentEntry : totalEntries); return Math.max(i - currentPosition, 1); } totalEntries += currentEntry; } currentBatchTotalEntries = totalEntries; return positionCount - currentPosition; }

Target:
private int calculateNextBatchSize() { int positionCount = currentPage.getPositionCount(); int totalLengths = 0; int position = currentPosition; while (position < positionCount) { int length = maxLengths[position]; if (totalLengths + length >= MAX_ROWS_PER_BLOCK) { break; } totalLengths += length; position++; } if (position == currentPosition) { currentBatchTotalLength = maxLengths[currentPosition]; return 1; } currentBatchTotalLength = totalLengths; return position - currentPosition; }
Source:
public boolean getCertifiedProductHasAdditionalSoftware(Long certifiedProductId) { Query query = entityManager.createNativeQuery( "select count(cr.certification_result_id) " + "from " + SCHEMA_NAME + ".certification_result cr " + " inner join " + SCHEMA_NAME + ".certification_result_additional_software cras" + " on cr.certification_result_id = cras.certification_result_id " + "where cr.certified_product_id = :certifiedProductId " + "and (NOT cras.deleted = true)"); query.setParameter("certifiedProductId", certifiedProductId); BigInteger count = (BigInteger) query.getSingleResult(); return count.intValue() > 0; }

Target:
public boolean getCertifiedProductHasAdditionalSoftware(Long certifiedProductId) { Query query = entityManager.createNativeQuery( "select count(cr.certification_result_id) " + "from " + SCHEMA_NAME + ".certification_result cr " + " inner join " + SCHEMA_NAME + ".certification_result_additional_software cras" + " on cr.certification_result_id = cras.certification_result_id " + "where cr.certified_product_id = :certifiedProductId " + "and NOT cras.deleted"); query.setParameter("certifiedProductId", certifiedProductId); BigInteger count = (BigInteger) query.getSingleResult(); return count.intValue() > 0; }
Source:
public MetadataValueList getPermissionFilteredMetadata(Context context, M obj) { List<MetadataValue> metadata = obj.getMetadata(); try { if (context != null && authorizeService.isAdmin(context)) { return new MetadataValueList(metadata); } for (MetadataValue mv : metadata) { MetadataField metadataField = mv.getMetadataField(); if (metadataExposureService .isHidden(context, metadataField.getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) { metadata.remove(mv); } } } catch (SQLException e) { log.error(e); } return new MetadataValueList(metadata); }

Target:
public MetadataValueList getPermissionFilteredMetadata(Context context, M obj) { List<MetadataValue> metadata = obj.getMetadata(); try { if (context != null && authorizeService.isAdmin(context)) { return new MetadataValueList(metadata); } for (MetadataValue mv : metadata) { MetadataField metadataField = mv.getMetadataField(); if (metadataExposureService .isHidden(context, metadataField.getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) { metadata.remove(mv); } } } catch (SQLException e) { log.error("Error filtering metadata based on permissions", e); } return new MetadataValueList(metadata); }
Source:
public void findEvents(final DeviceMessageMetadata deviceMessageMetadata, final FindEventsRequestDataList findEventsQueryMessageDataContainer) throws FunctionalException { LOGGER.info("findEvents for organisationIdentification: for deviceIdentification: {}", deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification()); final SmartMeter smartMeter = this.domainHelperService .findSmartMeter(deviceMessageMetadata.getDeviceIdentification()); LOGGER.info("Sending request message to core."); final RequestMessage requestMessage = new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), smartMeter.getIpAddress(), this.managementMapper.map(findEventsQueryMessageDataContainer, FindEventsRequestList.class)); this.osgpCoreRequestMessageSender.send(requestMessage, deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); }

Target:
public void findEvents(final DeviceMessageMetadata deviceMessageMetadata, final FindEventsRequestDataList findEventsQueryMessageDataContainer) throws FunctionalException { LOGGER.info("findEvents for organisationIdentification: for deviceIdentification: {}", deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification()); final SmartMeter smartMeter = this.domainHelperService .findSmartMeter(deviceMessageMetadata.getDeviceIdentification()); LOGGER.info(SENDING_REQUEST_MESSAGE_TO_CORE_LOG_MSG); final RequestMessage requestMessage = new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), smartMeter.getIpAddress(), this.managementMapper.map(findEventsQueryMessageDataContainer, FindEventsRequestList.class)); this.osgpCoreRequestMessageSender.send(requestMessage, deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); }
Source:
public void logOut() { L.d("Logging out"); AccountUtil.removeAccount(); WikipediaApp.getInstance().getBus().post(new LoginLogoutEvent()); ServiceFactory.get(getWikiSite()).getCsrfToken() .subscribeOn(Schedulers.io()) .flatMap(response -> ServiceFactory.get(getWikiSite()).postLogout(response.query().csrfToken()).subscribeOn(Schedulers.io())) .doFinally(() -> SharedPreferenceCookieManager.getInstance().clearAllCookies()) .subscribe(response -> L.d("Logout complete."), L::e); }

Target:
public void logOut() { L.d("Logging out"); AccountUtil.removeAccount(); ServiceFactory.get(getWikiSite()).getCsrfToken() .subscribeOn(Schedulers.io()) .flatMap(response -> ServiceFactory.get(getWikiSite()).postLogout(response.query().csrfToken()).subscribeOn(Schedulers.io())) .doFinally(() -> SharedPreferenceCookieManager.getInstance().clearAllCookies()) .subscribe(response -> L.d("Logout complete."), L::e); }
Source:
static Hashtable<String, String> getEnv(String dnsServerAddress) { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); if(dnsServerAddress != null && !dnsServerAddress.equals("")) { env.put("java.naming.provider.url", "dns://" + dnsServerAddress); } return env; }

Target:
static Hashtable<String, String> getEnv(String dnsServerAddress) { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); if(dnsServerAddress != null && !dnsServerAddress.isEmpty()) { env.put("java.naming.provider.url", "dns://" + dnsServerAddress); } return env; }
Source:
public List<Path> getPaths() { return subPaths; }

Target:
public List<Path> getPaths() { return Collections.unmodifiableList(subPaths); }
Source:
public ReferencedEnvelope getBounds(Filter filter) { try { GranuleSource source = reader.getGranules(reader.getGridCoverageNames()[0], true); Query query = new Query(null, filter); if (filter != null) { query.setFilter(filter); } FeatureCollection featureCollection = source.getGranules(query); return featureCollection.getBounds(); } catch (Exception exception) { throw new RuntimeException("Failed to collect bounds", exception); } }

Target:
public ReferencedEnvelope getBounds(Filter filter) { try { GranuleSource source = reader.getGranules(reader.getGridCoverageNames()[0], true); Query query = new Query(); if (filter != null) { query.setFilter(filter); } FeatureCollection featureCollection = source.getGranules(query); return featureCollection.getBounds(); } catch (Exception exception) { throw new RuntimeException("Failed to collect bounds", exception); } }
Source:
private List<ServiceReference<?>> getApplicationContextReferences(BundleContext bundleContext) throws InvalidSyntaxException { List<ServiceReference<?>> references = new ArrayList<>(); if (bundleContext != null) { references.addAll(bundleContext.getServiceReferences( ConfigurableApplicationContext.class, String.format(BUNDLE_SYMBOLIC_NAME_FILTER, MDS_ENTITIES_SYMBOLIC_NAME) )); } return references; }

Target:
private List<ServiceReference<ApplicationContext>> getApplicationContextReferences(BundleContext bundleContext) throws InvalidSyntaxException { List<ServiceReference<ApplicationContext>> references = new ArrayList<>(); if (bundleContext != null) { references.addAll(bundleContext.getServiceReferences( ApplicationContext.class, String.format(BUNDLE_SYMBOLIC_NAME_FILTER, MDS_ENTITIES_SYMBOLIC_NAME) )); } return references; }
Source:
public String streamExecutionLog(String streamName) { return restTemplate.getForObject(logsLink.expand(streamName, null).getHref(), String.class); }

Target:
public String streamExecutionLog(String streamName) { return restTemplate.getForObject(logsLink.expand(streamName).getHref(), String.class); }
Source:
public void acquireAllNodes() { this.readLock.lock(); try { logger.info("Starting node acquisition. Acquired nodes=" + getNumberOfAcquiredNodesWithLock() + ", Handled nodes=" + getNumberOfHandledNodesWithLock()); if (getNumberOfAcquiredNodesWithLock() < getNumberOfHandledNodesWithLock()) { int differenceBetweenHandledAndAcquiredNodes = getDifferenceBetweenNumberOfHandledAndAcquiredNodesWithLock(); logger.info("Starting " + differenceBetweenHandledAndAcquiredNodes + " nodes"); startNodes(differenceBetweenHandledAndAcquiredNodes); } } catch (RuntimeException e) { logger.error("Could not start nodes of local infrastructure " + this.nodeSource.getName(), e); } finally { this.readLock.unlock(); } }

Target:
public void acquireAllNodes() { this.readLock.lock(); try { int numberOfHandledNodes = getNumberOfHandledNodesWithLock(); int numberOfAcquiredNodes = getNumberOfAcquiredNodesWithLock(); logger.info("Starting node acquisition. Acquired nodes=" + numberOfAcquiredNodes + ", Handled nodes=" + numberOfHandledNodes); if (numberOfAcquiredNodes < numberOfHandledNodes) { int differenceBetweenHandledAndAcquiredNodes = getDifferenceBetweenNumberOfHandledAndAcquiredNodesWithLock(); logger.info("Starting " + differenceBetweenHandledAndAcquiredNodes + " nodes"); startNodes(differenceBetweenHandledAndAcquiredNodes); } } catch (RuntimeException e) { logger.error("Could not start nodes of local infrastructure " + this.nodeSource.getName(), e); } finally { this.readLock.unlock(); } }
Source:
void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException; } private static final Map<Format, Archiver> formats; static { Map<Format, Archiver> fmts = new EnumMap<Format, Archiver>(Format.class); fmts.put(Format.ZIP, new Archiver() { @Override public ArchiveOutputStream createArchiveOutputStream(OutputStream s) { ArchiveStreamFactory factory = new ArchiveStreamFactory(); try { return factory.createArchiveOutputStream( ArchiveStreamFactory.ZIP, s); } catch (ArchiveException e) { throw die("this can't happen: missing zip support"); } } @Override public void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException { final ZipArchiveEntry entry = new ZipArchiveEntry(path); if (mode == FileMode.REGULAR_FILE) ; else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) entry.setUnixMode(mode.getBits()); else warnArchiveEntryModeIgnored(path); entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); } }); formats = fmts; }

Target:
void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException; } private static final Map<Format, Archiver> formats; static { Map<Format, Archiver> fmts = new EnumMap<Format, Archiver>(Format.class); fmts.put(Format.ZIP, new Archiver() { @Override public ArchiveOutputStream createArchiveOutputStream(OutputStream s) { return new ZipArchiveOutputStream(s); } @Override public void putEntry(String path, FileMode mode, ObjectLoader loader, ArchiveOutputStream out) throws IOException { final ZipArchiveEntry entry = new ZipArchiveEntry(path); if (mode == FileMode.REGULAR_FILE) ; else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) entry.setUnixMode(mode.getBits()); else warnArchiveEntryModeIgnored(path); entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); } }); formats = fmts; }