auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void resetSoftToParent() throws IOException, GitAPIException, CheckoutConflictException { Ref orig_head = repo.getRef(Constants.ORIG_HEAD); if (orig_head == null) { <START> throw new NoHeadException( JGitText.get().cannotRebaseWithoutCurrentHead); <END> } ObjectId orig_headId = orig_head.getObjectId(); try { Git.wrap(repo).reset().setMode(ResetType.SOFT) .setRef("HEAD~1").call(); } finally { repo.writeOrigHead(orig_headId); } }</code><technical_language>This is ORIG_HEAD, HEAD. preserving for --- care had. this work? Ref ref = repo.getRef(ORIG_HEAD); ObjectId oldOrigId = ref == null ? null : ref.getObjectId(); try { ... } finally { repo.writeOrigHead(oldOrigId); }</technical_language>

Target:
private void resetSoftToParent() throws IOException, GitAPIException, CheckoutConflictException { Ref ref = repo.getRef(Constants.ORIG_HEAD); ObjectId orig_head = ref == null ? null : ref.getObjectId(); try { Git.wrap(repo).reset().setMode(ResetType.SOFT) .setRef("HEAD~1").call(); } finally { repo.writeOrigHead(orig_head); } }
Source:
<code>private BrokerCommandBase CreateCommand(AdActionType action, LdapBrokerBaseParameters parameters) { Class type; try { type = Class.forName(GetCommandTypeName(action)); Constructor info = ReflectionUtils.findConstructor(type, parameters.getClass()); Object tempVar = info.newInstance(parameters); return (BrokerCommandBase) ((tempVar instanceof BrokerCommandBase) ? tempVar : null); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException <START> | InvocationTargetException e) { <END> log.errorFormat("LdapBrokerCommandBase: Failed to get type information using reflection for Action: {0}", action); return null; } }</code><technical_language>simply catch Exception, do special handling for exception class</technical_language>

Target:
private BrokerCommandBase CreateCommand(AdActionType action, LdapBrokerBaseParameters parameters) { try { Class type = Class.forName(GetCommandTypeName(action)); Constructor info = ReflectionUtils.findConstructor(type, parameters.getClass()); Object tempVar = info.newInstance(parameters); return (BrokerCommandBase) ((tempVar instanceof BrokerCommandBase) ? tempVar : null); } catch (Exception e) { log.errorFormat("LdapBrokerCommandBase: Failed to get type information using reflection for Action: {0}", action); return null; } }
Source:
<code>public static PRINTER_INFO_2 getPrinterInfo2(String printerName) { IntByReference pcbNeeded = new IntByReference(); IntByReference pcReturned = new IntByReference(); HANDLEByReference pHandle = new HANDLEByReference(); <START> Winspool.INSTANCE.OpenPrinter(printerName, pHandle, null); <END> Winspool.INSTANCE.GetPrinter(pHandle.getValue(), 2, null, 0, pcbNeeded); if (pcbNeeded.getValue() <= 0) { return new PRINTER_INFO_2(); } PRINTER_INFO_2 pinfo2 = new PRINTER_INFO_2(pcbNeeded.getValue()); Winspool.INSTANCE.GetPrinter(pHandle.getValue(), 2, pinfo2.getPointer(), pcbNeeded.getValue(), pcReturned); pinfo2.read(); return pinfo2; }</code><technical_language>Check return of this</technical_language>

Target:
public static PRINTER_INFO_2 getPrinterInfo2(String printerName) { IntByReference pcbNeeded = new IntByReference(); IntByReference pcReturned = new IntByReference(); HANDLEByReference pHandle = new HANDLEByReference(); if (!Winspool.INSTANCE.OpenPrinter(printerName, pHandle, null)) throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); Win32Exception we = null; PRINTER_INFO_2 pinfo2 = null; try { Winspool.INSTANCE.GetPrinter(pHandle.getValue(), 2, null, 0, pcbNeeded); if (pcbNeeded.getValue() <= 0) return new PRINTER_INFO_2(); pinfo2 = new PRINTER_INFO_2(pcbNeeded.getValue()); if (!Winspool.INSTANCE.GetPrinter(pHandle.getValue(), 2, pinfo2.getPointer(), pcbNeeded.getValue(), pcReturned)) throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); pinfo2.read(); } catch (Win32Exception e) { we = e; } finally { if (!Winspool.INSTANCE.ClosePrinter(pHandle.getValue())) { Win32Exception ex = new Win32Exception(Kernel32.INSTANCE.GetLastError()); if (we != null) { ex.addSuppressed(we); } } } if (we != null) { throw we; } return pinfo2; }
Source:
<code>public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() >= 1) { throw new IAE("Function[%s] needs 0 argument", name()); } <START> return ExprEval.of(Math.PI); <END> }</code><technical_language>extracted a private static final constant</technical_language>

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() >= 1) { throw new IAE("Function[%s] needs 0 argument", name()); } return ExprEval.of(PI); }
Source:
<code>public void freeSlot(WorkerSlot slot) { for (SchedulerAssignmentImpl assignment : assignments.values()) { if (assignment.isSlotOccupied(slot)) { assertValidTopologyForModification(assignment.getTopologyId()); assignment.unassignBySlot(slot); String nodeId = slot.getNodeId(); assignment.setTotalSharedOffHeapNodeMemory( nodeId, calculateSharedOffHeapNodedMemory(nodeId, assignment)); nodeToScheduledResourcesCache.computeIfAbsent(nodeId, MAKE_MAP).put(slot, new NormalizedResourceRequest()); <START> nodeToScheduledOffHeapNodeMemoryCache.computeIfAbsent(nodeId, MAKE_MAP_STRING_DOUBLE); <END> nodeToUsedSlotsCache.computeIfAbsent(nodeId, MAKE_SET).remove(slot); } } totalResourcesPerNodeCache.remove(slot.getNodeId()); }</code><technical_language>Is this necessary? add map here, do it</technical_language>

Target:
public void freeSlot(WorkerSlot slot) { for (SchedulerAssignmentImpl assignment : assignments.values()) { if (assignment.isSlotOccupied(slot)) { assertValidTopologyForModification(assignment.getTopologyId()); assignment.unassignBySlot(slot); String nodeId = slot.getNodeId(); assignment.setTotalSharedOffHeapNodeMemory( nodeId, calculateSharedOffHeapNodeMemory(nodeId, assignment)); nodeToScheduledResourcesCache.computeIfAbsent(nodeId, Cluster::makeMap).put(slot, new NormalizedResourceRequest()); nodeToUsedSlotsCache.computeIfAbsent(nodeId, Cluster::makeSet).remove(slot); } } totalResourcesPerNodeCache.remove(slot.getNodeId()); }
Source:
<code>private static void composeMessage(PrivateMessage pm) { info("Opening private messages page"); mainPage.openPrivateMessages(); <START> info("Clicking compose button"); <END> pmPage.clickComposeMessage(); info("Start filling PM fields."); pmPage.fillPrivateMessageFields(pm); }</code><technical_language>this kind of messages of pmPage.clickComponseMessage()</technical_language>

Target:
private static void composeMessage(PrivateMessage pm) { mainPage.openPrivateMessages(); pmPage.clickComposeMessage(); pmPage.fillPrivateMessageFields(pm); }
Source:
<code>public void testCfEqualityChecker() throws TException { CassandraKeyValueServiceImpl kvs; <START> if (keyValueService instanceof CassandraKeyValueServiceImpl) { <END> kvs = (CassandraKeyValueServiceImpl) keyValueService; } else if (keyValueService instanceof SynchronousDelegate) { kvs = (CassandraKeyValueServiceImpl) ((SynchronousDelegate) keyValueService).delegate(); } else if (keyValueService instanceof AsyncDelegate) { kvs = (CassandraKeyValueServiceImpl) ((AsyncDelegate) keyValueService).delegate(); } else if (keyValueService instanceof TableSplittingKeyValueService) { KeyValueService delegate = ((TableSplittingKeyValueService) keyValueService).getDelegate(NEVER_SEEN); assertTrue("The nesting of Key Value Services has apparently changed", delegate instanceof CassandraKeyValueService); kvs = (CassandraKeyValueServiceImpl) delegate; } else { throw new IllegalArgumentException("Can't run this cassandra-specific test against a non-cassandra KVS"); } kvs.createTable(NEVER_SEEN, getMetadata()); List<CfDef> knownCfs = kvs.getClientPool().runWithRetry(client -> client.describe_keyspace(CASSANDRA.getConfig().getKeyspaceOrThrow()).getCf_defs()); CfDef clusterSideCf = Iterables.getOnlyElement(knownCfs.stream() .filter(cf -> cf.getName().equals(getInternalTestTableName())) .collect(Collectors.toList())); assertTrue("After serialization and deserialization to database, Cf metadata did not match.", ColumnFamilyDefinitions.isMatchingCf(kvs.getCfForTable(NEVER_SEEN, getMetadata(), FOUR_DAYS_IN_SECONDS), clusterSideCf)); }</code><technical_language>extract this a method, lines of: getUnderlyingKvs something. revert this patch call other method</technical_language>

Target:
public void testCfEqualityChecker() throws TException { CassandraKeyValueServiceImpl kvs; if (keyValueService instanceof CassandraKeyValueService) { kvs = getUnderlyingKvs(keyValueService); } else if (keyValueService instanceof TableSplittingKeyValueService) { KeyValueService delegate = ((TableSplittingKeyValueService) keyValueService).getDelegate(NEVER_SEEN); assertTrue("The nesting of Key Value Services has apparently changed", delegate instanceof CassandraKeyValueService); kvs = (CassandraKeyValueServiceImpl) delegate; } else { throw getUnrecognizedKeyValueServiceException(); } kvs.createTable(NEVER_SEEN, getMetadata()); List<CfDef> knownCfs = kvs.getClientPool().runWithRetry(client -> client.describe_keyspace(CASSANDRA.getConfig().getKeyspaceOrThrow()).getCf_defs()); CfDef clusterSideCf = Iterables.getOnlyElement(knownCfs.stream() .filter(cf -> cf.getName().equals(getInternalTestTableName())) .collect(Collectors.toList())); assertTrue("After serialization and deserialization to database, Cf metadata did not match.", ColumnFamilyDefinitions.isMatchingCf(kvs.getCfForTable(NEVER_SEEN, getMetadata(), FOUR_DAYS_IN_SECONDS), clusterSideCf)); }
Source:
<code>void save(String id, byte[] data) throws IOException { File file = new File(folder, filename(id)); BufferedSink sink = Okio.buffer(Okio.sink(file)); <START> sink.write(data).flush(); <END> }</code><technical_language>close() sink</technical_language>

Target:
void save(String id, byte[] data) throws IOException { final File file = toFile(id); BufferedSink sink = Okio.buffer(Okio.sink(file)); try { sink.write(data).flush(); } finally { closeQuitely(sink); } }
Source:
<code>protected boolean checkTemplateInStorageDomain() { <START> boolean retValue = getParameters().isImportAsNewEntity() || (!isUnregisteredVM() && checkIfDisksExist(imageList)) || isUnregisteredVM(); <END> if (retValue && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { List<StorageDomain> domains = Backend.getInstance() .runInternalQuery(VdcQueryType.GetStorageDomainsByVmTemplateId, new IdQueryParameters(getVm().getVmtGuid())).getReturnValue(); List<Guid> domainsId = LinqUtils.foreach(domains, new Function<StorageDomain, Guid>() { @Override public Guid eval(StorageDomain storageDomainStatic) { return storageDomainStatic.getId(); } }); if (Collections.disjoint(domainsId, imageToDestinationDomainMap.values())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } return retValue; }</code><technical_language>expression simplified :) - extract variables/reorder isUnregisteredVM condition/etc</technical_language>

Target:
protected boolean checkTemplateInStorageDomain() { boolean retValue = verifyDisksIfNeeded(); if (retValue && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { List<StorageDomain> domains = Backend.getInstance() .runInternalQuery(VdcQueryType.GetStorageDomainsByVmTemplateId, new IdQueryParameters(getVm().getVmtGuid())).getReturnValue(); List<Guid> domainsId = LinqUtils.foreach(domains, new Function<StorageDomain, Guid>() { @Override public Guid eval(StorageDomain storageDomainStatic) { return storageDomainStatic.getId(); } }); if (Collections.disjoint(domainsId, imageToDestinationDomainMap.values())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } return retValue; }
Source:
<code>public int getLaunchTimeout() { if( StringUtils.isEmpty(launchTimeout) || Integer.parseInt(launchTimeout) <= 0 ) <START> launchTimeout = "" + Integer.MAX_VALUE; <END> return Integer.parseInt(launchTimeout); }</code><technical_language>a toString() is building a string</technical_language>

Target:
public int getLaunchTimeout() { return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout; }
Source:
<code>public static void assertPulled(CouchClient client, DatastoreExtended datastore) { <START> logger.entering(DatabaseAssert.class.getCanonicalName(),"assertPulled", new Object[]{client,datastore}); <END> Long start = System.currentTimeMillis(); Set<String> alreadyChecked = new HashSet<String>(); ChangesResultWrapper changesBatch = new ChangesResultWrapper(client.changes("0", BATCH_LIMIT)); while(changesBatch.size() > 0) { for(ChangesResult.Row row : changesBatch.getResults()) { ChangeRowAdaptor adaptor = new ChangeRowAdaptor(row); if(alreadyChecked.contains(adaptor.id)) { continue; } DatabaseAssert.checkChangeRow(adaptor, client, datastore); alreadyChecked.add(adaptor.id); } changesBatch = new ChangesResultWrapper(client.changes(changesBatch.getLastSeq(), BATCH_LIMIT)); } Long end = System.currentTimeMillis(); logger.finest(String.format("Done check took %1 seconds",(end - start)/1000.0)); }</code><technical_language>of this.getClass().getName</technical_language>

Target:
public static void assertPulled(CouchClient client, DatastoreExtended datastore) { logger.entering("DatabaseAssert","assertPulled", new Object[]{client,datastore}); Long start = System.currentTimeMillis(); Set<String> alreadyChecked = new HashSet<String>(); ChangesResultWrapper changesBatch = new ChangesResultWrapper(client.changes("0", BATCH_LIMIT)); while(changesBatch.size() > 0) { for(ChangesResult.Row row : changesBatch.getResults()) { ChangeRowAdaptor adaptor = new ChangeRowAdaptor(row); if(alreadyChecked.contains(adaptor.id)) { continue; } DatabaseAssert.checkChangeRow(adaptor, client, datastore); alreadyChecked.add(adaptor.id); } changesBatch = new ChangesResultWrapper(client.changes(changesBatch.getLastSeq(), BATCH_LIMIT)); } Long end = System.currentTimeMillis(); logger.finest(String.format("Done check took %1 seconds",(end - start)/1000.0)); }
Source:
<code>public EViewHolder(AndroidAnnotationsEnvironment environment, TypeElement annotatedElement) throws Exception { super(environment, annotatedElement); <START> onFinishInflateCallBlock = new ArrayList<>(); <END> addSuppressWarning(); createConstructorAndBuilder(); }</code><technical_language>move initialisation declaration</technical_language>

Target:
public EViewHolder(AndroidAnnotationsEnvironment environment, TypeElement annotatedElement) throws Exception { super(environment, annotatedElement); addSuppressWarning(); createConstructorAndBuilder(); }
Source:
<code>public static void abandon(final PatchSet.Id patchSetId, final IdentifiedUser user, final String message, final ReviewDb db, final AbandonedSender.Factory senderFactory, final ChangeHookRunner hooks) throws NoSuchChangeException, InvalidChangeOperationException, EmailException, OrmException { final Change.Id changeId = patchSetId.getParentKey(); final PatchSet patch = db.patchSets().get(patchSetId); if (patch == null) { throw new NoSuchChangeException(changeId); } final ChangeMessage cmsg = new ChangeMessage(new ChangeMessage.Key(changeId, ChangeUtil .messageUUID(db)), user.getAccountId()); <START> cmsg.setPatchSetId(patchSetId); <END> final StringBuilder msgBuf = new StringBuilder("Patch Set " + patchSetId.get() + ": Abandoned"); if (message != null && message.length() > 0) { msgBuf.append("\n\n"); msgBuf.append(message); } cmsg.setMessage(msgBuf.toString()); final Change updatedChange = db.changes().atomicUpdate(changeId, new AtomicUpdate<Change>() { @Override public Change update(Change change) { if (change.getStatus().isOpen() && change.currentPatchSetId().equals(patchSetId)) { change.setStatus(Change.Status.ABANDONED); ChangeUtil.updated(change); return change; } else { return null; } } }); updatedChange(db, user, updatedChange, cmsg, senderFactory, "Change is no longer open or patchset is not latest"); hooks.doChangeAbandonedHook(updatedChange, user.getAccount(), message); }</code><technical_language>require psid in message constructor prevent future coders adding one</technical_language>

Target:
public static void abandon(final PatchSet.Id patchSetId, final IdentifiedUser user, final String message, final ReviewDb db, final AbandonedSender.Factory senderFactory, final ChangeHookRunner hooks) throws NoSuchChangeException, InvalidChangeOperationException, EmailException, OrmException { final Change.Id changeId = patchSetId.getParentKey(); final PatchSet patch = db.patchSets().get(patchSetId); if (patch == null) { throw new NoSuchChangeException(changeId); } final ChangeMessage cmsg = new ChangeMessage(new ChangeMessage.Key(changeId, ChangeUtil .messageUUID(db)), user.getAccountId(), patchSetId); final StringBuilder msgBuf = new StringBuilder("Patch Set " + patchSetId.get() + ": Abandoned"); if (message != null && message.length() > 0) { msgBuf.append("\n\n"); msgBuf.append(message); } cmsg.setMessage(msgBuf.toString()); final Change updatedChange = db.changes().atomicUpdate(changeId, new AtomicUpdate<Change>() { @Override public Change update(Change change) { if (change.getStatus().isOpen() && change.currentPatchSetId().equals(patchSetId)) { change.setStatus(Change.Status.ABANDONED); ChangeUtil.updated(change); return change; } else { return null; } } }); updatedChange(db, user, updatedChange, cmsg, senderFactory, "Change is no longer open or patchset is not latest"); hooks.doChangeAbandonedHook(updatedChange, user.getAccount(), message); }
Source:
<code>private void release() { terminationReleaseLock.lock(); try { statementLocks.close(); statementLocks = null; terminationReason = null; type = null; securityContext = null; transactionEvent = null; explicitIndexTransactionState = null; if ( txState != null ) { txState.release(); } <START> txState = null; <END> hooksState = null; closeListeners.clear(); reuseCount++; userMetaData = Collections.emptyMap(); userTransactionId = 0; statistics.reset(); operations.release(); pool.release( this ); } finally { terminationReleaseLock.unlock(); } }</code><technical_language>this of if statement</technical_language>

Target:
private void release() { terminationReleaseLock.lock(); try { statementLocks.close(); statementLocks = null; terminationReason = null; type = null; securityContext = null; transactionEvent = null; explicitIndexTransactionState = null; if ( txState != null ) { txState.release(); txState = null; } hooksState = null; closeListeners.clear(); reuseCount++; userMetaData = Collections.emptyMap(); userTransactionId = 0; statistics.reset(); operations.release(); pool.release( this ); } finally { terminationReleaseLock.unlock(); } }
Source:
<code>public void visitNode(AstNode astNode) { if (astNode.is(PythonGrammar.FUNCDEF) && currentFunction == null) { currentFunction = astNode; nestingLevel = 0; } <START> if (currentFunction != null) { <END> if (astNode.is(PythonGrammar.SUITE) && incrementsNestingLevel(astNode)) { nestingLevel++; } checkComplexity(astNode); } }</code><technical_language>want compute generic cognitive complexity, for functions, increase complexity of functions</technical_language>

Target:
public void visitNode(AstNode astNode) { if (astNode.is(PythonGrammar.FUNCDEF, PythonGrammar.CLASSDEF)) { nestingLevelStack.push(new NestingLevel(nestingLevelStack.peek(), astNode)); } else if (astNode.is(PythonGrammar.SUITE)) { if (isSuiteIncrementsNestingLevel(astNode)) { nestingLevelStack.peek().increment(); } } else if (astNode.is(PythonGrammar.IF_STMT, PythonGrammar.WHILE_STMT, PythonGrammar.FOR_STMT, PythonGrammar.EXCEPT_CLAUSE)) { incrementWithNesting(astNode.getFirstChild()); } else if (astNode.is(PythonKeyword.ELIF) || (astNode.is(PythonKeyword.ELSE) && astNode.getNextSibling().is(PythonPunctuator.COLON))) { incrementWithoutNesting(astNode); } else if (astNode.is(PythonGrammar.AND_TEST, PythonGrammar.OR_TEST)) { incrementWithoutNesting(astNode.getFirstChild(PythonKeyword.AND, PythonKeyword.OR)); } else if (astNode.is(PythonGrammar.TEST) && astNode.hasDirectChildren(PythonKeyword.IF)) { incrementWithNesting(astNode.getFirstChild(PythonKeyword.IF)); nestingLevelStack.peek().increment(); } }
Source:
<code>public ITmfTrace openMinimalTrace(String projectName, String traceName, Boolean isExperiment) throws FileNotFoundException, InstantiationException, IllegalAccessException, TmfTraceException, CoreException, TmfTraceImportException { String path = getTracePath(projectName, traceName, isExperiment); IFile file = getFile(path); <START> String location = file.getLocationURI().getPath(); <END> return openAndInitializeTrace(file, location, traceName, ""); }</code><technical_language>This is nullable a warning, return null if null</technical_language>

Target:
public @Nullable ITmfTrace openMinimalTrace(String projectName, String traceName, Boolean isExperiment) throws FileNotFoundException { String path = getTracePath(projectName, traceName, isExperiment); IFile file = getFile(path); String location = file.getLocationURI().getPath(); if (location == null) { return null; } try { return openAndInitializeTrace(file, location, traceName, ""); } catch (InstantiationException | IllegalAccessException | TmfTraceException | TmfTraceImportException e) { throw new NullPointerException(e.toString()); } }
Source:
<code>public boolean deleteContentJson(String uri) throws IOException { boolean deleteSuccessful; Path pathToDelete = toPath(uri); if (!Files.exists(pathToDelete)) { deleteSuccessful = false; } else if (isDataJsonFile(pathToDelete)) { Path parentDir = pathToDelete.getParent(); <START> deleteSuccessful = deleteDataJsonFile(parentDir); <END> } else { deleteSuccessful = Files.deleteIfExists(pathToDelete); } if (deleteSuccessful) { deleteEmptyParentDirectories(pathToDelete); } return deleteSuccessful; }</code><technical_language>minor, functions variables names string deleteDataJSON deleteDataJson. in scope of this PR decide for follow that. I typical standard initialisms acronyms in camelcase is full caps if characters letter caps rest (unless is character) e.g. userID deleteDataJson jsonThingHere</technical_language>

Target:
public boolean deleteContentJson(String uri) throws IOException { boolean deleteSuccessful; Path pathToDelete = toPath(uri); if (!Files.exists(pathToDelete)) { deleteSuccessful = false; } else if (isDataJsonFile(pathToDelete)) { Path parentDir = pathToDelete.getParent(); deleteSuccessful = deleteDataJsonFileAndRelatedPreviousVersionFiles(parentDir); } else { deleteSuccessful = Files.deleteIfExists(pathToDelete); } if (deleteSuccessful) { deleteEmptyParentDirectories(pathToDelete); } return deleteSuccessful; }
Source:
<code>private Map readMapValue(ObjectMapper mapper, String messagePayload) { Map context = null; try { context = mapper.readValue(messagePayload, Map.class); <START> } catch (IOException ioe) { <END> log.error(ioe.getMessage()); } return context; }</code><technical_language>fail instead</technical_language>

Target:
private Map readMapValue(ObjectMapper mapper, String messagePayload) { Map context; try { context = mapper.readValue(messagePayload, Map.class); } catch (IOException ioe) { throw new RuntimeException(ioe); } return context; }
Source:
<code>private String getDeviceIpAddressFromSessionProvider(final String iccId, final DlmsDevice dlmsDevice) throws SessionProviderException, SessionProviderUnsupportedException { final SessionProvider sessionProvider = this.sessionProviderService.getSessionProvider(dlmsDevice .getCommunicationProvider()); String deviceIpAddress; <START> deviceIpAddress = sessionProvider.getIpAddress(iccId); <END> if (deviceIpAddress == null) { this.jasperWirelessSmsClient.sendWakeUpSMS(iccId); for (int i = 0; i < this.dlmsJwccGetSessionRetries; i++) { try { Thread.sleep(this.dlmsJwccGetSessionSleepBetweenRetries); } catch (final InterruptedException e) { throw new SessionProviderException( "Interrupted while sleeping before calling the sessionProvider.getIpAddress", e); } deviceIpAddress = sessionProvider.getIpAddress(iccId); if (deviceIpAddress != null) { return deviceIpAddress; } } } return deviceIpAddress; }</code><technical_language>I a need declaration a separate line</technical_language>

Target:
private String getDeviceIpAddressFromSessionProvider(final String iccId, final DlmsDevice dlmsDevice) throws SessionProviderException, SessionProviderUnsupportedException { final SessionProvider sessionProvider = this.sessionProviderService.getSessionProvider(dlmsDevice .getCommunicationProvider()); String deviceIpAddress = sessionProvider.getIpAddress(iccId); if (deviceIpAddress == null) { this.jasperWirelessSmsClient.sendWakeUpSMS(iccId); for (int i = 0; i < this.jasperGetSessionRetries; i++) { try { Thread.sleep(this.jasperGetSessionSleepBetweenRetries); } catch (final InterruptedException e) { throw new SessionProviderException( "Interrupted while sleeping before calling the sessionProvider.getIpAddress", e); } deviceIpAddress = sessionProvider.getIpAddress(iccId); if (deviceIpAddress != null) { return deviceIpAddress; } } } return deviceIpAddress; }
Source:
<code>public void setTopView(TopView tv) { <START> topPanel.remove(0); <END> switch(tv) { case MAIN: topPanel.add(new FlowPanel()); break; case COMMIT: topPanel.add(commitMessageBlock); break; case PREFERENCES: topPanel.add(settingsPanel); break; case PATCH_SETS: topPanel.add(historyTable); break; case FILES: topPanel.add(fileList); break; } }</code><technical_language>better: topPanel.clear()</technical_language>

Target:
public void setTopView(TopView tv) { topPanel.clear(); switch(tv) { case COMMIT: topPanel.add(commitMessageBlock); break; case PREFERENCES: topPanel.add(settingsPanel); break; case PATCH_SETS: topPanel.add(historyTable); break; case FILES: topPanel.add(fileList); break; } }
Source:
<code>public static void main(String[] args) throws InterruptedException { ApplicationContext context = new GenericXmlApplicationContext("applicationContext.xml"); <START> calculateInvocationTime(context); <END> HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); }</code><technical_language>calculateInvocationTime</technical_language>

Target:
public static void main(String[] args) throws InterruptedException { ApplicationContext context = new GenericXmlApplicationContext("applicationContext.xml"); doInvocation(context); HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); }
Source:
<code>private CodeBlock javadocWithParameters() { CodeBlock.Builder builder = javadoc.toBuilder(); for (ParameterSpec parameterSpec : parameters) { if (!parameterSpec.javadoc.isEmpty()) { <START> builder.add("@param $L $L", parameterSpec.name, parameterSpec.javadoc); <END> } } return builder.build(); }</code><technical_language>close Kotlin line be! I do other tags in a follow-up PR</technical_language>

Target:
private CodeBlock javadocWithParameters() { CodeBlock.Builder builder = javadoc.toBuilder(); boolean emitTagNewline = true; for (ParameterSpec parameterSpec : parameters) { if (!parameterSpec.javadoc.isEmpty()) { if (emitTagNewline && !javadoc.isEmpty()) builder.add("\n"); emitTagNewline = false; builder.add("@param $L $L", parameterSpec.name, parameterSpec.javadoc); } } return builder.build(); }
Source:
<code>private void parsingError(String message) { logger.error(message); String o = "Command Line Options:\n" + " -i <file or directory name> : the name of a directory or file containing the input.\n" + " -o <file or directory name>: the output directory or file where the output will be stored. For \n" + " directories files will share the same name as the input file, so this directory must be different" + " from the input directory.\n" <START> + " -c <file name> : the name of the configuration file.\n" <END> + " -t <number of threads> : Allows users to specify the number of threads to use, by default there will be one" + " thread for every core on the machine.\n"; logger.error(o); System.exit(-1); }</code><technical_language>system exit, STDERR</technical_language>

Target:
private void parsingError(String message) { System.err.println(message); String o = "Command Line Options:\n" + " -i <file or directory name> : the name of a directory or file containing the input.\n" + " -o <file or directory name>: the output directory or file where the output will be stored. For \n" + " directories files will share the same name as the input file, so this directory must be different" + " from the input directory.\n" + " -c <file name> : the name of the configuration file.\n" + " -t <number of threads> : Allows users to specify the number of threads to use, by default there will be one" + " thread for every core on the machine.\n"; System.err.println(o); System.exit(-1); }
Source:
<code>public void testWriteProgressOrPriorityOrMetricsNotUpdatedAfterSweepRunsSuccessfully() { sweeperService.sweepTableFrom(TABLE_REF.getQualifiedName(), encodeStartRow(new byte[] {1, 2, 3})); <START> verify(priorityStore, never()).update(any(), any(), any()); <END> verify(progressStore, never()).saveProgress(any(), any()); Mockito.verifyZeroInteractions(sweepMetrics); }</code><technical_language>delete this test verifying metrics for tests, block this</technical_language>

Target:
public void testWriteProgressOrPriorityOrMetricsNotUpdatedAfterSweepRunsSuccessfully() { sweeperService.sweepTableFrom(TABLE_REF.getQualifiedName(), encodeStartRow(new byte[] {1, 2, 3})); Mockito.verifyZeroInteractions(sweepMetrics); }
Source:
<code><START> private void loadFile(File file) throws ConfigurationException { <END> Configuration config = null; try { config = Configuration.loadFile(file); ExtensionEntry entry = new ExtensionEntry(file, config); ExtensionEntry alreadyLoded = loadedEntries.get(entry.getName()); if (alreadyLoded != null) { throw new ConfigurationException("Could not load the configuration file \"" + file.getAbsolutePath() + "\". The configuration file + \"" + alreadyLoded.file.getAbsolutePath() + "\" already has the name " + entry.getName()); } loadedEntries.put(entry.name, entry); } catch (IOException exception) { throw new ConfigurationException( "Can't load object configuration file \"" + file.getAbsolutePath() + "\".", exception); } }</code><technical_language>please reorder loads place... please reorder public (interface) last</technical_language>

Target:
private void loadFile(File file) throws ConfigurationException { Configuration config = null; try { ExtensionEntry entry = new ExtensionEntry(file); ExtensionEntry alreadyLoded = loadedEntries.get(entry.getName()); if (alreadyLoded != null) { throw new ConfigurationException("Could not load the configuration file \"" + file.getAbsolutePath() + "\". The configuration file + \"" + alreadyLoded.file.getAbsolutePath() + "\" already has the name " + entry.getName()); } loadedEntries.put(entry.name, entry); } catch (IOException exception) { throw new ConfigurationException( "Can't load object configuration file \"" + file.getAbsolutePath() + "\".", exception); } }
Source:
<code>public Key(final HttpRequest request, final int start) { String matchingPath = ((ResteasyUriInfo) request.getUri()).getMatchingPath(); this.path = start == 0 ? matchingPath : matchingPath.substring(start); this.start = start; this.method = request.getHttpMethod(); <START> if (request.getHttpHeaders().getMediaType().getParameters().containsKey("boundary")) { <END> this.contentType = new MediaType(request.getHttpHeaders().getMediaType().getType(), request.getHttpHeaders().getMediaType().getSubtype()); } else { this.contentType = request.getHttpHeaders().getMediaType(); } this.accepts = request.getHttpHeaders().getAcceptableMediaTypes(); }</code><technical_language>get a cache hit "boundary" equals() checks parameters equal. cache if is a "boundary"</technical_language>

Target:
public Key(final HttpRequest request, final int start) { String matchingPath = ((ResteasyUriInfo) request.getUri()).getMatchingPath(); this.path = start == 0 ? matchingPath : matchingPath.substring(start); this.start = start; this.method = request.getHttpMethod(); this.contentType = request.getHttpHeaders().getMediaType(); this.accepts = request.getHttpHeaders().getAcceptableMediaTypes(); }
Source:
<code>public void CheckFiles() { <START> boolean debug = true; <END> if (debug) { downloadAgent = new ChannelDownloader(); } else { downloadAgent = new DefaultDownloader(); } checkNativeDir(); checkSoundDir(); MojamStartup.instance.startgame(); }</code><technical_language>new downloader downloadbar... fully stable i guess.. this false</technical_language>

Target:
public void CheckFiles() { System.out.println(Options.getAsInteger(Options.DLSYSTEM)); if (Options.getAsInteger(Options.DLSYSTEM, 0)==1) { downloadAgent = new ChannelDownloader(); } else if(Options.getAsInteger(Options.DLSYSTEM, 0)==0){ downloadAgent = new DefaultDownloader(); } checkNativeDir(); checkSoundDir(); MojamStartup.instance.startgame(); }
Source:
<code>public boolean isValidValue(final Object element) { boolean result = super.isValidValue(element); if (result) { EObject eObject = EMFHelper.getEObject(element); result = (ProtocolUtils.isProtocol(eObject) && <START> !SystemElementsUtils.isSystemProtocol((Collaboration) eObject) && <END> !SystemElementsUtils.isBaseProtocol((Collaboration) eObject)); } return result; }</code><technical_language>If agreed letting users choose system protocols in browser, I suppose this condition</technical_language>

Target:
public boolean isValidValue(final Object element) { boolean result = super.isValidValue(element); if (result) { EObject eObject = EMFHelper.getEObject(element); result = (ProtocolUtils.isProtocol(eObject) && !SystemElementsUtils.isBaseProtocol((Collaboration) eObject)); } return result; }
Source:
<code>public static Comparator<Graph.Node> getComparator() { Comparator<Graph.Node> comparator = null; String text = System.getProperty("testng.order", Order.INSTANCES.getValue()); Order order = Order.parse(text); switch (order) { case INSTANCES: comparator = new Comparator<Graph.Node>() { @Override public int compare(Graph.Node o1, Graph.Node o2) { return o1.getObject().toString().compareTo(o2.getObject().toString()); } @Override public String toString() { return "Instance_Names"; } }; break; case METHOD_NAMES: comparator = new Comparator<Graph.Node>() { @Override public int compare(Graph.Node o1, Graph.Node o2) { if (o1.getObject() instanceof ITestNGMethod && o2.getObject() instanceof ITestNGMethod) { String n1 = ((ITestNGMethod) o1.getObject()).getMethodName(); String n2 = ((ITestNGMethod) o1.getObject()).getMethodName(); return n1.compareTo(n2); } return o1.getObject().getClass().getName().compareTo(o2.getObject().getClass().getName()); } @Override public String toString() { return "Method_Names"; } }; break; case NONE: <START> default: <END> } return comparator; }</code><technical_language>Instead of null, a default comparator (all params equals)</technical_language>

Target:
public static Comparator<ITestNGMethod> getComparator() { Comparator<ITestNGMethod> comparator; String text = System.getProperty("testng.order", Order.INSTANCES.getValue()); Order order = Order.parse(text); switch (order) { case METHOD_NAMES: comparator = new Comparator<ITestNGMethod>() { @Override public int compare(ITestNGMethod o1, ITestNGMethod o2) { String n1 = o1.getMethodName(); String n2 = o1.getMethodName(); return n1.compareTo(n2); } @Override public String toString() { return "Method_Names"; } }; break; case NONE: comparator = new Comparator<ITestNGMethod>() { @Override public int compare(ITestNGMethod o1, ITestNGMethod o2) { return 0; } @Override public String toString() { return "No_Sorting"; } }; break; case INSTANCES: default: comparator = new Comparator<ITestNGMethod>() { @Override public int compare(ITestNGMethod o1, ITestNGMethod o2) { return o1.toString().compareTo(o2.toString()); } @Override public String toString() { return "Instance_Names"; } }; } return comparator; }
Source:
<code>public long getValueReference() { if (getFmiVariable() != null){ return <START> (int)getFmiVariable().getValueReference(); <END> } return super.getValueReference(); }</code><technical_language>I do code of cast ? result type is long good I</technical_language>

Target:
public long getValueReference() { if (getFmiVariable() != null){ return (long)getFmiVariable().getValueReference(); } return super.getValueReference(); }
Source:
<code>protected final ISeries addSeries(IYSeries series) { ISeriesSet seriesSet = getSwtChart().getSeriesSet(); int seriesCount = seriesSet.getSeries().length; String seriesName = series.getLabel(); IYSeries ySeries = fModel.getSeries().stream().filter(elem -> elem.getLabel().equals(seriesName)).findAny().orElse(null); if (ySeries == null) { setSeries(seriesName, new double[fModel.getXAxis().length]); ySeries = fModel.getSeries().stream().filter(elem -> elem.getLabel().equals(seriesName)).findAny().get(); } String colorTxt = ySeries.getColor(); Color color = getColor(seriesName, colorTxt); switch (ySeries.getSeriesType()) { case IYSeries.BAR: IBarSeries <START> barSeries = (IBarSeries) seriesSet.createSeries(SeriesType.BAR, seriesName); barSeries.setBarColor(color); barSeries.setVisible(true); return barSeries; <END> default: ILineSeries lineSeries = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, seriesName); lineSeries.enableArea(IYSeries.AREA.equals(ySeries.getSeriesType())); lineSeries.setLineStyle(LINE_STYLES.get(getLineStyle(ySeries.getSeriesType(), seriesCount))); lineSeries.setSymbolType(IYSeries.SCATTER.equals(ySeries.getSeriesType()) ? PlotSymbolType.DIAMOND : PlotSymbolType.NONE); lineSeries.setLineColor(color); lineSeries.setVisible(true); return lineSeries; } }</code><technical_language>forget add padding</technical_language>

Target:
protected final ISeries addSeries(IYSeries series) { ISeriesSet seriesSet = getSwtChart().getSeriesSet(); int seriesCount = seriesSet.getSeries().length; String seriesName = series.getLabel(); IYSeries ySeries = fModel.getSeries().stream().filter(elem -> elem.getLabel().equals(seriesName)).findAny().orElse(null); if (ySeries == null) { setSeries(seriesName, new double[fModel.getXAxis().length]); ySeries = fModel.getSeries().stream().filter(elem -> elem.getLabel().equals(seriesName)).findAny().get(); } String colorTxt = ySeries.getColor(); Color color = getColor(seriesName, colorTxt); switch (ySeries.getSeriesType()) { case IYSeries.BAR: IBarSeries barSeries = (IBarSeries) seriesSet.createSeries(SeriesType.BAR, seriesName); barSeries.enableStack(true); barSeries.setBarColor(color); barSeries.setBarPadding(0); barSeries.setVisible(true); return barSeries; default: ILineSeries lineSeries = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, seriesName); lineSeries.enableArea(IYSeries.AREA.equals(ySeries.getSeriesType())); lineSeries.setLineStyle(LINE_STYLES.get(getLineStyle(ySeries.getSeriesType(), seriesCount))); lineSeries.setSymbolType(IYSeries.SCATTER.equals(ySeries.getSeriesType()) ? PlotSymbolType.DIAMOND : PlotSymbolType.NONE); lineSeries.setLineColor(color); lineSeries.setVisible(true); return lineSeries; } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); <START> <END> ArcGISMap map = new ArcGISMap(Basemap.createTopographic()); mMapView.setMap(map); if (ContextCompat.checkSelfPermission(this, reqPermission[0]) == PackageManager.PERMISSION_GRANTED) { applyDictionaRendererToGraphics(); } else { int requestCode = 2; ActivityCompat.requestPermissions(this, reqPermission, requestCode); } }</code><technical_language>remove white space</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.createTopographic()); mMapView.setMap(map); mMapView.addSpatialReferenceChangedListener(spatialReferenceChangedEvent -> mMapView .setViewpointGeometryAsync(mMapView.getGraphicsOverlays().get(0).getExtent())); requestReadPermission(); }
Source:
<code>public boolean implies(Permission p) { if (!(p instanceof PortalAccessPermission)) { return false; } PortalAccessPermission pp = (PortalAccessPermission) p; for (String portal : pp.portalsAccess) { <START> if (!this.allPortals && !portalsAccess.contains(portal)) { <END> return false; } } return true; }</code><technical_language>brain hurts.. if negative negative negative. more positive? I is easy. this code, is clear if is a mistake. Thanks</technical_language>

Target:
public boolean implies(Permission p) { if (!(p instanceof PortalAccessPermission)) { return false; } PortalAccessPermission clientRequest = (PortalAccessPermission) p; if (this.allPortals) { return true; } return portalsAccess.containsAll(clientRequest.portalsAccess); }
Source:
<code>public int[] findJoinPositions(int probePosition, Page probe, int probeGeometryChannel) { Block probeGeometryBlock = probe.getBlock(probeGeometryChannel); if (probeGeometryBlock.isNull(probePosition)) { return EMPTY_ADDRESSES; } Slice slice = probeGeometryBlock.getSlice(probePosition, 0, probeGeometryBlock.getSliceLength(probePosition)); OGCGeometry probeGeometry = deserialize(slice); verify(probeGeometry != null); if (probeGeometry.isEmpty()) { return EMPTY_ADDRESSES; } IntArrayList matchingPositions = new IntArrayList(); Envelope envelope = getEnvelope(probeGeometry); rtree.query(envelope, item -> { GeometryWithPosition geometryWithPosition = (GeometryWithPosition) item; <START> Optional<Double> radius = radiusChannel.map(channel -> getRadius(geometryWithPosition.position)); <END> if (spatialRelationshipTest.apply(geometryWithPosition.ogcGeometry, probeGeometry, radius)) { matchingPositions.add(geometryWithPosition.position); } }); return matchingPositions.toIntArray(null); }</code><technical_language>OptionalDouble is convenient avoids autoboxing</technical_language>

Target:
public int[] findJoinPositions(int probePosition, Page probe, int probeGeometryChannel) { Block probeGeometryBlock = probe.getBlock(probeGeometryChannel); if (probeGeometryBlock.isNull(probePosition)) { return EMPTY_ADDRESSES; } Slice slice = probeGeometryBlock.getSlice(probePosition, 0, probeGeometryBlock.getSliceLength(probePosition)); OGCGeometry probeGeometry = deserialize(slice); verify(probeGeometry != null); if (probeGeometry.isEmpty()) { return EMPTY_ADDRESSES; } IntArrayList matchingPositions = new IntArrayList(); Envelope envelope = getEnvelope(probeGeometry); if (radiusChannel == -1) { rtree.query(envelope, item -> { GeometryWithPosition geometryWithPosition = (GeometryWithPosition) item; if (spatialRelationshipTest.apply(geometryWithPosition.ogcGeometry, probeGeometry, OptionalDouble.empty())) { matchingPositions.add(geometryWithPosition.position); } }); } else { rtree.query(envelope, item -> { GeometryWithPosition geometryWithPosition = (GeometryWithPosition) item; if (spatialRelationshipTest.apply(geometryWithPosition.ogcGeometry, probeGeometry, OptionalDouble.of(getRadius(geometryWithPosition.position)))) { matchingPositions.add(geometryWithPosition.position); } }); } return matchingPositions.toIntArray(null); }
Source:
<code>void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { if (!maybeProcessDecryptCallbackAndComplete()) { <START> cleanupExpiredInFlightRequests(); <END> checkAndMaybeComplete(true); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } } }</code><technical_language>this need if</technical_language>

Target:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { cleanupExpiredInFlightRequests(); checkAndMaybeComplete(); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } }
Source:
<code>public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<SupportedAdditionalClusterFeature> addlFeatures = getOptionalEntity(Set.class, QueryType.GetClusterFeaturesByClusterId, new IdQueryParameters(asGuid(clusterId)), clusterId, false); if (addlFeatures != <START> null && !addlFeatures.isEmpty()) { <END> for (SupportedAdditionalClusterFeature entity : addlFeatures) { if (entity.isEnabled()) { features.getClusterFeatures().add(ClusterFeaturesMapper.map(entity.getFeature(), null)); } } } return features; }</code><technical_language>iterate addlFeatures, checking for emptiness is required</technical_language>

Target:
public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<SupportedAdditionalClusterFeature> addlFeatures = getOptionalEntity(Set.class, QueryType.GetClusterFeaturesByClusterId, new IdQueryParameters(asGuid(clusterId)), clusterId, false); if (addlFeatures != null) { for (SupportedAdditionalClusterFeature entity : addlFeatures) { if (entity.isEnabled()) { features.getClusterFeatures().add(ClusterFeaturesMapper.map(entity.getFeature(), null)); } } } return features; }
Source:
<code>public int execute(AtlasDbServices services) { <START> PrintWriter output = new PrintWriter(System.out, true); <END> if (truncateOldQueue) { services.getKeyValueService().truncateTable(AtlasDbConstants.OLD_SCRUB_TABLE); output.println("Truncated the old scrub queue."); } else { run(services.getKeyValueService(), output, MoreObjects.firstNonNull(batchSize, 1000)); } return 0; }</code><technical_language>Sanitize input of truncate batch-size provided</technical_language>

Target:
public int execute(AtlasDbServices services) { Preconditions.checkArgument(!truncateOldQueue || batchSize == null, "Truncating the old scrub queue and specifying a batch size are mutually exclusive options."); PrintWriter output = new PrintWriter(System.out, true); if (truncateOldQueue) { services.getKeyValueService().truncateTable(AtlasDbConstants.OLD_SCRUB_TABLE); output.println("Truncated the old scrub queue."); } else { run(services.getKeyValueService(), output, MoreObjects.firstNonNull(batchSize, 1000)); } return 0; }
Source:
<code>public void readOnlyIsSupportedByDiskInterface() { disk.setReadOnly(true); disk.setDiskInterface(DiskInterface.VirtIO); assertThat(validator.isReadOnlyPropertyCompatibleWithInterface(), isValid()); <START> disk.setReadOnly(true); <END> disk.setDiskInterface(DiskInterface.VirtIO_SCSI); assertThat(validator.isReadOnlyPropertyCompatibleWithInterface(), isValid()); disk.setReadOnly(false); disk.setDiskInterface(DiskInterface.IDE); assertThat(validator.isReadOnlyPropertyCompatibleWithInterface(), isValid()); }</code><technical_language>set true</technical_language>

Target:
public void readOnlyIsSupportedByDiskInterface() { disk.setReadOnly(true); disk.setDiskInterface(DiskInterface.VirtIO); assertThat(validator.isReadOnlyPropertyCompatibleWithInterface(), isValid()); disk.setReadOnly(false); disk.setDiskInterface(DiskInterface.IDE); assertThat(validator.isReadOnlyPropertyCompatibleWithInterface(), isValid()); }
Source:
<code>private void deleteOrphans() { <START> File[] files = new File(repo.getObjectsDirectory(), "pack").listFiles(); END> if (files == null) { return; } for (File file : files) { if (file.isFile() && isOrphan(file)) { file.delete(); } } }</code><technical_language>I change works. Great. optimisations I suggest. If array files in hand information in hand detect orphans. need do expensive filesystem calls (the .exists() calls) in isOrphan method. I would: - I DirectoryStream a filter for .pack,.index,.bitmap files Matthias suggested - I sort stream ensure packs bitmap/index files. is easy detect orphan index,bitmap files (if follow a .pack file)</technical_language>

Target:
private void deleteOrphans() { Path packDir = Paths.get(repo.getObjectsDirectory().getAbsolutePath(), "pack"); DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { public boolean accept(Path file) throws IOException { String name = file.toFile().getName(); return name != null && name.startsWith("pack") && (name.endsWith("." + PackExt.PACK.getExtension()) || name.endsWith("." + PackExt.BITMAP_INDEX.getExtension()) || name.endsWith( "." + PackExt.INDEX.getExtension())); } }; try { Stream<Path> pathStream = StreamSupport.stream( Files.newDirectoryStream(packDir, filter).spliterator(), false); List<String> names = pathStream .map(path -> path.toFile().getName()) .collect(Collectors.toList()); names.stream().filter(name -> isOrphan(name, names)) .forEach(name -> deleteQuietly(packDir.resolve(name))); } catch (IOException e) { LOG.error(e.getMessage(), e); } }