auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<AuditLogWithHistory> getAuditLogsWithHistoryForId(final UUID accountId, final AuditLevel auditLevel, final InternalTenantContext context) throws AccountApiException { <START> return transactionalSqlDao.execute(false, AccountApiException.class, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { <END> @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws EntityPersistenceException, EventBusException { final AccountSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT, accountId, auditLevel, context); } }); }</code><technical_language>true instead (it's a read-only operation)</technical_language>

Target:
public List<AuditLogWithHistory> getAuditLogsWithHistoryForId(final UUID accountId, final AuditLevel auditLevel, final InternalTenantContext context) throws AccountApiException { return transactionalSqlDao.execute(true, AccountApiException.class, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) { final AccountSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT, accountId, auditLevel, context); } }); }
Source:
<code>public void testStatementPeriodMONTHLY() { Calendar date = Calendar.getInstance(); Calendar aCalendar = Calendar.getInstance(); date = Calendar.getInstance(); date.set(Calendar.DATE, QuotaStatementImpl.s_LAST_STATEMENT_SENT_DAYS + 1); Calendar period[] = quotaStatement.statementTime(date, STATEMENT_PERIODS.MONTHLY); assertTrue(period == null); date.set(Calendar.DATE, QuotaStatementImpl.s_LAST_STATEMENT_SENT_DAYS - 1); period = quotaStatement.statementTime(date, STATEMENT_PERIODS.MONTHLY); assertTrue(period != null); <START> assertTrue(period[0].toString(), period[0].before(period[1])); <END> assertTrue(period[0].toString(), period[0].get(Calendar.DATE) == 1); aCalendar = Calendar.getInstance(); aCalendar.add(Calendar.MONTH, -1); aCalendar.set(Calendar.DATE, aCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1); assertTrue(period[1].toString(), period[1].get(Calendar.DATE) == aCalendar.get(Calendar.DATE)); }</code><technical_language>Add assertion length of period is 2 avoid a confusing ArrayIndexOutofBoundsException</technical_language>

Target:
public void testStatementPeriodMONTHLY() { Calendar date = Calendar.getInstance(); Calendar aCalendar = Calendar.getInstance(); date = Calendar.getInstance(); date.set(Calendar.DATE, QuotaStatementImpl.s_LAST_STATEMENT_SENT_DAYS + 1); Calendar period[] = quotaStatement.statementTime(date, STATEMENT_PERIODS.MONTHLY); assertTrue(period == null); date.set(Calendar.DATE, QuotaStatementImpl.s_LAST_STATEMENT_SENT_DAYS - 1); period = quotaStatement.statementTime(date, STATEMENT_PERIODS.MONTHLY); assertTrue(period != null); assertTrue(period.length == 2); assertTrue(period[0].toString(), period[0].before(period[1])); assertTrue(period[0].toString(), period[0].get(Calendar.DATE) == 1); aCalendar = Calendar.getInstance(); aCalendar.add(Calendar.MONTH, -1); aCalendar.set(Calendar.DATE, aCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1); assertTrue(period[1].toString(), period[1].get(Calendar.DATE) == aCalendar.get(Calendar.DATE)); }
Source:
<code>public void spec103_mustSignalOnMethodsSequentially() throws Exception { <START> notVerified(); END> }</code><technical_language>stochastically test it</technical_language>

Target:
public void spec103_mustSignalOnMethodsSequentially() throws Throwable { final int iterations = 100; final int elements = 10; stochasticTest(iterations, new Function<Integer, Void>() { @Override public Void apply(final Integer runNumber) throws Throwable { activePublisherTest(elements, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { final Latch callLatch = new Latch(env); final Latch completionLatch = new Latch(env); pub.subscribe(new Subscriber<T>() { private Subscription subs; private long gotElements = 0; private String state = "init"; @Override public void onSubscribe(Subscription s) { callLatch.assertOpen("Expected latch to be open during onSubscribe call, state seems to be: " + state); callLatch.close(); state = "onSubscribe"; subs = s; subs.request(1); callLatch.reOpen(); } @Override public void onNext(T ignore) { callLatch.assertOpen("Expected latch to be open during onNext call, state seems to be: " + state); callLatch.close(); state = "onNext-" + ignore; gotElements += 1; if (gotElements <= elements) subs.request(1); callLatch.reOpen(); } @Override public void onError(Throwable t) { callLatch.assertOpen("Expected latch to be open during onError call, state seems to be: " + state); callLatch.close(); state = "onError"; callLatch.reOpen(); } @Override public void onComplete() { callLatch.assertOpen("Expected latch to be open during onComplete call, state seems to be: " + state); callLatch.close(); state = "onComplete"; callLatch.reOpen(); completionLatch.close(); } }); completionLatch.expectClose(elements * env.defaultTimeoutMillis(), "Expected 10 elements to be drained"); } }); return null; } }); }
Source:
<code>public void localeTwoLetterCodeResolves() { <START> assertThat("A locale with a 2-letter code resolves correctly", <END> LanguageUtil.getLocale("af").getDisplayLanguage().equals("Afrikaans")); }</code><technical_language>tests pass if users locale is non-English? I of non-instrumented test runs in English</technical_language>

Target:
public void localeTwoLetterCodeResolves() { assertThat("A locale with a 3-letter code resolves correctly", "Afrikaans", is(LanguageUtil.getLocale("af").getDisplayLanguage())); }
Source:
<code>private void loadCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char[] password = "testpassword".toCharArray(); <START> String testTrustKeyStorePath = "src/test/testTrustKeyStore"; <END> System.setProperty("javax.net.ssl.trustStore" , testTrustKeyStorePath); File file = new File(testTrustKeyStorePath); InputStream localCertIn = new FileInputStream(file); ks.load(localCertIn, password); localCertIn.close(); if (ks.containsAlias("nutch")) { return; } InputStream certIn = new FileInputStream("src/test/nutch.cer"); BufferedInputStream bis = new BufferedInputStream(certIn); CertificateFactory cf = CertificateFactory.getInstance("X.509"); while (bis.available() > 0) { Certificate cert = cf.generateCertificate(bis); ks.setCertificateEntry("nutch", cert); } certIn.close(); OutputStream out = new FileOutputStream(file); ks.store(out, password); out.close(); }</code><technical_language>This break Windows for sure. Please classloader</technical_language>

Target:
private void loadCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { String testTrustKeyStorePath = getResourcePath("testTrustKeyStore"); File file = new File(testTrustKeyStorePath); InputStream localCertIn = new FileInputStream(file); char[] password = "testpassword".toCharArray(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(localCertIn, password); localCertIn.close(); if (ks.containsAlias("nutch")) { return; } String cerFilePath = getResourcePath("nutch.cer"); InputStream certIn = new FileInputStream(cerFilePath); BufferedInputStream bis = new BufferedInputStream(certIn); CertificateFactory cf = CertificateFactory.getInstance("X.509"); while (bis.available() > 0) { Certificate cert = cf.generateCertificate(bis); ks.setCertificateEntry("nutch", cert); } certIn.close(); OutputStream out = new FileOutputStream(file); ks.store(out, password); out.close(); }
Source:
<code>public void onCompletion(RecordMetadata recordMetadata, Exception e) { if (e != null) { <START> if(body instanceof Exchange) { <END> ((Exchange)body).setException(e); } } recordMetadatas.add(recordMetadata); if (count.decrementAndGet() == 0) { workerPool.submit(new Runnable() { @Override public void run() { log.trace("All messages sent, continue routing."); if(callback != null) { callback.done(false); } } }); } }</code><technical_language>I if check for instanceof Message here, if a message, message -> getExchange get set exception</technical_language>

Target:
public void onCompletion(RecordMetadata recordMetadata, Exception e) { if (e != null) { if (body instanceof Exchange) { ((Exchange)body).setException(e); } if (body instanceof Message && ((Message)body).getExchange() != null) { ((Message)body).getExchange().setException(e); } } recordMetadatas.add(recordMetadata); if (count.decrementAndGet() == 0) { workerPool.submit(new Runnable() { @Override public void run() { log.trace("All messages sent, continue routing."); if (callback != null) { callback.done(false); } } }); } }
Source:
<code>public DisksAllocationView() { diskAllocationTargetEnabled = new EntityModelCheckBoxEditor(Align.RIGHT); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); driver.initialize(this); <START> listHeader = new EntityModelCellTable(false, (Resources) GWT.create( <END> PopupSimpleTableResources.class), true); }</code><technical_language>this, get NPE calling driver.cleanup() generated impl. like: getEditor().myField.cleanup(); I perfectly valid for a field null, right for driver.cleanup() assume fields non-null. suggest remove this code fix driver.cleanup() like: if (getEditor().myField != null) { getEditor().myField.cleanup(); } TL;DR hidden "field non-null avoid NPE" assumption removed</technical_language>

Target:
public DisksAllocationView() { diskAllocationTargetEnabled = new EntityModelCheckBoxEditor(Align.RIGHT); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); driver.initialize(this); }
Source:
<code>private void handleMissingResponse(Response response) { if (response instanceof UnsureResponse) { allFuture.hasUnsureResponse = true; } Map<Object, Collection<Address>> contactedNodes = this.contactedNodes == null ? new HashMap<>() : this.contactedNodes; Map<Address, List<Object>> requestedKeys; synchronized (contactedNodes) { for (Object key : keys) { contactedNodes.computeIfAbsent(key, k -> new ArrayList<>(4)).add(target); } requestedKeys = getKeysByOwner(ctx, keys, checkTopologyId(command), null, contactedNodes); } int pos = destinationIndex; for (Map.Entry<Address, List<Object>> addressKeys : requestedKeys.entrySet()) { allFuture.increment(); List<Object> keysForAddress = addressKeys.getValue(); ReadOnlyManyCommand remoteCommand = helper.copyForRemote(command, keysForAddress, ctx); remoteCommand.setTopologyId(command.getTopologyId()); Address target = addressKeys.getKey(); <START> rpcManager.invokeCommand(target, remoteCommand, new MapResponseCollector(true, 1), <END> rpcManager.getSyncRpcOptions()) .whenComplete(new ReadManyHandler(target, allFuture, ctx, command, keysForAddress, contactedNodes, pos, helper)); pos += keysForAddress.size(); } Arrays.fill(allFuture.results, pos, destinationIndex + keys.size(), LOST_PLACEHOLDER); allFuture.lostData = true; allFuture.countDown(); }</code><technical_language>SingleResponseCollector</technical_language>

Target:
private void handleMissingResponse(Response response) { if (response instanceof UnsureResponse) { allFuture.hasUnsureResponse = true; } Map<Object, Collection<Address>> contactedNodes = this.contactedNodes == null ? new HashMap<>() : this.contactedNodes; Map<Address, List<Object>> requestedKeys; synchronized (contactedNodes) { for (Object key : keys) { contactedNodes.computeIfAbsent(key, k -> new ArrayList<>(4)).add(target); } requestedKeys = getKeysByOwner(ctx, keys, checkTopologyId(command), null, contactedNodes); } int pos = destinationIndex; for (Map.Entry<Address, List<Object>> addressKeys : requestedKeys.entrySet()) { allFuture.increment(); List<Object> keysForAddress = addressKeys.getValue(); ReadOnlyManyCommand remoteCommand = helper.copyForRemote(command, keysForAddress, ctx); remoteCommand.setTopologyId(command.getTopologyId()); Address target = addressKeys.getKey(); rpcManager.invokeCommand(target, remoteCommand, SingletonMapResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()) .whenComplete(new ReadManyHandler(target, allFuture, ctx, command, keysForAddress, contactedNodes, pos, helper)); pos += keysForAddress.size(); } Arrays.fill(allFuture.results, pos, destinationIndex + keys.size(), LOST_PLACEHOLDER); allFuture.lostData = true; allFuture.countDown(); }
Source:
<code>SweepResults runOneIteration( TableReference tableRef, byte[] startRow, SweepBatchConfig batchConfig) { Stopwatch watch = Stopwatch.createStarted(); try { <START> log.info("Beginning"); <END> SweepResults results = sweepRunner.run( tableRef, batchConfig, startRow); long elapsedMillis = watch.elapsed(TimeUnit.MILLISECONDS); log.info("Swept successfully.", LoggingArgs.tableRef("tableRef", tableRef), UnsafeArg.of("startRow", startRowToHex(startRow)), SafeArg.of("cellTs pairs examined", results.getCellTsPairsExamined()), SafeArg.of("cellTs pairs deleted", results.getStaleValuesDeleted()), SafeArg.of("time taken", elapsedMillis), SafeArg.of("last swept timestamp", results.getSweptTimestamp())); sweepPerfLogger.logSweepResults( SweepPerformanceResults.builder() .sweepResults(results) .tableName(tableRef.getQualifiedName()) .elapsedMillis(elapsedMillis) .build()); return results; } catch (RuntimeException e) { log.info("Failed to sweep.", LoggingArgs.tableRef("tableRef", tableRef), UnsafeArg.of("startRow", startRowToHex(startRow)), SafeArg.of("batchConfig", batchConfig)); throw e; } }</code><technical_language>add more info here.. lets beggining sweep table x startrow x batchConfig x</technical_language>

Target:
SweepResults runOneIteration( TableReference tableRef, byte[] startRow, SweepBatchConfig batchConfig) { Stopwatch watch = Stopwatch.createStarted(); try { SweepResults results = sweepRunner.run( tableRef, batchConfig, startRow); long elapsedMillis = watch.elapsed(TimeUnit.MILLISECONDS); log.info("Analyzed cell+timestamp pairs" + " from table {}" + " starting at row {}" + " and deleted stale values" + " in ms" + " up to timestamp {}.", SafeArg.of("cellTs pairs examined", results.getCellTsPairsExamined()), LoggingArgs.tableRef("tableRef", tableRef), UnsafeArg.of("startRow", startRowToHex(startRow)), SafeArg.of("cellTs pairs deleted", results.getStaleValuesDeleted()), SafeArg.of("time taken", elapsedMillis), SafeArg.of("last swept timestamp", results.getSweptTimestamp())); sweepPerfLogger.logSweepResults( SweepPerformanceResults.builder() .sweepResults(results) .tableName(tableRef.getQualifiedName()) .elapsedMillis(elapsedMillis) .build()); return results; } catch (RuntimeException e) { log.info("Failed to sweep table {}" + " at row {}" + " with candidate batch size {}," + " delete batch size {}," + " and cell+timestamp pairs to examine.", LoggingArgs.tableRef("tableRef", tableRef), UnsafeArg.of("startRow", startRowToHex(startRow)), SafeArg.of("candidateBatchSize", batchConfig.candidateBatchSize()), SafeArg.of("deleteBatchSize", batchConfig.deleteBatchSize()), SafeArg.of("maxCellTsPairsToExamine", batchConfig.maxCellTsPairsToExamine()), e); throw e; } }
Source:
<code>public void run() { <START> for(ManagedScheduledExecutorServiceImpl service : managedScheduledExecutorServices) { <END> Collection<AbstractManagedThread> hungThreads = service.getHungThreads(); if (hungThreads != null && !hungThreads.isEmpty()) { for (AbstractManagedThread hungThread : hungThreads) { EeLogger.ROOT_LOGGER.abortingHungThread(hungThread.toString(), service.getName()); hungThread.interrupt(); } } } }</code><technical_language>This iteration is thread-safe</technical_language>

Target:
public void run() { List<ManagedScheduledExecutorServiceImpl> threadSaveList; synchronized (managedScheduledExecutorServices) { threadSaveList = new ArrayList<>(managedScheduledExecutorServices); } for(ManagedScheduledExecutorServiceImpl service : threadSaveList) { Collection<AbstractManagedThread> hungThreads = service.getHungThreads(); if (hungThreads != null && !hungThreads.isEmpty()) { for (AbstractManagedThread hungThread : hungThreads) { EeLogger.ROOT_LOGGER.abortingHungThread(hungThread.toString(), service.getName()); hungThread.interrupt(); } } } }
Source:
<code>private void getSealedPartitionsInDc(Datacenter dc, Map<String, Set<String>> dcToSealedPartitions, Map<String, Set<String>> nodeToNonExistentReplicas) { String dcName = dc.getName(); dcToSealedPartitions.put(dcName, new HashSet<>()); HelixAdmin admin = adminForDc.get(dcName); Set<String> allInstancesInHelix = new HashSet<>(admin.getInstancesInCluster(clusterName)); for (DataNodeId dataNodeId : dc.getDataNodes()) { DataNode dataNode = (DataNode) dataNodeId; Set<String> replicasOnNode = staticClusterMap.getReplicas(dataNode) .stream() .map(replicaId -> replicaId.getPartitionId().toPathString()) .collect(Collectors.toSet()); String instanceName = getInstanceName(dataNode); ensureOrThrow(allInstancesInHelix.contains(instanceName), "Instance not present in Helix " + instanceName); InstanceConfig instanceConfig = admin.getInstanceConfig(clusterName, instanceName); List<String> sealedReplicas = instanceConfig.getRecord().getListField(ClusterMapUtils.SEALED_STR); if (sealedReplicas != null) { for (String sealedReplica : sealedReplicas) { info("Replica is sealed on {}", sealedReplica, instanceName); dcToSealedPartitions.get(dcName).add(sealedReplica); if (!replicasOnNode.contains(sealedReplica)) { <START> logger.warn("Replica is in sealed list but not on node {}", sealedReplica, replicasOnNode); <END> nodeToNonExistentReplicas.computeIfAbsent(instanceName, key -> new HashSet<>()).add(sealedReplica); } } } } }</code><technical_language>replicasOnNode is a set of replicas a node, want log node id here</technical_language>

Target:
private void getSealedPartitionsInDc(Datacenter dc, Map<String, Set<String>> dcToSealedPartitions, Map<String, Set<String>> nodeToNonExistentReplicas) { String dcName = dc.getName(); dcToSealedPartitions.put(dcName, new HashSet<>()); HelixAdmin admin = adminForDc.get(dcName); Set<String> allInstancesInHelix = new HashSet<>(admin.getInstancesInCluster(clusterName)); for (DataNodeId dataNodeId : dc.getDataNodes()) { DataNode dataNode = (DataNode) dataNodeId; Set<String> replicasOnNode = staticClusterMap.getReplicas(dataNode) .stream() .map(replicaId -> replicaId.getPartitionId().toPathString()) .collect(Collectors.toSet()); String instanceName = getInstanceName(dataNode); ensureOrThrow(allInstancesInHelix.contains(instanceName), "Instance not present in Helix " + instanceName); InstanceConfig instanceConfig = admin.getInstanceConfig(clusterName, instanceName); List<String> sealedReplicas = instanceConfig.getRecord().getListField(ClusterMapUtils.SEALED_STR); if (sealedReplicas != null) { for (String sealedReplica : sealedReplicas) { info("Replica is sealed on {}", sealedReplica, instanceName); dcToSealedPartitions.get(dcName).add(sealedReplica); if (!replicasOnNode.contains(sealedReplica)) { logger.warn("Replica is in sealed list but not on node {}", sealedReplica, instanceName); nodeToNonExistentReplicas.computeIfAbsent(instanceName, key -> new HashSet<>()).add(sealedReplica); } } } } }
Source:
<code>public boolean isTaskExecutable(NodeSet selectedNodes, EligibleTaskDescriptor task) { <START> logger.info("Selected Nodes: " + selectedNodes); <END> logger.info("Analysing task: " + task.getInternal().getName()); String allocRam = task.getInternal().getGenericInformation().get(RAM_VARIABLE_NAME); if (allocRam != null) { return canRunTaskOnNode(selectedNodes, task, Integer.parseInt(allocRam)); } else { return true; } }</code><technical_language>loggers changed debug</technical_language>

Target:
public boolean isTaskExecutable(NodeSet selectedNodes, EligibleTaskDescriptor task) { logger.debug("Selected Nodes: " + selectedNodes); logger.debug("Analysing task: " + task.getInternal().getName()); String allocRam = task.getInternal().getGenericInformation().get(RAM_VARIABLE_NAME); if (allocRam != null) { return canRunTaskOnNode(selectedNodes, task, Integer.parseInt(allocRam)); } else { return true; } }
Source:
<code>public void testResolvedSymRef() throws IOException { Ref ref = db.getRef(Constants.HEAD); assertEquals(Constants.HEAD, ref.getName()); assertTrue("is symbolic ref", ref instanceof SymbolicRef); assertSame(Ref.Storage.LOOSE, ref.getStorage()); <START> Ref dst = ((SymbolicRef) ref).getTarget(); <END> assertNotNull("has target", dst); assertEquals("refs/heads/master", dst.getName()); assertSame(dst.getObjectId(), ref.getObjectId()); assertSame(dst.getPeeledObjectId(), ref.getPeeledObjectId()); assertEquals(dst.isPeeled(), ref.isPeeled()); }</code><technical_language>getTarget a part of Ref API</technical_language>

Target:
public void testResolvedSymRef() throws IOException { Ref ref = db.getRef(Constants.HEAD); assertEquals(Constants.HEAD, ref.getName()); assertTrue("is symbolic ref", ref.isSymbolic()); assertSame(Ref.Storage.LOOSE, ref.getStorage()); Ref dst = ref.getTarget(); assertNotNull("has target", dst); assertEquals("refs/heads/master", dst.getName()); assertSame(dst.getObjectId(), ref.getObjectId()); assertSame(dst.getPeeledObjectId(), ref.getPeeledObjectId()); assertEquals(dst.isPeeled(), ref.isPeeled()); }
Source:
<code><START> public void fetchesUrls() throws Exception { <END> final Release release = Mockito.mock(Release.class); final String url = "http://url"; final String htmlurl = "http://html_url"; final String assetsurl = "http://assets_url"; final String uploadurl = "http://upload_url"; Mockito.doReturn( Json.createObjectBuilder() .add("url", url) .add("html_url", htmlurl) .add("assets_url", assetsurl) .add("upload_url", uploadurl) .build() ).when(release).json(); final Release.Smart smart = new Release.Smart(release); MatcherAssert.assertThat( smart.url().toString(), Matchers.equalTo(url) ); MatcherAssert.assertThat( smart.htmlUrl().toString(), Matchers.equalTo(htmlurl) ); MatcherAssert.assertThat( smart.assetsUrl().toString(), Matchers.equalTo(assetsurl) ); MatcherAssert.assertThat( smart.uploadUrl().toString(), Matchers.equalTo(uploadurl) ); }</code><technical_language>Denis, this tests violates basic testing principle: "One test item". Unit tests independent</technical_language>

Target:
public void fetchesUrls() throws Exception { final Release release = Mockito.mock(Release.class); final String url = "http://url"; Mockito.doReturn( Json.createObjectBuilder() .add("url", url) .build() ).when(release).json(); final Release.Smart smart = new Release.Smart(release); MatcherAssert.assertThat( smart.url().toString(), Matchers.equalTo(url) ); }
Source:
<code>private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) { if (BINDINGS.containsKey(cls)) { if (debug) Log.d(TAG, "HIT: Cached in binding map."); <START> return BINDINGS.get(cls); <END> } String clsName = cls.getName(); if (clsName.startsWith("android.") || clsName.startsWith("java.") || clsName.startsWith("androidx.")) { if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); return null; } Constructor<? extends Unbinder> bindingCtor; try { Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding"); bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class); if (debug) Log.d(TAG, "HIT: Loaded binding class and constructor."); } catch (ClassNotFoundException e) { if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); bindingCtor = findBindingConstructorForClass(cls.getSuperclass()); } catch (NoSuchMethodException e) { throw new RuntimeException("Unable to find binding constructor for " + clsName, e); } BINDINGS.put(cls, bindingCtor); return bindingCtor; }</code><technical_language>I this requires a double hash lookup in common case. revert logic check containsKey if get returns null</technical_language>

Target:
private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> cls) { Constructor<? extends Unbinder> bindingCtor = BINDINGS.get(cls); if (bindingCtor != null) { if (debug) Log.d(TAG, "HIT: Cached in binding map."); return bindingCtor; } String clsName = cls.getName(); if (clsName.startsWith("android.") || clsName.startsWith("java.") || clsName.startsWith("androidx.")) { if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); return null; } try { Class<?> bindingClass = cls.getClassLoader().loadClass(clsName + "_ViewBinding"); bindingCtor = (Constructor<? extends Unbinder>) bindingClass.getConstructor(cls, View.class); if (debug) Log.d(TAG, "HIT: Loaded binding class and constructor."); } catch (ClassNotFoundException e) { if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); bindingCtor = findBindingConstructorForClass(cls.getSuperclass()); } catch (NoSuchMethodException e) { throw new RuntimeException("Unable to find binding constructor for " + clsName, e); } BINDINGS.put(cls, bindingCtor); return bindingCtor; }
Source:
<code>void waitUntilConnectionIsOpen() { try { executorService.awaitTermination(connectTimeoutMillis, TimeUnit.MILLISECONDS); if (!connectionThread.get() || !webSocketClient.isOpen()) { throw new CouldNotConnect(); } } catch (final InterruptedException | ExecutionException e) { <START> throw new CouldNotConnect(e); <END> } }</code><technical_language>re-interrupt current thread interruptedexception is thrown</technical_language>

Target:
void waitUntilConnectionIsOpen() { try { executorService.awaitTermination(connectTimeoutMillis, TimeUnit.MILLISECONDS); if (!connectionThread.get() || !webSocketClient.isOpen()) { throw new CouldNotConnect(); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } catch (final ExecutionException e) { throw new CouldNotConnect(e); } }
Source:
<code>public int getProviderSpecVersionCode() { try { ProviderInfo info = mContext.getPackageManager().resolveContentProvider(FlashCardsContract.AUTHORITY, PackageManager.GET_META_DATA); if (info == null) { return -1; } Bundle metaData = info.metaData; if (metaData == null) { return DEFAULT_PROVIDER_SPEC_VALUE; } if (info.metaData.containsKey(PROVIDER_SPEC_META_DATA_KEY)) { return info.metaData.getInt(PROVIDER_SPEC_META_DATA_KEY); } else { return DEFAULT_PROVIDER_SPEC_VALUE; } } <START> catch (Throwable t) { <END> return -2; } }</code><technical_language>I catch necessary, code is verbose, name of method suitable for a public method. this? java /** version of AnkiDroid supports fast bulk insert **/ public boolean supportsBulkInsert() { return getProviderSpecVersionCode() >= BULK_INSERT_MIN_SPEC_VERSION; } private int getProviderSpecVersionCode() { ProviderInfo info = mContext.getPackageManager().resolveContentProvider(FlashCardsContract.AUTHORITY, PackageManager.GET_META_DATA); if (info == null) { return -1; } Bundle metaData = info.metaData; if (metaData == null || !metaData.containsKey(PROVIDER_SPEC_META_DATA_KEY)) { return DEFAULT_PROVIDER_SPEC_VALUE; } return metaData.getInt(PROVIDER_SPEC_META_DATA_KEY); }</technical_language>

Target:
private int getProviderSpecVersionCode() { ProviderInfo info = mContext.getPackageManager().resolveContentProvider(FlashCardsContract.AUTHORITY, PackageManager.GET_META_DATA); if (info == null) { return -1; } if (info.metaData != null && info.metaData.containsKey(PROVIDER_SPEC_META_DATA_KEY)) { return info.metaData.getInt(PROVIDER_SPEC_META_DATA_KEY); } else { return DEFAULT_PROVIDER_SPEC_VALUE; } }
Source:
<code>public IndexCoordinates getIndexCoordinates() { <START> return indexCoordinatesResolver.resolve(getEvaluationContext(null), IndexCoordinates.of(getIndexName())); <END> }</code><technical_language>simplifying this method IndexCoordinates.of(getIndexName())) keeping evaluation getIndexName()</technical_language>

Target:
public IndexCoordinates getIndexCoordinates() { return resolve(IndexCoordinates.of(getIndexName())); }
Source:
<code>public boolean remove(SimpleUri id) { Setting setting = get(id); if (setting == null) { <START> LOGGER.warn("The setting to remove with the id \"{}\" does not exist in the config.", id); <END> return false; } else if (setting.hasSubscribers()) { LOGGER.warn("The setting with the id \"{}\" still has subscribers and cannot be removed.", id); return false; } settingMap.remove(id); return true; }</code><technical_language>write: LOGGER.warn("Setting \"{}\" exist.", id); below: LOGGER.warn("Setting \"{}\" removed while subscribers.", id);</technical_language>

Target:
public boolean remove(SimpleUri id) { Setting setting = get(id); if (setting == null) { LOGGER.warn("Setting \"{}\" does not exist.", id); return false; } else if (setting.hasSubscribers()) { LOGGER.warn("Setting \"{}\" cannot be removed while it has subscribers.", id); return false; } settingMap.remove(id); return true; }
Source:
<code>public void testRandomCell() { for (int i = 0; i < 50; i++) { <START> Optional<MockCell> c = grid.getRandomCell(cell -> cell.getX() < 3 && cell.getY() > CELL_HEIGHT); <END> assertTrue(c.isPresent()); MockCell cell = c.get(); assertThat(cell.getX(), allOf(greaterThanOrEqualTo(0), lessThan(3))); assertThat(cell.getY(), allOf(greaterThanOrEqualTo(16), lessThan(20))); } assertThat(grid.getRandomCell(new Random(), c -> false).isPresent(), is(false)); }</code><technical_language>Please revert change this line. 15 is CELL_HEIGHT, is same. Otherwise, a change of CELL_HEIGHT unintentionally break this test</technical_language>

Target:
public void testRandomCell() { for (int i = 0; i < 50; i++) { Optional<MockCell> c = grid.getRandomCell(cell -> cell.getX() < 3 && cell.getY() > 15); assertTrue(c.isPresent()); MockCell cell = c.get(); assertThat(cell.getX(), allOf(greaterThanOrEqualTo(0), lessThan(3))); assertThat(cell.getY(), allOf(greaterThanOrEqualTo(16), lessThan(20))); } assertThat(grid.getRandomCell(new Random(), c -> false).isPresent(), is(false)); }
Source:
<code>public Codec getCodec() { <START> return new NMFDataCodec(); <END> }</code><technical_language>Do new instance of NMFDataCodec time</technical_language>

Target:
public Codec getCodec() { return nmfDataCodec; }
Source:
<code>public void refresh() { isRefreshCancelled = false; savedPagesCompleted = 0; progressDialog.show(); for (int i = 0; i < savedPages.size(); i++) { final SavedPage savedPage = savedPages.get(i); <START> new RefreshSavedPageTask((WikipediaApp) context.getApplicationContext(), savedPage) { <END> @Override public void onBeforeExecute() { if (isRefreshCancelled) { cancel(); return; } Log.d("Wikipedia", "refreshing start: " + savedPage.getTitle().getDisplayText()); } @Override public void onFinish(List<Section> result) { if (!progressDialog.isShowing()) { isRefreshCancelled = true; return; } savedPagesCompleted++; progressDialog.setProgress(savedPagesCompleted); Log.d("Wikipedia", "Count is " + savedPagesCompleted + " of " + savedPages.size()); if (savedPagesCompleted == savedPages.size()) { progressDialog.dismiss(); } Log.d("Wikipedia", "refreshing end: " + savedPage.getTitle().getDisplayText()); } @Override public void onCatch(Throwable caught) { isRefreshCancelled = true; if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); getErrorDialog().show(); } }.execute(); } }</code><technical_language>WikipediaApp.getInstance() alternative is cast</technical_language>

Target:
public void refresh() { isRefreshCancelled = false; savedPagesCompleted = 0; progressDialog.show(); for (int i = 0; i < savedPages.size(); i++) { final SavedPage savedPage = savedPages.get(i); new RefreshSavedPageTask(WikipediaApp.getInstance(), savedPage) { @Override public void onBeforeExecute() { if (isRefreshCancelled) { cancel(); return; } Log.d("Wikipedia", "refreshing start: " + savedPage.getTitle().getDisplayText()); } @Override public void onFinish(List<Section> result) { if (!progressDialog.isShowing()) { isRefreshCancelled = true; return; } savedPagesCompleted++; progressDialog.setProgress(savedPagesCompleted); Log.d("Wikipedia", "Count is " + savedPagesCompleted + " of " + savedPages.size()); if (savedPagesCompleted == savedPages.size()) { progressDialog.dismiss(); } Log.d("Wikipedia", "refreshing end: " + savedPage.getTitle().getDisplayText()); } @Override public void onCatch(Throwable caught) { isRefreshCancelled = true; if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); getErrorDialog().show(); } }.execute(); } }
Source:
<code>public void registerDefaults() { StatList.allStats.stream() <START> .map(statistic -> (Statistic) statistic) <END> .map(stat -> stat.getStatisticFormat().orElse(stat.getGroup().getDefaultStatisticFormat())) .distinct() .forEach(this::registerAdditionalCatalog); }</code><technical_language>combine cast call below, .map(stat -> ((Statistic) stat).getStatisticFormat()..</technical_language>

Target:
public void registerDefaults() { StatList.ALL_STATS.stream() .map(statistic -> (Statistic) statistic) .map(stat -> stat.getStatisticFormat().orElse(stat.getGroup().getDefaultStatisticFormat())) .distinct() .forEach(this::registerAdditionalCatalog); }
Source:
<code>Stream<Host> getPrioritizedHostStream(Stream<Host> hostStream, Capabilities capabilities) { Set<Host> filteredHostSet = hostStream.collect(Collectors.toSet()); Map<String, Set<Host>> hostBuckets = sortHostsToBucketsByBrowser(filteredHostSet); if (allBucketsSameSize(hostBuckets)) { LOG.fine("All Hosts Prioritized prior to sorting"); return hostBuckets.values().stream().distinct().flatMap(Set::stream); } final List<Map.Entry<String, Set<Host>>> sorted = hostBuckets.entrySet().stream().sorted( Comparator.comparingInt(v -> v.getValue().size()) ).collect(Collectors.toList()); <START> LOG.info(sorted.toString()); <END> Map<String, Set<Host>> newHostBuckets; for (Map.Entry<String, Set<Host>> entry: sorted) { if (entry.getKey().equals(capabilities.getBrowserName())) { continue; } final Set<Host> filteredHosts = filteredHostSet.stream().filter(host -> !entry.getValue().contains(host)).collect(Collectors.toSet()); newHostBuckets = sortHostsToBucketsByBrowser(filteredHosts); if (allBucketsSameSize(newHostBuckets)) { LOG.fine("Hosts have been balanced according to browser priority"); return newHostBuckets.values().stream().distinct().flatMap(Set::stream); } } return hostBuckets.values().stream().distinct().flatMap(Set::stream); }</code><technical_language>want drop logging level in a follow-up PR</technical_language>

Target:
Stream<Host> getPrioritizedHostStream(Stream<Host> hostStream, Capabilities capabilities) { Set<Host> filteredHostSet = hostStream.collect(Collectors.toSet()); Map<String, Set<Host>> hostBuckets = sortHostsToBucketsByBrowser(filteredHostSet); if (allBucketsSameSize(hostBuckets)) { return hostBuckets.values().stream().distinct().flatMap(Set::stream); } final List<Map.Entry<String, Set<Host>>> sorted = hostBuckets.entrySet().stream().sorted( Comparator.comparingInt(v -> v.getValue().size()) ).collect(Collectors.toList()); Map<String, Set<Host>> newHostBuckets; for (Map.Entry<String, Set<Host>> entry: sorted) { if (entry.getKey().equals(capabilities.getBrowserName())) { continue; } final Set<Host> filteredHosts = filteredHostSet.stream().filter(host -> !entry.getValue().contains(host)).collect(Collectors.toSet()); newHostBuckets = sortHostsToBucketsByBrowser(filteredHosts); if (allBucketsSameSize(newHostBuckets)) { LOG.fine("Hosts have been balanced according to browser priority"); return newHostBuckets.values().stream().distinct().flatMap(Set::stream); } } return hostBuckets.values().stream().distinct().flatMap(Set::stream); }
Source:
<code><START> public void setReference(String reference) { <END> this.reference = (reference != null) ? reference : ""; }</code><technical_language>prefer setReference setAlternate private (or protected if a child class, I assume is case right now)</technical_language>

Target:
private void setReference(String reference) { this.reference = (reference != null) ? reference : ""; }
Source:
<code>public void testMetricsAggregations() throws Exception { <START> CountDownLatch latch = new CountDownLatch(2); <END> LogicalPlanConfiguration lpc = new LogicalPlanConfiguration(new Configuration()); TestGeneratorInputOperator inputOperator = dag.addOperator("input", TestGeneratorInputOperator.class); OperatorWithMetrics o1 = dag.addOperator("o1", OperatorWithMetrics.class); MockAggregator aggregator = new MockAggregator(latch); dag.setOperatorAttribute(o1, Context.OperatorContext.METRICS_AGGREGATOR, aggregator); dag.setAttribute(Context.OperatorContext.STORAGE_AGENT, new StramTestSupport.MemoryStorageAgent()); dag.setOperatorAttribute(o1, Context.OperatorContext.PARTITIONER, new StatelessPartitioner<TestGeneratorInputOperator>(4)); dag.addStream("TestTuples", inputOperator.outport, o1.inport1); lpc.prepareDAG(dag, null, "AutoMetricTest"); StramLocalCluster lc = new StramLocalCluster(dag); lc.runAsync(); latch.await(); Assert.assertEquals("progress", 4L, ((Long)aggregator.result.get("progress")).longValue()); lc.shutdown(); }</code><technical_language>I understand modified test verifies code changes made. number of partitions changed 2 4 verify partial metrics change made</technical_language>

Target:
public void testMetricsAggregations() throws Exception { CountDownLatch latch = new CountDownLatch(2); LogicalPlanConfiguration lpc = new LogicalPlanConfiguration(new Configuration()); TestGeneratorInputOperator inputOperator = dag.addOperator("input", TestGeneratorInputOperator.class); OperatorWithMetrics o1 = dag.addOperator("o1", OperatorWithMetrics.class); MockAggregator aggregator = new MockAggregator(latch); dag.setOperatorAttribute(o1, Context.OperatorContext.METRICS_AGGREGATOR, aggregator); dag.setAttribute(Context.OperatorContext.STORAGE_AGENT, new StramTestSupport.MemoryStorageAgent()); dag.setOperatorAttribute(o1, Context.OperatorContext.PARTITIONER, new StatelessPartitioner<TestGeneratorInputOperator>(2)); dag.addStream("TestTuples", inputOperator.outport, o1.inport1); lpc.prepareDAG(dag, null, "AutoMetricTest"); StramLocalCluster lc = new StramLocalCluster(dag); lc.runAsync(); latch.await(); Assert.assertEquals("progress", 2L, ((Long)aggregator.result.get("progress")).longValue()); lc.shutdown(); }
Source:
<code>public void registerDock() { editor.registerDock("test", mock(IsWidget.class)); verify(placeManager).registerOnOpenCallback(placeRequestArgumentCaptor.capture(), any(Command.class)); final PlaceRequest placeRequest = placeRequestArgumentCaptor.getValue(); <START> assertEquals("org.docks.PlaceHolder", placeRequest.getIdentifier()); final Map<String, String> parameters = placeRequest.getParameters(); assertEquals(1, parameters.size()); assertEquals("test", parameters.get("name")); <END> }</code><technical_language>simplify assertj: java Assertions.assertThat(placeRequest) .hasFieldOrPropertyWithValue("identifier", "org.docks.PlaceHolder") .hasFieldOrPropertyWithValue("parameters", Collections.singletonMap("name", "test")); singletonMap: java assertEquals("org.docks.PlaceHolder", placeRequest.getIdentifier()); final Map<String, String> parameters = placeRequest.getParameters(); assertEquals(Collections.singletonMap("name", "test"), parameters);</technical_language>

Target:
public void registerDock() { editor.registerDock("test", mock(IsWidget.class)); verify(placeManager).registerOnOpenCallback(placeRequestArgumentCaptor.capture(), any(Command.class)); final PlaceRequest placeRequest = placeRequestArgumentCaptor.getValue(); Assertions.assertThat(placeRequest) .hasFieldOrPropertyWithValue("identifier", "org.docks.PlaceHolder") .hasFieldOrPropertyWithValue("parameters", Collections.singletonMap("name", "test")); }
Source:
<code>public Dialog onCreateDialog(Bundle savedInstanceState) { final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View view = inflater.inflate(R.layout.fragment_dialog_rating, null); <START> mRatingBar = (RatingBar) view.findViewById(R.id.ratingBar); <END> mRatingBar.setOnRatingBarChangeListener(this); mAlertDialog = new AlertDialog.Builder(getContext()) .setPositiveButton(getString(R.string.label_submit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int id) { submit(); } }) .setNegativeButton(android.R.string.cancel, null) .setView(view) .setCancelable(true) .create(); mAlertDialog.setOnShowListener(this); return mAlertDialog; }</code><technical_language>nit: try data binding. a minimal improvement a nit</technical_language>

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { binding = DataBindingUtil.inflate(getActivity().getLayoutInflater(), R.layout.fragment_dialog_rating, null, false); binding.ratingBar.setOnRatingBarChangeListener(this); binding.tvDescription.setText(R.string.rating_dialog_message); mAlertDialog = new AlertDialog.Builder(getContext()) .setPositiveButton(getString(R.string.label_submit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int id) { submit(); } }) .setNegativeButton(android.R.string.cancel, null) .setView(binding.getRoot()) .create(); mAlertDialog.setCanceledOnTouchOutside(false); mAlertDialog.setOnShowListener(this); return mAlertDialog; }
Source:
<code><START> public void getSupportedOutputSizes_targetResolutionLargerThan640x480() { <END> setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY); SupportedSurfaceCombination supportedSurfaceCombination = new SupportedSurfaceCombination( mContext, CAMERA_ID, mMockCamcorderProfileHelper); FakeUseCase useCase = new FakeUseCaseConfig.Builder().setTargetRotation( Surface.ROTATION_90).setTargetResolution(new Size(1280, 960)).build(); List<Size> resultList = supportedSurfaceCombination.getSupportedOutputSizes(useCase); List<Size> expectedList = Arrays.asList(new Size[]{ new Size(1280, 960), new Size(640, 480), new Size(1920, 1080), new Size(1280, 720), new Size(1280, 720), new Size(960, 544), new Size(800, 450) }); assertEquals(expectedList, resultList); }</code><technical_language>previous test "getSupportedOutputSizes_targetResolution1080x1920InRotation0" resolution larger 640x480 I get stress "larger 640x480" in this test. rename test name reflect point is is 4:3 resolution. want highlight verify mod16 16:9 resolution 960x544 is properly handling in mistmatched list</technical_language>

Target:
public void getSupportedOutputSizes_targetResolutionLargerThan640x480() { setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY); SupportedSurfaceCombination supportedSurfaceCombination = new SupportedSurfaceCombination( mContext, CAMERA_ID, mMockCamcorderProfileHelper); FakeUseCase useCase = new FakeUseCaseConfig.Builder().setTargetRotation( Surface.ROTATION_90).setTargetResolution(new Size(1280, 960)).build(); List<Size> resultList = supportedSurfaceCombination.getSupportedOutputSizes(useCase); List<Size> expectedList = Arrays.asList(new Size[]{ new Size(1280, 960), new Size(640, 480), new Size(1920, 1080), new Size(1280, 720), new Size(960, 544), new Size(800, 450) }); assertEquals(expectedList, resultList); }
Source:
<code>public RegistryResponseType documentRegistryXDSRegisterDocumentSetB(RegisterDocumentSetRequestType body) { <START> return new NhinDocDataSubmissionImpl(inboundDocDataSubmission).documentRepositoryRegisterDocumentSetB(body, <END> context); }</code><technical_language>Optinal: Suggestion add log Incomming nhin message DDS troubleshoot in future</technical_language>

Target:
public RegistryResponseType documentRegistryXDSRegisterDocumentSetB(RegisterDocumentSetRequestType body) { LOG.debug("Calling service with context and inbound submission class {}", context, inboundDocDataSubmission.getClass().getName()); return new NhinDocDataSubmissionImpl(inboundDocDataSubmission).documentRepositoryRegisterDocumentSetB(body, context); }
Source:
<code>private void initLocalizationEditor() { localeBox = new ListBox(); <START> localeBox.getElement().setId("AbstractLoginFormView_localeBox"); END> String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName(); String[] localeNames = LocaleInfo.getAvailableLocaleNames(); boolean foundDefaultLocale = false; for (String localeName : localeNames) { if (!DEFAULT_LOCALE.equals(localeName)) { String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName); localeBox.addItem(nativeName, localeName); if (localeName.equals(currentLocale)) { setSelectedLocale(localeBox.getItemCount() - 1); foundDefaultLocale = true; } } } if (!foundDefaultLocale && localeNames.length > 0) { setSelectedLocale(0); } localeBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { String localeQueryParam = LocaleInfo.getLocaleQueryParam(); String localeString = "?" + localeQueryParam + "=" + localeBox.getValue(localeBox.getSelectedIndex()); Window.open(FrontendUrlUtils.getCurrentPageURL() + localeString, "_self", ""); } }); }</code><technical_language>Instead of defining ID manually, please @WithElementId annotation, for example: @UiField(provided = true) @Ignore @WithElementId public ListBox localeBox; @WithElementId annotation is part of declarative DOM element ID framework referred "IdHandler". Please ElementIdHandler ElementIdHandlerGenerator classes for details this framework works implemented</technical_language>

Target:
private void initLocalizationEditor() { localeBox = new ListBox(); String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName(); String[] localeNames = LocaleInfo.getAvailableLocaleNames(); boolean foundDefaultLocale = false; for (String localeName : localeNames) { if (!DEFAULT_LOCALE.equals(localeName)) { String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName); localeBox.addItem(nativeName, localeName); if (localeName.equals(currentLocale)) { setSelectedLocale(localeBox.getItemCount() - 1); foundDefaultLocale = true; } } } if (!foundDefaultLocale && localeNames.length > 0) { setSelectedLocale(0); } localeBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { String localeQueryParam = LocaleInfo.getLocaleQueryParam(); String localeString = "?" + localeQueryParam + "=" + localeBox.getValue(localeBox.getSelectedIndex()); Window.open(FrontendUrlUtils.getCurrentPageURL() + localeString, "_self", ""); } }); }
Source:
<code>private void createMarkers(Processor model, int severity, Collection<String> msgs, String markerType) throws Exception { Collection<String> msgsCopy = new ArrayList<String>(msgs); <START> for (String msg : msgsCopy) { <END> createMarker(model, severity, msg, markerType); } }</code><technical_language>just: java for (String msg : msgs.toArray(new String[0])) ? need a new ArrayList. array</technical_language>

Target:
private void createMarkers(Processor model, int severity, Collection<String> msgs, String markerType) throws Exception { for (String msg : msgs.toArray(new String[0])) { createMarker(model, severity, msg, markerType); } }
Source:
<code>public void testEncodeChunkedContent() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler()); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, false); int length = 8077 + 8096; char[] array = new char[length]; Arrays.fill(array, 'a'); String longText = new String(array); encoder.addBodyAttribute("data", longText); encoder.addBodyAttribute("moreData", "abcd"); HttpRequest finalRequest = encoder.finalizeRequest(); <START> ch.writeOutbound(finalRequest); <END> ch.writeOutbound(encoder); ch.flushOutbound(); }</code><technical_language>add assert for return</technical_language>

Target:
public void testEncodeChunkedContent() throws Exception { HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, false); int length = 8077 + 8096; char[] array = new char[length]; Arrays.fill(array, 'a'); String longText = new String(array); encoder.addBodyAttribute("data", longText); encoder.addBodyAttribute("moreData", "abcd"); assertNotNull(encoder.finalizeRequest()); while (!encoder.isEndOfInput()) { encoder.readChunk((ByteBufAllocator) null).release(); } assertTrue(encoder.isEndOfInput()); encoder.cleanFiles(); }