auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public synchronized List<Product> getTopNProducts(int n) throws CatalogException { List<Product> products = new Vector<Product>(); IndexSearcher searcher = null; try { try { reader = DirectoryReader.open(indexDir); } catch (IOException e) { e.printStackTrace(); } searcher = new IndexSearcher(reader); BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder(); TermQuery tq = new TermQuery(new Term("myfield", "myvalue")); booleanQuery.add(tq, BooleanClause.Occur.MUST); Sort sort = new Sort(new SortField("CAS.ProductReceivedTime", SortField.Type.STRING, true)); LOG.log(Level.FINE, "Querying LuceneCatalog: q: [" + booleanQuery + "]"); TopDocs check = searcher.search(booleanQuery.build(), 1, sort); if(check.totalHits>0) { TopDocs topDocs = searcher.search(booleanQuery.build(), check.totalHits, sort); ScoreDoc[] hits = topDocs.scoreDocs; if (hits.length > 0) { int i = 0; while (products.size() < Math.min(n, hits.length)) { Document productDoc = searcher.doc(hits[i].doc); CompleteProduct prod = toCompleteProduct(productDoc, false, false); products.add(prod.getProduct()); i++; } } else { LOG.log(Level.WARNING, "Top N query produced no products!"); } } else{ <START> return products; <END> } } catch (IOException e) { LOG.log(Level.WARNING, "IOException when opening index directory: [" + indexFilePath + "] for search: Message: " + e.getMessage()); throw new CatalogException(e.getMessage(), e); } finally { if (searcher != null) { try { } catch (Exception ignore) { } } } return products; }</code><technical_language>remove this line</technical_language>

Target:
public synchronized List<Product> getTopNProducts(int n) throws CatalogException { List<Product> products = new Vector<Product>(); IndexSearcher searcher = null; try { try { reader = DirectoryReader.open(indexDir); } catch (IOException e) { e.printStackTrace(); } searcher = new IndexSearcher(reader); BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder(); TermQuery tq = new TermQuery(new Term("myfield", "myvalue")); booleanQuery.add(tq, BooleanClause.Occur.MUST); Sort sort = new Sort(new SortField("CAS.ProductReceivedTime", SortField.Type.STRING, true)); LOG.log(Level.FINE, "Querying LuceneCatalog: q: [" + booleanQuery + "]"); TopDocs check = searcher.search(booleanQuery.build(), 1, sort); if(check.totalHits>0) { TopDocs topDocs = searcher.search(booleanQuery.build(), check.totalHits, sort); ScoreDoc[] hits = topDocs.scoreDocs; if (hits.length > 0) { int i = 0; while (products.size() < Math.min(n, hits.length)) { Document productDoc = searcher.doc(hits[i].doc); CompleteProduct prod = toCompleteProduct(productDoc, false, false); products.add(prod.getProduct()); i++; } } else { LOG.log(Level.WARNING, "Top N query produced no products!"); } } } catch (IOException e) { LOG.log(Level.WARNING, "IOException when opening index directory: [" + indexFilePath + "] for search: Message: " + e.getMessage()); throw new CatalogException(e.getMessage(), e); } finally { if (searcher != null) { try { } catch (Exception ignore) { } } } return products; }
Source:
<code>private void cleanNativeReferences() { NativeObjectReference reference = (NativeObjectReference) referenceQueue.poll(); while (reference != null) { reference.cleanup(); reference.clear(); <START> referencesPool.freeIndexList.add(reference.refIndex); <END> reference = (NativeObjectReference) referenceQueue.poll(); } }</code><technical_language>means I idea of in-liners for speed up. ( I love in fact! CM! ), for sake of maintainability, I request pack a method if affect performance. this part tight is in protected area though. But... know..</technical_language>

Target:
private void cleanNativeReferences() { NativeObjectReference reference = (NativeObjectReference) referenceQueue.poll(); while (reference != null) { reference.cleanup(); referencesPool.freeIndexList.add(reference.refIndex); reference = (NativeObjectReference) referenceQueue.poll(); } }
Source:
<code>public StorageQuotaConfig(VerifiableProperties verifiableProperties) { zkClientConnectAddress = verifiableProperties.getString(ZK_CLIENT_CONNECT_ADDRESS); <START> refresherPollingIntervalMs = verifiableProperties.getInt(REFRESHER_POLLING_INTERVAL_MS, 30 * 60 * 1000); containerStorageQuotaInJson = verifiableProperties.getString(CONTAINER_STORAGE_QUOTA_IN_JSON, ""); sourcePollingIntervalMs = verifiableProperties.getInt(SOURCE_POLLING_INTERVAL_MS, 30 * 60 * 1000); } <END></code><technical_language>minor: getIntInRange instead of getInt here</technical_language>

Target:
public StorageQuotaConfig(VerifiableProperties verifiableProperties) { zkClientConnectAddress = verifiableProperties.getString(ZK_CLIENT_CONNECT_ADDRESS); refresherPollingIntervalMs = verifiableProperties.getIntInRange(REFRESHER_POLLING_INTERVAL_MS, 30 * 60 * 1000, 0, Integer.MAX_VALUE); containerStorageQuotaInJson = verifiableProperties.getString(CONTAINER_STORAGE_QUOTA_IN_JSON, ""); sourcePollingIntervalMs = verifiableProperties.getInt(SOURCE_POLLING_INTERVAL_MS, 30 * 60 * 1000); }
Source:
<code>private boolean filterBranch(Branch branch) { if (!includeBaseline && branch.getBranchType() == BranchType.BASELINE) { console.writeln( <START> "Branch %s[%s] is a baseline branch and that option was not specified! It will not be purged!\n", <END> branch, branch.getGuid()); return true; } else if (!includeUnarchived && branch.getArchiveState() == BranchArchivedState.UNARCHIVED) { console.writeln( "Branch %s[%s] is an unarchived branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } else if (!includeUndeleted && !branch.isDeleted()) { console.writeln( "Branch %s[%s] is an undeleted branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } return false; }</code><technical_language>This string stored in a constant branch type a %s parameter</technical_language>

Target:
private boolean filterBranch(Branch branch) { if (!includeBaseline && branch.getBranchType() == BranchType.BASELINE) { console.writeln( "Branch %s[%s] is a %s branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid(), branch.getBranchType()); return true; } else if (!includeUnarchived && branch.getArchiveState() == BranchArchivedState.UNARCHIVED) { console.writeln( "Branch %s[%s] is an unarchived branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } else if (!includeUndeleted && !branch.isDeleted()) { console.writeln( "Branch %s[%s] is an undeleted branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } return false; }
Source:
<code>public boolean execute() throws Exception { String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); String artifactTypeArg = requiredArgument(1, Messages.i18n.format("AddEntry.InvalidArgMsg.ArtifactType")); String pathToContent = optionalArgument(2); QName varName = new QName("archive", "active-archive"); SrampArchive archive = (SrampArchive) getContext().getVariable(varName); if (archive == null) { print(Messages.i18n.format("NO_ARCHIVE_OPEN")); return false; } <START> if (archivePathArg.endsWith(File.separator)) { <END> print(Messages.i18n.format("Archive.Path.Arg.should.not.contain.slash.end")); return false; } InputStream contentStream = null; try { ArtifactType type = ArtifactType.valueOf(artifactTypeArg); String name = new File(archivePathArg).getName(); if (pathToContent != null) { File contentFile = new File(pathToContent); contentStream = FileUtils.openInputStream(contentFile); } BaseArtifactType artifact = type.newArtifactInstance(); artifact.setName(name); archive.addEntry(archivePathArg, artifact, contentStream); print(Messages.i18n.format("AddEntry.Added", archivePathArg)); } catch (SrampArchiveException e) { print(e.getLocalizedMessage()); } finally { IOUtils.closeQuietly(contentStream); } return true; }</code><technical_language>replace this a "validateArchivePath" method? I imagine do a additional checks (e.g. invalid characters in page)</technical_language>

Target:
public boolean execute() throws Exception { super.initialize(); String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); String artifactTypeArg = requiredArgument(1, Messages.i18n.format("AddEntry.InvalidArgMsg.ArtifactType")); String pathToContent = optionalArgument(2); if (!this.validate(archivePathArg)) { return false; } InputStream contentStream = null; try { ArtifactType type = ArtifactType.valueOf(artifactTypeArg); String name = new File(archivePathArg).getName(); if (pathToContent != null) { File contentFile = new File(pathToContent); contentStream = FileUtils.openInputStream(contentFile); } BaseArtifactType artifact = type.newArtifactInstance(); artifact.setName(name); archive.addEntry(archivePathArg, artifact, contentStream); print(Messages.i18n.format("AddEntry.Added", archivePathArg)); } catch (SrampArchiveException e) { print(Messages.i18n.format("AddEntry.SrampArchiveException", e.getLocalizedMessage())); } finally { IOUtils.closeQuietly(contentStream); } return true; }
Source:
<code>public static void onWebViewProviderChanged(PackageInfo packageInfo) { <START> LogPrinter printer = new LogPrinter(Log.DEBUG, LOGTAG); packageInfo.applicationInfo.dump(printer, ""); <END> sPackage = packageInfo; if (!sMultiprocessEnabled) { return; } final String serviceName = getServiceName(); if (SystemService.isStopped(serviceName)) { SystemService.start(serviceName); } else if (sZygote != null) { SystemService.restart(serviceName); } try { SystemService.waitForState(serviceName, SystemService.State.RUNNING, 5000); } catch (TimeoutException e) { Log.e(LOGTAG, "Timed out waiting for " + serviceName); return; } connectToZygoteIfNeeded(); }</code><technical_language>Is this gonna stripped correctly in user builds? I heavily doubt it. gonna a lot of call overhead. wants webview logspam in a userdebug build</technical_language>

Target:
public static void onWebViewProviderChanged(PackageInfo packageInfo) { sPackage = packageInfo; if (!sMultiprocessEnabled) { return; } final String serviceName = getServiceName(); if (SystemService.isStopped(serviceName)) { SystemService.start(serviceName); } else if (sZygote != null) { SystemService.restart(serviceName); } try { SystemService.waitForState(serviceName, SystemService.State.RUNNING, 5000); } catch (TimeoutException e) { Log.e(LOGTAG, "Timed out waiting for " + serviceName); return; } connectToZygoteIfNeeded(); }
Source:
<code>public void testConfigureDurableParquetAppender() throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.getLocal(conf); FileSystemWriter<Object> writer = new FileSystemWriter<Object>( fs, new Path("/tmp"), new DatasetDescriptor.Builder() .property(FileSystemProperties.NON_DURABLE_PARQUET_PROP, "false") .schema(SchemaBuilder.record("test").fields() .requiredString("s") .endRecord()) .format("parquet") .build()); <START> Assert.assertEquals("Should default to ParquetAppender", <END> DurableParquetAppender.class, writer.appender.getClass()); }</code><technical_language>"disabling non-durable parquet appender get a durable appender"</technical_language>

Target:
public void testConfigureDurableParquetAppender() throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.getLocal(conf); FileSystemWriter<Object> writer = new FileSystemWriter<Object>( fs, new Path("/tmp"), new DatasetDescriptor.Builder() .property(FileSystemProperties.NON_DURABLE_PARQUET_PROP, "false") .schema(SchemaBuilder.record("test").fields() .requiredString("s") .endRecord()) .format("parquet") .build()); Assert.assertEquals("Disabling the non-durable parquet appender should get us a durable appender", DurableParquetAppender.class, writer.newAppender(testDirectory).getClass()); }
Source:
<code><START> public void shouldBeAbleToDeserializeADogWithoutRoot() throws Exception { <END> InputStream stream = asStream("{'name':'Brutus','age':7}"); when(deserializeeInstance.get()).thenReturn(new Deserializee()); Object[] deserialized = deserializer.deserialize(stream, dogParameterWithoutRoot); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }</code><technical_language>need a test default root, forcing root option. this feature ;)</technical_language>

Target:
public void shouldBeAbleToDeserializeADogWithoutRoot() throws Exception { InputStream stream = asStream("{'name':'Brutus','age':7}"); Object[] deserialized = deserializer.deserialize(stream, dogParameterWithoutRoot); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }
Source:
<code>public KeyStore getInternalKeyStore() throws Exception { if (tenantId == MultitenantConstants.SUPER_TENANT_ID) { if (internalKeyStore == null) { ServerConfigurationService config = this.getServerConfigService(); if (config. getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE) == null) { return null; } String file = new File(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_TYPE)); String password = config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_PASSWORD); try (FileInputStream in = new FileInputStream(file)){ store.load(in, password.toCharArray()); internalKeyStore = store; } } return internalKeyStore; } else { <START> throw new CarbonException("Permission denied for accessing internal key store"); <END> } }</code><technical_language>Is this correct message provide here. internal key store is for super tenant. information mentioned</technical_language>

Target:
public KeyStore getInternalKeyStore() throws Exception { if (tenantId == MultitenantConstants.SUPER_TENANT_ID) { if (internalKeyStore == null) { ServerConfigurationService config = this.getServerConfigService(); if (config. getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE) == null) { return null; } String file = new File(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_TYPE)); String password = config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_PASSWORD); try (FileInputStream in = new FileInputStream(file)) { store.load(in, password.toCharArray()); internalKeyStore = store; } } return internalKeyStore; } else { throw new CarbonException("Permission denied for accessing internal key store. The internal key store is " + "available only for the super tenant."); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_points); mapButton = (Button)findViewById(R.id.mapButton); nextScenarioButton = (Button)findViewById(R.id.nextScenarioButton); <START> Intent i = getIntent(); <END> int currentPointsValue = i.getExtras().getInt("current_scenario_points"); currentPoints = (TextView)findViewById(R.id.current_points_text); totalPoints = (TextView)findViewById(R.id.total_points_text); currentPoints.setText(currentPointsValue + ""); totalPoints.setText(SessionHistory.totalPoints + ""); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent returnIntent = new Intent(); setResult(Activity.RESULT_CANCELED, returnIntent); finish(); } }); nextScenarioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent returnIntent = new Intent(); setResult(Activity.RESULT_OK, returnIntent); finish(); } }); }</code><technical_language>i for intent is for counters. avoid creating a variable call getIntent in next line</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_points); mapButton = (Button) findViewById(R.id.mapButton); nextScenarioButton = (Button) findViewById(R.id.nextScenarioButton); Integer currentPointsValue = getIntent().getExtras().getInt(getString(R.string.current_points_key)); currentPointsTextView = (TextView) findViewById(R.id.current_points_text); totalPointsTextView = (TextView) findViewById(R.id.total_points_text); currentPointsTextView.setText(currentPointsValue.toString()); Integer totalPointsValue = SessionHistory.totalPoints; totalPointsTextView.setText(totalPointsValue.toString()); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_CANCELED, new Intent()); finish(); } }); nextScenarioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_OK, new Intent()); finish(); } }); }
Source:
<code>public List<Entity> resolve() { SelectorType selectorType = this.selector.getType(); int defaultCount = 1; if (INFINITE_TYPES.contains(selectorType)) { defaultCount = 0; } int maxToSelect = this.selector.get(ArgumentTypes.COUNT).orElse(defaultCount); boolean isReversed = maxToSelect < 0; maxToSelect = Math.abs(maxToSelect); Set<? extends Extent> extents = getExtentSet(); Stream<Entity> entityStream = extents.stream() .flatMap(ext -> ext.getEntities().stream()) .filter(this.selectorFilter); if (maxToSelect != 0) { if (selectorType == SelectorTypes.RANDOM) { List<Entity> holder = entityStream.collect(Collectors.toList()); <START> Collections.shuffle(holder); <END> entityStream = holder.stream(); } entityStream = entityStream.limit(maxToSelect); } return entityStream.sorted(distanceSort(isReversed)).collect(GuavaCollectors.toImmutableList()); }</code><technical_language>shuffle effect stream get sorted below. I right behavior be, entities supposed sorted distance? a bit waste of performance if it</technical_language>

Target:
public List<Entity> resolve() { SelectorType selectorType = this.selector.getType(); int defaultCount = 1; if (INFINITE_TYPES.contains(selectorType)) { defaultCount = 0; } int maxToSelect = this.selector.get(ArgumentTypes.COUNT).orElse(defaultCount); boolean isReversed = maxToSelect < 0; maxToSelect = Math.abs(maxToSelect); Set<? extends Extent> extents = getExtentSet(); Stream<Entity> entityStream = extents.stream() .flatMap(ext -> ext.getEntities().stream()) .filter(this.selectorFilter); if (maxToSelect != 0) { if (selectorType == SelectorTypes.RANDOM) { List<Entity> holder = entityStream.collect(Collectors.toList()); Collections.shuffle(holder); entityStream = holder.stream(); } else { entityStream = entityStream.sorted(distanceSort(isReversed)); } entityStream = entityStream.limit(maxToSelect); } else { entityStream = entityStream.sorted(distanceSort(isReversed)); } return entityStream.collect(GuavaCollectors.toImmutableList()); }
Source:
<code>getReplicationLoad(ServerName[] serverNames) { List<ReplicationPeerDescription> peerList = this.getReplicationPeerManager().listPeers(null); if (peerList == null) { return null; } HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> replicationLoadSourceMap = new HashMap<>(peerList.size()); peerList.stream() .forEach(peer -> replicationLoadSourceMap.put(peer.getPeerId(), new ArrayList<>())); for (ServerName serverName : serverNames) { List<ReplicationLoadSource> replicationLoadSources = getServerManager().getLoad(serverName).getReplicationLoadSourceList(); for (ReplicationLoadSource replicationLoadSource : replicationLoadSources) { <START> List<Pair<ServerName, ReplicationLoadSource>> replicationLoadSourceList = <END> replicationLoadSourceMap.get(replicationLoadSource.getPeerID()); if (replicationLoadSourceList == null) { LOG.debug(replicationLoadSource.getPeerID() + " does not exist, but it exists " + "in znode(/hbase/replication/rs). when the rs restarts, peerId is deleted, so " + "we just need to ignore it"); continue; } replicationLoadSourceList.add(new Pair<>(serverName, replicationLoadSource)); } } for (List<Pair<ServerName, ReplicationLoadSource>> loads : replicationLoadSourceMap.values()) { if (loads.size() > 0) { loads.sort(Comparator.comparingLong(load -> (-1) * load.getSecond().getReplicationLag())); } } return replicationLoadSourceMap; }</code><technical_language>nit: if debug log is imp, this replaced lines of code for-each lambda: replicationLoadSources.forEach(replicationLoadSource -> Optional .ofNullable(replicationLoadSourceMap.get(replicationLoadSource.getPeerID())) .ifPresent(pairs -> pairs.add(new Pair<>(serverName, replicationLoadSource)))); However, if debug log is imp, feel free ignore this nit</technical_language>

Target:
getReplicationLoad(ServerName[] serverNames) { List<ReplicationPeerDescription> peerList = this.getReplicationPeerManager().listPeers(null); if (peerList == null) { return null; } HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> replicationLoadSourceMap = new HashMap<>(peerList.size()); peerList.stream() .forEach(peer -> replicationLoadSourceMap.put(peer.getPeerId(), new ArrayList<>())); for (ServerName serverName : serverNames) { List<ReplicationLoadSource> replicationLoadSources = getServerManager().getLoad(serverName).getReplicationLoadSourceList(); for (ReplicationLoadSource replicationLoadSource : replicationLoadSources) { List<Pair<ServerName, ReplicationLoadSource>> replicationLoadSourceList = replicationLoadSourceMap.get(replicationLoadSource.getPeerID()); if (replicationLoadSourceList == null) { LOG.debug("{} does not exist, but it exists " + "in znode(/hbase/replication/rs). when the rs restarts, peerId is deleted, so " + "we just need to ignore it", replicationLoadSource.getPeerID()); continue; } replicationLoadSourceList.add(new Pair<>(serverName, replicationLoadSource)); } } for (List<Pair<ServerName, ReplicationLoadSource>> loads : replicationLoadSourceMap.values()) { if (loads.size() > 0) { loads.sort(Comparator.comparingLong(load -> (-1) * load.getSecond().getReplicationLag())); } } return replicationLoadSourceMap; }
Source:
<code>public List<String> getBuildDirs(Review review) { return Lists.transform(review.getFiles(), new Function<ReviewFile, String>() { @Nullable @Override public String apply(ReviewFile file) { if (file.isSourceFile()) { return StringUtils.substringBeforeLast(file.getReviewFilename(), SRC_MAIN).concat(getMainBuildDir()); <START> } else if (file.isTestFile()) { <END> return StringUtils.substringBeforeLast(file.getReviewFilename(), SRC_TEST).concat(getTestBuildDir()); } return file.getSourceDir(); } }); }</code><technical_language>else is needed returned in line</technical_language>

Target:
public List<String> getBuildDirs(Review review) { return Lists.transform(review.getFiles(), new Function<ReviewFile, String>() { @Nullable @Override public String apply(ReviewFile file) { if (file.isSourceFile()) { return substringBeforeLast(file.getReviewFilename(), SRC_MAIN).concat(getMainBuildDir()); } if (file.isTestFile()) { return substringBeforeLast(file.getReviewFilename(), SRC_TEST).concat(getTestBuildDir()); } return file.getSourceDir(); } }); }
Source:
<code>public void testEditReadOnlyLogFileConfiguration() throws Exception { final File path = tempFolder.newFolder(); final String logDirectory = emptyDirectory(path.getAbsolutePath()); LogFileConfiguration config = new LogFileConfiguration(logDirectory); <START> <END> testWithConfiguration(LogLevel.DEBUG, config, new Runnable() { @Override public void run() { thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxSize(1024); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxRotateCount(3); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setUsePlaintext(true); } }); }</code><technical_language>tests do not, in fact, throw Exception. I prefer signatures changed reflect exact exception is thrown, if any</technical_language>

Target:
public void testEditReadOnlyLogFileConfiguration() throws IOException { final File path = tempFolder.newFolder(); final String logDirectory = emptyDirectory(path.getAbsolutePath()); LogFileConfiguration config = new LogFileConfiguration(logDirectory); testWithConfiguration(LogLevel.DEBUG, config, () -> { Database.log.getFile().setConfig(config); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxSize(1024); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxRotateCount(3); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setUsePlaintext(true); }); }
Source:
<code>protected int doWork() { if (OUTPUT.exists()) { throw new PicardException(OUTPUT.getAbsolutePath() + " already exists. Delete this file and try again, or specify a different output file."); } try (BufferedWriter writer = makeWriter()) { SequenceDictionaryUtils.encodeDictionary(writer, new SAMSequenceRecordIterator(REFERENCE_SEQUENCE, TRUNCATE_NAMES_AT_WHITESPACE)); } catch (FileNotFoundException e) { throw new PicardException("File " + OUTPUT.getAbsolutePath() + " not found"); } catch (IOException e) { throw new PicardException("Can't write to or close output file " + OUTPUT.getAbsolutePath()); } catch (IllegalArgumentException e) { OUTPUT.delete(); <START> throw new PicardException(e.getMessage()); <END> } return 0; }</code><technical_language>reason pass e 2nd argument, preserve stack trace</technical_language>

Target:
protected int doWork() { int sequencesWritten = 0; if (OUTPUT.exists()) { throw new PicardException(OUTPUT.getAbsolutePath() + " already exists. Delete this file and try again, or specify a different output file."); } final Map<String, Set<String>> aliasesByContig = loadContigAliasesMap(); try (BufferedWriter writer = makeWriter()) { final Iterable<SAMSequenceRecord> samSequenceRecordIterable = getSamSequenceRecordsIterable(); SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer); samDictCodec.encodeHeaderLine(false); for (SAMSequenceRecord samSequenceRecord : samSequenceRecordIterable) { final Set<String> aliases = aliasesByContig.get(samSequenceRecord.getSequenceName()); if (aliases != null) { samSequenceRecord.setAttribute(AN_ATTRIBUTE, String.join(",", aliases)); } samDictCodec.encodeSequenceRecord(samSequenceRecord); if (++sequencesWritten >= NUM_SEQUENCES) { break; } } } catch (FileNotFoundException e) { throw new PicardException("File " + OUTPUT.getAbsolutePath() + " not found"); } catch (IOException e) { throw new PicardException("Can't write to or close output file " + OUTPUT.getAbsolutePath()); } catch (IllegalArgumentException e) { OUTPUT.delete(); throw new PicardException("Unknown problem. Partial dictionary file was deleted.", e); } return 0; }
Source:
<code><START> public Object getRootObject() { <END> return new SecurityExpressionRoot(SecurityContextHolder.getContext().getAuthentication()) {}; }</code><technical_language>Return type of SecurityExpressionOperations reduce reflection overhead</technical_language>

Target:
public SecurityExpressionRoot getRootObject() { return new SecurityExpressionRoot(SecurityContextHolder.getContext().getAuthentication()) {}; }
Source:
<code>public List<DeactivatedBeneficiary> findDeactivatedBeneficiariesOtherThanManualDeactivation(String externalId) { try { List<DeactivatedBeneficiary> deactivatedBeneficiaryWithSelectDeactivationReasons = new ArrayList<>(); List<DeactivatedBeneficiary> deactivatedBeneficiaries = deactivatedBeneficiaryDataService.findByExternalId(externalId); if (deactivatedBeneficiaries != null && deactivatedBeneficiaries.size() != 0) { for (DeactivatedBeneficiary deactivatedBeneficiary : deactivatedBeneficiaries ) { if (!DeactivationReason.LOW_LISTENERSHIP.equals(deactivatedBeneficiary.getDeactivationReason()) && !DeactivationReason.WEEKLY_CALLS_NOT_ANSWERED.equals(deactivatedBeneficiary.getDeactivationReason())) { deactivatedBeneficiaryWithSelectDeactivationReasons.add(deactivatedBeneficiary); } } } return deactivatedBeneficiaryWithSelectDeactivationReasons; } catch (ConstraintViolationException e) { <START> LOGGER.debug("List of constraints: {}", e.getConstraintViolations()); <END> throw e; } }</code><technical_language>change LOGGER.error</technical_language>

Target:
public List<DeactivatedBeneficiary> findDeactivatedBeneficiariesOtherThanManualDeactivation(String externalId) { try { List<DeactivatedBeneficiary> deactivatedBeneficiaryWithSelectDeactivationReasons = new ArrayList<>(); List<DeactivatedBeneficiary> deactivatedBeneficiaries = deactivatedBeneficiaryDataService.findByExternalId(externalId); if (deactivatedBeneficiaries != null && deactivatedBeneficiaries.size() != 0) { for (DeactivatedBeneficiary deactivatedBeneficiary : deactivatedBeneficiaries ) { if (!DeactivationReason.LOW_LISTENERSHIP.equals(deactivatedBeneficiary.getDeactivationReason()) && !DeactivationReason.WEEKLY_CALLS_NOT_ANSWERED.equals(deactivatedBeneficiary.getDeactivationReason())) { deactivatedBeneficiaryWithSelectDeactivationReasons.add(deactivatedBeneficiary); } } } return deactivatedBeneficiaryWithSelectDeactivationReasons; } catch (ConstraintViolationException e) { LOGGER.error("List of constraints: {}", e.getConstraintViolations()); throw e; } }
Source:
<code><START> public AutobatchingLeadershipObserverFactory( <END> DisruptorAutobatcher<Map.Entry<Client, LeadershipEvent>, Void> leadershipEventProcessor) { this.leadershipEventProcessor = leadershipEventProcessor; }</code><technical_language>nit: Is this meant private? users create(...)</technical_language>

Target:
private AutobatchingLeadershipObserverFactory( DisruptorAutobatcher<Map.Entry<Client, LeadershipEvent>, Void> leadershipEventProcessor) { this.leadershipEventProcessor = leadershipEventProcessor; }
Source:
<code>public EnumTemperature getTemperature() { <START> return EnumTemperature.getFromValue(ForestryAPI.climateManager.getTemperature(worldObj, pos)); <END> }</code><technical_language>problem in DefaultClimateProvider Replace this line EnumTemperature.getFromBiome(Biome Biome, World world, BlockPos pos) detect EnumTemperature.HELLISH</technical_language>

Target:
public EnumTemperature getTemperature() { return EnumTemperature.getFromBiome(worldObj.getBiome(pos), worldObj, pos); }
Source:
<code>public boolean remove(Object o) { return innerList.remove(o); <START> } <END></code><technical_language>Hmmm, this need de-parenting</technical_language>

Target:
public boolean remove(Object o) { boolean remove = innerList.remove(o); if (o != null && o instanceof Node) ((Node) o).setParentNode(null); return remove; }
Source:
<code>private HiveShellField loadScriptUnderTest(Object testCaseInstance, HiveShellBuilder hiveShellBuilder) { try { Set<Field> fields = ReflectionUtils.getAllFields(testCaseInstance.getClass(), withAnnotation(HiveSQL.class)); Preconditions.checkState(fields.size() == 1, "Exact one field should to be annotated with @HiveSQL"); Field field = fields.iterator().next(); HiveSQL annotation = field.getAnnotation(HiveSQL.class); List<Path> scriptPaths = getScriptPaths(annotation); boolean isAutoStart = annotation.autoStart(); <START> Charset charset = annotation.encoding().equals("") ? Charset.defaultCharset() : Charset.forName(annotation.encoding()); <END> hiveShellBuilder.setScriptsUnderTest(scriptPaths, charset); return new HiveShellField() { @Override public void setShell(HiveShell shell) { ReflectionUtils.setField(testCaseInstance, field.getName(), shell); } @Override public boolean isAutoStart() { return isAutoStart; } }; } catch (Throwable t) { throw new IllegalArgumentException("Failed to init field annotated with @HiveSQL: " + t.getMessage(), t); } }</code><technical_language>Move this line 105 show in diff changed. try get diff small necessary changes</technical_language>

Target:
private HiveShellField loadScriptUnderTest(Object testCaseInstance, HiveShellBuilder hiveShellBuilder) { try { Set<Field> fields = ReflectionUtils.getAllFields(testCaseInstance.getClass(), withAnnotation(HiveSQL.class)); Preconditions.checkState(fields.size() == 1, "Exact one field should to be annotated with @HiveSQL"); Field field = fields.iterator().next(); HiveSQL annotation = field.getAnnotation(HiveSQL.class); List<Path> scriptPaths = getScriptPaths(annotation); Charset charset = annotation.encoding().equals("") ? Charset.defaultCharset() : Charset.forName(annotation.encoding()); boolean isAutoStart = annotation.autoStart(); hiveShellBuilder.setScriptsUnderTest(scriptPaths, charset); return new HiveShellField() { @Override public void setShell(HiveShell shell) { ReflectionUtils.setField(testCaseInstance, field.getName(), shell); } @Override public boolean isAutoStart() { return isAutoStart; } }; } catch (Throwable t) { throw new IllegalArgumentException("Failed to init field annotated with @HiveSQL: " + t.getMessage(), t); } }
Source:
<code>private String computeDynamicValue(AbstractBuild build, String parameterizedValue) throws IllegalStateException, InterruptedException, IOException { String value = parameterizedValue; while (value != null && value.contains("${")) { int start = value.indexOf("${", 0); <START> int end = value.indexOf("}", start); <END> String parameter = value.substring(start + 2, end); String parameterValue = build.getEnvironment(TaskListener.NULL).get(parameter); if (parameterValue == null) { throw new IllegalStateException(parameter); } value = value.substring(0, start) + parameterValue + (value.length() > end + 1 ? value.substring(end + 1) : ""); } logger.fine("oldValue = " + parameterizedValue + "; newValue = " + value); return value; }</code><technical_language>end a of -1 if a user a typo in expression. avoid checking contains } _after_ ${, entering body of loop. Alternatively, if a fix Util.replaceMacro() pending review, copy-paste implementation a TODO start fixed version soon is released</technical_language>

Target:
private String computeDynamicValue(AbstractBuild build, String parameterizedValue) throws IllegalStateException, InterruptedException, IOException { final EnvVars envVars = build.getEnvironment(TaskListener.NULL); final VariableResolver<String> environmentVariables = new VariableResolver<String>() { public String resolve(String name) { return envVars.get(name); } }; final BuildVariableResolver buildVariables = new BuildVariableResolver(build.getProject()); @SuppressWarnings("unchecked") final Union<String> bothVariables = new VariableResolver.Union<String>(buildVariables, environmentVariables); String value = Util.replaceMacro(parameterizedValue, bothVariables); logger.fine("oldValue = " + parameterizedValue + "; newValue = " + value); return value; }
Source:
<code>public static void <START> createAndFillFileForCompare(String <END> filePath, InputStream inputStream) { FileOutputStream outputStream = createFileForCompare(filePath); try { int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); outputStream.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { Thread.sleep(500); outputStream.close(); outputStream = null; } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } }</code><technical_language>weird method name</technical_language>

Target:
public static void createAndFillFileForCompare(String filePath, InputStream inputStream) { FileOutputStream outputStream = createFileForCompare(filePath); try { int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Source:
<code>default Range<Long> versionRange() { <START> Optional<Long> firstVersion = timestampMapping() <END> .values() .stream() .map(LockWatchVersion::version) .min(Long::compareTo); Optional<Long> lastVersion = timestampMapping() .values() .stream() .map(LockWatchVersion::version) .max(Long::compareTo); Preconditions.checkState(firstVersion.isPresent() && lastVersion.isPresent(), "Cannot compute timestamp mapping for empty map of timestamps"); return Range.closed(firstVersion.get(), lastVersion.get()); }</code><technical_language>I a cute one: timestampMapping().values().stream().mapToLong( LockWatchVersion::version).summaryStatistics() get sorted</technical_language>

Target:
default Range<Long> versionRange() { LongSummaryStatistics summary = timestampMapping().values().stream().mapToLong( LockWatchVersion::version).summaryStatistics(); return Range.closed(summary.getMin(), summary.getMax()); }
Source:
<code>public void onEntityFieldChange( String newValue ) { if ( getDataObject() != null ) { <START> final Boolean doAdd = Boolean.TRUE.toString().equals( newValue ); <END> if ( doAdd ) { if ( !hasIdField( getDataObject() ) ) { List<ObjectProperty> configurableFields = persistenceConfigurableFields( getDataObject() ); String message = buildOnSetPersistableRefactoringMessage( false, configurableFields ); view.showYesNoCancelPopup( CommonConstants.INSTANCE.Warning(), message, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, true ); } }, Constants.INSTANCE.persistence_domain_objectEditor_add_identifier_action(), ButtonType.PRIMARY, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, false ); } }, Constants.INSTANCE.persistence_domain_objectEditor_dont_add_identifier_action(), ButtonType.DANGER, new Command() { @Override public void execute() { updateEntityField( null ); loadPropertyEditor(); } }, CommonConstants.INSTANCE.Cancel(), ButtonType.DEFAULT ); } else { doEntityFieldChange( doAdd, false ); } } else { doEntityFieldChange( doAdd, false ); } } }</code><technical_language>Boolean.parse(String) is nicer, essential</technical_language>

Target:
public void onEntityFieldChange( String newValue ) { if ( getDataObject() != null ) { final Boolean doAdd = Boolean.parseBoolean( newValue ); if ( doAdd ) { if ( !hasIdField( getDataObject() ) ) { List<ObjectProperty> configurableFields = persistenceConfigurableFields( getDataObject() ); String message = buildOnSetPersistableRefactoringMessage( false, configurableFields ); view.showYesNoCancelPopup( CommonConstants.INSTANCE.Warning(), message, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, true ); } }, Constants.INSTANCE.persistence_domain_objectEditor_add_identifier_action(), ButtonType.PRIMARY, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, false ); } }, Constants.INSTANCE.persistence_domain_objectEditor_dont_add_identifier_action(), ButtonType.DANGER, new Command() { @Override public void execute() { updateEntityField( null ); loadPropertyEditor(); } }, CommonConstants.INSTANCE.Cancel(), ButtonType.DEFAULT ); } else { doEntityFieldChange( doAdd, false ); } } else { doEntityFieldChange( doAdd, false ); } } }
Source:
<code>public static Optional<WeightedSerializableObject<EntitySnapshot>> getNextSnapshot(MobSpawnerBaseLogic logic) { int weight = 1; if(logic.getRandomEntity() != null) { weight = logic.getRandomEntity().itemWeight; } <START> Class<? extends Entity> entityClass = EntityList.stringToClassMapping.getOrDefault(logic.getEntityNameToSpawn(), EntityPig.class); <END> EntityType type = EntityTypeRegistryModule.getInstance().getForClass(entityClass); Optional<Entity> nextEntity = createEntity(type, logic.getSpawnerWorld()); if(nextEntity.isPresent()) { logic.spawnNewEntity(nextEntity.get(), false); return Optional.of(new WeightedSerializableObject<>(new SpongeEntitySnapshotBuilder().from(nextEntity.get()).build(), weight)); } return Optional.empty(); }</code><technical_language>This is need verified Forge I Forge handles entity registration differently</technical_language>

Target:
public static Optional<WeightedSerializableObject<EntitySnapshot>> getNextSnapshot(MobSpawnerBaseLogic logic) { int weight = 1; if(logic.getRandomEntity() != null) { weight = logic.getRandomEntity().itemWeight; } EntityType type = getType(logic.getEntityNameToSpawn()).orElse(EntityTypes.PIG); NBTTagCompound data = logic.getRandomEntity() == null ? null : logic.getRandomEntity().nbtData; Optional<Entity> nextEntity = createEntity((World) logic.getSpawnerWorld(), type, data); if(nextEntity.isPresent()) { return Optional.of(new WeightedSerializableObject<>(EntitySnapshot.builder().from(nextEntity.get()).build(), weight)); } return Optional.empty(); }
Source:
<code>public void initialise(String otherStatus, T value) { PollResponse<String> inProgressPollResponse <START> = new PollResponse<>(PollResponse.OperationStatus.fromString("CUSTOM_OTHER_STATUS"), "my custom response"); <END> END: com.azure.core.util.polling.pollresponse.custom.status }</code><technical_language>Do a static import of OperationStatus need fully-qualify PollResponse. part</technical_language>

Target:
public void initialise(String otherStatus, T value) { PollResponse<String> inProgressPollResponse = new PollResponse<>(OperationStatus.fromString("CUSTOM_OTHER_STATUS"), "my custom response"); END: com.azure.core.util.polling.pollresponse.custom.status }
Source:
<code>public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (requestInProgress) { <START> requestInProgress = false; <END> logDurations(); logMessage.append(" : Channel disconnected while request in progress."); publicAccessLogger.logError(logMessage.toString()); } super.disconnect(ctx, future); }</code><technical_language>write a function for this. this code is repeated in 3 places</technical_language>

Target:
public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (request != null) { logError(" : Channel disconnected while request in progress."); } super.disconnect(ctx, future); }
Source:
<code><START> private boolean touch(QueryHistoryMetrics entry) { <END> ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> node = entry.link(); if (node == null) { node = evictionQueue.offerLastx(entry); if (!entry.setLinkIfAbsent(node)) { removeLink(node); return false; } else if (qryMetrics.get(entry.key()) != entry) { removeLink(node); return false; } return true; } else if (removeLink(node)) { ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> newNode = evictionQueue.offerLastx(entry); if (!entry.replaceLink(node, newNode)) { removeLink(newNode); return false; } else if (qryMetrics.get(entry.key()) != entry) { removeLink(node); return false; } } return false; }</code><technical_language>is unexpected race condition. Consider test: java public class QueryHistoryRaceTest extends GridCommonAbstractTest { @After public void stopCluster() throws Exception { stopAllGrids(); } @Test public void updateMetricsSimultaneously() throws Exception { IgniteEx ign = startGrid(0); IgniteCache<Object, Object> cache = ign.getOrCreateCache(new CacheConfiguration<>("test") .setIndexedTypes(Integer.class, Integer.class)); cache.put(1, 1); CompletableFuture.allOf( CompletableFuture.runAsync(() -> cache.query(new SqlFieldsQuery("select * Integer")).getAll()), CompletableFuture.runAsync(() -> cache.query(new SqlFieldsQuery("select * Integer")).getAll()) ).join(); cache.query(new SqlFieldsQuery("select * Integer")).getAll(); cache.query(new SqlFieldsQuery("select * Integer")).getAll(); cache.query(new SqlFieldsQuery("select * Integer")).getAll(); cache.query(new SqlFieldsQuery("select * Integer")).getAll(); } } In end of method observe a situation qryMetrics map contains entry evictionQueue is empty. I suppose a query in statistics forever. idea fat fix simply</technical_language>

Target:
private boolean touch(QueryHistoryMetrics entry) { ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> node = entry.link(); if (node == null) { node = evictionQueue.offerLastx(entry); if (!entry.replaceLink(null, node)) { removeLink(node); return false; } if (node.item() == null) { entry.replaceLink(node, null); return false; } return true; } else if (removeLink(node)) { ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> newNode = evictionQueue.offerLastx(entry); if (!entry.replaceLink(node, newNode)) { removeLink(newNode); } } return false; }
Source:
<code>private List<BootLogic> loadBootLogics(ClassLoader cl) { List<BootLogic> r = new ArrayList<>(); for (BootLogic b : ServiceLoader.load(BootLogic.class,cl)) { r.add(b); } Collections.sort(r, new Comparator<BootLogic>() { @Override public int compare(BootLogic o1, BootLogic o2) { return -Float.compare(o1.ordinal(),o2.ordinal()); } }); if (r.isEmpty()) { <START> throw new IllegalStateException("No @BootLogic found. Aborting"); <END> } return r; }</code><technical_language>This is a regular interface, annotation, remove @</technical_language>

Target:
private List<BootLogic> loadBootLogics(ClassLoader cl) { List<BootLogic> r = new ArrayList<>(); for (BootLogic b : ServiceLoader.load(BootLogic.class,cl)) { r.add(b); } r.sort((o1, o2) -> -Float.compare(o1.ordinal(), o2.ordinal())); if (r.isEmpty()) { throw new IllegalStateException("No BootLogic found. Aborting"); } return r; }
Source:
<code>private MimeMessage makeMessageWithSubjectAndText(String subjectKeyInPropertiesFile, String textKeyInPropertiesFile, String ... textParameters) { MimeMessage message = new MimeMessage(session); String subject = loadedProperties.getProperty(subjectKeyInPropertiesFile, ""); StringBuffer text = new StringBuffer(); text.append(loadedProperties.getProperty("defaultBegin", "")); String mainContentFormat = loadedProperties.getProperty(textKeyInPropertiesFile, ""); <START> text.append(String.format(mainContentFormat, (Object[]) textParameters)); <END> text.append(loadedProperties.getProperty("defaultEnd", "")); if (!supportMailAddress.equals("")) { text.append(loadedProperties.getProperty("unsubscribeNoticeBefore", "")); text.append(" "); text.append(supportMailAddress); text.append(loadedProperties.getProperty("unsubscribeNoticeAfter", "")); } try { message.setSubject(subject); message.setText(text.toString()); } catch (MessagingException mex) { log.error(mex.getMessage()); } return message; }</code><technical_language>Do want formatting a bit more safe? If I mistaking, this breaks if number of parameters match number of placeholders. hand is good breaking fix text-template parameter list. logging exception inserting text unreplaced placeholders a bit smoother. know... a suggestions</technical_language>

Target:
private MimeMessage makeMessageWithSubjectAndText(String subjectKeyInPropertiesFile, String textKeyInPropertiesFile, String ... textParameters) { MimeMessage message = new MimeMessage(session); String subject = loadedProperties.getProperty(subjectKeyInPropertiesFile, ""); StringBuilder text = new StringBuilder(); text.append(loadedProperties.getProperty("defaultBegin", "")); String mainContentFormat = loadedProperties.getProperty(textKeyInPropertiesFile, ""); try { String formattedContent = String.format(mainContentFormat, (Object[]) textParameters); text.append(formattedContent); } catch (IllegalFormatException e) { log.error(String.format("Could not format notification email content for keys %s and %s", subjectKeyInPropertiesFile, textKeyInPropertiesFile), e); text.append(mainContentFormat); } text.append(loadedProperties.getProperty("defaultEnd", "")); if (!supportMailAddress.equals("")) { text.append(loadedProperties.getProperty("unsubscribeNoticeBefore", "")); text.append(" "); text.append(supportMailAddress); text.append(loadedProperties.getProperty("unsubscribeNoticeAfter", "")); } try { message.setSubject(subject); message.setText(text.toString()); } catch (MessagingException mex) { log.error(mex.getMessage()); } return message; }