auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TranslatedExpression<T> translate(FunctionMetadata functionMetadata, RowExpression original, List<TranslatedExpression<T>> translatedArguments) { if (!isFunctionPresent(functionMetadata)) { return untranslated(original); } try { return new TranslatedExpression<>(Optional.of((T) functionMapping.get(functionMetadata).invokeWithArguments(translatedArguments)), original, translatedArguments); } catch (Throwable t) { return untranslated(original); } }

Target:
Just let it throw the error.
Source:
public void maintenance() { Guid clusterId = getClusterIdOfSelectedHosts(); if (clusterId == null) { maintenance(false, false, null); } else { AsyncDataProvider.getInstance().getClusterById(new AsyncQuery<>( cluster -> { if (cluster != null) { maintenance(true, cluster.supportsGlusterService(), clusterId); } }), clusterId); } }

Target:
Since it is always true, can be get rid of this variable?
Source:
public DagBuilder(final String name, final DagProcessor dagProcessor) { requireNonNull(name, "The name of the DagBuilder can't be null"); requireNonNull(name, "The dagProcessor of the DagBuilder can't be null"); this.dag = new Dag(name, dagProcessor); }

Target:
Should this be `requireNonNull(dagProcessor, ` ?
Source:
private void selectStrutsFunctionality(HttpServletRequest request) { Functionality functionality = RenderersAnnotationProcessor.getFunctionalityForType(getFunctionalityType()); MenuFunctionality menuItem = MenuFunctionality.findFunctionality(functionality.getProvider(), functionality.getKey()); if (!menuItem.isAvailableForCurrentUser()) { throw AuthorizationException.unauthorized(); } BennuPortalDispatcher.selectFunctionality(request, menuItem); }

Target:
You should add a `null` check here, as the selected functionality may not be installed, yielding a `null` Menu Item.
Source:
private void logFailureResponseObject(MockHttpException httpEx, String url, long callDelay) { LogLevel logLevel = restAdapter.logLevel; RestAdapter.Log log = restAdapter.log; if (logLevel.log()) { log.log(String.format("<--- MOCK %s %s (%sms)", httpEx.code, url, callDelay)); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(httpEx.responseBody + ""); // Hack to convert toString while supporting null. log.log("<--- END MOCK"); } } }

Target:
String.valueOf
Source:
public void newSelection(final TmfPieChartViewer context) { if (context.isDisposed()) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { synchronized (context.getMutexLayoutChange()) { if (!context.isDisposed()) { context.updateTimeRangeSelectionPieChart(); context.getTimeRangePC().redraw(); context.layout(); } } } }); }

Target:
just use context
Source:
private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (!nextRequestHandler.needsCoordinator()) { // For non-coordinator requests, sleep here to prevent a tight loop when no node is available time.sleep(retryBackoffMs); metadata.requestUpdate(); } transactionManager.lookupCoordinator(nextRequestHandler); transactionManager.retry(nextRequestHandler); }

Target:
It reads a bit strange to fall through to `lookupCoordinator` if we know the request doesn't need the coordinator. Maybe clearer with a slight restructure: ```java transactionManager.retry(nextRequestHandler); if (nextRequestHandler.needsCoordinator()) { transactionManager.lookupCoordinator(nextRequestHandler); } else { // For non-coordinator requests, sleep here to prevent a tight loop when no node is available time.sleep(retryBackoffMs); metadata.requestUpdate(); } ```
Source:
public void testGetVersion() throws Exception { BugzillaRestClient client = new BugzillaRestClient(actualFixture.location()); assertNotNull(client.getClient()); assertNull(client.getClient().getLoginToken()); BugzillaRestVersion version = client.getVersion(new NullOperationMonitor()); assertTrue("expeccted: " + actualFixture.getVersion() + " actual: " + version.toString(), actualFixture.getVersion().compareTo(version.toString()) == 0); }

Target:
(spelling) I guess there is a reason you can't use asserEquals here as oppossed to compareTo? Not sure why the semantics should be different there.
Source:
private String locateTool(String tool) { String[] roots = { "/usr/bin/", "/usr/local/bin/", "/Users/christian/.nvm/versions/node/v6.6.0/bin/" }; for (String root : roots) { if (new File(root + tool).exists()) { return root + tool; } } return null; }

Target:
Not sure we need a reference to your particular nodes setup
Source:
public void setAcl(FileSystem hdfs, String path, AccessControlList acl) throws IOException { // convert AccessControlList into hdfsAcl List<AclEntry> aclSpecs = new ArrayList<>(); for (alluxio.security.authorization.AclEntry entry : acl.getEntries()) { AclEntry hdfsAclEntry = getHdfsAclEntry(entry); aclSpecs.add(hdfsAclEntry); } // set hdfsAcl; try { hdfs.setAcl(new Path(path), aclSpecs); } catch (UnsupportedOperationException e) { LOG.warn("Setting ACL on HDFS with acl disabled"); } }

Target:
this logging may be spammy, so we should not log this.
Source:
public void sendUserListMessage(UserList userlist){ UserListMessage ulm = new UserListMessage(userlist); broadcastMessageToFans(ulm); Log.i("Messaging Service", "User List Message Sent"); }

Target:
Lets use a TAG variable
Source:
private int nextCorrelationId() { if (SaslClientAuthenticator.isReserved(correlation)) correlation = SaslClientAuthenticator.MAX_RESERVED_CORRELATION_ID + 1; return correlation++; }

Target:
make it if-then-else since we dont't need the increment in the line below? Also split this line since we don't include the statement in the same line as `if`.
Source:
public void uniqueCorrelationIDs() throws MuleException { CoreEvent firstEvent = getEventBuilder().message(of("first")).build(); CoreEvent secondEvent = getEventBuilder().message(of("second")).build(); assertThat("Duplicated correlationID", firstEvent.getContext().getCorrelationId(), not(Is.is(secondEvent.getContext().getCorrelationId()))); }

Target:
static import for `is`
Source:
private void setupActivityFromState(final Bundle state) { if (state != null) { if (!shouldShowDualPane) { toggleNavigationDrawer(state.getBoolean(STATE_DRAWER_OPENED, false)); } } }

Target:
Single if can be used here too
Source:
public VdcActionParametersBase getParameters(Host incoming, VDS entity) { VdsStatic updated = getMapper(modelType, VdsStatic.class).map(incoming, entity.getStaticData()); UpdateVdsActionParameters updateParams = new UpdateVdsActionParameters(updated, "root", "", false); if (incoming.isSetOverrideIptables()) { updateParams.setOverrideFirewall(incoming.isOverrideIptables()); } return updateParams; }

Target:
why hardcode?
Source:
private boolean isSamePrefix(String a, String b) { int as = a.lastIndexOf('/'); int bs = b.lastIndexOf('/'); return a.substring(0, as + 1).equals(b.substring(0, bs + 1)); }

Target:
Style-nit: This method can be static.
Source:
public void stop(ComponentContext context) throws InterruptedException { super.stop(context); redirectResolver = new DefaultRedirectResolver(); }

Target:
Do we need it after stop ? If not, it makes more sense to put it in `start` method (and maybe remove the field init).
Source:
public synchronized void initCamelCronService() { if (this.service == null) { this.service = CronHelper.resolveCamelCronService( getCamelContext(), this.cronService ); if (this.service == null) { throw new RuntimeCamelException("Cannot find any CamelCronService: please add a valid implementation, such as 'camel-quartz', in order to use the 'camel-cron' component"); } try { getCamelContext().addService(this.service, true, false); } catch (Exception e) { throw new RuntimeCamelException(e); } } }

Target:
I am not a fan of this, cant we move this to doStart so its initialized there?
Source:
public void teardownTest() throws InterruptedException { //give time for operations to finish firewallPolicyApi().delete(currentFirewallPolicy.id()); Thread.sleep(15000); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }

Target:
Doing this in a live test is a symptom of something that users will probably have to do themselves. better use the build-in `Predicates2.retry` construct to wait until the server is deleted and consider binding it to the guice context so it can be reused where needed.
Source:
public Object next() { if ( position >= len ) { throw new NoSuchElementException(); } Object result = Array.get( array, position ); position++; return result; }

Target:
In what way is this an improvement?
Source:
protected int getNumOfElementOnPage(By cssSelectorBy) { changeImplicitWait(500, TimeUnit.MILLISECONDS); int numElementOnPage = 0; try { numElementOnPage = driver.findElements(cssSelectorBy).size(); } catch (Exception ex) { numElementOnPage = 0; } finally { restoreDeaultImplicitWait(); } return numElementOnPage; }

Target:
Why are you assigning 0 to numElementOnPage, as you assign some value again in the next line?
Source:
public void set(String field, final String value) { if (!"".equals(field)) { if (isUserDefinedField(field)) { userDefinedFields.put(field, value); String fieldName = getUserDefinedFieldName(field); if (fieldName != null) { userDefinedFieldNames.add(new ControlField(fieldName)); } field = fieldName; } if (field != null) { values.put(field, value); } } }

Target:
I don't understand this, why testing if the field name is not empty? Shouldn't this be removed?
Source:
public Result(String targetContentEncoding, EmbeddedChannel contentEncoder) { ObjectUtil.checkNotNull(targetContentEncoding, "targetContentEncoding"); ObjectUtil.checkNotNull(contentEncoder, "contentEncoder"); this.targetContentEncoding = targetContentEncoding; this.contentEncoder = contentEncoder; }

Target:
nit: you can merge lines above as `checkNotNull` will return the given argument
Source:
public boolean onPrepareOptionsMenu(Menu menu) { LibraryAdapter adapter = mCurrentAdapter; boolean isLibraryAdapter = (adapter != null && adapter.getMediaType() != MediaUtils.TYPE_FILE); menu.findItem(MENU_GO_HOME).setVisible(!isLibraryAdapter); menu.findItem(MENU_SORT).setEnabled(adapter != null); return super.onPrepareOptionsMenu(menu); }

Target:
Just change this to ``` setVisible(adapter != null && adapter.getMediaType() == MediaUtils.TYPE_FILE) ``` and get rid of isLibraryAdapter
Source:
public void login() { page.login(validAdminPassword, validAdminLogin); }

Target:
Looks strange.
Source:
protected static String truncateValueToMaxLength(String inputValue, int maxLength) { if (StringUtils.length(inputValue) <= maxLength) { return inputValue; } else { return inputValue.substring(0, maxLength); } }

Target:
Could you use StringUtils.truncate instead?
Source:
private void init() { // Creating ObjectChecker must be deferred. Unit tests change // behavior of is{Windows,MacOS} in constructor of subclass. if (platformChecker == null) { setPlatformChecker(); } }

Target:
style nit: we don't use braces around single line blocks
Source:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; if (id != null && id.getValue() != null && id.getValue().size() > 0) { oII = id.getValue().get(0); } return oII; }

Target:
Again, prefer "isEmpty()" over a "size()" comparison.
Source:
public MediaType getContentType() { if (this.readOnly && this.cachedContentType != null) { return this.cachedContentType; } else { String value = getFirst(CONTENT_TYPE); MediaType contentType = (StringUtils.hasLength(value) ? MediaType.parseMediaType(value) : null); if (this.readOnly) { this.cachedContentType = contentType; } return contentType; } }

Target:
This can be improved. The `this.readOnly` check shows that this method is mixing two concerns: map lookup and caching. I would prefer if caching was done in a separate wrapper class(`ReadOnlyHttpHeaders`), that is returned when `HttpHeaders.readOnlyHttpHeaders` is called (instead of backing the map with an unmodifiable `MultiValueMap`).
Source:
protected String[] fillTypeCombo() { ArrayList<String> list = new ArrayList<>(); for(DataType dataType : EventTypeLibrary.getInstance().getEventTypes()){ list.add(dataType.getName()); } return list.toArray(new String[0]); }

Target:
change to List
Source:
public NettyTransportConnectionStats(EmbeddedCacheManager cacheManager, ChannelGroup acceptedChannels, String threadNamePrefix) { this.cacheManager = cacheManager; this.isGlobalStatsEnabled = cacheManager != null ? cacheManager.getCacheManagerConfiguration().globalJmxStatistics().enabled() : false; this.acceptedChannels = acceptedChannels; this.threadNamePrefix = threadNamePrefix; }

Target:
Can be simplified to `cacheManager != null && cacheManager.getCacheManagerConfiguration().globalJmxStatistics().enabled()`
Source:
public static Scheduler computation() { synchronized (computationGuard) { if (computationScheduler == null) { Scheduler c = RxJavaPlugins.getInstance().getSchedulersHook().getComputationScheduler(); if (c != null) { computationScheduler = c; } else { computationScheduler = new EventLoopsScheduler(); } } return computationScheduler; } }

Target:
I don't like putting a synchronized block in the line of fire on something like this that doesn't need to be. This is a global lock and exactly the type of stuff I find in our production environments.
Source:
public Change munge(String entityId, Collection<Statement> statements) { munge(entityId, statements, emptySet(), emptySet(), null, null); }

Target:
missing return
Source:
public void testMaxSizePassed() throws ArrayIndexOutOfBoundsException { try{SizeLimitedVector slv = new SizeLimitedVector(1); slv.add(13); slv.add(14); } catch (ArrayIndexOutOfBoundsException e) { fail("array capacity is passed, capacity was 1, but 2 elements got added"); } }

Target:
The whole point of the SizeLimitedVector is that you can append as many things to it as you like but it only stores the last X amount.
Source:
public Double getTotalCpuReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return _resourceList .get(exec) .get(Config.TOPOLOGY_COMPONENT_CPU_PCORE_PERCENT); } LOG.warn("cannot find - {}", exec); return null; }

Target:
Again I don't think this log message adds much.
Source:
public static void writeStyle(final InputStream in, final Resource styleFile) throws IOException { BufferedOutputStream out = null; try { out = new BufferedOutputStream(styleFile.out()); IOUtils.copy(in, out); out.flush(); } finally { out.close(); } }

Target:
Perhaps try-with-resources? And there are also tabs here that could be fixed.
Source:
private void RestoreVmFromBaseSnapshot(VM vm) { if (DbFacade.getInstance().getDiskImageDAO().getAllStatelessVmImageMapsForVm(vm.getId()).size() > 0) { log.infoFormat("Deleting snapshots for stateless vm {0}", vm.getId()); Backend.getInstance().runInternalAction(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(vm.getId()), new CommandContext(getCompensationContext())); } }

Target:
Please dont use this {0} , and use String.format instead.
Source:
public void setParams(Object[] params) { if (params.length != 1) { throw new IllegalArgumentException("expecting one parameter"); } setParams((Map<Object, Number>) params[0]); }

Target:
Please use Map<?,?>
Source:
public LuceneAnalysisDefinitionTranslationMapBuilder(Class<D> targetClass) { super(); this.targetClass = targetClass; }

Target:
No `super();` needed.
Source:
public void should_balance_requests_across_connections() throws InterruptedException { // Generate just the right load to completely fill the pool. All requests should succeed. int simultaneousRequests = POOL_SIZE * REQUESTS_PER_CONNECTION; for (int i = 0; i < simultaneousRequests; i++) { reschedule(null, null); } SECONDS.sleep(5); done.countDown(); Throwable unexpectedError = unexpectedErrorRef.get(); if (unexpectedError != null) { fail("At least one request failed unexpectedly", unexpectedError); } }

Target:
Introduction 5 seconds delay in a test seems like a lot, maybe instead we could create a new `AtomicInteger successfullRequests = simultaneousRequests`, increment it in every successful session execute, and change the sleep to: `awaitUntil( () successfullRequests == simultaneousRequests)`? The test will keep the characteristic because we will be waiting until all succeed OR error will happen. wdyt?
Source:
public void generateSourceMaps() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.generateInlineSourceMaps", false)).thenReturn(true); boolean b = mocker.getComponentUnderTest().isGenerateInlineSourceMaps(); assertTrue(b == true); }

Target:
``` assertTrue(b); ```
Source:
private IStatus getFormPresenterStatus() { IStatus saveStatus = Status.OK_STATUS; if (formPresenterSupport != null && formPresenterSupport.getCurrentStatus() != null) { saveStatus = formPresenterSupport.getCurrentStatus(); } return saveStatus; }

Target:
i don't think that `formPresenterSupport` can be `null`. If i miss something, then these null checks must be also added to `dispose` method
Source:
protected void fallbackOnDefaultCache() { CacheService cacheService = Framework.getService(CacheService.class); if (cacheService != null) { if (descriptor.cacheEntryName == null) { cache.setEntryCacheName("cache-" + getName()); cacheService.registerCache("cache-" + getName()); } if (descriptor.cacheEntryWithoutReferencesName == null) { cache.setEntryCacheWithoutReferencesName("cacheWithoutReference-" + getName()); cacheService.registerCache("cacheWithoutReference-" + getName()); } } }

Target:
Put `"cache-" + getName()` in a local variable to avoid repetition.
Source:
public void addInformation(ItemStack stack, World world, List<String> tooltip, ITooltipFlag flag) { if (stack.hasTagCompound()) { Binding binding = getBinding(stack); if (binding != null) { tooltip.add(new TextComponentTranslation("tooltip.bloodmagic.currentOwner", binding.getOwnerName()).getFormattedText()); } } }

Target:
There is no reason for these formatting changes
Source:
private static String normaliseTypeName(String dataType) { if (dataType.indexOf("(")<=0) dataType = dataType.toUpperCase().trim(); else dataType = dataType.toUpperCase().trim().substring(0,dataType.indexOf("(")); return dataType; }

Target:
There no whitespace around `<=`. Also - good to enclose blocks of that that if/else in {}.
Source:
public String sendHttpGetToBroker(String table, String path) { return doHttpActionWithHeaders( Request.builder().prepareGet().setUri(URI.create(String.format("http://%s/%s", getBrokerHost(table), path))), Optional.empty(), Optional.empty()); }

Target:
private
Source:
public FluoConfiguration resolveFluoConfiguration(String appName) { try { return getAppConfiguration(appName); } catch (FluoException e) { FluoConfiguration config = new FluoConfiguration(getFluoConfiguration()); config.setApplicationName(appName); return config; } }

Target:
Not sure if this would be the best place to print it. I was thinking it may be useful to print which config file it ended up using.
Source:
public String getCachedString() { String rv; if (variableData.expression == null || variableData.expression.length() == 0) rv = "_"; else if (Double.isNaN(getCachedValue())) rv = "*"; else rv = "" + (int) getCachedValue(); return rv; }

Target:
This variable is useless. Please just use `return` in your `if/…` branches.
Source:
public static boolean anyRunning() { IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles(); ScriptConsole console; for(int i=0; i<ic.length; i++) { if (ic[i] instanceof ScriptConsole){ console = (ScriptConsole)ic[i]; if(console.isRunning()) return true; } } return false; }

Target:
Please use even for one line if clauses.
Source:
private void checkVersionForProfileLI(PackageSetting ps, PackageParser.Package pkg) { if (isUpgrade() && ps != null && pkg != null) { if (ps.versionCode != pkg.mVersionCode) { Slog.d(TAG, ps.name + " clear profile due to version change " + ps.versionCode + " != " + pkg.mVersionCode); clearAppProfilesLIF(pkg, UserHandle.USER_ALL); return true; } if (DEBUG_INSTALL) { Slog.d(TAG, "Package " + ps.name + " keep profile"); } } }

Target:
oups, bad rebase.
Source:
RealmAsyncTask logOutAsync(RealmUser user, Callback<RealmUser> callback) { checkLooperThread("Asynchronous log out is only possible from looper threads."); return new Request<RealmUser>(SyncManager.NETWORK_POOL_EXECUTOR, callback) { @Override public RealmUser run() throws ObjectServerError { RealmLog.error("Log out user"); logOut(user); return user; } }.start(); }

Target:
```suggestion RealmLog.info("Log out user " + user.getEmail()); ```
Source:
@Override protected Map<String, Pair<String, String>> getExclusiveLocks() { final LockMessage lockMessage = createLockMessage(); return templatesLockedForUpdate.stream() .collect(Collectors.toMap( template -> template.getId().toString(), template -> LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, lockMessage))); }

Target:
please put the @Override annotation on its own line
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__HOT_PLUG); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK); if (getDisk() != null) { addCanDoActionMessage(String.format("$%1$s %2$s", "diskAliases", getDiskAlias())); } }

Target:
imo this should be added only when it's needed by the message, theres no need to add the disk alias if we get a message that the vm isn't down for example..as we do for all the messages.
Source:
public <B> Eval<B> map(final F<A, B> f) { return bind(a -> now(f.f(a))); }

Target:
could be `final`.
Source:
protected PhysicalOperator getNewWithChild(PhysicalOperator child) { return new IteratorValidator(child, this.isRepeatable); }

Target:
Remove the 'this' qualifier .
Source:
public synchronized List<Inode<?>> getInodeList() { return Lists.newArrayList(mLockList.getInodes()); }

Target:
does `LockList#getInodes` already make a copy?
Source:
private void setupNetworkDao() { when(getDbFacadeMockInstance().getNetworkDao()).thenReturn(networkDaoMock); when(networkDaoMock.get(networkId)).thenReturn((networkMocked)); when(networkMocked.getQosId()).thenReturn(null); }

Target:
And here return the proper ID as well - you're trying to mimic real behavior.
Source:
public void checkStorageDomainNotEqualWithStatusActive() { setStorageDomainStatus(StorageDomainStatus.Active); assertFalse(cmd.checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); List<String> messages = cmd.getReturnValue().getCanDoActionMessages(); assertEquals(2, messages.size()); assertEquals(messages.get(0), VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2.toString()); assertEquals(messages.get(1), String.format("$status %1$s", StorageDomainStatus.Active)); }

Target:
shouldn't actual <--> expected be replaced here as well ?
Source:
public ShowBubbleActor createBubbleActor() throws InterpretationException { String textToDisplay = text == null ? "" : text.interpretString(sprite); if (textToDisplay.equals("")) { return null; } return new ShowBubbleActor(textToDisplay, sprite, type); }

Target:
this can be replaced by `textToDisplay.isEmpty()`
Source:
public List<String> getGroupsForUser(String userId) { List<String> groups = groupStore.get(userId); if( groups == null ) { groups = new ArrayList<String>(0); } return new java.util.ArrayList<String>(groups); }

Target:
Maybe remove the package name as it is already in the import statements.
Source:
public FlashScope getFlashCookie() { return wrapped.getFlashScope(); }

Target:
please leave it that way - it's intentionally referencing the deprecated version.
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); if (repository == null) { return null; } PushToGerritWizard wiz = new PushToGerritWizard(repository); WizardDialog dlg = new WizardDialog(HandlerUtil .getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; }

Target:
style nit: no braces around single line blocks
Source:
public WriteRequest(ByteBuf buf) { writeMode = ICorfuPayload.fromBuffer(buf, WriteMode.class); streamAddresses = null; data = ICorfuPayload.fromBuffer(buf, LogData.class); }

Target:
I think we can remove the streamAddresses field
Source:
protected void assertSameLastUpdateTime() { assertTrueEventually(() -> { long lastUpdateTime = localCollectionStats.getLastUpdateTime(); assertEqualsStringFormat("Expected the lastUpdateTime to be %d, but was %d", previousUpdateTime, lastUpdateTime); previousUpdateTime = lastUpdateTime; }); }

Target:
Do we need the `assertTrueEventually()` in these methods? In the concrete tests a reference is obtained to the stats instance, which means, by the time the operations return the stats instance is updated.
Source:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { // Query for storageDoaminId is looking for Active ISO domain if (!isStorageDomainIdValid(storageDomainId)) { throw new EngineException(EngineError.GetIsoListError); } if (forceRefresh) { if (refreshRepos(storageDomainId, imageType)) { throw new EngineException(EngineError.IMAGES_NOT_SUPPORTED_ERROR); } } else { refreshReposIfIntervalPassed(storageDomainId, imageType); } // In any case, whether refreshed or not, get Iso list from the cache. return getCachedIsoListByDomainId(storageDomainId, imageType); }

Target:
Missing ! operator
Source:
private static GitSynchronizer getSynchronizer() { Display display = Display.getCurrent(); Assert.isNotNull(display); if (Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.USE_LOGICAL_MODEL)) { return new ModelAwareGitSynchronizer(display); } return new DefaultGitSynchronizer(display); }

Target:
I wouldn't get the display here. It forces you to have a ModelAwareGitSynchronizer(Display) constructor even though that class itself doesn't need it. I'd just go with parameterless constructors, and use PlatformUI.getWorkbench().getDisplay() in DefaultGitSynchronizer.openGitTreeCompare() instead.
Source:
public long getAvgExecutionTime() { long avgExecTime = -1; try { synchronized (this) { avgExecTime = totalExecutionTime / invocationCnt; } } catch (Exception e) { if (invocationCnt == 0 && totalExecutionTime == 0) { avgExecTime = 0; } } return avgExecTime; }

Target:
Why is the synchronized block here within the 'try' part of the try-catch block? Shouldn't the 'catch' part also run in the synchronized block ?
Source:
public void cleanUpEnvironment() { fTrace.dispose(); fScriptingMarkerSource.dispose(); fScriptingMarkerSource = null; fScriptingMarkerSourceFactory.dispose(); fTraceMarkerScriptingModule = null; }

Target:
Technically, you still need to null-check ftrace, just like all other fields, as you never know why the test fails, maybe the first line exploded, this method is still called, but everything is null.
Source:
public int hashCode() { return HashCodeBuilder.reflectionHashCode(formField.getPageNumber()); }

Target:
This should call .append(formField.getPageNumber()).build();
Source:
public static byte[] toUtf8(final String string) { if(string == null){ return null; } try { return string.getBytes(UTF8_STRING); } catch (UnsupportedEncodingException e) { // Should never happen throw Throwables.propagate(e); } }

Target:
annotate with nullable.
Source:
private void decodeLocalizedTitles(DBObject dbObject, Described entity) { if (dbObject.containsField(LOCALIZED_TITLES_KEY)) { List<DBObject> localisedTitlesDBO = TranslatorUtils.toDBObjectList(dbObject, LOCALIZED_TITLES_KEY); entity.setLocalizedTitles(Iterables.transform(localisedTitlesDBO, new Function<DBObject, LocalizedTitle>() { @Override public LocalizedTitle apply(DBObject input) { return localizedTitleTranslator.fromDBObject(input, new LocalizedTitle()); } })); } }

Target:
I don't think you need this condition. `TranslatorUtils.toDBObjectList` will return an emptylist if the key isn't set, which should then be fine.
Source:
public String getText(Object element) { if (element instanceof String) { return (String) element; } if (element instanceof FileAndName) { return ((FileAndName) element).getFile().getName(); } return null; }

Target:
Is there a chance of a NPE? could be getFile() null?
Source:
public QueryManager() { this.queries = Multimaps.synchronizedSetMultimap( HashMultimap.<String, ListenableFuture>create() ); this.queryDatasources = Maps.newHashMap(); }

Target:
this needs to be a concurrent hashmap.
Source:
public void setProgressMessage(String progressMessage) { this.progressMessage = progressMessage; }

Target:
Please make it `final`.
Source:
static String chomp(String line) { if (line.charAt(line.length() - 1) == '\n') { return line.substring(0, line.length() - 1); } return line; }

Target:
consider being paranoid and prefix with "line.length() > 0"?
Source:
private Platform getPlatform() throws LauncherStartFailedException { logger.trace("Init Platform..."); updateMessage(BundleUtils.getLabel("splash_checkOS")); final Platform platform = Platform.getPlatform(); if (!platform.isLinux() && !platform.isMac() && !platform.isWindows()) { logger.warn("Detected unexpected platform: {}", platform); } logger.debug("Platform: {}", platform); return platform; }

Target:
Since you removed `throw new LauncherStartFailedException();` this method should not throw such an exception anymore. ```suggestion private Platform getPlatform() { ```
Source:
public SpatialLayoutUnique( CoordinateReferenceSystem crs, SpaceFillingCurve curve ) { super( crs, curve ); }

Target:
Can be package-private
Source:
public void close() throws IOException { // mark this context as closed. The real cleanup like closing of EJB receivers // *isn't* the responsibility of the EJB client context. We'll just let our EJBClientContextListeners // (if any) know about the context being closed and let them handle closing the receivers if they want to this.closed = true; for (final EJBClientContextListener listener : this.ejbClientContextListeners) { try { listener.contextClosed(this); } catch (Throwable t) { logger.debug("Ignoring the exception thrown by an EJB client context listener while closing the context " + this, t); } } // close the executor we use for reconnect handlers this.reconnectionExecutorService.shutdownNow(); }

Target:
I wonder if this should be an atomic operation?
Source:
public void run() { log.info("Starting writer"); try { writerRegistry.register(this); running = true; runUntilCanceled(); } catch (InterruptedException ie) { log.info("Exiting due to thread interrupt"); Thread.currentThread().interrupt(); } catch (Exception e) { log.error("Caught exception running writer: {}", e.getMessage(), e); } finally { running = false; writerRegistry.unregister(this); } }

Target:
Don't catch bare Exception
Source:
private TerrainFacing determineFacing() { Terrain terrain = getTerrain(); TerrainFacingDeterminer facingDeterminer = new TerrainFacingDeterminer(); facingDeterminer.setTopSame(terrain.isSame(topTerrain())); facingDeterminer.setRightSame(terrain.isSame(rightTerrain())); facingDeterminer.setBottomSame(terrain.isSame(bottomTerrain())); facingDeterminer.setLeftSame(terrain.isSame(leftTerrain())); return facingDeterminer.getFacing(); }

Target:
I almost feel a factory approach coming here: `factory.getFacingDeterminer(type)` etc. So we can abstract it. Renaming is nice (now) btw, so it is very explicit for terrain! :)
Source:
public static Locale getLocaleFromString(String localeString, boolean returnDefaultLocale) { Locale result = returnDefaultLocale ? null : Locale.US; try { result = org.apache.commons.lang.LocaleUtils.toLocale(localeString); if(null == result && returnDefaultLocale) { result = Locale.US; } } catch(IllegalArgumentException e) { result = returnDefaultLocale ? Locale.US : null; } return result; }

Target:
Please use "something <operator> null" convention
Source:
private void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { final Collection<String> existingTopics = subscriptionUpdates(); if (usesPatternSubscription() && !existingTopics.equals(topics)) { topics.addAll(existingTopics); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); } }

Target:
Seems the callers are conditioned on `usesPatternSubscription()` already?
Source:
public void tearDown() throws Exception { super.tearDown(); if (origApp != null) Entities.destroyAll(newApp.getManagementContext()); if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir); }

Target:
is this is a typo? (checking for `origApp != null` and then calling method on `newApp`)
Source:
public void notifyUnlock(Collection<? extends EObject> elements) { for (IAuthorityListener listener : Lists.newArrayList(listeners)) { listener.notifyIsReleased((Collection<EObject>) elements); } }

Target:
Why do you use a new array to do iteration? If it is to avoid possible ConcurrentModificationException in multi-thread use case, a synchronized block would be more adapted.
Source:
public File getWorkingDir() { return this.workingDir.toFile(); }

Target:
Any reason to not make this return `Path`? It's new API.
Source:
protected void readHiveRecordAndInsertIntoRecordBatch(Object rowValue) { for (int columnRefIdx = 0; columnRefIdx < selectedStructFieldRefs.length; columnRefIdx++) { Object columnValue = finalObjInspector.getStructFieldData(rowValue, selectedStructFieldRefs[columnRefIdx]); if (columnValue == null) { continue; } columnValueWriters[columnRefIdx].write(columnValue); } }

Target:
Please invert this condition, additional loop breakers make code reading worse.
Source:
private void matchSinglelineComment(boolean includeNewline) { int c = getChar(); while (c != '\n' && c != EOFCHAR && (includeNewline || (c != '\r'))) { c = getChar(); } if (c == EOFCHAR || !includeNewline) { ungetChar(c); } }

Target:
This logic is not correct since it would stop at the first '\r' in "// blah \r blah \r\n".
Source:
private Member createSomeMember(final Vo createdVo) throws ExtendMembershipException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException, InternalErrorException, PrivilegeException { final Candidate candidate = setUpCandidate(); final Member createdMember = perun.getMembersManagerBl().createMemberSync(sess, createdVo, candidate); return createdMember; }

Target:
Also there do not use Privilege Exception. You are calling Bl method so no need throw Privilege Exception at all.
Source:
private ByteBuf createByteBuffer(int i, long lid, long eid) { ByteBuf bb = Unpooled.buffer(4 + 16); bb.writeLong(lid); bb.writeLong(eid); bb.writeInt(i); return bb; }

Target:
This is missing the translation of `bb.putLong(eid-1);`, and the allocation needs to be updated to match it.
Source:
private void attachDiskToTemplate(Guid templateId) { DiskImage templateDiskImage = getParameters().getDiskImage(); DiskVmElement dve = new DiskVmElement(templateDiskImage.getId(), templateId); dve.setDiskInterface(DiskInterface.VirtIO); DbFacade.getInstance().getDiskVmElementDao().save(dve); VmDeviceUtils.addDiskDevice(templateId, templateDiskImage.getId()); }

Target:
use getDiskVmElementDao(), please apply to all the dao calls in that class
Source:
public double computeFor(ASTMethodOrConstructorDeclaration node, MetricVersion version) { JavaParserVisitor visitor = (CycloVersion.IGNORE_BOOLEAN_PATHS.equals(version)) ? new CycloPathUnawareOperationVisitor() : new StandardCycloVisitor(); MutableInt cyclo = (MutableInt) node.jjtAccept(visitor, new MutableInt(1)); return (double) cyclo.getValue(); }

Target:
Since the version is a enum, we can compare here using `==` directly.
Source:
public long estimateEncodedKeyComponentSize(int[] key) { // the size is calculated conservatively, first key may be accounted for twice long estimatedSize = (key.length * Integer.BYTES); estimatedSize += Arrays.stream(key) .filter(element -> dimLookup.getValue(element) != null) .mapToLong(element -> dimLookup.getValue(element).length() * Character.BYTES).sum(); return estimatedSize; }

Target:
nit: Druid code convention is like ``` .mapToLong(element -> dimLookup.getValue(element).length() * Character.BYTES) .sum(); ```
Source:
public void add(int index, T element) { if (comparingSet.add(element)) { try { super.add(index, element); } catch (IndexOutOfBoundsException ioobException) { comparingSet.remove(element); throw new IndexOutOfBoundsException(); } } }

Target:
nicely done! just one consideration: the `ioobException` contains the information on what went wrong (i.e. what the actual index was and the size of the list) and by catching it and then throwing a new one you lose this information. so please change it such that the stacktrace and message of the original exception are passed on: ``` } catch (IndexOutOfBoundsException ioobException) { comparingSet.remove(element); throw ioobException; ```
Source:
public String getClusterName() { final String clusterName = client.getClientConfig().getClusterName(); if (clusterName == null) { throw new RuntimeException("Cluster name cannot be null on the client which participates in XA Transaction"); } return clusterName; }

Target:
how can a `clusterName` be `null`?
Source:
public JSchConnection getProxyConnection() { String proxyConnectionName = getProxyConnectionName(); if (proxyConnectionName.equals(EMPTY_STRING)) { return null; } else { return (JSchConnection) fManager.getConnection(proxyConnectionName); } }

Target:
Redundant else.
Source:
protected void deleteLog() { CommandContext commandContext = new CommandContext(); commandContext.setData("SingleRun", "true"); commandContext.setData("OlderThan", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); synchronized (this) { jobServicesClient.scheduleRequest(CONTAINER_ID, JobRequestInstance.builder().command("org.jbpm.executor.commands.LogCleanupCommand").build()); } }

Target:
This commandContext seems unused.
Source:
private static String buildPredicate(Column partitionKey, String value) { if (isQuotedType(partitionKey.getType())) { return String.format("(%s='%s')", partitionKey.getName(), value); } else { return String.format("(%s=%s)", partitionKey.getName(), value); } }

Target:
Nit: this "else" is redundant since the "if" branch returns conditionally. We generally prefer to write such expressions as ```java if (...) { return ...; } return ...;
Source:
int expiryQueueSize() { log.warn("The expiry queueSize attribute is deprecated and will be removed"); return expiryQueueSize.get(); }

Target:
@diegolovison the warning should be logged when setting the queue size, not when reading it. This is what I had in mind: https://github.com/infinispan/infinispan/commit/4b40bf35dfbd892fb993b9096a30164ec0a4af39
Source:
public IAuthorizationPrincipal getPrincipalForEntity(Entity entity) { // attempt to determine the entity type class for this principal if (entity != null) { Class entityType; if (entity.getEntityType().equals(EntityEnum.GROUP.toString())) { entityType = IEntityGroup.class; } else { entityType = EntityEnum.getEntityEnum(entity.getEntityType()).getClazz(); } // construct an authorization principal for this JsonEntityBean AuthorizationService authService = AuthorizationService.instance(); IAuthorizationPrincipal p = authService.newPrincipal(entity.getId(), entityType); return p; } return null; }

Target:
:art: Personally I would lean toward using a guard statement. ```java if (entity == null) { return null } ... ```
Source:
public static List<String> getKeyListFromBlobStore(BlobStore blobStore) throws Exception { Iterator<String> keys = blobStore.listKeys(); List<String> keyList = new ArrayList<String>(); while (keys != null && keys.hasNext()) { keyList.add(keys.next()); } LOG.debug("KeyList from blobstore {}", keyList); return keyList; }

Target:
should move keys!=null out of while (add an if )
Source:
private @Nullable Map<@NonNull String, @NonNull SegmentStoreStatistics> getPerTypeStats(long start, long end , IProgressMonitor monitor) { Collection<@NonNull ISegment> store = getSegmentStore(start, end); if (store == null) { return null; } if (monitor.isCanceled()) { return Collections.EMPTY_MAP; } return calculateTotalPerType(store, monitor); }

Target:
can this return emptyMap? and just be another clause of the if below?
Source:
protected void toLegacyText(StringBuilder builder) { builder.append(this.selector); }

Target:
Override
Source:
public void refresh() { start(); super.refresh(true); }

Target:
We should not force all of the refreshes
Source:
private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { if (savedRequest == null) { return false; } else if (savedRequest instanceof DefaultSavedRequest) { DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) savedRequest; return defaultSavedRequest.doesRequestMatch(request, this.portResolver); } else { String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } }

Target:
This `else if` block can be removed. We only have information about the saved request URL, so that is all we can really compare.
Source:
public void setEnabled(boolean enabled) { asTextBox().setEnabled(enabled); if (enabled) { asTextBox().getElement().getStyle().setBackgroundColor("#ffffff"); //$NON-NLS-1$ } else { // the default background of the textbox is not the same as our disabled color asTextBox().getElement().getStyle().setBackgroundColor("#e5e5e5"); //$NON-NLS-1$ } }

Target:
Wouldn't it make more sense to add/remove a style class instead of hard coding a background color into the box? What if we change the default background color of the application to not be white, then this will have to change too. I did a quick search and I can't find any other 'disabled' color in the application as #E5E5E5, where did that color come from?
Source:
public void registerLayers(MapActivity activity) { // remove old if existing after turn if(parkingLayer != null) { activity.getMapView().removeLayer(parkingLayer); } parkingLayer = new ParkingPositionLayer(activity, this); // activity.getMapView().addLayer(parkingLayer, 5.5f); registerWidget(activity); }

Target:
ParkingPositionLayer - delete
Source:
public String toString() { String prefix = (TotalMilliseconds < 0) ? "-" : ""; // Ok to use String.format directly since GWT does not use TimeSpan from ui override package return String.format("%s%d.%02d:%02d:%02d.%03d", prefix, Days, Hours, Minutes, Seconds, Milliseconds); }

Target:
If you are going to use ternary operator, might as well just drop it right into the return below, without the intermediate variable
Source:
private void handleTransferComplete(final FileTransfer fileTransfer) { this.activeFileTransfers.remove(fileTransfer); this.concurrentTransfersSemaphore.release(); System.out.println(">>> " + this.concurrentTransfersSemaphore.availablePermits()); }

Target:
Assuming this is another debugging call.
Source:
public Object clone() throws CloneNotSupportedException { super.clone(); CommandContext ctx = new CommandContext(); ctx.setFromContext(this); return this.duplicate(); }

Target:
clone should not use duplicate... duplicate should be an alias of clone. hmmm... you created infinite loop? clone->duplicate->clone? this entire logic is incorrect... should be, something line: CommandContext cloned = (CommandContext)super.clone(); cloned.setFromContext(this); return cloned;
Source:
@Override public Response execute(Request request) throws IOException { HttpUriRequest apacheRequest = createRequest(request); HttpResponse apacheResponse = execute(client, apacheRequest); String url = request.getUrl(); if (this.redirectHandler != null && this.redirectHandler.finalUri != null) { // if we have a redirect handler, and it has been redirected, use it's url url = this.redirectHandler.finalUri.toString(); } return parseResponse(url, apacheResponse); }

Target:
Drop the `this` here and two lines down.
Source:
public GlobalMetricsConfigurationBuilder metrics() { globalConfig.metrics().gauges(true); return globalConfig.metrics(); }

Target:
I thought you wanted to end this practice, Adrian?
Source:
static RelDistribution getDistribution(RelNode node) { if (node instanceof VoltLogicalTableScan) { return node.getTable().getDistribution(); } return node.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); }

Target:
I would always return from the trait set to avoid modifying the trait associated with a table itself
Source:
public void setCorrelationId(String correlationId) { if (correlationId == null) { this.correlationId = Guid.NewGuid().toString(); } else if (correlationId.length() <= 100) { this.correlationId = correlationId; } else { this.correlationId = correlationId.substring(0, 100); } }

Target:
I don't think we should manipulate the correlation Id. I would add input validator for validating the correlation Id length.
Source:
public void shouldRunQueryFromFile() throws IOException, InterruptedException { try (TempFile file = new TempFile()) { Files.write("select * from hive.default.nation;\n", file.file(), UTF_8); launchPrestoCliWithServerArgument("--file", file.file().getAbsolutePath()); assertThat(trimLines(presto.readRemainingOutputLines())).containsAll(nationTableBatchLines); presto.waitForWithTimeoutAndKill(); } }

Target:
we don't assert anywhere that on success cli exits with `0`.
Source:
static <E extends Enum<E>> Optional<Class<?>> ifEnum(Type type) { return Optional.of(type) .map(GenericTypes::getErasedType) .filter(Class::isEnum) .map(c -> (Class<E>) c); }

Target:
can / should this be `Optional<Class<E>>`?
Source:
private String getter() { ImmutableList<String> topSpeciesNames = featuredSpeciesService.getSpeciesNamesSortedByExperimentCount(); return GSON.toJson( ImmutableMap.of( "topSpecies", topSpeciesNames.subList(0, Math.min(topSpeciesNames.size(), FEATURED_SPECIES)), "allSpecies", ImmutableList.sortedCopyOf(topSpeciesNames), "separator", ThreadLocalRandom.current().nextDouble() > 0.999 ? BEST_SEPARATOR : NORMAL_SEPARATOR)); }

Target:
I don't quite following this random separator logic...
Source:
private long roundToNextMinute(long timeInMillis) { Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(timeInMillis); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MINUTE, 1); return calendar.getTimeInMillis(); }

Target:
Shouldn't this be Calendar.getInstance() instead ? That way it's truly a no-op.
Source:
public void testMapInvalidEnumValue() throws SQLException { Handle h = db.openHandle(); h.createStatement("insert into something (id, name) values (1, 'joe')").execute(); try { h.createQuery("select * from something order by id") .mapToBean(SomethingElse.class) .findFirst(); fail("Expected IllegalArgumentException was not thrown"); } catch (IllegalArgumentException e) { assertThat(e).isNotNull(); } }

Target:
Redundant assertion
Source:
private static void cachePut(final CacheKey key, final boolean value) { final LRUMap<CacheKey, Boolean> cache = SecuredItemImpl.CACHE.get(); if (cache != null) { cache.put(key, value); SecuredItemImpl.CACHE.set(cache); } }

Target:
Again, this change modifies the is not semantic meaning.
Source:
public void setUp() throws Exception { testContext = getInstrumentation().getContext(); }

Target:
Don't you need a `super.setUp()` call here?
Source:
private void maybeAddCluster() throws IOException { for (Map.Entry<String, HelixAdmin> entry : adminForDc.entrySet()) { // Add a cluster entry in every DC String dcName = entry.getKey(); HelixAdmin admin = entry.getValue(); if (!admin.getClusters().contains(clusterName)) { info("Adding cluster in {}", clusterName, dcName); admin.addCluster(clusterName); admin.addStateModelDef(clusterName, LeaderStandbySMD.name, LeaderStandbySMD.build()); } } }

Target:
seems there is no IOException thrown from this method.
Source:
private int matchResultColour(MatchResult result) { int colour; switch (result) { case WON: colour = R.color.battlereport_won; break; case LOST: colour = R.color.battlereport_lost; break; case DRAW: colour = R.color.battlereport_draw; break; default: return R.color.black; } return context.getResources().getColor(colour); }

Target:
Any reason for this not assigning `colour` like the rest of the cases, instead of returning?
Source:
public PotionEffect getPotionEffect() { return super.getPotionEffect; }

Target:
Compile error here @mcenderdragon
Source:
public static CalledStringFunction create(long start, long end, int depth, String value, @Nullable ICalledFunction parent) { if (start > end) { throw new IllegalArgumentException(Messages.TimeError + '[' + start + ',' + end + ']'); } return new CalledStringFunction(start, end, value, depth, parent); }

Target:
I think this could be protected