auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testDeadlock() { final ISchedulingRule rule = new TestRule(); final boolean[] blocked = new boolean[] {false}; final boolean[] lockAcquired = new boolean[] {false}; final SubMonitor beginRuleMonitor = SubMonitor.convert(null); Thread locking = new Thread("SyncExecWhileUIThreadWaitsForRuleTest") { @Override public void run() { try { Job.getJobManager().beginRule(rule, null); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { blocked[0] = true; try { Job.getJobManager().beginRule(rule, beginRuleMonitor); } finally { Job.getJobManager().endRule(rule); } blocked[0] = false; } }); while (!blocked[0]) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } Display.getDefault().syncExec(new Runnable() { @Override public void run() { Job.getJobManager().beginRule(rule, null); lockAcquired[0] = true; Job.getJobManager().endRule(rule); } }); } finally { Job.getJobManager().endRule(rule); } } }; locking.start(); final long waitStart = System.currentTimeMillis(); Thread canceler = new Thread("Canceler") { @Override public void run() { while (true) { if (System.currentTimeMillis() - waitStart > 60000) { beginRuleMonitor.setCanceled(true); break; } } } }; canceler.start(); Display display = Display.getDefault(); while (!lockAcquired[0]) { try { if (!display.readAndDispatch()) { display.sleep(); } } catch (SWTException e) { fail("Deadlock occurred"); } } assertFalse("deadlock occurred", beginRuleMonitor.isCanceled()); boolean interrupted = Thread.interrupted(); if (interrupted) { } }

Target:
public void testDeadlock() { final ISchedulingRule rule = new TestRule(); final boolean[] blocked = new boolean[] {false}; final boolean[] lockAcquired = new boolean[] {false}; final SubMonitor beginRuleMonitor = SubMonitor.convert(null); Thread locking = new Thread("SyncExecWhileUIThreadWaitsForRuleTest") { @Override public void run() { try { Job.getJobManager().beginRule(rule, null); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { blocked[0] = true; try { Job.getJobManager().beginRule(rule, beginRuleMonitor); } finally { Job.getJobManager().endRule(rule); } blocked[0] = false; } }); while (!blocked[0]) { try { Thread.sleep(100); } catch (InterruptedException e) { } } Display.getDefault().syncExec(new Runnable() { @Override public void run() { Job.getJobManager().beginRule(rule, null); lockAcquired[0] = true; Job.getJobManager().endRule(rule); } }); } finally { Job.getJobManager().endRule(rule); } } }; locking.start(); final long waitStart = System.currentTimeMillis(); Thread canceler = new Thread("Canceler") { @Override public void run() { while (true) { if (System.currentTimeMillis() - waitStart > 60000) { beginRuleMonitor.setCanceled(true); break; } } } }; canceler.start(); Display display = Display.getDefault(); while (!lockAcquired[0]) { try { if (!display.readAndDispatch()) { display.sleep(); } } catch (SWTException e) { fail("Deadlock occurred"); } } assertFalse("deadlock occurred", beginRuleMonitor.isCanceled()); if (Thread.interrupted()) { } }
Source:
public FunctionSignature[] getFunctionSignatures() { return new FunctionSignature[]{ new BasicFunctionSignature(getType(null), ScalarArgument.GEOMETRY) }; }

Target:
public FunctionSignature[] getFunctionSignatures() { return new FunctionSignature[]{ new BasicFunctionSignature(Type.STRING, ScalarArgument.GEOMETRY) }; }
Source:
public void init() { this.pager = new Pager(); this.videosByUser = session.prepare( "SELECT videoid, title, added FROM examples.random_paging_rest_ui WHERE userid = ?"); }

Target:
public void init() { this.pager = new OffsetPager(ITEMS_PER_PAGE); this.videosByUser = session.prepare( "SELECT videoid, title, added FROM examples.random_paging_rest_ui WHERE userid = ?"); }
Source:
public void testSubmitLocal() { TestQueryOperationHandler operationHandler = new TestQueryOperationHandler(); pool = createPool(operationHandler); QueryOperation operation = new QueryExecuteOperation(); int repeatCount = 10; for (int i = 0; i < repeatCount; i++) { pool.submit(500, QueryOperationExecutable.local(operation)); } assertTrueEventually(() -> { List<ExecuteInfo> infos = operationHandler.tryPollExecuteInfos(repeatCount); assertNotNull(infos); Set<String> threadNames = new HashSet<>(); for (int i = 1; i < infos.size(); i++) { assertSame(operation, infos.get(i).getOperation()); threadNames.add(infos.get(i).getThreadName()); } assertEquals(1, threadNames.size()); }); for (int i = 0; i < repeatCount; i++) { pool.submit(QueryOperation.PARTITION_ANY, QueryOperationExecutable.local(operation)); } assertTrueEventually(() -> { List<ExecuteInfo> infos = operationHandler.tryPollExecuteInfos(repeatCount); assertNotNull(infos); Set<String> threadNames = new HashSet<>(); for (ExecuteInfo info : infos) { assertSame(operation, info.getOperation()); threadNames.add(info.getThreadName()); } assertTrue(threadNames.size() > 0); }); }

Target:
public void testSubmitLocal() { TestQueryOperationHandler operationHandler = new TestQueryOperationHandler(); pool = createPool(operationHandler); List<QueryOperation> operations = new ArrayList<>(); int repeatCount = 10; for (int i = 0; i < repeatCount; i++) { QueryExecuteOperation operation = new QueryExecuteOperation(); operations.add(operation); pool.submit(500, QueryOperationExecutable.local(operation)); } assertTrueEventually(() -> { List<ExecuteInfo> infos = operationHandler.tryPollExecuteInfos(repeatCount); assertNotNull(infos); Set<String> threadNames = new HashSet<>(); for (int i = 1; i < infos.size(); i++) { assertSame(operations.get(i), infos.get(i).getOperation()); threadNames.add(infos.get(i).getThreadName()); } assertEquals(1, threadNames.size()); }); for (int i = 0; i < repeatCount; i++) { pool.submit(QueryOperation.PARTITION_ANY, QueryOperationExecutable.local(operations.get(i))); } assertTrueEventually(() -> { List<ExecuteInfo> infos = operationHandler.tryPollExecuteInfos(repeatCount); assertNotNull(infos); Set<String> threadNames = new HashSet<>(); for (int i = 1; i < infos.size(); i++) { assertTrue(operations.contains(infos.get(i).getOperation())); threadNames.add(infos.get(i).getThreadName()); } assertTrue(threadNames.size() > 0); }); }
Source:
public DataSketchesFunctions() { this.sketchClasses = new ArrayList<SketchDescriptor>(); registerHll(); registerCpc(); registerKll(); registerTheta(); registerTuple(); registerQuantiles(); registerFrequencies(); }

Target:
private DataSketchesFunctions() { this.sketchClasses = new ArrayList<SketchDescriptor>(); this.descriptors = new ArrayList<HiveUDFPlugin.UDFDescriptor>(); registerHll(); registerCpc(); registerKll(); registerTheta(); registerTuple(); registerQuantiles(); registerFrequencies(); buildCalciteFns(); buildDescritors(); }
Source:
public String getLocalizedMessage() { return "stormpath.cookie.insecure.error"; }

Target:
public String getLocalizedMessage() { return I8N_MESSAGE_KEY; }
Source:
public Integer getSkipHeaderRows() { return skipHeaderRows; }

Target:
public int getSkipHeaderRows() { return skipHeaderRows; }
Source:
EncryptionCosmosAsyncContainer(String id, CosmosAsyncDatabase database, Encryptor encryptor) { this.container = BridgeInternal.createCosmosAsyncContainer(id, database); this.encryptor = encryptor; this.encryptionScheduler = Schedulers.elastic(); }

Target:
EncryptionCosmosAsyncContainer(String id, CosmosAsyncDatabase database, Encryptor encryptor) { this.container = BridgeInternal.createCosmosAsyncContainer(id, database); this.encryptor = encryptor; this.encryptionScheduler = Schedulers.boundedElastic(); }
Source:
private void testGetForExistingBlobs(List<BlobId> blobIds, Map<BlobId, ByteBuffer> blobIdToUploadedDataMap) throws Exception { StoreInfo storeInfo = store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); assertTrue( "Number of records returned by get should be " + blobIds.size() + " found " + storeInfo.getMessageReadSetInfo() .size(), storeInfo.getMessageReadSetInfo().size() == blobIds.size()); for (int i = 0; i < storeInfo.getMessageReadSetInfo().size(); i++) { if (blobIdToUploadedDataMap.containsKey(storeInfo.getMessageReadSetInfo().get(i).getStoreKey())) { ByteBuffer uploadedData = blobIdToUploadedDataMap.get(storeInfo.getMessageReadSetInfo().get(i).getStoreKey()); ByteBuffer downloadedData = ByteBuffer.allocate((int) storeInfo.getMessageReadSetInfo().get(i).getSize()); WritableByteChannel writableByteChannel = Channels.newChannel(new ByteBufferOutputStream(downloadedData)); storeInfo.getMessageReadSet().writeTo(i, writableByteChannel, -1, -1); downloadedData.flip(); assertTrue(uploadedData.equals(downloadedData)); break; } } }

Target:
private void testGetForExistingBlobs(List<BlobId> blobIds, Map<BlobId, ByteBuffer> blobIdToUploadedDataMap) throws Exception { StoreInfo storeInfo = store.get(blobIds, EnumSet.noneOf(StoreGetOptions.class)); assertEquals("Number of records returned by get should be same as uploaded", storeInfo.getMessageReadSetInfo().size(), blobIds.size()); for (int i = 0; i < storeInfo.getMessageReadSetInfo().size(); i++) { if (blobIdToUploadedDataMap.containsKey(storeInfo.getMessageReadSetInfo().get(i).getStoreKey())) { ByteBuffer uploadedData = blobIdToUploadedDataMap.get(storeInfo.getMessageReadSetInfo().get(i).getStoreKey()); ByteBuffer downloadedData = ByteBuffer.allocate((int) storeInfo.getMessageReadSetInfo().get(i).getSize()); WritableByteChannel writableByteChannel = Channels.newChannel(new ByteBufferOutputStream(downloadedData)); storeInfo.getMessageReadSet().writeTo(i, writableByteChannel, -1, -1); downloadedData.flip(); assertEquals(uploadedData, downloadedData); break; } } }
Source:
public void listChannels(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = TYPE_KEY, required = false) String type, @RequestParam(value = PLATFORM_ID_KEY, required = false) String platformId, @RequestParam(value = ADVERTISED, required = false) String advertised) throws IOException { try { final ApplicationConfiguration appConfig; try { appConfig = appConfig(request); } catch (ApiKeyNotFoundException | RevokedApiKeyException | InvalidIpForApiKeyException ex) { outputter.writeError(request, response, FORBIDDEN); return; } Optional<Set<Annotation>> annotations = annotationExtractor.extract(request); if (annotations.isPresent() && !validAnnotations(annotations.get())) { errorViewFor(request, response, BAD_ANNOTATION); return; } List<ChannelGroup> channelGroups = ImmutableList.copyOf(channelGroupResolver.channelGroups()); Selection selection = SELECTION_BUILDER.build(request); channelGroups = selection.applyTo(Iterables.filter( filterer.filter(channelGroups, constructFilter(platformId, type, advertised)), new Predicate<ChannelGroup>() { @Override public boolean apply(ChannelGroup input) { return appConfig.isEnabled(input.getPublisher()); } })); if (!Strings.isNullOrEmpty(advertised)) { ImmutableList.Builder filtered = ImmutableList.builder(); for (ChannelGroup channelGroup : channelGroups) { filtered.add(filterByAdvertised(channelGroup)); } channelGroups = filtered.build(); } modelAndViewFor(request, response, channelGroups, appConfig); } catch (Exception e) { errorViewFor(request, response, AtlasErrorSummary.forException(e)); } }

Target:
public void listChannels(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = TYPE_KEY, required = false) String type, @RequestParam(value = PLATFORM_ID_KEY, required = false) String platformId, @RequestParam(value = ADVERTISED, required = false) String advertised) throws IOException { try { final ApplicationConfiguration appConfig; try { appConfig = appConfig(request); } catch (ApiKeyNotFoundException | RevokedApiKeyException | InvalidIpForApiKeyException ex) { errorViewFor(request, response, AtlasErrorSummary.forException(ex)); return; } Optional<Set<Annotation>> annotations = annotationExtractor.extract(request); if (annotations.isPresent() && !validAnnotations(annotations.get())) { errorViewFor(request, response, BAD_ANNOTATION); return; } List<ChannelGroup> channelGroups = ImmutableList.copyOf(channelGroupResolver.channelGroups()); Selection selection = SELECTION_BUILDER.build(request); channelGroups = selection.applyTo(Iterables.filter( filterer.filter(channelGroups, constructFilter(platformId, type, advertised)), new Predicate<ChannelGroup>() { @Override public boolean apply(ChannelGroup input) { return appConfig.isEnabled(input.getPublisher()); } })); if (!Strings.isNullOrEmpty(advertised)) { ImmutableList.Builder filtered = ImmutableList.builder(); for (ChannelGroup channelGroup : channelGroups) { filtered.add(filterByAdvertised(channelGroup)); } channelGroups = filtered.build(); } modelAndViewFor(request, response, channelGroups, appConfig); } catch (Exception e) { errorViewFor(request, response, AtlasErrorSummary.forException(e)); } }
Source:
public void testCascadedValidationMultiThreaded() throws Exception { CountDownLatch startLatch = new CountDownLatch( 1 ); ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool( SIZE_OF_THREAD_POOL ); for ( int i = 0; i <= NUMBER_OF_RUNNABLES; i++ ) { Runnable run = new TestRunner( startLatch ); executor.execute( run ); } executor.shutdown(); startLatch.countDown(); executor.awaitTermination( 600, TimeUnit.SECONDS ); }

Target:
public void testCascadedValidationMultiThreaded() throws Exception { CountDownLatch startLatch = new CountDownLatch( 1 ); ExecutorService executor = Executors.newFixedThreadPool( SIZE_OF_THREAD_POOL ); for ( int i = 0; i <= NUMBER_OF_RUNNABLES; i++ ) { Runnable run = new TestRunner( startLatch ); executor.execute( run ); } executor.shutdown(); startLatch.countDown(); executor.awaitTermination( 600, TimeUnit.SECONDS ); }
Source:
public static org.kframework.definition.Definition from(String definitionText) { Pattern pattern = Pattern.compile("module ([A-Z_]*)"); Matcher m = pattern.matcher(definitionText); if(!m.find()) { throw new RuntimeException("Could not find any module in the definition"); } String nameOfLastModule = m.group(m.groupCount()); return from(definitionText, nameOfLastModule, Source.apply("generated")); }

Target:
public static org.kframework.definition.Definition from(String definitionText) { Pattern pattern = Pattern.compile("(?:^|\\s)module ([A-Z][A-Z\\-]*)"); Matcher m = pattern.matcher(definitionText); if(!m.find()) { throw new RuntimeException("Could not find any module in the definition"); } String nameOfLastModule = m.group(m.groupCount()); return from(definitionText, nameOfLastModule, Source.apply("generated")); }
Source:
public void drawItems(Rectangle bounds, ITimeDataProvider timeProvider, Item[] items, int topIndex, int nameSpace, GC gc) { int bottomIndex = Integer.min(topIndex + countPerPage() + 1, items.length); for (int i = topIndex; i < bottomIndex; i++) { Item item = items[i]; drawItem(item, bounds, timeProvider, i, nameSpace, gc); } TraceCompassLogUtils.traceCounter(LOGGER, Level.FINER, fDrawItemsCountLabel, bottomIndex - topIndex); for (DeferredEntry entry : fPostDrawEntries) { entry.draw(fTimeGraphProvider, gc); } for (DeferredLine line : fLines) { line.draw(gc); } Color prev = gc.getForeground(); Color black = COLOR_REGISTRY.get(BLACK.toString()); if (black == null) { COLOR_REGISTRY.put(BLACK.toString(), RGBAUtil.fromInt(BLACK.toInt()).rgb); black = COLOR_REGISTRY.get(BLACK.toString()); } gc.setForeground(black); int prevAA = gc.getAntialias(); gc.setAntialias(SWT.OFF); int prevLineWidth = gc.getLineWidth(); gc.setLineWidth(1); for (DeferredSegment seg : fPoints) { seg.draw(gc); } gc.setLineWidth(prevLineWidth); gc.setAntialias(prevAA); for (Rectangle rectangle : fSelectedRectangles) { int arc = Math.min(rectangle.height + 1, rectangle.width) / 2; gc.drawRoundRectangle(rectangle.x - 1, rectangle.y - 1, rectangle.width, rectangle.height + 1, arc, arc); } gc.setForeground(prev); }

Target:
public void drawItems(Rectangle bounds, ITimeDataProvider timeProvider, Item[] items, int topIndex, int nameSpace, GC gc) { int bottomIndex = Integer.min(topIndex + countPerPage() + 1, items.length); for (int i = topIndex; i < bottomIndex; i++) { Item item = items[i]; drawItem(item, bounds, timeProvider, i, nameSpace, gc); } TraceCompassLogUtils.traceCounter(LOGGER, Level.FINER, fDrawItemsCountLabel, bottomIndex - topIndex); for (DeferredEntry entry : fPostDrawEntries) { entry.draw(fTimeGraphProvider, gc); } for (DeferredLine line : fLines) { line.draw(gc); } Color prev = gc.getForeground(); Color black = getColor(BLACK.toInt()); gc.setForeground(black); int prevAA = gc.getAntialias(); gc.setAntialias(SWT.OFF); int prevLineWidth = gc.getLineWidth(); gc.setLineWidth(1); for (DeferredSegment seg : fPoints) { seg.draw(gc); } gc.setLineWidth(prevLineWidth); gc.setAntialias(prevAA); for (Rectangle rectangle : fSelectedRectangles) { int arc = Math.min(rectangle.height + 1, rectangle.width) / 2; gc.drawRoundRectangle(rectangle.x - 1, rectangle.y - 1, rectangle.width, rectangle.height + 1, arc, arc); } gc.setForeground(prev); }
Source:
public void eventHandle(ITmfEvent event, DataDrivenScenarioInfo scenarioInfo, IAnalysisDataContainer container) { if (container instanceof XmlPatternStateProvider) { for (Entry<String, String> entry : ((XmlPatternStateProvider) container).getStoredFields().entrySet()) { ((XmlPatternStateProvider) container).getHistoryBuilder().resetStoredFields((XmlPatternStateProvider) container, entry.getValue(), (TmfXmlScenarioInfo) scenarioInfo, event); } } }

Target:
public void eventHandle(ITmfEvent event, DataDrivenScenarioInfo scenarioInfo, IAnalysisDataContainer container) { if (container instanceof XmlPatternStateProvider && scenarioInfo instanceof TmfXmlScenarioInfo) { XmlPatternStateProvider provider = (XmlPatternStateProvider) container; for (Entry<String, String> entry : provider.getStoredFields().entrySet()) { provider.getHistoryBuilder().resetStoredFields(provider, entry.getValue(), (TmfXmlScenarioInfo) scenarioInfo, event); } } }
Source:
private void trimExternal(int offset, int limit) { ResultExternal temp = external; external = null; temp.reset(); while (--offset >= 0) { temp.next(); } while (--limit >= 0) { rows.add(temp.next()); if (rows.size() > maxMemoryRows) { if (external == null) { createExternalResult(); } addRowsToDisk(); } } if (external != null) { addRowsToDisk(); } temp.close(); }

Target:
private void trimExternal(int offset, int limit) { ResultExternal temp = external; external = null; temp.reset(); while (--offset >= 0) { temp.next(); } while (--limit >= 0) { rows.add(temp.next()); if (rows.size() > maxMemoryRows) { addRowsToDisk(); } } if (external != null) { addRowsToDisk(); } temp.close(); }
Source:
protected AgentIdentifier agentIdentifier() { return new AgentIdentifier(SystemUtil.getLocalhostNameOrRandomNameIfNotFound(), SystemUtil.getClientIp(systemEnvironment.getServiceUrl()), agentRegistry.uuid()); }

Target:
protected AgentIdentifier agentIdentifier() { return new AgentIdentifier(hostName, ipAddress, agentRegistry.uuid()); }
Source:
protected boolean canDoAction() { if (!isVmExist() || !acquireLockInternal()) { return false; } Disk diskInfo = getParameters().getDiskInfo(); if (diskInfo.getDiskStorageType() == DiskStorageType.IMAGE) { getDiskImageInfo().setDiskSnapshot(false); } VM vm = getVm(); if (vm != null) { if (!canRunActionOnNonManagedVm()) { return false; } updateDisksFromDb(); if (!isDiskCanBeAddedToVm(getParameters().getDiskInfo(), vm) || !isDiskPassPciAndIdeLimit(getParameters().getDiskInfo())) { return false; } } else if (Boolean.TRUE.equals(getParameters().getPlugDiskToVm())) { return failCanDoAction(VdcBllMessages.CANNOT_ADD_FLOATING_DISK_WITH_PLUG_VM_SET); } DiskValidator diskValidator = getDiskValidator(getParameters().getDiskInfo()); if (!validate(diskValidator.isReadOnlyPropertyCompatibleWithInterface())) { return false; } if (!setAndValidateDiskProfiles()) { return false; } if (DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfImageDiskCanBeAdded(vm, diskValidator); } if (DiskStorageType.LUN == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfLunDiskCanBeAdded(diskValidator); } return true; }

Target:
protected boolean canDoAction() { if (!isVmExist() || !acquireLockInternal()) { return false; } Disk diskInfo = getParameters().getDiskInfo(); if (diskInfo.getDiskStorageType() == DiskStorageType.IMAGE) { getDiskImageInfo().setDiskSnapshot(false); } VM vm = getVm(); if (vm != null) { if (!canRunActionOnNonManagedVm()) { return false; } updateDisksFromDb(); if (!isDiskCanBeAddedToVm(getParameters().getDiskInfo(), vm) || !isDiskPassPciAndIdeLimit(getParameters().getDiskInfo())) { return false; } } else if (Boolean.TRUE.equals(getParameters().getPlugDiskToVm())) { return failCanDoAction(VdcBllMessages.CANNOT_ADD_FLOATING_DISK_WITH_PLUG_VM_SET); } DiskValidator diskValidator = getDiskValidator(getParameters().getDiskInfo()); if (!validate(diskValidator.isReadOnlyPropertyCompatibleWithInterface())) { return false; } if (DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { if (!setAndValidateDiskProfiles()) { return false; } return checkIfImageDiskCanBeAdded(vm, diskValidator); } if (DiskStorageType.LUN == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfLunDiskCanBeAdded(diskValidator); } return true; }
Source:
private boolean milestoneSatisfies(IModel model, TurboIssue issue) { if (!content.isPresent()) return false; Optional<TurboMilestone> milestone = model.getMilestoneOfIssue(issue); if (!milestone.isPresent()) return false; String contents = content.get().toLowerCase(); String title = milestone.get().getTitle().toLowerCase(); List<TurboMilestone> allMilestones = model.getMilestones(); Collections.sort(allMilestones, new TurboMilestoneDueDateComparator()); int currentIndex = -1; for (TurboMilestone checker : allMilestones) { if (checker.isOpen()) { if (checker.getDueDate().isPresent() && checker.getDueDate().get().isBefore(LocalDate.now()) && checker.getOpenIssues() == 0) { continue; } currentIndex = allMilestones.indexOf(checker); break; } } if (currentIndex == -1 && allMilestones.size() > 0) { currentIndex = allMilestones.size() - 1; } String alias = contents; if (alias.equalsIgnoreCase("current") || alias.equalsIgnoreCase("curr")) { contents = allMilestones.get(currentIndex).getTitle(); } else if (alias.equalsIgnoreCase("previous") || alias.equalsIgnoreCase("prev")) { if (currentIndex - 1 >= 0) { contents = allMilestones.get(currentIndex - 1).getTitle(); } } else if (alias.equalsIgnoreCase("next")) { if (currentIndex + 1 < allMilestones.size()) { contents = allMilestones.get(currentIndex + 1).getTitle(); } } else if (alias.startsWith("previous-") || alias.startsWith("prev-")) { int offsetPos = alias.indexOf('-') + 1; int offset = Integer.parseInt(alias.substring(offsetPos).trim()); if (currentIndex - 1 - offset >= 0) { contents = allMilestones.get(currentIndex - 1 - offset).getTitle(); } } else if (alias.startsWith("next+")) { int offsetPos = alias.indexOf('+') + 1; int offset = Integer.parseInt(alias.substring(offsetPos).trim()); if (currentIndex + 1 + offset < allMilestones.size()) { contents = allMilestones.get(currentIndex + 1 + offset).getTitle(); } } contents = contents.toLowerCase(); return title.contains(contents); }

Target:
private boolean milestoneSatisfies(IModel model, TurboIssue issue) { if (!content.isPresent()) return false; Optional<TurboMilestone> milestone = model.getMilestoneOfIssue(issue); if (!milestone.isPresent()) return false; String contents = content.get().toLowerCase(); String title = milestone.get().getTitle().toLowerCase(); return title.contains(contents); }
Source:
public void testFew() { WeightedDoubleReservoirSample reservoir = new WeightedDoubleReservoirSample(200); reservoir.add(1.0, 1.0); reservoir.add(2.0, 1.0); reservoir.add(3.0, 0.5); Set<Double> samples = new HashSet<>(); for (double sample : reservoir.getSamples()) { samples.add(sample); } assertEquals(samples.size(), 3); assertTrue(samples.contains(Double.valueOf(1))); assertTrue(samples.contains(Double.valueOf(2))); assertTrue(samples.contains(Double.valueOf(3))); }

Target:
public void testFew() { WeightedDoubleReservoirSample reservoir = new WeightedDoubleReservoirSample(200); reservoir.add(1.0, 1.0); reservoir.add(2.0, 1.0); reservoir.add(3.0, 0.5); assertEquals(Arrays.stream(reservoir.getSamples()).sorted().toArray(), new double[] {1.0, 2.0, 3.0}); }
Source:
public QuotaBalanceVO() { super(); }

Target:
public QuotaBalanceVO() { }
Source:
public void testImportWithPadding() throws IOException { if(failWithPadding){ thrown.expect(IOException.class); thrown.expectMessage("Failure during job; return status 1"); NumericTypesTestUtils.configureJunitToExpectFailure(thrown); } ArgumentArrayBuilder builder = getArgsBuilder(); NumericTypesTestUtils.addPadding(builder); runImport(builder.build()); if (!failWithPadding) { verify(); } }

Target:
public void testImportWithPadding() throws IOException { if(failWithPadding){ NumericTypesTestUtils.configureJunitToExpectFailure(thrown); } ArgumentArrayBuilder builder = getArgsBuilder(); NumericTypesTestUtils.addPadding(builder); runImport(builder.build()); if (!failWithPadding) { verify(); } }
Source:
public synchronized Text getCurrentProxyDelegationToken() { return delegationTokenService; }

Target:
public Text getCurrentProxyDelegationToken() { return delegationTokenService; }
Source:
public synchronized void onError(Throwable t) { if(lastAsyncOperation != null) { lastAsyncOperation.future.completeExceptionally(t); lastAsyncOperation = null; } }

Target:
public synchronized void onError(Throwable t) { if(lastAsyncOperation != null) { lastAsyncOperation.future.completeExceptionally(t); lastAsyncOperation = null; } while(!asyncQueue.isEmpty()) { AsyncOperation op = asyncQueue.poll(); if(!op.future.isDone()) op.future.completeExceptionally(t); } }
Source:
public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<>(); if (isDiskImage()) { DiskImage oldDiskImage = (DiskImage) getOldDisk(); DiskImage newDiskImage = (DiskImage) getNewDisk(); boolean doesNewDiskHaveQuota = isDiskImageHasQuota(newDiskImage); boolean doesOldDiskHadQuota = isDiskImageHasQuota(oldDiskImage); boolean isQuotaChanged = !oldDiskImage.getQuotaId().equals(newDiskImage.getQuotaId()); long diskExtendingDiff = newDiskImage.getSizeInGigabytes() - oldDiskImage.getSizeInGigabytes(); if (doesNewDiskHaveQuota) { if (isQuotaChanged) { list.add(generateQuotaRequestParameters(newDiskImage, QuotaConsumptionParameter.QuotaAction.CONSUME, newDiskImage.getSizeInGigabytes())); } else if (diskExtendingDiff > 0L) { list.add(generateQuotaRequestParameters(newDiskImage, QuotaConsumptionParameter.QuotaAction.CONSUME, diskExtendingDiff)); } } if (doesOldDiskHadQuota && isQuotaChanged) { list.add(generateQuotaRequestParameters(oldDiskImage, QuotaConsumptionParameter.QuotaAction.RELEASE, oldDiskImage.getSizeInGigabytes())); } } return list; }

Target:
public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<>(); if (isDiskImage()) { DiskImage oldDiskImage = (DiskImage) getOldDisk(); DiskImage newDiskImage = (DiskImage) getNewDisk(); boolean doesOldDiskHadQuota = isDiskImageHasQuota(oldDiskImage); boolean isQuotaChanged = !Objects.equals(oldDiskImage.getQuotaId(), newDiskImage.getQuotaId()); long diskExtendingDiff = 0L; if (oldDiskImage != null) { diskExtendingDiff = newDiskImage.getSizeInGigabytes() - oldDiskImage.getSizeInGigabytes(); } if (isQuotaChanged) { list.add(generateQuotaRequestParameters(newDiskImage, QuotaConsumptionParameter.QuotaAction.CONSUME, newDiskImage.getSizeInGigabytes())); } else if (diskExtendingDiff > 0L) { list.add(generateQuotaRequestParameters(newDiskImage, QuotaConsumptionParameter.QuotaAction.CONSUME, diskExtendingDiff)); } if (doesOldDiskHadQuota && isQuotaChanged) { list.add(generateQuotaRequestParameters(oldDiskImage, QuotaConsumptionParameter.QuotaAction.RELEASE, oldDiskImage.getSizeInGigabytes())); } } return list; }
Source:
public void bindingChanged(BindingProvider prov, String itemName) { if (prov.getItemNames().contains(itemName)) { try { createItem(itemName, prov); } catch (Ipx800UnknownDeviceException e) { logger.error("Item " + itemName + " will be ignored"); e.printStackTrace(); } } else { logger.debug("Removing item {}", itemName); for (String deviceName : devices.keySet()) { for (Ipx800Port slot : devices.get(deviceName).getAllPorts()) { slot.destroyItem(itemName); } } } }

Target:
public void bindingChanged(BindingProvider prov, String itemName) { if (prov.getItemNames().contains(itemName)) { try { createInternalItem(itemName, prov); } catch (Ipx800UnknownDeviceException e) { logger.error("Item will be ignored", itemName); } } else { logger.debug("Removing item {}", itemName); for (String deviceName : devices.keySet()) { for (Ipx800Port slot : devices.get(deviceName).getAllPorts()) { slot.destroyItem(itemName); } } } }
Source:
@OnClick(R.id.reading_list_detail_back_button) protected void onBackPressed(View v) { if (actionListener != null) { actionListener.onBackPressed(); } }

Target:
@OnClick(R.id.reading_list_detail_back_button) void onBackPressed(View v) { if (actionListener != null) { actionListener.onBackPressed(); } }
Source:
public void testNotifyChanged() { Iterator<CommentAnnotation> iter = model.getAnnotationIterator(); assertEquals(1, getCount(iter)); IComment clone = generateComment(DEFAULT_TEXT, new Timestamp(DEFAULT_TIMESTAMP)); Notification notification = new NotificationImpl(Notification.ADD, null, clone); model.getItem().eNotify(notification); iter = model.getAnnotationIterator(); assertEquals(1, getCount(iter)); IComment newComment = generateComment("Actually, maybe it needs more work.", new Date()); notification = new NotificationImpl(Notification.ADD, null, newComment); model.getItem().eNotify(notification); iter = model.getAnnotationIterator(); assertEquals(2, getCount(iter)); notification = new NotificationImpl(Notification.REMOVE, newComment, null); model.getItem().eNotify(notification); iter = model.getAnnotationIterator(); assertEquals(2, getCount(iter)); }

Target:
public void testNotifyChanged() { Iterator<CommentAnnotation> iter = model.getAnnotationIterator(); assertEquals(1, getCount(iter)); IComment clone = generateComment(DEFAULT_TEXT, new Timestamp(DEFAULT_TIMESTAMP)); Notification notification = new NotificationImpl(Notification.ADD, null, clone); model.getItem().eNotify(notification); iter = model.getAnnotationIterator(); assertEquals(1, getCount(iter)); IComment newComment = generateComment("Actually, maybe it needs more work.", new Date()); notification = new NotificationImpl(Notification.ADD, null, newComment); model.getItem().eNotify(notification); iter = model.getAnnotationIterator(); assertEquals(2, getCount(iter)); notification = new NotificationImpl(Notification.REMOVE, newComment, null); model.getItem().eNotify(notification); iter = model.getAnnotationIterator(); assertEquals(1, getCount(iter)); }
Source:
public String getSingular() { if(singular == null) { final Singular fromAnnotation = getClass().getAnnotation(Singular.class); this.singular = (fromAnnotation != null ? fromAnnotation.value().toLowerCase(Locale.ROOT) : getKind()).toLowerCase(Locale.ROOT); } return singular; }

Target:
public String getSingular() { return singular; }
Source:
public static Configuration getHadoopConfiguration(String hadoopConfDir) { Configuration hadoopConfiguration = new Configuration(); if (new File(hadoopConfDir).exists()) { if (new File(hadoopConfDir + "/core-site.xml").exists()) { hadoopConfiguration.addResource(new Path(hadoopConfDir + "/core-site.xml")); } if (new File(hadoopConfDir + "/hdfs-default.xml").exists()) { hadoopConfiguration.addResource(new Path(hadoopConfDir + "/hdfs-default.xml")); } if (new File(hadoopConfDir + "/hdfs-site.xml").exists()) { hadoopConfiguration.addResource(new Path(hadoopConfDir + "/hdfs-site.xml")); } if (new File(hadoopConfDir + "/mapred-site.xml").exists()) { hadoopConfiguration.addResource(new Path(hadoopConfDir + "/mapred-site.xml")); } } return hadoopConfiguration; }

Target:
public static Configuration getHadoopConfiguration(String hadoopConfDir) { if (new File(hadoopConfDir).exists()) { Configuration hadoopConfiguration = new Configuration(); File coreSite = new File(hadoopConfDir, "core-site.xml"); if (coreSite.exists()) { hadoopConfiguration.addResource(new Path(coreSite.getAbsolutePath())); } File hdfsSite = new File(hadoopConfDir, "hdfs-site.xml"); if (hdfsSite.exists()) { hadoopConfiguration.addResource(new Path(hdfsSite.getAbsolutePath())); } File yarnSite = new File(hadoopConfDir, "yarn-site.xml"); if (yarnSite.exists()) { hadoopConfiguration.addResource(new Path(yarnSite.getAbsolutePath())); } File mapredSite = new File(hadoopConfDir, "mapred-site.xml"); if (mapredSite.exists()) { hadoopConfiguration.addResource(new Path(mapredSite.getAbsolutePath())); } return hadoopConfiguration; } return null; }
Source:
public void declareVariable(Class type, String name) { if (locals == Collections.EMPTY_MAP) { this.locals = new HashMap<String, Object>(1); } locals.put(name, null); if (types == null || types == Collections.EMPTY_MAP) { types = new HashMap<String, Class>(1); } types.put(name, type); }

Target:
public void declareVariable(Class type, String name) { if (locals == Collections.EMPTY_MAP) { this.locals = new HashMap<String, Object>(2); } locals.put(name, null); if (types == null || types == Collections.EMPTY_MAP) { types = new HashMap<String, Class>(2); } types.put(name, type); }
Source:
private DomainTranslator.ExtractionResult intersectExtractionResult(DomainTranslator.ExtractionResult left, DomainTranslator.ExtractionResult right) { RowExpression newRemainingExpression; if (right.getRemainingExpression().equals(TRUE_CONSTANT)) { newRemainingExpression = left.getRemainingExpression(); } else if (left.getRemainingExpression().equals(TRUE_CONSTANT)) { newRemainingExpression = right.getRemainingExpression(); } else { newRemainingExpression = and(left.getRemainingExpression(), right.getRemainingExpression()); } return new DomainTranslator.ExtractionResult(left.getTupleDomain().intersect(right.getTupleDomain()), newRemainingExpression); }

Target:
private static DomainTranslator.ExtractionResult intersectExtractionResult(DomainTranslator.ExtractionResult left, DomainTranslator.ExtractionResult right) { RowExpression newRemainingExpression; if (right.getRemainingExpression().equals(TRUE_CONSTANT)) { newRemainingExpression = left.getRemainingExpression(); } else if (left.getRemainingExpression().equals(TRUE_CONSTANT)) { newRemainingExpression = right.getRemainingExpression(); } else { newRemainingExpression = and(left.getRemainingExpression(), right.getRemainingExpression()); } return new DomainTranslator.ExtractionResult(left.getTupleDomain().intersect(right.getTupleDomain()), newRemainingExpression); }
Source:
public CheckedBiFunction<Object, Throwable, Duration> getDelayFunction() { return delayFunction; }

Target:
public DelayFunction<?, ? extends Throwable> getDelayFunction() { return delayFunction; }
Source:
public void validate() { Attribute<Long> reaperWakeUpInterval = attributes.attribute(REAPER_WAKE_UP_INTERVAL); Attribute<Long> completedTxTimeout = attributes.attribute(COMPLETED_TX_TIMEOUT); if (reaperWakeUpInterval.get()< 0) throw log.invalidReaperWakeUpInterval(reaperWakeUpInterval.get()); if (completedTxTimeout.get() < 0) throw log.invalidCompletedTxTimeout(completedTxTimeout.get()); CacheMode cacheMode = clustering().cacheMode(); if(attributes.attribute(TRANSACTION_PROTOCOL).get() == TransactionProtocol.TOTAL_ORDER) { if(transactionMode() != TransactionMode.TRANSACTIONAL) { throw log.invalidTxModeForTotalOrder(transactionMode()); } if(!cacheMode.isReplicated() && !cacheMode.isDistributed()) { throw log.invalidCacheModeForTotalOrder(clustering().cacheMode().friendlyCacheModeString()); } if (lockingMode() != LockingMode.OPTIMISTIC) { throw log.invalidLockingModeForTotalOrder(lockingMode()); } } if (!attributes.attribute(NOTIFICATIONS).get() && !getBuilder().template()) { log.transactionNotificationsDisabled(); } if (attributes.attribute(TRANSACTION_MODE).get() == TransactionMode.TRANSACTIONAL && !cacheMode.isSynchronous()) { throw log.unsupportedAsyncCacheMode(cacheMode); } if (attributes.attribute(TRANSACTION_MODE).get() == TransactionMode.TRANSACTIONAL && attributes.attribute(LOCKING_MODE).get() == LockingMode.OPTIMISTIC && !attributes.attribute(USE_EAGER_LOCKING).get() && getBuilder().locking().isolationLevel() == IsolationLevel.REPEATABLE_READ && cacheMode != CacheMode.INVALIDATION_SYNC && !getBuilder().invocationBatching().isEnabled()) { getBuilder().locking().writeSkewCheck(true); getBuilder().versioning().enable().scheme(VersioningScheme.SIMPLE); getBuilder().locking().validate(); getBuilder().versioning().validate(); } recovery.validate(); }

Target:
public void validate() { Attribute<Long> reaperWakeUpInterval = attributes.attribute(REAPER_WAKE_UP_INTERVAL); Attribute<Long> completedTxTimeout = attributes.attribute(COMPLETED_TX_TIMEOUT); if (reaperWakeUpInterval.get()< 0) throw log.invalidReaperWakeUpInterval(reaperWakeUpInterval.get()); if (completedTxTimeout.get() < 0) throw log.invalidCompletedTxTimeout(completedTxTimeout.get()); CacheMode cacheMode = clustering().cacheMode(); if(attributes.attribute(TRANSACTION_PROTOCOL).get() == TransactionProtocol.TOTAL_ORDER) { if(transactionMode() != TransactionMode.TRANSACTIONAL) { throw log.invalidTxModeForTotalOrder(transactionMode()); } if(!cacheMode.isReplicated() && !cacheMode.isDistributed()) { throw log.invalidCacheModeForTotalOrder(clustering().cacheMode().friendlyCacheModeString()); } if (lockingMode() != LockingMode.OPTIMISTIC) { throw log.invalidLockingModeForTotalOrder(lockingMode()); } } if (!attributes.attribute(NOTIFICATIONS).get() && !getBuilder().template()) { log.transactionNotificationsDisabled(); } if (attributes.attribute(TRANSACTION_MODE).get() == TransactionMode.TRANSACTIONAL && !cacheMode.isSynchronous()) { throw log.unsupportedAsyncCacheMode(cacheMode); } recovery.validate(); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Lifecycle {\n"); sb.append(" postStart: ").append(toIndentedString(postStart)).append("\n"); sb.append(" preStop: ").append(toIndentedString(preStop)).append("\n"); sb.append("}"); return sb.toString(); }

Target:
public String toString() { return "Lifecycle{" + "postStart=" + postStart + ", preStop=" + preStop + '}'; }
Source:
public void setAcceptableValues(Collection<Object> values) { if (values == null) { return; } editors.clear(); contentPanel.clear(); for (Object value : values) { LogicalNetworkEditor networkEditor = new LogicalNetworkEditor(elementId); editors.add(networkEditor); networkEditor.setValue((NicWithLogicalNetworks) value); contentPanel.add(networkEditor); } headerLabel.setText(messages.assignNicsToNetworks(values.size())); }

Target:
public void setAcceptableValues(Collection<Object> values) { if (values == null) { return; } editors.clear(); contentPanel.clear(); for (Object value : values) { LogicalNetworkEditor networkEditor = new LogicalNetworkEditor(); networkEditor.setElementId(elementId); editors.add(networkEditor); networkEditor.setValue((NicWithLogicalNetworks) value); contentPanel.add(networkEditor); } if (values.size() > 0) { headerLabel.setText(messages.assignNicsToNetworks(values.size())); } }
Source:
protected void initializeAndStart() { SinkConnectorConfig.validate(taskConfig); if (SinkConnectorConfig.hasTopicsConfig(taskConfig)) { String[] topics = taskConfig.get(SinkTask.TOPICS_CONFIG).split(","); Arrays.parallelSetAll(topics, i->topics[i].trim()); consumer.subscribe(Arrays.asList(topics), new HandleRebalance()); log.debug("{} Initializing and starting task for topics {}", this, topics); } else { String topicsRegexStr = taskConfig.get(SinkTask.TOPICS_REGEX_CONFIG); Pattern pattern = Pattern.compile(topicsRegexStr); consumer.subscribe(pattern, new HandleRebalance()); log.debug("{} Initializing and starting task for topics regex {}", this, topicsRegexStr); } task.initialize(context); task.start(taskConfig); log.info("{} Sink task finished initialization and start", this); }

Target:
protected void initializeAndStart() { SinkConnectorConfig.validate(taskConfig); if (SinkConnectorConfig.hasTopicsConfig(taskConfig)) { String[] topics = taskConfig.get(SinkTask.TOPICS_CONFIG).split(","); Arrays.setAll(topics, i -> topics[i].trim()); consumer.subscribe(Arrays.asList(topics), new HandleRebalance()); log.debug("{} Initializing and starting task for topics {}", this, topics); } else { String topicsRegexStr = taskConfig.get(SinkTask.TOPICS_REGEX_CONFIG); Pattern pattern = Pattern.compile(topicsRegexStr); consumer.subscribe(pattern, new HandleRebalance()); log.debug("{} Initializing and starting task for topics regex {}", this, topicsRegexStr); } task.initialize(context); task.start(taskConfig); log.info("{} Sink task finished initialization and start", this); }
Source:
public Integer getWeight() { return 100; }

Target:
private Integer getWeight() { return Weights.BUILT_IN_CONVENTION; }
Source:
private void watchLogsIfDebugEnabled(Map<String, String> startOptions) throws InfrastructureException { if (startOptions == null) { LOG.debug( "'startOptions' is null so we won't watch the container logs for workspace '{}'", getContext().getIdentity().getWorkspaceId()); return; } boolean shouldWatchContainerStartupLogs = Boolean.parseBoolean( startOptions.getOrDefault(DEBUG_WORKSPACE_START, Boolean.FALSE.toString())); if (shouldWatchContainerStartupLogs) { Set<String> podNames = machines .getMachines(getContext().getIdentity()) .values() .stream() .filter(Objects::nonNull) .map(KubernetesMachineImpl::getPodName) .filter(Objects::nonNull) .collect(Collectors.toSet()); LOG.debug( "Watch '{}' pods in workspace '{}'", podNames, getContext().getIdentity().getWorkspaceId()); namespace .deployments() .watchLogs( new PodLogToEventPublisher(this.eventPublisher, this.getContext().getIdentity()), LogWatchTimeouts.DEFAULT, podNames); } }

Target:
private void watchLogsIfDebugEnabled(Map<String, String> startOptions) throws InfrastructureException { if (startOptions == null || startOptions.isEmpty()) { LOG.debug( "'startOptions' is null or empty so we won't watch the container logs for workspace '{}'", getContext().getIdentity().getWorkspaceId()); return; } boolean shouldWatchContainerStartupLogs = Boolean.parseBoolean( startOptions.getOrDefault(DEBUG_WORKSPACE_START, Boolean.FALSE.toString())); if (shouldWatchContainerStartupLogs) { Set<String> podNames = machines .getMachines(getContext().getIdentity()) .values() .stream() .filter(Objects::nonNull) .map(KubernetesMachineImpl::getPodName) .filter(Objects::nonNull) .collect(Collectors.toSet()); LOG.debug( "Watch '{}' pods in workspace '{}'", podNames, getContext().getIdentity().getWorkspaceId()); namespace .deployments() .watchLogs( new PodLogToEventPublisher(this.eventPublisher, this.getContext().getIdentity()), LogWatchTimeouts.DEFAULT, podNames, LogWatcher.getLogLimitBytes(startOptions)); } }
Source:
public boolean isSessionLevelPrivilegeLinkClicked(int instrNum, int sectionLevelIndex, int sessionIndex, int linkNum) { return this.sessionLevelTableCheckbox(instrNum, sectionLevelIndex, sessionIndex, linkNum - 1).isSelected(); }

Target:
public boolean isSessionLevelPrivilegeLinkClicked(int instrNum, int sectionLevelIndex, int sessionIndex, int linkNum) { return getSessionLevelTableCheckbox(instrNum, sectionLevelIndex, sessionIndex, linkNum).isSelected(); }
Source:
public void setContactBlocked(String number, boolean blocked) { ContactInfo contact = account.getContactStore().getContact(number); if (contact == null) { contact = new ContactInfo(); contact.number = number; System.err.println("Adding and " + (blocked ? "blocking" : "unblocking") + " contact " + number); } else { System.err.println((blocked ? "Blocking" : "Unblocking") + " contact " + number); } contact.blocked = blocked; account.getContactStore().updateContact(contact); account.save(); }

Target:
public void setContactBlocked(String number, boolean blocked) throws InvalidNumberException { number = Utils.canonicalizeNumber(number, username); ContactInfo contact = account.getContactStore().getContact(number); if (contact == null) { contact = new ContactInfo(); contact.number = number; System.err.println("Adding and " + (blocked ? "blocking" : "unblocking") + " contact " + number); } else { System.err.println((blocked ? "Blocking" : "Unblocking") + " contact " + number); } contact.blocked = blocked; account.getContactStore().updateContact(contact); account.save(); }
Source:
protected void postLoad(DAnalysis dAnalysis, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) { new DEdgeNameEditPart(null); new DEdgeBeginNameEditPart(null); new DEdgeEndNameEditPart(null); boolean isModified = false; StringBuilder sb = new StringBuilder(Messages.SnapBackDistantLabelsMigrationParticipant_title); List<Node> distantEdgeLabels = new ArrayList<Node>(); for (DView dView : dAnalysis.getOwnedViews()) { for (DDiagram dDiagram : Iterables.filter(new DViewQuery(dView).getLoadedRepresentations(), DDiagram.class)) { List<Node> currentDistantEdgeLabels = getDistantEdgeLabels(dDiagram); distantEdgeLabels.addAll(currentDistantEdgeLabels); if (currentDistantEdgeLabels.size() > 0) { isModified = true; if (currentDistantEdgeLabels.size() > 1) { sb.append(MessageFormat.format(Messages.SnapBackDistantLabelsMigrationParticipant_severalLabelsSnapBacked, currentDistantEdgeLabels.size(), dDiagram.getName())); } else { sb.append(MessageFormat.format(Messages.SnapBackDistantLabelsMigrationParticipant_oneLabelSnapBacked, dDiagram.getName())); } } } } for (Node distantEdgeLabel : distantEdgeLabels) { String hint = distantEdgeLabel.getType(); Point offset = LabelEditPart.getSnapBackPosition(hint); if (offset != null) { ViewUtil.setStructuralFeatureValue(distantEdgeLabel, NotationPackage.eINSTANCE.getLocation_X(), Integer.valueOf(offset.x)); ViewUtil.setStructuralFeatureValue(distantEdgeLabel, NotationPackage.eINSTANCE.getLocation_Y(), Integer.valueOf(offset.y)); } } if (isModified) { DiagramPlugin.getDefault().logInfo(sb.toString()); } } }

Target:
protected void postLoad(DAnalysis dAnalysis, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) { initializeSnapBackPositionMap(); boolean isModified = false; StringBuilder sb = new StringBuilder(Messages.SnapBackDistantLabelsMigrationParticipant_title); List<Node> distantEdgeLabels = new ArrayList<Node>(); for (DView dView : dAnalysis.getOwnedViews()) { for (DDiagram dDiagram : Iterables.filter(new DViewQuery(dView).getLoadedRepresentations(), DDiagram.class)) { List<Node> currentDistantEdgeLabels = getDistantEdgeLabels(dDiagram); distantEdgeLabels.addAll(currentDistantEdgeLabels); if (currentDistantEdgeLabels.size() > 0) { isModified = true; if (currentDistantEdgeLabels.size() > 1) { sb.append(MessageFormat.format(Messages.SnapBackDistantLabelsMigrationParticipant_severalLabelsSnapBacked, currentDistantEdgeLabels.size(), dDiagram.getName())); } else { sb.append(MessageFormat.format(Messages.SnapBackDistantLabelsMigrationParticipant_oneLabelSnapBacked, dDiagram.getName())); } } } } for (Node distantEdgeLabel : distantEdgeLabels) { Point offset = LabelEditPart.getSnapBackPosition(distantEdgeLabel.getType()); if (offset != null) { ViewUtil.setStructuralFeatureValue(distantEdgeLabel, NotationPackage.eINSTANCE.getLocation_X(), Integer.valueOf(offset.x)); ViewUtil.setStructuralFeatureValue(distantEdgeLabel, NotationPackage.eINSTANCE.getLocation_Y(), Integer.valueOf(offset.y)); } } if (isModified) { DiagramPlugin.getDefault().logInfo(sb.toString()); } } }