auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private void assambleApnsClientBuilder(final iOSVariant iOSVariant, final ApnsClientBuilder builder) { <END> if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { try (final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate())) { builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory( new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } } catch (Exception e) { logger.error("Error reading certificate", e); } } throw new IllegalArgumentException("Not able to construct APNS client"); }</code><technical_language>yeah, previously a return statement in body run throw line. removed return line, throw line is get executed</technical_language>

Target:
private void assambleApnsClientBuilder(final iOSVariant iOSVariant, final ApnsClientBuilder builder) { if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { try (final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate())) { builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory( new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } return; } catch (Exception e) { logger.error("Error reading certificate", e); } } throw new IllegalArgumentException("Not able to construct APNS client"); }
Source:
<code>public String[] getContext(String document) { Collection<String> context = new LinkedList<>(); NGramModel model = new NGramModel(); model.add(document, minLength, maxLength); for (StringList tokenList : model) { if (tokenList.size() > 0) { <START> context.add("ng=" + StringUtil.toLowerCase(tokenList.getToken(0))); <END> } } return context.toArray(new String[context.size()]); }</code><technical_language>reason r StrugUtils commons.lang3 ? Time retire some of opennlp StringUtil I guess</technical_language>

Target:
public String[] getContext(String document) { Collection<String> context = new LinkedList<>(); NGramModel model = new NGramModel(); String normalized = normalizer.normalize(document).toString(); model.add(normalized, minLength, maxLength); for (StringList tokenList : model) { if (tokenList.size() > 0) { context.add("ng=" + StringUtil.toLowerCase(tokenList.getToken(0))); } } return context.toArray(new String[context.size()]); }
Source:
<code>private void onDomRetrieved(String dom) { webView.loadDataWithBaseURL( wikiUrl, <START> ((("<head>" <END> + Wiki.getGlobalCustomCss()) + Wiki.getGlobalCustomJavaScript()) + "</head>") + dom, "text/html", "utf-8", null); }</code><technical_language>triple parens required? a bit odd</technical_language>

Target:
private void onDomRetrieved(String dom) { webView.loadDataWithBaseURL( wikiUrl, "<head>" + Wiki.getGlobalCustomCss() + Wiki.getGlobalCustomJavaScript() + "</head>" + dom, "text/html", "utf-8", null); }
Source:
<code>private String parseDuration() { NumberFormat formatter = new DecimalFormat("00"); int hours = (int) Math.floor(duration / 3600); int minutes = (int) Math.floor(duration / 60 % 60); <START> int seconds = (int) Math.floor(duration % 60); <END> return String.format("%s:%s:%s", formatter.format(hours), formatter.format(minutes), formatter.format(seconds)); }</code><technical_language>universal operation, checked if sth similar is performed in repo already</technical_language>

Target:
private String parseDuration() { NumberFormat formatter = new DecimalFormat("00"); int hours = (int) Math.floor(duration / 3600), minutes = (int) Math.floor(duration / 60 % 60), seconds = (int) Math.floor(duration % 60); return String.format("%s:%s:%s", formatter.format(hours), formatter.format(minutes), formatter.format(seconds)); }
Source:
<code>@Test public void computationSchedulerUsesSuppliedThreadFactory() throws InterruptedException { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); threadRef.set(thread); return thread; } }; Scheduler scheduler = RxJavaSchedulersHook.createComputationScheduler(threadFactory); Worker worker = scheduler.createWorker(); final CountDownLatch latch = new CountDownLatch(1); worker.schedule(new Action0() { @Override public void call() { assertSame(threadRef.get(), Thread.currentThread()); latch.countDown(); } }); <START> assertTrue(latch.await(10, SECONDS)); <END> }</code><technical_language>Needs shut scheduler</technical_language>

Target:
@Test public void computationSchedulerUsesSuppliedThreadFactory() throws InterruptedException { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); threadRef.set(thread); return thread; } }; Scheduler scheduler = RxJavaSchedulersHook.createComputationScheduler(threadFactory); Worker worker = scheduler.createWorker(); final CountDownLatch latch = new CountDownLatch(1); worker.schedule(new Action0() { @Override public void call() { assertSame(threadRef.get(), Thread.currentThread()); latch.countDown(); } }); assertTrue(latch.await(10, SECONDS)); if (scheduler instanceof SchedulerLifecycle) { ((SchedulerLifecycle) scheduler).shutdown(); } }
Source:
<code>public int read() throws IOException { try { return this.blobInputStream.read(); <START> } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); <END> } }</code><technical_language>Shoundn't this happen BlobInputStream ? If push instead of creating new type</technical_language>

Target:
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
Source:
<code>public void refreshDetails(GlusterVolumeEntity volumeEntity) { AsyncDataProvider.getGlusterRemoveBricksStatus(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VdcQueryReturnValue vdcValue = (VdcQueryReturnValue) returnValue; GlusterVolumeTaskStatusEntity statusEntity = vdcValue.getReturnValue(); if (statusEntity != null) { showStatus(statusEntity); } else { <START> cancelRefresh(); <END> } } }), volumeEntity.getClusterId(), volumeEntity.getId(), getBricks()); }</code><technical_language>cancelRefresh if query is failed</technical_language>

Target:
public void refreshDetails(GlusterVolumeEntity volumeEntity) { AsyncDataProvider.getGlusterRemoveBricksStatus(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VdcQueryReturnValue vdcValue = (VdcQueryReturnValue) returnValue; GlusterVolumeTaskStatusEntity statusEntity = vdcValue.getReturnValue(); if (statusEntity != null) { showStatus(statusEntity); } } }), volumeEntity.getClusterId(), volumeEntity.getId(), getBricks()); }
Source:
<code><START> public QueueSet getQueueSet(TaskPriority priority) { <END> switch (priority) { case High: return highPriorityQueueSet; case Low: return lowPriorityQueueSet; default: throw new UnsupportedOperationException(); } }</code><technical_language>this quicker if/else if/else</technical_language>

Target:
public QueueSet getQueueSet(TaskPriority priority) { if (priority == TaskPriority.High) { return highPriorityQueueSet; } else { return lowPriorityQueueSet; } }
Source:
<code>private List<String> toList(String list) { list = list.trim(); if(list.length()==0) return Collections.emptyList(); <START> return Arrays.asList(list.split("<file/>")); <END> }</code><technical_language>Odd I expect xml <files><file>a.txt</file><file>b.txt</file></files> similar</technical_language>

Target:
private List<String> toList(String list) { list = list.trim(); if(list.length()==0) return Collections.emptyList(); return Arrays.asList(list.split(list.contains("<file/>") ? "<file/>" : " ")); }
Source:
<code>public void testDeleteSupplementaryFolder() { ITmfTrace trace = fTrace; assertNotNull(trace); String suppFilesPath = TmfTraceManager.getSupplementaryFileDir(trace); try { assertFalse(isDirectoryEmpty(suppFilesPath)); trace.dispose(); TmfTraceManager.deleteSupplementaryFolder(trace); File parent = new File(suppFilesPath); assertFalse(parent.exists()); <START> } catch (IOException e) { fail(e.getMessage()); } <END> }</code><technical_language>test throw exception, marked a failure too, complete stack</technical_language>

Target:
public void testDeleteSupplementaryFolder() throws IOException { ITmfTrace trace = fTrace; assertNotNull(trace); String suppFilesPath = TmfTraceManager.getSupplementaryFileDir(trace); assertFalse(isDirectoryEmpty(suppFilesPath)); trace.dispose(); TmfTraceManager.deleteSupplementaryFolder(trace); File parent = new File(suppFilesPath); assertFalse(parent.exists()); }
Source:
<code>void runOnce() { if (transactionManager != null) { try { transactionManager.resetProducerIdIfNeeded(); if (!transactionManager.isTransactional()) { maybeWaitForProducerId(); } else if (transactionManager.hasUnresolvedSequences() && !transactionManager.hasFatalError()) { transactionManager.transitionToFatalError( new KafkaException("The client hasn't received acknowledgment for " + "some previously sent messages and can no longer retry them. It isn't safe to continue.")); } else if (transactionManager.hasInFlightTransactionalRequest()) { client.poll(retryBackoffMs, time.milliseconds()); return; } maybeBeginFlush(); TransactionManager.TxnRequestHandler nextRequestHandler = transactionManager.nextRequestHandler(accumulator.hasIncomplete()); if (nextRequestHandler != null) { if (maybeSendTransactionalRequest(nextRequestHandler)) { <START> client.poll(retryBackoffMs, time.milliseconds()); <END> } return; } if (transactionManager.hasFatalError() || !transactionManager.hasProducerId()) { RuntimeException lastError = transactionManager.lastError(); if (lastError != null) maybeAbortBatches(lastError); client.poll(retryBackoffMs, time.milliseconds()); return; } else if (transactionManager.hasAbortableError()) { accumulator.abortUndrainedBatches(transactionManager.lastError()); } } catch (AuthenticationException e) { log.trace("Authentication exception while processing transactional request: {}", e); transactionManager.authenticationFailed(e); } } long currentTimeMs = time.milliseconds(); long pollTimeout = sendProducerData(currentTimeMs); client.poll(pollTimeout, currentTimeMs); }</code><technical_language>This logic is a bit awkward. I guess client.poll is disconnected send logic. I if reasonable create a method maybePollTransactionalRequest handles inflight check, sending next request, calling client.poll if necessary</technical_language>

Target:
void runOnce() { if (transactionManager != null) { try { transactionManager.resetProducerIdIfNeeded(); if (!transactionManager.isTransactional()) { maybeWaitForProducerId(); } else if (transactionManager.hasUnresolvedSequences() && !transactionManager.hasFatalError()) { transactionManager.transitionToFatalError( new KafkaException("The client hasn't received acknowledgment for " + "some previously sent messages and can no longer retry them. It isn't safe to continue.")); } else if (maybeSendAndPollTransactionalRequest()) { return; } if (transactionManager.hasFatalError() || !transactionManager.hasProducerId()) { RuntimeException lastError = transactionManager.lastError(); if (lastError != null) maybeAbortBatches(lastError); client.poll(retryBackoffMs, time.milliseconds()); return; } else if (transactionManager.hasAbortableError()) { accumulator.abortUndrainedBatches(transactionManager.lastError()); } } catch (AuthenticationException e) { log.trace("Authentication exception while processing transactional request: {}", e); transactionManager.authenticationFailed(e); } } long currentTimeMs = time.milliseconds(); long pollTimeout = sendProducerData(currentTimeMs); client.poll(pollTimeout, currentTimeMs); }
Source:
<code>public boolean apply(Entity entity) throws WorldEditException { BaseEntity state = entity.getState(); if (state != null) { Location newLocation; Location location = entity.getLocation(); Vector3 pivot = from.round().add(0.5, 0.5, 0.5); Vector3 newPosition = transform.apply(location.toVector().subtract(pivot)); Vector3 newDirection; newDirection = transform.isIdentity() ? entity.getLocation().getDirection() : transform.apply(location.getDirection()).subtract(transform.apply(Vector3.ZERO)).normalize(); newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); state = transformNbtData(state); <START> if (state.getType() == EntityTypes.PAINTING) { <END> CompoundTag tag = state.getNbtData(); if (tag != null) { boolean hasTilePosition = tag.containsKey("TileX") && tag.containsKey("TileY") && tag.containsKey("TileZ"); if (hasTilePosition) { newLocation = new Location(destination, tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ")); } } } boolean success = destination.createEntity(newLocation, state) != null; if (isRemoving() && success) { entity.remove(); } return success; } else { return false; } }</code><technical_language>do need this? a ton of sense me, Tile position updated location be. If this is inconsistent, change newLocation is calculated, read out of NBT data wrote</technical_language>

Target:
public boolean apply(Entity entity) throws WorldEditException { BaseEntity state = entity.getState(); if (state != null) { Location newLocation; Location location = entity.getLocation(); CompoundTag tag = state.getNbtData(); boolean hasTilePosition = tag != null && tag.containsKey("TileX") && tag.containsKey("TileY") && tag.containsKey("TileZ"); if (hasTilePosition) { location = location.setPosition(Vector3.at(tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ")).add(0.5, 0.5, 0.5)); } Vector3 pivot = from.round().add(0.5, 0.5, 0.5); Vector3 newPosition = transform.apply(location.toVector().subtract(pivot)); if (hasTilePosition) { newPosition = newPosition.subtract(0.5, 0.5, 0.5); } Vector3 newDirection; newDirection = transform.isIdentity() ? entity.getLocation().getDirection() : transform.apply(location.getDirection()).subtract(transform.apply(Vector3.ZERO)).normalize(); newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); state = transformNbtData(state); boolean success = destination.createEntity(newLocation, state) != null; if (isRemoving() && success) { entity.remove(); } return success; } else { return false; } }
Source:
<code><START> Map<ConnectionInfo, ConnectionState> getCurrentConnections(final InputStream in) throws IOException { <END> final Map<ConnectionInfo, ConnectionState> connectionToState = new HashMap<>(); try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { reader.readLine(); String line; while (null != (line = reader.readLine())) { final StringTokenizer tokenizer = new StringTokenizer(line); tokenizer.nextToken(); try { final String[] localAddress = tokenizer.nextToken().split(":"); final int localPort = Integer.parseInt(localAddress[1], 16); if (localPort != port) { continue; } final String[] remoteAddressPair = tokenizer.nextToken().split(":"); final InetAddress[] remoteAddresses = restoreAddresses(remoteAddressPair[0]); final int remotePort = Integer.parseInt(remoteAddressPair[1], 16); final ConnectionState connectionState = ConnectionState.fromCode(tokenizer.nextToken()); for (final InetAddress tmp : remoteAddresses) { connectionToState.put(new ConnectionInfo(tmp, remotePort), connectionState); } } catch (DecoderException | RuntimeException ex) { LOG.error("Failed to parse line, skipping: " + line, ex); } } } return connectionToState; }</code><technical_language>package scope</technical_language>

Target:
Map<ConnectionInfo, ConnectionState> getCurrentConnections(final InputStream in) throws IOException { final Map<ConnectionInfo, ConnectionState> connectionToState = new HashMap<>(); try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { reader.readLine(); String line; while (null != (line = reader.readLine())) { final StringTokenizer tokenizer = new StringTokenizer(line); tokenizer.nextToken(); try { final String[] localAddress = tokenizer.nextToken().split(":"); final int localPort = Integer.parseInt(localAddress[1], 16); if (localPort != port) { continue; } final String[] remoteAddressPair = tokenizer.nextToken().split(":"); final InetAddress[] remoteAddresses = restoreAddresses(remoteAddressPair[0]); final int remotePort = Integer.parseInt(remoteAddressPair[1], 16); final ConnectionState connectionState = ConnectionState.fromCode(tokenizer.nextToken()); Stream.of(remoteAddresses) .map(address -> new ConnectionInfo(address, remotePort)) .forEach(info -> connectionToState.put(info, connectionState)); } catch (final DecoderException | RuntimeException ex) { LOG.error("Failed to parse line, skipping: " + line, ex); } } } return connectionToState; }
Source:
<code>public void batchErrorReporting() throws SQLException { final int maxRetries = 2; final int retryBackoffMs = 1000; final int batchSize = 3; List<SinkRecord> records = new ArrayList<>(); SinkRecord record = new SinkRecord("stub", 0, null, null, null, null, 0); for (int i = 0; i < batchSize; i++) { <START> records.add(record); <END> } final JdbcDbWriter mockWriter = createMock(JdbcDbWriter.class); SinkTaskContext ctx = createMock(SinkTaskContext.class); mockWriter.write(records); SQLException exception = new SQLException("cause 1"); expectLastCall().andThrow(exception); mockWriter.write(anyObject()); expectLastCall().andThrow(exception).times(batchSize); JdbcSinkTask task = new JdbcSinkTask() { @Override void initWriter() { this.writer = mockWriter; } }; task.initialize(ctx); ErrantRecordReporter reporter = createMock(ErrantRecordReporter.class); expect(ctx.errantRecordReporter()).andReturn(reporter); expect(reporter.report(anyObject(), anyObject())).andReturn(createMock(Future.class)).times(batchSize); replayAll(); Map<String, String> props = new HashMap<>(); props.put(JdbcSinkConfig.CONNECTION_URL, "stub"); props.put(JdbcSinkConfig.MAX_RETRIES, String.valueOf(maxRetries)); props.put(JdbcSinkConfig.RETRY_BACKOFF_MS, String.valueOf(retryBackoffMs)); task.start(props); task.put(records); verifyAll(); }</code><technical_language>a testcase test 1st record in batch throwing exception retry this record errant reporter? Subsequent records in batch writer</technical_language>

Target:
public void batchErrorReporting() throws SQLException { final int maxRetries = 2; final int retryBackoffMs = 1000; final int batchSize = 3; List<SinkRecord> records = new ArrayList<>(); SinkRecord record = new SinkRecord("stub", 0, null, null, null, null, 0); for (int i = 0; i < batchSize; i++) { records.add(record); } final JdbcDbWriter mockWriter = createMock(JdbcDbWriter.class); SinkTaskContext ctx = createMock(SinkTaskContext.class); mockWriter.write(records); SQLException exception = new SQLException("cause 1"); expectLastCall().andThrow(exception); mockWriter.write(anyObject()); expectLastCall().andThrow(exception).times(batchSize); JdbcSinkTask task = new JdbcSinkTask() { @Override void initWriter() { this.writer = mockWriter; } }; task.initialize(ctx); ErrantRecordReporter reporter = createMock(ErrantRecordReporter.class); expect(ctx.errantRecordReporter()).andReturn(reporter); expect(reporter.report(anyObject(), anyObject())).andReturn(CompletableFuture.completedFuture(null)).times(batchSize); replayAll(); Map<String, String> props = new HashMap<>(); props.put(JdbcSinkConfig.CONNECTION_URL, "stub"); props.put(JdbcSinkConfig.MAX_RETRIES, String.valueOf(maxRetries)); props.put(JdbcSinkConfig.RETRY_BACKOFF_MS, String.valueOf(retryBackoffMs)); task.start(props); task.put(records); verifyAll(); }
Source:
<code>UndeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, BlobId blobId, String serviceId, long operationTimeMs, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.operationTimeMs = operationTimeMs; <START> byte blobDcId = blobId.getDatacenterId(); String originatingDcName = clusterMap.getDatacenterName(blobDcId); <END> this.operationTracker = new UndeleteOperationTracker(routerConfig, blobId.getPartition(), originatingDcName); }</code><technical_language>nit: lines combined single line</technical_language>

Target:
UndeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, BlobId blobId, String serviceId, long operationTimeMs, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.operationTimeMs = operationTimeMs; this.operationTracker = new UndeleteOperationTracker(routerConfig, blobId.getPartition(), clusterMap.getDatacenterName(blobId.getDatacenterId())); }
Source:
<code>public void setUp() throws Exception { initMocks(this); when(dbHandlerMock.getGlucoseReading(anyLong())).thenReturn(glucoseReadingMock); when(glucoseReadingMock.getNotes()).thenReturn(MOCK_NOTE_FOR_TEST); <START> when(glucoseReadingMock.getCreated()).thenReturn(new Date(System.currentTimeMillis())); <END> when(glucoseReadingMock.getReading()).thenReturn(TEST_READING_VALUE); }</code><technical_language>new Date() is current milliseconds time</technical_language>

Target:
public void setUp() throws Exception { initMocks(this); when(dbHandlerMock.getGlucoseReading(anyLong())).thenReturn(glucoseReadingMock); when(glucoseReadingMock.getNotes()).thenReturn(MOCK_NOTE_FOR_TEST); when(glucoseReadingMock.getCreated()).thenReturn(new Date()); when(glucoseReadingMock.getReading()).thenReturn(TEST_READING_VALUE); }
Source:
<code>public boolean setScannerEnabled(final IServer server, String scannerName, boolean enabled) { ModelNode op = new ModelNode(); op.get("operation").set("write-attribute"); op.get("name").set("scan-enabled"); op.get("value").set(enabled); ModelNode addr = op.get("address"); addr.add("subsystem", "deployment-scanner"); addr.add("scanner", scannerName); final String request = op.toJSONString(true); try { executeWithResult(server, request); <START> } catch(Exception e) { <END> return false; } return true; }</code><technical_language>log</technical_language>

Target:
public boolean setScannerEnabled(final IServer server, String scannerName, boolean enabled) { ModelNode op = new ModelNode(); op.get("operation").set("write-attribute"); op.get("name").set("scan-enabled"); op.get("value").set(enabled); ModelNode addr = op.get("address"); addr.add("subsystem", "deployment-scanner"); addr.add("scanner", scannerName); final String request = op.toJSONString(true); try { executeWithResult(server, request); } catch(Exception e) { JBossServerCorePlugin.log(e); return false; } return true; }
Source:
<code>Map<String, String> fetchAccountMetadata() { long startTimeMs = System.currentTimeMillis(); logger.trace("Start reading ZNRecord from path={}", znRecordPath); ZNRecord znRecord = helixStore.get(znRecordPath, null, AccessOption.PERSISTENT); logger.trace("Fetched ZNRecord from path={}, took time={} ms", znRecordPath, startTimeMs); if (znRecord == null) { logger.info("The ZNRecord to read does not exist on path={}", znRecordPath); <START> return null; <END> } Map<String, String> newAccountMap = fetchAccountMetadataFromZNRecord(znRecord); backupFileManager.persistState(newAccountMap, znRecord); return newAccountMap; }</code><technical_language>line 89, time = startTimeMs</technical_language>

Target:
Map<String, String> fetchAccountMetadata() { long startTimeMs = System.currentTimeMillis(); logger.trace("Start reading ZNRecord from path={}", znRecordPath); Stat stat = new Stat(); ZNRecord znRecord = helixStore.get(znRecordPath, stat, AccessOption.PERSISTENT); logger.trace("Fetched ZNRecord from path={}, took time={} ms", znRecordPath, System.currentTimeMillis() - startTimeMs); if (znRecord == null) { logger.info("The ZNRecord to read does not exist on path={}", znRecordPath); return null; } Map<String, String> newAccountMap = fetchAccountMetadataFromZNRecord(znRecord); if (newAccountMap != null) { backupFileManager.persistAccountMap(newAccountMap, stat); } return newAccountMap; }
Source:
<code>public CompactionDetails getCompactionDetails(long totalCapacity, long usedCapacity, long segmentCapacity, long segmentHeaderSize, List<String> logSegmentsNotInJournal, BlobStoreStats blobStoreStats, String dataDir) throws StoreException { String storeId = blobStoreStats.getStoreId(); <START> CompactionPolicySwitchInfo compactionPolicySwitchInfo = blobToCompactionPolicySwitchInfoMap.getOrDefault(storeId, new CompactionPolicySwitchInfo(new CompactionPolicyCounter(storeConfig), INIT_COMPACT_ALL_TIME)); blobToCompactionPolicySwitchInfoMap.put(storeId, compactionPolicySwitchInfo); CompactionPolicy selectCompactionPolicy = selectCompactionPolicyAndUpdateCompactionPolicySwitchInfo(dataDir, storeId, compactionPolicySwitchInfo); <END> logger.info("Current compaction policy is : {}", selectCompactionPolicy); backUpCompactionPolicyInfo(dataDir, storeId, compactionPolicySwitchInfo); compactionPolicySwitchInfo.getCompactionPolicyCounter().increment(); return selectCompactionPolicy.getCompactionDetails(totalCapacity, usedCapacity, segmentCapacity, segmentHeaderSize, logSegmentsNotInJournal, blobStoreStats, null); }</code><technical_language>logic a bit checking file time selecting a policy. if (!blobToCompactionPolicySwitchInfos.contain(storeId)) { File file = new File(Paths.get(dataDir, COMPACT_POLICY_INFO_PATH)) if (file.exists()) { ObjectMapper objectMapper = new ObjectMapper(); CompactionPolicySwitchInfo switchInfo = objectMapper.readValue(file, CompactionPolicySwithInfo.class); blobToCompactionPolicySwtichInfos.put(storeId, switchInfo); } else { blobToCompactionPolicySwtichInfos.put(storeId, new CompactionPolicySwitchInfo(new CompactionPolicyCounter(storeConfig), INIT_COMPACT_ALL_TIME)); } }</technical_language>

Target:
public CompactionDetails getCompactionDetails(long totalCapacity, long usedCapacity, long segmentCapacity, long segmentHeaderSize, List<String> logSegmentsNotInJournal, BlobStoreStats blobStoreStats, String dataDir) throws StoreException { String storeId = blobStoreStats.getStoreId(); CompactionPolicySwitchInfo compactionPolicySwitchInfo = getCompactionPolicySwitchInfo(storeId, dataDir, blobStoreStats); CompactionPolicy selectCompactionPolicy = selectCompactionPolicyAndUpdateCompactionPolicySwitchInfo(compactionPolicySwitchInfo, storeId, dataDir); logger.info("Current compaction policy is : for store : {}, dataDir : {}", selectCompactionPolicy, storeId, dataDir); compactionPolicySwitchInfo.getCompactionPolicyCounter().increment(); backUpCompactionPolicyInfo(dataDir, compactionPolicySwitchInfo); return selectCompactionPolicy.getCompactionDetails(totalCapacity, usedCapacity, segmentCapacity, segmentHeaderSize, logSegmentsNotInJournal, blobStoreStats, dataDir); }
Source:
<code>private void checkWorkDirectory() throws RuntimeConfigurationError { <START> if (myWorkDirectory != null && !myWorkDirectory.isEmpty()) { <END> File dir = new File(myWorkDirectory); try { if (!dir.isDirectory()) { throw new RuntimeConfigurationError("Incorrect path to working directory."); } } catch (SecurityException e) { throw new RuntimeConfigurationError("Access denied to working directory"); } } }</code><technical_language>StringUtil.isEmpty</technical_language>

Target:
private void checkWorkDirectory() throws RuntimeConfigurationError { if (StringUtil.isNotEmpty(myWorkDirectory)) { File dir = new File(myWorkDirectory); try { if (!dir.isDirectory()) { throw new RuntimeConfigurationError("Incorrect path to working directory."); } } catch (SecurityException e) { throw new RuntimeConfigurationError("Access denied to working directory"); } } }
Source:
<code>@Override public void end(Xid xid, int flags) { assert this.xid.equals(xid); if (log.isDebugEnabled()) log.debug("XA resource end(...) [xid=" + xid + ", flags=<" + flags(flags) + ">]"); if ((flags & TMSUSPEND) == TMSUSPEND) { cacheTx.stop(); } else if ((flags & TMFAIL) > 0) { cacheTx.setRollbackOnly(); } <START> <END> }</code><technical_language>new line required</technical_language>

Target:
@Override public void end(Xid xid, int flags) throws XAException { assert this.xid.equals(xid); if (log.isDebugEnabled()) log.debug("XA resource end(...) [xid=" + xid + ", flags=<" + flags(flags) + ">]"); if ((flags & TMSUSPEND) == TMSUSPEND) try { cacheTx.suspend(); } catch (Exception e) { throwException("Failed to suspend cache transaction: " + e.getMessage(), e); } else if ((flags & TMFAIL) > 0) cacheTx.setRollbackOnly(); }
Source:
<code>private ContentResponse execute(Request req) { <START> logger.debug("Sending HTTP request: {}", req.getMethod(), safeUri(req)); <END> ContentResponse res = send(req); logger.debug("Received HTTP response: {}: {}", req.getMethod(), safeUri(req), res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else if (HttpStatus.isClientError(res.getStatus())) { throw new TaskExecutionException("HTTP 4XX Client Error: " + requestStatus(req, res), ConfigElement.empty()); } else if (res.getStatus() >= 500 && res.getStatus() < 600) { throw new RuntimeException("HTTP 5XX Server Error: " + requestStatus(req, res)); } else { throw new RuntimeException("Unexpected HTTP status: " + requestStatus(req, res)); } }</code><technical_language>[minor] This return safeUri() reused a lines below</technical_language>

Target:
private ContentResponse execute(Request req) { URI safeUri = safeUri(req); logger.debug("Sending HTTP request: {}", req.getMethod(), safeUri); ContentResponse res = send(req); logger.debug("Received HTTP response: {}: {}", req.getMethod(), safeUri, res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else if (HttpStatus.isClientError(res.getStatus())) { switch (res.getStatus()) { case HttpStatus.REQUEST_TIMEOUT_408: case HttpStatus.TOO_MANY_REQUESTS_429: throw new RuntimeException("Failed HTTP request: " + requestStatus(req, res)); default: throw new TaskExecutionException("HTTP 4XX Client Error: " + requestStatus(req, res), ConfigElement.empty()); } } else if (res.getStatus() >= 500 && res.getStatus() < 600) { throw ephemeralError("HTTP 5XX Server Error: " + requestStatus(req, res)); } else { throw ephemeralError("Unexpected HTTP status: " + requestStatus(req, res)); } }
Source:
<code>private Object doResumableUpload() throws IOException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; int retriesAttempted = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { <START> List<InsertObjectRequest.Builder> requestList = new ArrayList<>(); <END> responseObserver = new InsertChunkResponseObserver(uploadId, writeOffset, objectHasher, requestList); stub.withDeadlineAfter(WRITE_STREAM_TIMEOUT.toMillis(), MILLISECONDS) .insertObject(responseObserver); try { responseObserver.done.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException( String.format("Resumable upload failed for '%s'", getResourceString()), e); } if (responseObserver.hasTransientError()) { writeOffset = getCommittedWriteSize(uploadId); } else { writeOffset += responseObserver.bytesWritten(); } } while (!responseObserver.hasFinalized()); return responseObserver.getResponseOrThrow(); }</code><technical_language>I realize this original implementation but: ArrayList.remove is inefficient - requires copying elements. switching a LinkedList</technical_language>

Target:
private Object doResumableUpload() throws IOException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; int retriesAttempted = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); TreeMap<Long, ByteString> dataChunkMap = new TreeMap<>(); do { responseObserver = new InsertChunkResponseObserver(uploadId, writeOffset, objectHasher, dataChunkMap); stub.withDeadlineAfter(WRITE_STREAM_TIMEOUT.toMillis(), MILLISECONDS) .insertObject(responseObserver); try { responseObserver.done.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException( String.format("Resumable upload failed for '%s'", getResourceString()), e); } if (responseObserver.hasTransientError()) { writeOffset = getCommittedWriteSize(uploadId); ++retriesAttempted; } else { writeOffset += responseObserver.bytesWritten(); retriesAttempted = 0; } if (retriesAttempted >= UPLOAD_RETRIES) { throw new IOException( String.format( "Too many retry attempts. Resumable upload failed for '%s'", resourceId)); } } while (!responseObserver.hasFinalized()); return responseObserver.getResponseOrThrow(); }
Source:
<code>public void testConvertDs3RequestWithoutRequestPayload() { final Request testRequest = RequestConverter.toRequest( <START> new Ds3Request("CreateBucketRequestHandler", <END> HttpVerb.PUT, Classification.amazons3, Requirement.REQUIRED, Requirement.NOT_ALLOWED, null, null, null, null, false, null, ImmutableList.of(), ImmutableList.of())); assertFalse(testRequest.hasRequestPayload()); assertEquals(testRequest.getRequestPayload(), null); }</code><technical_language>This new fixture function createBucketRequest() instead of reconstructing Ds3 model</technical_language>

Target:
public void testConvertDs3RequestWithoutRequestPayload() { final Request testRequest = RequestConverter.toRequest(Ds3ModelFixtures.createBucketRequest()); assertFalse(testRequest.hasRequestPayload()); assertEquals(testRequest.getRequestPayload(), null); }
Source:
<code>public void testSequentialCommand() throws Exception { <START> final int NB_DOCS = 10; <END> final int NB_COMMANDS = 10; for (int i = 0; i < NB_DOCS; i++) { DocumentModel doc = session.createDocumentModel("/", "doc" + i, "File"); session.createDocument(doc); } TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); List<String> commands = new ArrayList<>(NB_COMMANDS); for (int i = 0; i < NB_COMMANDS; i++) { commands.add(service.submit( new BulkCommand.Builder("dummySequential", "SELECT * FROM File").user("Administrator").build())); commands.add(service.submit( new BulkCommand.Builder("dummyConcurrent", "SELECT * FROM File").user("Administrator").build())); } assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(60))); List<BulkStatus> results = new ArrayList<>(NB_COMMANDS); commands.forEach(id -> results.add(service.getStatus(id))); assertFalse(overlapCommands( results.stream().filter(r -> "dummySequential".equals(r.getAction())).collect(Collectors.toList()), true)); assertTrue(overlapCommands( results.stream().filter(r -> "dummyConcurrent".equals(r.getAction())).collect(Collectors.toList()), false)); }</code><technical_language>// NOSONAR avoid warnings uppercase variables</technical_language>

Target:
public void testSequentialCommand() throws Exception { final int nbDocs = 10; final int nbCommands = 10; for (int i = 0; i < nbDocs; i++) { DocumentModel doc = session.createDocumentModel("/", "doc" + i, "File"); session.createDocument(doc); } TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); List<String> commands = new ArrayList<>(nbCommands); for (int i = 0; i < nbCommands; i++) { commands.add(service.submit( new BulkCommand.Builder("dummySequential", "SELECT * FROM File").user("Administrator").build())); commands.add(service.submit( new BulkCommand.Builder("dummyConcurrent", "SELECT * FROM File").user("Administrator").build())); } assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(60))); List<BulkStatus> results = commands.stream().map(service::getStatus).collect(Collectors.toList()); assertFalse(overlapCommands( results.stream().filter(r -> "dummySequential".equals(r.getAction())).collect(Collectors.toList()), true)); assertTrue(overlapCommands( results.stream().filter(r -> "dummyConcurrent".equals(r.getAction())).collect(Collectors.toList()), false)); }
Source:
<code>public void shouldTrimImageNames() { <START> userProperties.setProperty("ryuk.container.image", " testcontainersofficial/ryuk:0.3.1 "); assertEquals("trailing whitespace was not removed from image name property", "testcontainersofficial/ryuk:0.3.1",newConfig().getRyukImage()); <END> }</code><technical_language>touching this code... :) suggestion userProperties.setProperty("ryuk.container.image", " testcontainers/ryuk:0.3.1 "); assertEquals("trailing whitespace removed image name property", "testcontainers/ryuk:0.3.1",newConfig().getRyukImage());</technical_language>

Target:
public void shouldTrimImageNames() { userProperties.setProperty("ryuk.container.image", " testcontainers/ryuk:0.3.1 "); assertEquals("trailing whitespace was not removed from image name property", "testcontainers/ryuk:0.3.1",newConfig().getRyukImage()); }
Source:
<code>public static Optional<Properties> getPropertiesFile(String propertiesFilePath){ try { InputStream input = new FileInputStream(propertiesFilePath); Properties properties = new Properties(); properties.load(input); return Optional.ofNullable(properties); <START> }catch(Exception e){ <END> logger.error("Error while reading property file '"+propertiesFilePath+"'",e); return Optional.ofNullable(null); } }</code><technical_language>spaces</technical_language>

Target:
public static Properties getPropertiesFile(String propertiesFilePath) throws IOException { InputStream input = new FileInputStream(propertiesFilePath); Properties properties = new Properties(); properties.load(input); return properties; }
Source:
<code>public UfsStatus remove(AlluxioURI path) { UfsStatus removed = mStatuses.remove(path); if (removed == null) { return null; } <START> mChildren.remove(path); END> return removed; }</code><technical_language>Is contract if status DNE, children list DNE for path? is unclear relationship is 2 maps</technical_language>

Target:
public UfsStatus remove(AlluxioURI path) { Preconditions.checkNotNull(path, "can't remove null status cache path"); UfsStatus removed = mStatuses.remove(path); mChildren.remove(path); return removed; }
Source:
<code><START> public static Object parse(final String value, final boolean allowMore) throws JSONException { <END> return parse(value, 0, value.length(), allowMore); }</code><technical_language>is public parse method returns plain Object. I need public method here, right</technical_language>

Target:
public static JSONObject parse(final String value, final boolean allowMore) throws JSONException { return (JSONObject) parse(value, 0, value.length(), allowMore); }
Source:
<code>public static void addService(final ServiceTarget serviceTarget, final GitRepository gitRepository, final File repoRoot, final File tmpRoot) { <START> if (gitRepository != null) { <END> ContentRepository.Factory.addService(serviceTarget, new GitContentRepository(gitRepository, repoRoot, tmpRoot, OBSOLETE_CONTENT_TIMEOUT, LOCK_TIMEOUT)); } else { ContentRepository.Factory.addService(serviceTarget, repoRoot, tmpRoot); } }</code><technical_language>gitRepository null in this GitContentRepository class</technical_language>

Target:
public static void addService(final ServiceTarget serviceTarget, final GitRepository gitRepository, final File repoRoot, final File tmpRoot) { ContentRepository.Factory.addService(serviceTarget, new GitContentRepository(gitRepository, repoRoot, tmpRoot, OBSOLETE_CONTENT_TIMEOUT, LOCK_TIMEOUT)); }
Source:
<code>public void testExpandByIdWithPreExpansionWithCount() throws Exception { myDaoConfig.setPreExpandValueSets(true); loadAndPersistCodeSystemAndValueSet(HTTPVerb.POST); myTermSvc.preExpandDeferredValueSetsToTerminologyTables(); Parameters respParam = ourClient .operation() .onInstance(myExtensionalVsId) .named("expand") .withParameter(Parameters.class, "count", new IntegerType(1)) .execute(); ValueSet expanded = (ValueSet) respParam.getParameter().get(0).getResource(); String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(expanded); ourLog.info(resp); <START> assertThat(resp, stringContainsInOrder( <END> "<total value=\"24\"/>\n", "<offset value=\"0\"/>\n", "<parameter>\n", "<name value=\"offset\"/>\n", "<valueInteger value=\"0\"/>\n", "</parameter>\n", "<parameter>\n", "<name value=\"count\"/>\n", "<valueInteger value=\"1\"/>\n", "</parameter>\n", "<contains>\n", "<system value=\"<LINK_0>\"/>\n", "<code value=\"8450-9\"/>\n", "<display value=\"Systolic blood pressure--expiration\"/>\n", "</contains>\n", "</expansion>")); }</code><technical_language>I a assert test expanded.getContains().size() a size of 1</technical_language>

Target:
public void testExpandByIdWithPreExpansionWithCount() throws Exception { myDaoConfig.setPreExpandValueSets(true); loadAndPersistCodeSystemAndValueSet(HTTPVerb.POST); myTermSvc.preExpandDeferredValueSetsToTerminologyTables(); Parameters respParam = ourClient .operation() .onInstance(myExtensionalVsId) .named("expand") .withParameter(Parameters.class, "count", new IntegerType(1)) .execute(); ValueSet expanded = (ValueSet) respParam.getParameter().get(0).getResource(); String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(expanded); ourLog.info(resp); assertEquals(24, expanded.getExpansion().getTotal()); assertEquals(0, expanded.getExpansion().getOffset()); assertEquals("offset", expanded.getExpansion().getParameter().get(0).getName()); assertEquals(0, expanded.getExpansion().getParameter().get(0).getValueIntegerType().getValue().intValue()); assertEquals("count", expanded.getExpansion().getParameter().get(1).getName()); assertEquals(1, expanded.getExpansion().getParameter().get(1).getValueIntegerType().getValue().intValue()); assertEquals(1, expanded.getExpansion().getContains().size()); assertEquals("<LINK_0>", expanded.getExpansion().getContainsFirstRep().getSystem()); assertEquals("8450-9", expanded.getExpansion().getContainsFirstRep().getCode()); assertEquals("Systolic blood pressure--expiration", expanded.getExpansion().getContainsFirstRep().getDisplay()); }
Source:
<code>private boolean registerLibvirtSecretsImpl(VDS vds, List<LibvirtSecret> libvirtSecrets, boolean clearUnusedSecrets) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vds.getId(), libvirtSecrets, clearUnusedSecrets)); if (!returnValue.getSucceeded()) { <START> log.error("Failed to register libvirt secret on vds {}.", vds.getName()); <END> return false; } return true; }</code><technical_language>this error line 179, shown twice. simply replace line 221-226 return returnValue.getSucceeded;</technical_language>

Target:
private boolean registerLibvirtSecretsImpl(VDS vds, List<LibvirtSecret> libvirtSecrets, boolean clearUnusedSecrets) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vds.getId(), libvirtSecrets, clearUnusedSecrets)); return returnValue.getSucceeded(); }
Source:
<code>public String toString() { return "FinalizingFieldAccessPostAggregator{" + <START> "name'" + name + '\'' + <END> ", fieldName='" + fieldName + '\'' + '}'; }</code><technical_language>name=' is missing equals sign</technical_language>

Target:
public String toString() { return "FinalizingFieldAccessPostAggregator{" + "name='" + name + '\'' + ", fieldName='" + fieldName + '\'' + '}'; }
Source:
<code>private boolean isUsingDefaultPassword() { <START> return getPlaintextPasswordFromProperties().equals("autogenerated"); <END> }</code><technical_language>getPlaintextPasswordFromProperties() is marked @Nullable means this result in a NPE. Reverse check ... "autogenerated".equals(getPlaintextPasswordFromProperties())</technical_language>

Target:
private boolean isUsingDefaultPassword() { return "autogenerated".equals(getPlaintextPasswordFromProperties()); }
Source:
<code>private void verifyResults(TestScenario testScenario, TestCase testCase, ApmMockServer apmServer) throws TestFailException { Collection<?> objects = getCapturedData(testScenario.getEnvironment().getType(), apmServer); System.out.println("Captured objects:\n" + objects); String json; try { json = serialize(objects); } catch (IOException e) { throw new TestFailException(testCase, "Failed to serialize traces", e); } for (JsonPathVerify jsonPathVerify: testCase.getVerify().getJsonPath()) { <START> if (!JsonPathVerifier.verify(json, jsonPathVerify)) { <END> throw new TestFailException(testCase, jsonPathVerify); } } }</code><technical_language>if more path returning false? collect failures report all, instead of failing first</technical_language>

Target:
private List<JsonPathVerify> verifyResults(TestScenario testScenario, TestCase testCase, ApmMockServer apmServer) { Collection<?> objects = getCapturedData(testScenario.getEnvironment().getType(), apmServer); log.info(String.format("Captured objects:\n%s", objects)); String json; try { json = serialize(objects); } catch (IOException ex) { log.severe(String.format("Failed to serialize traces: %s", objects)); throw new RuntimeException("Failed to serialize traces = " + objects, ex); } List<JsonPathVerify> failedJsonPathVerify = new ArrayList<>(); for (JsonPathVerify jsonPathVerify: testCase.getVerify().getJsonPath()) { if (!JsonPathVerifier.verify(json, jsonPathVerify)) { failedJsonPathVerify.add(jsonPathVerify); } } return failedJsonPathVerify; }
Source:
<code>protected String createProcessTitle(Map<String, String> context) { <START> return "Reindex"; <END> }</code><technical_language>s.a</technical_language>

Target:
protected String createProcessTitle(Map<String, String> context) { return Strings.apply("Reindexing mapping '%s'", context.get("ed")); }