auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Long getTimeFromDateString(String dateString) { try { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date date = dateFormatter.parse(dateString); return date.getTime(); } catch (ParseException e) { logger.warn("Could not parse milliseconds from an HTTP date header (" + dateString + ")."); return null; } }

Target:
minor `return dateFormatter.parse(dateString).getTime()`
Source:
public OpaqueTokenConfigurer(ApplicationContext context) { this.context = context; }

Target:
Please remove the `public` modifier
Source:
public void onDateInputBlur(final BlurEvent blurEvent) { final Object target = getEventTarget(blurEvent); if (this.onValueInputBlur != null && !Objects.isNull(target)) { onValueInputBlur.accept(blurEvent); } }

Target:
For consistency, could we use `!Objects.isNull(this.onValueInputBlur) && !Objects.isNull(target)` please?
Source:
public void registerAt(Class<? extends Filter> filter, Class<? extends Filter> atFilter) { Integer position = getOrder(atFilter); if (position == null) { throw new IllegalArgumentException( "Cannot register after unregistered Filter " + atFilter); } put(filter, position + 1); }

Target:
The new registerAt method has the same implementation as the existing registerAfter method. Possible case for reuse.
Source:
public boolean matches(String packageName) { if (packageName == null || packageName.isEmpty()) { return false; } boolean result = false; for (Pattern pattern : patterns) { result |= pattern.matcher(packageName).matches(); } return result; }

Target:
Just a little otimization: if one pattern matches, you don't need to check the others. To do this, write if (pattern.matcher(packageName).matches()) return true;
Source:
public Mapping<String, V> build() { return new ImmutableDomainWildcardMapping<V>(defaultValue, new LinkedHashMap<String, V>(map)); }

Target:
you can pass directly `map` to the `ImmutableDomainWildcardMapping` constructor (it will make the copy internally)
Source:
static boolean isFixedWidth(ValueVector vv) { return (vv instanceof FixedWidthVector); }

Target:
```suggestion private static boolean isFixedWidth(ValueVector vv) { return (vv instanceof FixedWidthVector); } ```
Source:
public static Mono<byte[]> downloadFileAsync(String url, HttpPipeline httpPipeline) { FileService service = RestProxy.create(FileService.class, httpPipeline); try { return service.download(getHost(url), getPathAndQuery(url)) .flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue())); } catch (MalformedURLException ex) { return Mono.empty(); } }

Target:
Maybe a `Mono.error` would be more proper? Generally we would like an error early than late.
Source:
public long getOldestWriteTimstamp() { // When there is no data in the buffer return the max possible timestamp // so that no query's timestamp is less than this timestamp if(writes.size() == 0) { return Long.MAX_VALUE; } Write oldestWrite = writes.get(0); return oldestWrite.getVersion(); }

Target:
Can you add an explicit else block ``` if (condition) { } else { } ```
Source:
private static String getAddonDirectory(List<String> arguments) { int addDirectoryIndex = arguments.indexOf("--immutableAddonDir") + 1; return arguments.get(addDirectoryIndex); }

Target:
We are asuming we will allways have that argument. Is that the case ?
Source:
private void updateWatchdogModels() { updateWatchdogModels(getOSType().getSelectedItem()); }

Target:
Are these changes relevant to this patch?
Source:
public ScanningMode enter(CtElement element) { CtElement ele = element; if (ele.hasParent(ignoredParent)) { if (element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; }

Target:
I don't understand the purpose of local variable ele here: IMHO you can just remove this variable and the first if.
Source:
protected boolean isInterestingFolder(IFolder folder) { return !findProductFiles(folder, false).isEmpty(); }

Target:
Is this correct? When deleting a product, I would assume that this reports the parent as not interesting and we never see the file delta.
Source:
protected Short getNetworkAccessPointTypeCode(String hostAddress) { if (InetAddressValidator.getInstance().isValid(hostAddress)) { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_IP; } else { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_NAME; } }

Target:
This is the only place you put an "else" after the "if" returns -- for consistency, change this to not use an else statement.
Source:
public void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); maybeThrowIfCommitOffsetsNotOwned(offsets); log.debug("Committing offsets: {}", offsets); offsets.forEach(this::updateLastSeenEpochIfNewer); coordinator.commitOffsetsAsync(new HashMap<>(offsets), callback); } catch (CommitFailedException e) { log.error("Failed to commit offsets asynchronously because they do not belong to dynamically assigned partitions"); callback.onComplete(offsets, e); } finally { release(); } }

Target:
Just wondering, does this mean we did not used to check if all the offsets actually belonged to auto-assigned partitions? Or did we just straight throw the `CommitFailedException`? Is this a behavioral change?
Source:
public void applyState(XSiteState[] chunk) throws Exception { if (trace) { log.tracef("Received state: %s", extractKeys(chunk)); } else if (debug) { log.debugf("Received state: %s keys", chunk.length); } if (transactionManager != null) { applyStateInTransaction(chunk); } else { applyStateInNonTransaction(chunk); } }

Target:
The trace log doesn't allow you to easily see how many entries there are, so it's actually less informative than the debug log :) Long lines in the log can also be a PITA to deal with, I would suggest logging just the number of entries at debug level and a separate line for each processed/skipped entry.
Source:
protected CallbackTracker(RestRequest restRequest, String operationType, Histogram operationTimeTracker, Histogram callbackProcessingTimeTracker) { this.restRequest = restRequest; this.operationType = operationType; this.operationTimeTracker = operationTimeTracker; this.callbackProcessingTimeTracker = callbackProcessingTimeTracker; blobId = RestUtils.getOperationOrBlobIdFromUri(restRequest); }

Target:
Can we define enums for operation type
Source:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); }

Target:
Can this move closer to the end of this method? The app remove can happen after the shell is disposed since it's TBR is already false.
Source:
public boolean isComplex() { if (metadata.getType().getMinorType() == MinorType.MAP || metadata.getType().getMinorType() == MinorType.UNION || metadata.getType().getMinorType() == MinorType.LIST) { return true; } return false; }

Target:
Nit, but ``` return metadata.getType().getMinorType() == MinorType.MAP || metadata.getType().getMinorType() == MinorType.UNION || metadata.getType().getMinorType() == MinorType.LIST; ``` And below.
Source:
protected Builder() { super(ShipyardApi.class); id("shipyard") .name("Shipyard Remote Docker Management API") .identityName("<shipyard-service-key>") .credentialName("not used") .documentation(URI.create("http://shipyard-project.com/docs/api/")) .version("2.0.4") .defaultEndpoint("https://127.0.0.1:8080") .defaultProperties(ShipyardApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.<Class<? extends Module>>of( OkHttpCommandExecutorServiceModule.class, ShipyardHttpApiModule.class)); }

Target:
Remove this from this list. The preferred way is to install it as part of the `ShipyardHttpApiModule`, which has already been done.
Source:
PrintWriter createErrorWriter() { return new PrintWriter( new OutputStreamWriter(System.err, StandardCharsets.UTF_8)); }

Target:
optional: import UTF_8 static
Source:
public void selectAll(){ int numberOfFiles = mAdapter.getCount(); for(int i = 0; i < numberOfFiles; i++){ File file = (File) mAdapter.getItem(i); if (file != null) { /// Click on a directory if (file.isDirectory()) { } else { /// Click on a file getListView().setItemChecked(i, true); // notify the change to the container Activity mContainerActivity.onFileClick(file); } } } }

Target:
If we are not doing anything when file is a directory, this check is not necessary.
Source:
public VersionNumber getNeededDependenciesMinimumJavaVersion() { VersionNumber versionNumber = null; try { versionNumber = minimumJavaVersion == null ? null : new VersionNumber(minimumJavaVersion); } catch (NumberFormatException nfe) { logBadMinJavaVersion("'minimumJavaVersion' was specified for plugin ''{0}'' but unparseable (received {1})", this.name, minimumJavaVersion); } for (Plugin p: getNeededDependencies()) { VersionNumber v = p.getNeededDependenciesMinimumJavaVersion(); if (v == null) { continue; } if (versionNumber == null || v.isNewerThan(versionNumber)) { versionNumber = v; } } return versionNumber; }

Target:
I tend to agree, but I used the existing naming pattern. So I think either we'd fix everything, or nothing to be consistent.
Source:
public void validate() { throw new CacheConfigurationException("MODULE ERROR"); }

Target:
you could throw a ```RuntimeException``` to have a better simulation.
Source:
public void addPages() { addPage(fSelectPage); addPage(fSelectDirectories); addPage(fScanPage); addPage(fImportOptions); }

Target:
remove empty line
Source:
public CheckEditPartResized(SWTBotGefEditPart editPartBot) { this.graphicalEditPart = (GraphicalEditPart) editPartBot.part(); this.initialSize = graphicalEditPart.getFigure().getBounds().getSize().getCopy(); }

Target:
You can replace by: this((GraphicalEditPart) editPartBot.part());
Source:
public static long getBaseSize(byte[] delta) { int p = 0; long baseLen = 0; int c, shift = 0; do { c = delta[p++] & 0xff; baseLen |= ((c & 0x7f) << shift); shift += 7; } while ((c & 0x80) != 0); return baseLen; }

Target:
looks like this explicit cast was done to prevent overflow, hence I am not sure if it is safe to remove this cast same question for the other occurrences below
Source:
public Result apply(N node, Captures captures, Context context) { Map<DereferenceExpression, VariableReferenceExpression> expressions = getDereferenceSymbolMap(ExpressionExtractor.extractExpressionsNonRecursive(node), context, metadata, sqlParser); if (expressions.isEmpty()) { return Result.empty(); } return Result.ofPlanNode(new ProjectNode(context.getIdAllocator().getNextId(), rewrite(context, node, HashBiMap.create(expressions)), identityAssignmentsAsSymbolReferences(node.getOutputVariables()))); }

Target:
static import ExpressionExtractor.extractExpressionsNonRecursive
Source:
protected void onResume() { String action = getIntent().getAction(); if (action == null || !action.equals("Already created")) { // don't restart if action is present Intent intent = new Intent(this, AddBudgetActivity.class); startActivity(intent); finish(); } else { // remove the unique action so the next time onResume // call will force restart getIntent().setAction(null); } super.onResume(); }

Target:
Move this call to the start of the method, since that's generally how it's done.
Source:
public QuotaViolationException(MetricName metricName, double value, double bound) { super(metricName + " violated quota."); this.metricName = metricName; this.value = value; this.bound = bound; }

Target:
I think we want to make the string computation lazy, but not lose info. We could do that by overriding `toString`.
Source:
public VViewModelProperties inherit() { final VDefaultViewModelProperties properties = VViewFactory.eINSTANCE.createDefaultViewModelProperties(); properties.getInheritableProperties().addAll(getInheritableProperties().entrySet()); return properties; }

Target:
needs cloning
Source:
public static XmlDataProviderManager getInstance() { if (INSTANCE == null) { INSTANCE = new XmlDataProviderManager(); } return INSTANCE; }

Target:
sync
Source:
private void handleFailure(Throwable t) { if (message.doCallbackOnFailure()) { MessageOut response = new MessageOut(MessagingService.Verb.INTERNAL_RESPONSE) .withParameter(ParameterType.FAILURE_RESPONSE, MessagingService.ONE_BYTE); if (t instanceof TombstoneOverwhelmingException) { response = response.withParameter(ParameterType.FAILURE_REASON.FAILURE_REASON, Shorts.checkedCast(RequestFailureReason.READ_TOO_MANY_TOMBSTONES.code)); } MessagingService.instance().sendReply(response, id, message.from); } }

Target:
It's just a bug in the code that happens to compile and work (with a warning). I'll remove the extra one.
Source:
public Optional<UsernamePasswordCredentials> extract(WebContext context) { final String username = context.getRequestParameter(this.usernameParameter); final String password = context.getRequestParameter(this.passwordParameter); if (username == null || password == null) { return Optional.empty(); } return Optional.of(new UsernamePasswordCredentials(username, password)); }

Target:
I'm surprised that getRequestParameter does not return an Optional :)
Source:
public void partHidden(IWorkbenchPartReference partRef) { setActive(partRef, false); }

Target:
This causes now editor not to open (sometimes) on BP hit if the debug view is hidden - all in a single window. Open Java perspective, start debugging, close editor, hide view, resume after few times editor is not opened...
Source:
public boolean isSelected() { if (parent != null) { return parent.isSelected(); } return selected; }

Target:
again I don't think we should modify the generated methods. If we need to we should set this on merge.
Source:
public A value() { return trampoline().run(); }

Target:
could be `final`.
Source:
private RelationalSymbolicValue(Kind kind, SymbolicValue leftOp, SymbolicValue rightOp) { super(leftOp, rightOp); this.kind = kind; }

Target:
operands can be directly initialized : this.leftOp = leftOp; and so only super() constructor is required.
Source:
private void mapNodes() { if (fNodesList == null) { fNodesMap = new HashMap<>(1); return; } // Create a map with capacity for all child nodes. fNodesMap = new HashMap<>(fNodesList.size() * 4 / 3); for (ModelDelta element : fNodesList) { mapNode( element ); } }

Target:
please name all 4 loop vars either node or delta
Source:
public File generateMultipleDockets(Collection<DocketData> docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket_multipage.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(file); try { exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } finally { fileOutputStream.flush(); fileOutputStream.close(); } return file; }

Target:
Please use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement instead of handling this manually.
Source:
private ContentSource source(AbstractTreeIterator iterator) { if (iterator instanceof WorkingTreeIterator) return ContentSource.create((WorkingTreeIterator) iterator); return ContentSource.create(db.newObjectReader()); }

Target:
style nit: missing braces
Source:
public void copy(IFileStore destination, int options, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); final IFileInfo sourceInfo = fetchInfo(EFS.NONE, null); if (sourceInfo.isDirectory()) { copyDirectory(sourceInfo, destination, options, subMonitor.split(1)); } else { copyFile(sourceInfo, destination, options, subMonitor.split(1)); } }

Target:
No submonitor is needed in this method. The original monitor can be passed to mutually exclusive method calls as is.
Source:
public void stopTransport() { if (transport != null && transportStatus == ComponentStatus.RUNNING) transport.stop(); transportStatus = ComponentStatus.TERMINATED; try { unregisterServerMBeans(); } catch (Exception e) { throw new CacheException(e); } }

Target:
I think you meant to have brackets encapsulate the entire rest of the method?
Source:
public void test43() throws Exception { ClassNode cls = getClassNode(TestCls.class); String code = cls.getCode().toString(); assertThat(code, containsOne("continue;")); }

Target:
In this case jadx replace `continue` with `else` and I think this is correct change. Anyway, jadx don't have any information to restore such code. Or I miss something? P.S. Next time for complex code write `check` method to check that method logic not changed after transformations during decompilation (as example see [`TestSwitchWithFallThroughCase`](https://github.com/skylot/jadx/blob/e1f4955286f73a6ca4525fc27b11fd02106f7f08/jadx-core/src/test/java/jadx/tests/integration/switches/TestSwitchWithFallThroughCase.java#L44) test) because sometimes code changed heavily but logic is preserved and is hard to check such case with "eye".
Source:
public List<DocumentType> getSpecialDocumentTypes() { checkDirty(); return specialDocumentTypes.values().stream().collect(Collectors.toList()); }

Target:
`Collections#unmodifiableList` could be better there.
Source:
public void postReport(String urlString, Report report, Map<String, String> headers) throws NetworkException, BadResponseException { try { nullCheckLatch.await(20, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { exception.printStackTrace(); } super.postReport(urlString, report, headers); }

Target:
Is it worth extending this timeout? AFIACT it won't effect the correct working of the latch, but could prevent issues if the tests are running on an especially slow device/simulator.
Source:
public static String composeObjectId(AuditLogableBase logable, AuditLogType logType) { return composeObjectId(logable, logType, logable.getUserId()); }

Target:
this method can be non-static and private - it isn't used outside of the class
Source:
private void removeSessionImpl(String sessionId, int reason, String message, Object... msgArgs) { AcctUtils.reportRecords(reason, getPrincipalName(sessionId), (ExtMap) getData(sessionId, AUTH_RECORD_PARAMETER_NAME, false), (ExtMap) getData(sessionId, PRINCIPAL_RECORD_PARAMETER_NAME, false), message, msgArgs ); sessionInfoMap.remove(sessionId); getDbFacade().getEngineSessionDao().removeBySessionId(sessionId); }

Target:
you can remove by seq... no?
Source:
private int createHashCode() { int result = System.identityHashCode( scriptEvaluatorFactory ); result = 31 * result + System.identityHashCode( clockProvider ); result = 31 * result + ( temporalValidationTolerance != null ? temporalValidationTolerance.hashCode() : 0 ); result = 31 * result + System.identityHashCode( constraintValidatorPayload ); return result; }

Target:
The `temporalValidationTolerance` cannot be null either (and you don't have the null check in the `equals()` method anyway). Will change.
Source:
public int getNumThreads() { int numThreadsConfigured = getNumThreadsConfigured(); if (numThreadsConfigured != DEFAULT_NUM_THREADS) { return numThreadsConfigured; } else { return Runtime.getRuntime().availableProcessors() - 1; } }

Target:
I suspect this code is unused (or maybe lightly used) or else someone would have complained by now that it doesn't work when you only have one processor. It should be `max(1, Runtime.getRuntime().availableProcessors() - 1)`.
Source:
protected String generateSlug(Id id) { return "app-" + idCodec.encode(id.toBigInteger()); }

Target:
If it shouldn't be possible to store an Application without a slug then this abstract implementation should have control over it and not rely on an implementation calling this method.
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { setRetainInstance(true); return new BottomSheetDialog(requireContext(), getTheme()); }

Target:
Invoking `setRetainInstance(true)` on a fragment with UI is quite risky (we might/will leak all the views), do we really need it? Moreover, `SignupBottomSheetDialogFragment` currently holds a reference to the Activity, which will also leak after a configuration change. Wdyt?
Source:
public boolean onBlockStartBreak(ItemStack stack, BlockPos pos, EntityPlayer player) { if(!ToolHelper.isBroken(stack) && this instanceof IAoeTool && ((IAoeTool) this).isAoeHarvestTool()) { for(BlockPos extraPos : ((IAoeTool) this).getAOEBlocks(stack, player.worldObj, player, pos)) { breakBlock(stack, player, extraPos, pos); } } return super.onBlockStartBreak(stack, pos, player); }

Target:
Redundant instanceof and casts
Source:
protected void setRefLogIdent(final PatchSetApproval submitAudit) { if (submitAudit != null) { branchUpdate.setRefLogIdent(mArguments.identifiedUserFactory.create( submitAudit.getAccountId()).newRefLogIdent()); } }

Target:
Should subclasses be allowed to override this method?
Source:
public PipeRunResult doPipe(Message message, IPipeLineSession session) throws PipeRunException { try { try (MessageOutputStream target=MessageOutputStream.getTargetStream(this, session, getNextPipe())) { try (OutputStream out = target.asStream()) { pgpAction.run(message.asInputStream(), out); } return target.getPipeRunResult(); } } catch (Exception e) { throw new PipeRunException(this, "Exception was thrown during PGPPipe execution.", e); } }

Target:
mag 1 try weg?
Source:
public void saveRevisionData(Session session, Object revisionData) { session.save( revisionInfoEntityName, revisionData ); if ( revisionInfoNumberReader != null ) { if ( revisionInfoNumberReader.getRevisionNumber( revisionData ).longValue() < 0 ) { throw new AuditException( "Negative revision numbers are not allowed" ); } } sessionCacheCleaner.scheduleAuditDataRemoval( session, revisionData ); }

Target:
it seems using `&&` is more in line with existing coding pattern, though minor.
Source:
private static boolean isRootPrivate(Component root, Map<String, ComponentDto> existingDtosByKeys) { String rootKey = root.getKey(); ComponentDto rootDto = existingDtosByKeys.get(rootKey); if (rootDto == null) { if (Component.Type.VIEW == root.getType()) { return NEW_VIEWS_SHOULD_BE_PRIVATE; } throw new IllegalStateException(String.format("The project '%s' is not stored in the database, during a project analysis.", rootKey)); } return rootDto.isPrivate(); }

Target:
Using `false` is enough here, without constant
Source:
public void error(SAXParseException e) throws SAXException { if (firstException == null) { firstException = e; messageBuffer = new StringBuilder(64); messageBuffer.append('\'').append(resourceId).append('\'').append("' validation error:"); } messageBuffer.append('\n').append(e.toString()); }

Target:
I might be missing something, but it seems that this method doesn't throws a SAXException. Perhaps it should "throw e" at the end?
Source:
public void onGoogleSignupFinished(String name, String email, String photoUrl, String username) { AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_SOCIAL_SUCCESS); mLoginAnalyticsListener.trackAnalyticsSignIn(false); if (mIsJetpackConnect) { ActivityLauncher.showSignupEpilogueForResult(this, name, email, photoUrl, username, false); } else { ActivityLauncher.showMainActivityAndSignupEpilogue(this, name, email, photoUrl, username); } setResult(Activity.RESULT_OK); finish(); }

Target:
Shouldn't this be `trackAnalyticsSignIn(true)`? I believe the flag is meant to identify self-hosted vs WP.com logins, and WP.com signups should count as the latter.
Source:
protected void log(final Level level, final String msg, final Throwable t) { this.logger.log(level, this.simpleName + " " + msg, t); }

Target:
warning: The static field AbstractProcessor.logger should be accessed in a static way.
Source:
private short[] toShortArray(int[] ints) { if (ints == null) { return null; } short[] shorts = new short[ints.length]; for (int i = 0; i < shorts.length; i++) { shorts[i] = toShort(ints[i]); } return shorts; }

Target:
minor: make it static
Source:
protected void onSuccess(List<Question> questions) { if (questions == null) { showAlert("GetQuestion", "質問がありません。"); } else { for (Question q : questions) { questionList.add(q); } } // スクロールを確認するため追加 for (int i = 0; i < 20; i++) questionList.add(new Question("タイトル" + i, "本文" + i, "作者" + i)); adapter.notifyDataSetChanged(); }

Target:
ここは、`questionList.addAll(questions);`と書くとすっきりしますね。
Source:
public AssociationOrderBy(String expression, String order) { columnName = expression.substring( 1, expression.length() - 1 ); kind = ( "desc".equalsIgnoreCase( order ) ) ? Order.DESC : Order.ASC; }

Target:
Nit picking, but we don't need the extra brackets. Let's just keep: ``` kind = "desc".equalsIgnoreCase( order ) ? Order.DESC : Order.ASC; ```
Source:
public FloatSelectiveStreamReader( StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, boolean outputRequired, LocalMemoryContext systemMemoryContext) { this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = filter.orElse(null); this.outputRequired = outputRequired; this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || this.filter.testNull(); }

Target:
nulls should be allowed if filter is non-deterministic; consider adding a test that uses `array(real)` to test this `nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull();`
Source:
public void setProvidedProducts(Collection<Product> providedProducts) { this.providedProductDtos = null; if (providedProducts != null) { this.providedProducts = new HashSet<>(providedProducts); } }

Target:
We need to clear the collection here if the inbound collection is null. Can probably just drop the entire thing down to single line: ``` this.providedProducts = providedProducts != null ? new HashSet<>(providedProducts) : null; ```
Source:
public NetworkCommon(T parameters) { super(parameters); this.setStoragePoolId(getNetwork().getDataCenterId()); }

Target:
The changes make this line relevant only for AddNetworkCommand. Please remove it and modify: AddNetworkCommand.getPermissionCheckSubjects() to use getNetwork() instead in a safe way. It can come as a follower patch.
Source:
private Collection<File> transactionFiles( File dbLocation ) throws IOException { Collection<File> txFiles = new ArrayList<>(); DirectoryStream<Path> dirStream = Files.newDirectoryStream( dbLocation.toPath(), "neostore.transaction.db.*" ); dirStream.forEach( path -> txFiles.add( path.toFile() ) ); return txFiles; }

Target:
you need to close this directory stream
Source:
private String getBundleVersion() { ClassLoader cl = getClass().getClassLoader(); if (cl instanceof URLClassLoader) { URL url = ((URLClassLoader) cl).findResource(JarFile.MANIFEST_NAME); try { Manifest manifest = new Manifest(url.openStream()); return manifest.getMainAttributes().getValue("Bundle-Version"); } catch (IOException e) { // do nothing - will return null } } return null; }

Target:
url should be checked for null.
Source:
protected void configure() { super.configure(); install(new OkHttpCommandExecutorServiceModule()); bind(new TypeLiteral<Supplier<SSLContext>>() { }).to(new TypeLiteral<SSLContextWithKeysSupplier>() { }); bind(OkHttpClientSupplier.class).to(new TypeLiteral<DockerOkHttpClientSupplier>() {}); }

Target:
Do it simpler: ``` java bind(OkHttpClientSupplier.class).to(DockerOkHttpClientSupplier.class); ```
Source:
public void setupEnvironment() { CorrelationIdTracker.clean(); DbUser user = mock(DbUser.class); when(engineSessionDao.remove(anyLong())).thenReturn(1); mcr.mockConfigValue(ConfigValues.UserSessionTimeOutInterval, 30); sessionDataContainer.setUser(session, user); }

Target:
If this is done for every test case, why not just do in in the MockConfigRule's constructor in line 33?
Source:
public void clear() { commands.clear(); ; items.clear(); getView().clear(); }

Target:
Useless statement.
Source:
public void setNearClip(float nearClipIn) { nearClip = nearClipIn; }

Target:
I'd write: `this.nearClip = nearClip` And I'd use the same also in the following method. Or did you get a checkstyle warning about it?
Source:
public void scheduleTask(TaskDefinition task) throws SchedulerException { boolean contains = false; for (String taskDef : scheduledTasks) { if (taskDef.equals(task.getName())) { contains = true; break; } } if (!contains) { scheduledTasks.add(task.getName()); } }

Target:
Oh i see! If it is only used for testing purposes and hence in src/test, then you are correct to have it stay. 👍
Source:
public SafeHtml getValue() { if (showUnderline) { return templates.underlinedHeader(headerText); } return headerText; }

Target:
I would use the showUnderline in the setter instead of the getter. Now each time getValue is called, it has to evaluate the template. If you do that in the setter, then the value is always the underlined version and the evaluation only happens once.
Source:
private String resolveUrl(URI uri, String link) { String url = cfg.getString("gerrit", null, "canonicalWebUrl"); if (Strings.isNullOrEmpty(url)) { url = uri.toString(); } if (!url.endsWith("/")) { url += "/"; } if (Strings.isNullOrEmpty(link)) { url += "#" + link; } return url; }

Target:
Should this be if (!Strings.isNullOrEmpty(link)) { ?
Source:
public void onSkipInWrite(S item, Throwable t) { if(skipWriteDelegate != null && t instanceof Exception) { try { skipWriteDelegate.onSkipWriteItem(Collections.<Object>singletonList(item), (Exception) t); } catch (Exception e) { throw new BatchRuntimeException(e); } } }

Target:
This actually isn't correct. The "item" in this case that is being passed to the JSR-352 SkipListener is actually all the items in the current chunk. Unlike Spring Batch, the JSR does not provide facilities to identify which item within a chunk caused the error. See section 9.2.7 of the spec for more detail
Source:
private FileStatus[] listConstraintFilesInDBDir(FileSystem fs, Path dbDir) { try { return fs.listStatus(new Path(dbDirs[0].getPath(), ReplicationSemanticAnalyzer.CONSTRAINTS_ROOT_DIR_NAME)); } catch (FileNotFoundException e) { return new FileStatus[]{}; } catch (IOException e) { throw new RuntimeException(e); } }

Target:
Shall use dbDir instead of dbDirs[0] array.
Source:
public static boolean sqSupportsExternalIssues() { return orchestrator.getServer().version().isGreaterThanOrEquals(7, 2); }

Target:
Access can be private
Source:
public void testMakeTimeZone_All() throws IOException { ZoneInfoDB.TzData instance = ZoneInfoDB.getInstance(); String[] availableIDs = instance.getAvailableIDs(); Arrays.sort(availableIDs); for (String id : availableIDs) { BufferIterator bufferIterator = instance.getBufferIterator(id); // Create a ZoneInfo at the earliest possible time to allow us to use the // useDaylightTime() method to check whether it ever has or ever will support daylight // savings time. ZoneInfo zoneInfo = ZoneInfo.makeTimeZone(id, bufferIterator, Long.MIN_VALUE); assertNotNull("TimeZone " + id + " was not created", zoneInfo); assertEquals(id, zoneInfo.getID()); } }

Target:
It will be interesting to see if this times out / runs out of memory on low spec devices. It's a good test, though.
Source:
public Integer getDefaultAutoLimit() { return defaultAutoLimit; }

Target:
```suggestion public int getDefaultAutoLimit() { ```
Source:
public byte getFormatVersion() { return formatVersion; }

Target:
Can be package-private
Source:
public SubscribeRule(@JsonProperty("type") final Type type, @JsonProperty("all") final Boolean all, @JsonProperty("publisher") final String publisher, @JsonProperty("track") final String track, @JsonProperty("kind") final Kind kind, @JsonProperty("priority") final Priority priority) { this.type = type; this.all = all; this.kind = kind; this.priority = priority; this.publisher = publisher; this.track = track; }

Target:
nit: ordering is different.
Source:
public Subcategory getSubcategory() { return subcategories.get(0); }

Target:
Backward incompatible change: if there are no subcategories it used to return null, now it's throwing null pointer.
Source:
public void load(LazyBlock lazyBlock) { if (block == null) { return; } while (block instanceof LazyBlock) { block = ((LazyBlock) block).getBlock(); } Block coercedBlock = coercer.apply(block); lazyBlock.setBlock(coercedBlock); // clear reference to loader to free resources, since load was successful block = null; }

Target:
Use `if` here instead. We don't nest `LazyBlock`s
Source:
public final String dumpConfiguration() { if (this.properties.isEmpty()) return "No configuration settings stored"; @SuppressWarnings("rawtypes") Enumeration e = this.properties.propertyNames(); String response = "TSD Configuration:\n"; response += "File [" + this.config_location + "]\n"; while (e.hasMoreElements()) { String key = (String) e.nextElement(); response += "Key [" + key + "] Value [" + this.properties.getProperty(key) + "]\n"; } return response; }

Target:
You want to cumulate in a `StringBuilder` here, not a plain `String`.
Source:
public void cleanup() { try { log.info("Start cleanup"); DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.AuditLogAgingThreshold) * -1); auditLogDao.removeAllBeforeDate(latestTimeToKeep); log.info("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing audit log cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } }

Target:
We should move that to debug in different patch (or remove at all), I see no value for that in INFO level
Source:
public void saveContainer(String id) { HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph Optional.ofNullable(canvasHandler.getGraphIndex().get(id)).ifPresent(node -> { map.put(DEFAULT_NODE_ID, id); map.put(svgNodeId, id); }); context.saveGroup(map); }

Target:
In this case, `Optional` doesn't really give you anything. A simple null check does the exact same thing, doesn't allocate a new object on the heap, and doesn't require a lambda. Also, this seems much better readable: String node = canvasHandler.getGraphIndex().get(id); if (canvasHandler.getGraphIndex().get(id) == null) { context.saveGroup(Collections.emptyMap()); } else { HashMap<String, String> map = new HashMap<>(2); map.put(DEFAULT_NODE_ID, id); map.put(svgNodeId, id); context.saveGroup(map); } Overall, this is also much more efficient that the original.
Source:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(DbFacade.getInstance() .getGlusterVolumeDao() .getById(getParameters().getVolumeId())); }

Target:
please extract method : protected GlusterVolumeInfoDao getGlusterVolumeInfoDao() The reason for doing this, is so you will be able to write a test using mockito (and not pockermock / static mocking) for this query.
Source:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Prefs.crashedBeforeActivityCreated(false); ActivityUtil.requestFullUserOrientation(this); setTheme(); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); }

Target:
If I'm understanding this patch correctly, the idea is that if we've reached this point, we're not in an infinite crash loop -- is that right?
Source:
void shareFreeList(final BlockRevQueue q) { q.shareFreeList(pending); }

Target:
I would probably implement this the other way around. Since pending is "this" (well, the backing store) we should do: pending.shareFreeList(q); to mirror the intent of the caller of invoking this.shareFreeList(q). Its a subtle issue about how we are discarding a potentially large free list from the bottom of the stack by pushing down an empty free list from the top of the stack. Weird, I know. But at least mirror the caller's intent.
Source:
public static boolean isDomainSocketSupported(WorkerNetAddress workerNetAddress) { boolean isDomainSocketSupported = !workerNetAddress.getDomainSocketPath().isEmpty(); if (isDomainSocketSupported) { if (Configuration.getBoolean(PropertyKey.WORKER_DATA_SERVER_DOMAIN_SOCKET_AS_UUID)) { isDomainSocketSupported = FileUtils.exists(workerNetAddress.getDomainSocketPath()); } else { isDomainSocketSupported = workerNetAddress.getHost().equals(NetworkAddressUtils.getClientHostName()); } } return isDomainSocketSupported && CHANNEL_TYPE == ChannelType.EPOLL; }

Target:
we could simplify this by immediately returning `false` if `workerNetAddress.getDomainSocketPath().isEmpty()`
Source:
public static GrpcDataWriter create(FileSystemContext context, WorkerNetAddress address, long id, long length, RequestType type, OutStreamOptions options) throws IOException { long chunkSize = Configuration.getBytes(PropertyKey.USER_NETWORK_WRITER_CHUNK_SIZE_BYTES); BlockWorkerClient grpcClient = context.acquireBlockWorkerClient(address); try { return new GrpcDataWriter(context, address, id, length, chunkSize, type, options, grpcClient); } catch (Exception e) { // Close the client before releasing in order to get it removed from the pool. grpcClient.close(); context.releaseBlockWorkerClient(address, grpcClient); throw e; } }

Target:
Is there a way to tell that the gRPC channel is in a bad state without having to manually close it?
Source:
public static RowMapperFactory of(Type type, RowMapper<?> mapper) { return (t, ctx) -> t == type ? Optional.of(mapper) : Optional.empty(); }

Target:
Better to use `t.equals(type)` so parameterized types can satisfy test.
Source:
private void updateQosChangeability() { getQosModel().setIsChangable(getQosOverridden().getEntity() && (!getIsToSync().getIsChangable() || getIsToSync().getEntity())); }

Target:
I would check getQosOverridden().getIsChangeable() instead of (!getIsToSync().getIsChangable() || getIsToSync().getEntity()) but as you wish...
Source:
public boolean isRelevant() { if (!jenkins.hasPermission(Jenkins.RUN_SCRIPTS))) { return false; } if (rule.getMasterKillSwitch()) { return true; // always relevant if it is enabled. } return jenkins.isUseSecurity() // if security is off, there's no point && (jenkins.getComputers().length>1 // if there's no slave, || !jenkins.clouds.isEmpty() // and no clouds, likewise this is pointless || Relevance.fromExtension() // unless a plugin thinks otherwise ) ; }

Target:
:bug: uncompilable extra `)`
Source:
public final void validateNullUser() { final AuthKeys authKeys = new AuthKeys(); final String user = null; final String password = "password"; authKeys.authenticate(user, password); }

Target:
avoid one time variables, see https://github.com/tpc2/qulice/wiki/mistakes#one-time-variables
Source:
public int getRackId() { if (rackId == null) { throw new IllegalStateException("rackId not defined for the data node " + hostname + ":" + port); } return rackId; }

Target:
`IllegalStateException` is actually thrown (not `IllegalArgument`).
Source:
public Collection<String> getProductSearchName() { if (aias != null) { return ActionableItems.getNames(aias); } return Collections.emptyList(); }

Target:
Interesting that this method will handle nulls for aias but performSearch would NPE. This was exposed in a change to the test for this class.
Source:
protected boolean validateScreenDescriptor() { if (screenBackgroundColor >= screenColors) { // Not in the specification, but here the background color would refer to a color // index not within the bounds of the Global Color Table. return false; } return true; }

Target:
Please simplify this.
Source:
public void testEmptyKeyDefaults() { for (PropertyKey key : PropertyKey.defaultKeys()) { assertNotEquals(key.getDefaultValue(), "", String.format( "Property keys cannot have a default value of \"\". Offending key: %s", key.getName())); } }

Target:
could we also check that the default value is not `null`?
Source:
private boolean shouldAdd(String dimName) { final boolean belowThreshold = pQueue.size() < this.threshold; final boolean belowMax = belowThreshold || this.comparator.compare(pQueue.peek().getTopNMetricVal(), dimName) < 0; return belowMax && comparator.compare(dimName, previousStop) > 0; }

Target:
Is it possible to avoid copy pasting the code and reuse the code from the other topnresultbuilders?
Source:
public int hashCode() { int result = Objects.hash(entity); result = 31 * result + Arrays.hashCode(values); return result; }

Target:
Any reason why this doesn't use Objects.hash()? Because of the 31 instead of 37? I am ok for changing the hashcode formula here as long as it doesn't violate the equals contract.
Source:
Store getStore(PartitionId id) throws StoreException { BlobStore store = stores.get(id); if (store == null) { throw new StoreException("Could not find partition " + id + " on disk " + disk, StoreErrorCodes.Partition_Not_Found); } if (!store.isStarted()) { throw new StoreException("Store for partition " + id + " on disk " + disk + " has not been started successfully", StoreErrorCodes.Store_Not_Started); } return store; }

Target:
don't need to throw exceptions - just return `null`.
Source:
public static int getValue(String text) { if (text == null || text.isEmpty() || text.equals("build")) { //$NON-NLS-1$ return BUILD; } if (text.equals("codan")) { //$NON-NLS-1$ return CODAN; } if (text.equals("build,codan")) { //$NON-NLS-1$ return BUILD_AND_CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ }

Target:
This is apparently out of date.
Source:
public String getToolTipText(Object element) { if (element instanceof TestCaseElement) { String ignoreReason= ((TestCaseElement) element).getIgnoreReason(); if (ignoreReason != null && ignoreReason.length() > 0) { return ignoreReason; } } return super.getToolTipText(element); }

Target:
!ignoreReason.isEmpty() can be used
Source:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); } return IOUtils.toString(is, DEFAULT_ENCODING); } catch (Exception e) { } } return null; }

Target:
There is no reason to catch all exceptions like this.
Source:
public void testGetLevel() throws Exception { assertEquals(building.getLevel(0), levelA); assertNotSame(building.getLevel(0), levelB); }

Target:
Dodaj testowanie drugiego Levelu. Moim zdaniem ten test sfailuje dla levelu 1.
Source:
public Optional<Shape> getShapeAt(final double x, final double y) { return null; }

Target:
I know this is just test class, but this is what `Optinal.empty()` is for - avoiding necessity to sometimes use null ;-)
Source:
public void setElement( IAdaptable element ) { if (element instanceof ICLineBreakpoint) { fElement = new CBreakpointContext((ICBreakpoint)element, null); } else { fElement = element; } }

Target:
I think we should check for ICBreakpoint instead to include any other kind of breakpoints that uses this properties page. For example a watchpoint or an eventBreakpoing can trigger this code.
Source:
private boolean TxBegin() { if (!TransactionalContext.isInTransaction()) { corfuRuntime.getObjectsView() .TXBuild() .type(TransactionType.OPTIMISTIC) .build().begin(); return true; } return false; }

Target:
I don't like the Idea of managing transactions inside table class
Source:
public UUID send(Iterable<? extends MimeMessage> messages, Session session) throws MessagingException { MailListener listener = getListener("memory"); UUID batchID = sendAsynchronously(messages, session, listener); waitTillSent(Long.MAX_VALUE); Iterator<MailStatus> errors = listener.getErrors(); if (errors.hasNext()) { throw new MessagingException( String.format("Failed to send mail message [%s] ", errors.next().getException())); } return batchID; }

Target:
This is not good enough. How do we know which emails failed to be sent? In addition you're sending an exception only for the frist error... what about all the rest?
Source:
public java.io.File toLocalFile(int options, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor); //caching is the only recognized option if (options != EFS.CACHE) return null; return FileCache.getCache().cache(this, subMonitor); }

Target:
No submonitor is needed in this method. The original monitor can be passed to a single method call as is.
Source:
public NewCommentsConsumer(JiraEndpoint endpoint, Processor processor) { super(endpoint, processor); LOG.info("JIRA NewCommentsConsumer: Indexing current issue comments."); getComments(); }

Target:
We should move such tasks to doStart and not in constructors
Source:
private boolean isCatalogAccessible(String catalogName) { return accessControl.filterCatalogs(session.getIdentity(), ImmutableSet.of(catalogName)).contains(catalogName) && metadata.catalogExists(session, catalogName); }

Target:
i would reverse -- check access control only for existing catalogs. I think an access control impl may have problems for non-existing catalogs. (here & below)
Source:
public static void invalidateThumbnail(PublishedInfo layer) { //Allow a bit of leeway, to support GetMap composer format //(in case of getMap returning before put layer) Date d = new Date(new Date().getTime()-1000); if (Metadata.modified(layer) != null && d.before(Metadata.modified(layer))) { return; } Metadata.map(layer).remove(Metadata.THUMBNAIL); }

Target:
use `System.currentTimeMillis()` and avoid creating Date objects. Not sure why we're using Date objects anyway (for Metadata) but I guess we're stuck now. `Long` would be preferable.
Source:
public void setScrollView(@Nullable ObservableWebView webView) { this.webView = webView; if (this.webView != null) { this.webView.clearAllListeners(); this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }

Target:
I think this should clear any previous webView's listeners, not the current one.
Source:
private void verifyFetchedLog(List<String> logs, String[] expectedLogs) { StringBuilder stringBuilder = new StringBuilder(); for (String log : logs) { stringBuilder.append(log); } String accumulatedLogs = stringBuilder.toString(); for (String expectedLog : expectedLogs) { LOG.error("Checking match for " + expectedLog); assertTrue(accumulatedLogs.contains(expectedLog)); } }

Target:
Can be info log.
Source:
private String uriWithoutExtension(String requestUri) { int suffixStart = requestUri.lastIndexOf("."); if (suffixStart >= 0) { return requestUri.substring(0, suffixStart); } return null; }

Target:
If we can't find an extension, shouldn't we just return `requestUri`?
Source:
private static URL deploymentStaticOne() throws Throwable { System.out.println("deploymentStatic"); return new URL("http://blah.com/static"); }

Target:
Remove this
Source:
public void createAndDropViewTest() throws DatabaseEngineException { test5Columns(); try { engine.dropView("VN"); } catch (final Throwable a) { } engine.executeUpdate( createView("VN").as(select(all()).from(table("TEST"))) ); engine.dropView("VN"); }

Target:
I know this was already like this, but it is weird we are dropping the view before creating. If the goal is to assert that it throws an exception, then we should assert on it, otherwise this is not doing anything.
Source:
private void ensureIndexes() { storageStrategy.ensureIndexes(template.eventCollection(), template.snapshotCollection()); }

Target:
Adjusting this to `private` will be a breaking change - please keep it `public`. Just replacing the `@PostConstruct` for an `@Deprecated` is sufficient I think.
Source:
public <T> ResourceOperations<T> getResourceOperations(Class<T> type) { return (ResourceOperations<T>) (File.class.equals(type) ? DefaultFileOperations.INSTANCE : null); }

Target:
No need to return anything different than DefaultFileOperations.INSTANCE here
Source:
public REVERSE_DEBUG_ACTIONS_ENUM getOperation() { String item = combo.getItem(combo.getSelectionIndex()); return REVERSE_DEBUG_ACTIONS_ENUM.valueOf(item.toUpperCase()); }

Target:
What string is this? Is it the one we defined in messages.properties? If so, this won't work when translated.
Source:
public int fill(final FluidStack resource, final boolean doFill) { if (resource == null) return 0; if (resource.amount <= 0) return 0; if (!matchesFilter(resource)) return 0; int ret = super.fill(resource, doFill); if (ret != 0 && updateCallback != null) updateCallback.accept(this); return ret; }

Target:
This is unnecessary, its called via canFillFluidType() in super.fill().