auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Map<String, RevisionInfo> revisions(ChangeData cd) <START> throws OrmException, IOException { <END> ChangeControl ctl = control(cd); if (ctl == null) { return null; } Collection<PatchSet> src; Map<PatchSet.Id, PatchSet> revEdits = Collections.emptyMap(); if (cd.getLimitedPatchSets() != null || has(ALL_REVISIONS)) { src = cd.patches(db); if (userProvider.get().isIdentifiedUser()) { try { revEdits = edits.read(cd.getChange()); } catch (Exception e) { throw new IOException(e); } } } else { src = Collections.singletonList(cd.currentPatchSet(db)); } Map<String, RevisionInfo> res = Maps.newLinkedHashMap(); for (PatchSet in : src) { if (ctl.isPatchVisible(in, db.get())) { RevisionInfo revisionInfo = toRevisionInfo(cd, in); res.put(in.getRevision().get(), revisionInfo); if (!revEdits.isEmpty()) { PatchSet.Id editId = PatchSet.Id.editFrom(in.getId()); if (revEdits.containsKey(editId)) { PatchSet editPatchSet = revEdits.get(editId); RevisionInfo revisionEditInfo = toRevisionInfo(cd, editPatchSet); if (revisionInfo.isCurrent) { assert(revisionEditInfo.isCurrent); revisionInfo.isCurrent = false; } res.put(editPatchSet.getRevision().get(), revisionEditInfo); } } } } return res; }</code><technical_language>throwing exceptions line this is a bit neater read wrapping</technical_language>

Target:
private Map<String, RevisionInfo> revisions(ChangeData cd) throws OrmException, IOException { ChangeControl ctl = control(cd); if (ctl == null) { return null; } Collection<PatchSet> src; Map<PatchSet.Id, PatchSet> revEdits = Collections.emptyMap(); if (cd.getLimitedPatchSets() != null || has(ALL_REVISIONS)) { src = cd.patches(); if (userProvider.get().isIdentifiedUser()) { try { revEdits = edits.read(cd.getChange()); } catch (Exception e) { throw new IOException(e); } } } else { src = Collections.singletonList(cd.currentPatchSet()); } Map<String, RevisionInfo> res = Maps.newLinkedHashMap(); for (PatchSet in : src) { if (ctl.isPatchVisible(in, db.get())) { RevisionInfo revisionInfo = toRevisionInfo(cd, in); res.put(in.getRevision().get(), revisionInfo); if (!revEdits.isEmpty()) { PatchSet.Id editId = PatchSet.Id.editFrom(in.getId()); if (revEdits.containsKey(editId)) { PatchSet editPatchSet = revEdits.get(editId); RevisionInfo revisionEditInfo = toRevisionInfo(cd, editPatchSet); if (revisionInfo.isCurrent) { assert(revisionEditInfo.isCurrent); revisionInfo.isCurrent = false; } res.put(editPatchSet.getRevision().get(), revisionEditInfo); } } } } return res; }
Source:
<code>public void testSanitizeForLogMessage() { assertNull("should return null if given null", SanitizationHelper.sanitizeForLogMessage(null)); <START> String unsanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" <END> + " It contains some <script>dangerous</script> elements </span>"; String correctSanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" + " It contains some &lt;script&gt;dangerous&lt;&#x2f;script&gt; elements </span>"; assertEquals("Should escape HTML special characters" + "other than in <span class=\"text-danger\">, <span class=\"bold\"> and <br>", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); }</code><technical_language>Some HTML elements other class</technical_language>

Target:
public void testSanitizeForLogMessage() { assertNull("should return null if given null", SanitizationHelper.sanitizeForLogMessage(null)); String unsanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" + " It contains some <script>dangerous</script> elements </span>"; String correctSanitized = "<span class=\"text-danger\"> A <span class=\"bold\">typical</span> log message <br>" + " It contains some &lt;script&gt;dangerous&lt;&#x2f;script&gt; elements </span>"; assertEquals("Should escape HTML special characters" + "other than in <span class=\"text-danger\">, <span class=\"bold\"> and <br>", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); unsanitized = "Hmm. <span class=\"text-info\"> How about this? </span> and <span> this</span>"; correctSanitized = "Hmm. &lt;span class=&quot;text-info&quot;&gt; How about this? </span> and <span> this</span>"; assertEquals("Should escape if span has a class other than 'bold' or 'text-danger'", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); unsanitized = "Single <span class='bold'> quotation mark? </span>"; correctSanitized = "Single &lt;span class=&#39;bold&#39;&gt; quotation mark? </span>"; assertEquals("Should escape if attribute is specified using single quotation marks", correctSanitized, SanitizationHelper.sanitizeForLogMessage(unsanitized)); }
Source:
<code>public Table execute() throws MetaModelException { final MutableTable table = getTable(); final Object source = ElasticSearchUtils.getMappingSource(table); final ElasticSearchDataContext dataContext = getUpdateCallback().getDataContext(); final IndicesAdminClient indicesAdmin = dataContext.getElasticSearchClient().admin().indices(); final String indexName = dataContext.getIndexName(); final PutMappingRequestBuilder requestBuilder = new PutMappingRequestBuilder(indicesAdmin) .setIndices(indexName).setType(table.getName()); <START> if (source instanceof Map) { <END> requestBuilder.setSource((Map<?, ?>) source); } else { requestBuilder.setSource(source); } final PutMappingResponse result = requestBuilder.execute().actionGet(); logger.debug("PutMapping response: acknowledged={}", result.isAcknowledged()); final MutableSchema schema = (MutableSchema) getSchema(); schema.addTable(table); return table; }</code><technical_language>missing something, a Map</technical_language>

Target:
public Table execute() throws MetaModelException { final MutableTable table = getTable(); final Map<String, ?> source = ElasticSearchUtils.getMappingSource(table); final ElasticSearchDataContext dataContext = getUpdateCallback().getDataContext(); final IndicesAdminClient indicesAdmin = dataContext.getElasticSearchClient().admin().indices(); final String indexName = dataContext.getIndexName(); final PutMappingRequestBuilder requestBuilder = new PutMappingRequestBuilder(indicesAdmin).setIndices(indexName) .setType(table.getName()); requestBuilder.setSource(source); final PutMappingResponse result = requestBuilder.execute().actionGet(); logger.debug("PutMapping response: acknowledged={}", result.isAcknowledged()); final MutableSchema schema = (MutableSchema) getSchema(); schema.addTable(table); return table; }
Source:
<code>ShardSyncTaskManager(final IKinesisProxy kinesisProxy, final ILeaseManager<KinesisClientLease> leaseManager, final InitialPositionInStreamExtended initialPositionInStream, final boolean cleanupLeasesUponShardCompletion, final boolean ignoreUnexpectedChildShards, final long shardSyncIdleTimeMillis, final IMetricsFactory metricsFactory, ExecutorService executorService, ShardSyncer shardSyncer) { this.kinesisProxy = kinesisProxy; this.leaseManager = leaseManager; this.metricsFactory = metricsFactory; this.cleanupLeasesUponShardCompletion = cleanupLeasesUponShardCompletion; this.ignoreUnexpectedChildShards = ignoreUnexpectedChildShards; this.shardSyncIdleTimeMillis = shardSyncIdleTimeMillis; this.executorService = executorService; this.initialPositionInStream = initialPositionInStream; this.shardSyncer = shardSyncer; this.shardSyncRequestPending = new AtomicBoolean(false); <START> this.lock = new ReentrantLock(Boolean.TRUE); <END> }</code><technical_language>specific reason enforce fairness</technical_language>

Target:
ShardSyncTaskManager(final IKinesisProxy kinesisProxy, final ILeaseManager<KinesisClientLease> leaseManager, final InitialPositionInStreamExtended initialPositionInStream, final boolean cleanupLeasesUponShardCompletion, final boolean ignoreUnexpectedChildShards, final long shardSyncIdleTimeMillis, final IMetricsFactory metricsFactory, ExecutorService executorService, ShardSyncer shardSyncer) { this.kinesisProxy = kinesisProxy; this.leaseManager = leaseManager; this.metricsFactory = metricsFactory; this.cleanupLeasesUponShardCompletion = cleanupLeasesUponShardCompletion; this.ignoreUnexpectedChildShards = ignoreUnexpectedChildShards; this.shardSyncIdleTimeMillis = shardSyncIdleTimeMillis; this.executorService = executorService; this.initialPositionInStream = initialPositionInStream; this.shardSyncer = shardSyncer; this.shardSyncRequestPending = new AtomicBoolean(false); this.lock = new ReentrantLock(); }
Source:
<code>protected void endWithFailure() { if (commandCoordinatorUtil.getCommandExecutionStatus(getCommandId()) != CommandExecutionStatus.EXECUTED) { changeStorageDomainStatusInTransaction(loadStoragePoolIsoMap(), StorageDomainStatus.Unknown); auditLogDirector.log(this, AuditLogType.USER_DEACTIVATE_STORAGE_DOMAIN_OVF_UPDATE_INCOMPLETE); } else { StoragePoolIsoMap map = loadStoragePoolIsoMap(); <START> changeDomainStatusWithCompensation(map, <END> StorageDomainStatus.Unknown, StorageDomainStatus.Active, getCompensationContext()); } setSucceeded(true); }</code><technical_language>do need compensation data here</technical_language>

Target:
protected void endWithFailure() { if (commandCoordinatorUtil.getCommandExecutionStatus(getCommandId()) != CommandExecutionStatus.EXECUTED) { changeStorageDomainStatusInTransaction(loadStoragePoolIsoMap(), StorageDomainStatus.Unknown); auditLogDirector.log(this, AuditLogType.USER_DEACTIVATE_STORAGE_DOMAIN_OVF_UPDATE_INCOMPLETE); } else { changeStorageDomainStatusInTransaction(loadStoragePoolIsoMap(), StorageDomainStatus.Active); } setSucceeded(true); }
Source:
<code>private void emitAndIndent(String s) { try { boolean first = true; for (String line : s.split("\n", -1)) { if (!first) { if ((javadoc || comment) && trailingNewline) { emitIndentation(); out.append(javadoc ? " *" : " } out.append('\n'); trailingNewline = true; } first = false; if (line.isEmpty()) continue; if (trailingNewline) { emitIndentation(); if (javadoc) { out.append(" * "); } else if (comment) { out.append(" } } out.append(line); trailingNewline = false; } } catch (IOException e) { <START> throw new RuntimeException(e); <END> } }</code><technical_language>rethrow? want IO leaking over</technical_language>

Target:
private CodeWriter emitAndIndent(String s) throws IOException { boolean first = true; for (String line : s.split("\n", -1)) { if (!first) { if ((javadoc || comment) && trailingNewline) { emitIndentation(); out.append(javadoc ? " *" : " } out.append('\n'); trailingNewline = true; } first = false; if (line.isEmpty()) continue; if (trailingNewline) { emitIndentation(); if (javadoc) { out.append(" * "); } else if (comment) { out.append(" } } out.append(line); trailingNewline = false; } return this; }
Source:
<code>private X509CertificateHolder getCertFromTruststoreWithX500Name( X500Name name, KeyStore truststore) throws OcspCheckerException { Enumeration<String> aliases; try { aliases = truststore.aliases(); } catch (KeyStoreException e) { throw new OcspCheckerException("Problem getting aliases from truststore.", e); } while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); try { java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias); X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded()); X500Name currentName = currentCertHolder.getSubject(); if (name.equals(currentName)) { return currentCertHolder; } } catch (CertificateEncodingException | IOException | KeyStoreException ignore) { <START> } <END> } throw new OcspCheckerException( String.format("Could not find cert matching X500Name of %s", name)); }</code><technical_language>If exception thrown, logging information exception. Otherwise, troubleshoot happening attaching a debugger</technical_language>

Target:
private X509CertificateHolder getCertFromTruststoreWithX500Name( X500Name name, KeyStore truststore) throws OcspCheckerException { Enumeration<String> aliases; try { aliases = truststore.aliases(); } catch (KeyStoreException e) { throw new OcspCheckerException( "Problem getting aliases from truststore." + NOT_VERIFIED_MSG, e); } while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); try { java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias); X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded()); X500Name currentName = currentCertHolder.getSubject(); if (name.equals(currentName)) { return currentCertHolder; } } catch (CertificateEncodingException | IOException | KeyStoreException e) { LOGGER.debug("Problem loading truststore certificate." + CONTINUING_MSG, e); } } throw new OcspCheckerException( String.format("Could not find cert matching X500Name of %s.", name) + NOT_VERIFIED_MSG); }
Source:
<code>public void testList() { List<Snapshot> snapshots = snapshotApi().getList(); assertNotNull(snapshots); <START> assertFalse(snapshots.isEmpty()); <END> }</code><technical_language>Assert contains created snapshot</technical_language>

Target:
public void testList() { List<Snapshot> snapshots = snapshotApi().list(); assertNotNull(snapshots); assertFalse(snapshots.isEmpty()); assertTrue(Iterables.any(snapshots, new Predicate<Snapshot>() { @Override public boolean apply(Snapshot input) { return input.id().equals(testSnapshot.id()); } })); }
Source:
<code>public Collection<? extends GrantedAuthority> getAuthorities() { return user.getRoles() <START> .stream() <END> .map(a -> new SimpleGrantedAuthority(a.getUserRole())) .collect(Collectors.toSet()); }</code><technical_language>suggestion .stream() .map(UserRole::getName) .map(SimpleGrantedAuthority::new)</technical_language>

Target:
public Collection<? extends GrantedAuthority> getAuthorities() { return user.getRoles() .stream() .map(SecurityRole::getRoleName) .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); }
Source:
<code>public static IGerritHudsonTriggerConfig getConfig(String serverName) { <START> return PluginImpl.getInstance().getServer(serverName).getConfig(); <END> }</code><technical_language>npe ''' GerritServer server = getServer(serverName); if (server != null) return server.getConfig(); else { return null; } '''</technical_language>

Target:
public static IGerritHudsonTriggerConfig getConfig(String serverName) { GerritServer server = PluginImpl.getInstance().getServer(serverName); if (server != null) { return server.getConfig(); } else { logger.error("Could not find the Gerrit Server: {}", serverName); return null; } }
Source:
<code>public void addToOrderBook(Order order) { if(order instanceof BuyOrder){ <START> if(buyOrders.containsKey(order.getStockSymbol())){ buyOrders.get(order.getStockSymbol()).add(order); }else{ ArrayList<Order> orders = new ArrayList<Order>(); orders.add(order); buyOrders.put(order.getStockSymbol(), orders); } <END> }else{ if(sellOrders.containsKey(order.getStockSymbol())){ sellOrders.get(order.getStockSymbol()).add(order); }else{ ArrayList<Order> orders = new ArrayList<Order>(); orders.add(order); sellOrders.put(order.getStockSymbol(), orders); } } }</code><technical_language>Consider extracting this function called addBuyOrderToOrderBook addBuyOrder</technical_language>

Target:
public void addToOrderBook(Order order) { if(order instanceof BuyOrder){ addBuyOrderToOrderBook(order); }else{ addSellOrderToOrderBook(order); } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Record {"); sb.append("id = ").append(id).append(", "); sb.append("title = ").append(title).append(", "); sb.append("type = "); switch (type) { case TYPE_EXPENSE: sb.append("expense"); break; case TYPE_INCOME: sb.append("income"); break; default: sb.append("unknown"); break; } sb.append(", "); <START> sb.append("date = ").append(time).append(", "); <END> sb.append("category = ").append(category).append(", "); sb.append("price = ").append(price).append(", "); sb.append("account = ").append(account).append(", "); sb.append("currency = ").append(currency).append(", "); sb.append("decimals = ").append(decimals); sb.append("}"); return sb.toString(); }</code><technical_language>breaks format</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Record {"); sb.append("id = ").append(id).append(", "); sb.append("title = ").append(title).append(", "); sb.append("type = "); switch (type) { case TYPE_EXPENSE: sb.append("expense"); break; case TYPE_INCOME: sb.append("income"); break; default: sb.append("unknown"); break; } sb.append(", "); sb.append("time = ").append(time).append(", "); sb.append("category = ").append(category).append(", "); sb.append("price = ").append(price).append(", "); sb.append("account = ").append(account).append(", "); sb.append("currency = ").append(currency).append(", "); sb.append("decimals = ").append(decimals); sb.append("}"); return sb.toString(); }
Source:
<code>private void onRemove() { if (getWindow() != null) { return; } <START> ConfirmationModel model = (ConfirmationModel) getWindow(); <END> if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> prms = getRemoveUnregisteredEntityParams(storagePool.getId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), prms, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }</code><technical_language>noted in other commits, NPE</technical_language>

Target:
private void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> removeUnregisteredEntityParams = getRemoveUnregisteredEntityParams(storagePool.getId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), removeUnregisteredEntityParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }
Source:
<code>public String getRequestorName(UserNotification notification) { if(notification == null) return "Unavailable"; if(notification.getRequestor() == null) return "Unavailable"; <START> return (notification.getRequestor().getLastName() != null && notification.getRequestor().getLastName() != null) ? notification.getRequestor().getFirstName() + " " + notification.getRequestor().getLastName() : "Unavailable"; <END> }</code><technical_language>More English. lines above</technical_language>

Target:
public String getRequestorName(UserNotification notification) { if(notification == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable"); if(notification.getRequestor() == null) return BundleUtil.getStringFromBundle("notification.email.info.unavailable");; return (notification.getRequestor().getLastName() != null && notification.getRequestor().getLastName() != null) ? notification.getRequestor().getFirstName() + " " + notification.getRequestor().getLastName() : BundleUtil.getStringFromBundle("notification.email.info.unavailable"); }
Source:
<code>private void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user, VmInterfaceManager vmInterfaceManager) { VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(vm.getClusterId(), vm.getStoragePoolId(), AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES); MacPool macPool = vmInterfaceManager.getMacPool(); List<VmNic> dbNics = vmNicDao.getAllForVm(vm.getId()); List<VmNetworkInterface> newNics = vm.getInterfaces(); Map<String, Long> preexistingMacsUsageFrequency = countMacUsageFrequency(dbNics); Map<String, Long> macsFromRequestUsageFrequency = countMacUsageFrequency(newNics); vmInterfaceManager.removeAll(dbNics); releaseExtraMacs(macPool, preexistingMacsUsageFrequency, macsFromRequestUsageFrequency); allocateMacsMissingInMacPool(macPool, newNics, preexistingMacsUsageFrequency, macsFromRequestUsageFrequency); for (VmNetworkInterface vmInterface : newNics) { vmInterface.setVmId(vm.getId()); if (vmInterface.getId() == null) { vmInterface.setId(Guid.newGuid()); } vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user); vmInterfaceManager.persistIface(vmInterface, compensationContext); } vnicProfileHelper.auditInvalidInterfaces(vm.getName()); <START> } <END></code><technical_language>is a place hold this code introduce one, this code longer</technical_language>

Target:
private void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user, VmInterfaceManager vmInterfaceManager) { VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(vm.getClusterId(), vm.getStoragePoolId(), AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES); MacPool macPool = vmInterfaceManager.getMacPool(); List<VmNic> dbNics = vmNicDao.getAllForVm(vm.getId()); new SyncMacsInMacPool(macPool, auditLogDirector, dbNics, vm.getInterfaces()).sync(); vmInterfaceManager.removeAll(dbNics); for (VmNetworkInterface vmInterface : vm.getInterfaces()) { vmInterface.setVmId(vm.getId()); if (vmInterface.getId() == null) { vmInterface.setId(Guid.newGuid()); } vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user); vmInterfaceManager.persistIface(vmInterface, compensationContext); } vnicProfileHelper.auditInvalidInterfaces(vm.getName()); }
Source:
<code>private void handleTask(Task task, Map<String, Object> parameters) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); boolean success = true; try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { <START> for (TaskActionInformation action : task.getActions()) { <END> executor.execute(task, action, task.getActions().indexOf(action), taskContext); } handleSuccess(parameters, task); } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { handleError(parameters, task, e); success = false; } catch (RuntimeException e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); success = false; } if (task.retryTaskOnFailure()) { if (success && isTaskRetryAlreadyScheduled(parameters)) { unscheduleTaskRetry(task.getTrigger().getEffectiveListenerRetrySubject()); } else if (!success && !isTaskRetryAlreadyScheduled(parameters)) { scheduleTaskRetry(task, parameters); } } }</code><technical_language>simple for loop instead of foreach</technical_language>

Target:
private void handleTask(Task task, Map<String, Object> parameters) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); boolean success = true; try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { for (int i = 0; i < task.getActions().size(); i++) { executor.execute(task, task.getActions().get(i), i, taskContext); } handleSuccess(parameters, task); } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { handleError(parameters, task, e); success = false; } catch (RuntimeException e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); success = false; } if (task.retryTaskOnFailure()) { if (success && isTaskRetryAlreadyScheduled(parameters)) { unscheduleTaskRetry(task.getTrigger().getEffectiveListenerRetrySubject()); } else if (!success && !isTaskRetryAlreadyScheduled(parameters)) { scheduleTaskRetry(task, parameters); } } }
Source:
<code>public void toParamDocs_Test() { <START> final List<ParamDescriptor> pds = Arrays.asList( <END> createParamDescriptor("1"), createParamDescriptor("2")); final ImmutableMap<String, String> result = toParamDocs(pds); assertThat(result.size(), is(2)); assertThat(result.get("Name1"), is("Description1")); assertThat(result.get("Name2"), is("Description2")); }</code><technical_language>This ImmutableList</technical_language>

Target:
public void toParamDocs_Test() { final ImmutableList<ParamDescriptor> pds = ImmutableList.of( createParamDescriptor("1"), createParamDescriptor("2")); final ImmutableMap<String, String> result = toParamDocs(pds); assertThat(result.size(), is(2)); assertThat(result.get("Name1"), is("Description1")); assertThat(result.get("Name2"), is("Description2")); }
Source:
<code>private List<Filter> makeFilters(BitmapIndexSelector selector) { final Indexed<String> allDimVals = selector.getDimensionValues(dimension); final List<Filter> filters = Lists.newArrayList(); if (allDimVals != null) <START> { <END> for (int i = 0; i < allDimVals.size(); i++) { String dimVal = allDimVals.get(i); if (value.equals(fn.apply(dimVal))) { filters.add(new SelectorFilter(dimension, dimVal)); } } } else if (value.equals(fn.apply(null))) { filters.add(new SelectorFilter(dimension, null)); } return filters; }</code><technical_language>code looked ok, I druid codebase style is parenthesis line for class/method opening</technical_language>

Target:
private List<Filter> makeFilters(BitmapIndexSelector selector) { Indexed<String> allDimVals = selector.getDimensionValues(dimension); final List<Filter> filters = Lists.newArrayList(); if (allDimVals == null) { allDimVals = new Indexed<String>() { @Override public Iterator<String> iterator() { return null; } @Override public Class<? extends String> getClazz() { return null; } @Override public int size() { return 1; } @Override public String get(int index) { return null;} @Override public int indexOf(String value) { return 0; } }; } for (int i = 0; i < allDimVals.size(); i++) { String dimVal = allDimVals.get(i); if (value.equals(Strings.nullToEmpty(fn.apply(dimVal)))) { filters.add(new SelectorFilter(dimension, dimVal)); } } return filters; }
Source:
<code>public Object getChromedriverPorts() { <START> return getCapability(AndroidMobileCapabilityType.BUILD_TOOLS_VERSION); <END> }</code><technical_language>BUILD_TOOLS_VERSION</technical_language>

Target:
public List<Object> getChromedriverPorts() { return (List<Object>) getCapability(AndroidMobileCapabilityType.CHROMEDRIVER_PORTS); }
Source:
<code>private void showCallout(final Graphic graphic) { TextView calloutContent = new TextView(getApplicationContext()); calloutContent.setTextColor(Color.BLACK); calloutContent.setText(graphic.getAttributes().get("PlaceName").toString() + "\n" + graphic.getAttributes().get("StAddr").toString()); mCallout = mMapView.getCallout(); mCallout.setShowOptions(new Callout.ShowOptions(true, false, false)); mCallout.setContent(calloutContent); <START> mCallout.setLocation(graphic.computeCalloutLocation(graphic.getGeometry().getExtent().getCenter(), mMapView)); <END> mCallout.show(); mMapView.addMapScaleChangedListener(new MapScaleChangedListener() { @Override public void mapScaleChanged(MapScaleChangedEvent mapScaleChangedEvent) { if (mMapView.getCallout().isShowing()) { mCallout.setLocation(graphic.computeCalloutLocation(graphic.getGeometry().getExtent().getCenter(), mMapView)); mCallout.show(); } } }); }</code><technical_language>Attach GeoElement Callout. This allow for callout leader position follow symbol offset above: java // set leader position show callout Point calloutLocation = graphic.computeCalloutLocation(graphic.getGeometry().getExtent().getCenter(), mMapView); mCallout.setGeoElement(graphic, calloutLocation); ![attach](<LINK_0></technical_language>

Target:
private void showCallout(final Graphic graphic) { TextView calloutContent = new TextView(getApplicationContext()); calloutContent.setTextColor(Color.BLACK); calloutContent.setText(graphic.getAttributes().get("PlaceName").toString() + "\n" + graphic.getAttributes().get("StAddr").toString()); mCallout = mMapView.getCallout(); mCallout.setShowOptions(new Callout.ShowOptions(true, false, false)); mCallout.setContent(calloutContent); Point calloutLocation = graphic.computeCalloutLocation(graphic.getGeometry().getExtent().getCenter(), mMapView); mCallout.setGeoElement(graphic, calloutLocation); mCallout.show(); }
Source:
<code>public void sessionEnded( ExecutionEvent event ) { if ( logger.isInfoEnabled() ) { if ( event.getSession().getProjects().size() > 1 ) { logReactorSummary( event.getSession() ); } ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); <START> if ( iLoggerFactory instanceof MavenSlf4jWrapperFactory ) <END> { MavenSlf4jWrapperFactory loggerFactory = (MavenSlf4jWrapperFactory) iLoggerFactory; loggerFactory.getLogLevelRecorder() .filter( LogLevelRecorder::isThresholdHit ) .ifPresent(recorder -> event.getSession().getResult().addException( new Exception( "Build failed due to log statements with a higher severity than allowed. " + "Fix the logged issues or remove flag --fail-level (-fl)." ) ) ); } logResult( event.getSession() ); logStats( event.getSession() ); infoLine( '-' ); } }</code><technical_language>missing else here. Is a situation this condition is _not_ true? If is, fl switch work? If so, work</technical_language>

Target:
public void sessionEnded( ExecutionEvent event ) { if ( logger.isInfoEnabled() ) { if ( event.getSession().getProjects().size() > 1 ) { logReactorSummary( event.getSession() ); } ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if ( iLoggerFactory instanceof MavenSlf4jWrapperFactory ) { MavenSlf4jWrapperFactory loggerFactory = (MavenSlf4jWrapperFactory) iLoggerFactory; loggerFactory.getLogLevelRecorder() .filter( LogLevelRecorder::metThreshold ) .ifPresent( recorder -> event.getSession().getResult().addException( new Exception( "Build failed due to log statements with a higher severity than allowed. " + "Fix the logged issues or remove flag --fail-on-severity (-fos)." ) ) ); } logResult( event.getSession() ); logStats( event.getSession() ); infoLine( '-' ); } }
Source:
<code>protected Spec[] getSelectedSpecs() { <START> List list <END> = fileAssociationViewer.getStructuredSelection().toList(); return (Spec[]) list.toArray(new Spec[list.size()]); }</code><technical_language>add generic</technical_language>

Target:
protected Spec[] getSelectedSpecs() { List<Spec> list = fileAssociationViewer.getStructuredSelection().toList(); return list.toArray(new Spec[list.size()]); }
Source:
<code>public void consume(String message) { logger.info("[MQ] receive message: {}: {}.", this.queue(), message); if (Strings.isNullOrEmpty(message)) { logger.error("[MQ] message is empty"); return; } <START> try { <END> InvestSuccessMessage investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); UserInfo userInfo = investSuccessMessage.getUserInfo(); InvestInfo investInfo = investSuccessMessage.getInvestInfo(); LoanDetailInfo loanDetailInfo = investSuccessMessage.getLoanDetailInfo(); if (duringActivities() && loanDetailInfo.isActivity() && loanDetailInfo.getActivityDesc().equals("早鸟专享")){ schoolExclusive(userInfo, investInfo, loanDetailInfo); } if (duringActivities() && !loanDetailInfo.getActivityType().equals("NEWBIE") && !investInfo.getTransferStatus().equals("SUCCESS") && investInfo.getStatus().equals("SUCCESS")) { activityInvestMapper.create(new ActivityInvestModel(investInfo.getInvestId(), userInfo.getLoginName(), userInfo.getUserName(), userInfo.getMobile(), investInfo.getAmount(), ActivityCategory.SCHOOL_SEASON_ACTIVITY.name())); } } catch (IOException e) { logger.error("[MQ] parse message failed: {}: {}.", this.queue(), message); } }</code><technical_language>duringActivities()</technical_language>

Target:
public void consume(String message) { logger.info("[MQ] receive message: {}: {}.", this.queue(), message); if (Strings.isNullOrEmpty(message)) { logger.error("[MQ] message is empty"); return; } Date date=DateTime.now().toDate(); if(!date.before(activitySchoolSeasonEndTime) || !date.after(activitySchoolSeasonStartTime)){ return; } try { InvestSuccessMessage investSuccessMessage = JsonConverter.readValue(message, InvestSuccessMessage.class); UserInfo userInfo = investSuccessMessage.getUserInfo(); InvestInfo investInfo = investSuccessMessage.getInvestInfo(); LoanDetailInfo loanDetailInfo = investSuccessMessage.getLoanDetailInfo(); if (loanDetailInfo.isActivity() && loanDetailInfo.getActivityDesc().equals("早鸟专享")){ schoolExclusive(userInfo, investInfo, loanDetailInfo); } if (!loanDetailInfo.getActivityType().equals("NEWBIE") && !investInfo.getTransferStatus().equals("SUCCESS") && investInfo.getStatus().equals("SUCCESS")) { activityInvestMapper.create(new ActivityInvestModel(investInfo.getInvestId(), userInfo.getLoginName(), userInfo.getUserName(), userInfo.getMobile(), investInfo.getAmount(), ActivityCategory.SCHOOL_SEASON_ACTIVITY.name())); } } catch (IOException e) { logger.error("[MQ] parse message failed: {}: {}.", this.queue(), message); } }
Source:
<code>private void saturateCluster(FSSchedulerNode schedulerNode) { while (!Resources.isNone(schedulerNode.getUnallocatedResource())) { createDefaultContainer(); <START> schedulerNode.allocateContainer(containers.get((int)containerNum - 1)); <END> schedulerNode.containerStarted(containers.get((int)containerNum - 1). getContainerId()); } }</code><technical_language>need typecast if change int</technical_language>

Target:
private void saturateCluster(FSSchedulerNode schedulerNode) { while (!Resources.isNone(schedulerNode.getUnallocatedResource())) { createDefaultContainer(); schedulerNode.allocateContainer(containers.get(containers.size() - 1)); schedulerNode.containerStarted(containers.get(containers.size() - 1). getContainerId()); } }
Source:
<code>public static Driver getNextAvailableDriverFromPool() { if (driverPool.isEmpty()) { <START> driverPool.add(new DriverSetup().instantiateDriver()); <END> } return driverPool.remove(); }</code><technical_language>work? java if (driverPool.isEmpty()) { return new DriverSetup().instantiateDriver(); } return driverPool.remove(); feels safer limit number of interactions driverPool</technical_language>

Target:
private static Driver getNextAvailableDriverFromPool() { return driverPool.remove(); }
Source:
<code>public Message<?> getMessage(UUID messageId) { Assert.notNull(messageId, "'messageId' must not be null"); MessageHolder messageHolder = (MessageHolder) doRetrieve(MESSAGE_KEY_PREFIX + messageId); if (messageHolder != null) { <START> Assert.isInstanceOf(MessageHolder.class, messageHolder); <END> return messageHolder.getMessage(); } else { return null; } }</code><technical_language>? a ClassCastException above</technical_language>

Target:
public Message<?> getMessage(UUID messageId) { Assert.notNull(messageId, "'messageId' must not be null"); Object object = doRetrieve(MESSAGE_KEY_PREFIX + messageId); if (object != null) { return extractMessage(object); } else { return null; } }
Source:
<code>public void call() { for (String threadToIgnore : this.threadsToIgnore) { if (Thread.currentThread().getName().matches(threadToIgnore)) { <START> log.debug("Thread with name [" + Thread.currentThread().getName() +"] matches the " <END> + "regex [" + threadToIgnore + "]. A span will not be created for this Thread."); this.actual.call(); return; } } Span span = this.parent; boolean created = false; if (span != null) { span = this.tracer.continueSpan(span); } else { span = this.tracer.createSpan(RXJAVA_COMPONENT); this.tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, RXJAVA_COMPONENT); this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getThreadNameKey(), Thread.currentThread().getName()); created = true; } try { this.actual.call(); } finally { if (created) { this.tracer.close(span); } else { this.tracer.detach(span); } } }</code><technical_language>extract Thread.currentThread().getName()? a format string (and avoid string cat debug on)</technical_language>

Target:
public void call() { for (String threadToIgnore : this.threadsToIgnore) { String threadName = Thread.currentThread().getName(); if (threadName.matches(threadToIgnore)) { log.debug(String.format( "Thread with name [%s] matches the regex [%s]. A span will not be created for this Thread.", threadName, threadToIgnore)); this.actual.call(); return; } } Span span = this.parent; boolean created = false; if (span != null) { span = this.tracer.continueSpan(span); } else { span = this.tracer.createSpan(RXJAVA_COMPONENT); this.tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, RXJAVA_COMPONENT); this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getThreadNameKey(), Thread.currentThread().getName()); created = true; } try { this.actual.call(); } finally { if (created) { this.tracer.close(span); } else { this.tracer.detach(span); } } }
Source:
<code>public Result onResponse(Result result, Invoker<?> invoker, Invocation invocation) { String startAttach = invocation.getAttachment(TIMEOUT_FILTER_START_TIME); if (startAttach != null) { long elapsed = System.currentTimeMillis() - Long.valueOf(startAttach); if (invoker.getUrl() != null && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(), "timeout", Integer.MAX_VALUE)) { if (logger.isWarnEnabled()) { logger.warn("invoke time out. method: " + invocation.getMethodName() + " arguments: " + Arrays.toString(invocation.getArguments()) + " , url is " + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms."); } } <START> invocation.getAttachments().remove(TIMEOUT_FILTER_START_TIME); <END> } return result; }</code><technical_language>I care scenario here, in case of exception while executing _invoker.invoke(invocation)_ , remove TIMEOUT_FILTER_START_TIME attacchment ? I this piece of code care of removing TIMEOUT_FILTER_START_TIME in case of exception. do say</technical_language>

Target:
public Result onResponse(Result result, Invoker<?> invoker, Invocation invocation) { String startAttach = invocation.getAttachment(TIMEOUT_FILTER_START_TIME); if (startAttach != null) { long elapsed = System.currentTimeMillis() - Long.valueOf(startAttach); if (invoker.getUrl() != null && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(), "timeout", Integer.MAX_VALUE)) { if (logger.isWarnEnabled()) { logger.warn("invoke time out. method: " + invocation.getMethodName() + " arguments: " + Arrays.toString(invocation.getArguments()) + " , url is " + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms."); } } } return result; }
Source:
<code>public void validateCertificate(X509Certificate certificate, PKI.CAType caType) throws IOException { File tmpCertFile = File.createTempFile("cert-", ".pem"); try (FileWriter fw = new FileWriter(tmpCertFile, false)) { fw.write(X509Factory.BEGIN_CERT); fw.write("\n"); fw.write(b64encoder.encodeToString(certificate.getEncoded())); fw.write("\n"); fw.write(X509Factory.END_CERT); fw.flush(); List<String> commands = new ArrayList<>(); commands.add(OPENSSL); commands.add("verify"); commands.add("-CAfile"); <START> commands.add(Paths.get(pki.getCACertsDir(caType), "ca-chain.cert.pem").toString()); <END> commands.add("-crl_check"); commands.add("-CRLfile"); commands.add(pki.getCACRLPath(caType)); commands.add(tmpCertFile.getAbsolutePath()); executeCommand(commands, false); } catch (GeneralSecurityException ex) { throw new IOException(ex); } finally { tmpCertFile.delete(); } }</code><technical_language>This a method in PKI. Depending intermediate CA chain file name "ca-chain.cert.pem" differ</technical_language>

Target:
public void validateCertificate(X509Certificate certificate, PKI.CAType caType) throws IOException { File tmpCertFile = File.createTempFile("cert-", ".pem"); try (FileWriter fw = new FileWriter(tmpCertFile, false)) { fw.write(X509Factory.BEGIN_CERT); fw.write("\n"); fw.write(b64encoder.encodeToString(certificate.getEncoded())); fw.write("\n"); fw.write(X509Factory.END_CERT); fw.flush(); List<String> commands = new ArrayList<>(); commands.add(OPENSSL); commands.add("verify"); commands.add("-CAfile"); commands.add(pki.getChainOfTrustFilePath(caType).toString()); commands.add("-crl_check"); commands.add("-CRLfile"); commands.add(pki.getCACRLPath(caType).toString()); commands.add(tmpCertFile.getAbsolutePath()); executeCommand(commands, false); } catch (GeneralSecurityException ex) { throw new IOException(ex); } finally { tmpCertFile.delete(); } }
Source:
<code>public ProjectHandleResolverDTO mapProjectHandleResolver(IProjectHandleResolver resolver) { ProjectHandleResolverDTO dto = new ProjectHandleResolverDTO(); dto.setDescription(resolver.getDescription()); dto.setHandleExample(resolver.getHandleExample()); dto.setHandlePattern(resolver.getHandlePattern()); dto.setId(resolver.getId()); dto.setProjectName(resolver.getProjectName()); dto.setProjectUrl(resolver.getProjectUrl()); dto.setResolvedHandlePattern(resolver.getResolvedHandlePattern()); dto.setUsername(resolver.getUsername()); dto.setResolvedHandleExample(resolver.getResolvedHandleExample()); dto.setValidation(resolver.getValidation().toString()); <START> System.out.println(resolver.getValidation().toString()); <END> return dto; }</code><technical_language>delete</technical_language>

Target:
public ProjectHandleResolverDTO mapProjectHandleResolver(IProjectHandleResolver resolver) { ProjectHandleResolverDTO dto = new ProjectHandleResolverDTO(); dto.setDescription(resolver.getDescription()); dto.setHandleExample(resolver.getHandleExample()); dto.setHandlePattern(resolver.getHandlePattern()); dto.setId(resolver.getId()); dto.setProjectName(resolver.getProjectName()); dto.setProjectUrl(resolver.getProjectUrl()); dto.setResolvedHandlePattern(resolver.getResolvedHandlePattern()); dto.setUsername(resolver.getUsername()); dto.setResolvedHandleExample(resolver.getResolvedHandleExample()); dto.setValidation(resolver.getValidation()); return dto; }
Source:
<code><START> public int getMinRecordLength() { <END> return 0; }</code><technical_language>Need implement</technical_language>

Target:
public int getMinRecordLength() { Iterator<DataStore> iter = delegateHandler.getWritableDelegatesIterator(); int minRecordLength = Integer.MAX_VALUE; while (iter.hasNext()) { minRecordLength = Math.min(minRecordLength, iter.next().getMinRecordLength()); } return minRecordLength; }
Source:
<code>public SSHClient getSSHClient() { Long timeout = TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds)); EngineSSHClient sshclient = new EngineSSHClient(); if (getParameters().getvds().getSSHKeyFingerprint().isEmpty()) { sshclient.setVds(getParameters().getvds()); try { getParameters().getvds().setSSHKeyFingerprint(sshclient.getHostFingerprint()); <START> DbFacade.getInstance().getVdsStaticDao().save(getParameters().getVdsStaticData()); <END> } catch (Exception e) { log.warnFormat( "couldn't set fingerprint for vds", e); } } else { sshclient.setVds(getParameters().getvds()); } sshclient.setHardTimeout(timeout); sshclient.setSoftTimeout(timeout); sshclient.setPassword(getParameters().getPassword()); return (SSHClient) sshclient; }</code><technical_language>this logic EngineSSHClient</technical_language>

Target:
public EngineSSHClient getSSHClient() { Long timeout = TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds)); EngineSSHClient sshclient = new EngineSSHClient(); if (getParameters().getvds().getSSHKeyFingerprint().isEmpty()) { sshclient.setVds(getParameters().getvds()); try { getParameters().getvds().setSSHKeyFingerprint(sshclient.getHostFingerprint()); DbFacade.getInstance().getVdsStaticDao().save(getParameters().getVdsStaticData()); } catch (Exception e) { log.warnFormat( "couldn't set fingerprint for vds", e); } } else { sshclient.setVds(getParameters().getvds()); } sshclient.setHardTimeout(timeout); sshclient.setSoftTimeout(timeout); sshclient.setPassword(getParameters().getPassword()); return sshclient; }
Source:
<code>public void cleanupPreCommitConditionsOnFailure() { MutableLong counter = new MutableLong(0L); PreCommitCondition failsCondition = new PreCommitCondition() { @Override public void throwIfConditionInvalid(long timestamp) { throw new TransactionFailedRetriableException("Condition failed"); } @Override public void cleanup() { counter.increment(); } }; try { <START> wrappedSerializableTxManager.runTaskWithConditionThrowOnConflict(failsCondition, (tx, condition) -> { <END> tx.put(TABLE, ImmutableMap.of(TEST_CELL, PtBytes.toBytes("value"))); return null; }); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(1)); try { wrappedSerializableTxManager.runTaskWithConditionReadOnly(failsCondition, (tx, condition) -> tx.get(TABLE, ImmutableSet.of(TEST_CELL))); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(2)); }</code><technical_language>a formatting changes formatting necessary, wrappedSerializableTxManager expect of disappear</technical_language>

Target:
public void cleanupPreCommitConditionsOnFailure() { MutableLong counter = new MutableLong(0L); PreCommitCondition failsCondition = new PreCommitCondition() { @Override public void throwIfConditionInvalid(long timestamp) { throw new TransactionFailedRetriableException("Condition failed"); } @Override public void cleanup() { counter.increment(); } }; try { serializableTxManager.runTaskWithConditionThrowOnConflict(failsCondition, (tx, condition) -> { tx.put(TABLE, ImmutableMap.of(TEST_CELL, PtBytes.toBytes("value"))); return null; }); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(1)); try { serializableTxManager.runTaskWithConditionReadOnly(failsCondition, (tx, condition) -> tx.get(TABLE, ImmutableSet.of(TEST_CELL))); fail(); } catch (TransactionFailedRetriableException e) { } assertThat(counter.intValue(), is(2)); }
Source:
<code>private void deleteSwipeItem(int position) { <START> if (swipeDismissListener != null && position < listView.getCount()) { <END> swipeDismissListener.delete(position); } }</code><technical_language>wrong fix</technical_language>

Target:
private void deleteSwipeItem(int position) { if (swipeDismissListener != null) { swipeDismissListener.delete(position); } }
Source:
<code>private void createAPI(APIRequest apiCreationRequest, String apiName) throws APIManagerIntegrationTestException { <START> <END> HttpResponse apiCreationResponse = apiPublisher.addAPI(apiCreationRequest); assertEquals(apiCreationResponse.getResponseCode(), Response.Status.OK.getStatusCode(), "Response Code miss matched when creating the API"); verifyResponse(apiCreationResponse); }</code><technical_language>Lets remove type of new lines</technical_language>

Target:
private void createAPI(APIRequest apiCreationRequest, String apiName) throws APIManagerIntegrationTestException { HttpResponse apiCreationResponse = apiPublisher.addAPI(apiCreationRequest); verifyResponse(apiCreationResponse); }