auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public ChannelWriteController( END ApplicationConfigurationFetcher appConfigFetcher, ChannelStore store, ModelReader reader, ChannelModelTransformer channelTransformer ) { this.appConfigFetcher = checkNotNull(appConfigFetcher); this.store = checkNotNull(store); this.reader = checkNotNull(reader); this.channelTransformer = checkNotNull(channelTransformer); } Constructor should be private. Make a static factory method

Target:
private ChannelWriteController( ApplicationConfigurationFetcher appConfigFetcher, ChannelStore store, ModelReader reader, ChannelModelTransformer channelTransformer ) { this.appConfigFetcher = checkNotNull(appConfigFetcher); this.store = checkNotNull(store); this.reader = checkNotNull(reader); this.channelTransformer = checkNotNull(channelTransformer); }
Source:
public TestGerritClient(TaskRepository repository, AbstractWebLocation location) { super(repository, GerritFixture.current().getGerritVersion()); START System.out.println("Testing against Gerrit " + GerritFixture.current().getGerritVersion()); END initialize(location, null, null, null, null); } replace this file with "previous version" and commit again - it should remove it from this review

Target:
public TestGerritClient(TaskRepository repository, AbstractWebLocation location) { super(repository, GerritFixture.current().getGerritVersion()); initialize(location, null, null, null, null); }
Source:
private String GetLocalStoragesFormattedString() { StringBuilder localStorages = new StringBuilder(""); //$NON-NLS-1$ START for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) END { if (a.getStorageType() == StorageType.LOCALFS) { localStorages.append(a.getStorageName()).append(", "); //$NON-NLS-1$ } } return localStorages.substring(0, localStorages.length() - 2); } The empty string here is redundent

Target:
private String GetLocalStoragesFormattedString() { StringBuilder localStorages = new StringBuilder(); for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) { if (a.getStorageType() == StorageType.LOCALFS) { localStorages.append(a.getStorageName()).append(", "); //$NON-NLS-1$ } } return localStorages.substring(0, localStorages.length() - 2); }
Source:
public void setup() { START generator = new SequentialIdentifierGenerator(); END handler = new SequentialIdentifierGeneratorResourceHandler(); } Why are you setting these from here? Why are they class level variables?

Target:
public void setup() { handler = new SequentialIdentifierGeneratorResourceHandler(); }
Source:
void onChangeRevision(@SuppressWarnings("unused") ChangeEvent e) { int idx = diffBase.getSelectedIndex(); START if (0 <= idx && fileTableMode == FileTable.Mode.REVIEW) { END String n = diffBase.getValue(idx); loadConfigInfo(changeInfo, !n.isEmpty() ? n : null); } } I don't understand how ignoring the UI event when the Diff base popup selects another field in edit mode fixes the linked issue. A more descriptive commit message would help. Is the diffBase widget just supposed to be disabled or invisible in edit mode?

Target:
void onChangeRevision(@SuppressWarnings("unused") ChangeEvent e) { int idx = diffBase.getSelectedIndex(); if (0 <= idx) { String n = diffBase.getValue(idx); loadConfigInfo(changeInfo, !n.isEmpty() ? n : null); } }
Source:
public String getFingerprint(Schema schema) { if (theClient == null) { theClient = initializeClient(); } String subject = schema.getName(); final int guid; try { guid = theClient.register(subject, schema); START System.out.println("GUID: [" + guid + "]"); END } catch (IOException | RestClientException e) { throw new RuntimeException(e); } return Integer.toString(guid); } this should be removed

Target:
public String getFingerprint(Schema schema) { final String subject = schema.getName(); final int guid; try { guid = theClient.register(subject, schema); } catch (IOException | RestClientException e) { throw new RuntimeException(e); } return Integer.toString(guid); }
Source:
private boolean declaringTypeIsLocalOrImported(CtTypeReference declaringType) { if (declaringType != null) { START if (!isTypeInCollision(declaringType, false) && (isImportedInClassImports(declaringType) || classNamePresentInJavaLang(declaringType))) { END return true; } if (!isTypeInCollision(declaringType, false) && addClassImport(declaringType)) { return true; } while (declaringType != null) { if (declaringType.equals(targetType)) { return true; } declaringType = declaringType.getDeclaringType(); } } return false; } Actually I was testing that and trying to import the declaring type just below. So I assume you had a problem somewhere importing a declaring type: the condition below is useless then...

Target:
private boolean declaringTypeIsLocalOrImported(CtTypeReference declaringType) { if (declaringType != null) { if (!isTypeInCollision(declaringType, false) && addClassImport(declaringType)) { return true; } if (isImportedInClassImports(declaringType) || classNamePresentInJavaLang(declaringType)) { return true; } while (declaringType != null) { if (declaringType.equals(targetType)) { return true; } declaringType = declaringType.getDeclaringType(); } } return false; }
Source:
MkNotifications(final int quantity) { this.notifications = new ArrayList<Notification>(quantity); START for (int index = 0; index < quantity; index += 1) { END this.notifications.add(index, new MkNotification(index)); } } @prondzyn `++ index`

Target:
MkNotifications(final int quantity) { this.notifications = new ArrayList<Notification>(quantity); for (int index = 0; index < quantity; ++index) { this.notifications.add(index, new MkNotification(index)); } }
Source:
START @Override public String setCity(String city) { END return city; } The left side should be the preferred style (annotations in an extra line).

Target:
public String setCity(String city) { return city; }
Source:
private static SSLFactory getSSLFactoryIfRequired(VerifiableProperties verifiableProperties) START throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, END IllegalAccessException { boolean sslRequired = new NettyConfig(verifiableProperties).nettyServerEnableSSL || new ClusterMapConfig(verifiableProperties).clusterMapSslEnabledDatacenters.length() > 0; return sslRequired? SSLFactory.getNewInstance(new SSLConfig(verifiableProperties)) : null; } `throws Exception`

Target:
private static SSLFactory getSSLFactoryIfRequired(VerifiableProperties verifiableProperties) throws Exception { boolean sslRequired = new NettyConfig(verifiableProperties).nettyServerEnableSSL || new ClusterMapConfig(verifiableProperties).clusterMapSslEnabledDatacenters.length() > 0; return sslRequired ? SSLFactory.getNewInstance(new SSLConfig(verifiableProperties)) : null; }
Source:
public T LIMIT(int value) { sql().limit = String.valueOf(value); sql().limitingRowsStrategy = SQLStatement.LimitingRowsStrategy.OFFSET_LIMIT; START return getSelf(); END } The newly added line makes me think about DRY for some reason. :D How about... ```java return LIMIT(String.valueOf(value)); ```

Target:
public T LIMIT(int value) { return LIMIT(String.valueOf(value)); }
Source:
START @Override public void testSiteBuildWithForkedMojo() throws Exception { END // TODO currently failing, apparently from NPE in DefaultDependencyGraphBuilder.canFindCoreClass after failing to resolve an artifact from the test project } Please follow existed coding style and put new line after Override

Target:
public void testSiteBuildWithForkedMojo() throws Exception { // TODO currently failing, apparently from NPE in DefaultDependencyGraphBuilder.canFindCoreClass after failing to resolve an artifact from the test project }
Source:
boolean spends(Transaction txA, Transaction txB) { boolean spends = false; for (TransactionInput txInput : txA.getInputs()) { START spends |= txInput.getOutpoint().getHash().equals(txB.getHash()); END } return spends; } This can just be "if (txInput.....) return true" right? No need to continue looping after finding that the condition is correct.

Target:
boolean spends(Transaction txA, Transaction txB) { for (TransactionInput txInput : txA.getInputs()) { if (txInput.getOutpoint().getHash().equals(txB.getHash())) { return true; } } return false; }
Source:
public void setup() START throws Exception { END sslFactory = TestUtils.createSSLFactory(); SSLContext sslContext = sslFactory.createSSLContext(); sslSocketFactory = sslContext.getSocketFactory(); sslEchoServer = new SSLBlockingEchoServer(sslFactory, sslPort); sslEchoServer.start(); } new echo server for every test or will a single one for all tests suffice? If a single one will suffice, then you could declare all variables used here as static and turn these two functions into @BeforeClass and @AfterClass

Target:
public void setup() throws Exception { }
Source:
public boolean isFinished() { START checkState(initialized.get(), "Driver is not initialized"); END checkLockNotHeld("Can not check finished status while holding the driver lock"); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown Optional<Boolean> result = tryWithLock(this::isFinishedInternal); return result.orElseGet(() -> state.get() != State.ALIVE || driverContext.isDone()); } not needed in this method?

Target:
public boolean isFinished() { checkLockNotHeld("Can not check finished status while holding the driver lock"); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown Optional<Boolean> result = tryWithLock(this::isFinishedInternal); return result.orElseGet(() -> state.get() != State.ALIVE || driverContext.isDone()); }
Source:
START public Node(String address, String logPath) { END this.address = address; this.logPath = logPath; this.shutdown = new ShutdownAction(this); this.start = new StartAction(this); } There is a 3 param constructor, we can call this to reduce code rep..

Target:
public Node(String address, String logPath) { this(address, null, logPath); }
Source:
private double cumulativeProbability(double x) { try { NormalDistribution normDist = new NormalDistribution(); return normDist.cumulativeProbability(x); START } catch (Exception ex) { END return Double.NaN; } } What kind of Exception can be thrown here? Could this be made more specific? Also, is it possible to use some other mechanism of detecting whatever problem this exception is detecting? Exceptions are quite slow compared to other forms of flow control and so I'm concerned about using them in a post-aggregator `compute` function.

Target:
private double cumulativeProbability(double x) { try { NormalDistribution normDist = new NormalDistribution(); return normDist.cumulativeProbability(x); } catch (IllegalArgumentException ex) { return Double.NaN; } }
Source:
public Response afterLRA(@HeaderParam(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) URI endedLRAId) { START if (afterLRACounter.getAndIncrement() < 2) { END return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.ok().build(); } Actually I see the code may well apply if the scan is in progress

Target:
public Response afterLRA(@HeaderParam(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) URI endedLRAId) { if (afterLRACounter.getAndIncrement() < 1) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.ok().build(); }
Source:
public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException { START OpenmrsUtil.validatePassword(user.getUsername(), hashedPassword, user.getSystemId()); END dao.changeHashedPassword(user, hashedPassword, salt); } Does this really work? That validate method i think expects non hashed passwords, probably you shouldn't validate this, the ticket says changePassword methods. I also think these should delegate to the changePassword method that validates the password to centralize the code

Target:
public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException { dao.changeHashedPassword(user, hashedPassword, salt); }
Source:
public void updateSystemMemoryUsage(long deltaMemoryInBytes) { if (taskContext == null) { START Optional<TaskContext> taskContext = queryContext.getTaskContextByTaskId(taskId); END verify(taskContext.isPresent(), "task does not exist"); this.taskContext = taskContext.get(); } if (deltaMemoryInBytes > 0) { taskContext.reserveSystemMemory(deltaMemoryInBytes); } else { taskContext.freeSystemMemory(-deltaMemoryInBytes); } } Consider adding `queryContext.getRequiredTaskContext(taskId)` to do this in one shot without the `Optional`

Target:
public void updateSystemMemoryUsage(long deltaMemoryInBytes) { if (taskContext == null) { taskContext = queryContext.getTaskContextByTaskId(taskId); } if (deltaMemoryInBytes > 0) { taskContext.reserveSystemMemory(deltaMemoryInBytes); } else { taskContext.freeSystemMemory(-deltaMemoryInBytes); } }
Source:
public void testAllOutputsReferenced() throws Exception { tester().assertThat(new PruneAggregationColumns()) START .on(p -> buildProjectedAggregation(p, Predicates.alwaysTrue())) END .doesNotFire(); } static import

Target:
public void testAllOutputsReferenced() throws Exception { tester().assertThat(new PruneAggregationColumns()) .on(p -> buildProjectedAggregation(p, alwaysTrue())) .doesNotFire(); }
Source:
START public void setSessionRollbackCount(int count) { END sessionRollbackCount = count; } synchronized

Target:
public synchronized void setSessionRollbackCount(int count) { sessionRollbackCount = count; }
Source:
public PermissionTypeColumn() { START makeSortable(Comparator.comparing(p -> !resources.userImage().equals(p))); END } This doesn't seem aligned with the original implementation

Target:
public PermissionTypeColumn() { makeSortable(Comparator.comparing(p -> !resources.userImage().equals(getValue(p)))); }
Source:
private boolean hasSameSeparateDerivedEncodings() { START return (separateDerivedEncodingsButton == null) END || (separateDerivedEncodingsButton.getSelection() == getStoredSeparateDerivedEncodingsValue()); } we can also get rid of the parenthesis by the way.

Target:
private boolean hasSameSeparateDerivedEncodings() { return separateDerivedEncodingsButton == null || separateDerivedEncodingsButton.getSelection() == getStoredSeparateDerivedEncodingsValue(); }
Source:
START void setMetric(Object metric) { END this.metric = metric; } not synchronized?

Target:
synchronized void setMetric(Object metric) { this.metric = metric; }
Source:
START public ProgramState stackValue(SymbolicValue sv) { END Deque<SymbolicValue> newStack = new LinkedList<>(stack); newStack.push(sv); return new ProgramState(this, newStack); } Why public ?

Target:
ProgramState stackValue(SymbolicValue sv) { Deque<SymbolicValue> newStack = new LinkedList<>(stack); newStack.push(sv); return new ProgramState(this, newStack); }
Source:
private CertificateDTO addCertByChild(List<CertificateDTO> toList, List<CertificateDTO> fromList, CertificateDTO child){ if (null != child && CollectionUtils.isNotEmpty(fromList)) { for(CertificateDTO cert : fromList){ START if(child.getAuthorityKeyID().compareTo(cert.getSubjectKeyID())==0){ END toList.add(cert); fromList.remove(cert); return cert; } } } return null; } Can we use .equals() instead of .compareTo?

Target:
private CertificateDTO addCertByChild(List<CertificateDTO> toList, List<CertificateDTO> fromList, CertificateDTO child){ if (null != child && CollectionUtils.isNotEmpty(fromList)) { for(CertificateDTO cert : fromList){ if (child.getAuthorityKeyID().equals(cert.getSubjectKeyID())) { toList.add(0, cert); fromList.remove(cert); return cert; } } } return null; }
Source:
START private void analyzeClass(final byte[] source) { END final long classId = CRC64.classId(source); final int version = BytecodeVersion.read(source); final byte[] b = BytecodeVersion.downgradeIfNeeded(version, source); final ClassReader reader = new ClassReader(b); final ClassVisitor visitor = createAnalyzingVisitor(classId, reader.getClassName()); reader.accept(visitor, 0); } Move this private method below the public analyze* methods?

Target:
private void analyzeClass(final byte[] source) { final long classId = CRC64.classId(source); final int version = BytecodeVersion.get(source); final byte[] b = BytecodeVersion.downgradeIfNeeded(version, source); final ClassReader reader = new ClassReader(b); final ClassVisitor visitor = createAnalyzingVisitor(classId, reader.getClassName()); reader.accept(visitor, 0); }
Source:
public void close() throws ItemStreamException { if (!ignoreItemStream && delegate instanceof ItemStream) { ((ItemStream) delegate).close(); } START } END Removing the configuration option above simplifies all three of these methods.

Target:
public void close() throws ItemStreamException { if (delegate instanceof ItemStream) { ((ItemStream) delegate).close(); } }
Source:
public FileMode getMode(File f, FS.Attributes attributes) { START if (attributes.isSymbolicLink()) END return FileMode.SYMLINK; else if (attributes.isDirectory()) { return FileMode.TREE; } else if (attributes.isExecutable()) return FileMode.EXECUTABLE_FILE; else return FileMode.REGULAR_FILE; } style nit: missing braces

Target:
public FileMode getMode(File f, FS.Attributes attributes) { if (attributes.isSymbolicLink()) { return FileMode.SYMLINK; } else if (attributes.isDirectory()) { return FileMode.TREE; } else if (attributes.isExecutable()) { return FileMode.EXECUTABLE_FILE; } else { return FileMode.REGULAR_FILE; } }
Source:
protected UserException typeConversionError(ColumnMetadata schema, ValueDef valueDef) { String type = valueDef.type().name().toLowerCase(); if (valueDef.isArray()) { for (int i = 0; i < valueDef.dimensions(); i++) { START type += "[]"; END } } return typeConversionError(schema, type); } Please use StringBuilder.

Target:
protected UserException typeConversionError(ColumnMetadata schema, ValueDef valueDef) { StringBuilder buf = new StringBuilder() .append(valueDef.type().name().toLowerCase()); if (valueDef.isArray()) { for (int i = 0; i < valueDef.dimensions(); i++) { buf.append("[]"); } } return typeConversionError(schema, buf.toString()); }
Source:
public void testStructWithNull() throws Exception { runTest( "test_flat_map/flat_map_struct_with_null.dwrf", INTEGER, STRUCT_TYPE, START ExpectedValuesBuilder.get(Function.identity(), TestMapFlatSelectiveStreamReader::intToList).setNullValuesFrequency(TestMapFlatSelectiveStreamReader.ExpectedValuesBuilder.Frequency.SOME)); END } static import TestMapFlatSelectiveStreamReader.ExpectedValuesBuilder.Frequency.SOME

Target:
public void testStructWithNull() throws Exception { runTest( "test_flat_map/flat_map_struct_with_null.dwrf", INTEGER, STRUCT_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatSelectiveStreamReader::intToList).setNullValuesFrequency(SOME)); }
Source:
protected void refreshVisuals() { Connector connector = (Connector) getNotationView(); START NamedStyle namedStyle = connector.getNamedStyle(NotationPackage.Literals.INT_VALUE_STYLE, "delta"); END if (namedStyle instanceof IntValueStyle) { refreshArrowDelta((IntValueStyle) namedStyle); } else { // no style - reset value ((DurationLinkFigure) getFigure()).setArrowPositionDelta(0); } super.refreshVisuals(); } As a convention, it is typically the responsibility of the refreshSomething() method to extract the style and change the figure. #refreshVisuals() typically calls all #refreshSomething() methods, then each method reads its own style from the notation, and calls #setSomething() on the Figure Also, #refreshSomething() methods are usually protected, so subclasses may adapt the behavior, without having to install their own listeners (Although in that case, I doubt we'll ever have to override the DurationLink EditParts)

Target:
protected void refreshVisuals() { refreshArrowDelta(); super.refreshVisuals(); }
Source:
@Override public void changeKey(@Nullable State outgoingState, State incomingState, Flow.Direction direction, Context incomingStateContext, Flow.TraversalCallback callback) { if (textView == null) { textView = new TextView(activity); textView.setGravity(Gravity.CENTER); } textView.setText(incomingState.getKey().toString()); START activity.setContentView(textView); END callback.onTraversalCompleted(); } Weird that you're calling setContentView over and over again.

Target:
@Override public void changeKey(@Nullable State outgoingState, State incomingState, Flow.Direction direction, Context incomingStateContext, Flow.TraversalCallback callback) { if (textView == null) { textView = new TextView(activity); textView.setGravity(Gravity.CENTER); activity.setContentView(textView); } textView.setText(incomingState.getKey().toString()); callback.onTraversalCompleted(); }
Source:
public String toHex(DiscreteElement<?> element) { START return ""; END } Should return the same value it would have returned had it not called toHex

Target:
public String toHex(DiscreteElement<?> element) { return element.getValue().toString(); }
Source:
public TestNGTestListener() { START EnvironmentCheck.checkJVMVersion(); END progressLogger = new TestSuiteProgress(); } For TestNG modules we can throw an exception in `TestNGSuiteChecksTest.beforeSuite()` instead of calling `System.exit()`

Target:
public TestNGTestListener() { progressLogger = new TestSuiteProgress(); }
Source:
START void setTo( String to ) { END if ( to != null && !"".equals( to ) ) { to = to.replaceAll( ";", "," ); props.put( "to", to ); } } @cravobranco, `removing` the public access modifier makes these methods invisible outside of the package and will break code using these methods from other packages. Please update the PR with the `public` access modifier. See: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Target:
public void setTo( String to ) { if ( to != null && !"".equals( to ) ) { to = to.replaceAll( ";", "," ); props.put( "to", to ); } }
Source:
START private void prepareMockFileUrls() throws URISyntaxException { END when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE)).thenReturn(new URI(SOURCE_VERSION_URL)); when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE2)).thenReturn(new URI(SOURCE_VERSION_URL_FILE2)); } I wonder why this method is not final while the others similar to it are. What is the reason for having final methods here?

Target:
private final void prepareMockFileUrls() throws URISyntaxException { when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE)).thenReturn(new URI(SOURCE_VERSION_URL)); when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE2)).thenReturn(new URI(SOURCE_VERSION_URL_FILE2)); }
Source:
public IStatus validate(Object[] selection) { String errorMessage = ""; //$NON-NLS-1$ START if (selection.length == 0) { END errorMessage = NO_SELECTION; } else { final Object firstSelection = selection[0]; if (selection.length != 1 || false == firstSelection instanceof Property || (firstSelection instanceof Property && false == ((Property) firstSelection).getType() instanceof PrimitiveType)) { errorMessage = Messages.SinglePropertyAttributeValidator_errorMessage; } } return buildIStatus(errorMessage); } Just notice: It's preferable to manage the comparison '<=' instead of '=='

Target:
public IStatus validate(Object[] selection) { String errorMessage = ""; //$NON-NLS-1$ if (selection.length <= 0) { errorMessage = NO_SELECTION; } else { final Object firstSelection = selection[0]; if (selection.length != 1 || false == firstSelection instanceof Property || (firstSelection instanceof Property && false == ((Property) firstSelection).getType() instanceof PrimitiveType)) { errorMessage = Messages.SinglePropertyAttributeValidator_errorMessage; } } return buildIStatus(errorMessage); }
Source:
public boolean isItemValidForSlot(int slot, ItemStack stack) { if (slot == SLOT_INPUT) { boolean b1 = FluidItemHelper.isContainer(stack); boolean b2 = FluidItemHelper.isEmptyContainer(stack); FluidStack filter = getFilterFluid(); boolean b3 = filter == null; boolean b4 = FluidItemHelper.containsFluid(stack, filter); START return b1 && (b2 || b3 || b4); END } return false; } This is less efficient because it looses the short circuit property of Boolean logic.

Target:
public boolean isItemValidForSlot(int slot, ItemStack stack) { if (slot == SLOT_INPUT) { if (!FluidItemHelper.isContainer(stack)) return false; if (FluidItemHelper.isEmptyContainer(stack)) return true; FluidStack filter = getFilterFluid(); return filter == null || FluidItemHelper.containsFluid(stack, filter); } return false; }
Source:
public MigratableTableTranslation<DBOColumnModel, DBOColumnModel> getTranslator() { return new BasicMigratableTableTranslation<DBOColumnModel>(){ @TemporaryCode(author="ziming", comment = "one-time migration change. remove after stack 309") @Override public DBOColumnModel createDatabaseObjectFromBackup(DBOColumnModel backup) { //doing this round trip will assign default value to maxListLength START ColumnModel columnModel = ColumnModelUtils.createDTOFromDBO(backup); END if(ColumnTypeListMappings.isList(columnModel.getColumnType())){ columnModel.setMaximumListLength(ColumnConstants.MAX_ALLOWED_LIST_LENGTH); } DBOColumnModel modifiedDBO = ColumnModelUtils.createDBOFromDTO(columnModel, StackConfigurationSingleton.singleton().getTableMaxEnumValues()); return modifiedDBO; } }; } let ColumnModelUtils.createDTOFromDBO(backup); handle the set to default (not setting it here)

Target:
public MigratableTableTranslation<DBOColumnModel, DBOColumnModel> getTranslator() { return new BasicMigratableTableTranslation<DBOColumnModel>(){ @TemporaryCode(author="ziming", comment = "one-time migration change. remove after stack 309") @Override public DBOColumnModel createDatabaseObjectFromBackup(DBOColumnModel backup) { //doing this round trip will assign default value to maxListLength ColumnModel columnModel = ColumnModelUtils.createDTOFromDBO(backup); DBOColumnModel modifiedDBO = ColumnModelUtils.createDBOFromDTO(columnModel, StackConfigurationSingleton.singleton().getTableMaxEnumValues()); return modifiedDBO; } }; }
Source:
private void openProposalPopupAsync() { START getControl().getDisplay().asyncExec(new Runnable() { @Override public void run() END { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } } }); } use lambda instead private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(() -> { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } }); }

Target:
private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(() -> { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } }); }
Source:
private static boolean performImportWithoutUI(VirtualFile importSource, Project destinationProject) throws IOException { for (ModuleImporter importer : ModuleImporter.getAllImporters(destinationProject)) { if (importer.canImport(importSource)) { START HashMap<String, VirtualFile> modules = Maps.newHashMap(); END for (ModuleToImport module : importer.findModules(importSource)) { modules.put(module.name, module.location); } importer.importProjects(modules); return true; } } return false; } nit - use Map instead of HashMap on left hand side

Target:
private static boolean performImportWithoutUI(VirtualFile importSource, Project destinationProject) throws IOException { for (ModuleImporter importer : ModuleImporter.getAllImporters(destinationProject)) { if (importer.canImport(importSource)) { Map<String, VirtualFile> modules = Maps.newHashMap(); for (ModuleToImport module : importer.findModules(importSource)) { modules.put(module.name, module.location); } importer.importProjects(modules); return true; } } return false; }
Source:
public static InputStream getContactPhotoStream(ContentResolver contentResolver, Uri uri) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { final Uri contactUri = uri.toString().startsWith( ContactsContract.Contacts.CONTENT_LOOKUP_URI.toString()) ? ContactsContract.Contacts.lookupContact(contentResolver, uri) START : uri; END return openContactPhotoInputStream(contentResolver, contactUri); } else { return ContactPhotoStreamIcs.get(contentResolver, uri); } } I would rather this be something like: ``` java if (uri.toString().startsWith(Contacts.CONTENT_LOOKUP_URI.toString()) { uri = Contacts.lookupContact(contentResolver, uri); } ``` to avoid the unnecessary assignment when the `Uri` does not match.

Target:
public static InputStream getContactPhotoStream(ContentResolver contentResolver, Uri uri) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (uri.toString().startsWith(ContactsContract.Contacts.CONTENT_LOOKUP_URI.toString())) uri = ContactsContract.Contacts.lookupContact(contentResolver, uri); return openContactPhotoInputStream(contentResolver, uri); } else { return ContactPhotoStreamIcs.get(contentResolver, uri); } }
Source:
public Collection<String> getReviewUrls(String taskUrl) { START List<String> reviewUrls = taskReviewsMap.get(taskUrl); END if (reviewUrls == null) { return Collections.emptyList(); } return reviewUrls; } Multimap never returns null, so we could get rid of this method.

Target:
public Collection<String> getReviewUrls(String taskUrl) { return taskReviewsMap.get(taskUrl); }
Source:
private void showResource(final IResource resource) { IProject project = resource.getProject(); RepositoryMapping mapping = RepositoryMapping.getMapping(project); if (mapping == null) return; Repository newRep = mapping.getRepositoryOrNestedSubmoduleRepository(resource); if (newRep != currentRepository) START { END reload(newRep); } } style nit: we don't use braces around single line blocks

Target:
private void showResource(final IResource resource) { Repository newRep = getRepositoryOrNestedSubmoduleRepository(resource); if (newRep != null && newRep != currentRepository) { reload(newRep); } }
Source:
public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); START ent.setLength(1); END ent.setObjectId(data); } a length of 1? That's wrong in most cases, or?

Target:
public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); ent.setLength(length); ent.setObjectId(data); }
Source:
private List<Action> handleChangesCanceled(Session session, Resource resource, ResourceStatus newStatus) { final List<Action> actions = Lists.newArrayList(); actions.add(Action.RELOAD); START return actions; END } Would be simpler as: return Arrays.asList(Action.RELOAD);

Target:
private List<Action> handleChangesCanceled(Session session, Resource resource, ResourceStatus newStatus) { return Arrays.asList(Action.RELOAD); }
Source:
START public LocalDateTime toLocalDateTimeBin(TimeZone tz, byte[] bytes) throws PSQLException { END ParsedBinaryTimestamp parsedTimestamp = this.toParsedTimestampBin(null, bytes, true); if (parsedTimestamp.infinity == Infinity.POSITIVE) { return LocalDateTime.MAX; } else if (parsedTimestamp.infinity == Infinity.NEGATIVE) { return LocalDateTime.MAX; } return LocalDateTime.ofEpochSecond(parsedTimestamp.millis / 1000L, parsedTimestamp.nanos, ZoneOffset.UTC); } Is this change required?

Target:
public LocalDateTime toLocalDateTimeBin(TimeZone tz, byte[] bytes) throws PSQLException { ParsedBinaryTimestamp parsedTimestamp = this.toParsedTimestampBin(tz, bytes, true); if (parsedTimestamp.infinity == Infinity.POSITIVE) { return LocalDateTime.MAX; } else if (parsedTimestamp.infinity == Infinity.NEGATIVE) { return LocalDateTime.MAX; } return LocalDateTime.ofEpochSecond(parsedTimestamp.millis / 1000L, parsedTimestamp.nanos, ZoneOffset.UTC); }
Source:
void hideCurrentToolTip () { START checkWidget (); END if (this.selectedMenuItem != null) { selectedMenuItem.hideToolTip (); } } For non-public methods checkWidget() is not required.

Target:
void hideCurrentToolTip () { if (this.selectedMenuItem != null) { selectedMenuItem.hideToolTip (); } }
Source:
public void installEdition(Set<String> pluginKeys) { Optional<UpdateCenter> updateCenter = updateCenterMatrixFactory.getUpdateCenter(true); START Set<Release> pluginsToInstall = new HashSet<>(); END if (updateCenter.isPresent()) { for (String pluginKey : pluginKeys) { pluginsToInstall.addAll(updateCenter.get().findInstallablePlugins(pluginKey, Version.create(""))); } } pluginsToInstall.forEach(super::download); } no need to create this Set when updateCenter is not present

Target:
public void installEdition(Set<String> pluginKeys) { Optional<UpdateCenter> updateCenter = updateCenterMatrixFactory.getUpdateCenter(true); if (updateCenter.isPresent()) { Set<Release> pluginsToInstall = new HashSet<>(); for (String pluginKey : pluginKeys) { pluginsToInstall.addAll(updateCenter.get().findInstallablePlugins(pluginKey, Version.create(""))); } for (Release r : pluginsToInstall) { super.download(r); } } }
Source:
public boolean isApplicable(String requestPath) { START List<String> applicablePaths = ImmutableList.of("druid/coordinator/v1/security/"); END for (String path : applicablePaths) { if (requestPath.startsWith(path) && !requestPath.equals(path)) { return true; } } return false; } Looks that the list isn't needed.

Target:
public boolean isApplicable(String requestPath) { for (String path : applicablePaths) { if (requestPath.startsWith(path) && !requestPath.equals(path)) { return true; } } return false; }
Source:
public void execute(Runnable command) { final Runnable runnable = doWrap(command, controlPoint); try { super.execute(doIdentityWrap(runnable)); START } catch (RejectedExecutionException e) { END controlPoint.requestComplete(); throw e; } } should be catching Exception here too

Target:
public void execute(Runnable command) { final Runnable runnable = doWrap(command, controlPoint); try { super.execute(doIdentityWrap(runnable)); } catch (Exception e) { controlPoint.requestComplete(); throw e; } }
Source:
public void shouldFormatUniquenessConstraints() { START final int[] propertyKeyIds = new int[]{42}; END assertEquals( "new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, 42 ) )", formatArgument( new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, propertyKeyIds ) ) ) ); } not needed

Target:
public void shouldFormatUniquenessConstraints() { assertEquals( "new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, 42 ) )", formatArgument( new UniquenessConstraint( SchemaDescriptorFactory.forLabel( 23, 42 ) ) ) ); }
Source:
private void launchUserBrickScriptActivity(Context context, UserBrick userBrick) { START ((ScriptActivity) context).removeFormulaEditorFragment(); END Intent intent = new Intent(context, UserBrickScriptActivity.class); ProjectManager.getInstance().setCurrentUserBrick(userBrick); context.startActivity(intent); } can we be sure that context is a ScriptActivity?

Target:
private void launchUserBrickScriptActivity(Context context, UserBrick userBrick) { if (context instanceof ScriptActivity) { ((ScriptActivity) context).removeFormulaEditorFragment(); } Intent intent = new Intent(context, UserBrickScriptActivity.class); ProjectManager.getInstance().setCurrentUserBrick(userBrick); context.startActivity(intent); }
Source:
protected void revertTask() { getEnclosingCommand().getParameters().getDiskImage().setImageStatus(ImageStatus.ILLEGAL); ImagesHandler.updateImageStatus( START getEnclosingCommand().getParameters().getDestinationImageId(), ImageStatus.ILLEGAL); END } please perform the update explicitly on the image that you modified in the line before (add .getId)

Target:
protected void revertTask() { // nothing to do }
Source:
public void checkIPAdress() { Set<ConstraintViolation<VmNic>> validate = validator.validate(createVmNic(), groups); assertEquals(validMacAddress, validate.isEmpty()); if (validMacAddress) { assertTrue(validate.isEmpty()); } else { assertEquals(1, validate.size()); START assertTrue(validate.iterator().next().getMessage().equals(message)); END } } why not use assertEquals as well ?

Target:
public void checkIPAdress() { Set<ConstraintViolation<VmNic>> validate = validator.validate(createVmNic(), groups); assertEquals(validMacAddress, validate.isEmpty()); if (validMacAddress) { assertTrue(validate.isEmpty()); } else { assertEquals(1, validate.size()); assertEquals(message, validate.iterator().next().getMessage()); } }
Source:
public State advance() throws IOException { mCheckpointStream = null; mNextEntry = null; while (true) { updateInputStream(); if (mCheckpointStream != null) { return State.CHECKPOINT; } advanceEntry(); if (mNextEntry != null) { return State.LOG; } START if (mInputStream == null || mInputStream.isDone() || mInputStream.mFile.isIncompleteLog()) { END return State.DONE; } } } if `mNextEntry` is `null`, will this if statement always evaluate to `true`? If not, then it would just loop again, and what would happen?

Target:
public State advance() throws IOException { mCheckpointStream = null; mNextEntry = null; updateInputStream(); if (mCheckpointStream != null) { return State.CHECKPOINT; } advanceEntry(); if (mNextEntry != null) { return State.LOG; } return State.DONE; }
Source:
public boolean hasNext() { if (saveNext != null) { return true; } try { saveNext = internalNext(); return true; } catch (NoSuchElementException e) { START return false; END } } This is not a good convention. How about changing `internalNext()` to be able to return null to indicate there's no more elements?

Target:
public boolean hasNext() { if (saveNext != null) { return true; } saveNext = internalNext(); return (saveNext != null); }
Source:
public void process(IProgressMonitor monitor) throws CoreException { if (monitor == null) START monitor = new NullProgressMonitor(); END SubMonitor subMonitor = SubMonitor.convert(monitor, "Searching unused members", this.units.length); //$NON-NLS-1$ for (ICompilationUnit unit : this.units) { doSearchCU(unit, subMonitor.newChild(1)); } } This can be removed. The SubMonitor itself can handle null

Target:
public void process(IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, "Searching unused members", this.units.length); //$NON-NLS-1$ for (ICompilationUnit unit : this.units) { doSearchCU(unit, subMonitor.split(1)); } }
Source:
public void teardownTest() throws InterruptedException { sharedStorageApi().delete(currentSharedStorage.id()); START assertNodeAvailable(currentServer); END deleteServer(currentServer.id()); } Does it make sense to try to delete the server even if the shared storage delete operation failed? We should try to avoid leaking resources.

Target:
public void teardownTest() { sharedStorageApi().delete(currentSharedStorage.id()); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }
Source:
public BenchmarkSuiteConfig setSuite(String suite) { START if (suite != null) { this.suite = suite; } END return this; } This is unnecessary

Target:
public BenchmarkSuiteConfig setSuite(String suite) { this.suite = suite; return this; }
Source:
START private boolean isCloseable(Type type) { END return type.isSubtypeOf(JAVA_IO_AUTO_CLOSEABLE) || type.isSubtypeOf(JAVA_IO_CLOSEABLE); } I'm not sure you need to remove all of these `static` modifiers. Some of them are probably still valid (this one notably)

Target:
private static boolean isCloseable(Type type) { return type.isSubtypeOf(JAVA_IO_AUTO_CLOSEABLE) || type.isSubtypeOf(JAVA_IO_CLOSEABLE); }
Source:
START public synchronized CryptoService getCryptoService() { END if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } return cryptoService; } not sure if this needs to be synchronized

Target:
public CryptoService getCryptoService() { if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } return cryptoService; }
Source:
START public Segment(String path, String etag, long sizeBytes) { END this.path = checkNotNull(path, "path"); this.etag = checkNotNull(etag, "etag of %s", path); this.sizeBytes = sizeBytes; } @archupsg03 I think we can remove this change?

Target:
private Segment(String path, String etag, long sizeBytes) { this.path = checkNotNull(path, "path"); this.etag = checkNotNull(etag, "etag of %s", path); this.sizeBytes = sizeBytes; }
Source:
public START double @NonNull getXAxis() END { return fXValues; } @NonNull double[] ?

Target:
public double[] getXAxis() { return fXValues; }
Source:
START public void eachNonZeroInColumn(int j, MatrixProcedure procedure) { END int k = columnPointers[j], i = rowIndices[k]; while (i < columnPointers[j+1]) { procedure.apply(rowIndices[i],j,values[i]); i++; } } What about having a simple `for` loop here. Like: ``` java for (int i = columnPointers[k]; i < columnPointers[j + 1]; i++) { procedure.apply(rowIndices[i], j, values[i]); } ``` There is something wrong with your code. First, `i = rowIndicies[k]`. And then you're getting row by `rowIndicies[i]`. This is strange. I guarantee it will fail tests.

Target:
public void eachNonZeroInColumn(int j, MatrixProcedure procedure) { for (int i = columnPointers[j]; i < columnPointers[j + 1]; i++) { procedure.apply(rowIndices[i], j, values[i]); } }
Source:
public ApiAuthenticationResult authenticate(HttpRequest httpRequest) { Assert.notNull(httpRequest, "httpRequest argument cannot be null."); if (ServletHttpRequest.class.isAssignableFrom(httpRequest.getClass())){ START this.httpRequest = (ServletHttpRequest) httpRequest; END } else { Assert.isInstanceOf(HttpRequest.class, httpRequest, "The specified httpRequest argument must be an instance of " + HttpRequest.class.getName() + " or " + ServletHttpRequest.class.getName()); this.httpRequest = httpRequest; } return this.execute(); } wrong casting

Target:
public ApiAuthenticationResult authenticate(HttpRequest httpRequest) { Assert.notNull(httpRequest, "httpRequest argument cannot be null."); if (ServletHttpRequest.class.isAssignableFrom(httpRequest.getClass())){ this.httpRequest = httpRequest; } else { Assert.isInstanceOf(HttpRequest.class, httpRequest, "The specified httpRequest argument must be an instance of " + HttpRequest.class.getName() + " or " + ServletHttpRequest.class.getName()); this.httpRequest = httpRequest; } return this.execute(); }
Source:
public static Mode fromString(String inStr) { if (inStr == null || inStr.isEmpty()) { throw new IllegalArgumentException("String representation of MultiAuthenticator.Mode can not be null nor empty."); } inStr = inStr.toLowerCase(); START if (inStr.equals("any")){ END return ANY; } if (inStr.equals("all") || inStr.equals("every")){ return ALL; } throw new IllegalArgumentException("Unknown string representation [" + inStr + "] for MultiAuthenticator.Mode"); } could be also just `.equalsIgnoreCase()`

Target:
public static Mode fromString(String inStr) { if (inStr == null || inStr.isEmpty()) { throw new IllegalArgumentException("String representation of MultiAuthenticator.Mode can not be null nor empty."); } if (inStr.equalsIgnoreCase("any")){ return ANY; } if (inStr.equalsIgnoreCase("all")){ return ALL; } throw new IllegalArgumentException("Unknown string representation [" + inStr + "] for MultiAuthenticator.Mode"); }
Source:
protected CoverageAgendaListener createCoverageAgendaListenerWithData(Map<String, Integer> rulesToNumberOfTimes) { CoverageAgendaListener coverageAgendaListener = new CoverageAgendaListener(); for (Map.Entry<String, Integer> ruleToNumberOfTimes : rulesToNumberOfTimes.entrySet()) { BeforeMatchFiredEvent beforeMatchFiredEventMock = createBeforeMatchFiredEventMock(ruleToNumberOfTimes.getKey()); IntStream.range(0, ruleToNumberOfTimes.getValue()).forEach(i -> coverageAgendaListener.beforeMatchFired(beforeMatchFiredEventMock)); } START ; END return coverageAgendaListener; } Typo?

Target:
protected CoverageAgendaListener createCoverageAgendaListenerWithData(Map<String, Integer> rulesToNumberOfTimes) { CoverageAgendaListener coverageAgendaListener = new CoverageAgendaListener(); for (Map.Entry<String, Integer> ruleToNumberOfTimes : rulesToNumberOfTimes.entrySet()) { BeforeMatchFiredEvent beforeMatchFiredEventMock = createBeforeMatchFiredEventMock(ruleToNumberOfTimes.getKey()); IntStream.range(0, ruleToNumberOfTimes.getValue()).forEach(i -> coverageAgendaListener.beforeMatchFired(beforeMatchFiredEventMock)); } return coverageAgendaListener; }
Source:
private void startListFragment(byte[] bytes, Uri dataUri, String serverQuery, Preferences.CloudSearchPrefs cloudSearchPrefs) { Fragment listFragment = ImportKeysListFragment.newInstance(bytes, dataUri, serverQuery, false, cloudSearchPrefs); getSupportFragmentManager().beginTransaction() .replace(R.id.import_keys_list_container, listFragment, TAG_FRAG_LIST) START .commitAllowingStateLoss(); END // we commitAllowingStateLoss for when the Activity is already started but an Intent is // received and to be rendered } I'm really not a fan of `commitAllowingStateLoss`, and the general android advice is to use it as a last resort only. see above on handling `onNewIntent`.

Target:
private void startListFragment(byte[] bytes, Uri dataUri, String serverQuery, Preferences.CloudSearchPrefs cloudSearchPrefs) { Fragment listFragment = ImportKeysListFragment.newInstance(bytes, dataUri, serverQuery, false, cloudSearchPrefs); getSupportFragmentManager().beginTransaction() .replace(R.id.import_keys_list_container, listFragment, TAG_FRAG_LIST) .commit(); }
Source:
public Webhook(String componentUuid, @Nullable String ceTaskUuid, @Nullable String analysisUuid, String name, String url) { this.componentUuid = requireNonNull(componentUuid); this.ceTaskUuid = ceTaskUuid; START this.analysisUuid = requireNonNull(analysisUuid); END this.name = requireNonNull(name); this.url = requireNonNull(url); } :warning: `requireNonNull` on a nullable argument highlights that a UT is missing (could be testing that `Optional.empty()` is returned when argument is `null`)

Target:
public Webhook(String componentUuid, @Nullable String ceTaskUuid, @Nullable String analysisUuid, String name, String url) { this.componentUuid = requireNonNull(componentUuid); this.ceTaskUuid = ceTaskUuid; this.analysisUuid = analysisUuid; this.name = requireNonNull(name); this.url = requireNonNull(url); }
Source:
private static List<String> toStringList(final Object toCast) { // Return object as an ArrayList wherever it's defined as // list or not // // ### Example // object: // - firstValue // - secondValue // ### OR // object: singleValue // ### if (toCast instanceof List) { return (List<String>) toCast; } START return Collections.singletonList((String) toCast); END } I just want to make sure the result of this call is not expected to be modified anywhere. I see one assignment to a instance variable `this.excludeTags`

Target:
private static List<String> toStringList(final Object toCast) { // Return object as an ArrayList wherever it's defined as // list or not // // ### Example // object: // - firstValue // - secondValue // ### OR // object: singleValue // ### if (toCast instanceof List) { return (List<String>) toCast; } return new ArrayList<String>(Arrays.asList((String) toCast)); }
Source:
protected String getNameFromTopic(String topic) { if (!topic.startsWith(prefix)) { throw new IllegalArgumentException(String.format("topic %s with invalid prefix %s", topic, prefix)); } START return topic.replaceFirst(prefix, ""); END } `topic.substring(prefix.length())`

Target:
protected String getNameFromTopic(String topic) { if (!topic.startsWith(prefix)) { throw new IllegalArgumentException(String.format("topic %s with invalid prefix %s", topic, prefix)); } return topic.substring(prefix.length()); }
Source:
protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = Lookup.lookup(BUFFER_DIR_OPTION, dsn); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { START bufferDir = new File(this.ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); END } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); } // nitpick-mode-on Can you change `this.ctx` to `ctx`? // nitpick-mode-off

Target:
protected Buffer getBuffer(Dsn dsn) { File bufferDir; String bufferDirOpt = Lookup.lookup(BUFFER_DIR_OPTION, dsn); if (bufferDirOpt != null) { bufferDir = new File(bufferDirOpt); } else { bufferDir = new File(ctx.getCacheDir().getAbsolutePath(), DEFAULT_BUFFER_DIR); } Log.d(TAG, "Using buffer dir: " + bufferDir.getAbsolutePath()); return new DiskBuffer(bufferDir, getBufferSize(dsn)); }