auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUp() { final InMemoryStorageFactory storageFactory = InMemoryStorageFactory.getInstance(); commandStore = spy(new CommandStore(storageFactory.createCommandStorage())); scheduler = spy(new ExecutorCommandScheduler()); <START> final Log log = spy(new Log()); <END> commandBus = CommandBus.newBuilder() .setCommandStore(commandStore) .setCommandScheduler(scheduler) .setThreadSpawnAllowed(true) .setLog(log) .setAutoReschedule(false) .build(); eventBus = TestEventBusFactory.create(storageFactory); commandFactory = TestCommandFactory.newInstance(CommandBusShould.class); createProjectHandler = new CreateProjectHandler(newUuid()); responseObserver = new TestResponseObserver(); }</code><technical_language>Do this log else? local variable, lost references other methods. do spy then</technical_language>

Target:
public void setUp() { final InMemoryStorageFactory storageFactory = InMemoryStorageFactory.getInstance(); commandStore = spy(new CommandStore(storageFactory.createCommandStorage())); scheduler = spy(new ExecutorCommandScheduler()); commandBus = CommandBus.newBuilder() .setCommandStore(commandStore) .setCommandScheduler(scheduler) .setThreadSpawnAllowed(true) .setAutoReschedule(false) .build(); eventBus = TestEventBusFactory.create(storageFactory); commandFactory = TestCommandFactory.newInstance(CommandBusShould.class); createProjectHandler = new CreateProjectHandler(newUuid()); responseObserver = new TestResponseObserver(); }
Source:
<code>private int getAlertCount(AuditLog entry, List<AuditLog> results) { int count = 0; <START> log.info("Founding alerts"); <END> if (results != null) { for (AuditLog al : results) { log.info("Testing: {id='{}', severity='{}', type='{}', hostId='{}', hostName='{}', date='{}'}", al.getAuditLogId(), al.getSeverity(), al.getLogType(), al.getVdsId(), al.getVdsName(), al.getLogTime()); if (al.getSeverity() == entry.getSeverity() && al.getVdsId().equals(entry.getVdsId()) && al.getLogType() == entry.getLogType()) { count++; } log.info("Count: {}", count); } } log.info("Found alerts: {}", count); return count; }</code><technical_language>Founding =></technical_language>

Target:
private int getAlertCount(AuditLog entry, List<AuditLog> results) { int count = 0; if (results != null) { for (AuditLog al : results) { if (al.getSeverity() == entry.getSeverity() && al.getVdsId().equals(entry.getVdsId()) && al.getLogType() == entry.getLogType()) { count++; } } } return count; }
Source:
<code><START> protected synchronized void setPinned(boolean pinned) { <END> if (!pinned) { if (fSavedRangeSyncSignal != null) { windowRangeUpdated(fSavedRangeSyncSignal); fSavedRangeSyncSignal = null; } if (fSavedTimeSyncSignal != null) { selectionRangeUpdated(fSavedTimeSyncSignal); fSavedTimeSyncSignal = null; } } }</code><technical_language>I propose a common pin implementation base class AbstractTimeGraphView. note, existing implementation in this class inhibits changes coming in external, prevent pinned Call Stack view broadcasting a new window range</technical_language>

Target:
public void setPinned(boolean pinned) { if (!pinned) { if (fSavedRangeSyncSignal != null) { windowRangeUpdated(fSavedRangeSyncSignal); fSavedRangeSyncSignal = null; } if (fSavedTimeSyncSignal != null) { selectionRangeUpdated(fSavedTimeSyncSignal); fSavedTimeSyncSignal = null; } } }
Source:
<code>public CompletableFuture<LanguageServer> getInitializedLanguageClient() { return CompletableFuture.supplyAsync(() -> { <START> while (!this.wrapper.isInitialized()) { <END> try { Thread.sleep(50); } catch (InterruptedException e) { break; } } return this.server; }); }</code><technical_language>This is a clean approach introduce wait loops in CompletableFuture. LanguageServerWrapper return method providing CompletableFuture<LanguageServer>. simply initializeFuture.thenApply(() -> languageServer);</technical_language>

Target:
public CompletableFuture<LanguageServer> getInitializedLanguageClient() { return this.wrapper.getInitializedServer(); }
Source:
<code>void switchStructure(Object treeNodeData) throws NoSuchMetadataFieldException { try { metadataPanel.preserveLogical(); } catch (InvalidMetadataValueException e) { <START> logger.info(e.getLocalizedMessage()); <END> } metadataPanel.showLogical(structurePanel.getSelectedStructure()); if (Objects.nonNull(treeNodeData) && treeNodeData instanceof StructureTreeNode) { StructureTreeNode structureTreeNode = (StructureTreeNode) treeNodeData; if (Objects.nonNull(structureTreeNode.getDataObject())) { if (structureTreeNode.getDataObject() instanceof IncludedStructuralElement && structurePanel.getSelectedStructure().isPresent()) { IncludedStructuralElement structuralElement = structurePanel.getSelectedStructure().get(); if (!structuralElement.getViews().isEmpty()) { ArrayList<View> views = new ArrayList<>(structuralElement.getViews()); if (Objects.nonNull(views.get(0))) { View firstView = views.get(0); updatePhysicalStructureTree(firstView); updateGallery(firstView); } } } else if (structureTreeNode.getDataObject() instanceof View) { updateGallery((View) structureTreeNode.getDataObject()); } } } }</code><technical_language>Stack trace is nice (but necessary): suggestion logger.info(e.getLocalizedMessage(), e);</technical_language>

Target:
void switchStructure(Object treeNodeData) throws NoSuchMetadataFieldException { try { metadataPanel.preserveLogical(); } catch (InvalidMetadataValueException e) { logger.info(e.getLocalizedMessage(), e); } Optional<IncludedStructuralElement> selectedStructure = structurePanel.getSelectedStructure(); metadataPanel.showLogical(selectedStructure); if (treeNodeData instanceof StructureTreeNode) { StructureTreeNode structureTreeNode = (StructureTreeNode) treeNodeData; if (Objects.nonNull(structureTreeNode.getDataObject())) { if (structureTreeNode.getDataObject() instanceof IncludedStructuralElement && selectedStructure.isPresent()) { IncludedStructuralElement structuralElement = selectedStructure.get(); if (!structuralElement.getViews().isEmpty()) { ArrayList<View> views = new ArrayList<>(structuralElement.getViews()); if (Objects.nonNull(views.get(0))) { View firstView = views.get(0); updatePhysicalStructureTree(firstView); updateGallery(firstView); } } } else if (structureTreeNode.getDataObject() instanceof View) { updateGallery((View) structureTreeNode.getDataObject()); } } } }
Source:
<code>public void getFolderStatus(final String folderId, final OnResultListener2<String, FolderStatus> listener) { new GetRequest(mContext, mUrl, GetRequest.URI_STATUS, mApiKey, ImmutableMap.of("folder", folderId), result -> { FolderStatus m = new Gson().fromJson(result, FolderStatus.class); <START> mCachedFolderStatusInfo.put(folderId, m); <END> listener.onResult(folderId, m); }); }</code><technical_language>pass m? I assume folderId is attribute struct</technical_language>

Target:
public void getFolderStatus(final String folderId, final OnResultListener2<String, FolderStatus> listener) { new GetRequest(mContext, mUrl, GetRequest.URI_STATUS, mApiKey, ImmutableMap.of("folder", folderId), result -> { FolderStatus m = new Gson().fromJson(result, FolderStatus.class); mCachedFolderStatuses.put(folderId, m); listener.onResult(folderId, m); }); }
Source:
<code>public void returnsDefaultBlockingTimeoutIfConnectorWithoutSpecifiedIdleTimeoutIsMinimal() throws IOException { assertThat(BlockingTimeouts.getBlockingTimeout(OBJECT_MAPPER, getConfigurationFromResource( <START> "lock/one-specified-one-implicit-timeout.yml"))) <END> .isEqualTo(BlockingTimeouts.getDefaultBlockingTimeout()); }</code><technical_language>rename config file one-default-one-higher-explicit-timeout something, basically 90s > default</technical_language>

Target:
public void returnsDefaultBlockingTimeoutIfConnectorWithoutSpecifiedIdleTimeoutIsMinimal() throws IOException { assertThat(BlockingTimeouts.getBlockingTimeout(OBJECT_MAPPER, getConfigurationFromResource( "lock/one-default-one-higher-explicit-timeout.yml"))) .isEqualTo(BlockingTimeouts.scaleForErrorMargin(BlockingTimeouts.DEFAULT_IDLE_TIMEOUT, ERROR_MARGIN)); }
Source:
<code>protected <K, V> void assertLoadAfterOperation(CacheHelper<K, V> cacheHelper, ConditionalOperation operation, Ownership ownership, boolean skipLoad) { switch (ownership) { case PRIMARY: assertLoad(cacheHelper, skipLoad ? 0 : 1, 0, 0); break; case BACKUP: assertLoad(cacheHelper, 0, skipLoad ? 0 : 1, 0); break; case NON_OWNER: if (skipLoad) { assertLoad(cacheHelper, 0, 0, 0); } else { <START> assertEquals("primary owner load", 1, cacheHelper.loads(Ownership.PRIMARY)); <END> long backupLoads = cacheHelper.loads(Ownership.BACKUP); assertTrue("backup owner load: " + backupLoads, backupLoads <= 1); assertEquals("non owner load", 0, cacheHelper.loads(Ownership.NON_OWNER)); } break; } }</code><technical_language>In theory do this check primary cache loader managed load entry increment load count</technical_language>

Target:
protected <K, V> void assertLoadAfterOperation(CacheHelper<K, V> cacheHelper, ConditionalOperation operation, Ownership ownership, boolean skipLoad) { switch (ownership) { case PRIMARY: assertLoad(cacheHelper, skipLoad ? 0 : 1, 0, 0); break; case BACKUP: assertLoad(cacheHelper, 0, skipLoad ? 0 : 1, 0); break; case NON_OWNER: if (skipLoad) { assertLoad(cacheHelper, 0, 0, 0); } else { long primaryLoads = cacheHelper.loads(Ownership.PRIMARY); assertTrue("primary owner load: " + primaryLoads, primaryLoads <= 1); long backupLoads = cacheHelper.loads(Ownership.BACKUP); assertTrue("backup owner load: " + backupLoads, backupLoads <= 1); assertTrue("loads: primary=" + primaryLoads + ", backup=" + backupLoads, primaryLoads + backupLoads >= 1); assertEquals("non owner load", 0, cacheHelper.loads(Ownership.NON_OWNER)); } break; } }
Source:
<code>public void shouldBeRotatableByTheCreator() { <START> boolean canRotatePicture = actionService.checkFilter(ROTATE_PICTURE_FILTER_NAME, getActionContext(coreSession)); <END> assertTrue(canRotatePicture); }</code><technical_language>need boolean variable, enough do: suggestion assertTrue(actionService.checkFilter(ROTATE_PICTURE_FILTER_NAME, getActionContext(coreSession)));</technical_language>

Target:
public void shouldBeRotatableByTheCreator() { assertTrue(actionService.checkFilter(ROTATE_PICTURE_FILTER_NAME, getActionContext(coreSession))); }
Source:
<code>public String runTask(String[] args) throws Exception { final String schema = args[0]; String version = args[1]; <START> final String HadoopJobIdFile = args[2]; <END> final HadoopIngestionSpec theSchema = HadoopDruidIndexerConfig.JSON_MAPPER .readValue( schema, HadoopIngestionSpec.class ); final HadoopDruidIndexerConfig config = HadoopDruidIndexerConfig.fromSpec( theSchema .withTuningConfig(theSchema.getTuningConfig().withVersion(version)) ); final MetadataStorageUpdaterJobHandler maybeHandler; if (config.isUpdaterJobSpecSet()) { maybeHandler = injector.getInstance(MetadataStorageUpdaterJobHandler.class); } else { maybeHandler = null; } job = new HadoopDruidIndexerJob(config, maybeHandler); job.setHadoopJobIdFile(HadoopJobIdFile); log.info("Starting a hadoop index generator job..."); try { if (job.run()) { return HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsString( new HadoopIndexGeneratorInnerProcessingStatus( job.getPublishedSegments(), job.getStats(), null ) ); } else { return HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsString( new HadoopIndexGeneratorInnerProcessingStatus( null, job.getStats(), job.getErrorMessage() ) ); } } catch (Exception e) { log.error(e, "Encountered exception in HadoopIndexGeneratorInnerProcessing."); return HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsString( new HadoopIndexGeneratorInnerProcessingStatus( null, job.getStats(), e.getMessage() ) ); } }</code><technical_language>HadoopJobIdFile -> hadoopJobIdFile</technical_language>

Target:
public String runTask(String[] args) throws Exception { final String schema = args[0]; String version = args[1]; final String hadoopJobIdFile = args[2]; final HadoopIngestionSpec theSchema = HadoopDruidIndexerConfig.JSON_MAPPER .readValue( schema, HadoopIngestionSpec.class ); final HadoopDruidIndexerConfig config = HadoopDruidIndexerConfig.fromSpec( theSchema .withTuningConfig(theSchema.getTuningConfig().withVersion(version)) ); final MetadataStorageUpdaterJobHandler maybeHandler; if (config.isUpdaterJobSpecSet()) { maybeHandler = injector.getInstance(MetadataStorageUpdaterJobHandler.class); } else { maybeHandler = null; } job = new HadoopDruidIndexerJob(config, maybeHandler); job.setHadoopJobIdFile(hadoopJobIdFile); log.info("Starting a hadoop index generator job..."); try { if (job.run()) { return HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsString( new HadoopIndexGeneratorInnerProcessingStatus( job.getPublishedSegments(), job.getStats(), null ) ); } else { return HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsString( new HadoopIndexGeneratorInnerProcessingStatus( null, job.getStats(), job.getErrorMessage() ) ); } } catch (Exception e) { log.error(e, "Encountered exception in HadoopIndexGeneratorInnerProcessing."); return HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsString( new HadoopIndexGeneratorInnerProcessingStatus( null, job.getStats(), e.getMessage() ) ); } }
Source:
<code>public static List<SleepMetrics> fromV1(final com.hello.suripu.core.models.Timeline timelineV1) { <START> final List<SleepMetrics> metrics = new ArrayList<>(); <END> final Optional<SleepStats> maybeStatistics = timelineV1.statistics; if (maybeStatistics.isPresent() && !maybeStatistics.get().isFromNull()) { SleepStats statistics = maybeStatistics.get(); metrics.add(create("total_sleep", Optional.of(statistics.sleepDurationInMinutes.longValue()), Unit.MINUTES, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("sound_sleep", Optional.of(statistics.soundSleepDurationInMinutes.longValue()), Unit.MINUTES, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("time_to_sleep", Optional.of(statistics.sleepOnsetTimeMinutes.longValue()), Unit.MINUTES, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("times_awake", Optional.of(statistics.numberOfMotionEvents.longValue()), Unit.QUANTITY, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("fell_asleep", Optional.of(statistics.sleepTime), Unit.TIMESTAMP, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("woke_up", Optional.of(statistics.wakeTime), Unit.TIMESTAMP, CurrentRoomState.State.Condition.IDEAL)); } for (Insight insight : timelineV1.insights) { metrics.add(create(insight.sensor.toString(), Optional.<Long>absent(), Unit.CONDITION, insight.condition)); } return metrics; }</code><technical_language>Guava style for lists is recommended : Lists.newArrayList()</technical_language>

Target:
public static List<SleepMetrics> fromV1(final com.hello.suripu.core.models.Timeline timelineV1) { final List<SleepMetrics> metrics = Lists.newArrayList(); final Optional<SleepStats> maybeStatistics = timelineV1.statistics; if (maybeStatistics.isPresent() && !maybeStatistics.get().isFromNull()) { SleepStats statistics = maybeStatistics.get(); metrics.add(create("total_sleep", Optional.of(statistics.sleepDurationInMinutes.longValue()), Unit.MINUTES, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("sound_sleep", Optional.of(statistics.soundSleepDurationInMinutes.longValue()), Unit.MINUTES, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("time_to_sleep", Optional.of(statistics.sleepOnsetTimeMinutes.longValue()), Unit.MINUTES, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("times_awake", Optional.of(statistics.numberOfMotionEvents.longValue()), Unit.QUANTITY, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("fell_asleep", Optional.of(statistics.sleepTime), Unit.TIMESTAMP, CurrentRoomState.State.Condition.IDEAL)); metrics.add(create("woke_up", Optional.of(statistics.wakeTime), Unit.TIMESTAMP, CurrentRoomState.State.Condition.IDEAL)); } for (Insight insight : timelineV1.insights) { metrics.add(create(insight.sensor.toString(), Optional.<Long>absent(), Unit.CONDITION, insight.condition)); } return metrics; }
Source:
<code>public void typed_list_factory_should_allow_typed_list_assertions() { List<String> list = asList("Homer", "Marge", "Bart", "Lisa", "Maggie"); <START> assertThat((Object) list).instanceOf(list(String.class)).contains("Bart", "Lisa"); <END> }</code><technical_language>replace assertion this shows benefit of instanceOf: java assertThat(list).first().instanceOf(STRING).startsWith("Ho");</technical_language>

Target:
void typed_list_factory_should_allow_typed_list_assertions() { Object value = asList("Homer", "Marge", "Bart", "Lisa", "Maggie"); ListAssert<String> result = assertThat(value).asInstanceOf(list(String.class)); result.contains("Bart", "Lisa"); }
Source:
<code>private void testSingleString(final String value) { final JSONObject orthodoxJson = new JSONObject(value); <START> final JSONObject anarchyJson = (JSONObject) StrictJsonParser.parse(value); <END> Assert.assertEquals("Checking json " + value, orthodoxJson.toString(), anarchyJson.toString()); }</code><technical_language>I thought strict parser generate orthodoxJson</technical_language>

Target:
private void testSingleString(final String value) { final JSONObject orthodoxJson = new JSONObject(value); final JSONObject anarchyJson = StrictJsonParser.parseObject(value); Assert.assertEquals("Checking json " + value, orthodoxJson.toString(), anarchyJson.toString()); }
Source:
<code>public void commitDatabase() { String s = mapper.toJson(map); synchronized (map) { try (FileOutputStream outputStream = new FileOutputStream(file, false);) { outputStream.write(s.getBytes()); } catch (Exception e) { logger.error("Error writing JsonDB to {}. Cause {}.", file.getPath(), e.getMessage()); } File backup = new File(file.getParent() + File.separator + BACKUP_EXTENSION, System.currentTimeMillis() + SEPARATOR + file.getName()); <START> try (FileOutputStream outputStream = new FileOutputStream(backup, false);) { <END> outputStream.write(s.getBytes()); } catch (Exception e) { logger.error("Error writing JsonDB to {}. Cause {}.", file.getPath(), e.getMessage()); } deferredSince = 0; } }</code><technical_language>lines for writing out file identical for file backup (apart of this parameter, of course), please factor out</technical_language>

Target:
public void commitDatabase() { String json = mapper.toJson(map); synchronized (map) { writeDatabaseFile(file, json); writeDatabaseFile(new File(file.getParent() + File.separator + BACKUP_EXTENSION, System.currentTimeMillis() + SEPARATOR + file.getName()), json); deferredSince = 0; } }
Source:
<code>public void loadState(final Configuration configuration, final Graph... graphs) { if (graphs.length != 1) { throw new IllegalStateException("Must provide one graph to use, received " + graphs.length); } <START> Graph graph = graphs[0]; <END> if (configuration.containsKey(INITIAL_VOTE_STRENGTH_TRAVERSAL)) this.initialVoteStrengthTraversal = PureTraversal.loadState(configuration, INITIAL_VOTE_STRENGTH_TRAVERSAL, graph); if (configuration.containsKey(EDGE_TRAVERSAL)) { this.edgeTraversal = PureTraversal.loadState(configuration, EDGE_TRAVERSAL, graph); this.voteScope = MessageScope.Local.of(() -> this.edgeTraversal.get().clone()); this.countScope = MessageScope.Local.of(new MessageScope.Local.ReverseTraversalSupplier(this.voteScope)); } this.property = configuration.getString(PROPERTY, CLUSTER); this.maxIterations = configuration.getInt(MAX_ITERATIONS, 30); this.distributeVote = configuration.getBoolean(DISTRIBUTE_VOTE, false); }</code><technical_language>style is final variables marked - this be</technical_language>

Target:
public void loadState(final Configuration configuration, final Graph... graphs) { if (graphs.length != 1) { throw new IllegalArgumentException("Must provide one graph to use, received " + graphs.length); } final Graph graph = graphs[0]; if (configuration.containsKey(INITIAL_VOTE_STRENGTH_TRAVERSAL)) this.initialVoteStrengthTraversal = PureTraversal.loadState(configuration, INITIAL_VOTE_STRENGTH_TRAVERSAL, graph); if (configuration.containsKey(EDGE_TRAVERSAL)) { this.edgeTraversal = PureTraversal.loadState(configuration, EDGE_TRAVERSAL, graph); this.voteScope = MessageScope.Local.of(() -> this.edgeTraversal.get().clone()); this.countScope = MessageScope.Local.of(new MessageScope.Local.ReverseTraversalSupplier(this.voteScope)); } this.property = configuration.getString(PROPERTY, CLUSTER); this.maxIterations = configuration.getInt(MAX_ITERATIONS, 30); this.distributeVote = configuration.getBoolean(DISTRIBUTE_VOTE, false); }
Source:
<code>private String constructDisplayName(InstanceData instanceData) { StringBuilder dname = new StringBuilder(); for (QuestionDto q : displayNamePartList) { Map<Long, String> allAnswersForQuestion = instanceData.responseMap.get(q.getKeyId()); if (allAnswersForQuestion != null && allAnswersForQuestion.size() > 0) { String qtype = q.getType().toString(); <START> String answer = allAnswersForQuestion.get(Long.valueOf(0)); <END> if (answer != null) { if (dname.length() > 0) { dname.append(" - "); } dname.append(QuestionAnswerStore.getDatapointNameValue(qtype,answer)); } } } return dname.toString(); }</code><technical_language>literal 0L instead of Long.valueOf(0)</technical_language>

Target:
private String constructDisplayName(InstanceData instanceData) { StringBuilder dname = new StringBuilder(); for (QuestionDto q : displayNamePartList) { Map<Long, String> allAnswersForQuestion = instanceData.responseMap.get(q.getKeyId()); if (allAnswersForQuestion != null && allAnswersForQuestion.size() > 0) { String qtype = q.getType().toString(); String answer = allAnswersForQuestion.get(0L); if (answer != null) { if (dname.length() > 0) { dname.append(" - "); } dname.append(QuestionAnswerStore.getDatapointNameValue(qtype,answer)); } } } return dname.toString(); }
Source:
<code>public List<FieldNode> getSelectColsFromChildren(SelectOperator op, List<FieldNode> colList) { List<FieldNode> cols = new ArrayList<>(); SelectDesc conf = op.getConf(); if (colList != null && conf.isSelStarNoCompute()) { cols.addAll(colList); return cols; } List<ExprNodeDesc> selectExprs = conf.getColList(); List<String> outputColumnNames = conf.getOutputColumnNames(); for (int i = 0; i < outputColumnNames.size(); i++) { if (colList == null) { cols = mergeFieldNodes(cols, selectExprs.get(i)); <START> } else if (lookupColumn(colList, outputColumnNames.get(i)) != null) { <END> FieldNode childFn = lookupColumn(colList, outputColumnNames.get(i)); ExprNodeDesc desc = selectExprs.get(i); if (desc instanceof ExprNodeColumnDesc && ((ExprNodeColumnDesc) desc).getIsGenerated()) { FieldNode fn = new FieldNode(((ExprNodeColumnDesc) desc).getColumn()); fn.setNodes(childFn.getNodes()); cols = mergeFieldNodes(cols, fn); } else { cols = mergeFieldNodes(cols, selectExprs.get(i)); } } } return cols; }</code><technical_language>call lookupColumn need return below</technical_language>

Target:
public List<FieldNode> getSelectColsFromChildren(SelectOperator op, List<FieldNode> colList) { List<FieldNode> cols = new ArrayList<>(); SelectDesc conf = op.getConf(); if (colList != null && conf.isSelStarNoCompute()) { cols.addAll(colList); return cols; } List<ExprNodeDesc> selectExprs = conf.getColList(); List<String> outputColumnNames = conf.getOutputColumnNames(); for (int i = 0; i < outputColumnNames.size(); i++) { if (colList == null) { cols = mergeFieldNodesWithDesc(cols, selectExprs.get(i)); } else { FieldNode childFn = lookupColumn(colList, outputColumnNames.get(i)); if (childFn != null) { ExprNodeDesc desc = selectExprs.get(i); if (desc instanceof ExprNodeColumnDesc && ((ExprNodeColumnDesc) desc).getIsGenerated()) { FieldNode fn = new FieldNode(((ExprNodeColumnDesc) desc).getColumn()); fn.setNodes(childFn.getNodes()); cols = mergeFieldNodes(cols, fn); } else { cols = mergeFieldNodesWithDesc(cols, selectExprs.get(i)); } } } } return cols; }
Source:
<code><START> public void testIsComplete() throws Exception { <END> when( validator.isConditionValid( any( ConditionCol52.class ) ) ).thenReturn( true ); Callback<Boolean> callback = mock( Callback.class ); page.isComplete( callback ); verify( conditionsDefinedEvent ).fire( conditionsDefinedEventCaptor.capture() ); assertEquals( true, conditionsDefinedEventCaptor.getValue().getAreConditionsDefined() ); verify( callback ).callback( true ); }</code><technical_language>Test testIsNotComplete() is similar; avoid code duplication tests call a shared private method takes a boolean valid-state parameter; mock set-up verification</technical_language>

Target:
public void testIsComplete() throws Exception { testConditionCompletion( true ); }
Source:
<code>protected boolean isMapPositionValid(BlockPos pos, char mapPos) { IBlockState self = getBlockState(); IBlockState state = world.getBlockState(pos); switch (mapPos) { case 'O': if (self != state) return true; break; case 'B': case 'W': if (self == state) return true; break; case 'A': <START> if (world.isAirBlock(pos) || state.getMaterial() == Material.LAVA) <END> return true; break; } return false; }</code><technical_language>more efficient ask block if is air, world</technical_language>

Target:
protected boolean isMapPositionValid(BlockPos pos, char mapPos) { IBlockState self = getBlockState(); IBlockState state = world.getBlockState(pos); switch (mapPos) { case 'O': if (self != state) return true; break; case 'B': case 'W': if (self == state) return true; break; case 'A': if (state.getBlock().isAir(state, world, pos) || state.getMaterial() == Material.LAVA) return true; break; } return false; }
Source:
<code><START> public RepositoryObject getParent() { <END> return driver.getParentObject(this); }</code><technical_language>a Tombstone is longer in hierarchy (result of removing proxy), this method return a null throw exception</technical_language>

Target:
public RepositoryObject getParent() { return null; }
Source:
<code>public static void deleteEclipseProjectByNatureId(String natureId) throws CoreException { final IWorkspaceRunnable op = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (IProject project : projects) { if (project.hasNature("com.oaklandsw.transform.runtime.nature")) { continue; } if (project.getLocation() == null || !project.getLocation().toFile().exists() || !project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME).getLocation().toFile().exists()) { project.delete(false, true, monitor); continue; } if (!project.isOpen()) { project.open(monitor); } if (project.hasNature(natureId)) { <START> project.delete(false, true, monitor); <END> IFile eclipseClasspath = project.getFile(CLASSPATH_FILE_NAME); if (eclipseClasspath.exists()) { eclipseClasspath.delete(true, monitor); } IFile projectFile = project.getFile(PROJECT_FILE_NAME); if (projectFile.exists()) { projectFile.delete(true, monitor); } } } talendCodeJavaProjects.clear(); talendJobJavaProjects.clear(); tempJavaProject = null; }; }; IWorkspace workspace = ResourcesPlugin.getWorkspace(); try { ISchedulingRule schedulingRule = workspace.getRoot(); workspace.run(op, schedulingRule, IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException e) { if (e.getCause() != null) { ExceptionHandler.process(e.getCause()); } else { ExceptionHandler.process(e); } } }</code><technical_language>move this line here, .classpath .project file deleted</technical_language>

Target:
public static void deleteEclipseProjectByNatureId(String natureId) throws CoreException { final IWorkspaceRunnable op = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (IProject project : projects) { if (project.hasNature("com.oaklandsw.transform.runtime.nature")) { continue; } if (project.getLocation() == null || !project.getLocation().toFile().exists() || !project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME).getLocation().toFile().exists()) { project.delete(false, true, monitor); continue; } if (!project.isOpen()) { project.open(monitor); } if (project.hasNature(natureId)) { IFile eclipseClasspath = project.getFile(CLASSPATH_FILE_NAME); if (eclipseClasspath.exists()) { eclipseClasspath.delete(true, monitor); } IFile projectFile = project.getFile(PROJECT_FILE_NAME); if (projectFile.exists()) { projectFile.delete(true, monitor); } project.delete(false, true, monitor); } } talendCodeJavaProjects.clear(); talendJobJavaProjects.clear(); tempJavaProject = null; }; }; IWorkspace workspace = ResourcesPlugin.getWorkspace(); try { ISchedulingRule schedulingRule = workspace.getRoot(); workspace.run(op, schedulingRule, IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException e) { if (e.getCause() != null) { ExceptionHandler.process(e.getCause()); } else { ExceptionHandler.process(e); } } }
Source:
<code>protected void executeVmCommand() { if (shouldAddLease(getVm())) { if (FeatureSupported.isVmLeasesSupported(getEffectiveCompatibilityVersion())) { <START> if (validateLeaseStorageDomain(getVm().getLeaseStorageDomainId())) { <END> if (!addVmLease(getVm().getLeaseStorageDomainId(), getVm().getId())) { getVm().setLeaseStorageDomainId(null); } } else { auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_STORAGE_DOMAIN_ERROR); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_COMPAT_VERSION); } } super.executeVmCommand(); }</code><technical_language>validate (and feature support check) in validate() method</technical_language>

Target:
protected void executeVmCommand() { if (shouldAddLease(getVm().getStaticData())) { if (FeatureSupported.isVmLeasesSupported(getEffectiveCompatibilityVersion())) { if (validateLeaseStorageDomain(getVm().getLeaseStorageDomainId())) { if (!addVmLease(getVm().getLeaseStorageDomainId(), getVm().getId())) { getVm().setLeaseStorageDomainId(null); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_STORAGE_DOMAIN_ERROR); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_COMPAT_VERSION); } } super.executeVmCommand(); }
Source:
<code>@Override public boolean push(T row) { List<UUID> nodes = function.destination(row); <START> if (F.isEmpty(nodes)) <END> return true; List<Buffer> buffers = new ArrayList<>(nodes.size()); for (UUID node : nodes) { Buffer dest = perNodeBuffers.computeIfAbsent(node, this::createBuffer); if (!dest.ready()) return false; buffers.add(dest); } for (Buffer dest : buffers) dest.add(row); return true; }</code><technical_language>this situation is possible</technical_language>

Target:
@Override public boolean push(T row) { List<UUID> nodes = destination.targets(row); assert !F.isEmpty(nodes); List<Buffer> buffers = new ArrayList<>(nodes.size()); for (UUID node : nodes) { Buffer dest = getOrCreateBuffer(node); if (!dest.ready()) return false; buffers.add(dest); } for (Buffer dest : buffers) dest.add(row); return true; }
Source:
<code>public GroupDescription.Basic parse(String id) throws UnprocessableEntityException { GroupDescription.Basic group = parseId(id); if (group == null) { throw new UnprocessableEntityException(String.format( "Group Not Found: %s", id)); } <START> if (group.getClass().getEnclosingClass().equals(LdapGroupBackend.class)) { if (!groupControlFactory.controlFor(group).isVisible(groupBackend)) { throw new UnprocessableEntityException(String.format( "Group Not Found: %s", id)); } } else { if (!groupControlFactory.controlFor(group).isVisible()) { throw new UnprocessableEntityException(String.format( "Group Not Found: %s", id)); } } <END> return group; }</code><technical_language>LDAP-specific code of LdapGroupBackend</technical_language>

Target:
public GroupDescription.Basic parse(String id) throws UnprocessableEntityException { GroupDescription.Basic group = parseId(id); if (group == null || !groupControlFactory.controlFor(group).isVisible()) { throw new UnprocessableEntityException(String.format( "Group Not Found: %s", id)); } return group; }
Source:
<code>public void onChangedRepoConfigWatchList(ConfigReposConfig newConfigRepos) { boolean removed = false; for (String fingerprint : cachedGoPartials.getFingerprintToLatestKnownConfigMap().keySet()) { if (!newConfigRepos.hasMaterialWithFingerprint(fingerprint)) { removed = true; cachedGoPartials.removeKnown(fingerprint); } } for (String fingerprint : cachedGoPartials.getFingerprintToLatestValidConfigMap().keySet()) { if (!newConfigRepos.hasMaterialWithFingerprint(fingerprint)) { removed = true; cachedGoPartials.removeValid(fingerprint); } } if (removed) { <START> updateConfig(null, null, null); <END> } }</code><technical_language>Umm, this a dangerous. thought this this is handled properly? have. :) But, checking. surprised if this result in a NullPointerException deep in GoFileConfigDataSource something</technical_language>

Target:
public void onChangedRepoConfigWatchList(ConfigReposConfig newConfigRepos) { Set<String> known = cachedGoPartials.getFingerprintToLatestKnownConfigMap().keySet(); for (String fingerprint : known) { if (!newConfigRepos.hasMaterialWithFingerprint(fingerprint)) { cachedGoPartials.removeKnown(fingerprint); } } Set<String> valid = cachedGoPartials.getFingerprintToLatestValidConfigMap().keySet(); for (String fingerprint : valid) { if (!newConfigRepos.hasMaterialWithFingerprint(fingerprint)) { cachedGoPartials.removeValid(fingerprint); } } }
Source:
<code>public void testUmiUtil(List<String> observed, List<String> expected) { <START> <END> for( int i = 0;i < observed.size();i++ ) { SAMRecord rec = new SAMRecord(new SAMFileHeader()); rec.setAttribute("RX", observed.get(i)); Assert.assertEquals(UmiUtil.sanitizeUMI(rec, "RX"), expected.get(i)); } }</code><technical_language>remove whitespace</technical_language>

Target:
public void testUmiUtil(List<String> observed, List<String> expected) { for( int i = 0;i < observed.size();i++ ) { SAMRecord rec = new SAMRecord(new SAMFileHeader()); rec.setAttribute("RX", observed.get(i)); Assert.assertEquals(UmiUtil.getSanitizedUMI(rec, "RX"), expected.get(i)); } }
Source:
<code>public List<FeatureTypeStyle> transformInternal(MBStyle styleContext) { ContrastEnhancement ce = sf.contrastEnhancement(ff.literal(1.0), ContrastMethod.NONE); <START> if(getBrightnessMax() != null || getBrightnessMin() != null){ <END> ce.setMethod(ContrastMethod.NORMALIZE); ce.addOption("algorithm", ff.literal("StretchToMinimumMaximum")); Double newMin = (Double)getBrightnessMin() * 255; Double newMax = (Double)getBrightnessMax() * 255; ce.addOption("minValue", ff.literal(String.valueOf(newMin.intValue()))); ce.addOption("maxValue", ff.literal(String.valueOf(newMax.intValue()))); } RasterSymbolizer symbolizer = sf.rasterSymbolizer(getId(), null, sf.description(Text.text("raster"), null), NonSI.PIXEL, opacity(), null, null, null, ce, null, null); List<Rule> rules = new ArrayList<>(); MBFilter filter = getFilter(); org.geotools.styling.Rule rule = sf.rule(getId(), null, null, 0.0, Double.MAX_VALUE, Arrays.asList(symbolizer), filter.filter()); rules.add(rule); rule.setLegendGraphic(new Graphic[0]); return Collections.singletonList(sf.featureTypeStyle(getId(), sf.description(Text.text("MBStyle " + getId()), Text.text("Generated for " + getSourceLayer())), null, Collections.emptySet(), filter.semanticTypeIdentifiers(), rules)); }</code><technical_language>Is this test for of null? I assume prevent multiplying null in 231/232. If so, wanted &&. suggest brackets clearer. some more spaces consistent other code too</technical_language>

Target:
public List<FeatureTypeStyle> transformInternal(MBStyle styleContext) { ContrastEnhancement ce = sf.contrastEnhancement(ff.literal(1.0), ContrastMethod.NONE); if (getContrast() != null) { ce.setMethod(ContrastMethod.NORMALIZE); ce.addOption("algorithm", ff.literal("StretchToMinimumMaximum")); Double newMin = (Double)getBrightnessMin() * 255; Double newMax = (Double)getBrightnessMax() * 255; ce.addOption("minValue", ff.literal(String.valueOf(newMin.intValue()))); ce.addOption("maxValue", ff.literal(String.valueOf(newMax.intValue()))); } RasterSymbolizer symbolizer = sf.rasterSymbolizer(getId(), null, sf.description(Text.text("raster"), null), NonSI.PIXEL, opacity(), null, null, null, ce, null, null); List<Rule> rules = new ArrayList<>(); MBFilter filter = getFilter(); org.geotools.styling.Rule rule = sf.rule(getId(), null, null, 0.0, Double.MAX_VALUE, Arrays.asList(symbolizer), filter.filter()); rules.add(rule); rule.setLegendGraphic(new Graphic[0]); return Collections.singletonList(sf.featureTypeStyle(getId(), sf.description(Text.text("MBStyle " + getId()), Text.text("Generated for " + getSourceLayer())), null, Collections.emptySet(), filter.semanticTypeIdentifiers(), rules)); }
Source:
<code>private void createTable(boolean drop) { try (Statement stmt = connection.createStatement()) { if (drop) { String dropSql = table.getDropSql(); if (logger.isLogEnabled()) { logger.log(dropSql); } stmt.execute(dropSql); } String createSql = table.getCreateSql(); if (logger.isLogEnabled()) { logger.log(createSql); } stmt.execute(createSql); for (String sql : table.getPostCreateSqls(null)) { if (logger.isLogEnabled()) { logger.log(sql); } stmt.execute(sql); } } catch (SQLException e) { if (table.getDialect().isConcurrentUpdateException(e)) { <START> log.debug(e.getMessage(), e); <END> log.warn(e.toString()); throw new ConcurrentUpdateException(e); } throw new DirectoryException(String.format("Table '%s' creation failed: %s", table, e.getMessage()), e); } }</code><technical_language>do this, in pure terms of performance extra useless method call in debug mode. I do this change</technical_language>

Target:
private void createTable(boolean drop) { try (Statement stmt = connection.createStatement()) { if (drop) { String dropSql = table.getDropSql(); if (logger.isLogEnabled()) { logger.log(dropSql); } stmt.execute(dropSql); } String createSql = table.getCreateSql(); if (logger.isLogEnabled()) { logger.log(createSql); } stmt.execute(createSql); for (String sql : table.getPostCreateSqls(null)) { if (logger.isLogEnabled()) { logger.log(sql); } stmt.execute(sql); } } catch (SQLException e) { if (table.getDialect().isConcurrentUpdateException(e)) { log.debug(e, e); log.warn(e.toString()); throw new ConcurrentUpdateException(e); } throw new DirectoryException(String.format("Table '%s' creation failed: %s", table, e.getMessage()), e); } }
Source:
<code><START> public BootstrapperImpl( <END> PlaceManager placeManager) { this.placeManager = placeManager; }</code><technical_language>rm public</technical_language>

Target:
BootstrapperImpl( PlaceManager placeManager) { this.placeManager = placeManager; }
Source:
<code>public Response clusterShutdown() { store.state().desiredInstances(0); <START> return Response.ok().build(); <END> }</code><technical_language>response entity is missing</technical_language>

Target:
public Response clusterShutdown() { store.state().desiredInstances(0); return Response.ok(new GenericAPIResponse() {}).build(); }
Source:
<code>private void setQcowCompatForQcowImage() { Image image = imageDao.get(getDiskImage().getImageId()); if (getDiskImage().getDiskStorageType() == DiskStorageType.IMAGE && <START> getDiskImage().getVolumeFormat().equals(VolumeFormat.COW)) <END> { image.setQcowCompat(getDiskImage().getQcowCompat()); imageDao.update(image); } }</code><technical_language>equals for VolumeFormat '==' for DiskStorageType</technical_language>

Target:
private void setQcowCompatForQcowImage() { Image image = imageDao.get(getDiskImage().getImageId()); if (getDiskImage().getDiskStorageType() == DiskStorageType.IMAGE && getDiskImage().getVolumeFormat() == VolumeFormat.COW) { image.setQcowCompat(getDiskImage().getQcowCompat()); imageDao.update(image); } }
Source:
<code>protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Integer userId = SecurityContextUtils.getUserId(); if (userId != null) { MDC.put("userId", userId.toString()); } try { filterChain.doFilter(request, response); } finally { <START> MDC.remove("userId"); <END> } }</code><technical_language>extract "userId" a constant</technical_language>

Target:
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Integer userId = SecurityContextUtils.getUserId(); if (userId != null) { MDC.put(USER_ID, userId.toString()); } try { filterChain.doFilter(request, response); } finally { MDC.remove(USER_ID); } }
Source:
<code>public Object unserialize(byte[] bytes) { if (bytes == null) { return null; } ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = null; try { ois = new ObjectInputStream(bais); return ois.readObject(); } finally { if (ois != null) { ois.close(); } } } catch (Exception e) { throw new CacheException(e); <START> } <END> }</code><technical_language>above. exception thrown close() ignored</technical_language>

Target:
public Object unserialize(byte[] bytes) { if (bytes == null) { return null; } ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { bais = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { throw new CacheException(e); } finally { if (ois != null) { try { ois.close(); } catch (IOException e) { } } } }
Source:
<code>public void testEncryptThreads() throws Exception { List<Thread> l = new LinkedList<Thread>(); final String plain = "Test123!32@"; <START> final boolean failed[] = new boolean[] { false }; <END> for (int i=0;i<100;i++) { l.add ( new Thread( new Runnable() { @Override public void run() { try { String encrypted = EncryptionUtils.encrypt(plain, keyStoreURL, keyStorePass, certAlias); String plain2 = EncryptionUtils.decrypt(encrypted, keyStoreURL, keyStorePass, certAlias); if (!plain.equals(plain2)) { failed[0] = true; System.out.println("BAD"); System.out.println("plain2: " + plain2); } } catch (Exception e) { throw new RuntimeException(e); } } } ) ); } for (Thread t : l) { t.start(); } for (Thread t : l) { t.join(); } assertFalse(failed[0]); }</code><technical_language>This is dangerous in a multithreaded environment, "new AtomicBoolean(false)"</technical_language>

Target:
public void testEncryptThreads() throws Exception { List<Thread> l = new LinkedList<Thread>(); final String plain = "Test123!32@"; final AtomicBoolean failed = new AtomicBoolean(); for (int i=0;i<100;i++) { l.add ( new Thread( new Runnable() { @Override public void run() { try { String encrypted = EncryptionUtils.encrypt(plain, keyStoreURL, keyStorePass, certAlias); String plain2 = EncryptionUtils.decrypt(encrypted, keyStoreURL, keyStorePass, certAlias); if (!plain.equals(plain2)) { failed.set(true); System.out.println("BAD"); System.out.println("plain2: " + plain2); } } catch (Exception e) { throw new RuntimeException(e); } } } ) ); } for (Thread t : l) { t.start(); } for (Thread t : l) { t.join(); } assertFalse(failed.get()); }
Source:
<code>private IFrameDMContext createFrameContext(IExecutionDMContext execCtx, String frameNum) { assert execCtx != null && frameNum != null; if (execCtx == null || frameNum == null) { return null; } int intFrameNum = 0; try { intFrameNum = Integer.parseInt(frameNum); } catch (NumberFormatException e){ GdbPlugin.log(e); } <START> return fStackService.createFrameDMContext(execCtx, intFrameNum); <END> }</code><technical_language>added a check for null, in case some extender replaced MIStack service implement IGDBStack</technical_language>

Target:
private IFrameDMContext createFrameContext(IExecutionDMContext execCtx, String frameNum) { assert execCtx != null && frameNum != null; if (execCtx == null || frameNum == null) { return null; } int intFrameNum = 0; try { intFrameNum = Integer.parseInt(frameNum); } catch (NumberFormatException e){ GdbPlugin.log(e); } if (fStackService != null) { return fStackService.createFrameDMContext(execCtx, intFrameNum); } return null; }
Source:
<code>public ThingStatusInfo getLocalizedThingStatusInfo(Thing thing, Locale locale) { if (thing == null) { throw new IllegalArgumentException("Thing must not be null."); } if (thing.getHandler() == null) { return thing.getStatusInfo(); } String description = thing.getStatusInfo().getDescription(); if (!I18nUtil.isConstant(description)) { return thing.getStatusInfo(); } <START> Bundle bundle = FrameworkUtil.getBundle(thing.getHandler().getClass()); <END> Description desc = new Description(bundle, locale, description, i18nProvider); String translatedDescription = i18nProvider.getText(bundle, desc.key, description, locale, desc.args); return new ThingStatusInfo(thing.getStatus(), thing.getStatusInfo().getStatusDetail(), translatedDescription); }</code><technical_language>check handler is null above. I prefer a local variable for handler run trouble if handler is unset asynchronous</technical_language>

Target:
public ThingStatusInfo getLocalizedThingStatusInfo(Thing thing, Locale locale) { if (thing == null) { throw new IllegalArgumentException("Thing must not be null."); } ThingHandler thingHandler = thing.getHandler(); if (thingHandler == null) { return thing.getStatusInfo(); } String description = thing.getStatusInfo().getDescription(); if (!I18nUtil.isConstant(description)) { return thing.getStatusInfo(); } Bundle bundle = FrameworkUtil.getBundle(thingHandler.getClass()); Description desc = new Description(bundle, locale, description, i18nProvider); String translatedDescription = i18nProvider.getText(bundle, desc.key, description, locale, desc.args); return new ThingStatusInfo(thing.getStatus(), thing.getStatusInfo().getStatusDetail(), translatedDescription); }
Source:
<code>private void initRefreshListeners(Widget widget) { if (widget.getData(HAS_REFRESH_LISTENERS) != null) { return; } widget.setData(HAS_REFRESH_LISTENERS, true); final Listener focusInListener = new Listener() { @Override public void handleEvent(Event event) { event.widget.setData(NEEDS_TO_BE_REDRAW, true); } }; widget.addListener(SWT.FocusIn, focusInListener); final Listener selectionChangedListener = new Listener() { @Override public void handleEvent(Event event) { if (event.widget.getData(NEEDS_TO_BE_REDRAW) != null) { event.widget.setData(NEEDS_TO_BE_REDRAW, null); if (event.widget instanceof Control) { ((Control) event.widget).redraw(); } } } }; widget.addListener(SWT.Selection, selectionChangedListener); <START> widget.addDisposeListener(new DisposeListener() { <END> @Override public void widgetDisposed(DisposeEvent e) { e.widget.removeListener(SWT.FocusIn, focusInListener); e.widget.removeListener(SWT.Selection, selectionChangedListener); } }); }</code><technical_language>This dispose listener necessary removing listeners widget disposed</technical_language>

Target:
private void initRefreshListeners(Widget widget) { if (widget.getData(HAS_REFRESH_LISTENERS) != null) { return; } widget.setData(HAS_REFRESH_LISTENERS, true); Listener focusInListener = new Listener() { @Override public void handleEvent(Event event) { event.widget.setData(NEEDS_REDRAW, true); } }; widget.addListener(SWT.FocusIn, focusInListener); Listener selectionChangedListener = new Listener() { @Override public void handleEvent(Event event) { if (event.widget.getData(NEEDS_REDRAW) != null) { event.widget.setData(NEEDS_REDRAW, null); if (event.widget instanceof Control) { ((Control) event.widget).redraw(); } } } }; widget.addListener(SWT.Selection, selectionChangedListener); }