auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void setMatcherString(String pattern) { if (pattern.length() == 0) { searchPattern = null; } else { SearchPattern patternMatcher = new SearchPattern(); if (pattern.indexOf('*') != 0 && pattern.indexOf('?') != 0 && pattern.indexOf('.') != 0) { pattern = "*" + pattern; //$NON-NLS-1$ } patternMatcher.setPattern(pattern); searchPattern = patternMatcher; } }

Target:
@Lars Do you think that for consistency (and maybe another slight performance enhancement) this line should be changed as well?
Source:
public DefaultEditorSession(final ManagedSession session, final CanvasCommandManager<AbstractCanvasHandler> canvasCommandManager, final @Session SessionCommandManager<AbstractCanvasHandler> sessionCommandManager, final @Request SessionCommandManager<AbstractCanvasHandler> requestCommandManager, final ClientCommandRegistry<org.kie.workbench.common.stunner.core.command.Command<AbstractCanvasHandler, CanvasViolation>> clientCommandRegistry) { this.session = session; this.commandRegistry = clientCommandRegistry.setSession(session); this.sessionCommandManager = sessionCommandManager; this.requestCommandManager = requestCommandManager; this.canvasCommandManager = canvasCommandManager; }

Target:
yeah let's remove this :)
Source:
private String transformToHeaderValue(Directive... directives) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < directives.length - 1; i++) { sb.append(directives[i].headerValue).append(", "); } sb.append(directives[directives.length - 1].headerValue); return sb.toString(); }

Target:
For consistency across the project, please remove the `final` keyword here.
Source:
private static void fireOnFailure(final NodeProvisioner.PlannedNode plannedNode, final Throwable cause) { for (CloudProvisioningListener cl : CloudProvisioningListener.all()) { try { cl.onFailure(plannedNode, cause); } catch (Throwable e) { LOGGER.log(Level.SEVERE, "Unexpected uncaught exception encountered while " + "processing onFailure() listener call in " + cl + " for agent " + plannedNode.displayName, e); if (e instanceof Error) { throw e; } } } }

Target:
🐜 De-facto we process errors in the logging handler. E.g. logging constructs the string, and it may cause OutOfMemoryError, which suppresses the original one. I'd rather vote that Errors are being rethrown without any processing
Source:
public synchronized boolean isLastMQNotifLongAgo() { long delay = 18 * 3600; // 24h - 3h = 18h long threshold = sharedPreferences.getLong(getCurrentModeName() + LAST_MORNING_Q_TIMESTAMP, - delay) + delay; if (threshold < Calendar.getInstance().getTimeInMillis()) { Logger.d(TAG, "{} - Last MQ notif was yesterday", getCurrentModeName()); return true; } else { Logger.d(TAG, "{} - Last MQ notif was recent, do not notify", getCurrentModeName()); return false; } }

Target:
These two logs could be `Logger.v()`. That's all, good to go!
Source:
public CrewMember apply(org.atlasapi.media.entity.CrewMember input) { if (input instanceof org.atlasapi.media.entity.Actor) { return translateLegacyActor((org.atlasapi.media.entity.Actor) input); } else if(Objects.nonNull(input)) { return translateLegacyCrewMember(input); } else { return null; } }

Target:
Ditto `input != null`
Source:
public void testSocket() throws Exception { Socket s = new Socket(); s.connect(server.getLocalAddress()); s.close(); assertEquals(Collections.EMPTY_MAP, tagger.getLiveDescriptors()); }

Target:
Did you want to assert something before close in all these cases? i.e. it's not empty.
Source:
public ValuesMatcher( Map<String, Integer> outputSymbolAliases, Optional<Integer> expectedOutputSymbolCount, Optional<List<List<Expression>>> expectedRows) { this.outputSymbolAliases = ImmutableMap.copyOf(requireNonNull(outputSymbolAliases, "outputSymbolAliases is null")); this.expectedOutputSymbolCount = requireNonNull(expectedOutputSymbolCount, "expectedOutputSymbolCount is null"); this.expectedRows = requireNonNull(expectedRows, "expectedRows is null"); }

Target:
`requireNonNull` is not needed given `copyOf` checks for nullability.
Source:
protected Button getButton(int id) { return buttons.get(new Integer(id)); }

Target:
Can just pass id and let Java autoboxing take care of it.
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { if (data instanceof Hashtable) { Hashtable<?, ?> table = (Hashtable<?, ?>) data; color = (String) table.get("color"); //$NON-NLS-1$ } }

Target:
Better: Map
Source:
public void addRequestCleanupHandler(HttpServletRequest request) { RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest req) { try { close(); } catch (OperationException cause) { throw new NuxeoException(cause); } } }); }

Target:
`cause` —> `e` please
Source:
public void visitStatementList(PyStatementListTree pyStatementListTree) { if (isStmtListIncrementsNestingLevel(pyStatementListTree) && !pyStatementListTree.parent().is(Kind.FILE_INPUT)) { nestingLevelStack.peek().increment(); super.visitStatementList(pyStatementListTree); nestingLevelStack.peek().decrement(); } else { super.visitStatementList(pyStatementListTree); } }

Target:
Why not move the logic about `Kind.FILE_INPUT` inside `isStmtListIncrementsNestingLevel`?
Source:
private static void checkLxmlParseCall(SubscriptionContext ctx) { CallExpression callExpression = (CallExpression) ctx.syntaxNode(); if (checkCallExpressionFqn(callExpression, LXML_PARSE)) { CallExpression parserCall = getParserCall( getArgValueAsCallExpression( TreeUtils.nthArgumentOrKeyword(1, "parser", callExpression.arguments()))); if (parserCall != null && isUnsafeParserUsage(parserCall)) { ctx.addIssue(parserCall, MESSAGE).secondary(callExpression, MESSAGE); } } }

Target:
no need to add the same message to the secondary location
Source:
public int getVisibility(IBinding member) { try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getAccessibility(member); } catch (CoreException e) { CCorePlugin.log(e); throw new IllegalArgumentException(member.getName() + " is not a member of " + getName()); //$NON-NLS-1$ } }

Target:
The same error is reported twice.
Source:
public Map<String,Object> getDynamicTemplateData() { if(dynamicTemplateData == null) return Collections.<String,Object>emptyMap(); return dynamicTemplateData; }

Target:
Nitpick: It's generally safer to include curly brackets for _all_ if statements. It can help protect against a future developer accidentally introducing a bug if another line is added to the if statement. Alternatively, a more succinct way of writing this method would be: ``` return (dynamicTemplateData == null) ? Collections.<String, Object>emptyMap() : dynamicTemplateData; ```
Source:
public String getVersion() { return version; }

Target:
I'm not sure about public modifier here as version field represents reference's implementation details. I doubt consumers would be really interested in it. I would leave it private (or even remove it) unless there is a real usecase that requires access to its value. Making it private later would be hard (due to API breakage), we can make it public later without any problems.
Source:
public List<User> getUsers(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if(!AuthzResolver.isAuthorized(sess, Role.PERUNADMIN) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { throw new PrivilegeException(sess, "getUsers"); } return getUsersManagerBl().getUsers(sess); }

Target:
You can drop PERUNADMIN check here. And also in all other such methods in this file please.
Source:
protected void setDefaultSwitchTypeIfNeeded() { Cluster cluster = getCluster(); if (cluster.isSetRequiredSwitchType()) { SwitchType defaultSwitchType = DefaultSwitchType.getDefaultSwitchType(cluster.getCompatibilityVersion()); cluster.setRequiredSwitchTypeForCluster(defaultSwitchType); } }

Target:
Negation missing? if (!cluster.isSetRequiredSwitchType()) {
Source:
public List<BlockLocationInfo> getBlockLocations(AlluxioURI alluxioURI) throws IOException { throw new UnsupportedOperationException("GetBlockLocations is not supported."); }

Target:
Removed.
Source:
public CustomTxtParserWizard() { super(); setWindowTitle(Messages.CustomTxtParserInputWizardPage_windowTitle); }

Target:
can this be in the second ctor and call this(null) here?
Source:
protected Provider<AdditionalProperties> createProvider(String name) { Provider<AdditionalProperties> p = mock(Provider.class); when(p.getName()).thenReturn(name); return p; }

Target:
Don't see how this change is necessary
Source:
public static int mapApiToArtVersion(int api) { if (api < 19) { return NO_VERSION; } switch (api) { case 19: case 20: return 7; case 21: return 39; case 22: return 45; case 23: return 64; case 24: case 25: return 79; case 26: return 124; case 27: return 131; case 28: // 144 is the current version in the master branch of AOSP as of 2018-05-22 return 144; } return 143; }

Target:
You can change the 28 case to a default case, and remove this.
Source:
public void onAppendColumnEvent() { AppendColumnEvent event = new AppendColumnEvent(COLUMN_GROUP); scenarioSimulationEventHandler.onEvent(event); verify(scenarioSimulationEventHandler, times(1)).commonExecution(eq(scenarioSimulationContextLocal), isA(AppendColumnCommand.class)); verify(scenarioGridPanelMock).setFocus(true); }

Target:
@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
Source:
public static <T extends Widget> T serializeAndDeserialize( T instance ) throws Exception { byte[] bytes = serialize( instance ); T result = ( T )deserialize( bytes ); Object adapter = result.getDisplay().getAdapter( IDisplayAdapter.class ); IDisplayAdapter displayAdapter = ( IDisplayAdapter )adapter; displayAdapter.attachThread(); return result; }

Target:
Since getAdapter() has a generic interface, there is no need to type cast anymore.
Source:
public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { for (PreReceiveHook hook : hooks) { hook.onPreReceive(rp, commands); } }

Target:
maybe line wrap?
Source:
public DescriptionBuilder withAdditionalAnnotations(Annotation annotation, Annotation... additionalAnnotations) { if (annotation == null) { throw new NullPointerException("Cannot add a null annotation"); } annotations.add(annotation); annotations.addAll(Arrays.asList(additionalAnnotations)); return this; }

Target:
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?
Source:
public void onAttach(final Activity activity) { super.onAttach(activity); try { mListener = (Listener) activity; } catch (final ClassCastException e) { Lg.e(activity.getClass().getName(), " should implement ", Listener.class.getName()); } }

Target:
instanceof?
Source:
private void preloadDataSet(){ preloadedDataSet = load(iter.next()); totalOutcomes = preloadedDataSet.getLabels().size(1); inputColumns = preloadedDataSet.getFeatureMatrix().size(1); batch = preloadedDataSet.numExamples(); }

Target:
Need to be careful here. We can't always assume classification problems. Maybe use -1 (last dimension) instead?
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(); log.info(String.format("DeltaClient connected to DeltaServer at %s with zone %s", deltaServerURL, deltaClientZone)); }

Target:
`log.info()` to `ss.info()`.
Source:
protected void onInit() { super.onInit(); if (this.connectionFactory == null) { this.connectionFactory = new TcpNioServerConnectionFactory(super.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); }

Target:
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.
Source:
public static Pair<Integer, Integer> getPrecisionAndScale(String type) { 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())); }

Target:
are there some unit tests for this? Will this handle extraneous whitespaces well?
Source:
static String constructSegmentPath(String baseKey, String storageDir) { return JOINER.join( baseKey.isEmpty() ? null : baseKey, storageDir ) + "/index.zip"; }

Target:
we don't know if these were used in extensions, can the things that were public remain so?
Source:
public MappingIterator(Collection<S> source, Function<S, D> transformation) { this.sourceIt = source.iterator(); this.transformation = transformation; readNext(); }

Target:
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>.
Source:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (XWikiAttachment x : (Collection<? extends XWikiAttachment>) c) { if (map.remove(x.getFilename(), x)) { changed = true; } } if (changed) { updatedMap(); } return changed; }

Target:
remove(a,b) is going to use equals which is not right for XWikiAttachment. You should use remove(a) != b instead.
Source:
public void run(String... strings) throws Exception { System.out.println(">>> Starting Audit App... "); }

Target:
@erdemedeiros let's remove all the system outs
Source:
public CollectEnvCommand(FileSystemContext fsContext) { super(fsContext); mCommands = new HashMap<>(); mCommandsAlt = new HashMap<>(); registerCommands(); }

Target:
This is already initialized by super class.
Source:
protected void setBlobStorageService(BlobStorageService blobStorageService) { if (blobStorageService == null) { throw new IllegalArgumentException("BlobStorageService cannot be null"); } else { this.blobStorageService = blobStorageService; logger.trace("BlobStorage service set to {}", blobStorageService.getClass()); } }

Target:
The "else" seems unnecessary
Source:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.setToBeRendered(false); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); }

Target:
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.
Source:
public void setUp() { n = new CacheManagerNotifierImpl(); cl = new CacheManagerListener(); TestingUtil.inject(n, TestingUtil.named(KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR, new WithinThreadExecutor())); n.start(); n.addListener(cl); }

Target:
The executor shouldn't be needed here either
Source:
public char getLabel() { 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; }

Target:
Should be `final char rv;`.
Source:
public ReleasableBytesReference retainedSlice(int from, int length) { BytesReference slice = delegate.slice(from, length); refCounted.incRef(); return new ReleasableBytesReference(slice, refCounted); }

Target:
I would prefer to move this call to the private `ReleasableBytesReference` constructor.
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>(); lio.subscription = source.materialize().subscribe(lio); return lio; } }; }

Target:
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.
Source:
public static MessageType fromId(String id) { for(MessageType current : values()) { if(current.getId().equals(id)) { return current; } } return UNKNOWN; }

Target:
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
Source:
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)); }

Target:
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
Source:
ScriptExecutingMessageSource(AbstractScriptExecutingMessageProcessor<?> scriptMessageProcessor) { this.scriptMessageProcessor = scriptMessageProcessor; }

Target:
Having the Java Config style, it'd better to make this class `public`.
Source:
public void typeInSearchField(String content, int length) { waitForElementVisibleByElement(searchInput); searchInput.sendKeys(content.substring(0, length)); PageObjectLogging.log( "typeInSearchField", "String >>" + content.substring(0, length) + "<< was typed in string field", true ); }

Target:
How come there needs to be a substring for this?
Source:
public Iterable<E> read(Configuration configuration) throws IOException { // TODO: what to do with Configuration? create new view? DatasetReader<E> reader = view.newReader(); return reader; // TODO: who calls close? }

Target:
Inline.
Source:
public void setRefreshInterval(final long refreshInterval) { REFRESH_INTERVAL_IN_SECONDS = refreshInterval; }

Target:
if it is not constant, please convert to lower case?
Source:
public void onNewImageFromCamera() { if (navigator.isSdkAboveOrEqualM() && !navigator.doIHavePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { navigator.askForPermission(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_EXTERNAL_STORAGE_NEW_IMAGE_CAMERA); } else { interactor.createFile(this, CREATE_FILE_TAKE_PHOTO, null); } }

Target:
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.
Source:
public void testEquals() throws Exception { FixedWidthConfiguration conf1 = new FixedWidthConfiguration(1, "UTF8", 10, true, false, true); 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)); }

Target:
Please make sure there are overloaded constructors available for the old constructor signature. Then you also wont have to change this existing test.
Source:
public void showLinkPreview(PageTitle title, int entrySource) { final String linkPreviewFragmentTag = "link_preview_dialog"; if (getSupportFragmentManager().findFragmentByTag(linkPreviewFragmentTag) == null) { linkPreview = LinkPreviewDialog.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), linkPreviewFragmentTag); } }

Target:
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.
Source:
public void clear() { if (loader instanceof CacheStore) try { ((CacheStore) loader).clear(); } catch (CacheLoaderException e) { throw newCacheLoaderException(e); } }

Target:
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
Source:
public ApplicabilityIds getApplicabilityIds() { // TBD - Replace with call to IApplicabilityService calls once implemented ApplicabilityIds ids = new ApplicabilityIds(); // 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; }

Target:
This file needs some work to ensure it works with client.
Source:
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; }

Target:
private?
Source:
protected void addJAROption(Composite comp) { fJarButton = new Button(comp, SWT.CHECK); fJarButton.setText(getJarButtonText()); fJarButton.addSelectionListener(widgetSelectedAdapter(e -> { })); }

Target:
This does not do anything. Can be removed
Source:
public String getTurnDescription( Translation tr ) { if (rawName || !name.isEmpty()) return getName(); return tr.tr("finish"); }

Target:
The additional check is not used in other instructions, is it needed?
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) { throw e; } }

Target:
Catch?
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); } return writer.toString(); }

Target:
Make this as a log.error statement. And needs to have space after the ","
Source:
public TopicStatus(String topic, ConnectorTaskId task, long discoverTimestamp) { //TODO: check non-null this.topic = topic; this.connector = task.connector(); this.task = task.task(); this.discoverTimestamp = discoverTimestamp; }

Target:
How about replacing these four lines with: ``` this(topic, Objects.requireNotNull(task).connector(), task.task(), discoverTimestamp); ``` and then removing the TODO line?
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: return OGCGeometry.createFromEsriGeometry(readEnvelope(input), null); default: throw new IllegalArgumentException("Unexpected type: " + type); } }

Target:
Just add an envelope section to `createFromEsriGeometry` method in this file
Source:
public void close() { sketch = null; }

Target:
Could set `null` to the `values` field too
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(); long memoryAvailableNow = allocator.getLimit() - allocator.getAllocatedMemory() - reserveForOutgoing; 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 }

Target:
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.
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); throw new RuntimeException(errorMsg); } }

Target:
same as above. we shouldn't be throwing run-time exceptions when close is called.
Source:
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, 100); return currentVersion.compareTo(fixVersion) >= 0; }

Target:
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.
Source:
public static boolean isPluginPrefixAndArtifactIdEquals( Plugin p1, Plugin p2 ) { if ( StringUtils.equals( p1.getArtifactId(), p2.getArtifactId() ) && StringUtils.equals( p1.getPrefix(), p2.getPrefix() ) ) { return true; } return false; }

Target:
Why not just: return StringUtils.equals( p1.getArtifactId(), p2.getArtifactId() ) && StringUtils.equals( p1.getPrefix(), p2.getPrefix() );
Source:
public <VT> MessageOut<T> withParameter(ParameterType type, VT value) { List<Object> newParameters = new ArrayList<>(parameters.size() + 3); newParameters.addAll(parameters); newParameters.add(type); newParameters.add(value); return new MessageOut<T>(verb, payload, serializer, newParameters); }

Target:
I think tuple size used to be 3. I'll fix it.
Source:
private boolean validateTimeRange() { boolean isEmpty = fStartTimeRangeText.getText().isEmpty() || fEndTimeRangeText.getText().isEmpty(); return !isEmpty && parseTimeRange() && fStartTimestamp.compareTo(fEndTimestamp) <= 0; }

Target:
should this be < 0? do we want to import a 0 nanosecond range?
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)); filenamePath = filenameBuilder.toString(); return filenamePath; }

Target:
Move filenamePath declaration to this line and make it final
Source:
protected void changeStorageDomainStatusInTransaction(final StoragePoolIsoMap map, final StorageDomainStatus status) { executeInNewTransaction(new TransactionMethod<StoragePoolIsoMap>() { @SuppressWarnings("synthetic-access") @Override public StoragePoolIsoMap runInTransaction() { CompensationContext context = getCompensationContext(); context.snapshotEntityStatus(map, map.getstatus()); map.setstatus(status); getStoragePoolIsoMapDao().updateStatus(map.getId(), map.getstatus()); getCompensationContext().stateChanged(); return null; } }); }

Target:
this line can be removed
Source:
public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { if (tree.expression().is(Tree.Kind.IDENTIFIER)) { IdentifierTree identifier = (IdentifierTree) tree.expression(); final 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); }

Target:
remove `final` modifier.
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); if (SerializationUtil.isClassStaticAndSerializable(remappingFunction)) { BiFunctionExecutingEntryProcessor<K, V> ep = new BiFunctionExecutingEntryProcessor<>(remappingFunction); return executeOnKeyInternal(key, ep); } else { return computeIfPresentLocally(key, remappingFunction); } }

Target:
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.
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); if (tasks.size() == 0) { return; } for (Integer t : tasks) { transfer.transfer(t, tuple); } }

Target:
we don't need this check right. For loop won't enter if tasks are empty. We should avoid having multiple returns.
Source:
AffinityResourceDefinition(PathElement path) { super(path, UndertowExtension.getResolver(Constants.HANDLER, Constants.AFFINITY, path.getValue()), new ReloadRequiredAddStepHandler(), new ReloadRequiredRemoveStepHandler()); }

Target:
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.
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); return null; } finally { lock.unlock(); } }

Target:
throws
Source:
public void testTimeout() throws SystemException, RemoteException { log.info("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); } }

Target:
log.tracef
Source:
public UnstagedComparator(boolean sortAlphabetically) { this.alphabeticallySort = sortAlphabetically; }

Target:
doesn't need to be public
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 (device.getSnapshotId() != null) { isNativeIO = false; } return isNativeIO; }

Target:
So why not just add it to the boolean expression in line #1377?
Source:
public <T> T execute(Request<T> request, IProgressMonitor monitor) throws IOException, GerritException { if (!isAnonymous()) { return execute(request, true, monitor); } return execute(request, false, monitor); }

Target:
Lines 316-319 can be rewritten as return execute(request, !isAnonymous(), monitor);
Source:
public HighlightingInlineHyperlink(final String text, final String token, final String toHighlight) { super(text, token); highlight(text, toHighlight); }

Target:
Maybe highlight should be called from setText instead? That way, if the text is changed after construction it will get highlighted too.
Source:
String serializeInstallCmd(Collection<String> packages) { if (packages.isEmpty()) { return ""; } else { return CommandInfo.CMD_INSTALL + " " + String.join(" ", packages); } }

Target:
Not sure if this is guideline, I would prefer to use `protected` visibility rather than package protected one.
Source:
private List roundtrip(List vals, Map conf) { List ret = null; try { ret = deserialize(serialize(vals, conf), conf); } catch (IOException e) { LOG.error("Exception when serialize/deserialize ", e); } return ret; }

Target:
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.
Source:
public GlobalDirectoryResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.GLOBAL_DIRECTORY), EeExtension.getResourceDescriptionResolver(EESubsystemModel.GLOBAL_DIRECTORY)) .setAddRestartLevel(OperationEntry.Flag.RESTART_JVM) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_JVM) .setAddHandler(GlobalDirectoryResourceDefinition.ADD) .setRemoveHandler(GlobalDirectoryResourceDefinition.REMOVE) .setCapabilities(EE_GLOBAL_DIRECTORY_CAPABILITY) ); }

Target:
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.
Source:
public LockRangeDialog(Shell parentShell, TmfXYChartViewer chartViewer) { super(parentShell); this.fChartViewer = chartViewer; }

Target:
You can remove the this
Source:
public String toStringShort() { return MoreObjects.toStringHelper("") .add("ClientType", getStringFromOptional(mClientType)) .add("ClientHostname", mLocalHostName) .add("ServerAddress", mServerAddress) .add("ChannelId", mChannelId) .omitNullValues() .toString(); }

Target:
I am confused when this is supposed to be "" or `this`?
Source:
public CompilationUnit() { this(null, false, null, new NodeList<>(), new NodeList<>(), null); }

Target:
for the boolean parameter could be useful to use enums, so that it is more clear what it means
Source:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); description = (String) command.getParam(PARAM_DESC); }

Target:
cast is not needed.
Source:
protected void executeQueryCommand() { Provider provider = getDbFacade().getProviderDao().get(getParameters().getId()); NetworkProviderProxy client = getProviderProxyFactory().create(provider); getQueryReturnValue().setReturnValue(client.getAll()); }

Target:
shouldn't provider be validated for existence prior to accessing it?
Source:
public void testCrashlyticsUninitializedOnAnonymousReportDisabled() { Context context = InstrumentationRegistry.getTargetContext(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putBoolean(SettingsActivity.SETTINGS_CRASH_REPORTS, false); editor.clear(); editor.commit(); CrashReporter crashReporter = new CrashReporter(context); assertFalse(crashReporter.initialize()); }

Target:
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.
Source:
protected boolean uniqueInterfaceName(List<VmNetworkInterface> interfaces) { if (!VmHandler.IsNotDuplicateInterfaceName(interfaces, getInterfaceName(), getReturnValue().getCanDoActionMessages())) { return false; } else { return true; } }

Target:
it can be simplified to a single return statement 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, clusterManagerAdapter, discoveryServiceCallback);; return discoveryServiceCallback; }

Target:
typo --> ;;
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); 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); }

Target:
I would change the order to: assertTrue(prevChunk < smallChunk2); assertTrue(smallChunk2 < smallChunk1); assertTrue(smallChunk1 < nextChunk);
Source:
public void shouldSetTempImagesPathAsCompleteDirectory() { URI path = URI.create("/pages/newImagesTemp/"); ConfigCore.setImagesPath(URI.create("/pages/newImagesTemp/")); System.out.println(ConfigCore.getTempImagesPathAsCompleteDirectory()); assertEquals("Temp images path was set incorrectly!", path, URI.create("/pages/newImagesTemp/")); }

Target:
Why did you add this `System.out.println()` call? Maybe a logger is a better solution.
Source:
public MetadataHashAggPOP(@JsonProperty("child") PhysicalOperator child, @JsonProperty("context") MetadataAggregateContext context, @JsonProperty("phase") OperatorPhase phase) { super(child, phase, context.groupByExpressions(), Collections.emptyList(), 1.0F); this.context = context; this.phase = phase; Preconditions.checkArgument(context.createNewAggregations(), "Hash aggregate for metadata collecting should be used only for creating new aggregations."); }

Target:
Please move this check before assigning the variables.
Source:
private void saveProcess(Process process) { try { serviceManager.getProcessService().save(process); } catch (DataException e) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while saving process: " + process.getTitle(), e); logger.error(KITODO_SCRIPT_FIELD + "Error while saving process: " + process.getTitle(), e); } }

Target:
Please first log the error and then inform the user.
Source:
private String toHexString(QuantileDigest qdigest) { return new SqlVarbinary(qdigest.serialize().getBytes()).toString().replaceAll("\\s+", " "); }

Target:
private static
Source:
public String getHeader(){ return selectedPageHeader.getText(); }

Target:
this should be private method
Source:
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) { String userModelAttrName = getUserModelAttribute(); String attributeValue = getAttributeValue(); Property<Object> userModelProperty = userModelProperties.get(userModelAttrName.toLowerCase()); if (userModelProperty != null) { checkDuplicateEmail(userModelAttrName, attributeValue, realm, ldapProvider.getSession(), user); setPropertyOnUserModel(userModelProperty, user, attributeValue); } else { user.setAttribute(userModelAttrName, Arrays.asList(attributeValue)); } }

Target:
Does it have any sense to check for duplicated email here? IMO I am not seeing much sense to have hardcoded username or email same for all users? So I would just delete this line and also completely delete the methods "checkDuplicateEmail" and "checkDuplicateUsername" . And you can instead implement method on the HardcodedAttributeMapperFactory "validateConfiguration" and throw an error in case that "username" or "email" was configured as user model attribute.
Source:
public Boolean delete( ProjectName projectName ) { return callWithContext( () -> { final Boolean result = doDelete( projectName ); LOG.info( "Project deleted: " + projectName ); return result; } ); }

Target:
boolean instead of Boolean
Source:
public static void startServerInstance(File dataDir, ServerCnxnFactory factory, String hostPort) throws IOException, InterruptedException, KeeperException.NoNodeException { final int port = getPort(hostPort); LOG.info("STARTING server instance 127.0.0.1:{}", port); ZooKeeperServer zks = new ZooKeeperServer(dataDir, dataDir, 3000); factory.startup(zks); Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp( "127.0.0.1:" + port, CONNECTION_TIMEOUT, factory.isSecure())); }

Target:
this isn't needed anymore right?
Source:
public void shouldShowAllMusicsAsHTTP() { MockHttpResult mockHttpResult = new MockHttpResult(); controller = new MusicController(dao, userInfo, mockHttpResult, validator, musics); when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsHTTP(); assertEquals("<p class=\"content\">"+ Arrays.asList(music).toString()+"</p>", mockHttpResult.getBody()); }

Target:
If you want, you can change to use hamcrest here too. The method `Matchers.is` compare if two objects are equals.
Source:
public AttributeValueSearch(IAttributeType attributeType, String attributeValue) { this.attributeType = attributeType; this.attributeValue = attributeValue; Conditions.checkNotNull(attributeType, "attributeType"); Conditions.checkNotNullOrEmpty(attributeValue, "attributeValue"); }

Target:
wouldn't you want the conditions check prior to assignments?
Source:
public ListenerContainerIdleEvent(Object source, long idleTime, @Nullable String id, String... queueNames) { super(source); this.idleTime = Duration.ofMillis(idleTime); this.listenerId = id; this.queueNames = Arrays.asList(queueNames); }

Target:
What made you to wrap, when you still use a simple long afterwards?
Source:
public static XARecoveryModule getRegisteredXARecoveryModule () { if (registeredXARecoveryModule == null) { RecoveryManager recMan = RecoveryManager.manager(); Vector recoveryModules = recMan.getModules(); if (recoveryModules != null) { Enumeration modules = recoveryModules.elements(); while (modules.hasMoreElements()) { RecoveryModule m = (RecoveryModule) modules.nextElement(); if (m instanceof XARecoveryModule) { registeredXARecoveryModule = (XARecoveryModule) m; } } } } return registeredXARecoveryModule; }

Target:
you should break out of the loop early after finding the target module
Source:
public String getUrl() { return PluginImpl.getInstance().getServer(serverName).getConfig().getGerritFrontEndUrlFor(tEvent); }

Target:
possible NPE
Source:
public void testBoundarySignalProcessInstance() throws Exception { Long processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_BOUNDARY_SIGNAL_PROCESS); assertNotNull(processInstanceId); assertTrue(processInstanceId.longValue() > 0); try { checkAvailableBoundarySignals(CONTAINER_ID, processInstanceId); } catch (Exception e){ processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); e.printStackTrace(); fail(e.getMessage()); } }

Target:
Please move abortProcessInstance into the final statement, it should be done in any case. Also please delete e.printStackTrace(); - it doesn't bring any value. Also please delete fail(e.getMessage()); - unexpected exceptions should be thrown out of test method, JUnit will handle it as a failing test, printing exception with stacktrace to the log.
Source:
private void validateAppConfig(String fileName) throws Exception { String appsDir = getAppsDirectory(); if (appsDir.equalsIgnoreCase("apps") && !isAppConfiguredInSourceServerXml(fileName)) { // add application configuration applicationXml.createWebApplicationElement(fileName); } else if (appsDir.equalsIgnoreCase("dropins") && isAnyAppConfiguredInSourceServerXml()) throw new MojoExecutionException(messages.getString("error.install.app.dropins.directory")); }

Target:
why not calling isAppConfiguredInSourceServerXml(fileName) to make sure the app installed to the dropins location is not configured?
Source:
static RequestContextDataHolder getRequestContext(Context ctx) { return ctx.getOrDefault(REQUEST_CONTEXT_DATA_HOLDER, null); }

Target:
Please add `private` modifier
Source:
public long getNumberOfImagesInStorageDomain(Guid storageDomainId) { MapSqlParameterSource params = getCustomMapSqlParameterSource().addValue("storage_domain_id", storageDomainId); return getCallsHandler().executeRead("GetNumberOfImagesInStorageDomain", getLongMapper(), params); }

Target:
I'd inline this to conform with the rest of the class.
Source:
public TestObjectAsync() { try { Thread.sleep(100); Thread.sleep(100); counter = 1; } catch (InterruptedException ie) { throw new RuntimeException(ie); } }

Target:
Is it really necessary to wait 100 milliseconds? Why not `Thread.sleep(1)`. Why not `Thread.yield()`?
Source:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); return field != null ? field.getAnnotationsByType(Optional.class).length > 0 || beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0 : beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0; }

Target:
Maybe `beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0` should be checked before calling getField ? Method getField modifies field via reflection and optionally recursively calls itself, so it could be costly.
Source:
public int getImageselector () { return imageSelectorIndex; }

Target:
Why is this method required? Didn't see it used anywhere in the code
Source:
public InputStream getInputStream(FileHeader entry) throws IOException { if (entry == null) { return null; } InputStream inputStream = getEntryData(entry).getInputStream(); if (entry.getMethod() == ZipEntry.DEFLATED) { inputStream = new ZipInflaterInputStream(inputStream, new Inflater(true), (int) entry.getSize()); } return inputStream; }

Target:
I don't think we want to pass in an `Inflater` and than have `ZipInflaterInputStream` call `end()` on it.
Source:
private org.eclipse.swt.graphics.Image createImage() { org.eclipse.swt.graphics.Image newImage; RenderedImage image = renderManager.getImage(); this.backBufferTrsf=renderManager.getMapInternal().getViewportModel().worldToScreenTransform(); if (image != null) newImage = AWTSWTImageUtils.createSWTImage(image, false); else { newImage = new Image(getDisplay(), getWidth(), getHeight()); } return newImage; }

Target:
Can you explain the idea behind storing transformation here and not anywhere else (at the very beginning of repaint())? Is it worth to keep this information and to compare it within getDoubleBufferGraphics() rather using the up-to-date viewportModel Transformation. is it because of a non-atomar opration betwenn getImage() and getDoubleBufferGraphics() calls?
Source:
public VirtualMachine getCurrentMachineBuild(ITmfEvent event) { VirtualMachine machine = innerGetCurrentMachine(event); if (machine == null) { synchronized (fStateSystem) { String hostId = event.getTrace().getHostId(); machine = createMachine(fStateSystem, event.getTimestamp().toNanos(), hostId, event.getTrace().getName()); fKnownMachines.put(hostId, machine); } } return machine; }

Target:
this is nullable