auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void tearDownCluster() throws Exception { synchronized (MongoTestSuit.class) { if (initCount.decrementAndGet() == 0) { if (mongoClient != null) { mongoClient.dropDatabase(EMPLOYEE_DB); mongoClient.close(); } if (distMode) { DistributedMode.cleanup(); } else { START SingleMode.cleanup(); END } } } } Should the above include error handling? It seems that if the `dropDatabase` fails, then `close()` won't be called, nor will the `cleanup` method.

Target:
public static void tearDownCluster() throws Exception { if (mongoClient != null) { mongoClient.dropDatabase(EMPLOYEE_DB); mongoClient.close(); } synchronized (MongoTestSuit.class) { if (distMode) { DistributedMode.cleanup(); } else { SingleMode.cleanup(); } } }
Source:
public Writer getWriter(PhysicalOperator child) throws IOException { if (!(formatPlugin.supportsAutoPartitioning() || partitionColumns == null || partitionColumns.size() == 0)) { throw UserException.unsupportedError().message(String.format("%s format does not support auto-partitioning.", formatPlugin.getName())).build(logger); } AbstractWriter writer = formatPlugin.getWriter(child, location, partitionColumns); if (storageStrategy != null) { START writer.setStorageStrategy(storageStrategy); END } return writer; } Can the `setStorageStrategy` method accept a null storage strategy? Substitute `PERSISTENT` for null? Doing so will save the != null checks here and anywhere else that the method is called.

Target:
public Writer getWriter(PhysicalOperator child) throws IOException { if (!(formatPlugin.supportsAutoPartitioning() || partitionColumns == null || partitionColumns.size() == 0)) { throw UserException.unsupportedError().message(String.format("%s format does not support auto-partitioning.", formatPlugin.getName())).build(logger); } AbstractWriter writer = formatPlugin.getWriter(child, location, partitionColumns); writer.setStorageStrategy(storageStrategy); return writer; }
Source:
public void addClass( String fqcn, byte[] byteCodes ) { START assert ! cache.containsKey( fqcn ); END Class<?> newClass = defineClass(fqcn, byteCodes, 0, byteCodes.length); cache.put( fqcn, newClass ); } Please use Guava Preconditions.checkState(cache.containsKey(fqcn), "your error message");

Target:
public void addClass(String fqcn, byte[] byteCodes) { Class<?> newClass = defineClass(fqcn, byteCodes, 0, byteCodes.length); cache.put(fqcn, newClass); }
Source:
public void addClasses(Map<String, byte[]> results) { for ( String key : results.keySet() ) { addClass( key, results.get( key ) ); START } END } Using iteration over map via entry set is more efficient than via key set: for (Map.Entry<String, byte[]> result : results.entrySet()) { addClass(result.getKey(), result.getValue()); }

Target:
public void addClasses(Map<String, byte[]> results) { for (Map.Entry<String, byte[]> result : results.entrySet()) { addClass(result.getKey(), result.getValue()); } }
Source:
START public InvalidConnectionInfoException(String message) { END this.message = message; } Just use the normal facilities: ``` public Invalid...( String message ) { super( message ); } ... e.getMessage( ) ... ```

Target:
public InvalidConnectionInfoException(String message) { super(message); }
Source:
private String getHostName() throws UnknownHostException{ // DRILL_HOST_NAME sets custom host name. See drill-env.sh for details. String customHost = System.getenv("DRILL_HOST_NAME"); if (customHost == null) { return useIP ? InetAddress.getLocalHost().getHostAddress() : InetAddress.getLocalHost().getCanonicalHostName(); } else { return customHost; START } END } Minor code flow suggestion: ``` if (customHost == null) { return customHost; } return useIP ? InetAddress.getLocalHost().getHostAddress() : InetAddress.getLocalHost().getCanonicalHostName(); ```

Target:
private String getHostName() throws UnknownHostException{ // DRILL_HOST_NAME sets custom host name. See drill-env.sh for details. String customHost = System.getenv("DRILL_HOST_NAME"); if (customHost != null) { return customHost; } return useIP ? InetAddress.getLocalHost().getHostAddress() : InetAddress.getLocalHost().getCanonicalHostName(); }
Source:
public RowGroupInfo(@JsonProperty("path") String path, @JsonProperty("start") long start, @JsonProperty("length") long length, @JsonProperty("rowGroupIndex") int rowGroupIndex, long rowCount) { super(path, start, length); this.rowGroupIndex = rowGroupIndex; this.rowCount = rowCount; this.numRecordsToRead = rowCount; START this.preferredEndpoint = null; END } Not required.

Target:
public RowGroupInfo(@JsonProperty("path") String path, @JsonProperty("start") long start, @JsonProperty("length") long length, @JsonProperty("rowGroupIndex") int rowGroupIndex, long rowCount) { super(path, start, length); this.rowGroupIndex = rowGroupIndex; this.rowCount = rowCount; this.numRecordsToRead = rowCount; }
Source:
START public synchronized long skip(long n) throws IOException { END checkInputStreamState(); long bytesAvailable = this.count - this.curPosInBuffer; long bytesSkipped = 0; if (n <= 0) { return 0; } if (bytesAvailable <= 0) { checkInputStreamState(); bytesAvailable = getNextBlock(); if (bytesAvailable <= 0) { // End of stream return 0; } } bytesSkipped = bytesAvailable < n ? bytesAvailable : n; this.curPosInBuffer += bytesSkipped; return bytesSkipped; } Not sure the semantics of this are exactly correct... The InputStream version seeks forward by n bytes. This implementation seems to seek forward only within the data **in the buffer**. It does not (seem) to "Skips over and discards n bytes of data from this input stream." as InputStream does.

Target:
@Override public synchronized long skip(long n) throws IOException { checkInputStreamState(); long bytesAvailable = this.count - this.curPosInBuffer; long bytesSkipped = 0; if (n <= 0) { return 0; } if (bytesAvailable <= 0) { checkInputStreamState(); bytesAvailable = getNextBlock(); if (bytesAvailable <= 0) { // End of stream return 0; } } bytesSkipped = bytesAvailable < n ? bytesAvailable : n; this.curPosInBuffer += bytesSkipped; return bytesSkipped; }
Source:
public static BooleanType get(String literal) { String value = literal.toLowerCase().trim(); BooleanType booleanType = allLiterals.get(value); if (booleanType == null) { START throw new IllegalArgumentException("Invalid value for boolean: " + literal); END } return booleanType; } How is this exception handled?

Target:
public static BooleanType get(String literal) { final String value = literal.trim(); final BooleanType booleanType = allLiterals.get(value); if (booleanType == null) { throw new IllegalArgumentException("Invalid value for boolean: " + literal); } return booleanType; }
Source:
private void connect(DrillbitEndpoint endpoint) throws RpcException { client.connect(endpoint, parameters, getUserCredentials()).checkedGet(); START if (client.serverRequiresAuthentication()) { END try { client.authenticate(null).checkedGet(); } catch (SaslException e) { throw new RpcException(e); } } } what if the server doesn't require authentication, shouldn't the client wait too?

Target:
private void connect(DrillbitEndpoint endpoint) throws RpcException { client.connect(endpoint, properties, getUserCredentials()); }
Source:
public V get(final String key) { START return get(key, null); END } Minor point... Should this version simply call client.get as before? Should the version that takes a version require the version? Would seem to keep things a bit simpler that way...

Target:
public V get(final String key) { return get(key, false, null); }
Source:
public long getVersion() { START try (AutoCloseableLock lock = readLock.open()) { END return version.get(); } } It seems that the version number is always protected by a read or write lock. Does it need to be an atomic long? If so, what does the atomic long get us that a (lock protected) long does not?

Target:
public long getVersion() { try (AutoCloseableLock lock = readLock.open()) { return version; } }
Source:
public long getInSubqueryThreshold() { START return options.getOption(IN_SUBQUERY_THRESHOLD.getOptionName()).num_val; END } Change the declaration to: `public static final LongValidator IN_SUBQUERY_THRESHOLD ...` and here, `return options.getOption(IN_SUBQUERY_THRESHOLD;`

Target:
public long getInSubqueryThreshold() { return options.getOption(IN_SUBQUERY_THRESHOLD); }
Source:
public List<SqlNode> getOperandList() { START List<SqlNode> ops = Lists.newArrayList(); END ops.add(tableName); ops.add(SqlLiteral.createBoolean(tableExistenceCheck, SqlParserPos.ZERO)); return ops; } Use `ImmutableList`

Target:
public List<SqlNode> getOperandList() { final List<SqlNode> ops = ImmutableList.of( tableName, SqlLiteral.createBoolean(tableExistenceCheck, SqlParserPos.ZERO) ); return ops; }
Source:
START public void start() { END if (started) { return; } synchronized (queuedEvents) { started = true; isProcessing = true; } processEvents(); } Please add docs here.

Target:
public void start() { synchronized (queuedEvents) { if (started) { return; } started = true; isProcessing = true; } processEvents(); }
Source:
public FormatCreator getFormatCreator(final Configuration fsConf) { START if (formatCreator == null) { END formatCreator = new FormatCreator(dContext, fsConf, fsConfig, dContext.getClasspathScan()); } return formatCreator; } Is the `FormatCreator` instance tied to some settings in `fsConf`? If yes, wouldn't a subsequent invocation of this function ignore the passed `fsConf` with different values of such settings?

Target:
public FormatCreator getFormatCreator(final Configuration fsConf) { return new FormatCreator(dContext, fsConf, fsConfig, dContext.getClasspathScan()); }
Source:
START protected String getBaseTableLocation() { END final FormatSelection origSelection = (FormatSelection) table.getSelection(); return origSelection.getSelection().selectionRoot; } I do not find this method being used outside this class. Is it intentional?

Target:
private String getBaseTableLocation() { final FormatSelection origSelection = (FormatSelection) table.getSelection(); return origSelection.getSelection().selectionRoot; }
Source:
public void testSubmitPlanSingleNode() throws Exception { startCluster(1); START DrillClient client = DrillClient.newBuilder().build(); END client.connect(); List<QueryDataBatch> results = client.runQuery(QueryType.LOGICAL, plan); for (QueryDataBatch result : results) { System.out.println(result); result.release(); } client.close(); } Let's keep the default constructor to be the same as the default builder. No reason to force a builder when there are no properties.

Target:
public void testSubmitPlanSingleNode() throws Exception { startCluster(1); DrillClient client = new DrillClient(); client.connect(); List<QueryDataBatch> results = client.runQuery(QueryType.LOGICAL, plan); for (QueryDataBatch result : results) { System.out.println(result); result.release(); } client.close(); }
Source:
public boolean isTypeInferenceEnabled() { START return options.getOption(TYPE_INFERENCE.getOptionName()).bool_val; END } ``` java return option.getOption(TYPE_INFERENCE); ```

Target:
public boolean isTypeInferenceEnabled() { return options.getOption(TYPE_INFERENCE); }
Source:
public void close() { if (hjHelper != null) { hjHelper.clear(); } // If we didn't receive any data, hyperContainer may be null, check before clearing if (hyperContainer != null) { hyperContainer.clear(); } if (hashTable != null) { hashTable.clear(); } container.clear(); START outputAllocator.close(); END super.close(); } outputAllocator can be null, right ?

Target:
public void close() { if (hjHelper != null) { hjHelper.clear(); } // If we didn't receive any data, hyperContainer may be null, check before clearing if (hyperContainer != null) { hyperContainer.clear(); } if (hashTable != null) { hashTable.clear(); } container.clear(); if (outputAllocator != null) { outputAllocator.close(); } super.close(); }
Source:
protected FileSelection(final FileSelection selection) { Preconditions.checkNotNull(selection, "selection cannot be null"); this.statuses = selection.statuses; this.files = selection.files; this.selectionRoot = selection.selectionRoot; START this.dirStatus = new BitSet(StatusType.values().length); END } Should this constructor copy the dirStatus from the input "selection" as well?

Target:
protected FileSelection(final FileSelection selection) { Preconditions.checkNotNull(selection, "selection cannot be null"); this.statuses = selection.statuses; this.files = selection.files; this.selectionRoot = selection.selectionRoot; this.dirStatus = selection.dirStatus; }
Source:
public void close() throws Exception { START profileStore.close(); END transientProfiles.close(); } AutoCloseables.close(...)

Target:
public void close() throws Exception { }
Source:
public <V> TransientStore<V> getOrCreateTransientStore(final TransientStoreConfig<V> config) { final ZkEphemeralStore<V> store = (ZkEphemeralStore<V>)factory.getOrCreateStore(config); try { START store.start(); END } catch (final Exception e) { throw new DrillRuntimeException("unable to start zookeeper transient store", e); } return store; } Accessing profiles will trigger starting the store again, which will cause an "already started" exception.

Target:
public <V> TransientStore<V> getOrCreateTransientStore(final TransientStoreConfig<V> config) { final ZkEphemeralStore<V> store = (ZkEphemeralStore<V>)factory.getOrCreateStore(config); return store; }
Source:
private void updatePeak() { final long currentMemory = locallyHeldMemory.get(); while (true) { final long previousPeak = peakAllocation.get(); if (currentMemory > previousPeak) { if (peakAllocation.compareAndSet(previousPeak, currentMemory)) { // if we're able to update peak, finish. return; } else { // peak allocation changed underneath us. try again. continue; } } else { return; } START } END } Is this loop equivalent to the following? ``` do { final long previousPeak = peakAllocation.get(); if (peakAllocation.compareAndSet(previousPeak, currentMemory)) { // if we're able to update peak, finish. return; } } while(currentMemory > previousPeak) ``` that feels more natural to me.

Target:
private void updatePeak() { final long currentMemory = locallyHeldMemory.get(); long previousPeak; do { previousPeak = peakAllocation.get(); if (peakAllocation.compareAndSet(previousPeak, currentMemory)) { // if we're able to update peak, finish. return; } } while (currentMemory > previousPeak); }
Source:
private void childClosed(final BaseAllocator childAllocator) { if (DEBUG) { Preconditions.checkArgument(childAllocator != null, "child allocator can't be null"); synchronized (DEBUG_LOCK) { final Object object = childAllocators.remove(childAllocator); if (object == null) { childAllocator.historicalLog.logHistory(logger); START throw new IllegalStateException("Child allocator[" + childAllocator.id END + "] not found in parent allocator[" + id + "]'s childAllocators"); } } } } any reason we use `allocator.id` here and `name` in other places ? it makes it harder to follow the logs because we don't know which `id` corresponds to which `name`

Target:
private void childClosed(final BaseAllocator childAllocator) { if (DEBUG) { Preconditions.checkArgument(childAllocator != null, "child allocator can't be null"); synchronized (DEBUG_LOCK) { final Object object = childAllocators.remove(childAllocator); if (object == null) { childAllocator.historicalLog.logHistory(logger); throw new IllegalStateException("Child allocator[" + childAllocator.name + "] not found in parent allocator[" + name + "]'s childAllocators"); } } } }
Source:
public void eval() { org.apache.drill.exec.util.ByteBufUtil.checkBufferLength(in.buffer, in.start, in.end, 8); in.buffer.readerIndex(in.start); long epochMillis = Long.reverseBytes(in.buffer.readLong()); START in.buffer.readerIndex(0); END long millsOfDay = epochMillis % (24*3600*1000); out.value = epochMillis - millsOfDay; } Can you explain why this is necessary? It seems like the issue you are trying to resolve is related to whatever comes after this function rather than an issue with this function. There should not be any guarantees about the reader index of a Drillbuf (in fact, we should remove this from being exposed in functions). See how this function positions the reader before doing anything else. Is there some other operation which doesn't position the reader? We should apply the fix there.

Target:
public void eval() { org.apache.drill.exec.util.ByteBufUtil.checkBufferLength(in.buffer, in.start, in.end, 8); in.buffer.readerIndex(in.start); long epochMillis = Long.reverseBytes(in.buffer.readLong()); long millsOfDay = epochMillis % (24*3600*1000); out.value = epochMillis - millsOfDay; }
Source:
public SequenceFileRecordReader(final FileSplit split, final DrillFileSystem dfs, final String queryUserName, final String opUserName) { START final List<SchemaPath> columns = new ArrayList(); END columns.add(keySchema); columns.add(valueSchema); setColumns(columns); this.dfs = dfs; this.split = split; this.queryUserName = queryUserName; this.opUserName = opUserName; } new ArrayList<>();

Target:
public SequenceFileRecordReader(final FileSplit split, final DrillFileSystem dfs, final String queryUserName, final String opUserName) { final List<SchemaPath> columns = new ArrayList<>(); columns.add(keySchema); columns.add(valueSchema); setColumns(columns); this.dfs = dfs; this.split = split; this.queryUserName = queryUserName; this.opUserName = opUserName; }
Source:
public static boolean isUnion(MajorType toType) { START if (toType.getMinorType() == MinorType.UNION) { END return true; } return false; } probably better as return toType.getMinorType() == MinorType.UNION;

Target:
public static boolean isUnion(MajorType toType) { return toType.getMinorType() == MinorType.UNION; }
Source:
public void putChild(String name, ValueVector vector) { START putVector(name, vector); END field.addChild(vector.getField()); } If we're making this more public, isn't there some way we can verify that what is being loaded is right? Also, why isn't protected enough?

Target:
protected void putChild(String name, ValueVector vector) { putVector(name, vector); field.addChild(vector.getField()); }
Source:
protected void killIncoming(boolean sendUpstream) { START close(); END left.kill(sendUpstream); right.kill(sendUpstream); } You shouldn't call close here. I believe that should come from the FragmentExecutor.

Target:
protected void killIncoming(boolean sendUpstream) { left.kill(sendUpstream); right.kill(sendUpstream); }
Source:
public int getBufferSizeFor(int valueCount) { if (getAccessor().getValueCount() == 0) { return 0; } START return offsets.getBufferSizeFor(valueCount) + vector.getBufferSizeFor(valueCount); END } This first one should be passed valueCount +1 right? As was done in VariableLengthVectors.java

Target:
public int getBufferSizeFor(int valueCount) { if (valueCount == 0) { return 0; } return offsets.getBufferSizeFor(valueCount + 1) + vector.getBufferSizeFor(valueCount); }
Source:
public void deleteOption(final String name, final OptionType type) { try { SystemOptionManager.getValidator(name); // ensure the option exists } catch (final IllegalArgumentException e) { throw UserException.validationError(e) .build(logger); } // fallback if unable to delete locally START if (!deleteLocalOption(name, type)) { END fallback.deleteOption(name, type); } } you should call `name.toLowerCase()` here to make sure implementation will always be case insensitive.

Target:
public void deleteOption(final String name, final OptionType type) { SystemOptionManager.getValidator(name); // ensure the option exists // fallback if unable to delete locally if (!deleteLocalOption(name, type)) { fallback.deleteOption(name, type); } }
Source:
public void shutdownIfClient() { if (bus.isClient()) { try { Closeables.close(bus, true); START } catch (Exception e) { /* do nothing */ } END } } Any particular reason you added this ? is it safe to just ignore runtime exceptions here ?

Target:
public void shutdownIfClient() throws IOException { if (bus.isClient()) { Closeables.close(bus, true); } }
Source:
public void sort(SelectionVector4 vector4, VectorContainer container){ START Stopwatch watch = Stopwatch.createStarted(); END watch.start(); QuickSort qs = new QuickSort(); qs.sort(this, 0, vector4.getTotalCount()); logger.debug("Took us to sort records", watch.elapsed(TimeUnit.MICROSECONDS), vector4.getTotalCount()); } forgot to remove `watch.start()`

Target:
public void sort(SelectionVector4 vector4, VectorContainer container){ Stopwatch watch = Stopwatch.createStarted(); QuickSort qs = new QuickSort(); qs.sort(this, 0, vector4.getTotalCount()); logger.debug("Took us to sort records", watch.elapsed(TimeUnit.MICROSECONDS), vector4.getTotalCount()); }
Source:
START public synchronized static Set<Class<? extends StoragePluginConfig>> getSubTypes(final ScanResult classpathScan) { END final Set<Class<? extends StoragePluginConfig>> packages = classpathScan.getImplementations(StoragePluginConfig.class); logger.debug("Found logical operator classes: {}.", packages.size(), packages); return packages; } does this still need synchronized?

Target:
public static Set<Class<? extends StoragePluginConfig>> getSubTypes(final ScanResult classpathScan) { final Set<Class<? extends StoragePluginConfig>> packages = classpathScan.getImplementations(StoragePluginConfig.class); logger.debug("Found logical operator classes: {}.", packages.size(), packages); return packages; }
Source:
public DrillResultSetImpl newResultSet(AvaticaStatement statement, AvaticaPrepareResult prepareResult, TimeZone timeZone) { final ResultSetMetaData metaData = newResultSetMetaData(statement, prepareResult.getColumnList()); return new DrillResultSetImpl(statement, START (DrillPrepareResult) prepareResult, END metaData, timeZone); } Cast here is redundant here, DrillResultSetImpl() is expecting an AvaticaPrepareResult object

Target:
public DrillResultSetImpl newResultSet(AvaticaStatement statement, AvaticaPrepareResult prepareResult, TimeZone timeZone) { final ResultSetMetaData metaData = newResultSetMetaData(statement, prepareResult.getColumnList()); return new DrillResultSetImpl(statement, prepareResult, metaData, timeZone); }
Source:
public static SessionMap create(Config config) { Tracer tracer = new LoggingOptions(config).getTracer(); EventBus bus = new EventBusOptions(config).getEventBus(); JdbcSessionMapOptions sessionMapOptions = new JdbcSessionMapOptions(config); Connection connection; try { connection = sessionMapOptions.getJdbcConnection(); } catch (SQLException e) { START throw new ConfigException(e.toString()); END } return new JdbcBackedSessionMap(tracer, connection, bus); } Maybe add the underlying exception too? `new ConfigException(e)`

Target:
public static SessionMap create(Config config) { Tracer tracer = new LoggingOptions(config).getTracer(); EventBus bus = new EventBusOptions(config).getEventBus(); JdbcSessionMapOptions sessionMapOptions = new JdbcSessionMapOptions(config); Connection connection; try { connection = sessionMapOptions.getJdbcConnection(); } catch (SQLException e) { throw new ConfigException(e); } return new JdbcBackedSessionMap(tracer, connection, bus); }
Source:
public void tearDown() { START if (authenticator != null) END ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator); } Nit: we tend to always use braces in the selenium codebase. It makes it harder to cause chaos accidentally :)

Target:
public void tearDown() { if (authenticator != null) { ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator); } }
Source:
public static Collection<Supplier<Object[]>> buildGrids() { return ImmutableSet.of( () -> { try { return createRemotes(); START } catch (URISyntaxException | SSLException | CertificateException e) { END throw new RuntimeException(e); } }, () -> { try { return createInMemory(); } catch (Exception e) { throw new RuntimeException(e); } }); } Nit please alphabetise.

Target:
public static Collection<Supplier<Object[]>> buildGrids() { return ImmutableSet.of( () -> { try { return createRemotes(); } catch (CertificateException | SSLException | URISyntaxException e) { throw new RuntimeException(e); } }, () -> { try { return createInMemory(); } catch (Exception e) { throw new RuntimeException(e); } }); }
Source:
public boolean equals(Object o) { START if (this == o) { END return true; } if (o == null || getClass() != o.getClass()) { return false; } Select select = (Select) o; return Objects.equals(element, select.element); } Nowadays, we tend to follow a pattern of: ``` if (!(o instanceof Select)) { return false; } Select that = (Select) o; return Objects.equals(this.element, that.element); ```

Target:
public boolean equals(Object o) { if (!(o instanceof Select)) { return false; } Select select = (Select) o; return Objects.equals(element, select.element); }
Source:
public ChromeOptions merge(Capabilities extraCapabilities) { super.merge(extraCapabilities); if (extraCapabilities instanceof ChromeOptions) { START Map options = (Map) extraCapabilities.asMap().get("goog:chromeOptions"); END mergeArguments(options); mergeExtensions(options); mergeExtensionFiles(extraCapabilities); mergeBinary(options); mergeExperimentalOptions(extraCapabilities); } return this; } Please use generics. If there's no obvious type, the `Map<?, ?>` prevents compiler warnings, is correct, and is equally meaningless :)

Target:
public ChromeOptions merge(Capabilities extraCapabilities) { super.merge(extraCapabilities); return this; }
Source:
public FirefoxOptions merge(Capabilities capabilities) { super.merge(capabilities); if (capabilities instanceof FirefoxOptions) { START Map options = (Map) capabilities.asMap().get("moz:firefoxOptions"); END mergeArguments(options); mergeBooleanPrefs(capabilities); mergeIntPrefs(capabilities); mergeStringPrefs(capabilities); mergeLogLevel(capabilities); } return this; } Generics, please!

Target:
public FirefoxOptions merge(Capabilities capabilities) { super.merge(capabilities); return this; }
Source:
START public void merge(GridHubConfiguration other) { END super.merge(other); if (other.jettyMaxThreads != null) jettyMaxThreads = other.jettyMaxThreads; capabilityMatcher = other.capabilityMatcher; if (other.newSessionWaitTimeout != null) newSessionWaitTimeout = other.newSessionWaitTimeout; if (other.prioritizer != null) prioritizer = other.prioritizer; if (other.throwOnCapabilityNotPresent != throwOnCapabilityNotPresent) throwOnCapabilityNotPresent = other.throwOnCapabilityNotPresent; } There should be an `@Override` annotation here. Most IDEs will be busy freaking out at you, and some java versions won't compile the code.

Target:
public void merge(GridHubConfiguration other) { super.merge(other); if (other.jettyMaxThreads != null) { jettyMaxThreads = other.jettyMaxThreads; } capabilityMatcher = other.capabilityMatcher; if (other.newSessionWaitTimeout != null) { newSessionWaitTimeout = other.newSessionWaitTimeout; } if (other.prioritizer != null) { prioritizer = other.prioritizer; } if (other.throwOnCapabilityNotPresent != throwOnCapabilityNotPresent) { throwOnCapabilityNotPresent = other.throwOnCapabilityNotPresent; } }
Source:
private static Optional<Extension> loadCustomExtension() { String xpiProperty = System.getProperty(FirefoxDriver.SystemProperty.DRIVER_XPI_PROPERTY); START if (xpiProperty != null && !xpiProperty.equals("")) { END File xpi = new File(xpiProperty); return Optional.of((Extension) new FileExtension(xpi)); } return Optional.absent(); } instead of empty string, we probably should check that the File exists (next line down). Then log a warning if it doesn't and continue otherwise.

Target:
private static Extension loadCustomExtension() { String xpiProperty = System.getProperty(FirefoxDriver.SystemProperty.DRIVER_XPI_PROPERTY); if (xpiProperty != null) { File xpi = new File(xpiProperty); if (xpi.exists()) { return new FileExtension(xpi); } } return null; }
Source:
public TkWithAliasHeader(final Base base, final Take take) { this.base = base; this.take = take; this.header = START String.format("%s: %s", "X-Netbout-Alias", "%s"); END } @kujtimiihoxha Why not just `"X-Netbout-Alias: %s"` ?

Target:
public TkWithAliasHeader(final Base base, final Take take) { this.base = base; this.take = take; }
Source:
START public int allocate() throws IOException { END synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; // @checkstyle MagicNumber (1 line) if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } @danff should be declared `static`

Target:
public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; // @checkstyle MagicNumber (1 line) if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } }
Source:
private Ports() { START super(); END } @danff do we need to call `super()` here?

Target:
private Ports() { }
Source:
private static RqRegex request(final String code) throws Exception { return new RqRegex.Fake( START PATTERN, END URLEncoder.encode(TkEmVerifyTest.ENC.encrypt(code), "UTF-8") ); } @kujtimiihoxha statics should be prependended with class name, so here it should be TkEmVerifyTest.PATTERN

Target:
private static RqRegex request(final String code) throws Exception { return new RqRegex.Fake( TkEmVerifyTest.PATTERN, URLEncoder.encode(TkEmVerifyTest.ENC.encrypt(code), "UTF-8") ); }
Source:
public void rendersPage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(URN.create(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkIndex(base).act( new RqWithHeader( new RqWithAuth(urn), "Accept", "text/xml" ) START )).printBody(), END XhtmlMatchers.hasXPaths( "/page/alias/email", "/page/links/link[@rel='save-email']/@href" ) ); } @exper0 let's move the final `).printBody(),` to the next line to maintain correct indentation.

Target:
public void rendersPage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(URN.create(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkIndex(base).act(new RqWithAuth(urn)) ).printBody(), XhtmlMatchers.hasXPaths( "/page/alias/email", "/page/links/link[@rel='save-email']/@href" ) ); }
Source:
public void throwsExceptionIfUnknownAliasKicked() throws Exception { START final Inbox inbox = this.rule.get().aliases() END .iterate().iterator().next().inbox(); final Bout bout = inbox.bout(inbox.start()); final String friend = "jim"; bout.friends().kick(friend); } @dmzaytsev All variables here are still single-use variables, we can inline everything (i.e. make the whole test a single statement).

Target:
public void throwsExceptionIfUnknownAliasKicked() throws Exception { final Inbox inbox = this.rule.get().aliases() .iterate().iterator().next().inbox(); inbox.bout(inbox.start()).friends().kick("jim"); }
Source:
private static String generateAuthenticateHead( final String user, final String pass ) { final String auth = String.format("%s:%s", user, pass); START final String encoded = DatatypeConverter.printBase64Binary( END auth.getBytes() ); return String.format("Authorization: Basic %s", encoded); } @dmzaytsev let's inline this

Target:
private static String generateAuthenticateHead( final String user, final String pass ) { return String.format( "Authorization: Basic %s", DatatypeConverter.printBase64Binary( String.format("%s:%s", user, pass).getBytes() ) ); }
Source:
public void post(final String text) throws IOException { this.origin.post(text); for (final Friend friend : this.bout.friends().iterate()) { START if (friend.email().isEmpty() || this.self == friend.alias()) { END continue; } this.email(friend, text); } } @ndbroadbent use `.equals` here.

Target:
public void post(final String text) throws IOException { this.origin.post(text); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || this.self.equals(friend.alias())) { continue; } this.email(friend, text); } }
Source:
START public void updateItem(T item) { END mAlgorithm.lock(); try { mAlgorithm.updateItem(item); } finally { mAlgorithm.unlock(); } } Thoughts on returning a bool here? It could be helpful to know if an item you are trying to update was actually updated or not (and if not, can signal to the developer that they need to implement equals and hashcode).

Target:
public boolean updateItem(T item) { mAlgorithm.lock(); try { return mAlgorithm.updateItem(item); } finally { mAlgorithm.unlock(); } }
Source:
public boolean addItems(Collection<T> items) { boolean result; mAlgorithm.lock(); try { START result = mAlgorithm.addItems(items); END } finally { mAlgorithm.unlock(); } return result; } The `result` variable is not needed—the block within `finally` will still be invoked even after a `return`.

Target:
public boolean addItems(Collection<T> items) { mAlgorithm.lock(); try { return mAlgorithm.addItems(items); } finally { mAlgorithm.unlock(); } }
Source:
static XmlPullParser createParser(@IdRes int res) throws XmlPullParserException, IOException { InputStream stream = InstrumentationRegistry.getInstrumentation() .getTargetContext() .getResources() .openRawResource(res); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser parser = factory.newPullParser(); parser.setInput(stream, null); START parser.next(); END return parser; } Why does `next` have to be invoked here?

Target:
static XmlPullParser createParser(@IdRes int res) throws XmlPullParserException, IOException { InputStream stream = InstrumentationRegistry.getInstrumentation() .getTargetContext() .getResources() .openRawResource(res); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser parser = factory.newPullParser(); parser.setInput(stream, null); return parser; }
Source:
/* package */ void setFillColor(String color) { // Tolerate KML with leading or trailing whitespace in colors START color = color.trim(); END // Add # to allow for mOutline color to be parsed correctly int polygonColorNum = (Color.parseColor("#" + convertColor(color))); setPolygonFillColor(polygonColorNum); mStylesSet.add("fillColor"); } How about applying this method inside `convertColor` to avoid duplication and to make sure the same input sanitation is applied? Looks like in all cases `color.trim()` is desired before calling `convertColor` anyway.

Target:
/* package */ void setFillColor(String color) { // Add # to allow for mOutline color to be parsed correctly int polygonColorNum = (Color.parseColor("#" + convertColor(color))); setPolygonFillColor(polygonColorNum); mStylesSet.add("fillColor"); }
Source:
private void removePlacemarks(HashMap<? extends Feature, Object> placemarks) { // Remove map object from the map START super.removeFeatures((HashMap<Feature, Object>) placemarks); END } `super` reference can be removed here, as `removeFeatures()` is static.

Target:
private void removePlacemarks(HashMap<? extends Feature, Object> placemarks) { // Remove map object from the map removeFeatures((HashMap<Feature, Object>) placemarks); }
Source:
public final static byte[] decode(byte[] sArr, int sOff, int sLen) throws DecodeException { try { return doDecode(sArr, sOff, sLen); START } catch (Exception e) { END throw new DecodeException(e); } } is RuntimeException enough?

Target:
public final static byte[] decode(byte[] sArr, int sOff, int sLen) throws DecodeException { try { return doDecode(sArr, sOff, sLen); } catch (RuntimeException e) { throw new DecodeException(e); } }
Source:
START public BinaryBlockWriter(OutputStream out, Class<M> protoClass, BinaryConverter<M> binaryConverter, int numRecordsPerBlock) { END out_ = out; numRecordsPerBlock_ = numRecordsPerBlock; innerClass_ = protoClass; binaryConverter_ = binaryConverter; protoBlobs_ = new ArrayList<ByteString>(numRecordsPerBlock_); } Do you need this to become public? looks like you have a new public one below?

Target:
protected BinaryBlockWriter(OutputStream out, Class<M> protoClass, BinaryConverter<M> binaryConverter, int numRecordsPerBlock) { out_ = out; numRecordsPerBlock_ = numRecordsPerBlock; innerClass_ = protoClass; binaryConverter_ = binaryConverter; protoBlobs_ = new ArrayList<ByteString>(numRecordsPerBlock_); }
Source:
public LzoGenericB64LineRecordReader(TypeRef<M> typeRef, BinaryConverter<M> converter) { super(typeRef, new GenericWritable<M>(converter), converter); START LOG.info("record type is " + typeRef.getRawClass()); END } Don't think this adds anything anymode, the typeRef will just be the convertors creator. I'd just kill the log line

Target:
public LzoGenericB64LineRecordReader(TypeRef<M> typeRef, BinaryConverter<M> converter) { super(typeRef, new GenericWritable<M>(converter), converter); }
Source:
public LzoGenericBlockRecordReader(TypeRef<M> typeRef, BinaryConverter<M> binaryConverter) { super(typeRef, new BinaryBlockReader(null, binaryConverter), new GenericWritable<M>(binaryConverter)); START LOG.info("LzoGenericBlockRecordReader, type args are " + typeRef.getRawClass()); END } kill

Target:
public LzoGenericBlockRecordReader(TypeRef<M> typeRef, BinaryConverter<M> binaryConverter) { super(typeRef, new BinaryBlockReader(null, binaryConverter), new GenericWritable<M>(binaryConverter)); }
Source:
START public boolean readProtobuf(ProtobufWritable<M> message) throws Exception { END return readNext(message); } Exception is super generic and is usually an anti-pattern. Any reason for this change?

Target:
public boolean readProtobuf(ProtobufWritable<M> message) throws IOException { return readNext(message); }
Source:
public RecordReader createRecordReader( InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException { Configuration conf = HadoopCompat.getConfiguration(taskAttemptContext); initInputFormat(conf); if (shouldCombine(conf)) { return new CompositeRecordReader(delegate); } else { try { return delegate.createRecordReader(inputSplit, taskAttemptContext); } catch (InterruptedException e) { LOG.error("Thread interrupted", e); Thread.currentThread().interrupt(); throw new IOException(e); START } END } } you can just ``` } catch (InterruptedException e) { throw new IOException(e); } ``` Throwing an exception is the right answer here but there's no point setting the thread interrupt flag. See: http://docs.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html "Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect: if (Thread.interrupted()) // Clears interrupted status! throw new InterruptedException(); "

Target:
public RecordReader createRecordReader( InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { Configuration conf = HadoopCompat.getConfiguration(taskAttemptContext); initInputFormat(conf); if (shouldCombine(conf)) { return new CompositeRecordReader(delegate); } else { return delegate.createRecordReader(inputSplit, taskAttemptContext); } }
Source:
private static <T extends InputSplit> T deserializeInputSplitInternal( Configuration conf, DataInputStream in, Class<T> clazz) throws IOException { T split = ReflectionUtils.newInstance(clazz, conf); SerializationFactory factory = new SerializationFactory(conf); Deserializer<T> deserializer = factory.getDeserializer(clazz); START deserializer.open(new UncloseableDataInputStream((DataInputStream) in)); END return deserializer.deserialize(split); } you have several layers of wrapping into UncloseableDataInputStream if not one. It looks like it should be done only once in this method.

Target:
private static <T extends InputSplit> T deserializeInputSplitInternal( Configuration conf, DataInputStream in, Class<T> clazz) throws IOException { T split = ReflectionUtils.newInstance(clazz, conf); SerializationFactory factory = new SerializationFactory(conf); Deserializer<T> deserializer = factory.getDeserializer(clazz); deserializer.open(in instanceof UncloseableDataInputStream ? in : new UncloseableDataInputStream(in)); return deserializer.deserialize(split); }
Source:
public RecordWriter<K, V> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { START if (wrapped.realOutputFormat instanceof WorkFileOverride) { END ((WorkFileOverride) wrapped.realOutputFormat).setName(name); } return wrapped.getRecordWriter(ignored, job, name, progress); } right, I meant we could do this in DeprecatedOutputFormatWrapper. I agree, we can't avoid an interface like WorkFileOverride, since we can't really override getDefaultWorkFile for given _object_ ('realOutputFormat' in this case).

Target:
public RecordWriter<K, V> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { return wrapped.getRecordWriter(ignored, job, name, progress); }
Source:
public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { // set required fields conf for RCFile[Protobuf|Thrift] input format if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, Joiner.on(",").join(indices)); START } else { END conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, ""); } } prefer: ``` String value = ""; if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } value = Joiner.on(",").join(indices); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, value); ```

Target:
public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { // set required fields conf for RCFile[Protobuf|Thrift] input format String value = ""; if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } value = Joiner.on(",").join(indices); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, value); }
Source:
public static void setConversionProperties(Configuration conf) { if (conf != null) { useEnumId = conf.getBoolean(USE_ENUM_ID_CONF_KEY, false); START LOG.info("useEnumId is set to " + useEnumId); END } } can you make this a debug log? It would be easy to see if this config does not take affect. Pig creates multiple of these loaders and we will see lots of these in the log.

Target:
public static void setConversionProperties(Configuration conf) { if (conf != null) { useEnumId = conf.getBoolean(USE_ENUM_ID_CONF_KEY, false); LOG.debug("useEnumId is set to " + useEnumId); } }
Source:
public void initialize(Configuration conf, Properties tbl) throws SerDeException { try { String className = tbl START .getProperty(org.apache.hadoop.hive.serde.Constants.SERIALIZATION_CLASS); END protobufClass = conf.getClassByName(className).asSubclass(Message.class); protobufConverter = ProtobufConverter.newInstance(new TypeRef<Message>(protobufClass){}); } catch (Exception e) { throw new SerDeException(e); } } Nit - import Constants so this all fits on one line.

Target:
public void initialize(Configuration conf, Properties tbl) throws SerDeException { try { String className = tbl.getProperty(Constants.SERIALIZATION_CLASS); protobufClass = conf.getClassByName(className).asSubclass(Message.class); protobufConverter = ProtobufConverter.newInstance(protobufClass); } catch (Exception e) { throw new SerDeException(e); } }
Source:
protected void skipToNextSyncPoint(boolean atFirstRecord) throws IOException { // No need to skip to the sync point here; the block reader will do it for us. LOG.debug("LzoProtobufBlockRecordReader.skipToNextSyncPoint called with atFirstRecord = " + atFirstRecord); updatePosition = !atFirstRecord; START LOG.debug("reset first record offset in skipToNextSyncPoint()"); END } there is already a debug message above.

Target:
protected void skipToNextSyncPoint(boolean atFirstRecord) throws IOException { // No need to skip to the sync point here; the block reader will do it for us. LOG.debug("LzoProtobufBlockRecordReader.skipToNextSyncPoint called with atFirstRecord = " + atFirstRecord); updatePosition = !atFirstRecord; }
Source:
private Map<String,Object> walkJson(JSONObject jsonObj) { Map<String,Object> v = Maps.newHashMap(); for (Object key: jsonObj.keySet()) { START if (fields == null || fields.contains(key.toString())) END v.put(key.toString(), wrap(jsonObj.get(key))); } return v; } thanks. Let us know one this is ready to go. btw, you could skip map copy in the common case where no fields are set.

Target:
private Map<String,Object> walkJson(JSONObject jsonObj) { Map<String,Object> v = Maps.newHashMap(); for (Object key: jsonObj.keySet()) { v.put(key.toString(), wrap(jsonObj.get(key))); } return v; }
Source:
protected BinaryBlockReader(InputStream in, BinaryConverter<M> protoConverter, boolean skipEmptyRecords) { in_ = in; protoConverter_ = protoConverter; START skipEmptyBlobs = skipEmptyRecords; END searcher_ = new StreamSearcher(Protobufs.KNOWN_GOOD_POSITION_MARKER); } what's the difference between blobs and records? why use 2 terms?

Target:
protected BinaryBlockReader(InputStream in, BinaryConverter<M> protoConverter, boolean skipEmptyRecords) { in_ = in; protoConverter_ = protoConverter; searcher_ = new StreamSearcher(Protobufs.KNOWN_GOOD_POSITION_MARKER); this.skipEmptyRecords = skipEmptyRecords; }
Source:
public JsonLoader(String inputFormatClassName) { this.inputFormatClassName = inputFormatClassName; try { START this.inputFormat = (FileInputFormat) Class.forName(inputFormatClassName).newInstance(); END } catch (InstantiationException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } catch (IllegalAccessException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } catch (ClassNotFoundException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } } should be moved to getInputFormat(). need to use PigContext.resolveClasName() for Pig loaders.

Target:
public JsonLoader(String inputFormatClassName) { this.inputFormatClassName = inputFormatClassName; }
Source:
public InputFormat getInputFormat() throws IOException { START if (inputFormat != null) { END return inputFormat; } else { try { inputFormat = (FileInputFormat) PigContext.resolveClassName(inputFormatClassName).newInstance(); return inputFormat; } catch (InstantiationException e) { throw new IOException("Failed creating input format " + inputFormatClassName, e); } catch (IllegalAccessException e) { throw new IOException("Failed creating input format " + inputFormatClassName, e); } } } This could just return (InputFormat) PigContext.resolveClassName(inputFormatName).newInstance(); resolveClassName throws only IOException.

Target:
public InputFormat getInputFormat() throws IOException { try { return (FileInputFormat) PigContext.resolveClassName(inputFormatClassName).newInstance(); } catch (InstantiationException e) { throw new IOException("Failed creating input format " + inputFormatClassName, e); } catch (IllegalAccessException e) { throw new IOException("Failed creating input format " + inputFormatClassName, e); } }
Source:
public void onPause() { super.onPause(); START if (getAllowStartStopFromHeadsetKey()) { END unregisterHeadsetListener(); } unRegisterStartStopListener(); } isn't this the same bug that you had before, that headset wasn't working while app was minimized ?

Target:
public void onPause() { super.onPause(); }
Source:
private boolean matchesAnyCookieName(String cookieString, String... cookieNames) { //noinspection SimplifiableIfStatement START if (StringUtils.isEmpty(cookieString) || ArrayUtils.isEmpty(cookieNames)) { END return false; } return Arrays.stream(cookieNames).anyMatch(name -> matchesCookieName(cookieString, name)); } Why this separate `if` statement and not just `return isEmpty(cookieString) || isEmpty(cookieNames) || Arrays.stream(...`?

Target:
private boolean matchesAnyCookieName(String cookieString, String... cookieNames) { boolean isEmpty = StringUtils.isEmpty(cookieString) || ArrayUtils.isEmpty(cookieNames); return isEmpty || Arrays.stream(cookieNames) .anyMatch(name -> matchesCookieName(cookieString, name)); }