auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected static List<BuildFileStatement> getUnparseableStatements(@NotNull PsiElement element) { if (element instanceof PsiComment || element instanceof GrStatement) { return ImmutableList.of((BuildFileStatement)new UnparseableStatement(element)); } else { return <START> Collections.EMPTY_LIST; <END> } }</code><technical_language>Collections.emptyList()</technical_language>

Target:
protected static List<BuildFileStatement> getUnparseableStatements(@NotNull PsiElement element) { if (element instanceof PsiComment || element instanceof GrStatement) { return ImmutableList.of((BuildFileStatement)new UnparseableStatement(element)); } else { return Collections.emptyList(); } }
Source:
<code>private String prettyPrintContentWithTimeOut( AsyncPrettyPrinter asyncPrettyPrinter, InputStream in) throws IOException { AsyncPrettyPrintingTask prettyPrintingTask = new AsyncPrettyPrintingTask( in, asyncPrettyPrinter); <START> ExecutorService executor = Executors.newSingleThreadExecutor(); <END> Future<String> future = executor.submit(prettyPrintingTask); String prettifiedContent = ""; try { prettifiedContent = future.get(10, TimeUnit.SECONDS); } catch (TimeoutException | InterruptedException | ExecutionException e) { future.cancel(true); prettifiedContent = "Failed to pretty print data\n" + readContentsAsUTF8(in); } executor.shutdownNow(); return prettifiedContent; }</code><technical_language>Re-use this</technical_language>

Target:
private String prettyPrintContentWithTimeOut( AsyncPrettyPrinter asyncPrettyPrinter, InputStream in) throws IOException { AsyncPrettyPrintingCallable prettyPrintingCallable = new AsyncPrettyPrintingCallable( in, asyncPrettyPrinter); Future<String> future = sExecutorService.submit(prettyPrintingCallable); try { return Util.getUninterruptibly(future, PRETTY_PRINT_TIMEOUT_SEC, TimeUnit.SECONDS); } catch (TimeoutException e) { future.cancel(true); return "Time out after " + PRETTY_PRINT_TIMEOUT_SEC + " seconds of attempting to pretty print\n" + Util.readAsUTF8(in); } catch (ExecutionException e) { Throwable cause = e.getCause(); ExceptionUtil.propagateIfInstanceOf(cause, IOException.class); throw ExceptionUtil.propagate(cause); } }
Source:
<code>private void setTokenRefreshCredentials(LogicalPlan dag, Configuration conf) throws IOException { String principal = conf.get(StramClientUtils.TOKEN_REFRESH_PRINCIPAL, StramUserLogin.getPrincipal()); String keytabPath = principal.equals(StramUserLogin.getPrincipal()) ? conf.get(StramClientUtils.KEY_TAB_FILE, null) : conf.get(StramClientUtils.TOKEN_REFRESH_KEYTAB, null); <START> LOG.debug("User principal is {}, keytab is {}", principal, keytabPath); <END> if (keytabPath == null) { String keytab = StramUserLogin.getKeytab(); if (keytab != null) { Path localKeyTabPath = new Path(keytab); try (FileSystem fs = StramClientUtils.newFileSystemInstance(conf)) { Path destPath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), localKeyTabPath.getName()); if (!fs.exists(destPath)) { fs.copyFromLocalFile(false, false, localKeyTabPath, destPath); } keytabPath = destPath.toString(); } } } if ((principal != null) && (keytabPath != null)) { dag.setAttribute(LogicalPlan.PRINCIPAL, principal); dag.setAttribute(LogicalPlan.KEY_TAB_FILE, keytabPath); } else { LOG.warn("Credentials for refreshing tokens not available, application may not be able to run indefinitely"); } }</code><technical_language>Moe log line if</technical_language>

Target:
private void setTokenRefreshCredentials(LogicalPlan dag, Configuration conf) throws IOException { String principal = conf.get(StramClientUtils.TOKEN_REFRESH_PRINCIPAL, StramUserLogin.getPrincipal()); String keytabPath = conf.get(StramClientUtils.TOKEN_REFRESH_KEYTAB, conf.get(StramClientUtils.KEY_TAB_FILE)); if (keytabPath == null) { String keytab = StramUserLogin.getKeytab(); if (keytab != null) { Path localKeyTabPath = new Path(keytab); try (FileSystem fs = StramClientUtils.newFileSystemInstance(conf)) { Path destPath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), localKeyTabPath.getName()); if (!fs.exists(destPath)) { fs.copyFromLocalFile(false, false, localKeyTabPath, destPath); } keytabPath = destPath.toString(); } } } LOG.debug("User principal is {}, keytab is {}", principal, keytabPath); if ((principal != null) && (keytabPath != null)) { dag.setAttribute(LogicalPlan.PRINCIPAL, principal); dag.setAttribute(LogicalPlan.KEY_TAB_FILE, keytabPath); } else { LOG.warn("Credentials for refreshing tokens not available, application may not be able to run indefinitely"); } }
Source:
<code>public void testIsExternalVM() throws IOException { try { XmlDocument xmlDocument = new XmlDocument(getXmlOvfData()); assertFalse("VM should not be external VM", OvfUtils.isExternalVM(xmlDocument)); <START> } catch (Exception e) { e.printStackTrace(); } <END> }</code><technical_language><LINK_0> In other words: throw exception fail test if parsing XML fails</technical_language>

Target:
public void testIsExternalVM() throws Exception { XmlDocument xmlDocument = new XmlDocument(getXmlOvfData()); assertFalse("VM should not be external VM", OvfUtils.isExternalVM(xmlDocument)); }
Source:
<code>private void abandonTask(EntityRef oreon) { TaskComponent oreonTaskComponent = oreon.getComponent(TaskComponent.class); if (!oreonTaskComponent.assignedTaskType.equals(AssignedTaskType.None)) { <START> oreon.getComponent(OreonSpawnComponent.class).parent.getOwner().send(new ChatMessageEvent("Oreon got stuck abandoning task", notificationMessageEntity)); <END> NetworkComponent networkComponent = new NetworkComponent(); networkComponent.replicateMode = NetworkComponent.ReplicateMode.ALWAYS; taskEntity = entityManager.create(networkComponent); TaskComponent taskComponent = new TaskComponent(); taskComponent.assignedTaskType = oreonTaskComponent.assignedTaskType; taskComponent.assignedAreaIndex = oreonTaskComponent.assignedAreaIndex; taskComponent.taskRegion = oreonTaskComponent.taskRegion; taskComponent.creationTime = oreonTaskComponent.creationTime; taskComponent.buildingType = oreonTaskComponent.buildingType; taskComponent.taskStatus = oreonTaskComponent.taskStatus; taskEntity.addComponent(taskComponent); OreonSpawnComponent oreonSpawnComponent = oreon.getComponent(OreonSpawnComponent.class); addTask(oreonSpawnComponent.parent); oreonTaskComponent.assignedTaskType = AssignedTaskType.None; oreon.saveComponent(oreonTaskComponent); } }</code><technical_language>"Oreon stuck abandoning task" cleaned "Oreon stuck. Abandoning task." good if identify oreon</technical_language>

Target:
private void abandonTask(EntityRef oreon) { TaskComponent oreonTaskComponent = oreon.getComponent(TaskComponent.class); if (!oreonTaskComponent.assignedTaskType.equals(AssignedTaskType.None)) { String message = "Oreon " + oreon.getComponent(NameTagComponent.class).text + " got stuck. Abandoning task " + oreonTaskComponent.assignedTaskType; oreon.getComponent(OreonSpawnComponent.class).parent.getOwner().send(new ChatMessageEvent(message, notificationMessageEntity)); NetworkComponent networkComponent = new NetworkComponent(); networkComponent.replicateMode = NetworkComponent.ReplicateMode.ALWAYS; taskEntity = entityManager.create(networkComponent); TaskComponent taskComponent = new TaskComponent(); taskComponent.assignedTaskType = oreonTaskComponent.assignedTaskType; taskComponent.assignedAreaIndex = oreonTaskComponent.assignedAreaIndex; taskComponent.taskRegion = oreonTaskComponent.taskRegion; taskComponent.creationTime = oreonTaskComponent.creationTime; taskComponent.buildingType = oreonTaskComponent.buildingType; taskComponent.taskStatus = oreonTaskComponent.taskStatus; taskEntity.addComponent(taskComponent); OreonSpawnComponent oreonSpawnComponent = oreon.getComponent(OreonSpawnComponent.class); addTask(oreonSpawnComponent.parent); oreonTaskComponent.assignedTaskType = AssignedTaskType.None; oreon.saveComponent(oreonTaskComponent); } }
Source:
<code><START> public StoreContext createStoreContext() { <END> return new StoreContext( getUri(), getBucket(), getConf(), getUsername(), owner, boundedThreadPool, executorCapacity, invoker, getInstrumentation(), getStorageStatistics(), getInputPolicy(), changeDetectionPolicy, enableMultiObjectsDelete, metadataStore, this::keyToQualifiedPath, useListV1, false, (prefix, len) -> createTmpFileForWrite(prefix, len, getConf()), this::getBucketLocation); }</code><technical_language>This is a lot of parameters for a constructor. I worth builder pattern for readability sustainability</technical_language>

Target:
public StoreContext createStoreContext() { return new StoreContext( getUri(), getBucket(), getConf(), getUsername(), owner, boundedThreadPool, executorCapacity, invoker, getInstrumentation(), getStorageStatistics(), getInputPolicy(), changeDetectionPolicy, enableMultiObjectsDelete, metadataStore, useListV1, new ContextAccessorsImpl(), getTtlTimeProvider()); }
Source:
<code>private List<Snapshot> prepareSnapshotConfigWithoutImage(Guid imageGroupToRemove) { List<Snapshot> result = new LinkedList<Snapshot>(); List<DiskImage> snapshotDisks = getDiskImageDao().getAllSnapshotsForImageGroup(imageGroupToRemove); for (DiskImage snapshotDisk : snapshotDisks) { NGuid vmSnapshotId = snapshotDisk.getvm_snapshot_id(); if (vmSnapshotId != null && !Guid.Empty.equals(vmSnapshotId.getValue())) { Snapshot updated = <START> prepareSnapshotConfigWithoutImageSingleImage(snapshotDisk.getvm_snapshot_id().getValue(), <END> snapshotDisk.getImageId()); if (updated != null) { result.add(updated); } } } return result; }</code><technical_language>vmSnapshotId here, fetched checked it</technical_language>

Target:
private List<Snapshot> prepareSnapshotConfigWithoutImage(Guid imageGroupToRemove) { List<Snapshot> result = new LinkedList<Snapshot>(); List<DiskImage> snapshotDisks = getDiskImageDao().getAllSnapshotsForImageGroup(imageGroupToRemove); for (DiskImage snapshotDisk : snapshotDisks) { NGuid vmSnapshotId = snapshotDisk.getvm_snapshot_id(); if (vmSnapshotId != null && !Guid.Empty.equals(vmSnapshotId.getValue())) { Snapshot updated = prepareSnapshotConfigWithoutImageSingleImage(vmSnapshotId.getValue(), snapshotDisk.getImageId()); if (updated != null) { result.add(updated); } } } return result; }
Source:
<code>private static boolean tryRecursiveDelete(File file) { boolean success = true; for (int i = 0; i < 5; i++) { <START> success = recursiveDelete(file); <END> if (success) { break; } else { System.gc(); System.runFinalization(); try { Thread.sleep(50); } catch (InterruptedException e) { } } } return success; }</code><technical_language>add a check OS Windows looping this</technical_language>

Target:
private static boolean tryRecursiveDelete(File file) { boolean interrupted = false; try { for (int i = 0; i < 5; i++) { if (recursiveDelete(file) || !isWindows()) { return true; } else { System.gc(); System.runFinalization(); try { Thread.sleep(50); } catch (InterruptedException e) { interrupted = true; } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return false; }
Source:
<code>public void setValue(PreparedStatement st, int startIndex, T value) throws SQLException { if (!type.isAssignableFrom(value.getClass())) { <START> <END> } Array arr = st.getConnection().createArrayOf(typeName, (Object[])value); st.setArray(startIndex, arr); }</code><technical_language>@timowest this blank line do? this linked line 41</technical_language>

Target:
public void setValue(PreparedStatement st, int startIndex, T value) throws SQLException { if (convertPrimitives) { int length = java.lang.reflect.Array.getLength(value); Object value2 = java.lang.reflect.Array.newInstance(Primitives.wrap(type.getComponentType()), length); copy(value, value2, length); value = (T)value2; } Array arr = st.getConnection().createArrayOf(typeName, (Object[])value); st.setArray(startIndex, arr); }
Source:
<code>public void saveCondition_shouldSaveNewCondition(){ int patientId = 2; Date date = new Date(); Condition condition = new Condition(); condition.setCondition(new CodedOrFreeText()); condition.setClinicalStatus(ConditionClinicalStatus.ACTIVE); condition.setAdditionalDetail("saving a condition"); condition.setVerificationStatus(ConditionVerificationStatus.CONFIRMED); condition.setOnsetDate(date); condition.setUuid(UUID); condition.setPatient(patientService.getPatient(patientId)); <START> expectedException = ExpectedException.none(); <END> conditionService.saveCondition(condition); Condition savedCondition = conditionService.getConditionByUuid(UUID); Assert.assertEquals(ConditionVerificationStatus.CONFIRMED, savedCondition.getVerificationStatus()); Assert.assertEquals(ConditionClinicalStatus.ACTIVE, savedCondition.getClinicalStatus()); Assert.assertEquals(UUID, savedCondition.getUuid()); }</code><technical_language>is of expectedException</technical_language>

Target:
public void saveCondition_shouldSaveNewCondition(){ Integer patientId = 2; String uuid = "08002000-4469-12q3-551f-0339000c9a76"; CodedOrFreeText codedOrFreeText = new CodedOrFreeText(); Condition condition = new Condition(); condition.setCondition(codedOrFreeText); condition.setClinicalStatus(ConditionClinicalStatus.ACTIVE); condition.setUuid(uuid); condition.setPatient(new Patient(patientId)); conditionService.saveCondition(condition); Condition savedCondition = conditionService.getConditionByUuid(uuid); Assert.assertEquals(patientId, savedCondition.getPatient().getPatientId()); Assert.assertEquals(uuid, savedCondition.getUuid()); Assert.assertEquals(codedOrFreeText, savedCondition.getCondition()); Assert.assertEquals(ConditionClinicalStatus.ACTIVE, savedCondition.getClinicalStatus()); Assert.assertNotNull(savedCondition.getConditionId()); }
Source:
<code>public void update() { if (worldObj.isRemote || mode != Mode.On) { return; } battery.tick(getWorld(), getPos()); battery.addPower(1000); <START> if (worldObj.rand.nextDouble() > 0.9) { END> sendNetworkUpdate(NET_LED_STATUS); } if (isComplete) { return; } initCurrentPos(); mine(); }</code><technical_language>No, temporary for testing. needs replaced a check if send update message (the status of of LED's changed)</technical_language>

Target:
public void update() { if (worldObj.isRemote || mode != Mode.On) { return; } battery.tick(getWorld(), getPos()); battery.addPower(1000); if(true) { sendNetworkUpdate(NET_LED_STATUS); } if(tubeY == 0) { tubeY = pos.getY(); } else { double diff = currentPos.getY() - tubeY + this.getTubeOffset(); if(Math.abs(diff) <= 0.01) { tubeY = currentPos.getY() + this.getTubeOffset(); } else if(diff > 0) { tubeY += Math.max(diff * 0.05, 0.01); } else { tubeY += Math.min(diff * 0.05, -0.01); } } if (isComplete) { return; } initCurrentPos(); mine(); }
Source:
<code>public TypedAST parseGeneratedModule(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { <START> TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "TSL Parse"); <END> if (typAST instanceof wyvern.tools.typedAST.core.declarations.ModuleDeclaration) { return (wyvern.tools.typedAST.core.declarations.ModuleDeclaration) typAST; } else { throw new RuntimeException("Unexpected parsing input is not a module declaration: \"" + input + "\""); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }</code><technical_language>Please change parameter of getNewAST else ("Module gen", for example)</technical_language>

Target:
public wyvern.tools.typedAST.core.declarations.ModuleDeclaration parseGeneratedModule(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "Module generation"); if (typAST instanceof wyvern.tools.typedAST.core.declarations.ModuleDeclaration) { return (wyvern.tools.typedAST.core.declarations.ModuleDeclaration) typAST; } else { throw new RuntimeException("Unexpected parsing input is not a module declaration: \"" + input + "\""); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }
Source:
<code>private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final StorageDomainStatic masterDomain, final String exceptionMessage, final String logMessage) { getEventQueue().submitEventSync(new Event(_storagePoolId, masterDomain.getId(), null, EventType.RECONSTRUCT, "Reconstruct caused by failure to execute spm command"), () -> { log.warn(logMessage); AuditLogable logable = new AuditLogableImpl(); <START> logable.setVdsName(vdsDao.get(currentVdsId).getName()); <END> logable.setStorageDomainName(masterDomain.getName()); new AuditLogDirector().log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); return getEventListener().masterDomainNotOperational(masterDomain.getId(), storagePoolId, false, true); }); throw new IRSNoMasterDomainException(exceptionMessage); }</code><technical_language>purpose is host name only, please VdsStaticDao is lighter</technical_language>

Target:
private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final StorageDomainStatic masterDomain, final String exceptionMessage, final String logMessage) { getEventQueue().submitEventSync(new Event(_storagePoolId, masterDomain.getId(), null, EventType.RECONSTRUCT, "Reconstruct caused by failure to execute spm command"), () -> { log.warn(logMessage); AuditLogable logable = new AuditLogableImpl(); logable.setVdsName(vdsStaticDao.get(currentVdsId).getName()); logable.setStorageDomainName(masterDomain.getName()); new AuditLogDirector().log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); return getEventListener().masterDomainNotOperational(masterDomain.getId(), storagePoolId, false, true); }); throw new IRSNoMasterDomainException(exceptionMessage); }
Source:
<code>public void addToOrderBook(Order order) { if (order.getType() == OrderType.BUY) { <START> ArrayList<Order> tempList = this.buyOrders.get(order .getStockSymbol()); if (tempList == null) { tempList = new ArrayList<Order>(); } tempList.add(order); this.buyOrders.put(order.getStockSymbol(), tempList); <END> } if (order.getType() == OrderType.SELL) { ArrayList<Order> tempList = this.sellOrders.get(order .getStockSymbol()); if (tempList == null) { tempList = new ArrayList<Order>(); } tempList.add(order); this.sellOrders.put(order.getStockSymbol(), tempList); } }</code><technical_language>Consider extracting this method called addBuyOrderToOrderBook simply addBuyOrder</technical_language>

Target:
public void addToOrderBook(Order order) { if (order.getType() == OrderType.BUY) { addToOrders(this.buyOrders, order); } if (order.getType() == OrderType.SELL) { addToOrders(this.sellOrders, order); } }
Source:
<code>private void readBytesFromFile(String fileName, byte[] bytes) { try (FileInputStream fis = openFileInput(fileName)) { int n = 0; while (n < bytes.length) { <START> n += fis.read(bytes, n, bytes.length - n); <END> } } catch (IOException e) { throw new RuntimeException("Couldn't read from " + fileName, e); } }</code><technical_language>this is infinite loop if fis.read() returns -1</technical_language>

Target:
private void readBytesFromFile(String fileName, byte[] bytes) { try (FileInputStream fis = openFileInput(fileName)) { int numBytes = 0; while (numBytes < bytes.length) { int n = fis.read(bytes, numBytes, bytes.length - numBytes); if (n <= 0) { throw new RuntimeException("Couldn't read from " + fileName); } numBytes += n; } } catch (IOException e) { throw new RuntimeException("Couldn't read from " + fileName, e); } }
Source:
<code>public void setUp() throws Exception { mockViolationSink = mock(ViolationSink.class); <START> mockViolationSink = mock(ViolationSink.class); <END> lambdaPluginProperties = new LambdaPluginProperties(); lambdaPlugin = new LambdaPlugin(mockViolationSink, lambdaPluginProperties); }</code><technical_language>do need ;-)</technical_language>

Target:
public void setUp() throws Exception { mockViolationSink = mock(ViolationSink.class); lambdaPluginProperties = new LambdaPluginProperties(); lambdaPluginProperties.setS3Buckets("zalando-lambda-repository-eu-central-1,zalando-lambda-repository-eu-west-1"); lambdaPlugin = new LambdaPlugin(mockViolationSink, lambdaPluginProperties); }
Source:
<code>private void maybeAddLegacySuppressFilter() { try { Class<? extends Annotation> legacySuppressClass = (Class<? extends Annotation>) Class.forName("android.test.suitebuilder.annotation.Suppress"); <START> filter.intersect(new AnnotationExclusionFilter(legacySuppressClass)); <END> } catch (ClassNotFoundException e) { } }</code><technical_language>@brettchabot this return a Filter object is ignored? i.e. missing filter = ... <LINK_0></technical_language>

Target:
private void maybeAddLegacySuppressFilter() { try { Class<? extends Annotation> legacySuppressClass = (Class<? extends Annotation>) Class.forName("android.test.suitebuilder.annotation.Suppress"); filter = filter.intersect(new AnnotationExclusionFilter(legacySuppressClass)); } catch (ClassNotFoundException e) { } }
Source:
<code>public GenericShuffleProducer construct(final ConstructArgs args) { Set<Integer> workerIds = getRealWorkerIds(); List<ExchangePairID> operatorIds = getRealOperatorIds(); distributeFunction.setNumDestinations(workerIds.size(), operatorIds.size()); GenericShuffleProducer producer = new GenericShuffleProducer( null, operatorIds.toArray(new ExchangePairID[] {}), <START> MyriaUtils.integerSetToIntArray(workerIds), <END> distributeFunction); if (argBufferStateType != null) { producer.setBackupBuffer(argBufferStateType); } return producer; }</code><technical_language>changed Ints.toArray()</technical_language>

Target:
public GenericShuffleProducer construct(final ConstructArgs args) { Set<Integer> workerIds = getRealWorkerIds(); List<ExchangePairID> operatorIds = getRealOperatorIds(); distributeFunction.setDestinations(workerIds.size(), operatorIds.size()); GenericShuffleProducer producer = new GenericShuffleProducer( null, operatorIds.toArray(new ExchangePairID[] {}), Ints.toArray(workerIds), distributeFunction); if (argBufferStateType != null) { producer.setBackupBuffer(argBufferStateType); } return producer; }
Source:
<code>private void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); <START> AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { <END> 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()); }</code><technical_language>try 'getEntity().getStoragePoolId()' instead</technical_language>

Target:
private void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); List<ActionParametersBase> removeUnregisteredEntityParams = getRemoveUnregisteredEntityParams(getEntity().getStoragePoolId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), removeUnregisteredEntityParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); }
Source:
<code>public boolean equals(Object aObj, Object bObj) { if (areInstances(aObj, bObj, IFeatureModel.class)) { IFeature a = ((IFeatureModel) aObj).getFeature(); IFeature b = ((IFeatureModel) bObj).getFeature(); <START> return a.getId().equals(b.getId()); <END> } else if (areInstances(aObj, bObj, IFeatureChild.class)) { IFeatureChild a = (IFeatureChild) aObj; IFeatureChild b = (IFeatureChild) bObj; return a.getId().equals(b.getId()) && equals(a.getModel(), b.getModel()); } else if (areInstances(aObj, bObj, IFeaturePlugin.class)) { IFeaturePlugin a = (IFeaturePlugin) aObj; IFeaturePlugin b = (IFeaturePlugin) bObj; return a.getId().equals(b.getId()) && equals(a.getModel(), b.getModel()); } else { return aObj.equals(bObj); } }</code><technical_language>distinguish id (and in future WS target). I simply (identity) equals IFeatureModel here</technical_language>

Target:
public boolean equals(Object aObj, Object bObj) { return Objects.equals(aObj, bObj); }
Source:
<code>public BigDecimal eval() { try { evalValidation(); } catch (Exception e) { <START> throw new ExpressionException(e.getMessage()); <END> } return eval(true); }</code><technical_language>is evil, remove original stacktrace. Please *never* do this, debugging *so much* harder</technical_language>

Target:
public BigDecimal eval() { varDefValidation(); return eval(true); }
Source:
<code>public DebugContextEvent(IDebugContextProvider source, ISelection context, int flags) { super(source); Assert.isNotNull(context, "DebugContextEvent context <START> should not <END> be null"); fContext = context; fFlags = flags; }</code><technical_language>"must"</technical_language>

Target:
public DebugContextEvent(IDebugContextProvider source, ISelection context, int flags) { super(source); Assert.isNotNull(context, "DebugContextEvent context must not be null"); fContext = context; fFlags = flags; }
Source:
<code><START> public EvictingBoundedList<ArchivedExecution> getPriorExecutionAttempts() { <END> return priorExecutions; }</code><technical_language>written before, I prefer List<AccessExecution> return type</technical_language>

Target:
public List<AccessExecution> getPriorExecutionAttempts() { List<AccessExecution> accessExecutionList = new ArrayList<>(); for (ArchivedExecution archivedExecution: priorExecutions) { if (priorExecutions != null) { accessExecutionList.add(archivedExecution); } } return Collections.unmodifiableList(accessExecutionList); }
Source:
<code><START> void updateTopologyComponentParallelism(String topologyName, String newParallelism) <END> throws TopologyRuntimeManagementException, PackingException, UpdateDryRunResponse { LOG.fine(String.format("updateTopologyHandler called for %s with %s", topologyName, newParallelism)); SchedulerStateManagerAdaptor manager = Runtime.schedulerStateManagerAdaptor(runtime); TopologyAPI.Topology topology = manager.getTopology(topologyName); Map<String, Integer> changeRequests = parseNewParallelismParam(newParallelism); PackingPlans.PackingPlan currentPlan = manager.getPackingPlan(topologyName); if (!changeDetected(currentPlan, changeRequests)) { throw new TopologyRuntimeManagementException( String.format("The component parallelism request (%s) is the same as the " + "current topology parallelism. Not taking action.", newParallelism)); } PackingPlans.PackingPlan proposedPlan = buildNewPackingPlan(currentPlan, changeRequests, topology); if (Context.dryRun(config)) { PackingPlanProtoDeserializer deserializer = new PackingPlanProtoDeserializer(); PackingPlan oldPlan = deserializer.fromProto(currentPlan); PackingPlan newPlan = deserializer.fromProto(proposedPlan); throw new UpdateDryRunResponse(topology, config, newPlan, oldPlan, changeRequests); } Scheduler.UpdateTopologyRequest updateTopologyRequest = Scheduler.UpdateTopologyRequest.newBuilder() .setCurrentPackingPlan(currentPlan) .setProposedPackingPlan(proposedPlan) .build(); LOG.fine("Sending Updating topology request: " + updateTopologyRequest); if (!schedulerClient.updateTopology(updateTopologyRequest)) { throw new TopologyRuntimeManagementException( "Failed to update topology with Scheduler, updateTopologyRequest=" + updateTopologyRequest + "The topology can be in a strange stage. " + "Please check carefully or redeploy the topology !!"); } }</code><technical_language>hmm. updatePackingPlan() handles container parallelism changes, need a new function here</technical_language>

Target:
void updateTopologyComponentParallelism(String topologyName, String newParallelism) throws TopologyRuntimeManagementException, PackingException, UpdateDryRunResponse { LOG.fine(String.format("updateTopologyHandler called for %s with %s", topologyName, newParallelism)); Map<String, Integer> changeRequests = parseNewParallelismParam(newParallelism); SchedulerStateManagerAdaptor manager = Runtime.schedulerStateManagerAdaptor(runtime); TopologyAPI.Topology topology = manager.getTopology(topologyName); PackingPlans.PackingPlan currentPlan = manager.getPackingPlan(topologyName); if (!parallelismChangeDetected(currentPlan, changeRequests)) { throw new TopologyRuntimeManagementException( String.format("The component parallelism request (%s) is the same as the " + "current topology parallelism. Not taking action.", newParallelism)); } PackingPlans.PackingPlan proposedPlan = buildNewPackingPlan(currentPlan, changeRequests, null, topology); sendUpdateRequest(topology, changeRequests, currentPlan, proposedPlan); }
Source:
<code>public void refreshGeoRepDataForVolume(final GlusterVolumeEntity volume) { <START> VDSGroup cluster = getClusterDao().get(volume.getClusterId()); <END> discoverGeoRepDataForVolume(cluster, volume); List<GlusterGeoRepSession> geoRepSessions = getGeoRepDao().getGeoRepSessions(volume.getId()); refreshGeoRepSessionStatus(cluster, geoRepSessions); }</code><technical_language>Feature support check done</technical_language>

Target:
public void refreshGeoRepDataForVolume(final GlusterVolumeEntity volume) { if (volume == null) { throw new VdcBLLException(VdcBllErrors.GlusterVolumeGeoRepSyncFailed, "No volume information"); } VDSGroup cluster = getClusterDao().get(volume.getClusterId()); discoverGeoRepDataInCluster(cluster, volume.getName()); List<GlusterGeoRepSession> geoRepSessions = getGeoRepDao().getGeoRepSessions(volume.getId()); refreshGeoRepSessionStatus(cluster, geoRepSessions); }
Source:
<code>public Response toResponse(final JerseyViolationException exception) { <START> if (LOGGER.isDebugEnabled()) { <END> LOGGER.debug("Object validation failure", exception); } final Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); final Invocable invocable = exception.getInvocable(); final ImmutableList<String> errors = FluentIterable.from(exception.getConstraintViolations()) .transform(violation -> ConstraintMessage.getMessage(violation, invocable)).toList(); final int status = ConstraintMessage.determineStatus(violations, invocable); return Response.status(status) .entity(new ValidationErrorMessage(errors)) .build(); }</code><technical_language>difference java LOG.debug("Something say", throwable); // if (LOG.isDebugEnabled()) { LOG.debug("Something say", throwable); } minimal in this case (we're talking in middle of a jersey exception handler!) I prefer more concise approach. Thank for making changes</technical_language>

Target:
public Response toResponse(final JerseyViolationException exception) { LOGGER.debug("Object validation failure", exception); final Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); final Invocable invocable = exception.getInvocable(); final ImmutableList<String> errors = FluentIterable.from(exception.getConstraintViolations()) .transform(violation -> ConstraintMessage.getMessage(violation, invocable)).toList(); final int status = ConstraintMessage.determineStatus(violations, invocable); return Response.status(status) .entity(new ValidationErrorMessage(errors)) .build(); }
Source:
<code>public PostDonationCounselling createPostDonationCounsellingForDonation(Donation donation) { LOGGER.info("Creating post donation counselling for donation: " + donation); PostDonationCounselling existingCounselling = postDonationCounsellingRepository.findPostDonationCounsellingForDonation( donation); if (existingCounselling != null) { <START> LOGGER.info("Returning existing counselling instead of creating a new PostDonationCounselling"); <END> return existingCounselling; } PostDonationCounselling postDonationCounselling = new PostDonationCounselling(); postDonationCounselling.setDonation(donation); postDonationCounselling.setFlaggedForCounselling(true); postDonationCounsellingRepository.save(postDonationCounselling); return postDonationCounselling; }</code><technical_language>is this logged? If need logged, based discussions a level include some identification of PostDonationCounselling is related to</technical_language>

Target:
public PostDonationCounselling createPostDonationCounsellingForDonation(Donation donation) { LOGGER.info("Creating post donation counselling for donation: " + donation); PostDonationCounselling existingCounselling = postDonationCounsellingRepository.findPostDonationCounsellingForDonation( donation); if (existingCounselling != null) { return existingCounselling; } PostDonationCounselling postDonationCounselling = new PostDonationCounselling(); postDonationCounselling.setDonation(donation); postDonationCounselling.setFlaggedForCounselling(Boolean.TRUE); postDonationCounselling.setIsDeleted(Boolean.FALSE); postDonationCounselling.setCreatedBy(utilController.getCurrentUser()); postDonationCounselling.setCreatedDate(dateGeneratorService.generateDate()); postDonationCounselling.setLastUpdated(dateGeneratorService.generateDate()); postDonationCounselling.setLastUpdatedBy(utilController.getCurrentUser()); postDonationCounsellingRepository.save(postDonationCounselling); return postDonationCounselling; }
Source:
<code>private static List<ComponentDto> selectByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query, int offset, int limit) { Predicate<Set<?>> emptyList = list -> list != null && list.isEmpty(); <START> if (emptyList.test(query.getComponentIds()) <END> || emptyList.test(query.getComponentKeys()) || emptyList.test(query.getComponentUuids())) { return emptyList(); } return mapper(session).selectByQuery(organizationUuid, query, new RowBounds(offset, limit)); }</code><technical_language>a query#isEmpty method, this dao method easiest read</technical_language>

Target:
private static List<ComponentDto> selectByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query, int offset, int limit) { if (query.hasEmptySetOfComponents()) { return emptyList(); } return mapper(session).selectByQuery(organizationUuid, query, new RowBounds(offset, limit)); }
Source:
<code>public void validateSourceDomainValid() { DiskImage disk = new DiskImage(); initializeCommand(disk, VmEntityType.VM); initSrcStorageDomain(); initDestStorageDomain(StorageType.NFS); disk.setStorageIds(new ArrayList<>(Collections.singletonList(Guid.newGuid()))); <START> ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_SOURCE_STORAGE_DOMAIN_IS_NOT_VALID); <END> }</code><technical_language>I split line :)</technical_language>

Target:
public void validateSourceDomainValid() { DiskImage disk = new DiskImage(); initializeCommand(disk, VmEntityType.VM); initSrcStorageDomain(); initDestStorageDomain(StorageType.NFS); disk.setStorageIds(new ArrayList<>(Collections.singletonList(Guid.newGuid()))); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_SOURCE_STORAGE_DOMAIN_DOES_CONTAINS_THE_DISK); }
Source:
<code>public long getNativeFinalizerPtr() { <START> return 0; <END> }</code><technical_language>Remember create a nativeGetFinalizerMethodPtr method free native resources. Check OsMongoCollection for inspiration do it</technical_language>

Target:
public long getNativeFinalizerPtr() { return nativeGetFinalizerMethodPtr(); }
Source:
<code>public void showBadImagePopup(Integer errorCode) { String errorMessageForResult = getErrorMessageForResult(getContext(), errorCode); if (!StringUtils.isBlank(errorMessageForResult)) { DialogUtil.showAlertDialog(getActivity(), getString(R.string.warning), errorMessageForResult, <START> () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); <END> onNextButtonClicked(); }, () -> { deleteThisPicture(); }); } }</code><technical_language>uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); a separate line { is a statement lambda method call For example deleteThisPicture(); braces colon removed a statement lambda. a method reference ::deleteThisPicture input parameters () parameter for method deleteThisPicture()</technical_language>

Target:
public void showBadImagePopup(Integer errorCode) { String errorMessageForResult = getErrorMessageForResult(getContext(), errorCode); if (!StringUtils.isBlank(errorMessageForResult)) { DialogUtil.showAlertDialog(getActivity(), getString(R.string.warning), errorMessageForResult, () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); }, () -> deleteThisPicture() ); } }
Source:
<code>private <T> T update( T t ) throws Throwable { if( currentStage == t ) { <START> readScenarioState( currentStage ); <END> updateScenarioState( currentStage ); return t; } if( currentStage == null ) { ensureBeforeStepsAreExecuted(); } else { executeAfterStageMethods( currentStage ); readScenarioState( currentStage ); } updateScenarioState( t ); StageState stageState = getStageState( t ); if( !stageState.beforeStageCalled ) { stageState.beforeStageCalled = true; executeBeforeStageSteps( t ); } currentStage = t; return t; }</code><technical_language>This a big performance overhead. This is if statement good for: avoid overhead of reading updating state</technical_language>

Target:
private <T> T update( T t ) throws Throwable { if( currentStage == t ) { return t; } if( currentStage == null ) { ensureBeforeStepsAreExecuted(); } else { executeAfterStageMethods( currentStage ); readScenarioState( currentStage ); } updateScenarioState( t ); StageState stageState = getStageState( t ); if( !stageState.beforeStageCalled ) { stageState.beforeStageCalled = true; executeBeforeStageSteps( t ); } currentStage = t; return t; }
Source:
<code>public boolean isNeedToInitializeCache() { int quotaCount = getQuotaDAO().getQuotaCount(); int cacheCount = 0; <START> <END> for(Map<Guid, Quota> quotaMap : storagePoolQuotaMap.values()) { cacheCount += quotaMap.size(); } return cacheCount < quotaCount * MINIMUM_CACHE_FACTOR; }</code><technical_language>storagePoolQuotaMap. - variable is shared protected for multiple thread access</technical_language>

Target:
public boolean isNeedToInitializeCache() { int quotaCount = getQuotaDAO().getQuotaCount(); int cacheCount = 0; lock.readLock().lock(); try { for(Map<Guid, Quota> quotaMap : storagePoolQuotaMap.values()) { cacheCount += quotaMap.size(); } } finally { lock.readLock().unlock(); } return cacheCount < quotaCount * MINIMUM_CACHE_FACTOR; }
Source:
<code>public void getDefaultPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); <START> pm.getPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { <END> @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); }</code><technical_language>I if this test's name is correct, this line start pm.getDefaultPermissions. Otherwise, test's name getPermissions_returnLoadedResults</technical_language>

Target:
public void getDefaultPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getDefaultPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); }
Source:
<code>public void run() { try { long clearIntervalNanos = randomizeClearInterval(); long iteration = 0; long lastClearTime = System.nanoTime(); while (!testContext.isStopped()) { long batchSleepNanos = randomizeBatchSleep(); int batchSize = randomizeBatchSize(); for (int i = 0; i < batchSize; i++) { <START> int operation = randomizeOperation(); <END> switch (operation) { case OPERATE_GET: operateGet(); break; case OPERATE_PUT: operatePut(); break; case OPERATE_UPDATE: operateUpdate(); break; case OPERATE_REMOVE: operateRemove(); break; } operations.incrementAndGet(); if (testContext.isStopped()) { return; } if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } iteration++; } if (System.nanoTime() - lastClearTime >= clearIntervalNanos) { log("Executing clear operation"); replicatedMap.clear(); } TimeUnit.NANOSECONDS.sleep(batchSleepNanos); if (System.nanoTime() - lastClearTime >= clearIntervalNanos) { log("Executing clear operation"); replicatedMap.clear(); } } } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>a new method execute(Random?)Operation()</technical_language>

Target:
public void run() { long clearIntervalNanos = randomizeClearInterval(); long iteration = 0; long lastClearTime = System.nanoTime(); while (!testContext.isStopped()) { long batchSleepNanos = randomizeBatchSleep(); int batchSize = randomizeBatchSize(); for (int i = 0; i < batchSize; i++) { executeRandomOperation(); if (testContext.isStopped()) { return; } if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } iteration++; if (iteration % performanceUpdateFrequency == 0) { operations.addAndGet(performanceUpdateFrequency); } } clearReplicatedMapIfNeeded(clearIntervalNanos, lastClearTime); try { TimeUnit.NANOSECONDS.sleep(batchSleepNanos); } catch (InterruptedException e) { throw new RuntimeException(e); } clearReplicatedMapIfNeeded(clearIntervalNanos, lastClearTime); } }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProgressStepId other = (ProgressStepId) obj; if (stepNumber != other.stepNumber) return false; return true; <START> } <END></code><technical_language>equals hashcode comparing stepNumber, is of key. compare Progress objects IDs</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProgressStepId other = (ProgressStepId) obj; if (progress == null) { if (other.progress != null) return false; } else if (!progress.equals(other.progress)) return false; if (stepNumber != other.stepNumber) return false; return true; }
Source:
<code>public List<Guid> getIdsOfHostsWithStatus(VDSStatus status) { <START> return getCallsHandler().executeReadList("getIdsOfHostsWithStatus", <END> createGuidMapper(), getCustomMapSqlParameterSource() .addValue("status", status.getValue())); }</code><technical_language>SP names case-sensitive , worth call this GetIdsOfHostsWithStatus in SP file</technical_language>

Target:
public List<Guid> getIdsOfHostsWithStatus(VDSStatus status) { return getCallsHandler().executeReadList("GetIdsOfHostsWithStatus", createGuidMapper(), getCustomMapSqlParameterSource() .addValue("status", status.getValue())); }
Source:
<code>public void testColorSeekBar() { int whenBrickPosition = 0; onBrickAtPosition(whenBrickPosition).checkShowsText(R.string.brick_when_started); int penColorBrickPosition = 1; onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber(initValue) .perform(click()); <START> <END> onView(withId(colorRgbSeekbarId)) .perform(CustomSwipeAction.swipeLeftSlow()); onView(withId(colorRgbSeekbarId)) .perform(CustomSwipeAction.swipeRightSlow()); onColorSeekbar().closeAndSaveChanges(); onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber((int) MAX_COLOR_SEEKBAR_VALUE); }</code><technical_language>swipe directions? if initial is max, swipe action seekbar is broken, this test wount fail. set seekbar 0 in beginning of test, swipe time (!) right verify max</technical_language>

Target:
public void testColorSeekBar() { int whenBrickPosition = 0; onBrickAtPosition(whenBrickPosition).checkShowsText(R.string.brick_when_started); int penColorBrickPosition = 1; onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber(initValue) .perform(click()); onView(withId(colorRgbSeekbarId)) .perform(CustomSwipeAction.swipeRightSlow()); onColorSeekbar().closeAndSaveChanges(); onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber((int) MAX_COLOR_SEEKBAR_VALUE); }
Source:
<code>public byte[] apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { ObjectLoader loader = repo.open(tw.getObjectId(0)); <START> ByteArrayOutputStream out = new ByteArrayOutputStream(); <END> loader.copyTo(out); return Base64.encodeBase64(out.toByteArray()); } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }</code><technical_language>Guava's BaseEncoding nicer :-) Done</technical_language>

Target:
public String apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { ObjectLoader loader = repo.open(tw.getObjectId(0)); return BaseEncoding.base64().encode(loader.getBytes()); } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }