auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onAppendColumnEvent() { AppendColumnEvent event = new AppendColumnEvent(COLUMN_GROUP); scenarioSimulationEventHandler.onEvent(event); verify(scenarioSimulationEventHandler, times(1)).commonExecution(eq(scenarioSimulationContextLocal), isA(AppendColumnCommand.class)); START verify(scenarioGridPanelMock).setFocus(true); END } @jomarko If it is possible to move all those "context.getScenarioGridPanel().setFocus(true);" inside commonExecution, then move this "verify(scenarioGridPanelMock).setFocus(true);" inside "commonExecution" Test

Target:
public void onAppendColumnEvent() { AppendColumnEvent event = new AppendColumnEvent(COLUMN_GROUP); scenarioSimulationEventHandler.onEvent(event); verify(scenarioSimulationEventHandler).commonExecution(eq(scenarioSimulationContextLocal), isA(AppendColumnCommand.class), eq(true)); }
Source:
public static <T extends Widget> T serializeAndDeserialize( T instance ) throws Exception { byte[] bytes = serialize( instance ); T result = ( T )deserialize( bytes ); START Object adapter = result.getDisplay().getAdapter( IDisplayAdapter.class ); END IDisplayAdapter displayAdapter = ( IDisplayAdapter )adapter; displayAdapter.attachThread(); return result; } Since getAdapter() has a generic interface, there is no need to type cast anymore.

Target:
public static <T> T serializeAndDeserialize( T instance ) throws Exception { byte[] bytes = serialize( instance ); return ( T )deserialize( bytes ); }
Source:
START public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { END for (PreReceiveHook hook : hooks) { hook.onPreReceive(rp, commands); } } maybe line wrap?

Target:
public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { for (int i = 0; i < count; i++) hooks[i].onPreReceive(rp, commands); }
Source:
public DescriptionBuilder withAdditionalAnnotations(Annotation annotation, Annotation... additionalAnnotations) { if (annotation == null) { throw new NullPointerException("Cannot add a null annotation"); } annotations.add(annotation); START annotations.addAll(Arrays.asList(additionalAnnotations)); END return this; } This only checks the first parameter for `null`. Could you update the version that takes in a `List` to check the entries for `null`s and update this line to call that version?

Target:
public DescriptionBuilder withAdditionalAnnotations(Annotation annotation, Annotation... additionalAnnotations) { List<Annotation> annotations = new ArrayList<Annotation>(); annotations.add(annotation); annotations.addAll(Arrays.asList(additionalAnnotations)); return withAdditionalAnnotations(annotations); }
Source:
public void onAttach(final Activity activity) { super.onAttach(activity); try { mListener = (Listener) activity; START } catch (final ClassCastException e) { END Lg.e(activity.getClass().getName(), " should implement ", Listener.class.getName()); } } instanceof?

Target:
public void onAttach(final Activity activity) { super.onAttach(activity); if (activity instanceof Listener) { mListener = (Listener) activity; } else { Lg.e(activity.getClass().getName(), " should implement ", Listener.class.getName()); } }
Source:
private void preloadDataSet(){ preloadedDataSet = load(iter.next()); totalOutcomes = preloadedDataSet.getLabels().size(1); inputColumns = preloadedDataSet.getFeatureMatrix().size(1); START batch = preloadedDataSet.numExamples(); END } Need to be careful here. We can't always assume classification problems. Maybe use -1 (last dimension) instead?

Target:
private void preloadDataSet(){ preloadedDataSet = load(iter.next()); totalOutcomes = preloadedDataSet.getLabels().size(1); inputColumns = preloadedDataSet.getFeatureMatrix().size(1); }
Source:
public void startup(Application application, ComponentStartupStatus ss) { FileOps.ensureDir(deltaClientZone); FileOps.clearAll(deltaClientZone); zone = Zone.connect(deltaClientZone); deltaLink = DeltaLinkHTTP.connect(deltaServerURL); deltaClient = DeltaClient.create(zone, deltaLink); jmsMessagingClient = application.getJMSMessagingClient(); START log.info(String.format("DeltaClient connected to DeltaServer at %s with zone %s", deltaServerURL, deltaClientZone)); END } `log.info()` to `ss.info()`.

Target:
public void startup(Application application, ComponentStartupStatus ss) { FileOps.ensureDir(deltaClientZone); FileOps.clearAll(deltaClientZone); Zone zone = Zone.connect(deltaClientZone); deltaLink = DeltaLinkHTTP.connect(deltaServerURL); deltaClient = DeltaClient.create(zone, deltaLink); jmsMessagingClient = application.getJMSMessagingClient(); ss.info(String.format("DeltaClient connected to DeltaServer at %s with zone %s", deltaServerURL, deltaClientZone)); }
Source:
protected void onInit() { super.onInit(); if (this.connectionFactory == null) { START this.connectionFactory = new TcpNioServerConnectionFactory(super.getPort()); END this.connectionFactory.setDeserializer(new ByteArrayLfSerializer()); this.connectionFactory.setBeanFactory(getBeanFactory()); if (this.applicationEventPublisher != null) { this.connectionFactory.setApplicationEventPublisher(this.applicationEventPublisher); } this.connectionFactory.afterPropertiesSet(); } this.connectionFactory.registerListener(this); } I think we don't need this change. We have similar structure in the `UdpSyslogReceivingChannelAdapter` below but you don't override the `onInit()` logic there.

Target:
protected void onInit() { super.onInit(); if (this.connectionFactory == null) { this.connectionFactory = new TcpNioServerConnectionFactory(getPort()); this.connectionFactory.setDeserializer(new ByteArrayLfSerializer()); this.connectionFactory.setBeanFactory(getBeanFactory()); if (this.applicationEventPublisher != null) { this.connectionFactory.setApplicationEventPublisher(this.applicationEventPublisher); } this.connectionFactory.afterPropertiesSet(); } this.connectionFactory.registerListener(this); }
Source:
START public static Pair<Integer, Integer> getPrecisionAndScale(String type) { END String param = type.substring(8, type.length() - 1); String[] params = param.split(","); return new Pair<>(Integer.parseInt(params[0].trim()), Integer.parseInt(params[1].trim())); } are there some unit tests for this? Will this handle extraneous whitespaces well?

Target:
public static Pair<Integer, Integer> getPrecisionAndScale(String type) { type = type.trim(); String param = type.substring(8, type.length() - 1); String[] params = param.split(","); return new Pair<>(Integer.parseInt(params[0].trim()), Integer.parseInt(params[1].trim())); }
Source:
START static String constructSegmentPath(String baseKey, String storageDir) END { return JOINER.join( baseKey.isEmpty() ? null : baseKey, storageDir ) + "/index.zip"; } we don't know if these were used in extensions, can the things that were public remain so?

Target:
public static String constructSegmentPath(String baseKey, String storageDir) { return JOINER.join( baseKey.isEmpty() ? null : baseKey, storageDir ) + "/index.zip"; }
Source:
public MappingIterator(Collection<S> source, Function<S, D> transformation) { this.sourceIt = source.iterator(); this.transformation = transformation; START readNext(); END } I find it strange that the constructor already does some work. Might catch someone by surprise, especially if he wants to concatenate several iterators. I'd like this better if only hasNext() or next() actually advanced. It's more predictable. Maybe similar to the logic in CachingKeyPairProvider$CancellingKeyPairIterator . That one is similar to MappingIterator<Path, KeyPair>.

Target:
public MappingIterator(Collection<S> source, Function<S, D> transformation) { this.sourceIt = source.iterator(); this.transformation = transformation; }
Source:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (XWikiAttachment x : (Collection<? extends XWikiAttachment>) c) { START if (map.remove(x.getFilename(), x)) { END changed = true; } } if (changed) { updatedMap(); } return changed; } remove(a,b) is going to use equals which is not right for XWikiAttachment. You should use remove(a) != b instead.

Target:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (XWikiAttachment x : (Collection<? extends XWikiAttachment>) c) { if (map.get(x.getFilename()) == x) { map.remove(x.getFilename()); changed = true; } } if (changed) { updatedMap(); } return changed; }
Source:
public void run(String... strings) throws Exception { START System.out.println(">>> Starting Audit App... "); END } @erdemedeiros let's remove all the system outs

Target:
public void run(String... strings) throws Exception { }
Source:
public CollectEnvCommand(FileSystemContext fsContext) { super(fsContext); START mCommands = new HashMap<>(); mCommandsAlt = new HashMap<>(); END registerCommands(); } This is already initialized by super class.

Target:
public CollectEnvCommand(FileSystemContext fsContext) { super(fsContext); registerCommands(); }
Source:
protected void setBlobStorageService(BlobStorageService blobStorageService) { if (blobStorageService == null) { throw new IllegalArgumentException("BlobStorageService cannot be null"); START } else { END this.blobStorageService = blobStorageService; logger.trace("BlobStorage service set to {}", blobStorageService.getClass()); } } The "else" seems unnecessary

Target:
protected void setBlobStorageService(BlobStorageService blobStorageService) { if (blobStorageService == null) { throw new IllegalArgumentException("BlobStorageService cannot be null"); } this.blobStorageService = blobStorageService; logger.trace("BlobStorage service set to {}", blobStorageService.getClass()); }
Source:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); START windowModel.setToBeRendered(false); END windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); } I don't think this hurts but line 96 already sets this window.tbr to false and I have not seen that this property has changed.

Target:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); }
Source:
public void setUp() { n = new CacheManagerNotifierImpl(); cl = new CacheManagerListener(); START TestingUtil.inject(n, TestingUtil.named(KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR, new WithinThreadExecutor())); END n.start(); n.addListener(cl); } The executor shouldn't be needed here either

Target:
public void setUp() { n = new CacheManagerNotifierImpl(); cl = new CacheManagerListener(); n.start(); n.addListener(cl); }
Source:
public char getLabel() { START char rv; END switch (getType()) { case INPUT_VAL: rv = buttonData.inputVal; break; case AUTO_CHAR: rv = buttonData.autoChar; break; case CUSTOM: rv = buttonData.customChar; break; default: rv='*'; // Should never happen. } return rv; } Should be `final char rv;`.

Target:
public char getLabel() { final char rv; switch (getType()) { case INPUT_VAL: rv = buttonData.inputVal; break; case AUTO_CHAR: rv = buttonData.autoChar; break; case CUSTOM: rv = buttonData.customChar; break; default: rv = '*'; // Should never happen. } return rv; }
Source:
public ReleasableBytesReference retainedSlice(int from, int length) { BytesReference slice = delegate.slice(from, length); START refCounted.incRef(); END return new ReleasableBytesReference(slice, refCounted); } I would prefer to move this call to the private `ReleasableBytesReference` constructor.

Target:
public ReleasableBytesReference retainedSlice(int from, int length) { return new ReleasableBytesReference(delegate.slice(from, length), refCounted); }
Source:
public static <T> Iterable<T> latest(final Observable<? extends T> source) { return new Iterable<T>() { @Override public Iterator<T> iterator() { LatestObserverIterator<T> lio = new LatestObserverIterator<T>(); START lio.subscription = source.materialize().subscribe(lio); END return lio; } }; } This set races with the dereference of L101 and may cause NPE. Besides, since it would be set to the value `lio` essentially (plus a transparent SafeSubscriber layer), you don't really need this field. Just call `this.unsubscribe()` on L101.

Target:
public static <T> Iterable<T> latest(final Observable<? extends T> source) { return new Iterable<T>() { @Override public Iterator<T> iterator() { LatestObserverIterator<T> lio = new LatestObserverIterator<T>(); source.materialize().subscribe(lio); return lio; } }; }
Source:
public static MessageType fromId(String id) { for(MessageType current : values()) { if(current.getId().equals(id)) { return current; } } START return UNKNOWN; END } Discussion: does it make sense to return an enum entry here that I guess only exists for this method? Other alternatives could be to return `null` here, or an Optional

Target:
public static Optional<MessageType> fromId(String id) { for (MessageType current : values()) { if (current.getId().equals(id)) { return Optional.of(current); } } return Optional.empty(); }
Source:
private boolean isHostNetworkUnreacable(VDS vds) { VdsDynamic vdsDynamic = vds.getDynamicData(); return ((vdsDynamic.getStatus() == VDSStatus.Down) || (vdsDynamic.getStatus() == VDSStatus.Reboot) || (vdsDynamic.getStatus() == VDSStatus.NonOperational START && vdsDynamic.getNonOperationalReason() == NonOperationalReason.NETWORK_UNREACHABLE)); END } Please remove unnecessary brackets: return vdsDynamic.getStatus() == VDSStatus.Down || vdsDynamic.getStatus() == VDSStatus.Reboot || (vdsDynamic.getStatus() == VDSStatus.NonOperational && vdsDynamic.getNonOperationalReason() == NonOperationalReason.NETWORK_UNREACHABLE); Even remaining brackets are not necessary, but they makes code more readable

Target:
private boolean isHostNetworkUnreacable(VDS vds) { VdsDynamic vdsDynamic = vds.getDynamicData(); return (vdsDynamic.getStatus() == VDSStatus.Down || vdsDynamic.getStatus() == VDSStatus.Reboot || (vdsDynamic.getStatus() == VDSStatus.NonOperational && vdsDynamic.getNonOperationalReason() == NonOperationalReason.NETWORK_UNREACHABLE)); }
Source:
START ScriptExecutingMessageSource(AbstractScriptExecutingMessageProcessor<?> scriptMessageProcessor) { END this.scriptMessageProcessor = scriptMessageProcessor; } Having the Java Config style, it'd better to make this class `public`.

Target:
public ScriptExecutingMessageSource(AbstractScriptExecutingMessageProcessor<?> scriptMessageProcessor) { this.scriptMessageProcessor = scriptMessageProcessor; }
Source:
public void typeInSearchField(String content, int length) { waitForElementVisibleByElement(searchInput); START searchInput.sendKeys(content.substring(0, length)); END PageObjectLogging.log( "typeInSearchField", "String >>" + content.substring(0, length) + "<< was typed in string field", true ); } How come there needs to be a substring for this?

Target:
public void typeInSearchField(String content, int length) { waitForElementVisibleByElement(searchInput); searchInput.sendKeys(content.substring(0, 3)); PageObjectLogging.log( "typeInSearchField", "String >>" + content.substring(0, length) + "<< was typed in string field", true ); }
Source:
public Iterable<E> read(Configuration configuration) throws IOException { // TODO: what to do with Configuration? create new view? DatasetReader<E> reader = view.newReader(); START return reader; // TODO: who calls close? END } Inline.

Target:
public Iterable<E> read(Configuration configuration) throws IOException { // TODO: what to do with Configuration? create new view? return view.newReader(); // TODO: who calls close? }
Source:
public void setRefreshInterval(final long refreshInterval) { START REFRESH_INTERVAL_IN_SECONDS = refreshInterval; END } if it is not constant, please convert to lower case?

Target:
public void setRefreshInterval(final long refreshInterval) { this.refreshInterval = refreshInterval; }
Source:
public void onNewImageFromCamera() { START if (navigator.isSdkAboveOrEqualM() && !navigator.doIHavePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { END navigator.askForPermission(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_EXTERNAL_STORAGE_NEW_IMAGE_CAMERA); } else { interactor.createFile(this, CREATE_FILE_TAKE_PHOTO, null); } } These copy-paste sections are starting to clutter up the presenter. Please try to extract a common denominator (e.g. a function) to reduce repeating code snippets.

Target:
public void onNewImageFromCamera() { interactor.createFile(this, CREATE_FILE_TAKE_PHOTO, null); }
Source:
public void testEquals() throws Exception { FixedWidthConfiguration conf1 = new FixedWidthConfiguration(1, "UTF8", START 10, true, false, true); END FixedWidthConfiguration conf2 = new FixedWidthConfiguration(1, "UTF8", 10, true, false, true); assertEquals(conf1, conf2); FixedWidthConfiguration conf3 = new FixedWidthConfiguration(1, "UTF8", 10, false, false, true); assertFalse(conf1.equals(conf3)); } Please make sure there are overloaded constructors available for the old constructor signature. Then you also wont have to change this existing test.

Target:
public void testEquals() throws Exception { FixedWidthConfiguration conf1 = new FixedWidthConfiguration(1, "UTF8", 10, true); FixedWidthConfiguration conf2 = new FixedWidthConfiguration(1, "UTF8", 10, true); assertEquals(conf1, conf2); FixedWidthConfiguration conf3 = new FixedWidthConfiguration(1, "UTF8", 10, false); assertFalse(conf1.equals(conf3)); }
Source:
public void showLinkPreview(PageTitle title, int entrySource) { final String linkPreviewFragmentTag = "link_preview_dialog"; if (getSupportFragmentManager().findFragmentByTag(linkPreviewFragmentTag) == null) { START linkPreview = LinkPreviewDialog.newInstance(title, entrySource); END linkPreview.show(getSupportFragmentManager(), linkPreviewFragmentTag); } } You actually don't need a private variable for storing the link preview. If you look at the line directly above, the findFragmentByTag() function finds the dialog by its tag name (also specified above). You can cast the return value of this function into a LinkPreviewDialog, and call dismiss() on it.

Target:
public void showLinkPreview(PageTitle title, int entrySource) { final String linkPreviewFragmentTag = "link_preview_dialog"; if (getSupportFragmentManager().findFragmentByTag(linkPreviewFragmentTag) == null) { LinkPreviewDialog linkPreview = LinkPreviewDialog.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), linkPreviewFragmentTag); } }
Source:
public void clear() { START if (loader instanceof CacheStore) END try { ((CacheStore) loader).clear(); } catch (CacheLoaderException e) { throw newCacheLoaderException(e); } } IMO, if you use `if (...) { ... }`, it makes the code easy to read. I meant the `{` and `}` are missing :) edit: the same for the following `if`s

Target:
public void clear() { if (loader instanceof CacheStore) { try { ((CacheStore) loader).clear(); } catch (CacheLoaderException e) { throw newCacheLoaderException(e); } } }
Source:
public ApplicabilityIds getApplicabilityIds() { // TBD - Replace with call to IApplicabilityService calls once implemented START ApplicabilityIds ids = new ApplicabilityIds(); END // ids.getApplicabilityIds().add(new ApplicabilityId(345L, "ARC-210")); // ids.getApplicabilityIds().add(new ApplicabilityId(366L, "COMM")); // ids.getApplicabilityIds().add(new ApplicabilityId(376L, "ASM")); // ids.getApplicabilityIds().add(new ApplicabilityId(368L, "UTF")); // ids.getApplicabilityIds().add(new ApplicabilityId(466L, "MDR")); return ids; } This file needs some work to ensure it works with client.

Target:
public ApplicabilityIds getApplicabilityIds() { return null; }
Source:
START MediaType tryNarrowMediaType(MediaType negotiated, AdvancedCache<?, ?> cache) { END if (!negotiated.matchesAll()) return negotiated; MediaType storageMediaType = cache.getValueDataConversion().getStorageMediaType(); if (storageMediaType == null) return negotiated; if (storageMediaType.equals(MediaType.APPLICATION_OBJECT)) return TEXT_PLAIN; if (storageMediaType.match(MediaType.APPLICATION_PROTOSTREAM)) return APPLICATION_JSON; return negotiated; } private?

Target:
private MediaType tryNarrowMediaType(MediaType negotiated, AdvancedCache<?, ?> cache) { if (!negotiated.matchesAll()) return negotiated; MediaType storageMediaType = cache.getValueDataConversion().getStorageMediaType(); if (storageMediaType == null) return negotiated; if (storageMediaType.equals(MediaType.APPLICATION_OBJECT)) return TEXT_PLAIN; if (storageMediaType.match(MediaType.APPLICATION_PROTOSTREAM)) return APPLICATION_JSON; return negotiated; }
Source:
protected void addJAROption(Composite comp) { fJarButton = new Button(comp, SWT.CHECK); fJarButton.setText(getJarButtonText()); START fJarButton.addSelectionListener(widgetSelectedAdapter(e -> { END })); } This does not do anything. Can be removed

Target:
protected void addJAROption(Composite comp) { fJarButton = new Button(comp, SWT.CHECK); fJarButton.setText(getJarButtonText()); }
Source:
public String getTurnDescription( Translation tr ) { START if (rawName || !name.isEmpty()) END return getName(); return tr.tr("finish"); } The additional check is not used in other instructions, is it needed?

Target:
public String getTurnDescription( Translation tr ) { if (rawName) return getName(); return tr.tr("finish"); }
Source:
private void fetchPresenterWidgetTemplate(PresenterOptions presenterOptions) throws Exception { PresenterWidgetOptions presenterWidgetOptions = new PresenterWidgetOptions(); presenterWidgetOptions.setSingleton(presenterConfigModel.isUseSingleton()); try { createdPresenterWidgetTemplates = CreatePresenterWidget.run(presenterOptions, presenterWidgetOptions, true); } catch (Exception e) { START throw e; END } } Catch?

Target:
private void fetchPresenterWidgetTemplate(PresenterOptions presenterOptions) throws Exception { PresenterWidgetOptions presenterWidgetOptions = new PresenterWidgetOptions(); presenterWidgetOptions.setSingleton(presenterConfigModel.isUseSingleton()); createdPresenterWidgetTemplates = CreatePresenterWidget.run(presenterOptions, presenterWidgetOptions, true); }
Source:
public String toString() { StringWriter writer = new StringWriter(); try { new ObjectMapper().writeValue(writer, graph); } catch (Exception e) { log.debug ("Error while constructing new ObjectMapper",e); START } END return writer.toString(); } Make this as a log.error statement. And needs to have space after the ","

Target:
public String toString() { StringWriter writer = new StringWriter(); try { new ObjectMapper().writeValue(writer, graph); } catch (Exception e) { log.error ("Error while constructing new ObjectMapper", e); } return writer.toString(); }
Source:
public TopicStatus(String topic, ConnectorTaskId task, long discoverTimestamp) { //TODO: check non-null this.topic = topic; this.connector = task.connector(); this.task = task.task(); START this.discoverTimestamp = discoverTimestamp; END } How about replacing these four lines with: ``` this(topic, Objects.requireNotNull(task).connector(), task.task(), discoverTimestamp); ``` and then removing the TODO line?

Target:
public TopicStatus(String topic, ConnectorTaskId task, long discoverTimestamp) { this(topic, task.connector(), task.task(), discoverTimestamp); }
Source:
private static OGCGeometry readGeometry(BasicSliceInput input, Slice inputSlice, GeometryType type, int length) { switch (type) { case POINT: return readPoint(input); case MULTI_POINT: case LINE_STRING: case MULTI_LINE_STRING: case POLYGON: case MULTI_POLYGON: return readSimpleGeometry(input, inputSlice, type, length); case GEOMETRY_COLLECTION: return readGeometryCollection(input, inputSlice); case ENVELOPE: START return OGCGeometry.createFromEsriGeometry(readEnvelope(input), null); END default: throw new IllegalArgumentException("Unexpected type: " + type); } } Just add an envelope section to `createFromEsriGeometry` method in this file

Target:
private static OGCGeometry readGeometry(BasicSliceInput input, Slice inputSlice, GeometryType type, int length) { switch (type) { case POINT: return readPoint(input); case MULTI_POINT: case LINE_STRING: case MULTI_LINE_STRING: case POLYGON: case MULTI_POLYGON: return readSimpleGeometry(input, inputSlice, type, length); case GEOMETRY_COLLECTION: return readGeometryCollection(input, inputSlice); case ENVELOPE: return createFromEsriGeometry(readEnvelope(input), false); default: throw new IllegalArgumentException("Unexpected type: " + type); } }
Source:
public void close() { START sketch = null; END } Could set `null` to the `values` field too

Target:
public void close() { sketch = null; values = null; }
Source:
public boolean shouldSpill() { // Expected new batch size like the current, plus the Hash Values vector (4 bytes per HV) long batchSize = ( batchMemoryManager.getRecordBatchSizer(RIGHT_INDEX).getRowAllocWidth() + 4 ) * recordsPerBatch; long reserveForOutgoing = batchMemoryManager.getOutputBatchSize(); START long memoryAvailableNow = allocator.getLimit() - allocator.getAllocatedMemory() - reserveForOutgoing; END boolean needsSpill = minBatchesInAvailableMemory * batchSize > memoryAvailableNow; if ( needsSpill ) { logger.debug("should spill now - batch size {}, mem avail {}, reserved for outgoing {}", batchSize, memoryAvailableNow, reserveForOutgoing); } return needsSpill; // go spill if too little memory is available } We still need to account for the probe batch size here when we are processing a spilled partition. If we try to account for it in he PostBuildCalculator it will already be too late, because we will have already prefetched the probe side batch.

Target:
public boolean shouldSpill() { // Expected new batch size like the current, plus the Hash Values vector (4 bytes per HV) long batchSize = ( batchMemoryManager.getRecordBatchSizer(RIGHT_INDEX).getRowAllocWidth() + 4 ) * recordsPerBatch; long reserveForOutgoing = batchMemoryManager.getOutputBatchSize(); long memoryAvailableNow = allocator.getLimit() - allocator.getAllocatedMemory(); boolean needsSpill = minBatchesInAvailableMemory * batchSize > memoryAvailableNow - reserveForOutgoing; if ( needsSpill ) { logger.debug("should spill now - batch size {}, mem avail {}, reserved for outgoing {}", batchSize, memoryAvailableNow, reserveForOutgoing); } return needsSpill; // go spill if too little memory is available }
Source:
public void close() { try { Await.result(beam.close()); } catch (Exception e) { final String errorMsg = "Error while closing Druid beam client"; LOG.error(errorMsg, e); START throw new RuntimeException(errorMsg); END } } same as above. we shouldn't be throwing run-time exceptions when close is called.

Target:
public void close() { try { Await.result(beam.close()); } catch (Exception e) { LOG.error("Error while closing Druid beam client", e); } }
Source:
private boolean isPlatformKeybindingBug517068Fixed() { Bundle bundle = Platform.getBundle("org.eclipse.e4.ui.bindings"); //$NON-NLS-1$ Version currentVersion = bundle.getVersion(); START Version fixVersion = new Version(0, 12, 100); END return currentVersion.compareTo(fixVersion) >= 0; } Bug 517068 is actually targeting 0.12.1. Only 0.12.100 has it right now, but it should be backported to 0.12.1.

Target:
private boolean isPlatformKeybindingBug517068Fixed() { Bundle bundle = Platform.getBundle("org.eclipse.e4.ui.bindings"); //$NON-NLS-1$ Version currentVersion = bundle.getVersion(); Version fixVersion = new Version(0, 12, 1); return currentVersion.compareTo(fixVersion) >= 0; }
Source:
public static boolean isPluginPrefixAndArtifactIdEquals( Plugin p1, Plugin p2 ) { START if ( StringUtils.equals( p1.getArtifactId(), p2.getArtifactId() ) END && StringUtils.equals( p1.getPrefix(), p2.getPrefix() ) ) { return true; } return false; } Why not just: return StringUtils.equals( p1.getArtifactId(), p2.getArtifactId() ) && StringUtils.equals( p1.getPrefix(), p2.getPrefix() );

Target:
public static boolean isPluginPrefixAndArtifactIdEquals( Plugin p1, Plugin p2 ) { return StringUtils.equals( p1.getArtifactId(), p2.getArtifactId() ) && StringUtils.equals( p1.getPrefix(), p2.getPrefix() ); }
Source:
public <VT> MessageOut<T> withParameter(ParameterType type, VT value) { START List<Object> newParameters = new ArrayList<>(parameters.size() + 3); END newParameters.addAll(parameters); newParameters.add(type); newParameters.add(value); return new MessageOut<T>(verb, payload, serializer, newParameters); } I think tuple size used to be 3. I'll fix it.

Target:
public <VT> MessageOut<T> withParameter(ParameterType type, VT value) { List<Object> newParameters = new ArrayList<>(parameters.size() + 2); newParameters.addAll(parameters); newParameters.add(type); newParameters.add(value); return new MessageOut<T>(verb, payload, serializer, newParameters); }
Source:
private boolean validateTimeRange() { boolean isEmpty = fStartTimeRangeText.getText().isEmpty() || fEndTimeRangeText.getText().isEmpty(); return !isEmpty && parseTimeRange() && fStartTimestamp.compareTo(fEndTimestamp) <= 0; START } END should this be < 0? do we want to import a 0 nanosecond range?

Target:
private boolean validateTimeRange() { boolean isEmpty = fStartTimeRangeText.getText().isEmpty() || fEndTimeRangeText.getText().isEmpty(); return !isEmpty && parseTimeRange() && fStartTimestamp.compareTo(fEndTimestamp) < 0; }
Source:
public static String getFileNamePath(final String filename, final FieldbookProperties fieldbookProperties) { String filenamePath = ""; StringBuilder filenameBuilder = new StringBuilder(); filenameBuilder.append(fieldbookProperties.getUploadDirectory()); filenameBuilder.append(File.separator); filenameBuilder.append(SettingsUtil.cleanSheetAndFileName(filename)); START filenamePath = filenameBuilder.toString(); END return filenamePath; } Move filenamePath declaration to this line and make it final

Target:
public static String getFileNamePath(final String filename, final FieldbookProperties fieldbookProperties) { final StringBuilder filenameBuilder = new StringBuilder(); filenameBuilder.append(fieldbookProperties.getUploadDirectory()); filenameBuilder.append(File.separator); filenameBuilder.append(SettingsUtil.cleanSheetAndFileName(filename)); final String filenamePath = filenameBuilder.toString(); return filenamePath; }
Source:
protected void changeStorageDomainStatusInTransaction(final StoragePoolIsoMap map, final StorageDomainStatus status) { executeInNewTransaction(new TransactionMethod<StoragePoolIsoMap>() { @SuppressWarnings("synthetic-access") @Override public StoragePoolIsoMap runInTransaction() { START CompensationContext context = getCompensationContext(); END context.snapshotEntityStatus(map, map.getstatus()); map.setstatus(status); getStoragePoolIsoMapDao().updateStatus(map.getId(), map.getstatus()); getCompensationContext().stateChanged(); return null; } }); } this line can be removed

Target:
protected void changeStorageDomainStatusInTransaction(final StoragePoolIsoMap map, final StorageDomainStatus status) { executeInNewTransaction(new TransactionMethod<StoragePoolIsoMap>() { @Override public StoragePoolIsoMap runInTransaction() { CompensationContext context = getCompensationContext(); context.snapshotEntityStatus(map, map.getstatus()); updateStatus(map, status); getCompensationContext().stateChanged(); return null; } }); }
Source:
public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { if (tree.expression().is(Tree.Kind.IDENTIFIER)) { IdentifierTree identifier = (IdentifierTree) tree.expression(); START final Symbol owner = identifier.symbol().owner(); END if (owner != null && owner.isMethodSymbol()) { // No need to investigate selection on local symbols return; } } if (tree.expression().symbolType().isSubtypeOf("java.lang.Class")) { // No need to investigate selection on a Class object return; } super.visitMemberSelectExpression(tree); } remove `final` modifier.

Target:
public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { if (tree.expression().is(Tree.Kind.IDENTIFIER)) { IdentifierTree identifier = (IdentifierTree) tree.expression(); Symbol owner = identifier.symbol().owner(); if (owner != null && owner.isMethodSymbol()) { // No need to investigate selection on local symbols return; } } if (tree.expression().symbolType().isSubtypeOf("java.lang.Class")) { // No need to investigate selection on a Class object return; } super.visitMemberSelectExpression(tree); }
Source:
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(key, NULL_BIFUNCTION_IS_NOT_ALLOWED); START if (SerializationUtil.isClassStaticAndSerializable(remappingFunction)) { END BiFunctionExecutingEntryProcessor<K, V> ep = new BiFunctionExecutingEntryProcessor<>(remappingFunction); return executeOnKeyInternal(key, ep); } else { return computeIfPresentLocally(key, remappingFunction); } } Hi, @mmedenjak is right we need a fallback mechanism when server is not available. Having a fallback mechanism have greater scope. Lets make the `computeIfPresentLocally` only implementation for now for the client. The optimisation for the client can be addressed later.

Target:
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(key, NULL_BIFUNCTION_IS_NOT_ALLOWED); return computeIfPresentLocally(key, remappingFunction); }
Source:
public void sendUnanchored(Task task, String stream, List<Object> values, ExecutorTransfer transfer) { Tuple tuple = task.getTuple(stream, values); List<Integer> tasks = task.getOutgoingTasks(stream, values); START if (tasks.size() == 0) { END return; } for (Integer t : tasks) { transfer.transfer(t, tuple); } } we don't need this check right. For loop won't enter if tasks are empty. We should avoid having multiple returns.

Target:
public void sendUnanchored(Task task, String stream, List<Object> values, ExecutorTransfer transfer) { Tuple tuple = task.getTuple(stream, values); List<Integer> tasks = task.getOutgoingTasks(stream, values); for (Integer t : tasks) { transfer.transfer(t, tuple); } }
Source:
AffinityResourceDefinition(PathElement path) { START super(path, UndertowExtension.getResolver(Constants.HANDLER, Constants.AFFINITY, path.getValue()), new ReloadRequiredAddStepHandler(), new ReloadRequiredRemoveStepHandler()); END } Unless I'm mistaken, you don't need to reload the whole server, just restart the services of the parent resource. You can leverage RestartParentResourceRegistration for this.

Target:
AffinityResourceDefinition(PathElement path) { super(path, UndertowExtension.getResolver(Constants.HANDLER, Constants.AFFINITY, path.getValue())); }
Source:
@Override public E poll() { lock.lock(); try { if (queue.isEmpty()) { return null; } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); START return null; END } finally { lock.unlock(); } } throws

Target:
@Override public E poll() { lock.lock(); try { if (queue.isEmpty()) { return null; } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
public void testTimeout() throws SystemException, RemoteException { START log.info("Method stateful #testTimeout called"); END Transaction txn; txn = tm.getTransaction(); TxTestUtil.enlistTestXAResource(txn); TxTestUtil.enlistTestXAResource(txn); try { TxTestUtil.waitForTimeout(tm); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RemoteException("Interupted during waiting for transaction timeout", ie); } } log.tracef

Target:
public void testTimeout() throws SystemException, RemoteException { log.trace("Method stateful #testTimeout called"); Transaction txn; txn = tm.getTransaction(); TxTestUtil.enlistTestXAResource(txn); TxTestUtil.enlistTestXAResource(txn); try { TxTestUtil.waitForTimeout(tm); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RemoteException("Interupted during waiting for transaction timeout", ie); } }
Source:
START public UnstagedComparator(boolean sortAlphabetically) { END this.alphabeticallySort = sortAlphabetically; } doesn't need to be public

Target:
private UnstagedComparator(boolean sortAlphabetically) { this.alphabeticallySort = sortAlphabetically; }
Source:
public boolean shouldUseNativeIO(VM vm, DiskImage diskImage, VmDevice device) { StorageType storageType = diskImage.getStorageTypes().get(0); String diskType = getDiskType(vm, diskImage, device); boolean isNativeIO = !"file".equals(diskType) || (storageType == StorageType.GLUSTERFS && FeatureSupported.useNativeIOForGluster(vm.getCompatibilityVersion())); // marked as transient disk (file type) and uses cache when snapshotId is not null if START (device.getSnapshotId() != null) { END isNativeIO = false; } return isNativeIO; } So why not just add it to the boolean expression in line #1377?

Target:
public boolean shouldUseNativeIO(VM vm, DiskImage diskImage, VmDevice device) { StorageType storageType = diskImage.getStorageTypes().get(0); String diskType = getDiskType(vm, diskImage, device); return (!"file".equals(diskType) || (storageType == StorageType.GLUSTERFS && FeatureSupported.useNativeIOForGluster(vm.getCompatibilityVersion()))) && device.getSnapshotId() == null; // marked as transient disk (file type) and uses cache when snapshotId is not null // so native io should not be used }
Source:
public <T> T execute(Request<T> request, IProgressMonitor monitor) throws IOException, GerritException { if (!isAnonymous()) { return execute(request, true, monitor); } START return execute(request, false, monitor); END } Lines 316-319 can be rewritten as return execute(request, !isAnonymous(), monitor);

Target:
public <T> T execute(Request<T> request, IProgressMonitor monitor) throws IOException, GerritException { return execute(request, !isAnonymous(), monitor); }
Source:
public HighlightingInlineHyperlink(final String text, final String token, final String toHighlight) { super(text, token); START highlight(text, toHighlight); END } Maybe highlight should be called from setText instead? That way, if the text is changed after construction it will get highlighted too.

Target:
public HighlightingInlineHyperlink(final String text, final String token, final String toHighlight) { super(text, token); this.toHighlight = toHighlight; highlight(text, toHighlight); }
Source:
START String serializeInstallCmd(Collection<String> packages) { END if (packages.isEmpty()) { return ""; } else { return CommandInfo.CMD_INSTALL + " " + String.join(" ", packages); } } Not sure if this is guideline, I would prefer to use `protected` visibility rather than package protected one.

Target:
protected String serializeInstallCmd(Collection<String> packages) { if (packages.isEmpty()) { return ""; } else { return CommandInfo.CMD_INSTALL + " " + String.join(" ", packages); } }
Source:
private List roundtrip(List vals, Map conf) { List ret = null; try { ret = deserialize(serialize(vals, conf), conf); START } catch (IOException e) { END LOG.error("Exception when serialize/deserialize ", e); } return ret; } I would prefer to have the IOException thrown by roundtrip. Catching it will still cause the test to fail, but it will be harder to debug.

Target:
private List roundtrip(List vals, Map conf) throws IOException { return deserialize(serialize(vals, conf), conf); }
Source:
public GlobalDirectoryResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.GLOBAL_DIRECTORY), EeExtension.getResourceDescriptionResolver(EESubsystemModel.GLOBAL_DIRECTORY)) START .setAddRestartLevel(OperationEntry.Flag.RESTART_JVM) END .setRemoveRestartLevel(OperationEntry.Flag.RESTART_JVM) .setAddHandler(GlobalDirectoryResourceDefinition.ADD) .setRemoveHandler(GlobalDirectoryResourceDefinition.REMOVE) .setCapabilities(EE_GLOBAL_DIRECTORY_CAPABILITY) ); } Why RESTART_JVM? AFAICT if I add this after boot the service is installed immediately. You'd have to redeploy any app for it to use the module, but that doesn't even require a reload much less a process restart.

Target:
public GlobalDirectoryResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.GLOBAL_DIRECTORY), EeExtension.getResourceDescriptionResolver(EESubsystemModel.GLOBAL_DIRECTORY)) .setAddHandler(GlobalDirectoryResourceDefinition.ADD) .setRemoveHandler(GlobalDirectoryResourceDefinition.REMOVE) .setCapabilities(EE_GLOBAL_DIRECTORY_CAPABILITY) ); }
Source:
public LockRangeDialog(Shell parentShell, TmfXYChartViewer chartViewer) { super(parentShell); START this.fChartViewer END = chartViewer; } You can remove the this

Target:
public LockRangeDialog(Shell parentShell, TmfXYChartViewer chartViewer) { super(parentShell); fChartViewer = chartViewer; }
Source:
public String toStringShort() { START return MoreObjects.toStringHelper("") END .add("ClientType", getStringFromOptional(mClientType)) .add("ClientHostname", mLocalHostName) .add("ServerAddress", mServerAddress) .add("ChannelId", mChannelId) .omitNullValues() .toString(); } I am confused when this is supposed to be "" or `this`?

Target:
public String toStringShort() { return MoreObjects.toStringHelper(this) .add("ClientType", getStringFromOptional(mClientType)) .add("ClientHostname", mLocalHostName) .add("ServerAddress", mServerAddress) .add("ChannelId", mChannelId) .omitNullValues() .toString(); }
Source:
public CompilationUnit() { START this(null, false, null, new NodeList<>(), new NodeList<>(), null); END } for the boolean parameter could be useful to use enums, so that it is more clear what it means

Target:
public CompilationUnit() { this(null, null, new NodeList<>(), new NodeList<>(), null); }
Source:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); START description = (String) command.getParam(PARAM_DESC); END } cast is not needed.

Target:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); description = command.getParam(PARAM_DESC); }
Source:
protected void executeQueryCommand() { START Provider provider = getDbFacade().getProviderDao().get(getParameters().getId()); END NetworkProviderProxy client = getProviderProxyFactory().create(provider); getQueryReturnValue().setReturnValue(client.getAll()); } shouldn't provider be validated for existence prior to accessing it?

Target:
protected void executeQueryCommand() { Provider<?> provider = getDbFacade().getProviderDao().get(getParameters().getId()); NetworkProviderProxy client = getProviderProxyFactory().create(provider); getQueryReturnValue().setReturnValue(client.getAll()); }
Source:
public void testCrashlyticsUninitializedOnAnonymousReportDisabled() { Context context = InstrumentationRegistry.getTargetContext(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putBoolean(SettingsActivity.SETTINGS_CRASH_REPORTS, false); START editor.clear(); END editor.commit(); CrashReporter crashReporter = new CrashReporter(context); assertFalse(crashReporter.initialize()); } In some tests you're using `editor.clear()`, in some you don't. I guess it's better to use it in all tests. Assume that the tests are executed in a random order and should also start in a clean state. So using a [@Before method (setUp)](http://junit.sourceforge.net/javadoc/org/junit/Before.html) to clear the `SharedPreferences` seems like a good idea. Maybe create a static util method so others can benefit from it as well.

Target:
public void testCrashlyticsUninitializedOnAnonymousReportDisabled() { editor.putBoolean(SettingsActivity.SETTINGS_CRASH_REPORTS, false); editor.commit(); assertFalse(CrashReporter.initialize(context)); }
Source:
START protected boolean uniqueInterfaceName(List<VmNetworkInterface> interfaces) { END if (!VmHandler.IsNotDuplicateInterfaceName(interfaces, getInterfaceName(), getReturnValue().getCanDoActionMessages())) { return false; } else { return true; } } it can be simplified to a single return statement protected boolean uniqueInterfaceName(List<VmNetworkInterface> interfaces) { return VmHandler.IsNotDuplicateInterfaceName(interfaces, getInterfaceName(), getReturnValue().getCanDoActionMessages()); }

Target:
protected boolean uniqueInterfaceName(List<VmNetworkInterface> interfaces) { return VmHandler.IsNotDuplicateInterfaceName(interfaces, getInterfaceName(), getReturnValue().getCanDoActionMessages()); }
Source:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) throws InterruptedException { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); // Start LogReplicationDiscovery Service, responsible for // acquiring lock, retrieving Site Manager Info and processing this info // so this node is initialized as Source (sender) or Sink (receiver) replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, START clusterManagerAdapter, discoveryServiceCallback);; END return discoveryServiceCallback; } typo --> ;;

Target:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); // Start LogReplicationDiscovery Service, responsible for // acquiring lock, retrieving Site Manager Info and processing this info // so this node is initialized as Source (sender) or Sink (receiver) replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, clusterManagerAdapter, discoveryServiceCallback); replicationDiscoveryService.start(); return discoveryServiceCallback; }
Source:
public void testEndOfFreeBlockIsUsedIfThePreviousBlockIsLargerThanTheNextBlock() throws Exception { long prevChunk = mallocChunks(4); long middleChunk = mallocChunks(4); long nextChunk = mallocChunks(2); free(middleChunk); // This should be taken from the end of "middleChunk", since that's closer to the smaller neighbor long smallChunk1 = mallocChunks(1); // This should also be taken from the end of the remaining portion of "middleChunk" long smallChunk2 = mallocChunks(1); START assertTrue("The small chunks should have been allocated from the end of the free block", smallChunk1 > smallChunk2); assertTrue("The small chunks should have been allocated from space before 'nextChunk'", smallChunk1 < nextChunk); assertTrue("The small chunks should have been allocated from space after 'prevChunk'", smallChunk2 > prevChunk); END } I would change the order to: assertTrue(prevChunk < smallChunk2); assertTrue(smallChunk2 < smallChunk1); assertTrue(smallChunk1 < nextChunk);

Target:
public void testEndOfFreeBlockIsUsedIfThePreviousBlockIsLargerThanTheNextBlock() throws Exception { long prevChunk = mallocChunks(4); long middleChunk = mallocChunks(4); long nextChunk = mallocChunks(2); free(middleChunk); // This should be taken from the end of "middleChunk", since that's closer to the smaller neighbor long smallChunk1 = mallocChunks(1); // This should also be taken from the end of the remaining portion of "middleChunk" long smallChunk2 = mallocChunks(1); assertTrue("The small chunks should have been allocated from space after 'prevChunk'", prevChunk < smallChunk2); assertTrue("The small chunks should have been allocated from the end of the free block", smallChunk2 < smallChunk1); assertTrue("The small chunks should have been allocated from space before 'nextChunk'", smallChunk1 < nextChunk); }
Source:
public void shouldSetTempImagesPathAsCompleteDirectory() { URI path = URI.create("/pages/newImagesTemp/"); ConfigCore.setImagesPath(URI.create("/pages/newImagesTemp/")); START System.out.println(ConfigCore.getTempImagesPathAsCompleteDirectory()); END assertEquals("Temp images path was set incorrectly!", path, URI.create("/pages/newImagesTemp/")); } Why did you add this `System.out.println()` call? Maybe a logger is a better solution.

Target:
public void shouldSetTempImagesPathAsCompleteDirectory() { URI path = URI.create("/pages/newImagesTemp/"); ConfigCore.setImagesPath(URI.create("/pages/newImagesTemp/")); assertEquals("Temp images path was set incorrectly!", path, URI.create("/pages/newImagesTemp/")); }