auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static AbstractTaskContextStore loadTaskContextStore() { ExtensionPointReader<AbstractTaskContextStore> reader = new ExtensionPointReader<AbstractTaskContextStore>( ITasksCoreConstants.ID_PLUGIN, "contextStore", "contextStore", AbstractTaskContextStore.class); //$NON-NLS-1$ //$NON-NLS-2$ IStatus status = reader.read(); if (!status.isOK()) { StatusHandler.log(status); } AbstractTaskContextStore contextStore = reader.getItem(); if (contextStore != null) { return contextStore; } return new DefaultTaskContextStore(); }

Target:
This already happens inorg.eclipse.mylyn.commons.core.ExtensionPointReader.handleResult(IStatus)
Source:
public void sendMessage(String message) { buffer.append(message + "\n"); }

Target:
That's not how you use a StringBuffer though. `buffer.append(message).append("\n");` PS: Wrong ping.
Source:
private void updateStatusOfPushMessageInformation(final PushMessageInformation pushMessageInformation, final String variantID, final int receivers, final Boolean deliveryStatus, final String reason) { final VariantMetricInformation variantMetricInformation = new VariantMetricInformation(); variantMetricInformation.setPushMessageInformation(pushMessageInformation); variantMetricInformation.setVariantID(variantID); variantMetricInformation.setReceivers(receivers); variantMetricInformation.setDeliveryStatus(deliveryStatus); variantMetricInformation.setReason(reason); pushMessageInformation.getVariantInformations().add(variantMetricInformation); dispatchVariantMetricEvent.fire(variantMetricInformation); }

Target:
This is a reason why I got 2 receivers.. The variant information is added to PushMessageInformation in the `MetricCollector#updateExistingMetric`: https://github.com/matzew/aerogear-unifiedpush-server/blob/AGPUSH-1374/push/sender/src/main/java/org/jboss/aerogear/unifiedpush/message/MetricsCollector.java#L66 Since it is already added in the `NotificationDispatcher`, it re-adds "existing" variant metric. By removing this line it starts to work correctly
Source:
public void createActions() { setGoalOrderAction = new SetGoalOrderAction((GoalArtifact) editor.getAwa(), this); RemovedFromGoalHandler handler = new RemovedFromGoalHandler() { @Override public void removedFromGoal(Collection<? extends Artifact> removed) { worldComposite.removeItems(removed); worldComposite.getXViewer().remove(removed); worldComposite.getXViewer().refresh(goalArtifact); } }; removeFromGoalAction = new RemoveFromGoalAction((GoalArtifact) editor.getAwa(), this, handler); }

Target:
private
Source:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } client.connectionPool().evictAll(); if (client.connectionPool().connectionCount() > 0) { // Minimise test flakiness due to possible race conditions with connections closing. // Some number of tests will report here, but not fail due to this delay. System.out.println("Delaying to avoid flakes"); Thread.sleep(500L); System.out.println("After delay: " + client.connectionPool().connectionCount()); } }

Target:
Move this to `OkHttpClientTestRule.ensureAllConnectionsReleased()`
Source:
public void addQueueNames(String... queueNames) { try { addQueues(Arrays.stream(queueNames)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + queueNames, e.getCause()); } super.addQueueNames(queueNames); }

Target:
Or `Arrays.toString`
Source:
protected void buildScript(int age) { // hard-coded list of card types to load when continuing the feed if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); addPendingClient(new RandomClient(new RandomCard(getContext(), getSite()))); }

Target:
This kind of breaks the really clean streak of "new Client()" calls with no arguments. Could we make it adhere to this pattern?
Source:
private UpdateAccountResponse updateAccount(URL updateAccountUrl, String requestBody) throws Exception { RealmLog.debug("Network request (updateAccount): " + updateAccountUrl); Request request = newAuthRequest(updateAccountUrl) .post(RequestBody.create(JSON, requestBody)) .build(); RealmLog.error(updateAccountUrl.toString()); RealmLog.error(requestBody); Call call = client.newCall(request); Response response = call.execute(); return UpdateAccountResponse.from(response); }

Target:
debugging logging? if not the level should be `log` not `error`
Source:
public ListObjectStream(List<T> items) { this.items = items; this.i = 0; }

Target:
does not need to be public in non-public class
Source:
private void closeGroups(hdf5.Group[] groupArray) { for (int i = 0; i < groupArray.length; i++) { groupArray[i].deallocate(); } }

Target:
Haha, fair enough.
Source:
public void writeTo(ObjectOutput output) throws IOException { output.writeObject(ackTarget); if (ackTarget != null) { output.writeLong(id); } output.writeInt(topologyId); if (keys != null) { MarshallUtil.marshallCollection(keys, output); } else { assert segments != null; MarshallUtil.marshallIntCollection(segments, output); } }

Target:
`marshallCollection` handles `null`
Source:
public static ModelPlotConfig createRandomized() { return new ModelPlotConfig(randomBoolean(), randomAlphaOfLengthBetween(1, 30), randomBoolean()); }

Target:
Would be good to have a `null` case here for `annotationsEnabled`
Source:
boolean deregisterHardDeleteMetric(String storeId) { String prefix = storeId + SEPERATOR; return registry.remove(MetricRegistry.name(PersistentIndex.class, prefix + "CurrentHardDeleteProgress")) && registry .remove(MetricRegistry.name(Log.class, prefix + "PercentageHardDeleteCompleted")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteThreadRunning")) && registry.remove( MetricRegistry.name(PersistentIndex.class, prefix + "HardDeleteCaughtUp")); }

Target:
this function can be `private`
Source:
public void dispose() { this.runInControlledConcurrency(() -> { log.info("IrsProxyData::disposing"); resetIrs(); getSchedulUtil().deleteJob(storagePoolRefreshJobId); getSchedulUtil().deleteJob(domainRecoverOnHostJobId); _disposed = true; }); }

Target:
no need for 'this'
Source:
public boolean isEnabled() { return selectionMapsToSingleRepository(); }

Target:
This is also a regression, it no longer works for multiple repositories. Note that there is extra code below which handles multiple repositories.
Source:
private void eventuallyAssertEvictions(float expectedValue) { eventuallyAssertAttributeValue("Evictions", expectedValue); assert expectedValue == advanced.getStats().getEvictions(); }

Target:
When updating code can you replace plain asserts with those from the testing framework ?
Source:
public static boolean isNumber(Class<?> clazz) { if ( clazz == null ) { return false; } else if ( clazz.isPrimitive() ) { return NUMBER_TYPES.contains( clazz ); } else { return Number.class.isAssignableFrom( clazz ); } }

Target:
These seem to be covered by `NUMBER_TYPES` already?
Source:
public List<Connection> getTransitivelyConnectedElements(EObject element, EObject traceModel, int maximumDepth) { ArrayList<Object> accumulator = new ArrayList<>(); return getTransitivelyConnectedElements(element, traceModel, accumulator, DEFAULT_INITIAL_TRANSITIVITY_DEPTH, maximumDepth); }

Target:
Should be of type List<Object>.
Source:
public final CompletableFuture<Void> enterSynchronizationAsync(CompletableFuture<Void> releaseFuture) { while (true) { CompletableFuture<Void> currentFuture = synchronization.get(); if (synchronization.compareAndSet(currentFuture, releaseFuture)) return currentFuture; } }

Target:
a `do-while` will avoid checking 2 conditions (the while true and the CAS)
Source:
public ReferenceCounter referenceCounter() { return new ReferenceCounter() { @Override public boolean increment() { return ReferenceCountingSegment.this.increment(); } @Override public Closeable decrementOnceCloseable() { return ReferenceCountingSegment.this.decrementOnceCloseable(); } @Override public void decrement() { ReferenceCountingSegment.this.decrement(); } }; }

Target:
Make `ReferenceCountingSegment` implement `ReferenceCounter`. Then this function can just be `return this;` Which also means less inner classes and less lines of code to read in a delta 🙃
Source:
public void connectionDown() { for (Object listenerObject : coordinateListenerList.toArray()) { CoordinateListener coordinateListener = (CoordinateListener) listenerObject; coordinateListener.onCoordinateEvent( CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, "down"); } isSynchronizedWithZooKeeper.set(false); }

Target:
toArray copies the elements of the list into an array I think. Might depend on the implementation, but there are better ways to loop this. It also seems to lose type information.
Source:
public void addLocation(long blockId, BlockLocation location) { mBlockLocations.computeIfAbsent(blockId, x -> new HashMap<>()); mBlockLocations.get(blockId).put(location.getWorkerId(), location); }

Target:
What is the initial size of this `HashMap`?
Source:
public String getName() { return getHeader(Constants.BUNDLE_NAME) != null ? bundle.getHeaders().get(Constants.BUNDLE_NAME) : getSymbolicName(); }

Target:
You can re-use your `getHeader(...)` method - which I very much like - here?
Source:
public MojoParameterMetadataProvider(MavenProject project, Plugin plugin) { this.project = project; this.plugin = plugin; maven = (MavenImpl) MavenPlugin.getMaven(); parameters = new HashMap<String, List<MojoParameter>>(); }

Target:
please use diamond operator, i.e. "<>", instead of type parameters. reduces clutter and makes code easier to maintain.
Source:
protected void onPostExecute(OEmbed embed) { if (embed != null) { // TODO: decide if this is ok. Most likely because the setStep // function isnt intensive if(!isCancelled()) { mMainWebView.loadUrl(mStep.getEmded().getOembed().getURL()); mMainWebView.setTag(mStep.getEmded().getOembed().getURL()); } } }

Target:
Let's make this DRY. ``` String url = mStep.getEmded().getOembed().getURL(); mMainWebView.loadUrl(url); mMainWebView.setTag(url); ```
Source:
public int read(int offset, int[] positions, int positionCount) { outputPositions = initializeOutputPositions(outputPositions, positions, positionCount); outputPositionCount = positionCount; return outputPositionCount; }

Target:
outputPositionCount variable is not used; remove it `return positionCount;`
Source:
public void start(BootstrapContext ctx) throws ResourceAdapterInternalException { if (engine == null) { engine = new ModeShapeEngine(); engine.start(); } }

Target:
This method should probably be `synchronized`.
Source:
public String getValue() { return name().toLowerCase(); }

Target:
wouldn't it be preferred to store the value of each type in lower case instead of creating it each time this method invoked ?
Source:
public boolean start() { if (!started.get()) { LOGGER.info("started polling lookup [%s]", id); started.set(pollingLookup.isOpen()); } return started.get(); }

Target:
should be made such that start and stop cannot be called at the same time
Source:
public void tearDown(final ManagementClient managementClient, final String containerId) { // TODO: add {"allow-resource-service-restart" => true} to ejbRemoteAddress write-attribute operation once WFLY-8793 / JBEAP-10955 is fixed // and remove this reload try { ServerReload.reloadIfRequired(managementClient.getControllerClient()); } catch (Exception e) { throw new RuntimeException(e); } // TODO: remove this reload once WFLY-8821 / JBEAP-11074 is fixed try { ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), domainAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), realmAddress, false); }

Target:
This should be probably moved after following applyRemoveAllowReload.
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((section == null) ? 0 : section.hashCode()); result = prime * result + ((subsection == null) ? 0 : subsection.hashCode()); return result; }

Target:
I think its OK to assume section != null here.
Source:
private List<ProjectInfo> list(final ListRequest request) throws RestApiException { ListProjects lp = listProvider.get(); lp.setShowDescription(request.getDescription()); lp.setLimit(request.getLimit()); lp.setStart(request.getStart()); lp.setMatchPrefix(request.getPrefix()); Map<String, ProjectInfo> result = lp.apply(); return ImmutableList.copyOf(result.values()); }

Target:
I think List is fine.
Source:
public void testGetItemId() { Long expected = CoreArtifactTokens.OseeTypesFolder.getId(); Long actual = item.getItemId().getId(); assertEquals(expected, actual); }

Target:
replace with this 1 line: assertEquals(oreArtifactTokens.OseeTypesFolder, item.getItemId());
Source:
public void onDestroyView() { super.onDestroyView(); ((PageActivity)getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); app.getBus().unregister(this); }

Target:
I would put this in on Pause
Source:
public GroupScan clone(List<SchemaPath> columns) { logger.debug("HttpGroupScan clone {}", columns); HttpGroupScan newScan = new HttpGroupScan(this); newScan.columns = columns; return newScan; }

Target:
Better to have a constuctor that takes a `HttpGroupScan` and the list of columns. That way, the `columns` member can be `final` and the class can be immutable.
Source:
private void executeUpdate(String sql) { try { Statement statement = this.connection.createStatement(); statement.executeUpdate(sql); statement.close(); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
`finally` here?
Source:
private void buildDependenciesMap(@NotNull Module module, @NotNull Collection<VirtualFile> erlangModules, @NotNull List<String> globalParseTransforms) { for (VirtualFile erlangModule : erlangModules) { Set<String> dependencies = ContainerUtil.newHashSet(); ErlangFile erlangFile = getErlangFile(erlangModule); addDeclaredDependencies(module, erlangFile, dependencies); dependencies.addAll(resolvePathsFromNames(globalParseTransforms, module)); myPathsToDependenciesMap.put(erlangModule.getPath(), ContainerUtil.newArrayList(dependencies)); } }

Target:
There is no need to resolve these paths on every iteration - you only need it resolved once. Moreover, you can resolve it once one level above, passing resolved parse transforms to this method.
Source:
public void createFeaturesTest() throws IOException { String[] tokens = new String[] {"he", "went", "with", "you"}; AdaptiveFeatureGenerator generator = new BrownBigramFeatureGenerator(brownCluster); List<String> features = new ArrayList<>(); generator.createFeatures(features, tokens, 3, null); Assert.assertEquals(2, features.size()); Assert.assertTrue(features.contains("pbrowncluster,browncluster=0101,0010")); Assert.assertTrue(features.contains("pbrowncluster,browncluster=01010,00101")); }

Target:
This line can be moved up to the @Before method too.
Source:
public void getRelatedNoResult() throws Exception { PushOneCommit push = pushFactory.create(db, admin.getIdent()); PatchSet.Id ps = push.to(git, "refs/for/master").getPatchSetId(); List<ChangeAndCommit> related = getRelated(ps); assertThat(related.size()).isEqualTo(0); }

Target:
assertThat(related).isEmpty();
Source:
protected void destroyVm() { boolean vmMigrating = getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null; setActionReturnValue(vmMigrating ? destroyMigratingVm() : destroyNonMigratingVm()); managedBlockStorageCommandUtil.disconnectManagedBlockStorageDisks(getVm(), vmHandler, getVdsId()); }

Target:
This should be moved to: ProcessDownVmCommand
Source:
public void testParseDateFailed() { try { CommonUtils.parseFromUtcTime("this is obviously not a date"); fail("Parsing date should never be successfull here"); } catch (ParseException e) { } }

Target:
You may be able to simplify this test case through JUnit4 annotations, with the `@Expected`
Source:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { // never happens } return "<unknown:" + oid + ">"; }

Target:
@vlsi performance issues with using foreach ??
Source:
public List<Patient> getDuplicatePatientsByAttributes(List<String> attributes) throws APIException { if (attributes == null || !attributes.isEmpty()) { throw new APIException("Patient.no.attribute", (Object[]) null); } return dao.getDuplicatePatientsByAttributes(attributes); }

Target:
Are you sure you did the above line correctly? :)
Source:
private int countOccurrencesInTopology(final String topologyString, final String searchPattern) { final Matcher matcher = Pattern.compile(searchPattern).matcher(topologyString); final List<String> repartitionTopicsFound = new ArrayList<>(); while (matcher.find()) { repartitionTopicsFound.add(matcher.group()); } return repartitionTopicsFound.size(); }

Target:
likewise, this one can be static
Source:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username= "anyUser"; //mocks when(userRepository.findUser(anyString())).thenReturn(null); //Test passwordResetService.resetUserPassword(username); Assert.assertNotNull(userRepository.findUser(username)); verify(userRepository).findUser(username); verify(passwordResetService).resetUserPassword(username); }

Target:
@tumijacob I don't think that these verifies are ever called since the method call above should throw.
Source:
public void run() { log.info(Thread.currentThread().getName() + " is starting DFS"); try { frontier.searchForScenarios(queue, flag); } catch (IOException e) { e.printStackTrace(); } log.info(Thread.currentThread().getName() + " is done with DFS"); }

Target:
Don't use printStackTrace() and instead write to the logger using log.error("<Appropriate message>",e);
Source:
public BusinessServiceGraph getGraph() { m_rwLock.readLock().lock(); try { return m_g; } finally { m_rwLock.readLock().unlock(); } }

Target:
Can we return a copy of the graph instead of a reference? There's also no point in using a read lock when returning the reference. I'm mostly worried that callers may alter the graph in some way.
Source:
public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of( new Object[]{LockGranularity.TIME_CHUNK, false}, new Object[]{LockGranularity.TIME_CHUNK, true}, new Object[]{LockGranularity.SEGMENT, false}, new Object[]{LockGranularity.SEGMENT, true} ); }

Target:
This is a relatively slow test (~15 seconds per parameterized run), so all the permutations may be overkill. Perhaps remove (SEGMENT, false), which will still give coverage of both lock granularities and both with/without the input format API.
Source:
public static ByteBuffer handleBufferUnderflow(final SSLEngine engine, ByteBuffer buffer) { if (buffer.position() < buffer.limit()) { return buffer; } ByteBuffer replaceBuffer = enlargeBuffer(buffer, engine.getSession().getPacketBufferSize()); buffer.flip(); replaceBuffer.put(buffer); return replaceBuffer; }

Target:
Add `Preconditions.checkArgument` checks to verify that the passed `engine` and `buffer` are not `null`.
Source:
public void givenIdenticalSimpleObjects_whenCompared_thenEqual() { JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; String string2 = "{\"customer\": {\"id\": \"44521\", \"fullName\": \"Emily Jenkins\",\"age\": 27}}"; Assert.assertTrue(parser.parse(string1) .isJsonObject()); Assert.assertEquals(parser.parse(string1), parser.parse(string2)); }

Target:
Let's static import the assertions inside `org.junit.Assert` so we don't need to prefix them with `Assert.`
Source:
public TitleMatchingContainerScorer(double exactTitleMatchScore) { this.scorer = new ContentTitleScorer<>( NAME, Functions.<String>identity(), Score.valueOf(exactTitleMatchScore), Score.ONE ); }

Target:
```suggestion this(Score.valueOf(exactTitleMatchScore), Score.ONE); ```
Source:
public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { boolean retry = false; try { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; switch (response.getStatusCode()) { case 500: case 503: retry = super.shouldRetryRequest(command, response); break; default: break; } } finally { releasePayload(response); } return retry; }

Target:
Message seems to be unused. Remove this line?
Source:
public static void addRecoveryListenerIfNecessary(Channel channel) { if (channel instanceof ChannelProxy) { if (((ChannelProxy) channel).getTargetChannel() instanceof AutorecoveringChannel) { AutorecoveringChannel autorecoveringChannel = (AutorecoveringChannel) ((ChannelProxy) channel) .getTargetChannel(); if (hasListener.putIfAbsent(autorecoveringChannel, Boolean.TRUE) == null) { autorecoveringChannel.addRecoveryListener(INSTANCE); } } } }

Target:
Don't we need to deal with an `else` variant as well? On the other hand why `ChannelProxy` can't implement `AutorecoveringChannel` and delegate respectively? Although I believe there is going to be some overhead since we may disable auto-recovery, but we still fill up this cache almost for nothing...
Source:
public DelegatingTemplateEngine(final CompositeConfiguration config, final ContentStore db, final File destination, final File templatesPath) { super(config, db, destination, templatesPath); this.renderers = new TemplateEngines(config, db, destination, templatesPath); this.registerExtractorsForCustomTypes(); }

Target:
Was thinking about this.... could this call happen when other types are registered by Oven in DocumentTypes or was there a specific reason this occurs here?
Source:
NavigableSet<Clustering> makeClusterings(boolean reversed) { int pos = 0; NavigableSet<Clustering> clusterings = new TreeSet<>(reversed ? metadata.comparator.reversed() : metadata.comparator); while (pos <= KEY_RANGE) { int skip = rand.nextInt(KEY_RANGE / 10) * (rand.nextInt(3) + 2 / 3); // increased chance of getting 0 pos += skip; clusterings.add(clustering(pos)); } return clusterings; }

Target:
Nit: can be private
Source:
public Optional<String> getExtension() { return Optional.fromNullable(extension); }

Target:
Each of the getters in a POJO like this should have the same return type as the private member variables they expose. In this case, I'd recommend having `extension`, `dateformat`, and `frequencyOverride` be `Optional<>`s (in both their member variable types and their getter types). Our Jackson YAML deserialization should automatically take care of setting a missing field to an empty `Optional<>` in the resulting Java object.
Source:
@Test public void constructor_nullDelegate() { try { new ForwardingOs(null) { }; fail(); } catch (NullPointerException expected) { } }

Target:
Newline between @Test and public. There's only 4 instances like this in the libcore source, hundreds with it on its own line.
Source:
public boolean visitEnter(FunctionParseNode node) throws SQLException { // TODO: Oracle supports nested aggregate function while other DBs don't. Should we? if (node.isAggregate()) { if (aggregateFunction != null) { throw new SQLFeatureNotSupportedException("Nested aggregate functions are not supported"); } this.aggregateFunction = node; this.isAggregate = true; } else if(node.getClass().isAssignableFrom(ArrayIndexFunction.class)) { this.isAggregate = true; } return true; }

Target:
Remove this change please
Source:
public int hashCode() { return Objects.hash(baseDataSource + dimensions + metrics); }

Target:
Probably `Objects.hash(baseDataSource, dimensions, metrics);`?
Source:
public boolean registerIfNew(String name, AsyncHttpClient ahc) { AsyncHttpClient value = asyncHttpClientMap.putIfAbsent(name, ahc); if (value == null) return true; else return false; }

Target:
`return asyncHttpClientMap.putIfAbsent(name, ahc) == null;
Source:
public Node getContextNode() { return getLibraryNode() != null || getParent() == null ? this : org.raml.yagi.framework.util.NodeUtils.getContextNode(getParent()); }

Target:
You can replace the qualified name with import
Source:
private void getLazyRoutingConfig() { ImportHelper.loadRoutingFiles(app, new ImportHelper.LoadRoutingFilesCallback() { @Override public void onRoutingFilesLoaded() { notifyEvent(InitEvents.ROUTING_CONFIG_INITIALIZED); } }); }

Target:
Do not move it to ImportHelper
Source:
public <T> T toObject(ParameterizedTypeReference<T> type) { Assert.notNull(type, "Target type must not be null!"); final String url = traverseToFinalUrl(true); return operations.exchange(url, GET, prepareRequest(headers), type).getBody(); }

Target:
Doesn't need to be final.
Source:
public ValidationResult validateMacAddress(List<? extends VmNic> vmNics) { for (VmNic iface : vmNics) { String str = iface.getMacAddress(); if (str != null) { if (!VALIDATE_MAC_ADDRESS.matcher(iface.getMacAddress()).matches()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_NETWORK_INTERFACE_MAC_INVALID, String.format("$IfaceName %1$s", iface.getName()), String.format("$MacAddress %1$s", iface.getMacAddress())); } } } return ValidationResult.VALID; }

Target:
please inline this variable
Source:
public List<AuditLogWithHistory> getAuditLogsWithHistoryForId(final UUID accountId, final AuditLevel auditLevel, final InternalTenantContext context) throws AccountApiException { return transactionalSqlDao.execute(false, AccountApiException.class, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws EntityPersistenceException, EventBusException { final AccountSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT, accountId, auditLevel, context); } }); }

Target:
`true` instead (it's a read-only operation).
Source:
public void run() { while (true) { updateTraceEntry(fTimeAnalysisEntry, Long.MAX_VALUE, fRange.getStartTime().toNanos(), fRange.getEndTime().toNanos()); synchronized (fProcessTraceThreads) { if (fRestart) { fRestart = false; } else { fProcessTraceThreads.remove(fTimeAnalysisEntry.getTrace()); break; } } } }

Target:
should this be return?
Source:
public final Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable { try { if (hasSkipLocking(command)) { return invokeNextInterceptor(ctx, command); } lockAllAndRecord(ctx, Arrays.stream(command.getKeys()), getLockTimeoutMillis(command)); return invokeNextInterceptor(ctx, command); } finally { if (!ctx.isInTxScope()) { lockManager.unlockAll(ctx); } } }

Target:
Wouldn't `Arrays.asList()` be enough here? `Arrays.stream` seems to have a lot of memory overhead.
Source:
public GeographyPointValue(double longitude, double latitude) { // Add 0.0 to avoid -0.0. m_latitude = latitude + 0.0; m_longitude = longitude + 0.0; if (m_latitude < -90.0 || m_latitude > 90.0) { throw new IllegalArgumentException("Latitude out of range in GeographyPointValue constructor"); } if (m_longitude < -180.0 || m_longitude > 180.0) { throw new IllegalArgumentException("Longitude out of range in GeographyPointValue constructor"); } }

Target:
This seems esoteric. What's wrong with -0.0 here?
Source:
public final static AttachmentSizeFormatter getInstance() { try { return new AttachmentSizeFormatter(); } catch (ClassCastException e) { return new AttachmentSizeFormatter(Locale.ENGLISH); } }

Target:
should we not just always use Locale.English? Based on the formats we give it I'm not sure what effect other locales would actually ever have.
Source:
private static void initOculus() { switch (LWJGLUtil.getPlatform()) { case LWJGLUtil.PLATFORM_WINDOWS: OculusVrHelper.loadNatives(); break; } }

Target:
You can just do an if statement here. :)
Source:
private void copyTimestampsFromChangelog(Library library) { Date earliest = getEarliestChangeDate(library); Date latest = getLatestChangeDate(library); library.setCreationDate(earliest); }

Target:
Unused
Source:
protected ProjectUploadController createProjectUploadController() { if (projectUploadController == null) { projectUploadController = mock(ProjectUploadController.class); } return projectUploadController; }

Target:
since this happens in every test as the first thing, this probably should be in setUp(). at least the SharedPreferences call should be moved there. and i rather have the code duplication of having the two espresso clicks in each test, than this. before looking up what the method really does i suspected anything, but two clicks on "next" in it when reading the tests above.
Source:
public long getFilterBlobLimit() { return filterSpec.getBlobLimit(); }

Target:
I think we can keep this "final".
Source:
public static IRemoteConnection createConnection(URI hostUri, String hostName) throws RemoteConnectionException { IRemoteConnection connection = null; IRemoteConnectionType connectionType = getConnectionType(hostUri); IConnectionFactory connectionFactory = CONNECTION_FACTORIES.get(connectionType.getId()); // Create a new connection if (connectionFactory != null) { connection = connectionFactory.createConnection(hostUri, hostName); } else { connection = DEFAULT_CONNECTION_FACTORY.createConnection(hostUri, hostName); } return connection; }

Target:
You could set connectionFactory to default, and then create the connection in the return statement.
Source:
protected boolean canDoAction() { StorageServerConnectionExtension conn = getParameters().getStorageServerConnectionExtension(); return validate(getConnectionExtensionValidator().isConnectionExtensionExists(conn.getId())) && validate(getConnectionExtensionValidator().isConnectionDoesNotExistForHostAndTarget(conn.getHostId(), conn.getIqn())); }

Target:
I'd do this in the previous patch already.
Source:
public void setObservationLevel(final String observationLevel) { final Integer datasetTypeId = DatasetTypeEnum.getIdByName(observationLevel); if(datasetTypeId > 0) { this.observationLevel = Integer.toString(datasetTypeId); } else { this.observationLevel = observationLevel; } }

Target:
I think this logic should reside elsewhere, a service or controller class. A DTO usually only has properties with getters and setters. Make sure as well to have a unit test for this logic.
Source:
protected IStatus run(IProgressMonitor monitor) { while (!monitor.isCanceled()) { try { Thread.sleep(INDEXING_THREAD_SLEEP_VALUE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } monitor.done(); return Status.OK_STATUS; }

Target:
won't exit the loop. You need to return here
Source:
public void handleClose(CloseEvent event, List<DashboardPanel> panels) { String id = event.getComponent().getId(); for (DashboardPanel panel : panels) { if (panel.getType().replace(" ", "_").toLowerCase(Locale.ENGLISH).equals(id)) { panel.close(); break; } } }

Target:
Why can't we use id.equalIgnoreCase check instead of the other way around? This option is more flexible than hard code English locale
Source:
public LoggerServiceImpl() { actions.put( "log-record", new Runnable() { @Override public void run() { logrecord(); } } ); }

Target:
so you do not need default constructor now, night?
Source:
public void setMaxRowSize(int rowSize) { if (maxRowSize == -1) { maxRowSize = rowSize; } else { if (maxRowSize < rowSize) { maxRowSize = rowSize; } } }

Target:
if rowsize is always positive the check for -1 is not necessary
Source:
public InodeLockList() { mInodes = new ArrayList<>(); mLockModes = new ArrayList<>(); }

Target:
is this change no longer necessary?
Source:
public void testBuildBlobId() throws Exception { for (Short version : versions) { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); } }

Target:
if most of you test cases runs for both version, why not go our usual route of parametrized args.
Source:
private String resolveRelativeModulePath(String url) { File f = new File(url); if (!f.isAbsolute()) if (repo.isBare()) { url = new File(repo.getDirectory(), url).getAbsolutePath(); } else { url = new File(repo.getWorkTree(), url).getAbsolutePath(); } return url; }

Target:
curlies not needed
Source:
public void incSize(int by) { size += by; }

Target:
These are vary dangerous methods because they are public. This can lead to procedural programming where it is difficult to determine if the object is in a valid state. Can these be made private?
Source:
public CompletionStage<Void> rollback(LocalTransaction localTransaction) { try { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); } return CompletableFutures.completedNull(); }); } catch (Throwable e) { return handleRollbackFailure(e, localTransaction); } }

Target:
AFAICT `handleRollbackFailure` and `handleCommitFailure` don't need to return a `CompletionStage`
Source:
public void link(Attributes attributes, String hrefOrHashName, String text) { if (hrefOrHashName != null) { assertOpenBlock(); try { currentBlock.write('"'); writeAttributes(attributes); currentBlock.write(text); currentBlock.write('"'); currentBlock.write(':'); currentBlock.write(hrefOrHashName); } catch (IOException e) { throw new RuntimeException(e); } } }

Target:
This seems "lossy" in that the attributes and text of the link are lost if there is no link target. I'd prefer to see this emit as much as possible, and simply omit the href value if needed, e.g. if (hrefOrHashName == null) { hrefOrHashName = ""; } same with the other builders
Source:
protected IProblemLocation createProblemLocation(ProblemMarkerInfo info) { IProblemLocationFactory factory = CodanRuntime.getInstance().getProblemLocationFactory(); IFile file = (IFile) info.file; return factory.createProblemLocation(file, info.startChar, info.endChar, info.lineNumber); }

Target:
Redundant variable - inline.
Source:
protected void unregisterSender() { if (sender != null) sender.unregister(context, parent.getPriorityClass()); }

Target:
Why have this check here? I don't see a code path that can result in `sender` being null, which the check implies could happen. If this check is necessary it needs locking to avoid a race condition.
Source:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!isFinished(), "Operator is already finished"); index.addPage(page); if (!localUserMemoryContext.trySetBytes((index.getEstimatedSize().toBytes()))) { index.compact(); } localUserMemoryContext.setBytes(index.getEstimatedSize().toBytes()); operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount()); }

Target:
Do we need to call this if the above `trySetBytes` call worked? If not, move this inside of the `if`.
Source:
public Comparable getSortKey() { String sourceProviderName = mySourceProvider == null ? "" : mySourceProvider.getName(); final String s = getQualifiedNameSortKey() + "-" + (SdkConstants.FD_MAIN.equals(sourceProviderName) ? "" : sourceProviderName); return s; }

Target:
inline s?
Source:
protected String getLaunchDebugCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); String debugPort = getDebugPort(); String debugArgs = "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=" + debugPort + " -Xdebug "; String command = "java " + debugArgs + vmArguments + " -jar " + jar + " " + IJBossRuntimeConstants.SPACE + programArguments + "&"; return command; }

Target:
`" " + IJBossRuntimeConstants.SPACE`
Source:
private void initFirewallType() { ListModel<FirewallType> firewallType = getFirewallType(); firewallType.setItems(Arrays.asList(FirewallType.values())); firewallType.setIsChangeable(false); firewallType.setSelectedItem(FirewallType.FIREWALLD); }

Target:
you need to make sure that in case of edit you select the firewall type as it was configured on the cluster and not always select the default.
Source:
public void copyValues() { if (batchSize == 0) { return; } verify(decodedBlock != null); int[] positions = getPositions(); verify(positionsOffset + batchSize - 1 < positions.length && positions[positionsOffset] >= 0 && positions[positionsOffset + batchSize - 1] < decodedBlock.getPositionCount()); appendValuesToBuffer(); appendNulls(); bufferedPositionCount += batchSize; }

Target:
I'd remove this check. If you decide to keep it, consider separating conjuncts into separate calls and moving these into `appendValuesToBuffer`. ``` verify(positionsOffset + batchSize - 1 < positions.length); verify(positions[positionsOffset] >= 0); verify(positions[positionsOffset + batchSize - 1] < decodedBlock.getPositionCount()); ```
Source:
public StepContext getObject() throws Exception { org.springframework.batch.core.scope.context.StepContext stepContext = StepSynchronizationManager.getContext(); String stepName = stepContext.getStepName(); String jobName = stepContext.getStepExecution().getJobExecution().getJobInstance().getJobName(); Properties properties = batchPropertyContext.getStepLevelProperties(jobName + "." + stepName + "." + stepName); return new StepContext(stepContext.getStepExecution(), properties); }

Target:
Why the extra stepName here?
Source:
protected boolean hasInferredTypeHeader(MessageProperties properties) { boolean hasInferredTypeHeader = properties.getInferredArgumentType() != null; return hasInferredTypeHeader; }

Target:
No reason to extract the variable. The compilator is good here with optimization, but the source code is still this and maybe simplified.
Source:
private void invokeClassLoadTestingHookIfNeeded() throws InterruptedException { // Testing support only. if (TESTING_CLASS_LOAD != null) { TESTING_CLASS_LOAD.run(); if (Thread.currentThread().isInterrupted()) { // Otherwise the interrupt isn't recognized and the test doesn't work. throw new InterruptedException("loading was interrupted."); } } }

Target:
nit: maybe use a different runnable hook, which would directly throw the exception you need for your test, instead of "hardcoding" the exception here? We can imagine test cases which would involve setting the interrupted flag here, but without expecting this `InterruptedException` (for instance something which would try to get a `RemotingException` from the `proxy.fetch` call in `loadRemoteClass`).
Source:
public IEventDeclaration getEventDeclaration(int eventIndex) { if (eventIndex == EventDeclaration.UNSET_EVENT_ID) { return fEventUnsetId; } return fEvents.get(eventIndex); }

Target:
Could be get(0) if using a SingletonList (see below) or even better if UNSET_EVENT_ID was 0...
Source:
protected void loadProperties(Properties props) throws IOException { try { super.loadProperties(props); } catch(FileNotFoundException e) { //location was not found, create if (configFile != null && copyOutTemplate) { OutputStream fout = configFile.out(); props.store(fout, comments); fout.flush(); fout.close(); } } }

Target:
@NielsCharlier fix resource leak with a try-with-resources block?
Source:
public Builder addRequestHandler(RequestHandler requestHandler) { if (requestHandler == null) { throw new IllegalArgumentException("RequestHandler must not be null."); } if (requestHandlers == null) { requestHandlers = new ArrayList(); } if (requestHandlers.contains(requestHandler)) { throw new IllegalStateException("RequestHandler already registered."); } requestHandlers.add(requestHandler); return this; }

Target:
Missing generics
Source:
private Object eval(Bindings bindings, String expression) { try { return jsScriptEngine.eval(bindings, expression); } catch (javax.script.ScriptException t) { return new ScriptException(t.getCause()); } catch (Throwable t) { return new ScriptException(t); } }

Target:
![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove this use of "ScriptException"; it is deprecated. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ACallToDeprecatedMethod)
Source:
public void testWithParameters() throws IOException { try (Analyzer ws = newHomoglyphFilter()) { TokenStream ts = ws.tokenStream("", input); BaseTokenStreamTestCase.assertTokenStreamContents(ts, expected); } }

Target:
static import?
Source:
private static void editTree(TreeOperation op, Repository repo, RevWalk rw, RevCommit base, DirCacheEditor dce, ObjectInserter ins, String path, byte[] content) throws IOException, InvalidChangeOperationException { switch (op) { case DELETE_ENTRY: dce.add(new DeletePath(path)); break; case CHANGE_ENTRY: case RESTORE_ENTRY: dce.add(getPathEdit(op, repo, rw, base, path, ins, content)); } dce.finish(); }

Target:
Break after this line.
Source:
public RegisteredService findServiceBy(final long id) { var result = this.services.get(id, k -> this.serviceRegistry.findServiceById(id)); return validateRegisteredService(result); }

Target:
Are you switching to var in order to correctly determine the final type?
Source:
public Map<String, Object> getMetaData(String iconName) throws IconException { return this.getMetaData(iconName, getIconSet(iconName).getName()); }

Target:
This means ``getIconSet`` will be called twice for the most common use case. I would add a private ``getMetaData(String iconName, IconSet iconSet)`` and call it from the rest of the ``getMetaData()`` methods.
Source:
public QualityProfileDto selectByNameAndLanguage(String name, String language, DbSession session) { return mapper(session).selectByNameAndLanguage(name, language); }

Target:
![INFO](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-info.png 'Severity: INFO') Do not forget to remove this deprecated code someday. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS1133)
Source:
private int addFieldToDescriptionMap(Map<String, Object> descriptionMap, String diskAlias, String fieldName, String fieldValue, int descriptionAvailableLength) { if ((descriptionAvailableLength -= getJsonFieldPotentialOverhead(fieldName, descriptionMap)) > 0) { // There's enough space for the field's overhead in the metadata + at least one character from its value. if (fieldValue.length() > descriptionAvailableLength) { fieldValue = fieldValue.substring(0, descriptionAvailableLength); auditLogNoSpaceToStoreEntireDiskField(diskAlias, fieldName, fieldValue); } descriptionMap.put(fieldName, fieldValue); return descriptionAvailableLength - fieldValue.length(); } return 0; }

Target:
This is unintuitive - why not return the number of characters you need and allow the calling function to decide what to do with it?
Source:
public static CompletableFuture<Void> runLaterChecked(CheckedRunnable workToEnqueue) { return runLater(() -> { try { workToEnqueue.run(); } catch (Exception e) { throw new CompletionException(e); } }); }

Target:
I would probably catch throwables, because ClassDefNotFoundError..
Source:
public void add(String str, StatsSnapshot statsSnapshot) { this.subMap = this.subMap == null ? new HashMap<>() : this.subMap; this.subMap.put(str, statsSnapshot); }

Target:
minor: don't need `this.` in both lines
Source:
public Context currentContext() { return context; }

Target:
Our standard convention is to prefix with `this` for instance members - `return this.context`
Source:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { // jitter to avoid overloading database and overloading the backup store SECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis / 1000)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }

Target:
What if `organizationDiscoveryIntervalMillis` is less than 1000? Use `MILLISECONDS` instead
Source:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs, // so let's start with roughly 1/4 of that .initialCapacity(100) .weigher(new TypeCodecWeigher()) .maximumWeight(1000); if (logger.isTraceEnabled()) // do not bother adding a listener if it will be ineffective builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }

Target:
It's possible that log levels can be manipulated dynamically, but that seems like such a thin use case that we don't need to worry about it.
Source:
public void scanFile(JavaFileScannerContext context) { expectedLevel = 0; isBlockAlreadyReported = false; lastCheckedLine = 0; isInAnonymousClass.clear(); this.context = context; scan(context.getTree()); isInAnonymousClass.clear(); }

Target:
If you clear the list at the end of the scan, no need to clear it before.
Source:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { Project search = new Project(name); Project proj; if ((proj = env.getProjects().get(name)) != null) { return (proj); } } return null; }

Target:
unused variable?
Source:
public ImportNetworksModel(final com.google.inject.Provider<CommonModel> commonModelProvider, NetworkListModel sourceListModel) { this(sourceListModel, commonModelProvider); }

Target:
Instead of adding this injected ctor here, I would add a new class that extends ImportNetworksModel and has this ctor. So the base class will have the general ctor and the children will have the injected ones with the explicit model type. The way it is implemented now is a bit confusing.
Source:
void onNext(ClickEvent event) { GQuery.console.info("next"); next(); }

Target:
debug
Source:
public void testDestroy() throws Exception { final ManagedInstance managedInstance = mock(ManagedInstance.class); final Object control = mock(Object.class); final Consumer<Object> consumer = mock(Consumer.class); InstanceUtils.destroy(managedInstance, control, consumer); verify(consumer, times(1)).accept(eq(control)); verify(managedInstance, times(1)).destroy(eq(control)); }

Target:
The Exception is never thrown.
Source:
static GlyphPair gp(String original, String mirror) { return new GlyphPair(original, mirror); }

Target:
nit: Should be `public`. We're only using this inside of the package, but there is no reason to restrict it, and it should have the same visibility as the constructor, since it is just a shortcut for the ctor.
Source:
public void testSimpleAnnounce() throws IOException { IndexerSQLMetadataStorageCoordinator coordinator = new IndexerSQLMetadataStorageCoordinator( mapper, tablesConfig, derbyConnector ); coordinator.announceHistoricalSegments(segments); Assert.assertArrayEquals( mapper.writeValueAsString(defaultSegment).getBytes("UTF-8"), derbyConnector.lookup( tablesConfig.getSegmentsTable(), "id", "payload", defaultSegment.getIdentifier() ) ); }

Target:
i think, it is done in every test and can possibly be moved to setUp()
Source:
public static IDomain getFirstDomainOrCreate(IUser user) throws OpenShiftException { IDomain domain; domain = getFirstDomain(user); if (domain == null) { domain = user.createDomain(createRandomName()); } return domain; }

Target:
please dont remove explicit initialization
Source:
public void testSetDependencies() { Assert.assertNotNull(this.c.getDependencies()); final Set<String> dependencies = Sets.newHashSet(); dependencies.add("s3://netflix/jars/myJar.jar"); this.c.setDependencies(dependencies); Assert.assertEquals(dependencies, this.c.getDependencies()); this.c.setDependencies(null); Assert.assertThat(this.c.getDependencies(), Matchers.empty()); }

Target:
why not use `Sets.newHashSet({value})` here like you are everywhere else?
Source:
public static <T> PredicateOperation predicate(Operator operator, ImmutableList<Expression<?>> args) { return new PredicateOperation(operator, args); }

Target:
These `<T>`s don't occur anywhere in the method signature.
Source:
private void usingIsEmpty() { Optional<Object> op = Optional.emtpy(); if (!op.isEmpty()) { op.get(); // Compliant - dead code } }

Target:
typo in the name of the invoked method, should be `Optional.empty()`