auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldAddDifferentEntryIntoList() throws Exception { operation.xpath = "lists:double"; operation.value = 1.0; operation.run(doc); operation.value = 2.0; operation.run(doc); Double[] doubleValues = (Double[]) doc.getPropertyValue("lists:double"); assertEquals(2, doubleValues.length); assertEquals(1.0, doubleValues[0]); assertEquals(2.0, doubleValues[1]); operation.xpath = "lists:boolean"; operation.value = true; operation.run(doc); operation.value = false; operation.run(doc); Boolean[] booleanValues = (Boolean[]) doc.getPropertyValue("lists:boolean"); assertEquals(2, booleanValues.length); assertEquals(Boolean.TRUE, booleanValues[0]); assertEquals(Boolean.FALSE, booleanValues[1]); operation.xpath = "lists:integer"; operation.value = 1; operation.run(doc); operation.value = 2; operation.run(doc); Long[] longValues = (Long[]) doc.getPropertyValue("lists:integer"); assertEquals(2, longValues.length); assertEquals(Long.valueOf(1), longValues[0]); assertEquals(Long.valueOf(2), longValues[1]); operation.xpath = "lists:date"; Calendar now1 = Calendar.getInstance(); <START> sleep(1); <END> Calendar now2 = Calendar.getInstance(); operation.value = now1; operation.run(doc); operation.value = now2; operation.run(doc); Calendar[] dateValues = (Calendar[]) doc.getPropertyValue("lists:date"); assertEquals(2, dateValues.length); assertEquals(now1, dateValues[0]); assertEquals(now2, dateValues[1]); }</code><technical_language>sleep a tiny bit more, 10ms, some OS Windows a time granularity coarser 1ms</technical_language>

Target:
public void shouldAddDifferentEntryIntoList() throws Exception { operation.xpath = "lists:double"; operation.value = 1.0; operation.run(doc); operation.value = 2.0; operation.run(doc); Double[] doubleValues = (Double[]) doc.getPropertyValue("lists:double"); assertEquals(2, doubleValues.length); assertEquals(1.0, doubleValues[0]); assertEquals(2.0, doubleValues[1]); operation.xpath = "lists:boolean"; operation.value = true; operation.run(doc); operation.value = false; operation.run(doc); Boolean[] booleanValues = (Boolean[]) doc.getPropertyValue("lists:boolean"); assertEquals(2, booleanValues.length); assertEquals(Boolean.TRUE, booleanValues[0]); assertEquals(Boolean.FALSE, booleanValues[1]); operation.xpath = "lists:integer"; operation.value = 1; operation.run(doc); operation.value = 2; operation.run(doc); Long[] longValues = (Long[]) doc.getPropertyValue("lists:integer"); assertEquals(2, longValues.length); assertEquals(Long.valueOf(1), longValues[0]); assertEquals(Long.valueOf(2), longValues[1]); operation.xpath = "lists:date"; Calendar now1 = Calendar.getInstance(); Thread.sleep(10); Calendar now2 = Calendar.getInstance(); operation.value = now1; operation.run(doc); operation.value = now2; operation.run(doc); Calendar[] dateValues = (Calendar[]) doc.getPropertyValue("lists:date"); assertEquals(2, dateValues.length); assertEquals(now1, dateValues[0]); assertEquals(now2, dateValues[1]); }
Source:
<code>private synchronized void scheduleSuggesterIndexBuild() throws PluginExecutionException { if (future != null) { future.cancel(false); } try { future = executor.schedule(buildSuggesterIndex, 1, TimeUnit.MINUTES); } catch (RejectedExecutionException e) { <START> LOGGER.info( <END> "The offline gazetteer's suggester index could not be built automatically. It may have " + "to be built manually with the 'gazetteer:build-suggester-index' command."); throw new PluginExecutionException(e); } }</code><technical_language>this a warning</technical_language>

Target:
private synchronized void scheduleSuggesterIndexBuild() throws PluginExecutionException { if (future != null) { future.cancel(false); } try { future = executor.schedule(buildSuggesterIndex, 1, TimeUnit.MINUTES); } catch (RejectedExecutionException e) { LOGGER.warn( "The offline gazetteer's suggester index could not be built automatically. It may have " + "to be built manually with the 'gazetteer:build-suggester-index' command."); throw new PluginExecutionException(e); } }
Source:
<code>public void start(ServiceProvider<Service> serviceProvider) { LOGGER.debug("Starting service"); CacheManagerProviderService cacheManagerProviderService = serviceProvider.getService(CacheManagerProviderService.class); <START> if (cacheManagerProviderService != null) { <END> cacheManager = cacheManagerProviderService.getCacheManager(); cacheManager.registerListener(this); } started = true; }</code><technical_language>This for cacheManager null. References cacheManager presume non-nullness</technical_language>

Target:
public void start(ServiceProvider<Service> serviceProvider) { LOGGER.debug("Starting service"); CacheManagerProviderService cacheManagerProviderService = serviceProvider.getService(CacheManagerProviderService.class); cacheManager = cacheManagerProviderService.getCacheManager(); cacheManager.registerListener(this); }
Source:
<code>public String getUuid() { <START> return this.getIdentifierType().getUuid(); <END> }</code><technical_language>This is wrong. getUuid return uuid in class. this none, return string version of id</technical_language>

Target:
public String getUuid() { return this.getId().toString(); }
Source:
<code>public void testInitWithClassesAndNoSchema() throws Exception { System.out.println("Creating a .jar file using all of the classes associated with this test."); InMemoryJarfile originalInMemoryJar = new InMemoryJarfile(); VoltCompiler compiler = new VoltCompiler(false, false); ClassPath classpath = ClassPath.from(this.getClass().getClassLoader()); String packageName = "org.voltdb_testprocs.fakeusecase.greetings"; int classesFound = 0; for (ClassInfo myclass : classpath.getTopLevelClassesRecursive(packageName)) { compiler.addClassToJar(originalInMemoryJar, myclass.load()); classesFound++; } assertEquals(5, classesFound); System.out.println("Writing " + classesFound + " classes to jar file"); <START> File classesJarfile = File.createTempFile("TestInitStartWithClasses-procedures", ".jar"); <END> classesJarfile.deleteOnExit(); originalInMemoryJar.writeToFile(classesJarfile); Configuration c1 = new Configuration( new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "classes", classesJarfile.getPath()}); ServerThread server = new ServerThread(c1); server.setUncaughtExceptionHandler(handleUncaught); server.start(); server.join(); validateStagedCatalog(null, originalInMemoryJar); }</code><technical_language>Please update temp file name reflect test name</technical_language>

Target:
public void testInitWithClassesAndNoSchema() throws Exception { System.out.println("Creating a .jar file using all of the classes associated with this test."); InMemoryJarfile originalInMemoryJar = new InMemoryJarfile(); VoltCompiler compiler = new VoltCompiler(false, false); ClassPath classpath = ClassPath.from(this.getClass().getClassLoader()); String packageName = "org.voltdb_testprocs.fakeusecase.greetings"; int classesFound = 0; for (ClassInfo myclass : classpath.getTopLevelClassesRecursive(packageName)) { compiler.addClassToJar(originalInMemoryJar, myclass.load()); classesFound++; } assertEquals(5, classesFound); System.out.println("Writing " + classesFound + " classes to jar file"); File classesJarfile = File.createTempFile("TestInitStartWithClassesNoSchema-procedures", ".jar"); classesJarfile.deleteOnExit(); originalInMemoryJar.writeToFile(classesJarfile); Configuration c1 = new Configuration( new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "classes", classesJarfile.getPath()}); ServerThread server = new ServerThread(c1); server.setUncaughtExceptionHandler(handleUncaught); server.start(); server.join(); validateStagedCatalog(null, originalInMemoryJar); }
Source:
<code>private static List<? extends PerturbationMapping<?>> createMappingsForAllCombinations( List<? extends PerturbationMapping<?>> mappings) { int count = countScenarios(mappings, true); <START> return IntStream.range(0, mappings.size()).boxed() <END> .map(i -> multiplyPerturbations(mappings.get(i), count, i)) .collect(toImmutableList()); }</code><technical_language>Seq now</technical_language>

Target:
private static List<? extends PerturbationMapping<?>> createMappingsForAllCombinations( List<? extends PerturbationMapping<?>> mappings) { int count = countScenarios(mappings, true); return Seq.seq(mappings) .zipWithIndex() .map(tp -> multiplyPerturbations(tp.v1, count, tp.v2.intValue())) .collect(toImmutableList()); }
Source:
<code>public void shouldNotLogMessageAsInfo() { <START> logFeature.setLevel(DEPRECATED_LOGGER, "FATAL"); <END> System.setProperty(Framework.NUXEO_DEV_SYSTEM_PROP, "false"); logDeprecatedMessageAndVerify(false); }</code><technical_language>Talked in real, loggerClass do want</technical_language>

Target:
public void shouldNotLogMessageAsInfo() { logDeprecatedMessageAndVerify(false); }
Source:
<code>public void setZoom(int mapzoom) { <START> mapController.setZoom(mapzoom > maxZoomLevel ? maxZoomLevel : mapzoom); <END> }</code><technical_language>mapController.setZoom(Math.min(mapzoom, maxZoomLevel)); here</technical_language>

Target:
public void setZoom(int mapzoom) { mapController.setZoom(Math.min(mapzoom, maxZoomLevel)); }
Source:
<code>private void deployApplications() throws MojoFailureException { log.info("Deploying application [" + application + "]"); try { mule.deploy(application.getAbsolutePath()); } catch (MuleControllerException e) { <START> log.error("Couldn't deploy application: " + application + ". Check Mule Runtime logs"); <END> } }</code><technical_language>throw exception here</technical_language>

Target:
private void deployApplications() throws DeploymentException { log.info("Deploying application [" + application + "]"); try { mule.deploy(application.getAbsolutePath()); } catch (MuleControllerException e) { throw new DeploymentException("Couldn't deploy application: " + application + ". Check Mule Runtime logs"); } }
Source:
<code>private List<String> parsePoints(Element testcase) { List<String> points = new ArrayList<>(); NodeList messages = testcase.getElementsByTagName("Message"); for (int i = 0; i < messages.getLength(); i++) { Element message = (Element) messages.item(i); Element desc = (Element) message.getElementsByTagName("Description").item(0); String text = desc.getTextContent(); if (text.matches("^(TMC:.*)")) { String[] split = text.split("\\."); <START> points.add(split[1]); <END> } } return points; }</code><technical_language>Courses points names 1.1 1.2 in cases a single assignment more a single point. handle cases gracefully</technical_language>

Target:
private List<String> parsePoints(Element testcase) { List<String> points = new ArrayList<>(); NodeList messages = testcase.getElementsByTagName("Message"); for (int i = 0; i < messages.getLength(); i++) { Element message = (Element) messages.item(i); Element desc = (Element) message.getElementsByTagName("Description").item(0); String text = desc.getTextContent(); if (text.matches("^(TMC:.*)")) { String result = text.substring(text.indexOf(".") + 1); points.add(result); } } return points; }
Source:
<code>static Collection<Field> collectInjectedFields(Class<?> clazz) { <START> return collectNonStaticFieldsWithAnnotation(clazz, Inject.class, false); <END> }</code><technical_language>javax.Inject Scout beans some unexpected behavior running in a web container includes DI mechanism (like CDI). I suggest Scout-own inject annotation @InjectBean</technical_language>

Target:
static Collection<Field> collectInjectedFields(Class<?> clazz) { return collectNonStaticFieldsWithAnnotation(clazz, InjectBean.class, false); }
Source:
<code>public void register(Member member) throws Exception { Search.getFullTextEntityManager(em).persist(member); <START> initNewMember(); <END> }</code><technical_language>'em.persist(member);' enough, need wrap EntityManager needing access methods exposed JPA API</technical_language>

Target:
public void register(Member member) throws Exception { em.persist(member); initNewMember(); }
Source:
<code>private void saveMedications( @Nonnull final XWikiDocument docX, @Nonnull final Patient patient, @Nonnull final PatientData<Medication> medications, @Nonnull final PatientWritePolicy policy, @Nonnull final XWikiContext context) { final Stream<Medication> medsStream; if (PatientWritePolicy.MERGE.equals(policy)) { final PatientData<Medication> storedMedications = load(patient); medsStream = storedMedications != null ? buildMergedMedicationsMap(medications, storedMedications).entrySet().stream() .flatMap(mapEntry -> mapEntry.getValue().stream()) : StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); <START> docX.removeXObjects(Medication.CLASS_REFERENCE); <END> } else { medsStream = StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); docX.removeXObjects(Medication.CLASS_REFERENCE); } medsStream.forEach(medication -> saveMedication(docX, medication, context)); }</code><technical_language>if docX.removeXObjects(Medication.CLASS_REFERENCE); in if else, pool out place if</technical_language>

Target:
private void saveMedications( @Nonnull final XWikiDocument docX, @Nonnull final Patient patient, @Nonnull final PatientData<Medication> medications, @Nonnull final PatientWritePolicy policy, @Nonnull final XWikiContext context) { final Stream<Medication> medsStream; if (PatientWritePolicy.MERGE.equals(policy)) { final PatientData<Medication> storedMedications = load(patient); medsStream = storedMedications != null ? buildMergedMedicationsMap(medications, storedMedications).entrySet().stream() .flatMap(mapEntry -> mapEntry.getValue().stream()) : StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); } else { medsStream = StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); } docX.removeXObjects(Medication.CLASS_REFERENCE); medsStream.forEach(medication -> saveMedication(docX, medication, context)); }
Source:
<code>public void postGen(World world, Random rand, BlockPos pos) { if(isGoodBiome(world.getBiome(pos))) { <START> Blocks.FIRE.setFireInfo(world.getBlockState(pos).getBlock(), 5, 5); <END> } }</code><technical_language>This work think. setFireInfo sets fire info for forestry hives forestry hives block instance. implement methodsgetFlammability, getFireSpreadSpeed isFlammable in class of hive block</technical_language>

Target:
public void postGen(World world, Random rand, BlockPos pos)
Source:
<code>protected static boolean hasDefaultClause(SwitchStatementTree switchStatement) { return switchStatement.cases().stream() <START> .anyMatch(caseGroupTree -> caseGroupTree.labels().stream() <END> .anyMatch(caseLabelTree -> caseLabelTree.caseOrDefaultKeyword().text().equals("default"))); }</code><technical_language>This a flat map a anymatch</technical_language>

Target:
protected static boolean hasDefaultClause(SwitchStatementTree switchStatement) { return switchStatement.cases().stream() .flatMap(caseGroupTree -> caseGroupTree.labels().stream()) .anyMatch(caseLabelTree -> caseLabelTree.caseOrDefaultKeyword().text().equals("default")); }
Source:
<code>private void deleteAsyncQuery() { AsyncDbUtil asyncDbUtil = AsyncDbUtil.getInstance(elide); Iterable<Object> loaded = (Iterable<Object>) asyncDbUtil.executeInTransaction(elide.getDataStore(), (tx, scope) -> { try { <START> EntityDictionary dictionary = elide.getElideSettings().getDictionary(); <END> RSQLFilterDialect filterParser = new RSQLFilterDialect(dictionary); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, -(queryCleanupDays)); Date cleanupDate = cal.getTime(); Format dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); String cleanupDateFormatted = dateFormat.format(cleanupDate); log.debug("cleanupDateFormatted = {}", cleanupDateFormatted); FilterExpression filter = filterParser.parseFilterExpression("createdOn=le='" + cleanupDateFormatted + "'", AsyncQuery.class, false); log.debug("filter = {}", filter.toString()); EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQuery.class) .filterExpression(filter) .build(); Iterable<Object> loadedObjects = tx.loadObjects(asyncQueryCollection, scope); return loadedObjects; } catch (Exception e) { log.error("Exception: {}", e.getMessage()); } return null; }); Iterator<Object> itr = loaded.iterator(); while(itr.hasNext()) { AsyncQuery query = (AsyncQuery) itr.next(); log.info("Found a query to DELETE"); asyncDbUtil.deleteAsyncQueryAndResult(query.getId()); } }</code><technical_language>move a lot of this setup code closure (and transaction)</technical_language>

Target:
private void deleteAsyncQuery() { String cleanupDateFormatted = evaluateFormattedFilterDate(Calendar.DATE, queryCleanupDays); String filterExpression = "createdOn=le='" + cleanupDateFormatted + "'"; asyncQueryDao.deleteAsyncQueryAndResultCollection(filterExpression); }
Source:
<code>protected String getHumanFriendlyText(String location) { JsonNode swaggerSchemaNode = findNode(location); if (swaggerSchemaNode == null) { return location; } JsonNode title = swaggerSchemaNode.get("title"); if (title != null) { return title.asText(); } JsonNode description = swaggerSchemaNode.get("title"); if (description != null) { return description.asText(); } <START> JsonNode ref = swaggerSchemaNode.get("$ref"); <END> if (ref != null) { return ref.asText().substring(ref.asText().lastIndexOf("/") + 1); } return location; }</code><technical_language>careful Refs. I remember in a discussion JSON Refs JSON Pointer locator, to. I a form external reference. algo work here, a good idea check JSON Ref specification</technical_language>

Target:
protected String getHumanFriendlyText(String location) { JsonNode swaggerSchemaNode = findNode(location); if (swaggerSchemaNode == null) { return location; } JsonNode title = swaggerSchemaNode.get("title"); if (title != null) { return title.asText(); } JsonNode ref = swaggerSchemaNode.get("$ref"); if (ref != null) { return ref.asText().substring(ref.asText().lastIndexOf("/") + 1); } return location; }
Source:
<code><START> FileEntry(String name, String href, long lastModified, int size, List<FileEntry> subdirs) { <END> this.name = name; this.href = href; this.lastModified = lastModified; this.size = size; this.subdirs = subdirs; }</code><technical_language>pls method signature a wrapper calls do adjusted null argument</technical_language>

Target:
private FileEntry(String name, String href, long lastModified, int size, List<FileEntry> subdirs) { this(); this.name = name; this.href = href; this.lastModified = lastModified; this.size = size; this.subdirs = subdirs; }
Source:
<code>public void testThreadsKilledClientClose() throws Exception { int preNumClientReaper = 0; Map<Thread, StackTraceElement[]> preStMap = Thread.getAllStackTraces(); for (Thread t : preStMap.keySet()) { if (t.getName().contains("VoltDB Client Reaper Thread")) { preNumClientReaper++; } } ClientConfig config = new ClientConfig(); Client client = ClientFactory.createClient(config); client.createConnection("localhost"); client.close(); Thread.sleep(2000); Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces(); int postNumClientReaper = 0; for (Entry<Thread, StackTraceElement[]> e : stMap.entrySet()) { Thread t = e.getKey(); StackTraceElement[] st = e.getValue(); if (t == Thread.currentThread()) { continue; } String threadName = t.getName(); if (threadName.contains("VoltDB Client Reaper Thread")) { postNumClientReaper++; } if (threadName.contains("Reverse DNS lookups") || threadName.contains("Async Logger")) { System.out.println("threadName: " + threadName); for (StackTraceElement element : st) { System.out.println("stack trace element: " + element); } fail("Something failed to clean up."); } } System.out.println("preNumClientReaper : " + preNumClientReaper); System.out.println("postNumClientReaper : " + postNumClientReaper); if (preNumClientReaper != postNumClientReaper) { fail("Something failed to clean up. ClientReaper"); <START> } <END> }</code><technical_language>assertEquals(preNumClientReaper, postNumClientReaperl);</technical_language>

Target:
public void testThreadsKilledClientClose() throws Exception { int preNumClientReaper = 0; Map<Thread, StackTraceElement[]> preStMap = Thread.getAllStackTraces(); for (Thread t : preStMap.keySet()) { if (t.getName().contains("VoltDB Client Reaper Thread")) { preNumClientReaper++; } } ClientConfig config = new ClientConfig(); Client client = ClientFactory.createClient(config); client.createConnection("localhost"); client.close(); ClientFactory.decreaseClientNum(); Thread.sleep(2000); Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces(); int postNumClientReaper = 0; for (Entry<Thread, StackTraceElement[]> e : stMap.entrySet()) { Thread t = e.getKey(); if (t == Thread.currentThread()) { continue; } String threadName = t.getName(); if (threadName.contains("VoltDB Client Reaper Thread")) { postNumClientReaper++; } assertFalse(threadName.contains("Reverse DNS lookups") || threadName.contains("Async Logger") || threadName.contains("Estimated Time Updater")); } assertEquals(preNumClientReaper, postNumClientReaper); }
Source:
<code>public void countTest() throws Exception { sendManagementCallOnClientToCollectStats(); Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class); cache.put("one", "val1"); cache.put("two", "val2"); cache.get("one"); cache.get("two"); cache.get("three"); cache.get("four"); long cacheHitCount = 0; long clusteredHitCount = 0; long cacheMissCount = 0; long clusteredMissCount = 0; do { List<ContextualStatistics> stats = waitForNextStats(); for (ContextualStatistics stat : stats) { if (stat.getContext().contains("cacheName") && stat.getContext().get("cacheName").equals("dedicated-cache-1")) { <START> System.out.println("stats:"); <END> for (Map.Entry<String, Statistic<?, ?>> entry : stat.getStatistics().entrySet()) { System.out.println(" - " + entry.getKey() + " : " + entry.getValue()); } cacheHitCount = stat.getStatistic(Counter.class, "Cache:HitCount").getValue(); clusteredHitCount = stat.getStatistic(Counter.class, "Clustered:HitCount").getValue(); clusteredMissCount = stat.getStatistic(Counter.class, "Clustered:MissCount").getValue(); cacheMissCount = stat.getStatistic(Counter.class, "Cache:MissCount").getValue(); } } } while(!Thread.currentThread().isInterrupted() && (cacheHitCount != CACHE_HIT_COUNT) && (clusteredHitCount != CLUSTERED_HIT_COUNT) && (cacheMissCount != CACHE_MISS_COUNT) && (clusteredMissCount != CLUSTERED_MISS_COUNT)); Assert.assertThat(cacheHitCount,is(CACHE_HIT_COUNT)); Assert.assertThat(clusteredHitCount,is(CLUSTERED_HIT_COUNT)); Assert.assertThat(cacheMissCount,is(CACHE_MISS_COUNT)); Assert.assertThat(clusteredMissCount,is(CLUSTERED_MISS_COUNT)); }</code><technical_language>System.out</technical_language>

Target:
public void countTest() throws Exception { sendManagementCallOnClientToCollectStats(); Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class); cache.put("one", "val1"); cache.put("two", "val2"); cache.get("one"); cache.get("two"); cache.get("three"); cache.get("four"); long cacheHitCount = 0; long clusteredHitCount = 0; long cacheMissCount = 0; long clusteredMissCount = 0; do { List<ContextualStatistics> stats = waitForNextStats(); for (ContextualStatistics stat : stats) { if (stat.getContext().contains("cacheName") && stat.getContext().get("cacheName").equals("dedicated-cache-1")) { cacheHitCount = stat.getStatistic(Counter.class, "Cache:HitCount").getValue(); clusteredHitCount = stat.getStatistic(Counter.class, "Clustered:HitCount").getValue(); clusteredMissCount = stat.getStatistic(Counter.class, "Clustered:MissCount").getValue(); cacheMissCount = stat.getStatistic(Counter.class, "Cache:MissCount").getValue(); } } } while(!Thread.currentThread().isInterrupted() && (cacheHitCount != CACHE_HIT_COUNT) && (clusteredHitCount != CLUSTERED_HIT_COUNT) && (cacheMissCount != CACHE_MISS_COUNT) && (clusteredMissCount != CLUSTERED_MISS_COUNT)); Assert.assertThat(cacheHitCount,is(CACHE_HIT_COUNT)); Assert.assertThat(clusteredHitCount,is(CLUSTERED_HIT_COUNT)); Assert.assertThat(cacheMissCount,is(CACHE_MISS_COUNT)); Assert.assertThat(clusteredMissCount,is(CLUSTERED_MISS_COUNT)); }
Source:
<code>public List<EndpointRegistryInfo> getEndpointRegistries(String tenantDomain) throws EndpointRegistryException { int tenantId; try { tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); <START> if (!registryDAO.isEndpointRegistryTypeExists(EndpointRegistryConstants.REGISTRY_TYPE_WSO2, tenantId) && <END> !registryDAO.isEndpointRegistryNameExists(EndpointRegistryConstants.DEFAULT_REGISTRY_NAME, tenantId)) { EndpointRegistryInfo defaultRegistry = new EndpointRegistryInfo(); defaultRegistry.setName(EndpointRegistryConstants.DEFAULT_REGISTRY_NAME); defaultRegistry.setType(EndpointRegistryConstants.REGISTRY_TYPE_WSO2); defaultRegistry.setOwner(EndpointRegistryConstants.SYSTEM_USER_NAME); String regId = registryDAO.addEndpointRegistry(defaultRegistry, tenantId); log.info("Successfully created the default endpoint registry " + defaultRegistry.getName() + " of type :" + defaultRegistry.getType() + " with id :" + regId + " by :" + EndpointRegistryConstants.SYSTEM_USER_NAME); } List<EndpointRegistryInfo> endpointRegistryInfoList = new ArrayList<>(); EndpointRegistryInfo endpointRegistryInfo = registryDAO.getEndpointRegistry(tenantId); if (endpointRegistryInfo != null) { endpointRegistryInfoList.add(endpointRegistryInfo); } return endpointRegistryInfoList; } catch (UserStoreException e) { String msg = "Error while retrieving tenant information"; log.error(msg, e); throw new EndpointRegistryException("Error in retrieving Tenant Information while retrieving details of " + "endpoint registries", e); } }</code><technical_language>checking for existence creating Registry, simply fetch registry create if null</technical_language>

Target:
public List<EndpointRegistryInfo> getEndpointRegistries(String tenantDomain) throws EndpointRegistryException { int tenantId; try { tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); EndpointRegistryInfo endpointRegistryInfo = registryDAO.getEndpointRegistry(tenantId); if (endpointRegistryInfo == null) { EndpointRegistryInfo defaultRegistry = new EndpointRegistryInfo(); defaultRegistry.setName(EndpointRegistryConstants.DEFAULT_REGISTRY_NAME); defaultRegistry.setType(EndpointRegistryConstants.REGISTRY_TYPE_WSO2); defaultRegistry.setOwner(EndpointRegistryConstants.SYSTEM_USER_NAME); String regId = registryDAO.addEndpointRegistry(defaultRegistry, tenantId); log.info("Successfully created the default endpoint registry " + defaultRegistry.getName() + " of type :" + defaultRegistry.getType() + " with id :" + regId + " by :" + EndpointRegistryConstants.SYSTEM_USER_NAME); endpointRegistryInfo = registryDAO.getEndpointRegistry(tenantId); } List<EndpointRegistryInfo> endpointRegistryInfoList = new ArrayList<>(); if (endpointRegistryInfo != null) { endpointRegistryInfoList.add(endpointRegistryInfo); } return endpointRegistryInfoList; } catch (UserStoreException e) { String msg = "Error while retrieving tenant information"; log.error(msg, e); throw new EndpointRegistryException("Error in retrieving Tenant Information while retrieving details of " + "endpoint registries", e); } }
Source:
<code>private boolean isPropertyInvalid(Property property, Task task) { if ((property.getValue() == null || property.getValue().equals(""))) { List<String> parameter = new ArrayList<>(); parameter.add(property.getTitle()); parameter.add(task.getProcess().getTitle()); <START> Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); <END> return true; } return false; }</code><technical_language>Braces correct set double encode expression. is moved code fixed java if (property.getValue() == null || property.getValue().equals("")) { .... }</technical_language>

Target:
private boolean isPropertyInvalid(Property property, Task task) { if (property.getValue() == null || property.getValue().equals("")) { List<String> parameter = new ArrayList<>(); parameter.add(property.getTitle()); parameter.add(task.getProcess().getTitle()); Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); return true; } return false; }
Source:
<code>public void checkPermissionsRespectUmask() throws IOException, InterruptedException { final File newFile = tmp.newFile(); boolean posixSupported = isPosixSupported(newFile); assumeThat(posixSupported, is(true)); Path filePath = newFile.toPath(); AtomicFileWriter w = new AtomicFileWriter(filePath, StandardCharsets.UTF_8); w.write("whatever"); w.commit(); assertFalse(w.getTemporaryPath().toFile().exists()); assertTrue(filePath.toFile().exists()); final Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(filePath); for (PosixFilePermission perm : DEFAULT_GIVEN_PERMISSIONS) { <START> assertTrue("missing expected permission: " + perm, posixFilePermissions.contains(perm)); <END> } }</code><technical_language>replace loop assertThat(posixFilePermissions, equalTo(DEFAULT_GIVEN_PERMISSIONS)) catch changes add extra permissions well? get nicely formatted failures for free: Expected: <[OWNER_READ, GROUP_READ, OTHERS_READ, OWNER_WRITE]> but: <[OWNER_READ, OTHERS_WRITE, GROUP_READ, OTHERS_READ, OWNER_WRITE]></technical_language>

Target:
public void checkPermissionsRespectUmask() throws IOException, InterruptedException { final File newFile = tmp.newFile(); boolean posixSupported = isPosixSupported(newFile); assumeThat(posixSupported, is(true)); Path filePath = newFile.toPath(); AtomicFileWriter w = new AtomicFileWriter(filePath, StandardCharsets.UTF_8); w.write("whatever"); w.commit(); assertFalse(w.getTemporaryPath().toFile().exists()); assertTrue(filePath.toFile().exists()); assertThat(Files.getPosixFilePermissions(filePath), equalTo(DEFAULT_GIVEN_PERMISSIONS)); }
Source:
<code>public void onEventMainThread(DiscussionThreadPostedEvent event) { DiscussionThread newThread = event.getDiscussionThread(); if (discussionTopic.containsThread(newThread)) { if (postsFilter == DiscussionPostsFilter.UNANSWERED && newThread.getType() != DiscussionThread.ThreadType.QUESTION) { return; } int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(newThread, i); discussionPostsListView.setSelection(i); setScreenStateUponResult(null); <START> spinnersContainerLayout.setVisibility(View.VISIBLE); <END> } }</code><technical_language>this care of setScreenStateUponResult() implementation</technical_language>

Target:
public void onEventMainThread(DiscussionThreadPostedEvent event) { DiscussionThread newThread = event.getDiscussionThread(); if (discussionTopic.containsThread(newThread)) { if (postsFilter == DiscussionPostsFilter.UNANSWERED && newThread.getType() != DiscussionThread.ThreadType.QUESTION) { return; } int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(newThread, i); discussionPostsListView.setSelection(i); setScreenStateUponResult(); } }
Source:
<code>public Optional<Text> getShortDescription(CommandSource source) { <START> return Optional.fromNullable(this.description); <END> }</code><technical_language>change field Optional directly, need wrap this time</technical_language>

Target:
public Optional<Text> getShortDescription(CommandSource source) { return this.description; }
Source:
<code>public void abortScheduling(String requestId) { if(trace) { log.tracef("Request[%s] abort scheduling", requestId); } ScheduledRequest scheduledRequest = scheduledRequests.get(requestId); <START> if (scheduledRequest != null && scheduledRequest.request.isDone()) { <END> scheduledRequest.scheduledFuture.cancel(false); scheduledRequests.remove(requestId); } }</code><technical_language>care if request is done not, cancel future</technical_language>

Target:
public void abortScheduling(String requestId) { abortScheduling(requestId, false); }
Source:
<code>public CompletionStage<Void> rollback(LocalTransaction localTransaction) { try { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); <START> } <END> return CompletableFutures.completedNull(); }); } catch (Throwable e) { return handleRollbackFailure(e, localTransaction); } }</code><technical_language>AFAICT handleRollbackFailure handleCommitFailure need return a CompletionStage</technical_language>

Target:
public CompletionStage<Void> rollback(LocalTransaction localTransaction) { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); } return CompletableFutures.completedNull(); }); }
Source:
<code>public void testDomainLifecycleMethods() throws Throwable { DomainClient client = domainMasterLifecycleUtil.getDomainClient(); executeLifecycleOperation(client, null, START_SERVERS, true); waitUntilState(client, "master", "main-one", "STARTED"); waitUntilState(client, "master", "main-two", "STARTED"); waitUntilState(client, "master", "other-one", "STARTED"); waitUntilState(client, "slave", "main-three", "STARTED"); waitUntilState(client, "slave", "failure-one", "STARTED"); waitUntilState(client, "slave", "failure-two", "DISABLED"); <START> waitUntilState(client, "slave", "failure-three", "DISABLED"); <END> executeLifecycleOperation(client, null, STOP_SERVERS, false); waitUntilState(client, "master", "main-one", "STOPPED"); waitUntilState(client, "master", "main-two", "DISABLED"); waitUntilState(client, "master", "other-one", "DISABLED"); waitUntilState(client, "slave", "main-three", "STOPPED"); waitUntilState(client, "slave", "failure-two", "DISABLED"); waitUntilState(client, "slave", "failure-three", "DISABLED"); validateResponse(startServer(client, "master", "main-one")); ModelNode result = validateFailedResponse(startServer(client, "slave", "failure-two")); String failureDescription = result.asString(); Assert.assertTrue(failureDescription.contains("IllegalStateException")); Assert.assertTrue(failureDescription.contains("Java home")); Assert.assertTrue(failureDescription.contains("does not exist")); result = validateFailedResponse(startServer(client, "slave", "failure-three")); failureDescription = result.asString(); Assert.assertTrue(failureDescription.contains("IllegalStateException")); Assert.assertTrue(failureDescription.contains("Java home")); Assert.assertTrue(failureDescription.contains("does not exist")); }</code><technical_language>output here</technical_language>

Target:
public void testDomainLifecycleMethods() throws Throwable { DomainClient client = domainMasterLifecycleUtil.getDomainClient(); executeLifecycleOperation(client, null, START_SERVERS); waitUntilState(client, "master", "main-one", "STARTED"); waitUntilState(client, "master", "main-two", "STARTED"); waitUntilState(client, "master", "other-one", "STARTED"); waitUntilState(client, "slave", "main-three", "STARTED"); waitUntilState(client, "slave", "failure-one", "STARTED"); waitUntilState(client, "slave", "failure-two", "FAILED"); waitUntilState(client, "slave", "failure-three", "FAILED"); executeLifecycleOperation(client, null, STOP_SERVERS); waitUntilState(client, "master", "main-one", "STOPPED"); waitUntilState(client, "master", "main-two", "DISABLED"); waitUntilState(client, "master", "other-one", "DISABLED"); waitUntilState(client, "slave", "main-three", "STOPPED"); waitUntilState(client, "slave", "failure-two", "DISABLED"); waitUntilState(client, "slave", "failure-three", "DISABLED"); validateResponse(startServer(client, "master", "main-one")); ModelNode result = validateResponse(startServer(client, "slave", "failure-two")); Assert.assertThat(result.asString(), is("FAILED")); result = validateResponse(startServer(client, "slave", "failure-three")); Assert.assertThat(result.asString(), is("FAILED")); }
Source:
<code>public void publishJobModel(JobModel prevJM, JobModel currJM, String prevJMV, String currJMV, String leaseId) { try { JobModelBundle bundle = new JobModelBundle(prevJM, currJM, prevJMV, currJMV); byte[] data = SamzaObjectMapper.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(bundle); byte[] pageData = Arrays.copyOf(data, (int) JOB_MODEL_BLOCK_SIZE); InputStream is = new ByteArrayInputStream(pageData); blob.uploadPages(is, 0, JOB_MODEL_BLOCK_SIZE, AccessCondition.generateLeaseCondition(leaseId), null, null); LOG.info("Uploaded jobModel to blob", bundle.getCurrJobModel()); } catch (Exception e) { <START> LOG.error("JobModel publish failed for version = " + currJMV, new SamzaException(e)); <END> } }</code><technical_language>throw this exception , logging it. nit: logging, simply log original exception e throw wrapped exception</technical_language>

Target:
public boolean publishJobModel(JobModel prevJM, JobModel currJM, String prevJMV, String currJMV, String leaseId) { try { if (leaseId == null) { return false; } JobModelBundle bundle = new JobModelBundle(prevJM, currJM, prevJMV, currJMV); byte[] data = SamzaObjectMapper.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(bundle); byte[] pageData = Arrays.copyOf(data, (int) JOB_MODEL_BLOCK_SIZE); InputStream is = new ByteArrayInputStream(pageData); blob.uploadPages(is, 0, JOB_MODEL_BLOCK_SIZE, AccessCondition.generateLeaseCondition(leaseId), null, null); LOG.info("Uploaded jobModel to blob", bundle.getCurrJobModel()); return true; } catch (StorageException | IOException e) { LOG.error("JobModel publish failed for version = " + currJMV, e); return false; } }
Source:
<code>protected void runWithPartitionScanForNative() { EntryOperator operator = operator(this, backupProcessor, getPredicate()); Queue<Object> outComes = new LinkedList<>(); recordStore.forEach((key, record) -> { Data dataKey = toHeapData(key); operator.operateOnKey(dataKey); EntryEventType eventType = operator.getEventType(); if (eventType != null) { outComes.add(dataKey); outComes.add(operator.getOldValue()); outComes.add(operator.getByPreferringDataNewValue()); outComes.add(eventType); } }, true); <START> if (!isEmpty(outComes)) { <END> do { Data dataKey = (Data) outComes.poll(); Object oldValue = outComes.poll(); Object newValue = outComes.poll(); EntryEventType eventType = (EntryEventType) outComes.poll(); operator.init(dataKey, oldValue, newValue, null, eventType, null) .doPostOperateOps(); } while (!outComes.isEmpty()); } }</code><technical_language>outcomes is non-null already, remove if condition completely while(!outComes.isEmpty()) {..} loop instead of do {..} while (!outComes.isEmpty());</technical_language>

Target:
protected void runWithPartitionScanForNative() { EntryOperator operator = operator(this, backupProcessor, getPredicate()); Queue<Object> outComes = new LinkedList<>(); recordStore.forEach((key, record) -> { Data dataKey = toHeapData(key); operator.operateOnKey(dataKey); EntryEventType eventType = operator.getEventType(); if (eventType != null) { outComes.add(dataKey); outComes.add(operator.getOldValue()); outComes.add(operator.getByPreferringDataNewValue()); outComes.add(eventType); } }, true); while (!outComes.isEmpty()) { Data dataKey = (Data) outComes.poll(); Object oldValue = outComes.poll(); Object newValue = outComes.poll(); EntryEventType eventType = (EntryEventType) outComes.poll(); operator.init(dataKey, oldValue, newValue, null, eventType, null) .doPostOperateOps(); } }
Source:
<code>public static void asyncDeleteFullPathOptimistic(final ZooKeeper zk, final String originalPath, int znodeVersion, final AsyncCallback.VoidCallback callback, final String leafNodePath) { zk.delete(originalPath, znodeVersion, new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (rc == Code.OK.intValue()) { String parent = new File(originalPath).getParent().replace("\\", "/"); zk.getData(parent, false, (dRc, dPath, dCtx, data, stat) -> { if (Code.OK.intValue() == dRc && (stat != null && stat.getNumChildren() == 0)) { asyncDeleteFullPathOptimistic(zk, parent, -1, callback, leafNodePath); } else { <START> if (path.equals(leafNodePath)) { <END> callback.processResult(rc, path, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } } }, null); } else { if (path.equals(leafNodePath)) { callback.processResult(rc, path, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } } } }, leafNodePath); }</code><technical_language>wondering is difference if/else cases here? rc is OK here, same</technical_language>

Target:
public static void asyncDeleteFullPathOptimistic(final ZooKeeper zk, final String originalPath, int znodeVersion, final AsyncCallback.VoidCallback callback, final String leafNodePath) { zk.delete(originalPath, znodeVersion, new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (rc == Code.OK.intValue()) { String parent = new File(originalPath).getParent().replace("\\", "/"); zk.getData(parent, false, (dRc, dPath, dCtx, data, stat) -> { if (Code.OK.intValue() == dRc && (stat != null && stat.getNumChildren() == 0)) { asyncDeleteFullPathOptimistic(zk, parent, -1, callback, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } }, null); } else { if (path.equals(leafNodePath)) { callback.processResult(rc, path, leafNodePath); } else { callback.processResult(Code.OK.intValue(), path, leafNodePath); } } } }, leafNodePath); }
Source:
<code>public void generateValidMoves() { <START> validMoves = new String[operations]; <END> for (int i = 0; i < operations; i++) { validMoves[i] = "v_" + i; } print("Valid moves ready"); }</code><technical_language>operations is initialized in constructor, initialize validMoves way</technical_language>

Target:
private String[] generateValidMoves() { String[] validMoves = new String[operations]; for (int i = 0; i < operations; i++) { validMoves[i] = "v_" + i; } print("Valid moves ready"); return validMoves; }
Source:
<code>public void addQueueListener(QueueListener queueListener) { <START> if (!queueListeners.contains(queueListener)) { <END> queueListeners.add(queueListener); } }</code><technical_language>a set now, omit contains() check</technical_language>

Target:
public void addQueueListener(QueueListener queueListener) { queueListeners.add(queueListener); }
Source:
<code>private static String readTarContents(String archiveFile) throws FileNotFoundException, IOException { StringBuffer sb = new StringBuffer(); TarArchiveInputStream archive = new TarArchiveInputStream( new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(archiveFile)))); TarArchiveEntry entry; while ((entry = archive.getNextTarEntry()) != null) { <START> sb.append(entry.getName()); <END> } return sb.toString(); }</code><technical_language>This verifying names of files file contents. I reading this correct? If - need verify contents well</technical_language>

Target:
public static String readTarContents(String archiveFile) throws FileNotFoundException, IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = null; TarArchiveInputStream archiveInputStream = null; try { archiveInputStream = new TarArchiveInputStream( new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(archiveFile)))); TarArchiveEntry entry = archiveInputStream.getNextTarEntry(); while (entry != null) { br = new BufferedReader(new InputStreamReader(archiveInputStream)); String line; while ((line = br.readLine()) != null) { sb.append(line); } entry = archiveInputStream.getNextTarEntry(); } } finally { archiveInputStream.close(); br.close(); } return sb.toString(); }
Source:
<code>public void stop(BundleContext context) throws Exception { shutdownActiveLaunches(); plugin = null; super.stop(context); fgBundleContext = null; <START> if (fMemoryRetrievalFactory != null) { <END> Platform.getAdapterManager().unregisterAdapters(fMemoryRetrievalFactory, IDMContext.class); } }</code><technical_language>move this super.stop() for safety. fgBundle... line</technical_language>

Target:
public void stop(BundleContext context) throws Exception { shutdownActiveLaunches(); plugin = null; if (fMemoryRetrievalFactory != null) { Platform.getAdapterManager().unregisterAdapters(fMemoryRetrievalFactory, IDMContext.class); } super.stop(context); fgBundleContext = null; }
Source:
<code>public void accept(Observer<? super T> observer) { switch (kind) { case OnNext: observer.onNext(getValue()); break; case OnError: observer.onError(getThrowable()); break; case OnCompleted: observer.onCompleted(); break; default: <START> break; <END> } }</code><technical_language>thoughts, for exhaustive enum switches I prefer throw new AssertionError() in default case a programmer error for this branch taken</technical_language>

Target:
public void accept(Observer<? super T> observer) { switch (kind) { case OnNext: observer.onNext(getValue()); break; case OnError: observer.onError(getThrowable()); break; case OnCompleted: observer.onCompleted(); break; default: throw new AssertionError("Uncovered case: " + kind); } }
Source:
<code>public HttpRequest setUri(String uri) { ObjectUtil.checkNotNull(uri, "uri"); <START> this.uri = uri; <END> return this; }</code><technical_language>nit: merge lines checkNotNull return argument</technical_language>

Target:
public HttpRequest setUri(String uri) { this.uri = ObjectUtil.checkNotNull(uri, "uri"); return this; }
Source:
<code>NavDeepLink(@NonNull String uri) { StringBuilder uriRegex = new StringBuilder("^"); if (!SCHEME_PATTERN.matcher(uri).find()) { uriRegex.append("http[s]?://"); } Pattern fillInPattern = Pattern.compile("\\{(.+?)\\}"); Matcher matcher = fillInPattern.matcher(uri); int appendPos = 0; while (matcher.find()) { String argName = matcher.group(1); mArguments.add(argName); uriRegex.append(Pattern.quote(uri.substring(appendPos, matcher.start())) <START> .replace(".*", "\\E.*\\Q")); <END> uriRegex.append("(.+?)"); appendPos = matcher.end(); } if (appendPos < uri.length()) { uriRegex.append(Pattern.quote(uri.substring(appendPos)) .replace(".*", "\\E.*\\Q")); } mPattern = Pattern.compile(uriRegex.toString()); }</code><technical_language>I think, call end</technical_language>

Target:
NavDeepLink(@NonNull String uri) { StringBuilder uriRegex = new StringBuilder("^"); if (!SCHEME_PATTERN.matcher(uri).find()) { uriRegex.append("http[s]?://"); } Pattern fillInPattern = Pattern.compile("\\{(.+?)\\}"); Matcher matcher = fillInPattern.matcher(uri); int appendPos = 0; while (matcher.find()) { String argName = matcher.group(1); mArguments.add(argName); uriRegex.append(Pattern.quote(uri.substring(appendPos, matcher.start()))); uriRegex.append("(.+?)"); appendPos = matcher.end(); } if (appendPos < uri.length()) { uriRegex.append(Pattern.quote(uri.substring(appendPos))); } String finalRegex = uriRegex.toString().replace(".*", "\\E.*\\Q"); mPattern = Pattern.compile(finalRegex); }