auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testTombstonesWithLowerVersionThanTheRecordedVersionGetsGCed() throws Exception { VM vm0 = VM.getVM(0); VM vm1 = VM.getVM(1); Properties props = DistributedRule.getDistributedSystemProperties(); <START> props.put("conserve-sockets", "false"); <END> vm0.invoke(() -> { createCacheAndRegion(RegionShortcut.REPLICATE_PERSISTENT, props); region.put("K1", "V1"); region.put("K2", "V2"); }); vm1.invoke(() -> { createCacheAndRegion(RegionShortcut.REPLICATE, props); DistributionMessageObserver.setInstance(new RegionObserver()); }); AsyncInvocation<Object> vm0Async1 = vm0.invokeAsync(() -> { region.destroy("K1"); }); AsyncInvocation<Object> vm0Async2 = vm0.invokeAsync(() -> { region.destroy("K2"); }); AsyncInvocation<Object> vm0Async3 = vm0.invokeAsync(() -> { waitForTombstoneCount(2); performGC(2); }); vm1.invoke(() -> await() .until(() -> ((InternalCache) cache).getCachePerfStats().getTombstoneGCCount() == 1)); vm0Async1.await(); vm0Async2.await(); vm0Async3.await(); vm1.invoke(() -> { performGC(((LocalRegion) region).getTombstoneCount()); assertEquals(0, ((LocalRegion) region).getTombstoneCount()); }); }</code><technical_language>props.setProperty is more correct Map interface method put</technical_language>

Target:
public void testTombstonesWithLowerVersionThanTheRecordedVersionGetsGCed() throws Exception { VM vm0 = VM.getVM(0); VM vm1 = VM.getVM(1); Properties props = DistributedRule.getDistributedSystemProperties(); props.setProperty("conserve-sockets", "false"); vm0.invoke(() -> { createCacheAndRegion(RegionShortcut.REPLICATE_PERSISTENT, props); region.put("K1", "V1"); region.put("K2", "V2"); }); vm1.invoke(() -> { createCacheAndRegion(RegionShortcut.REPLICATE, props); DistributionMessageObserver.setInstance(new RegionObserver()); }); AsyncInvocation<Object> vm0Async1 = vm0.invokeAsync(() -> { region.destroy("K1"); }); AsyncInvocation<Object> vm0Async2 = vm0.invokeAsync(() -> { region.destroy("K2"); }); AsyncInvocation<Object> vm0Async3 = vm0.invokeAsync(() -> { waitForTombstoneCount(2); performGC(2); }); vm1.invoke(() -> await() .until(() -> ((InternalCache) cache).getCachePerfStats().getTombstoneGCCount() == 1)); vm0Async1.await(); vm0Async2.await(); vm0Async3.await(); vm1.invoke(() -> { performGC(((LocalRegion) region).getTombstoneCount()); assertEquals(0, ((LocalRegion) region).getTombstoneCount()); }); }
Source:
<code>public Modifier(ShapeRenderer shapeRenderer) { this.shapeRenderer = shapeRenderer; handles = new Handle[9]; for (int i = 0; i < 9; i++) { if (i == ORIGIN_HANDLE_INDEX) { handles[i] = new OriginHandle(shapeRenderer, HANDLE_SIZE / 2.0f, Color.CYAN); } else { handles[i] = new Handle(shapeRenderer, HANDLE_SIZE, Color.GREEN); } addActor(handles[i]); } handles[0].setAlignedX(handles[2]); handles[0].setAlignedY(handles[6]); handles[2].setAlignedX(handles[0]); handles[6].setAlignedY(handles[0]); <START> handles[8].setAlignedX(handles[2]); <END> handles[8].setAlignedY(handles[6]); handles[8].setRotationOffset(90); handles[1].setAlignedX(handles[0], handles[2]); handles[3].setAlignedY(handles[0], handles[6]); handles[7].setAlignedX(handles[6]); handles[5].setAlignedY(handles[2]); rotationHandle = new RotationHandle(shapeRenderer, HANDLE_SIZE / 2.0f, Color.RED); addActor(rotationHandle); }</code><technical_language>This wrong. handles[8].setAlignedY(handles[2]);</technical_language>

Target:
public Modifier(ShapeRenderer shapeRenderer) { this.shapeRenderer = shapeRenderer; handles = new Handle[9]; for (int i = 0; i < 9; i++) { if (i == ORIGIN_HANDLE_INDEX) { handles[i] = new OriginHandle(shapeRenderer, HANDLE_SIZE / 2.0f, Color.CYAN); } else { handles[i] = new Handle(shapeRenderer, HANDLE_SIZE, Color.GREEN); } addActor(handles[i]); } handles[0].setAlignedX(handles[2]); handles[0].setAlignedY(handles[6]); handles[2].setAlignedX(handles[0]); handles[6].setAlignedY(handles[0]); handles[8].setAlignedX(handles[6]); handles[8].setAlignedY(handles[2]); handles[1].setAlignedX(handles[0], handles[2]); handles[3].setAlignedY(handles[0], handles[6]); handles[7].setAlignedX(handles[6]); handles[5].setAlignedY(handles[2]); rotationHandle = new RotationHandle(shapeRenderer, HANDLE_SIZE / 2.0f, Color.RED); addActor(rotationHandle); }
Source:
<code>private boolean validateSourceStorageDomainsAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { boolean storageDomainAvailable = false; Iterator<Guid> iterator = image.getStorageIds().iterator(); while (iterator.hasNext()) { Guid storageDomainId = iterator.next(); StorageDomain sd = storageDomainDao.getForStoragePool(storageDomainId, getStoragePool().getId()); ValidationResult result = new StorageDomainValidator(sd).isDomainExistAndActive(); <START> if (result.isValid()) { storageDomainAvailable = true; } else { log.warn("Storage domain '{}' does not exist.", storageDomainId); iterator.remove(); } <END> } if (!storageDomainAvailable) { if (getParameters().isAllowPartialImport()) { log.warn("No active storage domain that contains the image {}/{} exists. " + "Ignoring since the force flag in on.", image.getId(), image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } else { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANNOT_FIND_DISK_IMAGE_IN_ACTIVE_DOMAINS, String.format("$diskImageId %1$s", image.getId()), String.format("$imageId %1$s", image.getImageId())); } } } return true; }</code><technical_language>For considuration: This nicer: if (!result.isValid()) { log.warn("Storage domain '{}' exist.", storageDomainId); iterator.remove(); } else if (!storageDomainAvailable) { storageDomainAvailable = true; }</technical_language>

Target:
private boolean validateSourceStorageDomainsAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { boolean storageDomainAvailable = false; Iterator<Guid> iterator = image.getStorageIds().iterator(); while (iterator.hasNext()) { Guid storageDomainId = iterator.next(); StorageDomain sd = storageDomainDao.getForStoragePool(storageDomainId, getStoragePool().getId()); ValidationResult result = new StorageDomainValidator(sd).isDomainExistAndActive(); if (!result.isValid()) { log.warn("Storage domain '{}' does not exist.", storageDomainId); iterator.remove(); } else if (!storageDomainAvailable) { storageDomainAvailable = true; } } if (!storageDomainAvailable) { if (!getParameters().isAllowPartialImport()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANNOT_FIND_DISK_IMAGE_IN_ACTIVE_DOMAINS, String.format("$diskImageId %1$s", image.getId()), String.format("$imageId %1$s", image.getImageId())); } log.warn("No active storage domain that contains the image {}/{} exists. " + "Ignoring since the force flag in on.", image.getId(), image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } } return true; }
Source:
<code>public Order findMatchingSellOrder(Order o) throws StockMarketExpection { if(o instanceof BuyOrder) { ArrayList<Order> pendingSellOrders = sellOrders.get(o.getStockSymbol()); Collections.sort(pendingSellOrders); <START> if(pendingSellOrders.get(0).getPrice() <= <END> o.getPrice()) { return pendingSellOrders.get(0); } return null; } else { throw new StockMarketExpection("Parameter must be a Buy Order"); } }</code><technical_language>long message chain</technical_language>

Target:
public Order findMatchingSellOrder(Order o) throws StockMarketExpection { if(o instanceof BuyOrder) { ArrayList<Order> pendingSellOrders = sellOrders.get(o.getStockSymbol()); Collections.sort(pendingSellOrders); Order pendingSale = pendingSellOrders.get(0); if(pendingSale.getPrice() <= o.getPrice()) { return pendingSellOrders.get(0); } return null; } else { throw new StockMarketExpection("Parameter must be a Buy Order"); } }
Source:
<code>public void testExecute() throws Exception { AccountAttributes student1 = typicalBundle.accounts.get("student1InCourse1"); loginAsStudent(student1.googleId); ______TS("Typical case: upload profile picture operation successful"); String filePath = "src/test/resources/images/profile_pic.png"; String contentType = URLConnection.guessContentTypeFromName(new File(filePath).getName()); PostStudentProfilePictureAction action = getActionWithParts("studentprofilephoto", contentType, filePath); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); StudentProfilePictureResults output = (StudentProfilePictureResults) result.getOutput(); <START> assertEquals(output.getMessage(), Const.StatusMessages.STUDENT_PROFILE_PICTURE_SAVED); <END> assertNotNull(output.getPictureKey()); }</code><technical_language>Insufficient check. confirm picture is added</technical_language>

Target:
public void testExecute() throws Exception { AccountAttributes student1 = typicalBundle.accounts.get("student1InCourse1"); loginAsStudent(student1.googleId); ______TS("Typical case: upload profile picture operation successful"); String filePath = "src/test/resources/images/profile_pic.png"; PostStudentProfilePictureAction action = getActionWithParts("studentprofilephoto", filePath); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); StudentProfilePictureResults output = (StudentProfilePictureResults) result.getOutput(); String resultPictureKey = output.getPictureKey(); String newPictureKey = logic.getStudentProfile(student1.googleId).pictureKey; assertNotNull(resultPictureKey); assertNotEquals(resultPictureKey, ""); assertEquals(resultPictureKey, newPictureKey); ______TS("Typical case: profile picture is null"); PostStudentProfilePictureAction nullProfilePicAction = getAction(); assertThrows(InvalidHttpRequestBodyException.class, () -> nullProfilePicAction.execute()); ______TS("Typical case: profile picture is too large"); String largeProfilePicFilePath = "src/test/resources/images/profile_pic_too_large.jpg"; PostStudentProfilePictureAction largeProfilePicAction = getActionWithParts("studentprofilephoto", largeProfilePicFilePath); assertThrows(InvalidHttpRequestBodyException.class, () -> largeProfilePicAction.execute()); ______TS("Typical case: not a profile picture"); String invalidProfilePicFilePath = "src/test/resources/images/not_a_picture.txt"; PostStudentProfilePictureAction invalidProfilePicAction = getActionWithParts("studentprofilephoto", invalidProfilePicFilePath); assertThrows(InvalidHttpRequestBodyException.class, () -> invalidProfilePicAction.execute()); }
Source:
<code>public boolean lookupAttributeBoolean( long deviceId, String attributeName, boolean defaultValue, boolean lookupConfig) { Object result = lookupAttribute(deviceId, attributeName, lookupConfig); <START> return result != null ? Boolean.parseBoolean(result.toString()) : defaultValue; <END> }</code><technical_language>I right way. check object type, parse if a string. Applies other methods</technical_language>

Target:
public boolean lookupAttributeBoolean( long deviceId, String attributeName, boolean defaultValue, boolean lookupConfig) { Object result = lookupAttribute(deviceId, attributeName, lookupConfig); if (result != null) { return result instanceof String ? Boolean.parseBoolean((String) result) : (Boolean) result; } return defaultValue; }
Source:
<code>protected void jobReachedGloballyTerminalState(ArchivedExecutionGraph archivedExecutionGraph) { super.jobReachedGloballyTerminalState(archivedExecutionGraph); <START> shutDownFuture.complete(ApplicationStatus.fromJobStatus(archivedExecutionGraph.getState())); <END> }</code><technical_language>I do this unconditionally want serve job result in case of a successful execution of job attached mode</technical_language>

Target:
protected void jobReachedGloballyTerminalState(ArchivedExecutionGraph archivedExecutionGraph) { super.jobReachedGloballyTerminalState(archivedExecutionGraph); if (jobCancelled || executionMode == ClusterEntrypoint.ExecutionMode.DETACHED) { shutDownFuture.complete(ApplicationStatus.fromJobStatus(archivedExecutionGraph.getState())); } }
Source:
<code>public void copy(Instance sourceMachine, String sourcePath, String targetPath, boolean overwrite) throws MachineException { if (!(sourceMachine instanceof DockerInstance)) { <START> throw new MachineException("Resources can not be copied from the machine " + sourceMachine.getId()); <END> } try { docker.copyResourceTo(container, targetPath, docker.getResourceFrom(((DockerInstance)sourceMachine).container, sourcePath), overwrite); } catch (IOException e) { throw new MachineException(e.getLocalizedMessage()); } }</code><technical_language>is obvious files copied in case</technical_language>

Target:
public void copy(Instance sourceMachine, String sourcePath, String targetPath, boolean overwrite) throws MachineException { if (!(sourceMachine instanceof DockerInstance)) { throw new MachineException("Unsupported copying between not docker machines"); } try { docker.putResource(container, targetPath, docker.getResource(((DockerInstance)sourceMachine).container, sourcePath), overwrite); } catch (IOException e) { throw new MachineException(e.getLocalizedMessage()); } }
Source:
<code>public RSAPrivateKeyMapper(String credentialName, int privateKey) { <START> Assert.assertNotNull(credentialName); <END> Assert.checkMinimumParameter("privateKey", 1, privateKey); this.privateKey = privateKey; this.credentialName = credentialName; }</code><technical_language>checkNotNullParam instead</technical_language>

Target:
public RSAPrivateKeyMapper(String credentialName, int privateKey) { Assert.checkNotNullParam("credentialName", credentialName); Assert.checkMinimumParameter("privateKey", 1, privateKey); this.privateKey = privateKey; this.credentialName = credentialName; }
Source:
<code>public void testActionIndifferentConfig() throws Exception { MuleTransactionConfig config = new MuleTransactionConfig(TransactionConfig.ACTION_INDIFFERENT); ExecutionTemplate executionTemplate = createExecutionTemplate(config); Object result = executionTemplate.execute(getEmptyTransactionCallback()); assertThat(result, is(RETURN_VALUE)); <START> assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.nullValue()); <END> }</code><technical_language>static import</technical_language>

Target:
public void testActionIndifferentConfig() throws Exception { MuleTransactionConfig config = new MuleTransactionConfig(ACTION_INDIFFERENT); ExecutionTemplate executionTemplate = createExecutionTemplate(config); Object result = executionTemplate.execute(getEmptyTransactionCallback()); assertThat(result, is(RETURN_VALUE)); assertThat(getInstance().getTransaction(), nullValue()); }
Source:
<code>public Map<String, String> tags() { <START> return tags; <END> }</code><technical_language>more safe return Collections.unmodifiableMap(tags);</technical_language>

Target:
public Map<String, String> tags() { return Collections.unmodifiableMap(tags); }
Source:
<code>public void cannotGetCharge_WhenInvalidChargeId() { String chargeId = "23235124"; connectorRestApiClient .withAccountId(accountId) .withChargeId(chargeId) .getCharge() .statusCode(NOT_FOUND.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains(format("Charge with id [%s] not found.", chargeId))) <START> .body("error_identifier", Matchers.is(ErrorIdentifier.GENERIC.toString())); <END> }</code><technical_language>Please static import is</technical_language>

Target:
public void cannotGetCharge_WhenInvalidChargeId() { String chargeId = "23235124"; connectorRestApiClient .withAccountId(accountId) .withChargeId(chargeId) .getCharge() .statusCode(NOT_FOUND.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains(format("Charge with id [%s] not found.", chargeId))) .body("error_identifier", is(ErrorIdentifier.GENERIC.toString())); }
Source:
<code>public ParquetInputFormat( Path[] paths, String[] fullFieldNames, DataType[] fullFieldTypes, int[] selectedFields, String partDefaultName, long limit, Configuration conf, boolean utcTimestamp) { this.limit = limit; <START> super.setFilePaths(paths); <END> this.partDefaultName = partDefaultName; this.fullFieldNames = fullFieldNames; this.fullFieldTypes = fullFieldTypes; this.selectedFields = selectedFields; this.conf = new SerializableConfiguration(conf); this.utcTimestamp = utcTimestamp; }</code><technical_language>Call parent's function in constructor</technical_language>

Target:
public ParquetInputFormat( Path[] paths, String[] fullFieldNames, DataType[] fullFieldTypes, int[] selectedFields, String partDefaultName, long limit, Configuration conf, boolean utcTimestamp) { super.setFilePaths(paths); this.limit = limit; this.partDefaultName = partDefaultName; this.fullFieldNames = fullFieldNames; this.fullFieldTypes = fullFieldTypes; this.selectedFields = selectedFields; this.conf = new SerializableConfiguration(conf); this.utcTimestamp = utcTimestamp; }
Source:
<code>public void dispose() { for (Object element : participants.values()) { <START> ISynchronizationScopeParticipant p = (ISynchronizationScopeParticipant) element; <END> p.dispose(); } super.dispose(); }</code><technical_language>'participants' is a typed collection loop var; rename participant</technical_language>

Target:
public void dispose() { for (ISynchronizationScopeParticipant participant : participants.values()) { participant.dispose(); } super.dispose(); }
Source:
<code>protected Task<Graph> createTask() { return new Task<Graph>() { @Override protected Graph call() throws IOException, ParseException { GraphBuilder gb; gb = new Neo4jBatchBuilder(database.get()); EdgeParser ep = new EdgeParserImpl(getEdgeFile()); NodeParser np = new NodeParserImpl(getNodeFile()); gb.constructGraph(np, ep); ep.close(); np.close(); <START> Graph graph = new Neo4jGraph(database.get()); <END> return graph; } }; }</code><technical_language>need create this variable</technical_language>

Target:
protected Task<Graph> createTask() { return new Task<Graph>() { @Override protected Graph call() throws IOException, ParseException { GraphBuilder gb; gb = new Neo4jBatchBuilder(database.get()); EdgeParser ep = new EdgeParserImpl(getEdgeFile()); NodeParser np = new NodeParserImpl(getNodeFile()); gb.constructGraph(np, ep); ep.close(); np.close(); return new Neo4jGraph(database.get()); } }; }
Source:
<code>public List<ConcreteResource> buildContent( RemoteRepository repository ) { if ( repository.getPrefetchPriority() <= 0 ) { logger.error( "The repository prefetch disabled, can not use html content listing", repository.getName() ); return Collections.emptyList(); } <START> if ( PREFETCH_LISTING_TYPE_KOJI.equals( repository.getPrefetchListingType() ) ) <END> { logger.warn( "Will start to use normal html content listing for the koji proxy remote {}", repository.getName() ); } final String rootPath = "/"; final KeyedLocation loc = LocationUtils.toLocation( repository ); final StoreResource res = new StoreResource( loc, rootPath ); try { final ListingResult lr = transferManager.list( res ); if ( lr != null && lr.getListing() != null ) { String[] files = lr.getListing(); List<ConcreteResource> resources = new ArrayList<>( files.length ); for ( final String file : lr.getListing() ) { resources.add( new StoreResource( loc, rootPath, file ) ); } return resources; } } catch ( TransferException e ) { logger.error( String.format( "Can not get transfer for repository %s", repository ), e ); } return Collections.emptyList(); }</code><technical_language>this happen? prevent it</technical_language>

Target:
public List<ConcreteResource> buildContent( RemoteRepository repository ) { if ( repository.getPrefetchPriority() <= 0 ) { logger.warn( "The repository prefetch disabled, can not use html content listing", repository.getName() ); return Collections.emptyList(); } final String rootPath = "/"; final KeyedLocation loc = LocationUtils.toLocation( repository ); final StoreResource res = new StoreResource( loc, rootPath ); try { final ListingResult lr = transferManager.list( res ); if ( lr != null && lr.getListing() != null ) { String[] files = lr.getListing(); List<ConcreteResource> resources = new ArrayList<>( files.length ); for ( final String file : lr.getListing() ) { resources.add( new StoreResource( loc, rootPath, file ) ); } return resources; } } catch ( TransferException e ) { logger.error( String.format( "Can not get transfer for repository %s", repository ), e ); } return Collections.emptyList(); }
Source:
<code>public void testParallel() { ParallelGateway gateway = new ParallelGateway(); gateway.getGeneral().getName().setValue(NAME); gateway.getGeneral().getDocumentation().setValue(DOCUMENTATION); <START> Node<View<BaseGateway>, ?> node = mockNode(UUID, gateway); <END> when(propertyWriterFactory.of(any(org.eclipse.bpmn2.ParallelGateway.class))).thenReturn(gatewayPropertyWriter); assertEquals(gatewayPropertyWriter, converter.toFlowElement(node)); verifyCommonValues(gatewayPropertyWriter, node); verify(gatewayPropertyWriter).setGatewayDirection(node); }</code><technical_language>need mock</technical_language>

Target:
public void testParallel() { ParallelGateway gateway = new ParallelGateway(); gateway.getGeneral().getName().setValue(NAME); gateway.getGeneral().getDocumentation().setValue(DOCUMENTATION); Node<View<BaseGateway>, ?> node = newNode(UUID, gateway); when(propertyWriterFactory.of(any(org.eclipse.bpmn2.ParallelGateway.class))).thenReturn(gatewayPropertyWriter); assertEquals(gatewayPropertyWriter, converter.toFlowElement(node)); verifyCommonValues(gatewayPropertyWriter, node); verify(gatewayPropertyWriter).setGatewayDirection(node); }
Source:
<code>public VmSlaPolicyCommand(T parameters) { super(parameters); setVmId((Guid) (getParameters().getSlaParameter(VmSlaPolicyParameters.Params.VM_ID))); <START> setVdsId((Guid) getParameters().getSlaParameter(VmSlaPolicyParameters.Params.VDS_ID)); <END> if (getVds() != null) { setVdsGroupId(getVds().getVdsGroupId()); } }</code><technical_language>removed (and getRunOnVds in execute method instead)</technical_language>

Target:
public VmSlaPolicyCommand(T parameters) { super(parameters); if (getParameters().getVm() != null) { setVm(getParameters().getVm()); setVdsGroupId(getParameters().getVm().getVdsGroupId()); } }
Source:
<code>@Override protected void executeQueryCommand() { try { executeQueryCommandChecked(); } catch (IOException ex) { final String errorMessage = "Failed to create signed websocket proxy ticket."; log.error(errorMessage, ex); log.debug("Exception", ex); getQueryReturnValue().setSucceeded(false); getQueryReturnValue().setExceptionString(errorMessage); <START> } catch (RuntimeException ex) { <END> log.error(ex.getMessage()); getQueryReturnValue().setSucceeded(false); getQueryReturnValue().setExceptionString(ex.getMessage()); } }</code><technical_language>this handled base class (with log is needed), no</technical_language>

Target:
@Override protected void executeQueryCommand() { try { executeQueryCommandChecked(); } catch (IOException ex) { throw new RuntimeException("Failed to create signed websocket proxy ticket.", ex); } }
Source:
<code>protected String getPossibleValuesString( final String propertyName, final List<Method> methods, final MeasurementVariable variable) { final StringBuilder possibleValuesString = new StringBuilder(); if (variable.getPossibleValues() != null && !variable.getPossibleValues().isEmpty() && !variable.getProperty().equals(propertyName)) { <START> for (final ValueReference value : variable.getPossibleValues()) { <END> if (possibleValuesString.length() > 0) { possibleValuesString.append("/"); } possibleValuesString.append(value.getName()); } } else if (variable.getProperty().equals(propertyName)) { for (final Method method : methods) { if (possibleValuesString.length() > 0) { possibleValuesString.append("/"); } possibleValuesString.append(method.getMcode()); } } return possibleValuesString.toString(); }</code><technical_language>StringUtils.join</technical_language>

Target:
protected String getPossibleValuesString( final String propertyName, final List<Method> methods, final MeasurementVariable variable) { final List<String> possibleValues = new ArrayList<>(); if (!variable.getProperty().equals(propertyName) && !CollectionUtils.isEmpty(variable.getPossibleValues())) { for (final ValueReference value : variable.getPossibleValues()) { possibleValues.add(value.getName()); } } else if (variable.getProperty().equals(propertyName)) { for (final Method method : methods) { possibleValues.add(method.getMcode()); } } return StringUtils.join(possibleValues, "/"); }
Source:
<code>public void loadExtension() { if (isInternal()) { _classLoader = ClassLoaderUtils.getParentClassLoader(); return; } synchronized (ExtensionPackage.class) { _latestClassLoader = new ExtensionClassLoader(ClassLoaderUtils.createClassLoader(getJarFiles(), null), <START> ClassLoaderUtils.getParentClassLoader(), "Extension: " + getName()); <END> _classLoader = _latestClassLoader; } }</code><technical_language>this design I imagine delete "_latestClassLoader" field this class, we</technical_language>

Target:
public void loadExtension() { if (isInternal()) { _classLoader = ClassLoaderUtils.getParentClassLoader(); return; } synchronized (ExtensionPackage.class) { final ClassLoader extensionLoader = new ExtensionClassLoader(ClassLoaderUtils.createClassLoader(getJarFiles(), null), ClassLoaderUtils.getParentClassLoader(), "Extension: " + getName()); _allExtensionClassLoaders.add(extensionLoader); _classLoader = extensionLoader; } }
Source:
<code>public void saveString(String string) throws Exception { System.out.println(this.getClass().getSimpleName() + " POST"); System.out.println(this.getClass().getSimpleName() + " begin transaction"); transactionManager.begin(); System.out.println(this.getClass().getSimpleName() + " save string"); <START> stringDao.save(string); <END> System.out.println(this.getClass().getSimpleName() + " commit transaction"); transactionManager.commit(); System.out.println(this.getClass().getSimpleName() + " transaction committed successfully"); }</code><technical_language>aborting transaction in a catch (Exception) code block if save fails</technical_language>

Target:
public void saveString(String string) throws Exception { System.out.println(this.getClass().getSimpleName() + " POST"); System.out.println(this.getClass().getSimpleName() + " begin transaction"); transactionManager.begin(); System.out.println(this.getClass().getSimpleName() + " save string"); try { stringDao.save(string); System.out.println(this.getClass().getSimpleName() + " commit transaction"); transactionManager.commit(); System.out.println(this.getClass().getSimpleName() + " transaction committed successfully"); } catch (SQLException e) { System.out.println(this.getClass().getSimpleName() + " rollback transaction"); transactionManager.rollback(); System.out.println(this.getClass().getSimpleName() + " transaction rolled back"); throw e; } }
Source:
<code>private boolean matches(String privateCreator, int tag, VR vr, boolean ignorePNCase, boolean matchNoValue, String[] keyVals) { String[] vals = getStrings(privateCreator, tag, null); if (vals == null || vals.length == 0) return matchNoValue; boolean ignoreCase = ignorePNCase && vr == VR.PN; for (String keyVal : keyVals) { DateRange dateRange = null; if (vr == VR.PN) <START> keyVal = new PersonName(keyVals[0]).toString(); <END> switch (vr) { case PN: keyVal = new PersonName(keyVals[0]).toString(); break; case DA: case DT: case TM: dateRange = toDateRange(keyVal, vr); } if (StringUtils.containsWildCard(keyVal)) { Pattern pattern = StringUtils.compilePattern(keyVal, ignoreCase); for (String val : vals) { if (val == null) if (matchNoValue) return true; else continue; if (vr == VR.PN) val = new PersonName(val).toString(); if (pattern.matcher(val).matches()) return true; } } else { for (String val : vals) { if (val == null) if (matchNoValue) return true; else continue; if (dateRange != null) if (dateRange.contains( vr.toDate(val, getTimeZone(), 0, false, null, new DatePrecision()))) return true; else continue; if (vr == VR.PN) val = new PersonName(val).toString(); if (ignoreCase ? keyVal.equalsIgnoreCase(val) : keyVal.equals(val)) return true; } } } return false; }</code><technical_language>I this if is handled in switch below, if removed</technical_language>

Target:
private boolean matches(String privateCreator, int tag, VR vr, boolean ignorePNCase, boolean matchNoValue, String[] keyVals) { String[] vals = getStrings(privateCreator, tag, null); if (vals == null || vals.length == 0) return matchNoValue; boolean ignoreCase = ignorePNCase && vr == VR.PN; for (String keyVal : keyVals) { DateRange dateRange = null; switch (vr) { case PN: keyVal = new PersonName(keyVals[0]).toString(); break; case DA: case DT: case TM: dateRange = toDateRange(keyVal, vr); break; } if (StringUtils.containsWildCard(keyVal)) { Pattern pattern = StringUtils.compilePattern(keyVal, ignoreCase); for (String val : vals) { if (val == null) if (matchNoValue) return true; else continue; if (vr == VR.PN) val = new PersonName(val).toString(); if (pattern.matcher(val).matches()) return true; } } else { for (String val : vals) { if (val == null) if (matchNoValue) return true; else continue; if (dateRange != null) if (dateRange.contains( vr.toDate(val, getTimeZone(), 0, false, null, new DatePrecision()))) return true; else continue; if (vr == VR.PN) val = new PersonName(val).toString(); if (ignoreCase ? keyVal.equalsIgnoreCase(val) : keyVal.equals(val)) return true; } } } return false; }
Source:
<code>private void ensureAdvancedOptionsOpen() { <START> if(control("advanced-button").exists()) { <END> control("advanced-button").click(); } }</code><technical_language>Extract control("advanced-button") local variable is called once</technical_language>

Target:
private void ensureAdvancedOptionsOpen() { Control advancedButton = control("advanced-button"); if(advancedButton.exists()) { advancedButton.click(); } }
Source:
<code>public int compareTo(SelectListAliasResolution o) { ExpressionColumn ecol = getExpressionColumn(); ExpressionColumn oecol = o.getExpressionColumn(); if (ecol == null || oecol == null) { return getIndex() - o.getIndex(); } else { int nc = getColumnName().compareTo(o.getColumnName()); if (nc != 0) { return nc; } else { RangeVariable rv = ecol.getRangeVariable(); RangeVariable orv = oecol.getRangeVariable(); if (rv == null) { if (orv == null) { return getIndex() - o.getIndex(); } else { if (orv.getColumnExpression(getAlias()) != null) { return 0; } else { return getIndex() - o.getIndex(); } } } else if (orv == null) { if (rv.getColumnExpression(getAlias()) != null) { return 0; } else { return getIndex() - o.getIndex(); } } else { ExpressionColumn myEC = rv.getColumnExpression(getColumnName()); ExpressionColumn oEC = orv.getColumnExpression(getColumnName()); if (myEC != null && oEC != null && myEC == oEC) { return 0; } else { <START> return getTableAlias().compareTo(o.getTableAlias()); <END> } } } } }</code><technical_language>getTableAlias() return null for NPE here</technical_language>

Target:
public int compareTo(SelectListAliasResolution o) { ExpressionColumn ecol = getExpressionColumn(); ExpressionColumn oecol = o.getExpressionColumn(); if (ecol == null || oecol == null) { return m_index - o.m_index; } else { int nc = m_columnName.compareTo(o.m_columnName); if (nc != 0) { return nc; } else { RangeVariable rv = ecol.getRangeVariable(); RangeVariable orv = oecol.getRangeVariable(); if (rv == null) { if (orv == null) { return m_index - o.m_index; } else { if (orv.getColumnExpression(m_alias) != null) { return 0; } else { return m_index - o.m_index; } } } else if (orv == null) { if (rv.getColumnExpression(m_columnName) != null) { return 0; } else { return m_index - o.m_index; } } else { ExpressionColumn myEC = rv.getColumnExpression(m_columnName); ExpressionColumn oEC = orv.getColumnExpression(m_columnName); if (myEC != null && oEC != null && myEC == oEC) { return 0; } else { assert(m_tableAlias != null); return m_tableAlias.compareTo(o.m_tableAlias); } } } } }
Source:
<code>public void testTrySend() { final AtomicBoolean isReady = new AtomicBoolean(); final AtomicInteger checkCount = new AtomicInteger(); client = new MockClient(time, metadata) { @Override public boolean ready(Node node, long now) { checkCount.incrementAndGet(); if (isReady.get()) return super.ready(node, now); else return false; } }; consumerClient = new ConsumerNetworkClient(new LogContext(), client, metadata, time, 100, 10, Integer.MAX_VALUE); consumerClient.send(node, heartbeat()); consumerClient.send(node, heartbeat()); assertEquals(2, consumerClient.pendingRequestCount(node)); assertEquals(0, client.inFlightRequestCount(node.idString())); consumerClient.trySend(time.milliseconds()); <START> assertEquals(checkCount.getAndSet(0), 1); <END> assertEquals(2, consumerClient.pendingRequestCount(node)); assertEquals(0, client.inFlightRequestCount(node.idString())); isReady.set(true); consumerClient.trySend(time.milliseconds()); assertEquals(checkCount.getAndSet(0), 2); assertEquals(2, consumerClient.pendingRequestCount(node)); assertEquals(2, client.inFlightRequestCount(node.idString())); }</code><technical_language>nit: expectation argument</technical_language>

Target:
public void testTrySend() { final AtomicBoolean isReady = new AtomicBoolean(); final AtomicInteger checkCount = new AtomicInteger(); client = new MockClient(time, metadata) { @Override public boolean ready(Node node, long now) { checkCount.incrementAndGet(); if (isReady.get()) return super.ready(node, now); else return false; } }; consumerClient = new ConsumerNetworkClient(new LogContext(), client, metadata, time, 100, 10, Integer.MAX_VALUE); consumerClient.send(node, heartbeat()); consumerClient.send(node, heartbeat()); assertEquals(2, consumerClient.pendingRequestCount(node)); assertEquals(0, client.inFlightRequestCount(node.idString())); consumerClient.trySend(time.milliseconds()); assertEquals(1, checkCount.getAndSet(0)); assertEquals(2, consumerClient.pendingRequestCount(node)); assertEquals(0, client.inFlightRequestCount(node.idString())); isReady.set(true); consumerClient.trySend(time.milliseconds()); assertEquals(2, checkCount.getAndSet(0)); assertEquals(2, consumerClient.pendingRequestCount(node)); assertEquals(2, client.inFlightRequestCount(node.idString())); }
Source:
<code>public void populate(ApplicationContext ctx) { <START> Map<String, Plugin> allPlugins = getPlugins(ctx); END> Map<String, Plugin> allExistingPlugins = dataService.findAll(PLUGIN, Plugin.class) .collect(toMap(Plugin::getId, Function.identity())); List<String> pluginIdsToDelete = newArrayList(); allExistingPlugins.forEach((pluginId, plugin) -> { if (allPlugins.get(pluginId) == null) { pluginIdsToDelete.add(pluginId); dataService.delete(PLUGIN, plugin); } }); pluginIdsToDelete.forEach(allExistingPlugins::remove); allPlugins.forEach(allExistingPlugins::putIfAbsent); dataService.getRepository(PLUGIN, Plugin.class).upsertBatch(newArrayList(allExistingPlugins.values())); }</code><technical_language>changes related description update? If this a bug fix? In case of a bug fix create issue a separate PR</technical_language>

Target:
public void populate(ApplicationContext ctx) { Map<String, Plugin> newOrChangedPluginMap = getPlugins(ctx); List<Plugin> deletedPlugins = new ArrayList<>(); Map<String, Plugin> existingPluginMap = dataService.findAll(PLUGIN, Plugin.class) .collect(toMap(Plugin::getId, Function.identity())); existingPluginMap.forEach((pluginId, plugin) -> { if (newOrChangedPluginMap.get(pluginId) == null) { deletedPlugins.add(plugin); } }); if (!newOrChangedPluginMap.isEmpty()) { dataService.getRepository(PLUGIN, Plugin.class).upsertBatch(newArrayList(newOrChangedPluginMap.values())); } if (!deletedPlugins.isEmpty()) { dataService.delete(PLUGIN, deletedPlugins.stream()); } }
Source:
<code>protected OperationSelector createOperationSelector() { <START> if (operationName.equals(OperationName.INCREMENT_AND_GET)) { <END> return new RatioOperationSelector.Builder().add(CounterOperations.INCREMENT_AND_GET, 1).build(); } else if (operationName.equals(OperationName.DECREMENT_AND_GET)) { return new RatioOperationSelector.Builder().add(CounterOperations.DECREMENT_AND_GET, 1).build(); } else if (operationName.equals(OperationName.ADD_AND_GET)) { return new RatioOperationSelector.Builder().add(CounterOperations.ADD_AND_GET, 1).build(); } else if (operationName.equals(OperationName.COMPARE_AND_SET)) { return new RatioOperationSelector.Builder().add(CounterOperations.COMPARE_AND_SET, 1).build(); } else { throw new IllegalArgumentException("Unknown operation!"); } }</code><technical_language>operationName is enum, switch</technical_language>

Target:
protected OperationSelector createOperationSelector() { switch (operationName) { case INCREMENT_AND_GET: return new RatioOperationSelector.Builder().add(CounterOperations.INCREMENT_AND_GET, 1).build(); case DECREMENT_AND_GET: return new RatioOperationSelector.Builder().add(CounterOperations.DECREMENT_AND_GET, 1).build(); case ADD_AND_GET: return new RatioOperationSelector.Builder().add(CounterOperations.ADD_AND_GET, 1).build(); case COMPARE_AND_SET: return new RatioOperationSelector.Builder().add(CounterOperations.COMPARE_AND_SET, 1).build(); default: throw new IllegalArgumentException("Unknown operation!"); } }
Source:
<code><START> public MockHelixParticipant(ClusterMapConfig clusterMapConfig) { <END> super(clusterMapConfig, new MockHelixManagerFactory(), metricRegistry, parseDcJsonAndPopulateDcInfo(clusterMapConfig.clusterMapDcsZkConnectStrings).get( clusterMapConfig.clusterMapDatacenterName).getZkConnectStrs().get(0), true); mockReplicationManagerListener = Mockito.mock(PartitionStateChangeListener.class); doAnswer(invocation -> { replicaState = ReplicaState.BOOTSTRAP; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateBootstrap(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeStandbyFromBootstrap(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.INACTIVE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDeactivation(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeInactiveFromStandby(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.OFFLINE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDisconnection(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeOfflineFromInactive(any(String.class)); }</code><technical_language>MockHelixParticipant(ClusterMapConfig) call this(clusterMapConfig, new MockHelixManagerFactory())</technical_language>

Target:
public MockHelixParticipant(ClusterMapConfig clusterMapConfig) { this(clusterMapConfig, new MockHelixManagerFactory()); mockReplicationManagerListener = Mockito.mock(PartitionStateChangeListener.class); doAnswer(invocation -> { replicaState = ReplicaState.BOOTSTRAP; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateBootstrap(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeStandbyFromBootstrap(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.INACTIVE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDeactivation(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeInactiveFromStandby(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.OFFLINE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDisconnection(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeOfflineFromInactive(any(String.class)); }
Source:
<code>static void assertMonitor(NodeMonitor monitor, Computer c) throws AssertionError { AbstractNodeMonitorDescriptor<?> descriptor = monitor.getDescriptor(); final Method monitorMethod; try { monitorMethod = AbstractAsyncNodeMonitorDescriptor.class.getDeclaredMethod("monitor", Computer.class); } catch (NoSuchMethodException ex) { <START> System.out.println("Cannot invoke monitor " + monitor + ", no monitor(Computer.class) method in the Descriptor. It will be ignored. " + ex.getMessage()); <END> return; } try { monitorMethod.setAccessible(true); Object res = monitorMethod.invoke(descriptor, c); System.out.println("Successfully executed monitor " + monitor); } catch (Exception ex) { throw new AssertionError("Failed to run monitor " + monitor + " for computer " + c, ex); } finally { monitorMethod.setAccessible(false); } }</code><technical_language>This is test code. throw up! Or, better, method @Restricted(NoExternalUse.class) public</technical_language>

Target:
static void assertMonitor(NodeMonitor monitor, Computer c) throws AssertionError { AbstractNodeMonitorDescriptor<?> descriptor = monitor.getDescriptor(); final Method monitorMethod; try { monitorMethod = AbstractAsyncNodeMonitorDescriptor.class.getDeclaredMethod("monitor", Computer.class); } catch (NoSuchMethodException ex) { throw new AssertionError("Cannot invoke monitor " + monitor + ", no monitor(Computer.class) method in the Descriptor. It will be ignored. ", ex); } try { monitorMethod.setAccessible(true); Object res = monitorMethod.invoke(descriptor, c); System.out.println("Successfully executed monitor " + monitor); } catch (Exception ex) { throw new AssertionError("Failed to run monitor " + monitor + " for computer " + c, ex); } finally { monitorMethod.setAccessible(false); } }
Source:
<code>public static boolean isSchemaCheckRequired(PTableType tableType, ReadOnlyProps props) { <START> if (PTableType.TABLE.equals(tableType) && isNamespaceMappingEnabled(tableType, props)) { return true; } <END> return false; }</code><technical_language>nit: return PTableType.TABLE.equals(tableType) && isNamespaceMappingEnabled(tableType, props);</technical_language>

Target:
public static boolean isSchemaCheckRequired(PTableType tableType, ReadOnlyProps props) { return PTableType.TABLE.equals(tableType) && isNamespaceMappingEnabled(tableType, props); }
Source:
<code>public void testExactExpirationOnWrite() throws Exception { initTest(StateTtlConfig.UpdateType.OnCreateAndWrite, StateTtlConfig.StateVisibility.NeverReturnExpired); takeAndRestoreSnapshot(); timeProvider.time = 0; ctx().update(ctx().updateEmpty); takeAndRestoreSnapshot(); timeProvider.time = 20; assertEquals(UNEXPIRED_AVAIL, ctx().getUpdateEmpty, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 50; ctx().update(ctx().updateUnexpired); takeAndRestoreSnapshot(); timeProvider.time = 120; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUnexpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 170; ctx().update(ctx().updateExpired); takeAndRestoreSnapshot(); timeProvider.time = 220; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUpdateExpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 300; assertEquals(EXPIRED_UNAVAIL, ctx().emptyValue, ctx().get()); <START> assertTrue(ctx().isOriginalEmptyValue()); <END> }</code><technical_language>suggestion assertTrue("Original state cleared access", ctx().isOriginalEmptyValue());</technical_language>

Target:
public void testExactExpirationOnWrite() throws Exception { initTest(StateTtlConfig.UpdateType.OnCreateAndWrite, StateTtlConfig.StateVisibility.NeverReturnExpired); takeAndRestoreSnapshot(); timeProvider.time = 0; ctx().update(ctx().updateEmpty); takeAndRestoreSnapshot(); timeProvider.time = 20; assertEquals(UNEXPIRED_AVAIL, ctx().getUpdateEmpty, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 50; ctx().update(ctx().updateUnexpired); takeAndRestoreSnapshot(); timeProvider.time = 120; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUnexpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 170; ctx().update(ctx().updateExpired); takeAndRestoreSnapshot(); timeProvider.time = 220; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUpdateExpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 300; assertEquals(EXPIRED_UNAVAIL, ctx().emptyValue, ctx().get()); assertTrue("Original state should be cleared on access", ctx().isOriginalEmptyValue()); }
Source:
<code>protected void setCapacity(String workerIdentity, int newExecutorNum, int newWaitQueueSize) throws IOException, ServiceException { long currentTime = System.currentTimeMillis(); if (currentTime > nextCheckTime) { <START> LlapZookeeperRegistryImpl.ConfigChangeLockResult lockResult = <END> registry.lockForConfigChange(currentTime + this.minConfigChangeDelayMs); LOG.debug("Got result for lock check: {}", lockResult); if (lockResult.isSuccess()) { LOG.info("Setting capacity for workerIdentity={} to newExecutorNum={}, newWaitQueueSize={}", workerIdentity, newExecutorNum, newWaitQueueSize); LlapServiceInstance serviceInstance = registry.getInstances().getInstance(workerIdentity); LlapManagementProtocolClientImpl client = clientFactory.create(serviceInstance); client.setCapacity(null, SetCapacityRequestProto.newBuilder() .setExecutorNum(newExecutorNum) .setQueueSize(newWaitQueueSize) .build()); } if (lockResult.getNextConfigChangeTime() > -1L) { nextCheckTime = lockResult.getNextConfigChangeTime(); } } else { LOG.debug("Skipping check. Current time and we are waiting for {}.", currentTime, nextCheckTime); } }</code><technical_language>is code opens a window for more blacklisted nodes maximum. If multiple conclusion blacklist (different) nodes time, -1L in nextCheckTime on, call lockForConfigChange. If executing in right order (increasing time), lock successful verifies next is higher previous blacklist potentially more daemons allowed. Instead, need 1) fetch current of distributed long. 2) compare current timestamp skip if is smaller. A local, cached nextCheckTime is unnecessary lead false positives...</technical_language>

Target:
protected void setCapacity(String workerIdentity, int newExecutorNum, int newWaitQueueSize) throws IOException, ServiceException { long currentTime = System.currentTimeMillis(); if (currentTime > nextCheckTime) { LlapZookeeperRegistryImpl.ConfigChangeLockResult lockResult = registry.lockForConfigChange(currentTime, currentTime + this.minConfigChangeDelayMs); LOG.debug("Got result for lock check: {}", lockResult); if (lockResult.isSuccess()) { LOG.info("Setting capacity for workerIdentity={} to newExecutorNum={}, newWaitQueueSize={}", workerIdentity, newExecutorNum, newWaitQueueSize); LlapServiceInstance serviceInstance = registry.getInstances().getInstance(workerIdentity); LlapManagementProtocolClientImpl client = clientFactory.create(serviceInstance); client.setCapacity(null, SetCapacityRequestProto.newBuilder() .setExecutorNum(newExecutorNum) .setQueueSize(newWaitQueueSize) .build()); } if (lockResult.getNextConfigChangeTime() > -1L) { nextCheckTime = lockResult.getNextConfigChangeTime(); } } else { LOG.debug("Skipping check. Current time and we are waiting for {}.", currentTime, nextCheckTime); } }