auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setActionConfirmationMessage(String message) { boolean isNonEmptyMessage = message != null; if (isNonEmptyMessage) { actionConfirmationMessage.setText(message); } actionConfirmationMessage.setVisible(isNonEmptyMessage); }

Target:
When will this be false?
Source:
public void close() throws InterruptedException { close(false, false); }

Target:
the second parameter can be removed
Source:
protected void recursivelyPrint(AbstractPlanNode node, StringBuilder sb) { for (int i = 0; i < indent; i++) { sb.append("\t"); } sb.append(node.toJSONString() + "\n"); indent++; if (node.getChildCount() > 0) { recursivelyPrint(node.getChild(0), sb); } }

Target:
This class has a member variable called `indent` which will incur a data race in `recursivelyPrint`. This is easily fixable though by just making `indent` a parameter to `recursivelyPrint`. I realize it's debug-only code.
Source:
public void update(int inputIndex) { status.setTargetOutputRowCount(super.update(inputIndex, status.getOutPosition())); if (logger.isDebugEnabled()) { logger.debug("BATCH_STATS, incoming {}: {}", inputIndex == 0 ? "left" : "right", getRecordBatchSizer(inputIndex)); } }

Target:
if condition not needed.
Source:
private int getNextPosition() throws CoreException { if (nextMemberPosition == -1) { nextMemberPosition = 0; while (nextMemberPosition < MAX_MEMBER_COUNT && getMemberRecord(nextMemberPosition) != 0) { nextMemberPosition++; } } return nextMemberPosition; }

Target:
Better: nextMemberPosition < 0
Source:
public BulkResponse executeRequest() { if (bulkRequest.numberOfActions() == 0) { return null; } logger.trace("[{}] ES API CALL: bulk request with actions", jobId, bulkRequest.numberOfActions()); BulkResponse bulkResponse = resultsPersisterService.bulkIndexWithRetry( bulkRequest, jobId, shouldRetry, msg -> auditor.warning(jobId, "Bulk indexing of annotations failed " + msg)); bulkRequest = new BulkRequest(AnnotationIndex.WRITE_ALIAS_NAME); return bulkResponse; }

Target:
nit: make `bulkRequest.numberOfActions()` a Supplier so it is only called if trace logging is enabled. ```suggestion logger.trace("[{}] ES API CALL: bulk request with actions", () -> jobId, () -> bulkRequest.numberOfActions()); ```
Source:
public int size() { int size = 0; // We have to loop through to make sure to remove expired entries for (Iterator<InternalCacheEntry<K, V>> iter = iterator(); iter.hasNext(); ) { if (iter.next().getValue() == null) continue; if (++size == Integer.MAX_VALUE) return Integer.MAX_VALUE; } return size; }

Target:
isn't the iterator() excluding the expired and Tombstones?
Source:
public static File getDiskCacheDir(Context context, String uniqueName) { // Check if media is mounted or storage is built-in, if so, try and use external cache dir // otherwise use internal cache dir. final String cachePath; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && context.getExternalCacheDir() != null) { cachePath = context.getExternalCacheDir().getPath(); } else { cachePath = context.getCacheDir().getPath(); } return new File(cachePath + File.separator + uniqueName); }

Target:
I'd prefer the old order so when Environment.getExternalStorageState() return null we don't get an NPE.
Source:
String getBucketName(URI uri) { if (uri.getHost() != null) { return uri.getHost(); } else if (uri.getUserInfo() == null) { return uri.getAuthority(); } throw new IllegalArgumentException("Unable to determine S3 bucket from URI."); }

Target:
mark this method private as this is only used in this class.
Source:
private MustacheFactory createNewMustacheFactory(Class<? extends View> key) { return (fileRoot != null) ? new DefaultMustacheFactory(new FileSystemResolver(fileRoot)) : new DefaultMustacheFactory(new PerClassMustacheResolver(key)); }

Target:
I think we could make this initialization more terse if we initialize `MustacheResolver` with the ternary operator and pass it to `DefaultMustacheFactory`. ```java new DefaultMustacheFactory(fileRoot.isPresent() ? new FileSystemResolver(fileRoot.get()) : new PerClassMustacheResolver(key)) ```
Source:
public boolean isValidValue(final Object element) { boolean result = super.isValidValue(element); if (result) { EObject eObject = EMFHelper.getEObject(element); result = (ProtocolUtils.isProtocol(eObject) && !SystemElementsUtils.isSystemProtocol((Collaboration) eObject) && !SystemElementsUtils.isBaseProtocol((Collaboration) eObject)); } return result; }

Target:
If we're all agreed on letting users choose system protocols in the browser, then I suppose we should not have this condition.
Source:
public void testLogin() throws Throwable { InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { loginTestTask.execute(); } }); assertThat(completionLatch.await(), is(true)); }

Target:
Very minor: consider another helper method for runOnMainSync() so we can focus on the interesting bit (loginTestTask.execute()). As a side note, executing from the main thread doesn't seem to be a requirement of "SaneAsyncTask" for whatever reason. However, it seems more proper to call execute on the main thread[0] since we think of it as a normal AsyncTask so I think we should keep it. [0] http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)
Source:
public static void warnIfDeprecatedDnsLookupValue(AbstractConfig config) { String clientDnsLookupValue = config.getString(CLIENT_DNS_LOOKUP_CONFIG); if (clientDnsLookupValue.equals(ClientDnsLookup.DEFAULT.toString())) log.warn("Configuration '{}' with value '{}' is deprecated and will be removed in " + "future version. Please use '{}' or another non-deprecated value.", CLIENT_DNS_LOOKUP_CONFIG, ClientDnsLookup.DEFAULT.toString(), ClientDnsLookup.USE_ALL_DNS_IPS); }

Target:
We don't need to call `toString()`
Source:
public HdfsCopyStats(String source, File destination, boolean enableStatsFile, int maxVersionsStatsFile, boolean isFileCopy, HdfsPathInfo pathInfo) { this.sourceFile = source; this.totalBytesTransferred = 0L; this.bytesTransferredSinceLastReport = 0L; this.pathInfo = pathInfo; this.lastReportNs = System.nanoTime(); this.startTimeMS = System.currentTimeMillis(); initializeStatsFile(destination, enableStatsFile, maxVersionsStatsFile, isFileCopy); aggStats = HdfsFetcherAggStats.getStats(); }

Target:
I would like to remove the method getStats and would like to make the aggStats static.
Source:
private void writeAlias(VmDevice device) { writer.writeStartElement("alias"); writer.writeAttributeString("name", String.format("ua-%s", device.getId().getDeviceId().toString())); writer.writeEndElement(); }

Target:
toString() is not needed here, AFAIK.
Source:
public ChartData(IDataChartProvider<?> provider, List<ChartSeries> series) { fProvider = provider; fSeries = checkNotNull(ImmutableList.copyOf(series)); }

Target:
You shouldn't need the checkNotNull
Source:
protected boolean isRegistered(final String uuid) { return handlers.containsKey(uuid) && !handlers.get(uuid).isEmpty(); }

Target:
can this case be given? I mean having an entry for the given `uuid` but with no registrations?
Source:
public synchronized Class<?> defineClass(String name, byte[] bytecode) { return defineClass(name, convertClassToResourcePath(name), bytecode); }

Target:
@manstis can this synchronized be removed? this method is only calling the defineClass overload which is already sync'ed.
Source:
public boolean onOptionsItemSelected(MenuItem item) { // home references the app icon if (item.getItemId() == android.R.id.home) { toggle(); // toggles the state of the sliding menu if(getSlidingMenu().isMenuShowing() && menu.isAdded()) setTitle(((ITitleable)menu).getTitle()); return true; } return false; }

Target:
Could we get brackets around this if
Source:
public static ParcelFileDescriptor fromSocket(Socket socket) { FileDescriptor fd = socket.getFileDescriptor$(); try { return fd != null ? ParcelFileDescriptor.dup(fd) : null; } catch (IOException ex) { throw new UncheckedIOException(ex); } }

Target:
super nit (okay to ignore): Here and below: For consistency, consider "e" rather than "ex". Typically we only use "ex" for nested catch blocks where the name "e" is already being used by the enclosing block.
Source:
private String getThemePrefixedPath(String path) { String prefix = themeProperties != null ? themeProperties.get(IntroTheme.ATT_ID) : null; prefix = prefix == null ? "" : prefix.trim(); //$NON-NLS-1$ if (prefix.length() == 0) { return null; } return prefix.charAt(prefix.length() - 1) == Path.SEPARATOR ? prefix + path : prefix + Path.SEPARATOR + path; }

Target:
Is the check for trailing Path.SEPARATOR necessary ? We just got the IntroTheme.ATT_ID property which is not supposed to have a trailing Path.SEPARATOR, no ?
Source:
protected void writeString(int majorType, byte[] bytes) throws IOException { int len = (bytes == null) ? 0 : bytes.length; writeType(majorType, len); m_os.write(bytes); }

Target:
what about the null case?
Source:
private void checkLogData(long address, ILogData logData) { if (logData == null || logData.getType() == DataType.EMPTY) { throw new RuntimeException("Unexpected return of empty data at address " + address + " on read"); } else if (logData.isTrimmed()) { throw new TrimmedException(); } }

Target:
extra `else` statement, please remove
Source:
private static void merge(AggregatedCalledFunction destination, AggregatedCalledFunction source) { long sourceDuration = source.getDuration(); long sourceSelfTime = source.getSelfTime(); destination.addToDuration(sourceDuration); destination.addToSelfTime(sourceSelfTime); destination.fStatistics.update(source.fStatistics.getMaxSegment(),source.fStatistics.getMinSegment(), sourceSelfTime); // merge the children callees. mergeChildren(destination, source); }

Target:
- space after comma - you need to pass the source duration as well
Source:
@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { V value = null; try { value = parseResponse(response, bodyConverter); } catch (Throwable t1) { propagateIfFatal(t1); callback.onError(t1); } if (value != null) callback.onSuccess(value); } return null; }); }

Target:
Think this needs to go right below line 91. `parseResponse` can return `null` (line 133), which will cause this future to never complete.
Source:
public SpiTransaction createServerTransaction(boolean isExplicit, int isolationLevel) { SpiTransaction t = transactionManager.createTransaction(isExplicit, isolationLevel); try { transactionScopeManager.set(t); } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } return t; }

Target:
if (!isExplicit) { // ... around the try
Source:
C baseApply() { final TreeMap<String, String> t = new TreeMap<String, String>(validate()); if(!children.contains(t)) { C child = newChild(); children.put(t, child); return child; } else return children.get(t); }

Target:
What about thread safety here? I might be mistaken, but by just looking at this code snippet it looks like more than one thread could check the condition, receive `false` from the `contains()` method and execute the above code block. That might be the reason the blocking `putIfAbsent` method is used here?
Source:
public void onConnect(String message) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); presenter.startListeningForDirection(); }

Target:
i'd maybe just "forward" the `onConnect` to the presenter instead
Source:
public ByteBuffer[] nioBuffers(int index, int length) { if (b1.nioBufferCount() == 1 && b2.nioBufferCount() == 1) { return new ByteBuffer[] { b1.nioBuffer(), b2.nioBuffer() }; } return ObjectArrays.concat(b1.nioBuffers(), b2.nioBuffers(), ByteBuffer.class); }

Target:
yup, this is incorrect, seems I failed somewhere, this logic has to be in `public ByteBuffer[] nioBuffers()`, gonna change it
Source:
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { this.disabledAdministrativeMonitors = new CopyOnWriteArraySet<>(disabledAdministrativeMonitors); }

Target:
why the instance-level lock suggestion, vs. what's been implemented here. seems like overkill
Source:
public boolean waitUntilReadyToProcess(Properties jobProps) { return true; }

Target:
Is this method going to be overridden in a subclass to provide a different behavior? This method can be protected if is not supposed to be overridden outside the package.
Source:
private ArrayList<Comment> fetchAllComments(ArticleTable article) { return (ArrayList<Comment>) hibernateTemplate.find("FROM Comment WHERE articleId = ?", article.getArticleId()); }

Target:
Casting to `ArrayList` is brittle. Could we return `List<>` from here instead?
Source:
public String getPreview() { StringBuilder bld= new StringBuilder(); bld.append("\n"); if (isEnabled(CleanUpConstants.NUMBER_SUFFIX)) { bld.append("long number1 = 10L;\n"); bld.append("float number2 = 10F;\n"); bld.append("double number3 = 10D;\n"); } else { bld.append("long number1 = 10l;\n"); bld.append("float number2 = 10f;\n"); bld.append("double number3 = 10d;\n"); } return bld.toString(); }

Target:
Missed this one in the previous review, needs updating as well!
Source:
private static ByteBuf serializeProtobuf(MessageLite msg, ByteBufAllocator allocator) { int size = msg.getSerializedSize(); ByteBuf buf = allocator.heapBuffer(size, size); try { msg.writeTo(new ByteBufOutputStream(buf)); } catch (IOException e) { // This is in-memory serialization, should not fail throw new RuntimeException(e); } // Advance writer idx buf.writerIndex(buf.capacity()); return buf; }

Target:
Is this a race or corruption happens all the time? Change looks fine, but I did not understand the actual issue with the current code on why corruption happening.
Source:
public void testEncodeOutputControl() { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_OUTPUT_CONTROL); command.set(Command.KEY_INDEX, 0); command.set(Command.KEY_DATA, "1"); assertEquals("(123456789012345AV001)", encoder.encodeCommand(command)); }

Target:
Is this the value we use for all other protocols?
Source:
void cancel() { super.cancel(); if (callback != null) { callback = null; } }

Target:
No `if` check needed, just always set the reference to `null`.
Source:
public void cancel() { try { Field field = FileWatchdog.class.getDeclaredField("interrupted"); field.setAccessible(true); field.set(this, true); } catch (ReflectiveOperationException cause) { throw new Error("Cannot cancel log4j watchdog", cause); } }

Target:
`new Error` -> `new RuntimeException`
Source:
public static boolean isEditAllowed(@NonNull PageTitle title) { return Arrays.asList(ENABLED_LANGUAGES).contains(title.getWikiSite().languageCode()); }

Target:
Very minor: it's probably cleaner just to initialized ENABLED_LANGUAGES using Arrays.asList
Source:
private InputStream simulateSendAndReceive(ByteArrayOutputStream baos) throws IOException { byte[] bytes = baos.toByteArray(); baos.reset(); int testMessageNo = 1; PacketFormat format = new PacketFormat(testMessageNo, bytes); format.serialize(baos); return new ByteArrayInputStream(baos.toByteArray()); }

Target:
Why is this hardcoded? and why is it 1 not 0?
Source:
public ShovingMatch(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{U}"); // Until end of turn, all creatures gain "{tap}: Tap target creature." Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new TapTargetEffect(), new TapSourceCost()); ability.addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addEffect( new GainAbilityAllEffect(ability, Duration.EndOfTurn, new FilterCreaturePermanent()) .setText("Until end of turn, all creatures gain \"{T}: Tap target creature.\"") ); }

Target:
This wasn't necessary, I was using the constructor I added that defaults to battlefield because most activated abilities are on the battlefield anyway. It doesn't really matter, I just figured I'd mention it.
Source:
public void testCompareRanges() { assertTrue(compareRanges("abcdefghij".getBytes(), 0, 10, "abcdefghij".getBytes(), 0, 10) == 0); assertTrue(compareRanges("123abcdefghij".getBytes(), 3, 10, "abcdefghij".getBytes(), 0, 10) == 0); }

Target:
Use `assertEquals`
Source:
public void setRequiredParametersForCreation(DateTime paymentDate, Timeframe timeframe, Integer requestedAmount, Boolean build){ this.paymentDate = paymentDate; this.timeframe = timeframe; this.requestedAmount = requestedAmount; //??? if(build){ this.build = build; }else{ this.building = build; } }

Target:
Verificar necessidade desse else
Source:
public TestElasticsearchIntegrationSmokeTest(EmbeddedElasticsearchNode embeddedElasticsearchNode) throws Exception { super(() -> createElasticsearchQueryRunner(embeddedElasticsearchNode, TpchTable.getTables())); this.embeddedElasticsearchNode = embeddedElasticsearchNode; }

Target:
unnecessary `throws` (same for the constructor above).
Source:
public CommandResult exec(ContextAwareCommandInvocation commandInvocation) { if (help) { commandInvocation.println(commandInvocation.getHelpInfo()); } return CommandResult.SUCCESS; }

Target:
print help all the time? the command `> server` alone isn't valid.
Source:
for (OsType type : OsType.values()) { osTypeValues.add(type.value().toLowerCase()); }

Target:
.value() returns .name().toLowerCase()
Source:
private Menu fillMenu(Menu m) { for (IAction action : getActions()) { IContributionItem item; String actionText = action.getText(); if (actionText == null || actionText.isEmpty()) { item = new Separator(); } else { item = new ActionContributionItem(action); } item.fill(m, -1); } return m; }

Target:
Why don't you change getAction() to return a Collection<ContributionItem>?
Source:
public void testThreadNameWithoutNumberNoDemon() { Assert.assertEquals(ThreadUtils.createThreadFactory(THREAD_NAME, false). newThread(EMPTY_RUNNABLE).getName(), THREAD_NAME); }

Target:
In all `assert` method, the first argument is the "expected" value while the second one is the "actual" value. Can you swap them in this file to match that definition?
Source:
public <T> ModelAdaptor<? super T> getModelAdaptor(Class<T> attributeType) { //noinspection unchecked return (ModelAdaptor<T>) adaptors.get(attributeType); }

Target:
```suggestion return (ModelAdaptor<? super T>) adaptors.get(attributeType); ```
Source:
public com.google.gwtorm.client.Key<?>[] members() { return new com.google.gwtorm.client.Key<?>[] {accountId, patchKey}; }

Target:
If you override accountId then the parentKey is automatically a member, and this needs to only include the patchKey.
Source:
public void init(final RuleModellerPage page) { this.page = page; if (page.plugin() instanceof BRLActionColumnPlugin) { } }

Target:
If it is then do what exactly? If we don't want to do anything do we need this ```if(..)``` block at all?
Source:
@Override public TaskResult syncShards() { return periodicShardSyncManager.start(); }

Target:
nit: Could you have `Override` in its own line.
Source:
static <T> List<T> without(List<T> list, Collection<Integer> indexes) { Set<Integer> indexesSet = ImmutableSet.copyOf(indexes); return IntStream.range(0, list.size()) .filter(index -> !indexesSet.contains(index)) .mapToObj(ImmutableList.copyOf(list)::get) .collect(toImmutableList()); }

Target:
Drop this `ImmutableList.copyOf` wrapper. It reduces clarity and we do expect random-access lists here anyway.
Source:
private Throwable getRealException(Throwable re) { if (re.getCause() == null) return re; Throwable cause = re.getCause(); if (cause instanceof CacheException || cause instanceof RuntimeException || cause instanceof Error) return getRealException(cause); else return re; }

Target:
CacheException instanceOf RuntimeException, I guess you can simplify here.
Source:
public void layoutIfNecessary() { if (dirtySize != null && control != null && control instanceof Composite) { if (control.getSize().equals(dirtySize)) { ((Composite) control).layout(); flushChildren = false; } } dirtySize = null; }

Target:
What does this change do?
Source:
public Attribute setLabelAttribute(Boolean isLabelAttr) { set(IS_LABEL_ATTRIBUTE, isLabelAttr); if (isLabelAttr != null && isLabelAttr) { setNillable(false); } return this; }

Target:
We ususally don't put the logic in the entity class. Will be confusing that this setter has side effects: `addAttribute("blah").setNillable(true).setLabelAttribute(true)`
Source:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof IntegrationEvaluationContextAware) { StandardEvaluationContext evaluationContext = IntegrationContextUtils.getEvaluationContext(beanFactory); if (bean instanceof IntegrationObjectSupport) { ConversionService conversionService = ((IntegrationObjectSupport) bean).getConversionService(); if (conversionService != null) { evaluationContext.setTypeConverter(new StandardTypeConverter(conversionService)); } } ((IntegrationEvaluationContextAware) bean).setIntegrationEvaluationContext(evaluationContext); } return bean; }

Target:
So, maybe just remove this code for now? And keep in mind it. However I remember this one: https://github.com/SpringSource/spring-integration/pull/827#issuecomment-20274110 I mean to rely just only on 'system-wide conversion service', not from endpoint.
Source:
public <R, X extends Exception> R withHandle(HandleCallback<R, X> callback) throws X { Handle h = JdbiUtil.getHandle(jdbi); R result = callback.withHandle(h); // close if not in transaction JdbiUtil.closeIfNeeded(h); return result; }

Target:
I believe we shouldn't close the handle here. It will be closed in the `afterCompletion` method. I think also it will probably be ignored because the handle is still binded to the active transaction.
Source:
public LanguageServerWrapper(@Nullable IProject project, @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) { this.initialProject = project; this.initialPath = initialPath; this.allWatchedProjects = new HashSet<>(); this.serverDefinition = serverDefinition; this.connectedDocuments = new HashMap<>(); }

Target:
In this case, shouldn't we getrid of the project parameter here (if we know the project, we shouldn't specify an extra initial path, or we should explicitly use the initial path.
Source:
public String getReplicaPath() { // GetRequest.Cloud_Replica_Keyword is added to avoid error on its peers. return getMountPath() + File.separator + GetRequest.Cloud_Replica_Keyword + File.separator + partitionId.toPathString(); }

Target:
minor: would prefer that `Cloud_Replica_Keyword` comes before mount path since that would order the path from least to most granular
Source:
public void addChildren(AlluxioURI path, Collection<UfsStatus> children) { UfsStatus status = mStatuses.get(path); // If this path doesn't yet exist, we can't keep track of the parent-child relationship // We can still add statuses to the cache regardless if (status != null) { mChildren.computeIfAbsent(path, ufsStatus -> new ConcurrentHashSet<>()).addAll(children); } children.forEach(child -> { AlluxioURI childPath = path.joinUnsafe(child.getName()); addStatus(childPath, child); }); }

Target:
Why can't we add this parent->children listing cache even if the parent status is not in the other map?
Source:
private void actionCompleted(SegmentHolder segmentHolder) { switch (segmentHolder.getType()) { case LOAD: segmentsToLoad.remove(segmentHolder.getSegment()); queuedSize.addAndGet(-segmentHolder.getSegmentSize()); break; case DROP: segmentsToDrop.remove(segmentHolder.getSegment()); break; default: throw new UnsupportedOperationException(); } callBackExecutor.execute( () -> executeCallbacks(segmentHolder) ); }

Target:
Pointless two level submission. `executeCallbacks()` submits each callback to itself another one time (this means that it's valuable to annotate each method in this class in which executor it's supposed to be run. Given that there are two different executors, plus "external", client code execution context (which we kind of shouldn't know where runs)
Source:
public ScheduledReporter build(MetricRegistry registry) { GraphiteReporter.Builder builder = builder(registry); if ("udp".equalsIgnoreCase(this.transport)) { return builder.build(new GraphiteUDP(host, port)); } else { return builder.build(new Graphite(host, port)); } }

Target:
Is `this` needed here? If not, consider dropping it.
Source:
public void onReceiveHangUpFromUser(QBRTCSession session, Integer userId) { setStatusForOpponent(userId, getString(R.string.text_status_hang_up)); Log.d(TAG, "onReceiveHangUpFromUser userId= " + userId); if (!isPeerToPeerCall) { if (userId == userIDFullScreen) { Log.d(TAG, "setAnotherUserToFullScreen call userId= " + userId); setAnotherUserToFullScreen(); } if (videoTrackMap != null && videoTrackMap.containsKey(userId)) { Log.d(TAG, "onReceiveHangUpFromUser videoTrackMap.remove(userId)= " + userId); videoTrackMap.remove(userId); } } }

Target:
опять копипаст) у тебя ж сверху в onConnectionClosedForUser точно такой код, И вообще если мы удаляем в onConnectionClosedForUser , то зачем еще здесь? onConnectionClosedForUser в любом случае срабатывает когда с юзером связь остаточно закрылась,
Source:
private boolean isThis(ExpressionTree expression) { ExpressionTree expressionNoParenthesis = (ExpressionUtils.skipParentheses(expression)); if (expressionNoParenthesis.is(Tree.Kind.IDENTIFIER)) { String targetName = ((IdentifierTree) expressionNoParenthesis).name(); return "this".equals(targetName); } return false; }

Target:
useless parentheses
Source:
protected Map<String, Queue> getQueueNamesToQueues() { return this.queues.stream() .collect(Collectors.toMap(q -> q.getActualName(), q -> q)); }

Target:
`Queue::getActualName` ?
Source:
public String toString() { Bundle myBundle = getBundle(); if (myBundle == null) return ""; //$NON-NLS-1$ String name = myBundle.getSymbolicName(); return name == null ? Long.valueOf(myBundle.getBundleId()).toString() : name; }

Target:
Using String.valueOf(myBundle.getBundleId()) would make more sense than .valueOf.toString
Source:
public void workbenchSelectionChanged(ISelection selection) { Object o = SelectionUtils.getSelectedObject(selection); if (o instanceof TextSelection) { String text = ((TextSelection) o).getText(); m_sourceGraphControl.setSourceText(text); } else if (o == null) { m_sourceGraphControl.setSourceText(""); //$NON-NLS-1$ } }

Target:
The test on the "else" case isn't needed -- if it's anything but a TextSelection the text can be set to the emprty string.
Source:
public JBlock getOnDestroyViewAfterSuperBlock() { if (onDestroyViewAfterSuperBlock == null) { setContentViewRelatedMethods(); } return onDestroyViewAfterSuperBlock; }

Target:
This could be private if you move the field creation to the holder as i suggested.
Source:
public boolean hasChildren(Object element) { return ((MyModel) element).children.size() > 0; }

Target:
Use isEmpty() to check whether the collection is empty or not.
Source:
public GroupedPropertyList getPropertyList() { if (propertyList == null) { try{ boolean parallel = true; long t1 = System.currentTimeMillis(); propertyList = new GroupedPropertyList(individual, vreq, editing,parallel); log.debug(" getPropertyList parallel: "+parallel+" time :"+(System.currentTimeMillis()-t1)+" ms"); }catch(Exception e) { e.printStackTrace(); } } return propertyList; }

Target:
I believe we can remove the `try`/`catch` wrappers. No checked Exceptions are thrown. Is there a particular Exception you are anticipating?
Source:
private void doTheTest(UserGroup g0) { String s = MARSHALER.marshal(g0); UserGroup ug = MARSHALER.unmarshal(s); System.out.println(g0); System.out.println(ug); System.out.println(s); assertTrue(g0.equals(ug)); }

Target:
Remove this ones
Source:
String getConstraintType() { final ConstraintType constraintType = presenter.getConstraintType(); if (constraintType == null) { return presenter.inferComponentType(presenter.getConstraintValue()).value(); } else { return constraintType.toString(); } }

Target:
This too would benefit from the (proposed) `ConstraintType.EMPTY` enumeration item.
Source:
private WikipediaApp getApplication() { return (WikipediaApp) getPageActivity().getApplication(); }

Target:
How about WikipediaApp.getInstance() instead?
Source:
public boolean isHostedEngineDirectLunDisk() { return disk.getDiskStorageType() == DiskStorageType.LUN && StorageConstants.HOSTED_ENGINE_LUN_DISK_ALIAS.equals(disk.getDiskAlias()); }

Target:
Should this be public or private? It is used only in the validator
Source:
public CommunityRest getParentCommunity(@Nullable HttpServletRequest httpServletRequest, UUID collectionId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Collection collection = collectionService.find(context, collectionId); Community parentCommunity = (Community) collectionService.getParentObject(context, collection); if (collection == null) { throw new ResourceNotFoundException("No such collection: " + collectionId); } return converter.toRest(parentCommunity, projection); } catch (SQLException e) { throw new RuntimeException(e); } }

Target:
Same here, JavaDocs for this method please
Source:
public List<WorkflowAction> findActions(List<WorkflowStep> steps, User user) throws DotDataException, DotSecurityException { List<WorkflowAction> actions = new ArrayList<>(); for(WorkflowStep step : steps) { actions.addAll(workFlowFactory.findActions(step)); } actions = APILocator.getPermissionAPI().filterCollection(actions, PermissionAPI.PERMISSION_USE, true, user); return actions; }

Target:
Immutable
Source:
private String updateIconUri(MPart part) { MPartDescriptor desc = modelService.getPartDescriptor(part.getElementId()); String iconURI = desc != null && desc.getIconURI() != null ? desc.getIconURI() : part.getIconURI(); part.getTransientData().put(ICON_URI_FOR_PART, iconURI); return iconURI; }

Target:
This code raises two more (previously existing) concerns: 1. Which iconURI has higher priority the descriptor or the part? 2. What happens if the iconURI of the descriptor is changed?
Source:
private Map<String, Pair<Class, Object>> getOverriddenReturnTypes(){ //Add attributes with 'smart' getters and setters that convert back and forth to correct values for MOLGENIS datatypes //Provide the attribute name as key, and a pair of returntype (Class) and a Object to be used as test value Map<String, Pair<Class, Object>> map = new HashMap<>(); return map; }

Target:
This will throw redundancy warnings in IntelliJ
Source:
public String getParentId(String testId) { return (String) getHibernateTemplate().find("select distinct w.parentId from WorkloadData w where w.taskId=? and w.sessionId=?", testId, sessionId).get(0); }

Target:
why is it public?
Source:
protected void executeQueryCommand() { List<Disk> diskList = DbFacade.getInstance() .getDiskDao() .getAllAttachableDisksByPoolId(getParameters().getStoragePoolId(), getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (CollectionUtils.isEmpty(diskList)) { setReturnValue(new ArrayList<>()); return; } setReturnValue(filterDisks(diskList)); }

Target:
Why can't you just return diskList? If I'm not mistaken DbFacade does not return null lists, only empty
Source:
public JoinFilterPreAnalysis computeJoinFilterPreAnalysisIfAbsent( Filter filter, List<JoinableClause> clauses, VirtualColumns virtualColumns ) { // Some filters have potentially expensive hash codes that are lazily computed and cached. // We call hashCode() here in a synchronized block before we attempt to use the Filter in the analyses map, // to ensure that the hashCode is only computed once per Filter since the Filter interface is not thread-safe. synchronized (analyses) { if (filter != null) { filter.hashCode(); } } JoinFilterPreAnalysisGroupKey key = new JoinFilterPreAnalysisGroupKey(filter, clauses, virtualColumns); return analyses.computeIfAbsent( key, (groupKey) -> { return JoinFilterAnalyzer.computeJoinFilterPreAnalysis( JoinableClauses.fromList(clauses), virtualColumns, filter, joinFilterRewriteConfig ); } ); }

Target:
Oh, is this why we don't need thread-safety on filter hashcode methods i guess? This seems kind of a funny way to prime them with the cached values, I think maybe the supplier.memoize pattern would be a little cleaner and make this not necessary?
Source:
protected AbstractFixedIntervalTask( String id, TaskResource taskResource, String dataSource, Interval interval ) { this(id, id, taskResource, dataSource, interval); }

Target:
there is already a constr, which takes (id,groupId,resource, dataSource,interval) Can we use that in indexTask, instead of adding a new one ?
Source:
private Object[][] finderSupportedResourceTypeData() { return new Object[][] { { FinderSupportedAssociationDataResource.class }, { FinderSupportedComplexKeyDataResource.class }, { FinderWithActionResource.class } }; }

Target:
You can use the expectedExceptions and expectedExceptionsMessageRegExp attributes of the @Test annotation
Source:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); doReturn(newPosixConnection.getId()).when(command).isConnWithSameDetailsExists(newPosixConnection, null); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }

Target:
We actually don't need this line at all. The test check something else
Source:
public void mercury_topbar_wikiaLogoRedirectsToFandomPage() { TopBar topBar = new ArticlePage() .open(MercurySubpages.MAIN_PAGE) .getTopBar(); Assertion.assertTrue(topBar.isLogoVisible()); topBar.clickWikiaLogo(); Assertion.assertTrue(topBar.getCurrentUrl().contains("www.wikia.com/fandom")); }

Target:
I think if it's not visible, click should fail, so is the assertion needed?
Source:
private ConfigurationServiceImplService getConfigService() throws ConnectionManagerException, MalformedURLException{ String url = oProxyHelper.getAdapterEndPointFromConnectionManager(DirectConfigConstants.DIRECT_CONFIG_SERVICE_NAME); if(cfService == null) { cfService = new ConfigurationServiceImplService(new URL(url+"?wsdl")); } return cfService; }

Target:
Should this be initialized in a static / thread-safe context?
Source:
void testDtoListResponses() { FlowJsonObjectReader reader = new FlowJsonObjectReader(); TypeReference<SurveyGroupDto> typeReference = new TypeReference<SurveyGroupDto>() {}; List<SurveyGroupDto> surveyList = null; try { surveyList = reader.readDtoListObject(DTO_LIST_JSON_OBJECT, typeReference); } catch (IOException e) { // } assertNotEquals(surveyList, null); assertEquals(surveyList.size(), 1); assertEquals(surveyList.get(0).getName(),"1.10.36 all questions"); }

Target:
This is a minor detail but the the assertZZZ methods work like this assertZZZ(expected, actual), this is valid for the whole of your test files. Also please format the file as some "," have no space after them.
Source:
public GroupScan clone(List<SchemaPath> columns) { HBaseUtils.verifyColumns(columns, hTableDesc); HBaseGroupScan newScan = new HBaseGroupScan(this); newScan.columns = columns == null ? ALL_COLUMNS : columns; return newScan; }

Target:
We should replace null columns with all_columns before verification or we will get exception. You have changed initial order of statements.
Source:
static <T, U> Function<T, Result<U>> reportMissing(Class<?> expectedClass) { return t -> Result.failure( "Not yet implemented: " + Optional.ofNullable(t) .map(o -> o.getClass().getCanonicalName()) .orElse("null -- expected " + expectedClass.getCanonicalName())); }

Target:
Can be private method.
Source:
private void rematchAllNetworksAndRequests() { // TODO: This may be slow, and should be optimized. final long now = SystemClock.elapsedRealtime(); final NetworkReassignment changes = computeNetworkReassignment(); if (VDBG || DDBG) log(changes.toString()); applyNetworkReassignment(changes, oldDefaultNetwork, now); }

Target:
hmm, I don't think this can get build pass.
Source:
public String getScroller() { return scroller == null ? DEFAULT_SCROLLER : scroller; }

Target:
wdyt if we replace it by ` return Objects.requireNonNullElse(scroller, DEFAULT_SCROLLER)` if you agree you will have some adaptation on 10.10 (java 8)
Source:
public String getMessage(){ return this.message; }

Target:
Nit: unnecessary this.
Source:
public Type convertReadValueToType(String pvReadValue) { Type lvType = convertReadValueToUnmodifiedType(pvReadValue); for (InterfaceOneWireTypeModifier lvTypeModifier : getTypeModifieryList()) { logger.debug("type of before modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType.toString()); lvType = lvTypeModifier.modify4Read(lvType); logger.debug("type of after modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType.toString()); } return lvType; }

Target:
no need for `.toString()`
Source:
public void clear() { this.domainsVisibility.clear(); }

Target:
this should be synchronized as well
Source:
public static Comment newComment(long issueId, int newCommentId, String comment) { DateTime now = DateTime.now(); Long id = Long.parseLong(issueId + "0" + newCommentId); URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + issueId + "/comment"); return new Comment(selfUri, comment, null, null, now, null, null, id); }

Target:
Since you are at it, can you please change this to `long` primitive type? :)
Source:
private void registerGlueCodeScope(ConfigurableApplicationContext context) { do { synchronized (context) { context.getBeanFactory().registerScope(SCOPE_CUCUMBER_GLUE, new GlueCodeScope()); context = (ConfigurableApplicationContext) context.getParent(); } } while (context != null); }

Target:
I don't think this works. We're swapping out `context` with a different instance. We should probably use a constant as a monitor.
Source:
private String truncateMessageLength(String message, int maxLength) { if (message.length() > maxLength) { message = message.substring(0, maxLength + 1); } return message; }

Target:
This line will actually return a substring of length maxLength + 1. If the substring indeed needs to be no longer than maxLength, then replace "maxLength + 1" with just "maxLength".
Source:
public void testErrorReceived() { TestObserver<Object> ts = new TestObserver<Object>(); TestException ex = new TestException("boo"); Flowable.error(ex).ignoreElements().subscribe(ts); ts.assertNoValues(); ts.assertTerminated();; ts.assertError(TestException.class); ts.assertErrorMessage("boo"); }

Target:
double `;`
Source:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (!(element instanceof DisplayItem)) { return false; } if (actionSet == null) { return false; } return CustomizePerspectiveDialog.includeInSetStructure((DisplayItem) element, actionSet); }

Target:
unnecessary linebreak
Source:
public static void runJSTestSuite() throws InterruptedException { // FIXME Update this when we stop using ARM Emulators int timeout = Build.SUPPORTED_ABIS[0].contains("armeabi") ? 180 : 60; JSTestCase.runJSTestSuite(JS_SUITE, data(), timeout); }

Target:
Why not just bump it up to `180` across the board?
Source:
public Map<String, String> getSystemSessionProperties(SessionConfigurationContext context) { HashMap<String, String> combinedProperties = new HashMap<>(); for (SessionMatchSpec sessionMatchSpec : sessionMatchSpecs) { combinedProperties.putAll(sessionMatchSpec.match(context)); } return ImmutableMap.copyOf(combinedProperties); }

Target:
Nit: declare as `Map`
Source:
public static void logAccess(Integer requestId, InetAddress remoteAddress, Principal principal, String operation) { new ThriftAccessLogger().log( String.format("Request ID: access from: principal: operation: {}", requestId, remoteAddress, principal, operation)); }

Target:
I thought it would be something like ``` LOG.info("Request ID: access from: principal: operation: {}", requestId, remoteAddress, principal, operation); ``` and ThriftAccessLogger.log would just go away
Source:
public static List<String> getComputerNames() { final ArrayList<String> names = new ArrayList<String>(); for (Computer c : Jenkins.getActiveInstance().getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); } } return names; }

Target:
`getActiveInstance` is deprecated, please use good old `getInstance`.
Source:
public void unbind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); final Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); synchronized (lock) { if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { eventNameToListenerMap.remove(eventName); } } } }

Target:
As above, you must perform both the read and the write in the critical section, otherwise there's no guarantee of consistency.
Source:
public Iterable<AccountGroup> all() { final List<AccountGroup> groups = new LinkedList<AccountGroup>(); for (final AccountGroup.NameKey groupName : list.get(ListKey.ALL)) { final AccountGroup group = get(groupName); if (group != null) { groups.add(group); } } return Collections.unmodifiableList(groups); }

Target:
If list.get(ListKey.ALL) returns a reasonable upper bounds for the size, I think that an ArrayList would likely be faster.
Source:
public void terminate(HazelcastInstance instance) { try { Address address = getNode(instance).address; terminateInstance(instance); if (isMockNetwork) { registry.removeInstance(address); } } finally { TestJmxLeakHelper.checkJmxBeans(instance.getName()); } }

Target:
We have a large number of tests that don't use `TestHazelcastInstanceFactory` at all and call `Hazelcast.newHazelcastInstance()` directly (in combination with `Hazelcast.shutdownAll()` / `HazelcastInstanceFactory.shutdownAll()` / `HazelcastInstanceFactory.terminateAll()`). Shouldn't those be checked as well, somehow?
Source:
public void endSuccessfully() { super.endSuccessfully(); if (getParameters().getImportAsTemplate()) { Guid newTemplateId = createTemplate(); // No reason for this to happen, but checking just to make sure if (newTemplateId != null) { attachDiskToTemplate(newTemplateId); } } updateDiskStatus(ImageStatus.OK); getReturnValue().setSucceeded(true); }

Target:
please change to setSucceeded
Source:
void validate() { // No-op, no validation required }

Target:
Interesting wrapping style :)
Source:
private void scheduleImmediateDelivery() { cancelDelayedDelivery(); while (state == State.RUNNING) { DeliveryAttempt previous = immediateDelivery.get(); if (previous != null && !previous.isDone()) previous.cancel(); DeliveryAttempt current = new DeliveryAttempt(); if (immediateDelivery.compareAndSet(previous, current)) { current.executeNow(); return; } } }

Target:
deliverEvents does not handle interruptions, so this is essentially a no-op if `previous` is already executing.
Source:
private static ObjectNode handleGaugeRollup(GaugeRollup rollup) { ObjectNode rollupNode = JsonNodeFactory.instance.objectNode(); rollupNode.put("timestamp", rollup.getTimestamp()); SimpleNumber rollupValue = rollup.getLatestValue(); rollupNode.put("latestVal", rollupValue.getDataType() == (SimpleNumber.Type.DOUBLE) ? rollupValue.getValue().doubleValue() : rollupValue.getValue().longValue()); return handleBasicRollup(rollup, rollupNode); }

Target:
Why do gauges get timestamp twice?
Source:
public GarruksWarsteed(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}{G}"); this.subtype.add(SubType.RHINO); this.power = new MageInt(3); this.toughness = new MageInt(5); // Vigilance this.addAbility(VigilanceAbility.getInstance()); // When Garruk's Warsteed enters the battlefield, you may search your library and/or graveyard for a card named Garruk, Savage Herald, reveal it, and put it into your hand. If you search your library this way, shuffle it. this.addAbility(new EntersBattlefieldTriggeredAbility(new SearchLibraryGraveyardPutInHandEffect(filter, false, true), true)); }

Target:
this doesn't need to have the ability and effect both be optional, just the ability is fine.
Source:
private void releaseFileChannel(long logId, CachedFileChannel cachedFileChannel) { lock.writeLock().lock(); try { if (cachedFileChannel.markDead()) { try { cachedFileChannel.fileChannel.close(); } catch (IOException e) { LOG.warn("Exception occurred in ReferenceCountedFileChannel" + " while closing channel for log file: {}", cachedFileChannel); } finally { IOUtils.close(LOG, cachedFileChannel.fileChannel); } // to guarantee the removed cachedFileChannel is what we want to remove. fileChannels.remove(logId, cachedFileChannel); } } finally { lock.writeLock().unlock(); } }

Target:
markDead doesn't need to be under a lock. The caller should call tryRetain() after receiving, which will either prevent markDead from having an effect, if it is called before it.
Source:
private static File getDefaultFile() { File netrc; File home = new File(System.getProperty("user.home")); //$NON-NLS-1$ netrc = new File(home, ".netrc"); //$NON-NLS-1$ if (netrc.exists()) return netrc; netrc = new File(home, "_netrc"); //$NON-NLS-1$ if (netrc.exists()) return netrc; return null; }

Target:
no need to declare this here, instead declare the type in line 141
Source:
static synchronized ServiceContext getServiceContext() { if (serviceContext == null) { synchronized (Context.class) { if (serviceContext == null) { log.error("serviceContext is null. Creating new ServiceContext()"); serviceContext = ServiceContext.getInstance(); } } } log.trace("serviceContext: {}", serviceContext); return ServiceContext.getInstance(); }

Target:
I can see that the method body was already synchronised. Can you instead remove the outer if (serviceContext == null)? Because i see it duplicated in the inner block.
Source:
public synchronized void activate() { OTELog.getLogger("test").debug("something"); listener = new Slf4jLogListener(); logService.addLogListener(listener); }

Target:
remove this line
Source:
public void testDeserialization() throws Exception { for (Short version : versions) { composedBlobIdAndDeserialize(version); } }

Target:
I don't understand the need of this test. We have the next one which tests serialization and deserialization if I am not wrong. Or does this tests something more than the next one ?
Source:
private List<VMWithPlugInfo> getVmsWithPlugInfo(Guid id) { List<VMWithPlugInfo> vmsWithPlugInfo = getCallsHandler().executeReadList ("GetVmsByDiskId", VMWithPlugInfoRowMapper.instance, getCustomMapSqlParameterSource().addValue("disk_guid", id)); return vmsWithPlugInfo; }

Target:
should be just return , no need for variable
Source:
public Jedis createResource() { Jedis jedis = new Jedis(this); try { jedis.select(db); } catch(JedisException e) { log.log(Level.SEVERE, "Can't select database due a Redis connection problem", e); } return jedis; }

Target:
@nykolaslima How about handling selecting db by constructor of BinaryJedis, as authentication takes place?
Source:
public JSchUIConnectionManager(IRemoteServices services) { fConnMgr = (JSchConnectionManager) services.getConnectionManager(); fConnMgr.setDefaultAuthenticatorFactory(new IUserAuthenticatorFactory() { @Override public IUserAuthenticator createUserAuthenticator(IRemoteConnection conn) { return new RemoteAuthenticator(conn); } }); }

Target:
Please keep initialization code out of the Activator class.
Source:
public BoltDeclarer addConfigurations(Map<String, Object> conf) { if (conf != null && !conf.isEmpty()) { component.componentConf.putAll(conf); } return this; }

Target:
Nit: I think putAll is a no-op when the conf is empty, so you probably don't need to check.
Source:
public void startTrackingBpForProcess(final IContainerDMContext containerDmc, final RequestMonitor rm) { final IBreakpointsTargetDMContext targetBpDmc = DMContexts.getAncestorOfType(containerDmc, IBreakpointsTargetDMContext.class); IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(fDebugModelId); for (IBreakpoint breakpoint : breakpoints) { if (supportsBreakpoint(breakpoint) && breakpoint instanceof ICBreakpoint) { setTargetFilter((ICBreakpoint) breakpoint, containerDmc); } } startTrackingBreakpoints(targetBpDmc, rm); }

Target:
Its a heavy read that bug! When you check if breakpoint applicable probably better reverse instanceof check and call. Instanceof is cheaper