auphong2707/dl4se-code-review-dataset huggingface dataset:
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 { START RealmLog.error("Log out user"); END logOut(user); return user; } }.start(); } ```suggestion RealmLog.info("Log out user " + user.getEmail()); ```

Target:
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 { logOut(user); return user; } }.start(); }
Source:
START @Override END 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))); } please put the @Override annotation on its own line

Target:
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))); }
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())); START } END } 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.

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__HOT_PLUG); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK); }
Source:
START public <B> Eval<B> map(final F<A, B> f) { END return bind(a -> now(f.f(a))); } could be `final`.

Target:
public final <B> Eval<B> map(final F<A, B> f) { return bind(a -> now(f.f(a))); }
Source:
protected PhysicalOperator getNewWithChild(PhysicalOperator child) { START return new IteratorValidator(child, this.isRepeatable); END } Remove the 'this' qualifier .

Target:
protected PhysicalOperator getNewWithChild(PhysicalOperator child) { return new IteratorValidator(child, isRepeatable); }
Source:
public synchronized List<Inode<?>> getInodeList() { START return Lists.newArrayList(mLockList.getInodes()); END } does `LockList#getInodes` already make a copy?

Target:
public synchronized List<Inode<?>> getInodeList() { return mLockList.getInodes(); }
Source:
private void setupNetworkDao() { when(getDbFacadeMockInstance().getNetworkDao()).thenReturn(networkDaoMock); when(networkDaoMock.get(networkId)).thenReturn((networkMocked)); START when(networkMocked.getQosId()).thenReturn(null); END } And here return the proper ID as well - you're trying to mimic real behavior.

Target:
private void setupNetworkDao() { when(getDbFacadeMockInstance().getNetworkDao()).thenReturn(networkDaoMock); when(networkDaoMock.get(networkId)).thenReturn((networkMocked)); }
Source:
public void checkStorageDomainNotEqualWithStatusActive() { setStorageDomainStatus(StorageDomainStatus.Active); assertFalse(cmd.checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); List<String> messages = cmd.getReturnValue().getCanDoActionMessages(); START assertEquals(2, messages.size()); END assertEquals(messages.get(0), VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2.toString()); assertEquals(messages.get(1), String.format("$status %1$s", StorageDomainStatus.Active)); } shouldn't actual <--> expected be replaced here as well ?

Target:
public void checkStorageDomainNotEqualWithStatusActive() { setStorageDomainStatus(StorageDomainStatus.Active); assertFalse(cmd.checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); List<String> messages = cmd.getReturnValue().getCanDoActionMessages(); assertEquals(2, messages.size()); assertEquals(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2.toString(), messages.get(0)); assertEquals(String.format("$status %1$s", StorageDomainStatus.Active), messages.get(1)); }
Source:
public ShowBubbleActor createBubbleActor() throws InterpretationException { String textToDisplay = text == null ? "" : text.interpretString(sprite); START if (textToDisplay.equals("")) { END return null; } return new ShowBubbleActor(textToDisplay, sprite, type); } this can be replaced by `textToDisplay.isEmpty()`

Target:
public ShowBubbleActor createBubbleActor() throws InterpretationException { String textToDisplay = text == null ? "" : text.interpretString(sprite); if (textToDisplay.isEmpty()) { return null; } return new ShowBubbleActor(textToDisplay, sprite, type); }
Source:
public List<String> getGroupsForUser(String userId) { List<String> groups = groupStore.get(userId); if( groups == null ) { groups = new ArrayList<String>(0); } START return new java.util.ArrayList<String>(groups); END } Maybe remove the package name as it is already in the import statements.

Target:
public List<String> getGroupsForUser(String userId) { List<String> groups = groupStore.get(userId); if( groups == null ) { groups = new ArrayList<String>(0); } return new ArrayList<String>(groups); }
Source:
public FlashScope getFlashCookie() { START return wrapped.getFlashScope(); END } please leave it that way - it's intentionally referencing the deprecated version.

Target:
public FlashScope getFlashCookie() { return wrapped.getFlashCookie(); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); START if (repository == null) { END return null; } PushToGerritWizard wiz = new PushToGerritWizard(repository); WizardDialog dlg = new WizardDialog(HandlerUtil .getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; } style nit: no braces around single line blocks

Target:
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; }
Source:
public WriteRequest(ByteBuf buf) { writeMode = ICorfuPayload.fromBuffer(buf, WriteMode.class); START streamAddresses = null; END data = ICorfuPayload.fromBuffer(buf, LogData.class); } I think we can remove the streamAddresses field

Target:
public WriteRequest(ByteBuf buf) { writeMode = ICorfuPayload.fromBuffer(buf, WriteMode.class); data = ICorfuPayload.fromBuffer(buf, LogData.class); }
Source:
protected void assertSameLastUpdateTime() { assertTrueEventually(() -> { START long lastUpdateTime = localCollectionStats.getLastUpdateTime(); END assertEqualsStringFormat("Expected the lastUpdateTime to be %d, but was %d", previousUpdateTime, lastUpdateTime); previousUpdateTime = lastUpdateTime; }); } 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.

Target:
protected void assertSameLastUpdateTime() { long lastUpdateTime = localCollectionStats.getLastUpdateTime(); assertEqualsStringFormat("Expected the lastUpdateTime to be %d, but was %d", previousUpdateTime, lastUpdateTime); previousUpdateTime = lastUpdateTime; }
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) { START if (refreshRepos(storageDomainId, imageType)) { END 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); } Missing ! operator

Target:
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); }
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); } START return new DefaultGitSynchronizer(display); END } 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.

Target:
private static GitSynchronizer getSynchronizer() { if (Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.USE_LOGICAL_MODEL)) { return new ModelAwareGitSynchronizer(); } return new DefaultGitSynchronizer(); }
Source:
public long getAvgExecutionTime() { long avgExecTime = -1; try { synchronized (this) { avgExecTime = totalExecutionTime / invocationCnt; START } END } catch (Exception e) { if (invocationCnt == 0 && totalExecutionTime == 0) { avgExecTime = 0; } } return avgExecTime; } 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 ?

Target:
public long getAvgExecutionTime() { long avgExecTime = -1; synchronized (this) { try { avgExecTime = totalExecutionTime / invocationCnt; } catch (Exception e) { if (invocationCnt == 0 && totalExecutionTime == 0) { avgExecTime = 0; } } } return avgExecTime; }
Source:
public void cleanUpEnvironment() { START fTrace.dispose(); END fScriptingMarkerSource.dispose(); fScriptingMarkerSource = null; fScriptingMarkerSourceFactory.dispose(); fTraceMarkerScriptingModule = null; } 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.

Target:
public void cleanUpEnvironment() { if (fTrace != null) { fTrace.dispose(); fTrace = null; } if (fScriptingMarkerSource != null) { fScriptingMarkerSource.dispose(); fScriptingMarkerSource = null; } if (fScriptingMarkerSourceFactory != null) { fScriptingMarkerSourceFactory.dispose(); fScriptingMarkerSourceFactory = null; } }
Source:
public int hashCode() { START return HashCodeBuilder.reflectionHashCode(formField.getPageNumber()); END } This should call .append(formField.getPageNumber()).build();

Target:
public int hashCode() { return new HashCodeBuilder().append(formField.getPageNumber()).build(); }
Source:
public static byte[] toUtf8(final String string) { if(string == null){ START return null; END } try { return string.getBytes(UTF8_STRING); } catch (UnsupportedEncodingException e) { // Should never happen throw Throwables.propagate(e); } } annotate with nullable.

Target:
public static byte[] toUtf8(final String string) { try { return string.getBytes(UTF8_STRING); } catch (UnsupportedEncodingException e) { // Should never happen throw Throwables.propagate(e); } }
Source:
private void decodeLocalizedTitles(DBObject dbObject, Described entity) { START if (dbObject.containsField(LOCALIZED_TITLES_KEY)) { END 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()); } })); } } 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.

Target:
private void decodeLocalizedTitles(DBObject dbObject, Described entity) { 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()); } })); }
Source:
public String getText(Object element) { if (element instanceof String) { return (String) element; } if (element instanceof FileAndName) { START return ((FileAndName) element).getFile().getName(); END } return null; } Is there a chance of a NPE? could be getFile() null?

Target:
public String getText(Object element) { if (element instanceof String) { return (String) element; } if (element instanceof FileAndName) { final File file = ((FileAndName) element).getFile(); if (file != null) { // should never not happen since file is final // and always set automatically return file.getName(); } } return null; }
Source:
public QueryManager() { this.queries = Multimaps.synchronizedSetMultimap( HashMultimap.<String, ListenableFuture>create() ); START this.queryDatasources = Maps.newHashMap(); END } this needs to be a concurrent hashmap.

Target:
public QueryManager() { this.queries = Multimaps.synchronizedSetMultimap( HashMultimap.<String, ListenableFuture>create() ); this.queryDatasources = Multimaps.synchronizedSetMultimap( HashMultimap.<String, String>create() ); }
Source:
START public void setProgressMessage(String progressMessage) { END this.progressMessage = progressMessage; } Please make it `final`.

Target:
public final void setProgressMessage(String progressMessage) { this.progressMessage = progressMessage; }
Source:
static String chomp(String line) { START if (line.charAt(line.length() - 1) == '\n') { END return line.substring(0, line.length() - 1); } return line; } consider being paranoid and prefix with "line.length() > 0"?

Target:
static String chomp(String line) { if (line != null && !line.isEmpty() && line.charAt(line.length() - 1) == '\n') { return line.substring(0, line.length() - 1); } return line; }
Source:
START private Platform getPlatform() throws LauncherStartFailedException { END 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; } Since you removed `throw new LauncherStartFailedException();` this method should not throw such an exception anymore. ```suggestion private Platform getPlatform() { ```

Target:
private Platform getPlatform() { 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; }
Source:
START public SpatialLayoutUnique( CoordinateReferenceSystem crs, SpaceFillingCurve curve ) END { super( crs, curve ); } Can be package-private

Target:
SpatialLayoutUnique( CoordinateReferenceSystem crs, SpaceFillingCurve curve ) { super( crs, curve ); }
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 START this.closed = true; END 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(); } I wonder if this should be an atomic operation?

Target:
public synchronized void close() throws IOException { if (closed) { return; } // 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(); }
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(); START } catch (Exception e) { END log.error("Caught exception running writer: {}", e.getMessage(), e); } finally { running = false; writerRegistry.unregister(this); } } Don't catch bare Exception

Target:
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(); } finally { running = false; writerRegistry.unregister(this); } }
Source:
private TerrainFacing determineFacing() { Terrain terrain = getTerrain(); START TerrainFacingDeterminer facingDeterminer = new TerrainFacingDeterminer(); END facingDeterminer.setTopSame(terrain.isSame(topTerrain())); facingDeterminer.setRightSame(terrain.isSame(rightTerrain())); facingDeterminer.setBottomSame(terrain.isSame(bottomTerrain())); facingDeterminer.setLeftSame(terrain.isSame(leftTerrain())); return facingDeterminer.getFacing(); } 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! :)

Target:
private TerrainFacing determineFacing() { Terrain terrain = getTerrain(); return TerrainFacingDeterminer.getFacing( terrain.isSame(topTerrain()), terrain.isSame(rightTerrain()), terrain.isSame(bottomTerrain()), terrain.isSame(leftTerrain()) ); }
Source:
public static Locale getLocaleFromString(String localeString, boolean returnDefaultLocale) { Locale result = returnDefaultLocale ? null : Locale.US; try { result = org.apache.commons.lang.LocaleUtils.toLocale(localeString); START if(null == result && returnDefaultLocale) { END result = Locale.US; } } catch(IllegalArgumentException e) { result = returnDefaultLocale ? Locale.US : null; } return result; } Please use "something <operator> null" convention

Target:
public static Locale getLocaleFromString(String localeString, boolean returnDefaultLocale) { Locale result = returnDefaultLocale ? null : Locale.US; try { result = org.apache.commons.lang.LocaleUtils.toLocale(localeString); if(result == null && returnDefaultLocale) { result = Locale.US; } } catch(IllegalArgumentException e) { result = returnDefaultLocale ? Locale.US : null; } return result; }
Source:
private void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { final Collection<String> existingTopics = subscriptionUpdates(); START if (usesPatternSubscription() && !existingTopics.equals(topics)) { END topics.addAll(existingTopics); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); } } Seems the callers are conditioned on `usesPatternSubscription()` already?

Target:
private void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { final Collection<String> existingTopics = subscriptionUpdates(); if (!existingTopics.equals(topics)) { topics.addAll(existingTopics); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); } }
Source:
public void tearDown() throws Exception { super.tearDown(); START if (origApp != null) Entities.destroyAll(newApp.getManagementContext()); END if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir); } is this is a typo? (checking for `origApp != null` and then calling method on `newApp`)

Target:
public void tearDown() throws Exception { super.tearDown(); if (origApp != null) Entities.destroyAll(origApp.getManagementContext()); if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir); }
Source:
public void notifyUnlock(Collection<? extends EObject> elements) { START for (IAuthorityListener listener : Lists.newArrayList(listeners)) { END listener.notifyIsReleased((Collection<EObject>) elements); } } 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.

Target:
public void notifyUnlock(Collection<? extends EObject> elements) { for (IAuthorityListener listener : listeners) { listener.notifyIsReleased((Collection<EObject>) elements); } }
Source:
START public File getWorkingDir() { END return this.workingDir.toFile(); } Any reason to not make this return `Path`? It's new API.

Target:
public Path getWorkingDir() { return this.workingDir; }
Source:
protected void readHiveRecordAndInsertIntoRecordBatch(Object rowValue) { for (int columnRefIdx = 0; columnRefIdx < selectedStructFieldRefs.length; columnRefIdx++) { Object columnValue = finalObjInspector.getStructFieldData(rowValue, selectedStructFieldRefs[columnRefIdx]); START if (columnValue == null) { END continue; } columnValueWriters[columnRefIdx].write(columnValue); } } Please invert this condition, additional loop breakers make code reading worse.

Target:
protected void readHiveRecordAndInsertIntoRecordBatch(Object rowValue) { for (int columnRefIdx = 0; columnRefIdx < selectedStructFieldRefs.length; columnRefIdx++) { Object columnValue = finalObjInspector.getStructFieldData(rowValue, selectedStructFieldRefs[columnRefIdx]); if (columnValue != null) { columnValueWriters[columnRefIdx].write(columnValue); } } }
Source:
private void matchSinglelineComment(boolean includeNewline) { int c = getChar(); START while (c != '\n' && c != EOFCHAR && (includeNewline || (c != '\r'))) { END c = getChar(); } if (c == EOFCHAR || !includeNewline) { ungetChar(c); } } This logic is not correct since it would stop at the first '\r' in "// blah \r blah \r\n".

Target:
private void matchSinglelineComment(boolean includeNewline) { int c = getChar(); while (c != '\n' && c != EOFCHAR) { int next = getChar(); if (c == '\r' && next == '\n' && !includeNewline) { // exclude CRLF line ending ungetChar(next); break; } c = next; } if (c == EOFCHAR || !includeNewline) { ungetChar(c); } }
Source:
START private Member createSomeMember(final Vo createdVo) throws ExtendMembershipException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException, InternalErrorException, PrivilegeException { END final Candidate candidate = setUpCandidate(); final Member createdMember = perun.getMembersManagerBl().createMemberSync(sess, createdVo, candidate); return createdMember; } Also there do not use Privilege Exception. You are calling Bl method so no need throw Privilege Exception at all.

Target:
private Member createSomeMember(final Vo createdVo) throws ExtendMembershipException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException, InternalErrorException { final Candidate candidate = setUpCandidate(); final Member createdMember = perun.getMembersManagerBl().createMemberSync(sess, createdVo, candidate); return createdMember; }
Source:
private ByteBuf createByteBuffer(int i, long lid, long eid) { ByteBuf bb = Unpooled.buffer(4 + 16); bb.writeLong(lid); START bb.writeLong(eid); END bb.writeInt(i); return bb; } This is missing the translation of `bb.putLong(eid-1);`, and the allocation needs to be updated to match it.

Target:
private ByteBuf createByteBuffer(int i, long lid, long eid) { ByteBuf bb = Unpooled.buffer(4 + 16); bb.writeLong(lid); bb.writeLong(eid); bb.writeLong(eid - 1); bb.writeInt(i); return bb; }
Source:
private void attachDiskToTemplate(Guid templateId) { DiskImage templateDiskImage = getParameters().getDiskImage(); DiskVmElement dve = new DiskVmElement(templateDiskImage.getId(), templateId); dve.setDiskInterface(DiskInterface.VirtIO); START DbFacade.getInstance().getDiskVmElementDao().save(dve); END VmDeviceUtils.addDiskDevice(templateId, templateDiskImage.getId()); } use getDiskVmElementDao(), please apply to all the dao calls in that class

Target:
private void attachDiskToTemplate(Guid templateId) { DiskImage templateDiskImage = getParameters().getDiskImage(); DiskVmElement dve = new DiskVmElement(templateDiskImage.getId(), templateId); dve.setDiskInterface(DiskInterface.VirtIO); getDiskVmElementDao().save(dve); VmDeviceUtils.addDiskDevice(templateId, templateDiskImage.getId()); }
Source:
public double computeFor(ASTMethodOrConstructorDeclaration node, MetricVersion version) { START JavaParserVisitor visitor = (CycloVersion.IGNORE_BOOLEAN_PATHS.equals(version)) END ? new CycloPathUnawareOperationVisitor() : new StandardCycloVisitor(); MutableInt cyclo = (MutableInt) node.jjtAccept(visitor, new MutableInt(1)); return (double) cyclo.getValue(); } Since the version is a enum, we can compare here using `==` directly.

Target:
public double computeFor(ASTMethodOrConstructorDeclaration node, MetricVersion version) { JavaParserVisitor visitor = (CycloVersion.IGNORE_BOOLEAN_PATHS == version) ? new CycloPathUnawareOperationVisitor() : new StandardCycloVisitor(); MutableInt cyclo = (MutableInt) node.jjtAccept(visitor, new MutableInt(1)); return (double) cyclo.getValue(); }
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) START .mapToLong(element -> dimLookup.getValue(element).length() * Character.BYTES).sum(); END return estimatedSize; } nit: Druid code convention is like ``` .mapToLong(element -> dimLookup.getValue(element).length() * Character.BYTES) .sum(); ```

Target:
public long estimateEncodedKeyComponentSize(int[] key) { // string length is being accounted for each time they are referenced, based on dimension handler interface, // even though they are stored just once. It may overestimate the size by a bit, but we wanted to leave // more buffer to be safe 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; }
Source:
public void add(int index, T element) { if (comparingSet.add(element)) { try { super.add(index, element); } catch (IndexOutOfBoundsException ioobException) { comparingSet.remove(element); START throw new IndexOutOfBoundsException(); END } } } 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; ```

Target:
public void add(int index, T element) { if (comparingSet.add(element)) { try { super.add(index, element); } catch (IndexOutOfBoundsException ioobException) { comparingSet.remove(element); throw ioobException; } } }
Source:
public String getClusterName() { final String clusterName = client.getClientConfig().getClusterName(); START if (clusterName == null) { END throw new RuntimeException("Cluster name cannot be null on the client which participates in XA Transaction"); } return clusterName; } how can a `clusterName` be `null`?

Target:
public String getClusterName() { return client.getClientConfig().getClusterName(); }
Source:
public JSchConnection getProxyConnection() { String proxyConnectionName = getProxyConnectionName(); if (proxyConnectionName.equals(EMPTY_STRING)) { return null; START } else { END return (JSchConnection) fManager.getConnection(proxyConnectionName); } } Redundant else.

Target:
public JSchConnection getProxyConnection() { String proxyConnectionName = getProxyConnectionName(); if (proxyConnectionName.equals(EMPTY_STRING)) { return null; } return (JSchConnection) fManager.getConnection(proxyConnectionName); }
Source:
protected void deleteLog() { START CommandContext commandContext = new CommandContext(); END 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()); } } This commandContext seems unused.

Target:
protected void deleteLog() { synchronized (this) { jobServicesClient.scheduleRequest(CONTAINER_ID, JobRequestInstance.builder().command("org.jbpm.executor.commands.LogCleanupCommand").build()); } }
Source:
private static String buildPredicate(Column partitionKey, String value) { if (isQuotedType(partitionKey.getType())) { return String.format("(%s='%s')", partitionKey.getName(), value); } START else { END return String.format("(%s=%s)", partitionKey.getName(), value); } } Nit: this "else" is redundant since the "if" branch returns conditionally. We generally prefer to write such expressions as ```java if (...) { return ...; } return ...;

Target:
private static String buildPredicate(Column partitionKey, String value) { if (isQuotedType(partitionKey.getType())) { return String.format("(%s='%s')", partitionKey.getName(), value); } return String.format("(%s=%s)", partitionKey.getName(), value); }
Source:
int expiryQueueSize() { START log.warn("The expiry queueSize attribute is deprecated and will be removed"); END return expiryQueueSize.get(); } @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

Target:
int expiryQueueSize() { return expiryQueueSize.get(); }
Source:
public IAuthorizationPrincipal getPrincipalForEntity(Entity entity) { // attempt to determine the entity type class for this principal START if (entity != null) { END 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; } :art: Personally I would lean toward using a guard statement. ```java if (entity == null) { return null } ... ```

Target:
public IAuthorizationPrincipal getPrincipalForEntity(Entity entity) { // attempt to determine the entity type class for this principal if (entity == null) { return 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; }
Source:
public static List<String> getKeyListFromBlobStore(BlobStore blobStore) throws Exception { Iterator<String> keys = blobStore.listKeys(); List<String> keyList = new ArrayList<String>(); START while (keys != null && keys.hasNext()) { END keyList.add(keys.next()); } LOG.debug("KeyList from blobstore {}", keyList); return keyList; } should move keys!=null out of while (add an if )

Target:
public static List<String> getKeyListFromBlobStore(BlobStore blobStore) throws Exception { Iterator<String> keys = blobStore.listKeys(); List<String> keyList = new ArrayList<String>(); if (keys != null) { while (keys.hasNext()) { keyList.add(keys.next()); } } LOG.debug("KeyList from blobstore {}", keyList); return keyList; }
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) { START return null; END } if (monitor.isCanceled()) { return Collections.EMPTY_MAP; } return calculateTotalPerType(store, monitor); } can this return emptyMap? and just be another clause of the if below?

Target:
private @Nullable Map<@NonNull String, @NonNull SegmentStoreStatistics> getPerTypeStats(long start, long end , IProgressMonitor monitor) { Collection<@NonNull ISegment> store = getSegmentStore(start, end); if (store == null || monitor.isCanceled()) { return null; } return calculateTotalPerType(store, monitor); }
Source:
START protected void toLegacyText(StringBuilder builder) END { builder.append(this.selector); } Override

Target:
protected void toLegacyText(StringBuilder builder) { builder.append( this.selector ); super.toLegacyText( builder ); }
Source:
public void refresh() { start(); START super.refresh(true); END } We should not force all of the refreshes

Target:
public void refresh() { start(); super.refresh(); }
Source:
private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { if (savedRequest == null) { return false; START } else if (savedRequest instanceof DefaultSavedRequest) { END DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) savedRequest; return defaultSavedRequest.doesRequestMatch(request, this.portResolver); } else { String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } } This `else if` block can be removed. We only have information about the saved request URL, so that is all we can really compare.

Target:
private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { if (savedRequest == null) { return false; } else { String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } }
Source:
public void setEnabled(boolean enabled) { asTextBox().setEnabled(enabled); START if (enabled) { END 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$ } } 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?

Target:
public void setEnabled(boolean enabled) { asTextBox().setEnabled(enabled); }
Source:
public void registerLayers(MapActivity activity) { // remove old if existing after turn if(parkingLayer != null) { activity.getMapView().removeLayer(parkingLayer); } START parkingLayer = new ParkingPositionLayer(activity, this); END // activity.getMapView().addLayer(parkingLayer, 5.5f); registerWidget(activity); } ParkingPositionLayer - delete

Target:
public void registerLayers(MapActivity activity) { registerWidget(activity); }
Source:
public String toString() { START String prefix = (TotalMilliseconds < 0) ? "-" : ""; END // 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); } If you are going to use ternary operator, might as well just drop it right into the return below, without the intermediate variable

Target:
public String toString() { // 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", (TotalMilliseconds < 0) ? "-" : "", Days, Hours, Minutes, Seconds, Milliseconds); }
Source:
private void handleTransferComplete(final FileTransfer fileTransfer) { this.activeFileTransfers.remove(fileTransfer); this.concurrentTransfersSemaphore.release(); START System.out.println(">>> " + this.concurrentTransfersSemaphore.availablePermits()); END } Assuming this is another debugging call.

Target:
private void handleTransferComplete(final FileTransfer fileTransfer) { this.activeFileTransfers.remove(fileTransfer); this.concurrentTransfersSemaphore.release(); }
Source:
public Object clone() throws CloneNotSupportedException { super.clone(); CommandContext ctx = new CommandContext(); ctx.setFromContext(this); START return this.duplicate(); END } 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;

Target:
public Object clone() { return new CommandContext(this); }
Source:
@Override public Response execute(Request request) throws IOException { HttpUriRequest apacheRequest = createRequest(request); HttpResponse apacheResponse = execute(client, apacheRequest); String url = request.getUrl(); START if (this.redirectHandler != null && this.redirectHandler.finalUri != null) { END // if we have a redirect handler, and it has been redirected, use it's url url = this.redirectHandler.finalUri.toString(); } return parseResponse(url, apacheResponse); } Drop the `this` here and two lines down.

Target:
@Override public Response execute(Request request) throws IOException { HttpUriRequest apacheRequest = createRequest(request); HttpResponse apacheResponse = execute(client, apacheRequest); String url = request.getUrl(); if (redirectHandler != null && redirectHandler.finalUri != null) { // If we have a redirect handler, and it has been redirected, use it's URL. url = redirectHandler.finalUri.toString(); } return parseResponse(url, apacheResponse); }
Source:
public GlobalMetricsConfigurationBuilder metrics() { START globalConfig.metrics().gauges(true); END return globalConfig.metrics(); } I thought you wanted to end this practice, Adrian?

Target:
public GlobalMetricsConfigurationBuilder metrics() { return globalConfig.metrics(); }
Source:
static RelDistribution getDistribution(RelNode node) { START if (node instanceof VoltLogicalTableScan) { END return node.getTable().getDistribution(); } return node.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); } I would always return from the trait set to avoid modifying the trait associated with a table itself

Target:
static RelDistribution getDistribution(RelNode node) { return node.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); }
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); } START } END I don't think we should manipulate the correlation Id. I would add input validator for validating the correlation Id length.

Target:
public void setCorrelationId(String correlationId) { this.correlationId = correlationId; }
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(); } START } END we don't assert anywhere that on success cli exits with `0`.

Target:
public void shouldRunQueryFromFile() throws Exception { 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(); } }
Source:
START static <E extends Enum<E>> Optional<Class<?>> ifEnum(Type type) { END return Optional.of(type) .map(GenericTypes::getErasedType) .filter(Class::isEnum) .map(c -> (Class<E>) c); } can / should this be `Optional<Class<E>>`?

Target:
static <E extends Enum<E>> Optional<Class<E>> ifEnum(Type type) { return Optional.of(type) .map(GenericTypes::getErasedType) .filter(Class::isEnum) .map(c -> (Class<E>) c); }
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), START "separator", ThreadLocalRandom.current().nextDouble() > 0.999 ? BEST_SEPARATOR : NORMAL_SEPARATOR)); END } I don't quite following this random separator logic...

Target:
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))); }
Source:
private long roundToNextMinute(long timeInMillis) { Calendar calendar = START new GregorianCalendar(); END calendar.setTimeInMillis(timeInMillis); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MINUTE, 1); return calendar.getTimeInMillis(); } Shouldn't this be Calendar.getInstance() instead ? That way it's truly a no-op.

Target:
private long roundToNextMinute(long timeInMillis) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeInMillis); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MINUTE, 1); return calendar.getTimeInMillis(); }
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) { START assertThat(e).isNotNull(); END } } Redundant assertion

Target:
public void testMapInvalidEnumValue() throws SQLException { Handle h = db.openHandle(); h.createStatement("insert into something (id, name) values (1, 'joe')").execute(); h.createQuery("select * from something order by id") .mapToBean(SomethingElse.class) .findFirst(); }
Source:
START private static void cachePut(final CacheKey key, final boolean value) { END final LRUMap<CacheKey, Boolean> cache = SecuredItemImpl.CACHE.get(); if (cache != null) { cache.put(key, value); SecuredItemImpl.CACHE.set(cache); } } Again, this change modifies the is not semantic meaning.

Target:
private 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); } }
Source:
public void setUp() throws Exception { START testContext = getInstrumentation().getContext(); END } Don't you need a `super.setUp()` call here?

Target:
public void setUp() throws Exception { super.setUp(); testContext = getInstrumentation().getContext(); }
Source:
START private void maybeAddCluster() throws IOException { END 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()); } } } seems there is no IOException thrown from this method.

Target:
private void maybeAddCluster() { 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()); } } }
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: START return R.color.black; END } return context.getResources().getColor(colour); } Any reason for this not assigning `colour` like the rest of the cases, instead of returning?

Target:
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: colour = R.color.black; break; } return context.getResources().getColor(colour); }
Source:
public PotionEffect getPotionEffect() { START return super.getPotionEffect; END } Compile error here @mcenderdragon

Target:
public PotionEffect getPotionEffect() { return super.getPotionEffect(); }
Source:
START public static END 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); } I think this could be protected

Target:
protected 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); }