auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int getCount() throws InterruptedException, KeeperException { START ZKUtil.FutureWatcher fw = new ZKUtil.FutureWatcher(); END return ByteBuffer.wrap(m_zk.getData(m_path, fw, null)).getInt(); } Is this FutureWatcher needed here? I don't know what's the purpose of this watcher. The method await() above calls get() on it after getting ZK data.

Target:
public int getCount() throws InterruptedException, KeeperException { return ByteBuffer.wrap(m_zk.getData(m_path, false, null)).getInt(); }
Source:
VoltTableSpliterator(VoltTable table, int origin, int fence) { System.out.printf("New VTS %d -> %d in Table with %d rows\n", origin, fence, table.getRowCount()); START System.out.flush(); END if (origin == fence) { m_row = null; return; } assert(origin < fence); m_row = table.fetchRow(origin); m_fence = fence; } Cleanup?

Target:
VoltTableSpliterator(VoltTable table, int origin, int fence) { m_fence = fence; if (origin == fence) { m_row = null; return; } assert(origin < fence); m_row = table.fetchRow(origin); }
Source:
public void reInitSysProc(CatalogContext catalogContext, CatalogSpecificPlanner csp) { assert(m_procedure != null); if (! m_isSysProc) { return; } START assert(m_procedure instanceof VoltSystemProcedure); END ((VoltSystemProcedure) m_procedure).initSysProc(m_site, catalogContext.cluster, catalogContext.getClusterSettings(), catalogContext.getNodeSettings()); m_csp = csp; } This assert is not needed since it will hit line 228 if the procedure is not a VoltSystemProcedure.

Target:
public void reInitSysProc(CatalogContext catalogContext, CatalogSpecificPlanner csp) { assert(m_procedure != null); if (! m_isSysProc) { return; } ((VoltSystemProcedure) m_procedure).initSysProc(m_site, catalogContext.cluster, catalogContext.getClusterSettings(), catalogContext.getNodeSettings()); m_csp = csp; }
Source:
public static Client createClient(ClientConfig config) { Client client = null; synchronized (ClientFactory.class) { if (!m_preserveResources && ++m_activeClientCount == 1) { VoltLogger.startAsynchronousLogging(); EstTimeUpdater.start(); ReverseDNSCache.start(); } } START config.enableSSL(); END client = new ClientImpl(config, config.getSslContext()); return client; } What's up here? Does this always create SSL clients?

Target:
public static Client createClient(ClientConfig config) { Client client = null; synchronized (ClientFactory.class) { if (!m_preserveResources && ++m_activeClientCount == 1) { VoltLogger.startAsynchronousLogging(); EstTimeUpdater.start(); ReverseDNSCache.start(); } } client = new ClientImpl(config); return client; }
Source:
public void markHostMissing(boolean isMissing) { START if (isMissing) { END this.isMissing = true; } } Do you need the IF case here? Or does it has use case to set isMissing to be false?

Target:
public void markHostMissing(boolean isMissing) { this.isMissing = isMissing; }
Source:
public void testMultiPartitionCURRENT_TIMESTAMP() throws IOException, ProcCallException { START END if (!isHSQL()) { Client client = getClient(); client.callProcedure(CurrentTimestampProcedure.class.getSimpleName()); } } A positive test would be clearer here: if (isHSQL()) { return; }

Target:
public void testMultiPartitionCURRENT_TIMESTAMP() throws IOException, ProcCallException { if (isHSQL()) { return; } Client client = getClient(); client.callProcedure(CurrentTimestampProcedure.class.getSimpleName()); }
Source:
public void stopping(Connection c) { m_isUp = false; if (!m_closing) { START if (isPrimary()) { END if (!m_hostMessenger.isShuttingDown()) { VoltDB.dropStackTrace("Received remote hangup from foreign host " + hostnameAndIPAndPort()); hostLog.warn("Received remote hangup from foreign host " + hostnameAndIPAndPort()); } m_hostMessenger.reportForeignHostFailed(m_hostId); } } } Remove one wrap of IF by: if (!m_closing && isPrimary())

Target:
public void stopping(Connection c) { m_isUp = false; if (!m_closing && isPrimary()) { if (!m_hostMessenger.isShuttingDown()) { VoltDB.dropStackTrace("Received remote hangup from foreign host " + hostnameAndIPAndPort()); hostLog.warn("Received remote hangup from foreign host " + hostnameAndIPAndPort()); } m_hostMessenger.reportForeignHostFailed(m_hostId); } }
Source:
public String getHostnameForHostID(int hostId) { if (hostId == m_localHostId) { return CoreUtils.getHostnameOrAddress(); } Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator(); if (it.hasNext()) { ForeignHost fh = it.next(); return fh.hostname(); START } else { END return "UNKNOWN"; } } @luyangco You can remove the ELSE and return "UNKNOWN".

Target:
public String getHostnameForHostID(int hostId) { if (hostId == m_localHostId) { return CoreUtils.getHostnameOrAddress(); } Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator(); if (it.hasNext()) { ForeignHost fh = it.next(); return fh.hostname(); } return "UNKNOWN"; }
Source:
public void testFiveNodeK1TwoRacks() throws JSONException { START TestDescription td = getBoringDescription(5, 6, 1, 2, 1); END subTestDescription(td, false); } If leafCount is still 1, how could it be two rack groups?

Target:
public void testFiveNodeK1TwoRacks() throws JSONException { TestDescription td = getBoringDescription(5, 6, 1, 1, 2); subTestDescription(td, false); }
Source:
private TablePopulationRequirements getMVInfoMessage(Table table, MaterializedViewInfo mv) { START TablePopulationRequirements retval; END if (! mv.getIssafewithnonemptysources()) { String viewName = mv.getTypeName(); String sourceName = mv.getParent().getTypeName(); String errorMessage = createViewDisallowedMessage(viewName, sourceName); retval = new TablePopulationRequirements(viewName); retval.setErrorMessage(errorMessage); if ( ! m_newTables.contains(sourceName)) { retval.addTableName(sourceName); } return retval; } return null; } Merge declaration into block-scoped initialization statement (first use).

Target:
private TablePopulationRequirements getMVInfoMessage(Table table, MaterializedViewInfo mv) { TablePopulationRequirements retval; if (! mv.getIssafewithnonemptysources()) { String viewName = mv.getTypeName(); String sourceName = mv.getParent().getTypeName(); String errorMessage = createViewDisallowedMessage(viewName, sourceName); retval = new TablePopulationRequirements(viewName); retval.setErrorMessage(errorMessage); retval.addTableName(sourceName); return retval; } return null; }
Source:
public synchronized void close() throws IOException { if (m_closed) { return; } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } START m_segments.clear(); END m_closed = true; } Is this correct? It doesn't look right to forget about all segments on segment close, which just closes the FDs. What happens to the segment files on disk? Are they just leaked?

Target:
public synchronized void close() throws IOException { if (m_closed) { return; } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_closed = true; }
Source:
public void enqueue(final DeferredSerialization ds) { synchronized (this) { if (m_isShutdown) { ds.cancel(); return; } updateLastPendingWriteTimeAndQueueBackpressure(); if (m_isSSLConfigured) { Iterator<DeferredSerialization> dsIter = new SSLDeferredSerializationIterator(m_sslEngine, ds); while (dsIter.hasNext()) { START m_queuedWrites.offer(dsIter.next()); END } } else { m_queuedWrites.offer(ds); } m_port.setInterests( SelectionKey.OP_WRITE, 0); } } shouldn't this be more implemented using [drainTo](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#drainTo%28java.util.Collection%29) strategy?

Target:
public void enqueue(final DeferredSerialization ds) { synchronized (this) { if (m_isShutdown) { ds.cancel(); return; } updateLastPendingWriteTimeAndQueueBackpressure(); m_queuedWrites.offer(ds); m_port.setInterests( SelectionKey.OP_WRITE, 0); } }
Source:
public MockPort() throws UnknownHostException { START super(null, null, new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 21212), pool, null); END } These tests should have SSL. They dont depend on server.

Target:
public MockPort() throws UnknownHostException { super(null, null, new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 21212), pool); }
Source:
private DeferredSerialization dsOf(final ByteBuffer buf) { return new DeferredSerialization() { @Override public ByteBuffer serialize(final ByteBuffer outbuf) throws IOException { outbuf.put(buf); START return null; END } @Override public void cancel() @Override public int getSerializedSize() { return buf.remaining(); } }; } I thought for non ssl we return the same bytebuffer.

Target:
private DeferredSerialization dsOf(final ByteBuffer buf) { return new DeferredSerialization() { @Override public void serialize(final ByteBuffer outbuf) throws IOException { outbuf.put(buf); } @Override public void cancel() @Override public int getSerializedSize() { return buf.remaining(); } }; }
Source:
public SSLBufferDecrypter(SSLEngine sslEngine) { this.m_sslEngine = sslEngine; START this.m_srcBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); END this.m_dstBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); this.m_partialLength = ByteBuffer.allocate(4); } where are the corresponding cleaners for these direct byte buffer allocations?

Target:
public SSLBufferDecrypter(SSLEngine sslEngine) { this.m_sslEngine = sslEngine; }
Source:
public final void convertToHeapBuffer() { if (m_buffer.isDirect()) { // Either this was allocated by the stored procedure as a direct buffer cached // from the EE. If the second, we need to make a copy so the EE can reuse the // buffer fir the next stored procedure. START ByteBuffer heapBuffer = ByteBuffer.allocate(m_buffer.limit()); END m_buffer.position(0); heapBuffer.put(m_buffer); heapBuffer.position(heapBuffer.limit()); } } This is a nit, but should this be "can reuse the buffer FOR the next stored procedure"?

Target:
public final void convertToHeapBuffer() { if (m_buffer.isDirect()) { // Either this was allocated by the stored procedure as a direct buffer or this // is cached from the EE. If the second, we need to make a copy so the EE can // reuse the buffer for the next stored procedure. ByteBuffer heapBuffer = ByteBuffer.allocate(m_buffer.limit()); m_buffer.position(0); heapBuffer.put(m_buffer); m_buffer = heapBuffer; } }
Source:
private boolean hasTrivialCoordinator(AbstractPlanNode planNode) { PlanNodeType planNodeType = planNode.getPlanNodeType(); if (PlanNodeType.RECEIVE == planNodeType || PlanNodeType.MERGERECEIVE == planNodeType) { return true; START } else if (PlanNodeType.PROJECTION == planNodeType) { END assert(planNode.getChildCount() == 1); return hasTrivialCoordinator(planNode.getChild(0)); } return false; } no "else" required after return

Target:
private boolean hasTrivialCoordinator(AbstractPlanNode planNode) { PlanNodeType planNodeType = planNode.getPlanNodeType(); if (PlanNodeType.RECEIVE == planNodeType || PlanNodeType.MERGERECEIVE == planNodeType) { return true; } if (PlanNodeType.PROJECTION == planNodeType) { assert(planNode.getChildCount() == 1); return hasTrivialCoordinator(planNode.getChild(0)); } return false; }
Source:
private void updatePartitioning(VoltTable vt) { START List<Integer> ketSet = new ArrayList<Integer>(); END while (vt.advanceRow()) { //check for mock unit test if (vt.getColumnCount() == 2) { Integer key = (int)(vt.getLong("PARTITION_KEY")); ketSet.add(key); } } m_partitionKeys.set(ImmutableSet.copyOf(ketSet)); } is ketSet a typo? keySet? Or am I missing what ket is?

Target:
private void updatePartitioning(VoltTable vt) { List<Integer> keySet = new ArrayList<Integer>(); while (vt.advanceRow()) { //check for mock unit test if (vt.getColumnCount() == 2) { Integer key = (int)(vt.getLong("PARTITION_KEY")); keySet.add(key); } } m_partitionKeys.set(ImmutableSet.copyOf(keySet)); }
Source:
public void clientCallback(ClientResponse clientResponse) throws Exception { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { START synchronized (Distributer.this) { END VoltTable results[] = clientResponse.getResults(); if (results != null && results.length > 0) { updatePartitioning(results[0]); } } } m_partitionUpdateStatus.set(clientResponse); if (m_latch != null) { m_latch.countDown(); } } Does this have to be synchronized? What isn't thread-safe?

Target:
public void clientCallback(ClientResponse clientResponse) throws Exception { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { VoltTable results[] = clientResponse.getResults(); if (results != null && results.length > 0) { updatePartitioning(results[0]); } } m_partitionUpdateStatus.set(clientResponse); if (m_latch != null) { m_latch.countDown(); } }
Source:
default File resolve(File path) { START return path.isAbsolute() ? path : new VoltFile(getVoltDBRoot(), path.getPath()); END } You dont have to use VoltFile as this is for new cli only right?

Target:
default File resolve(File path) { return path.isAbsolute() ? path : new File(getVoltDBRoot(), path.getPath()); }
Source:
public String getServerSpecificRoot(String hostId) { if (!m_hostRoots.containsKey(hostId)) { START throw new RuntimeException("getServerSpecificRoot possibly called before cluster has started."); END } return m_hostRoots.get(hostId) + "/voltdbroot"; } IllegalArgumentException

Target:
public String getServerSpecificRoot(String hostId) { if (!m_hostRoots.containsKey(hostId)) { throw new IllegalArgumentException("getServerSpecificRoot possibly called before cluster has started."); } return m_hostRoots.get(hostId) + "/voltdbroot"; }
Source:
void doCommonSPICompleteActions() { // Mark the transaction state as DONE m_txnState.setDone(); // Set the truncation handle here instead of when processing the // messages in the SpScheduler to avoid any races of transaction // completing on the Site and receiving the messages in the Scheduler // for MPs. // // We have to use the spHandle from the first fragment, not from the // current message because it may be out of order if we do so. If we use // the spHandle from the current completion message, it may be advancing // the truncation handle before previous SPs are finished. if (m_txnDoneNotification != null) { START m_txnDoneNotification.transactionDone(m_txnState.m_spHandle); END } // Flush us out of the head of the TransactionTaskQueue. Null check so we're reusable // for live rejoin replay if (m_queue != null) { m_queue.flush(getTxnId()); } } @nshi Does " m_txnState.setDone();" also means that the SPI receives the duplicate counter DONE? How does it make sure the SPI knows?

Target:
void doCommonSPICompleteActions() { // Mark the transaction state as DONE m_txnState.setDone(); // Flush us out of the head of the TransactionTaskQueue. Null check so we're reusable // for live rejoin replay if (m_queue != null) { m_queue.flush(getTxnId()); } }
Source:
public void increaseBackpressure(int messageSize) { assert(m_expectedThreadId == Thread.currentThread().getId()); if (messageSize < 1) { throw new IllegalArgumentException("Message size must be > 0 but was " + messageSize); } m_pendingTxnBytes += messageSize; m_pendingTxnCount++; checkAndLogInvariants(); if (m_pendingTxnBytes > MAX_DESIRED_PENDING_BYTES || m_pendingTxnCount > MAX_DESIRED_PENDING_TXNS) { if (!m_hadBackPressure) { START hostLog.info("TXN back pressure began"); END m_hadBackPressure = true; for (ACGMember m : m_members) { m.onBackpressure(); } } } } Unintended changes for debugging?

Target:
public void increaseBackpressure(int messageSize) { assert(m_expectedThreadId == Thread.currentThread().getId()); if (messageSize < 1) { throw new IllegalArgumentException("Message size must be > 0 but was " + messageSize); } m_pendingTxnBytes += messageSize; m_pendingTxnCount++; checkAndLogInvariants(); if (m_pendingTxnBytes > MAX_DESIRED_PENDING_BYTES || m_pendingTxnCount > MAX_DESIRED_PENDING_TXNS) { if (!m_hadBackPressure) { hostLog.debug("TXN back pressure began"); m_hadBackPressure = true; for (ACGMember m : m_members) { m.onBackpressure(); } } } }
Source:
private void offerInternal(Mailbox mailbox, Item item, long handle) { if (item.getSpHandle() <= handle) { mailbox.send(item.getResponseHSId(), item.getMessage()); } else { m_bufferedReads.add(item); START releaseBufferedReads(mailbox, handle); END } } Don't you want to call `releaseBufferedReads()` regardless of whether the current item can be released or not?

Target:
private void offerInternal(Mailbox mailbox, Item item, long handle) { m_bufferedReads.add(item); releaseBufferedReads(mailbox, handle); }
Source:
public boolean hasAllFinishedReading() throws IOException { if (m_closed) throw new IOException("Segment closed"); if (m_readCursors.size() == 0) return false; START for (String cid : m_readCursors.keySet()) { END SegmentReader reader = m_readCursors.get(cid); if (reader.m_objectReadIndex < m_numOfEntries) { return false; } } return true; } Use `values()` instead of `keySet()` can save a map lookup for you.

Target:
public boolean hasAllFinishedReading() throws IOException { if (m_closed) throw new IOException("Segment closed"); if (m_readCursors.size() == 0) return false; for (SegmentReader reader : m_readCursors.values()) { if (reader.m_objectReadIndex < m_numOfEntries) { return false; } } return true; }
Source:
START private PBDSegment peekFirstSegment() { END Map.Entry<Long, PBDSegment> entry = m_segments.firstEntry(); return (entry!=null) ? entry.getValue() : null; } Those functions are confusing because they may return `null` but under our assumption pdb should always has at least one segment. Maybe `assert(entry != null)` is more readable.

Target:
private PBDSegment peekFirstSegment() { Map.Entry<Long, PBDSegment> entry = m_segments.firstEntry(); // entry may be null in ctor and while we are manipulating m_segments in addSegment, for example return (entry==null) ? null : entry.getValue(); }
Source:
public SegmentReader(String cursorId) { START m_cursorId = cursorId; END } precondition checks for null and assert for tests please.

Target:
public SegmentReader(String cursorId) { assert(cursorId != null); m_cursorId = cursorId; }
Source:
public boolean isClosed() { START return m_closed == true; END } just return m_closed.

Target:
public boolean isClosed() { return m_closed; }
Source:
public synchronized void close() throws IOException { if (m_closed) { return; } m_closed = true; START for (ReadCursor cursor : m_readCursors.values()) { END cursor.close(); } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_cursorsWriter.close(); m_closed = true; } Shouldnt you close all cursors before setting m_closed=true

Target:
public synchronized void close() throws IOException { if (m_closed) { return; } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_cursorsWriter.close(); m_closed = true; }
Source:
public static byte[] fileToBytes(File path) throws IOException { byte[] bytes = null; try { bytes = Files.readAllBytes(path.toPath()); } catch (IOException ioe) { START throw new IOException("File " + path.getAbsolutePath() + " is empty"); END } return bytes; } This error message is no longer accurate. You don't have catch it here, just let it throw.

Target:
public static byte[] fileToBytes(File path) throws IOException { return Files.readAllBytes(path.toPath()); }
Source:
public void offerSp(InitiateResponseMessage msg, boolean isLeader, long handle) { // System.out.println(String.format("Leader %s, truncation handle %d, replica truncation handle %d", // Boolean.toString(isLeader), handle, m_lastSpTruncationHandle)); long truncationHandle = m_lastSpTruncationHandle; if (isLeader) { truncationHandle = handle; } START if (msg.getSpHandle() >= truncationHandle || truncationHandle == Long.MIN_VALUE) { END m_mailbox.send(msg.getInitiatorHSId(), msg); } else { m_shortCircuitReadSp.add(new Item(msg)); } releaseShortCircuitRead(truncationHandle, IS_SP); } No need to check for `truncationHandle == Long.MIN_VALUE`.

Target:
public void offerSp(InitiateResponseMessage msg, boolean isLeader, long handle) { // System.out.println(String.format("Leader %s, truncation handle %d, replica truncation handle %d", // Boolean.toString(isLeader), handle, m_lastSpTruncationHandle)); long truncationHandle = m_lastSpTruncationHandle; if (isLeader) { truncationHandle = handle; } if (msg.getSpHandle() >= truncationHandle) { m_mailbox.send(msg.getInitiatorHSId(), msg); } else { m_shortCircuitReadSp.add(new Item(msg)); } releaseShortCircuitRead(truncationHandle, IS_SP); }
Source:
private void stagePathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (PrintWriter pw = new PrintWriter(new FileWriter(depFH), true)) { m_pathList.store(pw, "DO NOT MODIFY THIS FILE"); START pw.flush(); END pw.close(); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to stage configuration path destination", false, e); } } flush and close are done automagically when you get out from the try with resource block

Target:
private void stagePathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (PrintWriter pw = new PrintWriter(new FileWriter(depFH), true)) { m_pathList.store(pw, "DO NOT MODIFY THIS FILE"); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to stage configuration path destination", false, e); } }
Source:
private void loadPathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (FileInputStream is = new FileInputStream(depFH)) { consoleLog.info("Loading Path configuration from " + depFH.getAbsolutePath()); m_pathList.load(is); START is.close(); END } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to read configuration path destination", false, e); } } flush and close are done automagically when you get out from the try with resource block

Target:
private void loadPathConfiguration(Configuration config) { File depFH = new VoltFile(config.m_voltdbRoot, VoltDB.INITIALIZED_PATHS); try (FileInputStream is = new FileInputStream(depFH)) { consoleLog.info("Loading Path configuration from " + depFH.getAbsolutePath()); m_pathList.load(is); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to read configuration path destination", false, e); } }
Source:
START public static ImmutableSortedSet<String> hosts(int...ports) { END if (ports.length == 0) { return ImmutableSortedSet.of( HostAndPort.fromParts("", DEFAULT_INTERNAL_PORT).toString()); } ImmutableSortedSet.Builder<String> sbld = ImmutableSortedSet.naturalOrder(); for (int p: ports) { sbld.add(HostAndPort.fromParts("", p).toString()); } return sbld.build(); } What's this used for without passing any IP/hostname?

Target:
public static ImmutableSortedSet<String> hosts(int...ports) { if (ports.length == 0) { return ImmutableSortedSet.of( HostAndPort.fromParts("", Constants.DEFAULT_INTERNAL_PORT).toString()); } ImmutableSortedSet.Builder<String> sbld = ImmutableSortedSet.naturalOrder(); for (int p: ports) { sbld.add(HostAndPort.fromParts("", p).toString()); } return sbld.build(); }
Source:
public static boolean isInitialAckDRId(long drId) { if (drId == -1) return true; int clusterId = getClusterIdFromDRId(drId); START if (clusterId >= 0 && clusterId < MAX_CLUSTER_ID) { END return !((drId >>> 63) == 1L) && (getSequenceNumberFromDRId(drId) == MAX_SEQUENCE_NUMBER); } return false; } The second condition should be clusterId <= MAX_CLUSTER_ID

Target:
public static boolean isInitialAckDRId(long drId) { if (drId == -1) return true; int clusterId = getClusterIdFromDRId(drId); if (clusterId >= 0 && clusterId <= MAX_CLUSTER_ID) { return ((drId >>> 63) != 1L) && (getSequenceNumberFromDRId(drId) == MAX_SEQUENCE_NUMBER); } return false; }
Source:
public static boolean isEmptyDRId (long drId) { START return ((drId >>> 63) == 1L) && !(drId == -1); END } Maybe you can use !=, which is simpler

Target:
public static boolean isEmptyDRId (long drId) { return ((drId >>> 63) == 1L) && (drId != -1); }
Source:
START private void checkProcStatistics(Client client) END throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; System.out.println(vt.toString()); } This function just seems to be cluttering the test output. Is it really serving a purpose? Can it be modifed to do an actual validation rather than just dump output for a visual inspection that, practically speaking, will never happen. In general, I LIKE keeping around PROVEN USEFUL visual diagnostic code so it can be quickly enabled when something goes wrong, BUT I like it DISABLED when all is running as expected for a less verbose successful run and the clearer identification of actual problem diagnostics.

Target:
private void checkProcStatistics(Client client) throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; //System.out.println(vt.toString()); }
Source:
public void shutdown() throws InterruptedException { for (VoltNetwork vn : m_networks) { vn.shutdown(); } // end "Reverse DNS lookups" thread before shutdown START ReverseDNSCache.m_es.shutdown(); END } catch any exceptions on vn.shutdown() to ensure ReverseDNSCache.m_es.shutdown() is invoked.

Target:
public void shutdown() throws InterruptedException { for (VoltNetwork vn : m_networks) { vn.shutdown(); } }
Source:
static private void addTableToProject(VoltProjectBuilder project, int tableId, boolean partitioned) { try { project.addLiteralSchema(String.format(tableDDL, tableId)); START project.addStmtProcedure("Insert" + tableId, "INSERT INTO T" + tableId + " VALUES (?)"); END if (partitioned) { project.addLiteralSchema(String.format(partitionDDL, tableId)); } } catch (IOException e) { assertFalse(true); } } You will automatically get a CRUD proc called T1.Insert, etc when you create the table, so I think these procedures are unnecessary.

Target:
static private void addTableToProject(VoltProjectBuilder project, int tableId, boolean partitioned) { try { project.addLiteralSchema(String.format(tableDDL, tableId)); if (partitioned) { project.addLiteralSchema(String.format(partitionDDL, tableId)); } } catch (IOException e) { assertFalse(true); } }
Source:
public boolean allInnerJoins() { return m_joinType == JoinType.INNER && START (m_leftNode == null ? true : m_leftNode.allInnerJoins()) && END (m_rightNode == null ? true : m_rightNode.allInnerJoins()); } `X ? true : Y` simplifies to `X || Y`.

Target:
public boolean allInnerJoins() { return m_joinType == JoinType.INNER && (m_leftNode == null || m_leftNode.allInnerJoins()) && (m_rightNode == null || m_rightNode.allInnerJoins()); }
Source:
public static byte[] compressJSONString(String data) throws IOException { START ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); END GZIPOutputStream gzip = new GZIPOutputStream(bos); gzip.write(data.getBytes(StandardCharsets.UTF_8)); gzip.close(); byte[] compressed = bos.toByteArray(); bos.close(); return compressed; } ``` java public static byte[] compressJSONString(String data) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); try (GZIPOutputStream gzip = new GZIPOutputStream(bos)) { gzip.write(data.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw e; } return bos.toByteArray(); } ```

Target:
public static byte[] compressJSONString(String data) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); try (GZIPOutputStream gzip = new GZIPOutputStream(bos)) { gzip.write(data.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw e; } return bos.toByteArray(); }
Source:
public void addImport(boolean enabled, String importType, String importFormat, String importBundle, Properties config) { START addImport(enabled, importType, importFormat, importBundle, config, null); END } why not send empty Properties so you dont have to deal with null.

Target:
public void addImport(boolean enabled, String importType, String importFormat, String importBundle, Properties config) { addImport(enabled, importType, importFormat, importBundle, config, new Properties()); }
Source:
void expandConditions() { expandConditions(whereExpressions, false); for (HsqlArrayList whereExpression : whereExpressions) { START if (whereExpression.size() > whereExpressionElementsUpperBound) { END // If the query's where clause is composed of 240+ predicate expressions, when parsing these // expressions, due to mutual recursion, thread stack can grow to it's maximum capacity, // resulting in stack overflow error. The optimal solution to avoid this is to convert the // mutual recursion into tail-recursion or iterative approach. Though the change needed // are at multiple places like generating unique id for the expression during construction // of volt XML elements and converting the expression tree for the plan to json-string. // So at present guard against query whose where clause has more than 232 predicates. String msg = "Limit of predicate expressions in \"where\" clause exceeded the maximum limit of " + whereExpressionElementsUpperBound + " predicates, predicates detected: " + whereExpression.size() + ". Reduce the number of predicates in the \"where\" clause to " + whereExpressionElementsUpperBound; throw new HsqlException(msg, "", ErrorCode.X_47002); } } expandConditions(joinExpressions, false); } I think a generic check would be best if at all possible. There are lots of places where expressions can appear, and it would be easy to miss some. You could add a new field to Expression that is the number of levels in the tree, that is computed whenever a building an expression. Any time an expression is constructed, the new number of levels is the max(number_of_levels_in_nth_child_tree) + 1. Not sure if this is feasible.

Target:
void expandConditions() { expandConditions(whereExpressions, false); expandConditions(joinExpressions, false); }
Source:
private ExpressionLike(ExpressionLike other) { super(OpTypes.LIKE); this.nodes = other.nodes; this.likeObject = other.likeObject; START this.noOptimisation = true; END } Why set this to true here, instead of copying the value from other?

Target:
private ExpressionLike(ExpressionLike other) { super(OpTypes.LIKE); this.nodes = other.nodes; this.likeObject = other.likeObject; }
Source:
public void shutdown(ShutdownInput shutDownInput) { START if (shutDownInput.getShutdownReason().equals(ShutdownReason.TERMINATE)) { END //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } } ``` java if (ShutdownReason.TERMINATE.equals(shutDownInput.getShutdownReason()) { ```

Target:
public void shutdown(ShutdownInput shutDownInput) { if (ShutdownReason.TERMINATE.equals(shutDownInput.getShutdownReason())) { //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } }
Source:
public void activate() { START m_isActive = true; END setupExecutor(); } Shouldnt this be on executor lock?

Target:
public void activate() { setupExecutor(); }
Source:
public HTTPClientInterface() { final ClientResponseImpl r = new ClientResponseImpl(ClientResponse.CONNECTION_TIMEOUT, new VoltTable[0], "Request Timeout"); m_timeoutResponse = r.toJSONString(); START m_closeAllExecutor = CoreUtils.getSingleThreadExecutor("HttpClientInterface-closeAll"); // STEBUG remove END m_servicePrincipal = getAuthSystem().getServicePrincipal(); m_spnegoEnabled = m_servicePrincipal != null && !m_servicePrincipal.isEmpty(); } Do u mean to leave STEBUG?

Target:
public HTTPClientInterface() { final ClientResponseImpl r = new ClientResponseImpl(ClientResponse.CONNECTION_TIMEOUT, new VoltTable[0], "Request Timeout"); m_timeoutResponse = r.toJSONString(); m_servicePrincipal = getAuthSystem().getServicePrincipal(); m_spnegoEnabled = m_servicePrincipal != null && !m_servicePrincipal.isEmpty(); }
Source:
VoltFormatter (String name, Properties prop) { if (!("csv".equalsIgnoreCase(name) || "tsv".equalsIgnoreCase(name))) { START throw new RuntimeException("Invalid format " + name + ", choices are either \"csv\" or \"tsv\"."); END } m_parser = new CSVParser("csv".equalsIgnoreCase(name) ? ',' : '\t'); } please use IllegalArgumentException

Target:
VoltFormatter (String name, Properties prop) { if (!("csv".equalsIgnoreCase(name) || "tsv".equalsIgnoreCase(name))) { throw new IllegalArgumentException("Invalid format " + name + ", choices are either \"csv\" or \"tsv\"."); } m_parser = new CSVParser("csv".equalsIgnoreCase(name) ? ',' : '\t'); }
Source:
public void reset() { drId = Long.MIN_VALUE; START spUniqueId = Long.MIN_VALUE; END mpUniqueId = Long.MIN_VALUE; } As a matter of default, it's a little odd that these are using `Long.MIN_VALUE` while the rest of DR uses 0, a.k.a. `InvocationBuffer.UNSET_UNIQUE_ID`

Target:
public void reset() { drId = Long.MIN_VALUE; spUniqueId = 0; mpUniqueId = 0; }
Source:
private void verifyPerspectiveIsLoaded(String perspectiveID, By elementInPerspective) { try { Waits.elementPresent(elementInPerspective, 10); } catch (WebDriverException ex) { START Assertions.fail("The perspective with ID " + perspectiveID + " could not be loaded."); END } } I forgot we should add `ex` as the second parameter of `Assertions.fail` not to loose the failure stacktrace. Please add it.

Target:
private void verifyPerspectiveIsLoaded(String perspectiveID, By elementInPerspective) { try { Waits.elementPresent(elementInPerspective, 10); } catch (WebDriverException exception) { Assertions.fail("The perspective with ID " + perspectiveID + " could not be loaded.", exception); } }
Source:
public void goOnline() { ReadOnlyStoreStatusValidation validation = validateReadOnlyStoreStatusBeforeGoingOnline(); if (validation.readyToGoOnline) { createOnlineServices(); startOnlineServices(); START getMetadataStore().setOfflineState(false); END } if (validation.e != null) { throw new VoldemortException("Problem while going online!", validation.e); } } In the existing code, this was the first statement. Any reason, why you are changing the order ? If not, I would like to keep the getMetadataStore().setOfflineState(false) to be the first statement.

Target:
public void goOnline() { ReadOnlyStoreStatusValidation validation = validateReadOnlyStoreStatusBeforeGoingOnline(); if (validation.readyToGoOnline) { getMetadataStore().setOfflineState(false); createOnlineServices(); startOnlineServices(); } if (validation.e != null) { throw new VoldemortException("Problem while going online!", validation.e); } }
Source:
public synchronized void recordWarningCode(int code) { START Integer Icode = code; END if(!warningCodes.containsKey(Icode)) { int[] val = new int[1]; val[0] = 0; warningCodes.put(Icode, val); } warningCodes.get(Icode)[0]++; } Nipick: can we follow Java conventions of beginning variable names with a lower case? We also don't typically prefix variables with type information, though I guess that's not a big deal if you want to leave it as is.

Target:
public synchronized void recordWarningCode(int code) { Integer key = code; if(!warningCodes.containsKey(key)) { int[] val = new int[1]; val[0] = 0; warningCodes.put(key, val); } warningCodes.get(key)[0]++; }
Source:
public void testVersionedDelete() { START System.out.println("*********** testing versioned delete ***********"); END ByteArray key = new ByteArray("keyOne".getBytes()); List<Versioned<byte[]>> conflictingVersions = generatePutWithConflictionVersions(key); if(conflictingVersions.size() == 0) { Assert.fail("Could not generate conflicting versions "); } testDelete(key, conflictingVersions.get(0).getVersion()); } get rid of these s.o.plns and replace with logger?

Target:
public void testVersionedDelete() { logger.info("*********** testing versioned delete ***********"); ByteArray key = new ByteArray("keyOne".getBytes()); List<Versioned<byte[]>> conflictingVersions = generatePutWithConflictionVersions(key); if(conflictingVersions.size() == 0) { Assert.fail("Could not generate conflicting versions "); } testDelete(key, conflictingVersions.get(0).getVersion()); }
Source:
public VoldemortService getService(ServiceType type) { START for(VoldemortService service: services) END if(service.getType().equals(type)) return service; throw new IllegalStateException(type.getDisplayName() + " has not been initialized."); } Please add { } even if its a single line statement.

Target:
public VoldemortService getService(ServiceType type) { for(VoldemortService service: services) { if(service.getType().equals(type)) { return service; } } throw new IllegalStateException(type.getDisplayName() + " has not been initialized."); }
Source:
public static String writeSingleClientConfigAvro(Properties props) { // FIXME: This sucks. We shouldn't be manually manipulating json... String avroConfig = new String(); START Boolean firstProp = true; END for(String key: props.stringPropertyNames()) { if(firstProp) { firstProp = false; } else { avroConfig = avroConfig + ",\n"; } avroConfig = avroConfig + "\t\t\"" + key + "\": \"" + props.getProperty(key) + "\""; } if(avroConfig.isEmpty()) { return "{}"; } else { return "{\n" + avroConfig + "\n\t}"; } } Any specific reason for not using just the String literal here. As in just using String avroConfig; instead of creating String object.

Target:
public static String writeSingleClientConfigAvro(Properties props) { // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json... String avroConfig = ""; Boolean firstProp = true; for(String key: props.stringPropertyNames()) { if(firstProp) { firstProp = false; } else { avroConfig = avroConfig + ",\n"; } avroConfig = avroConfig + "\t\t\"" + key + "\": \"" + props.getProperty(key) + "\""; } if(avroConfig.isEmpty()) { return "{}"; } else { return "{\n" + avroConfig + "\n\t}"; } }
Source:
private DbSpace getBdbStats() { START return new DbSpace(environment, sorted); END } Is nt sorted always false here? can you remove the variable?

Target:
private DbSpace getBdbStats() { return new DbSpace(environment); }
Source:
public <T> Mono<CosmosItemResponse<T>> upsertItem(T item, PartitionKey partitionKey, CosmosItemRequestOptions options) { final CosmosItemRequestOptions requestOptions = options == null ? new CosmosItemRequestOptions() : options; START ModelBridgeInternal.setPartitionKey(options, partitionKey); END return withContext(context -> upsertItemInternal(item, requestOptions, context)); } This is a bug, we need to pass `requestOptions` instead of `options` Since you are OOF, I will fix it in your branch and push it.

Target:
public <T> Mono<CosmosItemResponse<T>> upsertItem(T item, PartitionKey partitionKey, CosmosItemRequestOptions options) { final CosmosItemRequestOptions requestOptions = options == null ? new CosmosItemRequestOptions() : options; ModelBridgeInternal.setPartitionKey(requestOptions, partitionKey); return withContext(context -> upsertItemInternal(item, requestOptions, context)); }
Source:
private void releaseAfterCancel(HttpMethod method) { START if (mayHaveBody(method) && this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.CANCELLED)) { END if (logger.isDebugEnabled()) { logger.debug("Releasing body, not yet subscribed"); } this.bodyIntern() .doOnNext(byteBuf -> {}) .subscribe(byteBuf -> {}, ex -> {}); } } Do we need mayHaveBody check , what happen if we clear on all cancel irrespective of body, we can avoid extra check ?

Target:
private void releaseAfterCancel(HttpMethod method) { if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.CANCELLED)) { if (logger.isDebugEnabled()) { logger.debug("Releasing body, not yet subscribed"); } this.bodyIntern() .doOnNext(byteBuf -> {}) .subscribe(byteBuf -> {}, ex -> {}); } }
Source:
public BenchmarkRequestSubscriber(Meter successMeter, Meter failureMeter, Semaphore concurrencyControlSemaphore, AtomicLong count) { this.successMeter = successMeter; this.failureMeter = failureMeter; this.concurrencyControlSemaphore = concurrencyControlSemaphore; this.count = count; START logger = LoggerFactory.getLogger(this.getClass()); END } this class is getting instantiated in a for loop in your benchmark, meaning the logger initialization will be called per for loop iteration. logger should be static to avoid initialization cost per loop iteration.

Target:
public BenchmarkRequestSubscriber(Meter successMeter, Meter failureMeter, Semaphore concurrencyControlSemaphore, AtomicLong count) { this.successMeter = successMeter; this.failureMeter = failureMeter; this.concurrencyControlSemaphore = concurrencyControlSemaphore; this.count = count; }
Source:
public void testDelete() { Mono<LongIdDomainPartition> saveMono = this.repository.save(DOMAIN_1); START StepVerifier.create(saveMono).thenConsumeWhile(domain -> true).expectComplete().verify(); END Mono<Void> deleteMono = this.repository.delete(DOMAIN_1); StepVerifier.create(deleteMono).verifyComplete(); Mono<Long> countMono = repository.count(); StepVerifier.create(countMono).expectNext(1L).verifyComplete(); } `expectNext = DOMAIN_1`

Target:
public void testDelete() { Mono<LongIdDomainPartition> saveMono = this.repository.save(DOMAIN_1); StepVerifier.create(saveMono).expectNext(DOMAIN_1).expectComplete().verify(); Mono<Void> deleteMono = this.repository.delete(DOMAIN_1); StepVerifier.create(deleteMono).verifyComplete(); Mono<Long> countMono = repository.count(); StepVerifier.create(countMono).expectNext(1L).verifyComplete(); }
Source:
START public static Object getStringIDValue(Object idValue) { END Assert.notNull(idValue, "id should not be null"); if (idValue instanceof String) { Assert.hasText(idValue.toString(), "id should not be empty or only whitespaces."); return idValue; } else if (idValue instanceof Integer) { return Integer.toString((Integer) idValue); } else if (idValue instanceof Long) { return Long.toString((Long) idValue); } else { throw new IllegalQueryException("Type of id field must be String or Integer or Long"); } } This should return <String> type, why is it returning Object ?

Target:
public static String getStringIDValue(Object idValue) { Assert.notNull(idValue, "id should not be null"); if (idValue instanceof String) { Assert.hasText(idValue.toString(), "id should not be empty or only whitespaces."); return (String) idValue; } else if (idValue instanceof Integer) { return Integer.toString((Integer) idValue); } else if (idValue instanceof Long) { return Long.toString((Long) idValue); } else { throw new IllegalQueryException("Type of id field must be String or Integer or Long"); } }
Source:
START public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { END this.tokenFilters = Arrays.asList(tokenFilters); return this; } The options are input only

Target:
public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); return this; }
Source:
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties, CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } Database wrappedDatabase = new Database(); wrappedDatabase.setId(databaseProperties.getId()); START final CosmosDatabaseRequestOptions requestOptions = options; END return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context)); } From a code style perspective, it would be better to do lines 255-257 and 260 on a single line: `final CosmosDatabaseRequestOptions requestOptions = options == null ? new CosmosDatabaseRequestOptions() : options;`

Target:
public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseProperties, CosmosDatabaseRequestOptions options) { final CosmosDatabaseRequestOptions requestOptions = options == null ? new CosmosDatabaseRequestOptions() : options; Database wrappedDatabase = new Database(); wrappedDatabase.setId(databaseProperties.getId()); return withContext(context -> createDatabaseInternal(wrappedDatabase, requestOptions, context)); }
Source:
CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases(CosmosQueryRequestOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { START String spanName = "readAllDatabases"; pagedFluxOptions.setTracerInformation(this.tracerProvider, spanName, this.serviceEndpoint, null); END setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readDatabases(options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); } Could you save a variable declaration and set by just directly passing the string into the method call?

Target:
CosmosPagedFlux<CosmosDatabaseProperties> readAllDatabases(CosmosQueryRequestOptions options) { return UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { pagedFluxOptions.setTracerInformation(this.tracerProvider, "readAllDatabases", this.serviceEndpoint, null); setContinuationTokenAndMaxItemCount(pagedFluxOptions, options); return getDocClientWrapper().readDatabases(options) .map(response -> BridgeInternal.createFeedResponse( ModelBridgeInternal.getCosmosDatabasePropertiesFromV2Results(response.getResults()), response.getResponseHeaders())); }); }
Source:
private RecognizeOptions getRecognizeOptionsProperties(RecognizeOptions userProvidedOptions) { if (userProvidedOptions != null) { START return new RecognizeOptions() .setPollInterval(userProvidedOptions.getPollInterval()) .setFormContentType(userProvidedOptions.getFormContentType()) .setIncludeTextContent(userProvidedOptions.isIncludeTextContent()); END } else { return new RecognizeOptions(); } } why do we make a copy of the user-provided options here?

Target:
private RecognizeOptions getRecognizeOptionsProperties(RecognizeOptions userProvidedOptions) { if (userProvidedOptions != null) { return userProvidedOptions; } else { return new RecognizeOptions(); } }
Source:
void setup() { MockitoAnnotations.initMocks(this); when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH); when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1, maxAutoLockRenewalDuration)); START when(messageLockToken).thenReturn(LOCK_TOKEN); END client = new ServiceBusReceiverClient(asyncClient, OPERATION_TIMEOUT); } You don't need to mock this anymore you can set the string and return it.

Target:
void setup() { MockitoAnnotations.initMocks(this); when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH); when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1, maxAutoLockRenewalDuration)); client = new ServiceBusReceiverClient(asyncClient, OPERATION_TIMEOUT); }
Source:
public int compareTo(UInt128 other) { if (this.equals(other)) { return 0; } START if ((this.high < this.high) || ((this.high == other.high) && (this.low < other.low))) { END return -1; } return 1; } I think this is a typo -> `this.high < this.high` -> should be -> `this.high < other.high` ??

Target:
public int compareTo(UInt128 other) { if (this.equals(other)) { return 0; } if ((this.high < other.high) || ((this.high == other.high) && (this.low < other.low))) { return -1; } return 1; }
Source:
public TablesSharedKeyCredential(String accountName, String accountKey) { START Objects.requireNonNull(accountName, "'accountName' cannot be null."); END Objects.requireNonNull(accountKey, "'accountKey' cannot be null."); this.accountName = accountName; this.accountKey = accountKey; } This can be simplified to. Same with the line below. ```java this.accountName = Objects.requireNonNull(accountName, "'accountName' cannot be null."); ```

Target:
public TablesSharedKeyCredential(String accountName, String accountKey) { this.accountName = Objects.requireNonNull(accountName, "'accountName' cannot be null."); this.accountKey = Objects.requireNonNull(accountKey, "'accountKey' cannot be null."); }