auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean delegate(float delta) { START return rendererChanged; END } You don't really need "rendererChanged". "delegate" is the update method of the action (probably not the best method name) and returns true once the action is done. If the action only needs one update to execute (like in this case), it must return true (all things that should happen, already happened during initialize).

Target:
protected boolean delegate(float delta) { return true; }
Source:
private Boolean checkMatchpassword(String password, String password2) { START if (!password.equals(password2)) { return false; } else { return true; } END } you can use one single line for this...

Target:
private Boolean checkMatchpassword(String password, String password2) { return (password.equals(password2)); }
Source:
START public AuthMePlayer getPlayerInfo(String playerName) { END PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } return AuthMePlayerImpl.fromPlayerAuth(auth); } Api v4, deprecate api v3

Target:
public Optional<AuthMePlayer> getPlayerInfo(String playerName) { PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } return AuthMePlayerImpl.fromPlayerAuth(auth); }
Source:
public void setUnlogged(String user) { String sql = "UPDATE " + tableName + " SET " + col.IS_LOGGED + "=? WHERE LOWER(" + col.NAME + ")=?;"; if (user != null) { try (PreparedStatement pst = con.prepareStatement(sql)) { pst.setInt(1, 0); pst.setString(2, user); pst.executeUpdate(); } catch (SQLException ex) { logSqlException(ex); } } START } END Like in the MySQL class, here I'm missing the initialization of the `hasSession` column

Target:
public void setUnlogged(String user) { String sql = "UPDATE " + tableName + " SET " + col.IS_LOGGED + "=? WHERE LOWER(" + col.NAME + ")=?;"; try (PreparedStatement pst = con.prepareStatement(sql)) { pst.setInt(1, 0); pst.setString(2, user); pst.executeUpdate(); } catch (SQLException ex) { logSqlException(ex); } }
Source:
private String emailMask(String email){ String[] frag = email.split("@"); //Split id and domain int sid = frag[0].length() / 3 + 1; //Define the id view int sdomain = frag[1].length() / 3 + 1; //Define the domain view String id = frag[0].substring(0, sid) + "*****"; //Build the id START String domain = "***" + frag[1].substring(sdomain); //Build the domain END return id + "@" + domain; } I love the `+1` as to guarantee that there will always be a letter visible. Is there a reason for the asterisks in id vs. domain to be of different length? I might find it less confusing if my email `test@example.org` became something like `te***@***le.org` rather than `te*****@***le.org`.

Target:
private String emailMask(String email){ String[] frag = email.split("@"); //Split id and domain int sid = frag[0].length() / 3 + 1; //Define the id view (required length >= 1) int sdomain = frag[1].length() / 3; //Define the domain view (required length >= 0) String id = frag[0].substring(0, sid) + "***"; //Build the id String domain = "***" + frag[1].substring(sdomain); //Build the domain return id + "@" + domain; }
Source:
public void loadState(SonarLintGlobalSettings state) { XmlSerializerUtil.copyBean(state, this); includedRules.forEach(it -> { rules.put(it, new Rule(true)); }); excludedRules.forEach(it -> { rules.put(it, new Rule(false)); START }); END } If you don't clear (or better set to null) the two sets after the migration, it means the next time you'll reopen your IDE, the migration will happen again, and override possible different values added in the meantime by the user in the rules map.

Target:
public void loadState(SonarLintGlobalSettings state) { XmlSerializerUtil.copyBean(state, this); if(includedRules != null) { includedRules.forEach(it -> { rules.put(it, new Rule(true)); }); } if(excludedRules != null) { excludedRules.forEach(it -> { rules.put(it, new Rule(false)); }); } includedRules = null; excludedRules = null; }
Source:
public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { if (!globalSettings.isAutoTrigger()) { return; } Module m = ModuleUtil.findModuleForFile(file, myProject); if (m == null || !SonarLintUtils.shouldAnalyzeAutomatically(file, m)) { return; } analyzer.submitAsync(m, Collections.singleton(file), TriggerType.EDITOR_OPEN); START serverIssueUpdater.trackServerIssues(Collections.singleton(file)); END } To synchronize both tasks at the end (only do server issue tracking after local analysis completes) we could share a CountDownLatch

Target:
public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { if (!globalSettings.isAutoTrigger()) { return; } Module m = ModuleUtil.findModuleForFile(file, myProject); if (m == null || !SonarLintUtils.shouldAnalyzeAutomatically(file, m)) { return; } analyzer.submitAsync(m, Collections.singleton(file), TriggerType.EDITOR_OPEN); }
Source:
@Override public boolean value(VirtualFile virtualFile) { START return openedFiles.contains(virtualFile); END } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make this line start at column 7. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/sonarqube/coding_rules#rule_key=squid%3AIndentationCheck)

Target:
public boolean value(VirtualFile virtualFile) { return openedFiles.contains(virtualFile); }
Source:
public String getMaxConnections() { return maxConnections == null START ? Integer.valueOf(DEFAULT_CONNECTIONS).toString() END : maxConnections; } ``String.valueOf(DEFAULT_CONNECTIONS)`` would be more straightforward.

Target:
public String getMaxConnections() { return maxConnections == null ? String.valueOf(DEFAULT_CONNECTIONS) : maxConnections; }
Source:
private AWSCredentialsProvider getCredentialsProvider() { START if (null == awsSecretKey || null == awsAccessKey) { END return new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return new BasicAWSCredentials(awsAccessKey, awsSecretKey); } @Override public void refresh() { } }; } return new DefaultAWSCredentialsProviderChain(); } This looks backwards. This would attempt to create BasicAWSCredentials when neither awsSecretKey nor awsAccessKey is provided.

Target:
private AWSCredentialsProvider getCredentialsProvider() { if (null != awsSecretKey && null != awsAccessKey) { return new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return new BasicAWSCredentials(awsAccessKey, awsSecretKey); } @Override public void refresh() { } }; } return new DefaultAWSCredentialsProviderChain(); }
Source:
START public Boolean isWmtsCiteCompliant() { END return wmtsCiteCompliant; } Confused about the change of signature... what about keeping the field as Boolean for XStream, "boolean" for the methods, and then do a null check inside the body?

Target:
public boolean isWmtsCiteCompliant() { return wmtsCiteCompliant != null ? wmtsCiteCompliant : false; }
Source:
public void getFileName_ReturnsFileNameForSVG() { // given START Embedding embedding = new Embedding("image/svg+xml", "some data", null); END // when String fileName = embedding.getFileName(); // then assertThat(fileName).isEqualTo("embedding_-642587818.svg"); } then consider to leave old constructor and add new one below

Target:
public void getFileName_ReturnsFileNameForSVG() { // given Embedding embedding = new Embedding("image/svg+xml", "some data"); // when String fileName = embedding.getFileName(); // then assertThat(fileName).isEqualTo("embedding_-642587818.svg"); }
Source:
public String getRawName() { START return name().toLowerCase(Locale.US); END } My suggestion is to take a look at https://github.com/damianszczepanik/cucumber-reporting/tree/master/src/main/java/net/masterthought/cucumber/json/deserializers and move this change insto single class which is executed then the JSON is created instead of having the same fix in many places which are invoked many times during report creation

Target:
public String getRawName() { return name().toLowerCase(); }
Source:
private Properties buildProperties() { Properties props = new Properties(); props.setProperty("resource.loader", "class"); props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getCanonicalName()); props.setProperty("runtime.log", new File(configuration.getReportDirectory(), "velocity.log").getPath()); START props.setProperty("eventhandler.referenceinsertion.class", "org.apache.velocity.app.event.implement.EscapeHtmlReference"); END return props; } Also I prefer compile time checking, not runtime checking EscapeHtmlReference.class.getName() should work

Target:
private Properties buildProperties() { Properties props = new Properties(); props.setProperty("resource.loader", "class"); props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getCanonicalName()); props.setProperty("runtime.log", new File(configuration.getReportDirectory(), "velocity.log").getPath()); return props; }
Source:
public void generateReport_OnInvalidPath_ThrowsException() { START setUpWithJson(SAMPLE_JSON); END // given page = new FeaturesOverviewPage(reportResult, configuration) { @Override public String getWebPage() { // invalid file path return StringUtils.EMPTY; } }; // when thrown.expect(ValidationException.class); Deencapsulation.invoke(page, "generatePage"); } why it was not needed and now you copy it over and over again?

Target:
public void generateReport_OnInvalidPath_ThrowsException() { // given page = new FeaturesOverviewPage(reportResult, configuration) { @Override public String getWebPage() { // invalid file path return StringUtils.EMPTY; } }; // when thrown.expect(ValidationException.class); Deencapsulation.invoke(page, "generatePage"); }
Source:
public boolean isSleepingConsumer(){ START if(System.currentTimeMillis() < this.consumerSleepEndTime){ END return true; } return false; } 可以简化一下，直接return System.currentTimeMillis() < this.consumerSleepEndTime

Target:
public boolean isSleepingConsumer(){ return System.currentTimeMillis() < this.consumerSleepEndTime; }
Source:
private long getMemoryMb(String key) { long memoryMb = 0L; START if (key.equals(Constants.MAP_MEMORY_MB_CONF_KEY)){ END memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_MAP_MEMORY_MB); }else if (key.equals(Constants.REDUCE_MEMORY_MB_CONF_KEY)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_REDUCE_MEMORY_MB); } if (memoryMb == 0L) { throw new ProcessingException( "While correcting slot millis, " + key + " was found to be 0 "); } return memoryMb; } If key is null and there is no check for nullness of key, this would throw a NullPointerException. A better way to do this could be if (Constants.MAP_MEMORY_MB_CONF_KEY.equals(key)). Similarly for reduce memory mb.

Target:
private long getMemoryMb(String key) { long memoryMb = 0L; if (Constants.MAP_MEMORY_MB_CONF_KEY.equals(key)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_MAP_MEMORY_MB); }else if (Constants.REDUCE_MEMORY_MB_CONF_KEY.equals(key)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_REDUCE_MEMORY_MB); } if (memoryMb == 0L) { throw new ProcessingException( "While correcting slot millis, " + key + " was found to be 0 "); } return memoryMb; }
Source:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); START if (jobtracker == null) { END jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization String cluster = Cluster.getIdentifier(jobtracker); return cluster != null ? cluster: null; } Maybe use StringUtils.isEmpty(jobtracker) instead of jobtracker == null.

Target:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } String cluster = null; if (jobtracker != null) { // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization cluster = Cluster.getIdentifier(jobtracker); } return cluster; }
Source:
private Put getMegaByteMillisPut(Long mbMillis, JobKey jobKey) { START JobKeyConverter jobKeyConv = new JobKeyConverter(); END Put pMb = new Put(jobKeyConv.toBytes(jobKey)); pMb.add(Constants.INFO_FAM_BYTES, Constants.MEGABYTEMILLIS_BYTES, Bytes.toBytes(mbMillis)); return pMb; } minor: it appears that JobKeyConverter could be singleton.

Target:
private Put getMegaByteMillisPut(Long mbMillis, JobKey jobKey) { Put pMb = new Put(jobKeyConv.toBytes(jobKey)); pMb.add(Constants.INFO_FAM_BYTES, Constants.MEGABYTEMILLIS_BYTES, Bytes.toBytes(mbMillis)); return pMb; }
Source:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file " + ioe.getMessage()); START LOG.error(ioe.getStackTrace()); END throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey + " error: " + ioe.getMessage()); } } I think LOG.error("your log message", ioe); would do what these 2 lines are doing.

Target:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file ", ioe); throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey + " error: " , ioe); } }
Source:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file ", ioe); throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey START + " error: " + ioe.getMessage()); END } } This should use the constructor version: ProcessingException(String, Throwable) Otherwise you lose the stack trace of the underlying IOException

Target:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file ", ioe); throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey + " error: " , ioe); } }
Source:
START public Map<String, Serializable> getCachedMetaData( final String key ) { END final IPluginCacheManager cacheManager = PentahoSystem.get( IPluginCacheManager.class ); final IReportContentCache cache = cacheManager.getCache(); return cache.getMetaData( key ); } THere is no reason to have this method as public, I suppose. No one can call this method from elsewhere.

Target:
private Map<String, Serializable> getCachedMetaData( final String key ) { final IPluginCacheManager cacheManager = PentahoSystem.get( IPluginCacheManager.class ); final IReportContentCache cache = cacheManager.getCache(); return cache.getMetaData( key ); }
Source:
START public JobManager( final boolean isSupportAsync, final long pollingIntervalMilliseconds, END final long dialogThresholdMillisecond ) { if ( !isSupportAsync ) { logger.info( ASYNC_DISABLED ); } this.config = new Config( isSupportAsync, pollingIntervalMilliseconds, dialogThresholdMillisecond, Boolean.FALSE ); } Avoid duplicate code (and magically cover more lines in tests) by re-routing this constructor to the one with 4 parameters.

Target:
public JobManager( final boolean isSupportAsync, final long pollingIntervalMilliseconds, final long dialogThresholdMillisecond ) { this( isSupportAsync, pollingIntervalMilliseconds, dialogThresholdMillisecond, false ); }
Source:
@Override public PerformanceLoggingStopWatch createStopWatch( String tag, Object message ) { START return new LoggingStopWatch( tag, message + this.getMessage() ); END } Instead of using string + string, pass the "message" object into the "getMessage" method and format everything in one operation. Your format string would then be "%s sessionid[%s] userid[%s] requestid[%s]" You probably dont intend to use a one-space padding, two-space padding and 3 space padding on the format string either.

Target:
@Override public PerformanceLoggingStopWatch createStopWatch( String tag, Object message ) { return new LoggingStopWatch( tag, getMessage( String.valueOf( message ) ) ); }
Source:
public ThreadLocalSslBufferPool(int maxPoolSize, boolean preallocate, boolean allocateDirect) { pool = new ThreadLocal<NonBlockingSslBufferPoll>() { @Override protected NonBlockingSslBufferPoll initialValue() { int threadLocalMaxPoolSize = maxPoolSize / DEFAULT_WORKER_THREAD_COUNT; if (threadLocalMaxPoolSize % DEFAULT_WORKER_THREAD_COUNT != 0) { START threadLocalMaxPoolSize ++; END } return new NonBlockingSslBufferPoll(threadLocalMaxPoolSize, preallocate, allocateDirect); } }; } nit: threadLocalMaxPoolSize++

Target:
public ThreadLocalSslBufferPool(int maxPoolSize, boolean preallocate, boolean allocateDirect) { this(maxPoolSize, preallocate, allocateDirect, DEFAULT_WORKER_THREAD_COUNT); }
Source:
public void testNonBlockingAcquireBuffer() { SslBufferPool pool = new ThreadLocalSslBufferPool(1, true, true, 1); ByteBuffer buf1 = pool.acquireBuffer(); Assert.assertEquals(pool.getUnacquiredPoolSize(), 0); // Try to acquire buffer. Unlike SslBufferPool, this should not block and will return another buffer. ByteBuffer buf2 = pool.acquireBuffer(); START pool.releaseBuffer(buf1); END pool.releaseBuffer(buf2); } put these 2 in a finally block. don't know whether acquire can throw an exception like a runtime exception. similarly in other tests as well

Target:
public void testNonBlockingAcquireBuffer() { SslBufferPool pool = new ThreadLocalSslBufferPool(1, true, true, 1); ByteBuffer buf1 = null; ByteBuffer buf2 = null; try { buf1 = pool.acquireBuffer(); Assert.assertEquals(pool.getUnacquiredPoolSize(), 0); // Try to acquire buffer. Unlike SslBufferPool, this should not block and will return another buffer. buf2 = pool.acquireBuffer(); } finally { pool.releaseBuffer(buf1); pool.releaseBuffer(buf2); } }
Source:
List<String> getAllSeeds() { START final ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); END return builder.addAll(currentSeeds).addAll(newSeeds).addAll(oldSeeds).build(); } You can chain this like ``` java return ImmutableList.<String>builder() .addAll(currentSeeds) .addAll(newSeeds) .addAll(oldSeeds) .build(); ```

Target:
List<String> getAllSeeds() { return new ImmutableList.Builder<String>() .addAll(currentSeeds) .addAll(newSeeds) .addAll(oldSeeds) .build(); }
Source:
public void modify(Path path, byte[] data, Consumer<Long> progressConsumer) { FileWrapper file = getPath(path); START ProgressConsumer<Long> pc = l -> progressConsumer.accept(l); END file.overwriteFileJS(AsyncReader.build(data), 0, data.length, userContext.network, userContext.crypto, pc).join(); } can just use progressConsumer directly

Target:
public void modify(Path path, byte[] data, Consumer<Long> progressConsumer) { FileWrapper file = getPath(path); file.overwriteFileJS(AsyncReader.build(data), 0, data.length, userContext.network, userContext.crypto, l -> progressConsumer.accept(l)).join(); }
Source:
public void dosCborObject() throws Throwable { START if(true)throw new RuntimeException(); END // make a header for a byte[] that is 2^50 long byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); Assert.fail("Should have failed!"); } catch (RuntimeException e) } yep, will revert once I check it works on github

Target:
public void dosCborObject() throws Throwable { // make a header for a byte[] that is 2^50 long byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); Assert.fail("Should have failed!"); } catch (RuntimeException e) }
Source:
public byte[] read(Path path, BiConsumer<Long, Long> pc) { Path nativePath = virtualToNative(path); ensureCan(path, Permission.READ); if (nativePath.toFile().isDirectory()) { START return null; END } try { return Files.readAllBytes(nativePath); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } This would be easier to reason about if it raised an exception. Why return null?

Target:
public byte[] read(Path path, BiConsumer<Long, Long> pc) { Path nativePath = virtualToNative(path); ensureCan(path, Permission.READ); try { return Files.readAllBytes(nativePath); } catch (IOException ioe) { throw new IllegalStateException(ioe); } }
Source:
private CompletableFuture<Boolean> updatedSharedWithCache(FileWrapper file, Set<String> usersToAdd, SharedWithCache.Access access) { return file.getPath(network).thenCompose(path -> { START network.sharedWithCache.addSharedWith(access, file.getPointer().capability, usersToAdd); END CompletableFuture<Boolean> res = new CompletableFuture<>(); res.complete(true); return res; }); } no path required

Target:
private CompletableFuture<Boolean> updatedSharedWithCache(FileWrapper file, Set<String> usersToAdd, SharedWithCache.Access access) { sharedWithCache.addSharedWith(access, file.getPointer().capability, usersToAdd); CompletableFuture<Boolean> res = new CompletableFuture<>(); res.complete(true); return res; }
Source:
public CompletableFuture<Integer> readIntoArray(byte[] res, int offset, int length) { try { System.arraycopy(data, index, res, offset, length); } catch (ArrayIndexOutOfBoundsException e) { START System.out.println(); END } index += length; return CompletableFuture.completedFuture(length); } debug artefact?

Target:
public CompletableFuture<Integer> readIntoArray(byte[] res, int offset, int length) { System.arraycopy(data, index, res, offset, length); index += length; return CompletableFuture.completedFuture(length); }
Source:
private void test(byte[] input) throws IOException { random.nextBytes(input); byte[][] split = fragmenter.split(input); for (byte[] bytes : split) { int length = bytes.length; START assertTrue(length >= 0); END assertTrue(length <= Fragment.MAX_LENGTH); } byte[] recombine = fragmenter.recombine(split, input.length); assertTrue("recombine(split(input)) = input", Arrays.equals(input, recombine)); } In case is this zero?

Target:
private void test(byte[] input) throws IOException { random.nextBytes(input); byte[][] split = fragmenter.split(input); for (byte[] bytes : split) { int length = bytes.length; assertTrue(length > 0); assertTrue(length <= Fragment.MAX_LENGTH); } byte[] recombine = fragmenter.recombine(split, input.length); assertTrue("recombine(split(input)) = input", Arrays.equals(input, recombine)); }
Source:
START private static Object wrapHash(String key, Multihash h) { END Map<String, Object> json = new TreeMap<>(); json.put(key, h.toString()); return json; } Mind changing the type of this to ``Map<String, Object>``?

Target:
private static Map<String, Object> wrapHash(String key, Multihash h) { Map<String, Object> json = new TreeMap<>(); json.put(key, h.toString()); return json; }
Source:
public static int compare(byte[] a, byte[] b) { START for (int i=0; i < Math.min(a.length, b.length); i++) END if (a[i] != b[i]) return a[i] & 0xff - b[i] & 0xff; return 0; } Could you explain the contract here in a docstring? If two arrays are different lengths why are they ``equal`` if they have the same content up to the length of the smaller array?

Target:
public static int compare(byte[] a, byte[] b) { if (a.length != b.length) return a.length - b.length; for (int i=0; i < a.length; i++) if (a[i] != b[i]) return a[i] & 0xff - b[i] & 0xff; return 0; }
Source:
public int getQueuePositionForSong(long id) { START return mTimeline.getPositionForSong(id); END } Could we rename the function in SongTimeline to have the same function name? (= getQueuePositionForSong)

Target:
public int getQueuePositionForSong(long id) { return mTimeline.getQueuePositionForSong(id); }
Source:
START public org.kiji.schema.AsyncKijiBufferedWriter openAsyncBufferedWriter() throws IOException { END return AsyncHBaseAsyncKijiBufferedWriter.create(mTable); } Full path is no longer needed, right?

Target:
public AsyncKijiBufferedWriter openAsyncBufferedWriter() throws IOException { return AsyncHBaseAsyncKijiBufferedWriter.create(mTable); }
Source:
private PagedColumnIterable(final Column columnRequest) { mColumn = columnRequest.getColumnName(); mCloser = Closer.create(); mColumnRequest = columnRequest; mTableName = KijiManagedHBaseTableName START .getKijiTableName(mTable.getURI().getInstance(), mTable.getURI().getTable()).toBytes(); END } charset

Target:
private PagedColumnIterable(final Column columnRequest) { mColumn = columnRequest.getColumnName(); mColumnRequest = columnRequest; mTableName = KijiManagedHBaseTableName .getKijiTableName(mTable.getURI().getInstance(), mTable.getURI().getTable()).toBytes(); }
Source:
private CachedCuratorFrameworkImpl( final ReferenceCountedCache<K, CuratorFramework> cache, final K key, final CuratorFrameworkImpl delegate ) { super(delegate); mCache = cache; mCacheKey = key; START DebugResourceTracker END .get() .registerResource(this, ExceptionUtils.getStackTrace(new Exception())); } This looks like the result of a bad merge.

Target:
private CachedCuratorFrameworkImpl( final ReferenceCountedCache<K, CuratorFramework> cache, final K key, final CuratorFrameworkImpl delegate ) { super(delegate); mCache = cache; mCacheKey = key; DebugResourceTracker.get().registerResource(this); }
Source:
public void close() throws IOException { final State oldState = mState.getAndSet(State.CLOSED); Preconditions.checkState(oldState == State.OPEN, "Cannot close KijiTableWriter instance %s in state %s.", this, oldState); mLayoutConsumerRegistration.close(); try { START mHBClient.shutdown().join(); END } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); } mTable.release(); } I believe that many AsyncKTR's can share a single HBaseClient, so it should be 'owned' by the Kiji instead of being shut down here. Let me know if this isn't a clear explanation.

Target:
public void close() throws IOException { final State oldState = mState.getAndSet(State.CLOSED); Preconditions.checkState(oldState == State.OPEN, "Cannot close KijiTableWriter instance %s in state %s.", this, oldState); mLayoutConsumerRegistration.close(); mTable.release(); }
Source:
public KijiCell<T> next() { KeyValue kv = mKVs.next(); mNumVersions += 1; try { return new KijiCell<T>(mFamily, mQualifier, kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } catch (IOException ex) { START throw new KijiIOException(ex.getMessage()); END } } Use new KijiIOException(ex), to not lose the stacktrace of the cause

Target:
public KijiCell<T> next() { KeyValue kv = mKVs.next(); mNumVersions += 1; try { return new KijiCell<T>(mFamily, mQualifier, kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } catch (IOException ex) { throw new KijiIOException(ex); } }
Source:
public boolean equals(Object obj) { START return HttpServerModule.class.equals(obj.getClass()); END } Why not just `getClass().equals(obj.getClass())`? nit: The contract for equals says you should check for obj being null to avoid an NPE.

Target:
public boolean equals(Object obj) { return getClass().equals(obj.getClass()); }
Source:
START private Module getAdditionalBindings() { END return new AbstractModule() { @Override protected void configure() { bind(AdminContainerConfig.class).to(AdminConfigImpl.class); bind(AdminResourcesFilter.class); } }; } This method enforces AdminConfigImpl binding, while it should be possible to inject custom instance of it. Now injecting custom implementation results in duplicate binding exception.

Target:
private Module getAdditionalBindings() { return new AbstractModule() { @Override protected void configure() { bind(AdminResourcesFilter.class); } }; }
Source:
public Collection<E> makeConfirmedCollection() { START final ArrayList<E> list = new ArrayList<>(); END return list; } The local var is useless, you can remove it.

Target:
public Collection<E> makeConfirmedCollection() { return new ArrayList<>(); }
Source:
public static <T extends Collection<E>,E> T deepMerge(final Iterable<? extends Iterable<?>> iterableOfIterables, final T collectionToFill) { Iterator<? extends Iterable<?>> iterator = iterableOfIterables.iterator(); START if (!iterator.hasNext()) { END return collectionToFill; } while (iterator.hasNext()) { deepMergeRecursion(iterator.next(), collectionToFill); } return collectionToFill; } This if statement is not necessary as the while loop below would handle the negative case.

Target:
public static <T extends Collection<E>,E> T deepMerge(final Iterable<? extends Iterable<?>> iterableOfIterables, final T collectionToFill) { Iterator<? extends Iterable<?>> iterator = iterableOfIterables.iterator(); while (iterator.hasNext()) { deepMergeRecursion(iterator.next(), collectionToFill); } return collectionToFill; }
Source:
START protected Statement withInterruptIsolation(final Statement statement) { END return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { Thread.interrupted(); // clearing thread interrupted status for isolation } } }; } I personally would prefer this is be `final`

Target:
protected final Statement withInterruptIsolation(final Statement statement) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { Thread.interrupted(); // clearing thread interrupted status for isolation } } }; }
Source:
public void testAssumptionFailure(Failure failure) { START ignoreCount.getAndIncrement(); END } In #1294 (currently targeted for 4.13) we are proposing updating this class to collect assumption failure counts, so I am not sure we should make this change.

Target:
public void testAssumptionFailure(Failure failure) { // do nothing: same as passing (for 4.5; may change in 4.6) }
Source:
public void testRemoveElement() { START fullList.remove(2); END assertFalse(fullList.contains(3)); } fullList.remove(Integer.valueOf(3));

Target:
public void testRemoveElement() { fullList.remove(Integer.valueOf(3)); assertFalse(fullList.contains(3)); }
Source:
private static boolean hasSuppressed(Throwable exception) { START if (getSuppressed != null) { END try { Throwable[] suppressed = (Throwable[]) getSuppressed.invoke(exception); return suppressed.length != 0; } catch (Throwable e) { return false; } } else { return false; } } nit: I personally prefer existing out on error conditions early, to avoid over-intentation: if (getSuppressed == null) { return false; } try { ... } catch (Throwable e) { return false; }

Target:
private static boolean hasSuppressed(Throwable exception) { if (getSuppressed == null) { return false; } try { Throwable[] suppressed = (Throwable[]) getSuppressed.invoke(exception); return suppressed.length != 0; } catch (Throwable e) { return false; } }
Source:
public static <T> T notNull(T value, String message) { if (value == null) { START throw new NullPointerException(String.valueOf(message)); END } return value; } I conform to @panchenko's suggestion. I normally expect that `someMethod(someValue)` and `someMethod(someValue, null)` behave the same.

Target:
public static <T> T notNull(T value, String message) { if (value == null) { throw new NullPointerException(message); } return value; }
Source:
START public boolean isAnyExceptionExpected() { END return matcherBuilder.expectsThrowable(); } Let's make this final

Target:
public final boolean isAnyExceptionExpected() { return matcherBuilder.expectsThrowable(); }
Source:
START protected void after() throws Exception { END // do nothing } Why `Exception` instead of `Throwable` like we did for `before()`?

Target:
protected void after() throws Throwable { // do nothing }
Source:
public void assumeNotNullSingleNullThrowsException() { try { START assumeNotNull(null); END fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } } Please add a cast to `Object[]` here.

Target:
public void assumeNotNullSingleNullThrowsException() { try { assumeNotNull((Object[]) null); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } }
Source:
public void executeRulesInCorrectOrder() throws Exception { START LOG.clear(); END testResult(UseRuleChain.class); List<String> expectedLog = asList("starting outer rule", "starting middle rule", "starting inner rule", "finished inner rule", "finished middle rule", "finished outer rule"); assertEquals(expectedLog, LOG); } Let's put this call in a `@Before` method named `clearLog()`

Target:
public void executeRulesInCorrectOrder() throws Exception { testResult(UseRuleChain.class); List<String> expectedLog = asList("starting outer rule", "starting middle rule", "starting inner rule", "finished inner rule", "finished middle rule", "finished outer rule"); assertEquals(expectedLog, LOG); }
Source:
public void assumeNotNullThrowsException() { try { START Object[] objects = {1, 2, null}; END assumeNotNull(objects); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } } Please put this line outside of the "try" block

Target:
public void assumeNotNullThrowsException() { Object[] objects = {1, 2, null}; assumeNotNull(objects); }
Source:
START protected void after() throws Throwable { END // do nothing } We can't change the signature of published methods

Target:
protected void after() { // do nothing }
Source:
START Builder parentFolder(File parentFolder) { END this.parentFolder = parentFolder; return this; } Shouldn't this be public? Also, if we need the getter methods (and I don't think we do) could we put them right after the setter methods?

Target:
public Builder parentFolder(File parentFolder) { this.parentFolder = parentFolder; return this; }
Source:
protected boolean tryDelete() { boolean result = true; if (folder != null) { result = recursiveDelete(folder); } START return result; END } This method boils down to ``` java return folder == null || recursiveDelete(folder); ``` or ``` java if (folder == null) return true; return recursiveDelete(folder); ```

Target:
protected boolean tryDelete() { if (folder == null) { return true; } return recursiveDelete(folder); }
Source:
public void testStrictVerificationFailure() { PrintableResult result = testResult(HasTempFolderWithAssuredDeletion.class); assertThat(result, failureCountIs(1)); START assertThat(result.toString(), CoreMatchers.containsString("Unable to clean up temporary folder")); END } Please add a static import for `containsString`.

Target:
public void testStrictVerificationFailure() { PrintableResult result = testResult(HasTempFolderWithAssuredDeletion.class); assertThat(result, failureCountIs(1)); assertThat(result.toString(), containsString("Unable to clean up temporary folder")); }
Source:
START private Builder() { END } When subclassing the builder one might want to subclass the builder as well. Let's make it `protected`?

Target:
protected Builder() { }
Source:
public AssumptionViolatedException(String assumption, boolean valueMatcher, Object value, Matcher<?> matcher) { START if (value instanceof Throwable) { END initCause((Throwable) value); } this.assumption = assumption; this.value = value; this.matcher = matcher; this.valueMatcher = valueMatcher; } Looking closer, I think this should be: ``` if (!valueMatcher && (value instanceof Throwable)) { ``` This will lead to `initCause()` to only be called if you got here via the last constructor. This is a slight change in behavior, but I wouldn't expect the following to throw an `AssumptionViolationException` with a cause: ``` assumeThat(e, hasMessage("woops")); ``` _Edit:_ A much simpler solution would be to only call `initCause()` in `AssumptionViolatedException(String assumption, Throwable e)`. Sorry I didn't see that before; this class is too complicated.

Target:
public AssumptionViolatedException(String assumption, boolean valueMatcher, Object value, Matcher<?> matcher) { this.assumption = assumption; this.value = value; this.matcher = matcher; this.valueMatcher = valueMatcher; }
Source:
private void validateFolderName(String folderName) throws IOException { File tempFile = new File(folderName); START if (tempFile != null && tempFile.getParent() != null) { END String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; throw new IOException(errorMsg); } } `tempFile` cannot be `null`

Target:
private void validateFolderName(String folderName) throws IOException { File tempFile = new File(folderName); if (tempFile.getParent() != null) { String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; throw new IOException(errorMsg); } }
Source:
START public File newFolder(String folder) throws IOException, IllegalArgumentException { END return newFolder(new String[]{folder}); } Please remove `IllegalArgumentException` from the `throws` clause

Target:
public File newFolder(String folder) throws IOException { return newFolder(new String[]{folder}); }
Source:
START public static void assertEquals(String message, CharSequence expected, CharSequence actual) { END Assert.assertEquals(message, expected, actual); } We have not been making changes to the code under `junit.framework`

Target:
protected static void assertEquals(String message, CharSequence expected, CharSequence actual) { Assert.assertEquals(message, expected.toString(), actual.toString()); }
Source:
RuleMemberValidator build() { START return new RuleMemberValidator(fAnnotation, fMethods, fValidatorStrategies); END } change to: ``` return new RuleMemberValidator(this); ``` (see Effective Java, 2nd edition)

Target:
RuleMemberValidator build() { return new RuleMemberValidator(this); }
Source:
private static void internalAssertEquals( String message, Object expecteds, Object actuals, ComparisonHelper comparisonHelper) { String messagePrefix = message == null ? "" : message + ": "; if (arraysTriviallyEqual(messagePrefix, expecteds, actuals)) { return; } START assertElementsEqual(messagePrefix, comparisonHelper); END } What do you think about changing this code to ``` if (!arraysTriviallyEqual(messagePrefix, expecteds, actuals)) { assertElementsEqual(messagePrefix, comparisonHelper); } ```

Target:
private static void internalAssertEquals( String message, Object expecteds, Object actuals, ComparisonHelper comparisonHelper) { String messagePrefix = message == null ? "" : message + ": "; if (!arraysTriviallyEqual(messagePrefix, expecteds, actuals)) { assertElementsEqual(messagePrefix, expecteds, actuals, comparisonHelper); } }
Source:
START public void methodNameTest() throws Exception { END Description description = Description.createTestDescription("some-class-name", methodName); assertNotNull("Method name should be not null", description.getMethodName()); assertEquals(description.getMethodName(), methodName); } Note that we may be moving soon to a builder for Description objects, and the builder should provide a way to specify the test method and test class independently of the "description" (i.e. we wouldn't use a regex to parse it). Having both types of test would allow us to verify this bug doesn't come back. Thanks!

Target:
public void methodNameTest() throws Exception { Description description = Description.createTestDescription("some-class-name", methodName); assertNotNull("Method name should be not null", description.getMethodName()); assertEquals(methodName, description.getMethodName()); }
Source:
public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); START assertNotNull(fResult); END } Useless. This line will not be executed if `fResult` is `null` because a `NullPointerException` will be thrown the line before.

Target:
public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); }
Source:
START private String expectedDiff() { END return extractDiff(expected); } I would personally prefer if the methods that are the "external API" be public. Yes, the outer class can call private methods directly, but most IDEs show public methods differently, let you filter out non-public methods when browsing, etc.

Target:
public String expectedDiff() { return extractDiff(expected); }
Source:
private String compactPrefix() { START if (sharedPrefix.length() > contextLength) { END return ELLIPSIS + sharedPrefix.substring(sharedPrefix.length() - contextLength); } return sharedPrefix; } This is really a nit, but I would _personally_ prefer inverting this `if` statement: ``` if (sharedPrefix.length() <= contextLength) { return sharedPrefix; } ... ``` That way, 1) the simplest part of the code is taken care of up front and 2) the indented line is the short line, not the long line

Target:
public String compactPrefix() { if (sharedPrefix.length() <= contextLength) { return sharedPrefix; } return ELLIPSIS + sharedPrefix.substring(sharedPrefix.length() - contextLength); }
Source:
public boolean isComplete() { START return unassigned.size() == 0; END } how about `return unassigned.isEmpty()` ?

Target:
public boolean isComplete() { return unassigned.isEmpty(); }
Source:
public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { // don't catch ThreadDeath by accident throw e; START } catch (Throwable t) { END addError(test, t); } } IMHO, for things like variable naming, local consistency is arguably more important than global consistency, so naming this `e` is best. If we make a global change, I would prefer to rename variables of type `Throwable` to `e`

Target:
public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { // don't catch ThreadDeath by accident throw e; } catch (Throwable e) { addError(test, e); } }
Source:
static public void assertEquals(String message, double expected, double actual, double delta) { if (Double.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { START failNotEquals(message, Double.valueOf(expected), Double.valueOf(actual)); END } } This actually isn't an optimization; `Double.valueOf(double d)` just calls 'new Double(d)' Let's just remove this change. Since this class is deprecated, I want to minimize changes to it wherever possible.

Target:
static public void assertEquals(String message, double expected, double actual, double delta) { if (Double.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { failNotEquals(message, new Double(expected), new Double(actual)); } }
Source:
static public void assertEquals(String message, float expected, float actual, float delta) { if (Float.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { START failNotEquals(message, Float.valueOf(expected), Float.valueOf(actual)); END } } This actually isn't an optimization; Float.valueOf(float f) just calls 'new Float(f)'

Target:
static public void assertEquals(String message, float expected, float actual, float delta) { if (Float.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { failNotEquals(message, new Float(expected), new Float(actual)); } }
Source:
public Runner runnerForClass(Class<?> testClass) throws Exception { for (Class<?> currentTestClass = testClass; currentTestClass != null; currentTestClass = getEnclosingClassForNonStaticMemberClass(currentTestClass)) { RunWith annotation = currentTestClass.getAnnotation(RunWith.class); if (annotation != null) { START return buildRunner(annotation.value(), currentTestClass); END } } return null; } Are you sure you don't want to pass `testClass` instead of `currentTestClass` here? Passing the outermost class with `@RunWith` doesn't appear to solve #816

Target:
public Runner runnerForClass(Class<?> testClass) throws Exception { for (Class<?> currentTestClass = testClass; currentTestClass != null; currentTestClass = getEnclosingClassForNonStaticMemberClass(currentTestClass)) { RunWith annotation = currentTestClass.getAnnotation(RunWith.class); if (annotation != null) { return buildRunner(annotation.value(), testClass); } } return null; }
Source:
private Throwable createTimeoutException(Thread thread) { List<Throwable> exceptions = new ArrayList<Throwable>(); exceptions.add(createCurrentThreadException(thread)); exceptions.addAll(createAdditionalTimeoutExceptions(thread)); START return exceptions.size() == 1 ? exceptions.get(0) : new MultipleFailureException(exceptions); END } This can be simplified to MultipleFailureException.assertEmpty, for what it's worth.

Target:
protected Throwable createTimeoutException(Thread thread) { List<Throwable> exceptions = new ArrayList<Throwable>(); exceptions.add(createCurrentThreadException(thread)); exceptions.addAll(createAdditionalTimeoutExceptions(thread)); return exceptions.size() == 1 ? exceptions.get(0) : new MultipleFailureException(exceptions); }
Source:
private static ParametersRunnerFactory getParametersRunnerFactory( Class<?> klass) throws InstantiationException, IllegalAccessException { UseParametersRunnerFactory annotation = klass .getAnnotation(UseParametersRunnerFactory.class); if (annotation == null) { return DEFAULT_FACTORY; } else { Class<? extends ParametersRunnerFactory> factoryClass = annotation .value(); START return factoryClass.newInstance(); END } } Do we need some error handling here?

Target:
private ParametersRunnerFactory getParametersRunnerFactory(Class<?> klass) throws InstantiationException, IllegalAccessException { UseParametersRunnerFactory annotation = klass .getAnnotation(UseParametersRunnerFactory.class); if (annotation == null) { return DEFAULT_FACTORY; } else { Class<? extends ParametersRunnerFactory> factoryClass = annotation .value(); return factoryClass.newInstance(); } }
Source:
public boolean equals(Object obj) { START if (this == obj) END return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestClass other = (TestClass) obj; if (fClass == null) return other.fClass == null; else return fClass.equals(other.fClass); } JUnit style is to always use braces for "if" "do" and "while" statements.

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestClass other = (TestClass) obj; return fClass == other.fClass; }
Source:
public String toString() { START return fTestClass.getName() + " '" + fName + "' with parameters " END + Arrays.toString(fParameters); } If `fName` is null, then `toString()` will include `'null'`. Is that intentional? Why do you want to allow this class to have a null `fName` (vs an empty string)?

Target:
public String toString() { return fTestClass.getName() + " '" + fName + "' with parameters " + fParameters; }
Source:
public int hashCode() { int prime = 14747; START int result = prime + ((fName == null) ? 0 : fName.hashCode()); END result = prime * result + fTestClass.hashCode(); return prime * result + fParameters.hashCode(); } `fName` can't be null, so this can be simpler

Target:
public int hashCode() { int prime = 14747; int result = prime + fName.hashCode(); result = prime * result + fTestClass.hashCode(); return prime * result + fParameters.hashCode(); }