auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression) && !isDynamicFilter(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { // We should only consider equalities that have distinct left and right components return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }

Target:
Why do we need it here?
Source:
private void updateGroup(final TupleBatch tb, final int row, final Object[] curAggStates) throws DbException { for (int agg = 0; agg < aggregators.length; ++agg) { if (!(aggregators[agg] .getClass() .getName() .equals(StatefulUserDefinedAggregator.class.getName()))) { aggregators[agg].addRow(tb, row, curAggStates[agg]); } } }

Target:
instanceof
Source:
protected void update(float delta) { int lengthInterpretation; try { lengthInterpretation = length == null ? 0 : length.interpretInteger(sprite); } catch (InterpretationException interpretationException) { lengthInterpretation = 0; Log.d(getClass().getSimpleName(), "Formula interpretation for this specific Brick failed.", interpretationException); } this.sprite.runningStitch.activateStitching(sprite, new SimpleRunningStitch(sprite, lengthInterpretation)); }

Target:
Please apply same changes as requested in first review here.
Source:
protected void processSpanImpl(Span span, Map<String, String[]> servletRequestParameters) { long sum = 0; for (String weaselParameterToSum : weaselParametersToSum) { final Long timing = parsedLongOrNull(getParameterValueOrNull(weaselParameterToSum, servletRequestParameters)); if (timing == null) { discardSpan(span); return; } else { sum += timing; } } span.setTag(TIMING_RESOURCE, sum); }

Target:
remove line
Source:
private void close(Path path) throws IOException { Path directoryWhereGeneratedArtifactsWasPlaced = path.getParent(); try (Stream<Path> s = Files.list(directoryWhereGeneratedArtifactsWasPlaced)) { s.filter(p -> !Files.isDirectory(p)).map(ThrowingFunction.unchecked(p -> p)) .forEach(ThrowingConsumer.unchecked(Files::delete)); } }

Target:
`.map(ThrowingFunction.unchecked(p -> p))` unnecessary
Source:
public void hashcodeVerifyEqualsContract() { EqualsVerifier.forClass(MessageReference.class).suppress(Warning.NONFINAL_FIELDS).verify(); }

Target:
As a general rule: If you're unsure whether or not to suppress a warning, don't! You discovered the principal problem of mutable objects. The easy fix is to use [immutable objects](http://en.wikipedia.org/wiki/Immutable_object) whenever possible. `MessageReference` looks like it could be easily made immutable. So you should definitely do that instead of suppressing the warning.
Source:
public HttpRequest setUri(String uri) { ObjectUtil.checkNotNull(uri, "uri"); this.uri = uri; return this; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
protected ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { this.creds = creds; }

Target:
Make all Guice constructors package private by removing the method modifier. Just: ``` java @Inject ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { ```
Source:
protected int countChildrenOf(IResource checkResource) throws CoreException { if (checkResource.getType() == IResource.FILE) { return 1; } int count = 0; if (checkResource.isAccessible()) { for (IResource resource : ((IContainer) checkResource).members()) { count += countChildrenOf(resource); } } return count; }

Target:
rename 'child'
Source:
public String getAppFolderToMonitor() { if (folder == null) { File f = new File("Applications"); folder = f.getAbsolutePath(); } return folder; }

Target:
If this is null, can't we keep it null? That way you can disable the folder watching if you're not interested in it. The `startMonitor` method below also checks for the return value of this method being `null`. I guess `null` would then also be the default.
Source:
private static void count(Object inputBase, long inputAddress, int inputSize, int[] counts) { long input = inputAddress; Arrays.fill(counts, 0); if (inputSize != 0) { for (int i = 0; i < inputSize; i++) { int symbol = UNSAFE.getByte(inputBase, input) & 0xFF; input++; counts[symbol]++; } } }

Target:
I don't think you need this
Source:
public void submit(List<LuceneWork> workList, IndexingMonitor monitor) { Changeset changeset = new Changeset( workList, Thread.currentThread(), monitor ); transferQueue.add( changeset ); wakeUpConsumer(); boolean interrupted = false; while ( ! changeset.isProcessed() ) { LockSupport.park(); if ( Thread.interrupted() ) { interrupted = true; } } if ( interrupted ) { Thread.currentThread().interrupt(); } }

Target:
If it's interrupted you might want to return too, rather than getting stuck in another park.
Source:
public void setHttpService(HttpService httpService) { logger.info("setHttpService called"); this.httpService = httpService; }

Target:
could we directly reduce this to debug level?
Source:
public boolean isInternal() { return getParentNode() .filter(parent -> parent instanceof Name) .map(parent -> (Name) parent) .flatMap(Name::getQualifier) .map(parentNameQualifier -> parentNameQualifier == this) .orElse(false); }

Target:
Oh, yes, `Name` can only be qualified by another `Name`. I think it's a safe assumption to make :-)
Source:
private void logStart() { log(3, "Running test " + m_testName + " on " + m_classMap.size() + " " + " classes, " + " included groups:[" + Strings.mapToString(m_xmlMethodSelector.getIncludedGroups()) + "] excluded groups:[" + Strings.mapToString(m_xmlMethodSelector.getExcludedGroups()) + "]"); if (getVerbose() >= 3) { for (ITestClass tc : m_classMap.values()) { ((TestClass) tc).dump(); } } }

Target:
`valueOf` looks more appropriate (like `String#valueOf`)
Source:
public NutchJob(Configuration conf) throws IOException { super(conf, "NutchJob"); }

Target:
Does this mean that every Job will be named ```"NutchJob"```?
Source:
private void loadMachineUUID() { if (System.getProperty(PROP_UUID) != null) return; String uuid = loadExistingUUID(); if (uuid == null) { uuid = UUID.randomUUID().toString(); saveUUID(uuid); } EnvironmentInfo environment = environmentTracker.getService(); if (environment != null) { environment.setProperty(PROP_UUID, uuid); } else { System.setProperty(PROP_UUID, uuid); } }

Target:
Should use BundleContext.getProperty here, or the EnvonmentInfo service.
Source:
public synchronized boolean retry(ITestResult result) { if (currentTry < maxreruntimes) { ++currentTry; return true; } return false; }

Target:
Maybe we can use `AtomicInteger` and get rid of `synchronized` keyword ? On a side note, I noticed that you haven't enabled the `parallel` attribute on `@DataProvider` annotation. So you can completely get rid of the need for ensuring Thread safety.
Source:
public Statistics<T> visitIntConstant(ValueExpressions.IntExpression expr, Void value) throws RuntimeException { return (Statistics<T>)getStatistics(expr.getInt()); }

Target:
It was much nicer when we did not have to explicitly cast everywhere to `(Statistics<T>)`. Please consider re-working this part your changes.
Source:
public ServiceDate getEnd() { return end == UNBOUNDED_END ? null : end; }

Target:
It might even be more readable to export the symbolic constants outside the class, instead of null. Either way is fine. It might be clearer for debugging and logging.
Source:
public boolean isLoggedIn() { return token != null && hub != null; }

Target:
no public
Source:
public void setBuildStatus(String buildStatus) { StashBuildState overwrittenBuildState = null; try { overwrittenBuildState = StashBuildState.valueOf(buildStatus); } catch (Exception e) { // ignore unknown or null values } this.buildStatus = overwrittenBuildState; }

Target:
The complete method could be stripped down to: ``` try { this.buildStatus = StashBuildState.valueOf(buildStatus); } catch (Exception e) { // ignore unknown or null values } ```
Source:
public void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); BCSiliconConfig.preInit(); BCSiliconItems.preInit(); BCSiliconBlocks.preInit(); // Reload after all of the definitions have been created. BCSiliconConfig.reloadConfig(EnumRestartRequirement.GAME); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCSiliconProxy.getProxy()); BCSiliconProxy.getProxy().fmlPreInit(); }

Target:
Put this in the config preinit please
Source:
public Hash(HashType type){ this.type = type; try { digest = type.get(); } finally { type.recycle(digest); } }

Target:
Recycling a digest to which we still have references (namely in the member variable`digest`) is bound to give problems at some point: another thread may obtain it by means of `HashType.get()` while we are still using it! If you insist on recycling digests, I guess this could be done in the finalizer of `Hash`. Note that the semantics of `finally` don't have anything to do with finalizers!
Source:
private boolean validateExternalVnicProfileMapping() { drMappingHelper.mapVnicProfiles(vmTemplateFromConfiguration.getInterfaces(), getParameters().getExternalVnicProfileMappings()); final ValidationResult validationResult = externalVnicProfileMappingValidator.validateExternalVnicProfileMapping( getParameters().getExternalVnicProfileMappings(), getParameters().getClusterId()); return validate(validationResult); }

Target:
the mapping is still performed before the validation. it should be after it
Source:
public void serDeTest() { doSerDeTest(Collections.emptyList()); doSerDeTest(Arrays.asList("a", "b", "/signedId/abcdef")); }

Target:
do we need a `null` case?
Source:
protected void buildVmVideoCards() { createInfo.add(VdsProperties.display, vm.getdisplay_type().toString()); // vnc,qxl createInfo.add(VdsProperties.num_of_monitors, (new Integer(vm.getnum_of_monitors())).toString()); }

Target:
use String.valueOf(vm.getnum_of_monitors()) instead.
Source:
String encode(String segment) { return URL.encodeQueryString(type.replacePathSeparator(segment)); }

Target:
[optional] maybe this method can be static and should be moved to end of the class
Source:
public List<String> getStrongDependencies() { List<String> strongDependencies = new ArrayList<>(); strongDependencies.add(A_U_D_preferredMail); strongDependencies.add(A_U_D_ISMail); strongDependencies.add(A_U_D_publicAliasMails); strongDependencies.add(A_U_D_privateAliasMails); strongDependencies.add(A_U_D_o365EmailAddressesMU); return strongDependencies; }

Target:
This code is duplicate. Moreover, repeated "add" operations are not necessary. You can use something like this: ``` return Arrays.asList( A_U_D_preferredMail, A_U_D_ISMail, A_U_D_publicAliasMails, A_U_D_privateAliasMails, A_U_D_o365EmailAddressesMU); ```
Source:
boolean isCacheable() { return true; }

Target:
`isCacheable` is now `true`? I guess this was supposed to be `false` for generic extractors. Or am I wrong?
Source:
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, String keyAlgorithm, File keyFile, String keyPassword, KeyManagerFactory kmf, String keyStore) throws KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, IOException, CertificateException, KeyException, UnrecoverableKeyException { return buildKeyManagerFactory(toX509Certificates(certChainFile), keyAlgorithm, toPrivateKey(keyFile, keyPassword), keyPassword, kmf, keyStore); }

Target:
It does not make sense to expose a protected method and mark it as @Deprecated from the beginning. Maybe you should remove the annotation and make it package-private ?
Source:
public void testWrongPortConnection() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory, clientSSLConfig); try { // send request channel.connect(); fail("should have thrown!"); } catch (IOException e) { assertTrue(e.getMessage().contains("Connection refused")); } }

Target:
It's probably a bad idea to be checking for exception messages in the first place.
Source:
public void notifyParameterChanged(String name) { if (!fParameterNames.contains(name)) { throw new RuntimeException(String.format(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName())); } synchronized (fParameters) { Object oldValue = fParameters.get(name); Object value = getParameter(name); if ((value != null) && !(value.equals(oldValue))) { parameterChanged(name); } } }

Target:
the .contains() should probably be in the synchronized block too
Source:
public void testUnrecognizedSpec() { when(authentication.getAttributes().get(any(String.class))).thenReturn("strong_two_factor"); spec.setAuthenticationMethod("weak_two_factor"); assertTrue(this.spec.isSatisfiedBy(this.assertion)); }

Target:
Is this idiomatic? In fact expect that won't be true, it's just that will be interrupted before the assertTrue returns? Would be clearer to omit the assertTrue?
Source:
public static Bundle updateBundleConfig(Connection connection, Bundle bundle) throws SQLException { final String sql = "UPDATE portti_view_bundle_seq SET config=? WHERE bundle_id=? AND view_id=?"; try (final PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, bundle.config); statement.setLong(2, bundle.bundle); statement.setLong(3, bundle.view); statement.execute(); } return null; }

Target:
Why does this claim to return Bundle? Doesn't really matter though :)
Source:
protected int getOverProvisioningFactor() { return Integer.valueOf(Framework.getProperty(WORKMANAGER_OVERPROVISIONING_PROP, DEFAULT_WORKMANAGER_OVERPROVISIONING)); }

Target:
`Integer.parseInt`
Source:
protected void onDestroy() { super.onDestroy(); webView.setDownloadListener(null); }

Target:
Please move `super.onDestroy` to the end of the method.
Source:
public void closeTest() { // request is keep-alive by default. HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); EmbeddedChannel channel = createEmbeddedChannel(); channel.writeInbound(request); // drain the channel of content. while (channel.readOutbound() != null) { ; } assertFalse("Channel should be closed", channel.isOpen()); }

Target:
Which part in this test calls `NettyResponseChannel.close()`?
Source:
public String getRuleLogsForVms() { final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); cmd.add("get_rule_logs_for_vms"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = cmd.execute(parser); if (result == null) { return parser.getLine(); } return null; }

Target:
Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
private void addReporter(Class<? extends IReporter> r) { m_reporters.put(r, ClassHelper.newInstance(r)); }

Target:
We can avoid the instance creation if the reporter already exist
Source:
public final synchronized void addFunctions(List<? extends SqlFunction> functions) { addFunctions(TEMP_DEFAULT_CATALOG, functions); }

Target:
Don't mark methods as `final`.
Source:
public synchronized void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (oldInput != newInput) { if (newInput != null) { ImportTraceContentProvider input = (ImportTraceContentProvider) newInput; clearCandidates(); fTraceTypes.putAll(input.fTraceTypes); fTraceFiles.putAll(fTraceFiles); } } }

Target:
You can join the ifs. There's a content assist for that, it's awesome.
Source:
boolean isPowerManagementLegal() { return IsPowerManagementLegal(getParameters().getVdsStaticData(), getVdsGroup() .getcompatibility_version().toString()); }

Target:
please set a modifier - protected seem suitable
Source:
public void info(String message) { System.out.println(message); info.add(message); }

Target:
Should avoid `System.out` in tests. Instead can you write to log4j
Source:
public static File makeNumericDimFile(File dir, String dimension, ByteOrder order) { return new File(dir, StringUtils.safeFormat("numeric_dim_%s_%s.drd", dimension, order)); }

Target:
Probably should crash if bad format string
Source:
private AuditLogableBase createAuditLog(final VmNic iface) { AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(iface.getVmId()); logable.addCustomValue("MACAddr", iface.getMacAddress()); logable.addCustomValue("IfaceName", iface.getName()); return logable; }

Target:
Is there any longer a need for the VM ID ?
Source:
public boolean equals( VirtualValue other ) { if ( other == null || !(other instanceof MapValue) ) { return false; } MapValue that = (MapValue) other; return size() == that.size() && Arrays.equals( keys, that.keys ) && Arrays.equals( values, that.values ); }

Target:
same here, redundant?
Source:
private void processSingleClusterChanges(ManageNetworkClustersParameters param) { final List<ActionParametersBase> setupNetworksParams = new ArrayList<>( createNetworkClustersToSetupNetworksParametersTransformer().transform( param.getAttachments(), param.getDetachments(), param.getUpdates()) ); HostSetupNetworksParametersBuilder.updateParametersSequencing(setupNetworksParams); setupNetworksParams.forEach(this::withRootCommandInfo); runInternalMultipleActions(ActionType.PersistentHostSetupNetworks, setupNetworksParams, getContext().getExecutionContext()); }

Target:
nit: Formatting
Source:
private void setFixedLengthStreamingMode(HttpURLConnection connection, long length) { try { // Not caching method as invocation is literally sending > 2GB, which means reflection isn't a limiter! HttpURLConnection.class.getMethod("setFixedLengthStreamingMode", long.class).invoke(connection, length); } catch (Exception e) { throw new IllegalArgumentException("Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations." + " Use chunked encoding or multi-part upload, if possible, or use a different http driver." + " For more information: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6755625"); } }

Target:
[minor] Can be static?
Source:
String getErrorMessage(ClientResponse clientResponse) { String response = clientResponse.getEntity(String.class); try { // Try to see if the server responded with an error message from the API ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { // If not, inform the user of the underlying response (e.g. if server threw NPE or whatever) int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }

Target:
Method should probably be protected, given writing this for sub-classing.
Source:
public int hashCode() { int bits = 1; bits = 31 * bits + this.type.ordinal(); bits = 31 * bits + getToX(); bits = 31 * bits + getToY(); bits = 31 * bits + getToZ(); bits = 31 * bits + getFromX(); bits = 31 * bits + getFromY(); bits = 31 * bits + getFromZ(); return bits; }

Target:
`b ^ (b >> 31)` is missed here.
Source:
public static AccountCollection all(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.GET, classURL(Account.class), params, AccountCollection.class, (RequestOptions) null); }

Target:
This should call all ``` java return all(params, (RequestOptions) null); ```
Source:
public void onSaveClick() { editView.setSaveState(true); WikidataDescriptionEditDataClient client = new WikidataDescriptionEditDataClient(); client.submitDescription(pageTitle, editView.getDescription(), new WikidataDescriptionEditDataClient.Callback() { @Override public void success() { editView.setSaveState(false); L.i("WD description edit successful"); // TODO: go to success fragment } @Override public void failure(@NonNull Throwable caught) { editView.setSaveState(false); L.e("WD description edit failed: ", caught); // TODO: go to failure fragment } }); }

Target:
Since this is a Fragment with a lifecycle, consider holding a reference to Call<?> and canceling it in onDestroy() if Call<?> is nonnull.
Source:
protected ResourceSet loadResource(IEditorInput editorInput) { final URI resourceURI = EditUIUtil.getURI(getEditorInput(), null); return ResourceSetHelpers.loadResourceSetWithProxies(resourceURI, getCommandStack()); }

Target:
why not use the passed in editorInput
Source:
FileReftableStack.CompactionStats getCompactionStats() throws IOException { return reftableStack.getStats(); }

Target:
declared exception isn't thrown
Source:
public OnlineBackup incremental( String targetDirectory ) { outcome = new BackupService().doIncrementalBackup( hostNameOrIp, port, new File( targetDirectory ), getConsistencyCheck( true ), timeoutMillis, defaultConfig() ); return this; }

Target:
This changes default behaviour, right? Should it?
Source:
private boolean isValidConfiguration() { if (isDiscarding() || isCalleeData()) { return isAsync(); } else { return true; } }

Target:
This could just be `return !(isDiscarding() || isCalleeData()) || isAsync();`
Source:
public boolean setTrace(@NonNull ITmfTrace trace) throws TmfAnalysisException { boolean ret = super.setTrace(trace); if (!ret) { return ret; } ret = fCriticalPathModule.setTrace(trace); fCriticalPathModule.setParameter(CriticalPathModule.PARAM_GRAPH, getId()); return ret; }

Target:
should this be set if ret is false? I don't know.
Source:
public void fillContextMenu(final IMenuManager menu) { super.fillContextMenu(menu); final ISelection selection = getContext().getSelection(); if (selection.isEmpty()) { return; } // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { throw new RuntimeException(e); } // Differents behavior between win and linux : windows will not // display contextual menu if busy cursor while dialog is shown. // Fill the context menu contextMenuFiller.fillContextMenu(menu, selection); }

Target:
Before, with waitOtherJobs, we "Do nothing" in case of InterruptedException. Why do you change that? Have you test the difference?
Source:
public void dispose() { // run super. super.dispose(); // remove ourselves as a selection and registry listener getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); if (saveables != null) { saveables.removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }

Target:
Are you sure about that cast operation? You are asking for a service interface and cast it to a concrete implementation without instanceof check. You perform that check in the tracker that is only added to a SaveablesList.
Source:
public void setBaseballCard(BaseballCard card) { Locale locale = Locale.getDefault(); brand.setText(card.brand); year.setText(String.format(locale, "%d", card.year)); number.setText(String.format(locale, "%s", card.number)); player.setText(card.playerName); }

Target:
`String.format()` is no longer necessary here.
Source:
private String capitalize(String word) { return Character.toUpperCase(word.charAt(0)) + word.substring(1); }

Target:
Can be static
Source:
private static boolean isStringParameter( @NonNull Expression expression, @NonNull JavaContext context) { if (expression instanceof StringLiteral) { return true; } else { JavaParser.ResolvedNode resolvedNode = context.resolve(expression); if (resolvedNode instanceof JavaParser.ResolvedField) { if (((JavaParser.ResolvedField) resolvedNode).getValue() instanceof String) { return true; } } } return false; }

Target:
instead of this, use (at the callsite where you have the JavaContext) TypeDescriptor type = context.getType(expression); return type != null && type.matchesSignature(JavaContext.TYPE_STRING);
Source:
protected double getScore(double availableCpu, double availableMemory, Map<String, Double> availableGenericResources) { TopologyDetails td = getNextHighest(); return getScore(availableCpu, availableMemory, availableGenericResources, td); }

Target:
Nit: could we inline this to avoid unnecessary object creation
Source:
public <T extends Action> List<T> getActions(Class<T> type) { List<T> _actions = Util.filter(getPersistedActions(), type); for (TransientActionFactory<?> taf : TransientActionFactory.factoriesFor(getClass(), type)) { _actions.addAll(Util.filter(createFor(taf), type)); } return Collections.unmodifiableList(_actions); }

Target:
I think this should be reverted, so it would still take into account additions from pre-`TransientActionFactory` implementations.
Source:
public void addRepresentation (ImageData srcImageData, int zoom) { if (srcImageData == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); int imageSelectorIndex = DPIUtil.mapZoomToImageSelectorIndex(zoom); if (imageSelectorIndex == device.getImageSelector ()) { init(srcImageData); init(); } else { data [imageSelectorIndex] = srcImageData; } }

Target:
ImageData for current image needs to be updated in the array?
Source:
private DefaultEnvironment buildEnvironment(EnvironmentType environmentType) { DefaultEnvironment defaultEnvironment = new DefaultEnvironment(environmentType); defaultEnvironment.setup(); return defaultEnvironment; }

Target:
you don't need to do that if you're already calling `loadProperties` in the public constructor, right? https://github.com/caelum/vraptor4/pull/973/files#diff-b7b62c45c7478eb642acfb81c12a4227R82
Source:
public int hashCode() { return getRepositoryName() != null ? getRepositoryName().hashCode() : System.identityHashCode(this); }

Target:
Style-nit: This is hard to read. Maybe: if (getRepositoryName() != null) return getRepositoryName().hashCode(); return System.identityHashCode(this);
Source:
public List<String> getExtensions() { return extensions == null ? DEFAULT_EXTS : extensions; }

Target:
Can be removed and return only extensions without assigning logic.
Source:
public List<RadiologyOrder> getRadiologyOrdersByPatient(Patient patient) { Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatient(radiologyOrderCriteria, patient); List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); return result == null ? new ArrayList<RadiologyOrder>() : result; }

Target:
use final
Source:
public Weld addExtensions(Class<? extends Extension>... extensionClasses) { Object[] constructorParams = new Object[] {}; for (Class<? extends Extension> extensionClass : extensionClasses) { try { Extension extension = SecurityActions.newInstance(extensionClass); addExtension(extension); } catch (Exception ex) { CommonLogger.LOG.unableToInstantiate(extensionClass, constructorParams, ex); } } return this; }

Target:
This variable is useless in most cases. I would rather pass `new Object[] {}` to log method directly.
Source:
public RTTestsParser() { super(Messages._Warnings_RTTests_ParserName(), Messages._Warnings_RTTests_LinkName(), Messages._Warnings_RTTests_TrendName(), CYCLICTEST_WARNING_PATTERN, true); }

Target:
If the last parameter is `true` then you need to overwrite `isLineInteresting`.
Source:
private ValidationResult hostExists() { if (getVds() == null) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); } return ValidationResult.VALID; }

Target:
You could use ternary if for this: return getVds() == null ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST) : ValidationResult.VALID;
Source:
public static ToolTipString fromString(String text) { Objects.requireNonNull(text, "fromString cannot take null"); //$NON-NLS-1$ return new ToolTipString(text, toHtmlString(text)); }

Target:
You can remove all the requireNonNull due to @NNBD. I'm surprised we're allowed to use it, doing an explicit null check would be a compilation error...
Source:
public DataRadioStation getNextById(String id) { if (listStations.size() == 0) return null; for (int i = 0; i < listStations.size() - 1; i++) { if (listStations.get(i).ID.equals(id)) { return listStations.get(i + 1); } } return listStations.get(0); }

Target:
`if (listStations.isEmpty())`
Source:
public static void setBiomeArrayMethod(boolean jeidPresent) { try { if (jeidPresent) { biomeArrayMethod = Chunk.class.getMethod("getIntBiomeArray"); } else biomeArrayMethod = Chunk.class.getMethod("getBiomeArray"); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } }

Target:
Please add the `{}` for the one-liner
Source:
public String getDescription() { return "Transform files representing a structured table under an Alluxio directory." + "\n\n" + "Files are coalesced and converted to parquet format." + "\n\n" + "Definition is in format like 'write(hive).option(hive.num.files, 100)'," + "currently, the only modification you can do to the example definition is " + "the number of files in the option." }

Target:
I think since this will change in future release, it's better to let it be here so it's easier to update.
Source:
public static void validateNonNegative(int[] data, String paramName){ boolean nonnegative = true; for(int value : data){ if(value < 0) { nonnegative = false; } } Preconditions.checkArgument(nonnegative, "Values for %s must be >= 0, got: %s", paramName, data); }

Target:
Handling of nulls? You have some in the later methods, but not here... If null is acceptable, we should return null here. If not, let's either add a lombok ```@NonNull``` or a ```Preconditions.checkNotNull(```. At present, nulls will give a non-useful NPE.
Source:
public SetContentTypeFilter() { try { mimetypeToExtensionMap = new Properties(); mimetypeToExtensionMap.load(new InputStreamReader(this.getClass().getResourceAsStream( "mimetypeToExtension.txt"))); contentTypeProperties = new Properties(); contentTypeProperties.load(new InputStreamReader(this.getClass().getResourceAsStream( "toContentType.properties"))); } catch (IOException e) { log.error("Failed to load mimetype mappings", e); } }

Target:
Looking at this (and i realize this is my own crappy code), its really a configuration error for the files to fail to load, and we really don't want to be eating that and just putting something in the log. Could you either remove the try block and make this constructor throw the IOException, or rethrow an exception with a little extra context? Up to you which you prefer.
Source:
private SwiftApi api(String authUrl, Properties overrides) throws IOException { if (overrides == null){ overrides = new Properties(); } overrides.setProperty(CREDENTIAL_TYPE, "tempAuthCredentials"); return ContextBuilder.newBuilder(new SwiftApiMetadata()) .credentials("user", "password") .endpoint(authUrl) .overrides(overrides) .modules(ImmutableSet.of(new ExecutorServiceModule(sameThreadExecutor()))) .buildApi(SwiftApi.class); }

Target:
Instead of passing null, remove this check and call this method with a new Properties object.
Source:
public void setAcceptableValues(Collection<K> values) { buttons.clear(); panels.clear(); wrapperPanel.clear(); for (final K value : values) { addValue(value); } updateButtons(); }

Target:
add null check
Source:
public Bucket getOrCreateBucket(String bucketName) { try { Bucket bucket = storage.get(bucketName); if (bucket == null) { log.debug(String.format("Creating a new bucket %s", bucketName)); return storage.create(BucketInfo.of(bucketName)); } return bucket; } catch (StorageException e) { throw new NuxeoException(e); } }

Target:
`StorageException` is a runtime exception, no need to catch and rethrow it (several occurrences).
Source:
private void onFragmentLoaded() { if (searchAdapter == null) { searchAdapter = new SearchlistAdapter(getActivity(), itemAccess); setListAdapter(searchAdapter); } searchAdapter.notifyDataSetChanged(); setListShown(true); String query = getArguments().getString(ARG_QUERY); setEmptyText(getString(R.string.no_results_for_query) + " \"" + query + "\""); }

Target:
You need to keep in mind that the sentence construction in other languages could be different, so the query string doesn't always show at the end. You should use %1$s in your string on values/strings.xml and pass the query term as an extra argument to getString()
Source:
private Iterable<Ref> getSortedRefs() throws Exception { List<Ref> all = db.getRefDatabase().getRefsByPrefix(ALL); if (all instanceof RefMap || (all instanceof SortedMap && ((SortedMap) all).comparator() == null)) { return all; } return RefComparator.sort(all); }

Target:
Thanks. Marking resolved.
Source:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : source != null ? new ArrayList<ProfileEntry>((ArrayList<ProfileEntry>) source) : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; }

Target:
I don't understand why you need to create a new ArrayList for a collection that is coming from a query - it is necessarily not being used by anyone else. Also, why cast what's coming from the backend to an ArrayList? This means you're committing to a specific implementation. I think a cast to Collection is more appropriate. If it's important for you to have the end result in specifically an ArrayList (and not any other kind of collection), then I would create a new ArrayList, but still cast the result from the backend to Collection.
Source:
public FunctionKindRowColumnHeaderMetaData(final Supplier<FunctionDefinition> functionSupplier, final CellEditorControlsView.Presenter cellEditorControls, final KindPopoverView.Presenter editor, final Optional<String> editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.gridWidget = gridWidget; }

Target:
Since the `class` has _package_ protected access the constructor can probably have _package_ protection too?
Source:
public List<ProxiedPlayer> matchPlayer(String partialName) { List<ProxiedPlayer> matched = new ArrayList<ProxiedPlayer>(); for (ProxiedPlayer iPlayer : this.getPlayers()) { String iterPlayerName = iPlayer.getName(); if (partialName.equalsIgnoreCase(iterPlayerName)) { matched.add(iPlayer); break; } if (iterPlayerName.toLowerCase().contains(partialName.toLowerCase())) { matched.add(iPlayer); } } return matched; }

Target:
Wouldn't starts with make more sense?
Source:
private int zigzagDecode(int input) { return (input >> 1) ^ (-(input & 1)); }

Target:
I notice in the unzigzag method below, you use the unsigned right shift operator (`>>>`), but here you're using the signed one (`>>`). Is that intentional?
Source:
public void testEqualsCondition() { doTest(GoStringIndexIsByteQuickFix.NAME); }

Target:
Please create method`doTest() { doTest(GoStringIndexIsByteQuickFix.NAME); }` and maybe same method `doTestNoFix()`
Source:
public void testRedrawAfterDispose() { LineNumberRulerColumn lineNumberRulerColumn= new LineNumberRulerColumn(); CompositeRuler ruler= new CompositeRuler(); ruler.addDecorator(0, lineNumberRulerColumn); SourceViewer sourceViewer= new SourceViewer(fParent, ruler, SWT.NONE); lineNumberRulerColumn.getControl().setSize(10, 10); sourceViewer.getTextWidget().dispose(); try { lineNumberRulerColumn.redraw(); } catch (Exception notExpected) { notExpected.printStackTrace(); fail(); } }

Target:
why do we need try/catch here? It should not fail, and if it fails, junit will take care about the stack etc
Source:
public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; }

Target:
Please consider adding an overridden version of the `Script(String, int, Logger)` constructor that accepts `Duration` to encapsulate this type conversion.
Source:
public void testQueryCumulativeTable() { computeActual("SELECT * FROM \"*:*\""); computeActual("SELECT * FROM \"java.util.logging:*\""); assertTrue(computeActual("SELECT * FROM \"java.lang:*\"").getRowCount() > 0); assertTrue(computeActual("SELECT * FROM \"jAVA.LANg:*\"").getRowCount() > 0); }

Target:
shouldn't it be `> 1`
Source:
public RequestLogger get() { LoggingRequestLogger logger = new LoggingRequestLogger(mapper, setMDC, setContextMDC); log.info(new Exception("Stack trace"), "Creating %s at", logger); return logger; }

Target:
should these be `debug` level?
Source:
private IllegalReferenceCountException handleIllegalReferenceCountException(IllegalReferenceCountException e) { String accessRecord = leak.toString(); if (StringUtil.isNullOrEmpty(accessRecord)) { // means leak has been closed and there is no accessRecord. return e; } return new TrackedIllegalReferenceCountException(e.getMessage(), accessRecord); }

Target:
shouldn't we wrap the original `e` ?
Source:
public List<Payment> getAccountPayments(final UUID accountId, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { return paymentProcessor.getAccountPayments(accountId, withPluginInfo, tenantContext, internalCallContextFactory.createInternalTenantContext(accountId, tenantContext)); }

Target:
The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`
Source:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); Serializable auditParam = command.getParam(NXAuditEventsService.DISABLE_AUDIT_LOGGER); disableAudit = auditParam != null && Boolean.parseBoolean(auditParam.toString()); retentionManager = Framework.getService(RetentionManager.class); ruleId = (String) command.getParam(PARAM_RULE_ID); }

Target:
No need to cast to `String`, here `getParam` is a generic method `public <T> T getParam(String key)`
Source:
public boolean remove(Connection connection) { boolean removed = connectionPool.remove(connection); if (getHttpExchanges().isEmpty()) { tryRemoveIdleDestination(); } else { // We need to execute queued requests // even if this connection was removed. // We may create a connection that is not // needed, but it will eventually idle timeout. if (removed) process(true); } return connectionPool.remove(connection); }

Target:
should this check that the queue is not 0? Why acquire a connection if there are no waiting exchanges?
Source:
public boolean getRewriteBatchedStatements() { final String isRewrite = super.connectionProperties.getProperty(REWRITE_BATCHED_STATEMENTS); return isRewrite == null ? null : Boolean.valueOf(isRewrite); }

Target:
return null ? I think you meant 'false', did not you?
Source:
public static ScheduledExecutorService newScheduler(int numThreads, String threadNamePrefix, boolean isDaemon) { ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(numThreads, new SchedulerThreadFactory(threadNamePrefix, isDaemon)); scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); scheduler.setRemoveOnCancelPolicy(true); return scheduler; }

Target:
I am little wary about this. coz, all our existing schedulers are using this and setting this might cause them to be removed immediately. Even though ideally we want to be in that position, when rolling this out, don't want to have any unexpected behaviors.
Source:
public boolean setValue(T newValue) { if (!validator.validate(newValue)) { LOGGER.warn("The passed value is invalid.", newValue); return false; } PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }

Target:
Ah, that's what you meant. =) No, this isn't good: it's too generic, it wouldn't help you debug a failure. The validator itself has to log a warning and then return false, so that the warning can be very specific on what went wrong, i.e. the new value being beyond the maximum value allowed.
Source:
public void onMessage(MessageHolderWithTokens message) { try { logger.debug("receiving tokens from queue, triggering Notification Dispatcher class to pick the right sender"); dequeueEvent.fire(message); } catch (DispatchInitiationException e) { throw e; } catch (Exception e) { logger.error("NotificationDispatcher or PushNotificationSender unexpectedly failed, the message won't be redelivered", e); } }

Target:
Do we really want to move this from `trace` to `debug`?
Source:
private Collection<Key> getRegisteredKeys() { List<Key> result = new ArrayList<Key>(); for (Iterator<Key> i = cacheMap.keySet().iterator(); i.hasNext();) { result.add(i.next()); } return result; }

Target:
why not: return result.addAll(cacheMap.keySet());
Source:
public AbstractMetric(String metricName, String metricType, T initialValue, MetricReportManager manager) { name = metricName; type = metricType; value = initialValue; metricManager = manager; }

Target:
I would make this constructor `protected` because you cannot directly instantiate abstract classes. See the answers to http://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor for a discussion.
Source:
public void hasSameValues_checkingAgainstSameInstanceOfAllergy_shouldInterpretAsSameValues() { Allergy allergy = allergy(); allergy.hasSameValues(allergy()); }

Target:
Shouldn't this line be something like AssertTrue(allergy.hasSameValues(allergy())); ?
Source:
private static String readMapping() throws IOException, ParseException { JSONParser parser = new JSONParser(); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classloader.getResourceAsStream("mapping.json"); String mapping = IOUtils.toString(inputStream, "UTF-8"); Object object = parser.parse(mapping); JSONObject jsonObject = (JSONObject) object; return jsonObject.toJSONString(); }

Target:
You are open a stream object without closing it never. Maybe you can use the try-with-resources statement here and avoid / handle the unhandled IOException here.
Source:
public synchronized void commit() throws CommitException { SyncCommitObserver sco = null; try { sco = new SyncCommitObserver(); commitAsync(sco); sco.waitForCommit(); } finally { updates.clear(); weakNotification = null; observedColumns.clear(); columnsRead.clear(); } }

Target:
@mjwall I found the bug. Its my fault, I suggested clearing `observedColumns` and that is a bad thing to do. `observedColumns` is shared between transactions. It should be an immutable set, I'll open an issue for that.
Source:
public static boolean hasPictureId(byte[] buf, int off, int len) { if (!isValid(buf, off)) return false; if ((buf[off] & X_BIT) == 0 || (buf[off+1] & I_BIT) == 0) return false; return true; }

Target:
I would simplify to "return isValid(buf,off) && (buf[off] & X_BIT != 0) && (buf[off+1] & I_BIT) != 0)"
Source:
public void setEnabled(boolean enabled) { this.active = enabled; System.out.println("active state change: " + active); updateButtonState(); }

Target:
remove the println
Source:
default void beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { throw new UnsupportedOperationException("Method is not implemented"); }

Target:
Same here. I dont think we should be throwing exceptions.We should instead be having empty implementations.
Source:
private void handleEndActionJobAndStep() { if (!hasTaskHandlers() || getExecutionIndex() == getTaskHandlers().size() - 1) { if (!parentHasCallback() || getExecutionContext().getExecutionMethod() == ExecutionMethod.AsStep) { startFinalizingStep(); } } }

Target:
the inner 'if' isn't needed - the conditions can be added to the outer 'if'
Source:
private boolean waitForScanState(ScanStates state) { try { while (!getScanState().equals(state)) { scanState.wait(); } return true; } catch (InterruptedException e) { tsLogger.logger.warn("problem waiting for scanLock whilst in state " + state.name(), e); return false; } }

Target:
why did you change the do ... while into a while do loop. The caller already knows the scan state is not equal to state and since this is a private method it is safe to assume that the caller has already checked (under the lock) that he has to wait for a state change.
Source:
private void maybeScheduleCheckpoint() { switch (state()) { case RESTORING: this.checkpoint = checkpointableOffsets(); break; case RUNNING: if (!eosEnabled) { this.checkpoint = checkpointableOffsets(); } break; case SUSPENDED: this.checkpoint = checkpointableOffsets(); break; case CREATED: case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while scheduling checkpoint for active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while scheduling checkpoint for active task " + id); } }

Target:
Could we merge RESTORING and SUSPENDED?
Source:
protected void executeQueryCommand() { Provider hostProvider = getProvider(); HostProviderProxy proxy = ((HostProviderProxy) ProviderProxyFactory.getInstance().create(hostProvider)); getQueryReturnValue().setReturnValue(chainToString(proxy.getCertificateChain())); }

Target:
Why do you cast to HostProviderProxy?
Source:
public void t1() { testCaseExecutionOrder.add(new Object() {}.getClass().getEnclosingMethod().getName()); }

Target:
We could have leveraged `InvokedMethodListener` for this. See [here](https://github.com/cbeust/testng/blob/master/src/test/java/test/InvokedMethodListener.java)
Source:
public void testValidateDataStreamsNoConflicts() { Metadata metadata = createIndices(5, 10, "foo-datastream").metadata; try { validateDataStreams(metadata.getIndicesLookup(), (DataStreamMetadata) metadata.customs().get(DataStreamMetadata.TYPE)); } catch (Exception e) { fail("did not expect exception when validating a system without indices that would conflict with future backing indices: " + e.getMessage()); } }

Target:
Currently when the test fails with any error then there is no stacktrace to the original failure, which I think makes pinpointing the culprit easier? That being said, this is just preference, so feel free to ignore :)
Source:
public ShaderProvider getPassShaderProvider (int n) { if (n >= passShaderProviders.length) throw new GdxRuntimeException("ShaderProvider " + n + " doesn't exist in " + getClass().getName()); return passShaderProviders[n]; }

Target:
I dont think that this check is needed here (otherwise it will throw an index out of bounds exception, which says the same). https://github.com/libgdx/libgdx/wiki/Contributing#performance-considerations
Source:
public void onConnectionClosedForUser(QBRTCSession qbrtcSession, Integer integer) { setStatusForOpponent(integer, getString(R.string.closed)); stopTimer(); }

Target:
stopTimer() нужно поставить где сессия закрывается вообще, а не для конкретного юзера
Source:
public void install(ITextViewer textViewer) { for (IReconciler iReconciler : fReconcilers) { if(iReconciler != null) { iReconciler.install(textViewer); } } }

Target:
It would be better to run checks in the constructor to make sure no reconciler is null, or to create an actual list of non-null reconcilers that would be dereferenced here.
Source:
public JettyServer run(WebApplicationContext baseContext, boolean directlyUseAsWebAppRoot, Function<Function<Integer, JettyServer>, JettyServer> serverStarter, boolean exitOnError) { try { configureLogger(); configureSentry(baseContext); JettyServer jettyServer = createJettyServer(baseContext, directlyUseAsWebAppRoot, serverStarter, v->v.addLifeCycleListener(new JettyLifeCycleListener(baseContext))); jettyServer.start(); logStartupInfo(baseContext); return jettyServer; } catch (Exception e) { return logErrorAndExit(e, exitOnError); } }

Target:
а мы разве можем хоть когда-то не захотеть добавлять listener - я бы это унес прям в основной webAppInitializer
Source:
public PlanItem(String id, String definitionRef) { super(); this.id = id; this.definitionRef = definitionRef; }

Target:
AFAIK this is redundant.
Source:
public int hashCode() { return name.hashCode(); }

Target:
Looking on `QName` class, maybe we should use `return ~~name.hashCode()`.