auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ResourcePool parseResource(Element element) { if (!CORE_SCHEMA_NAMESPACE.equals(element.getNamespaceURI())) { return parseResourceExtension(element); <START> } <END> try { Object resource = unmarshaller.unmarshal(element); if (resource instanceof Heap) { ResourceType heapResource = ((Heap) resource).getValue(); return new SizedResourcePoolImpl(org.ehcache.config.ResourceType.Core.HEAP, heapResource.getValue().longValue(), parseUnit(heapResource), false); } else if (resource instanceof Offheap) { MemoryType offheapResource = ((Offheap) resource).getValue(); return new SizedResourcePoolImpl(org.ehcache.config.ResourceType.Core.OFFHEAP, offheapResource.getValue().longValue(), parseMemory(offheapResource), false); } else if (resource instanceof Disk) { PersistableMemoryType diskResource = ((Disk) resource).getValue(); return new SizedResourcePoolImpl(org.ehcache.config.ResourceType.Core.DISK, diskResource.getValue().longValue(), parseMemory(diskResource), diskResource.isPersistent()); } else { throw new AssertionError("Unrecognized resource: " + element + " / " + resource.getClass().getName()); } } catch (JAXBException e) { throw new IllegalArgumentException("Can't find parser for resource: " + element, e); } }</code><technical_language>terrified of drop-through errors... add else here</technical_language>

Target:
private ResourcePool parseResource(Element element) { if (!CORE_SCHEMA_NAMESPACE.equals(element.getNamespaceURI())) { return parseResourceExtension(element); } try { Object resource = unmarshaller.unmarshal(element); if (resource instanceof Heap) { ResourceType heapResource = ((Heap) resource).getValue(); return new SizedResourcePoolImpl<SizedResourcePool>(org.ehcache.config.ResourceType.Core.HEAP, heapResource.getValue().longValue(), parseUnit(heapResource), false); } else if (resource instanceof Offheap) { MemoryType offheapResource = ((Offheap) resource).getValue(); return new SizedResourcePoolImpl<SizedResourcePool>(org.ehcache.config.ResourceType.Core.OFFHEAP, offheapResource.getValue().longValue(), parseMemory(offheapResource), false); } else if (resource instanceof Disk) { PersistableMemoryType diskResource = ((Disk) resource).getValue(); return new SizedResourcePoolImpl<SizedResourcePool>(org.ehcache.config.ResourceType.Core.DISK, diskResource.getValue().longValue(), parseMemory(diskResource), diskResource.isPersistent()); } else { throw new AssertionError("Unrecognized resource: " + element + " / " + resource.getClass().getName()); } } catch (JAXBException e) { throw new IllegalArgumentException("Can't find parser for resource: " + element, e); } }
Source:
<code>public Flux<BlobChangefeedPagedResponse> byPage(String continuationToken, int preferredPageSize) { if (preferredPageSize <= 0) { return Flux.error(new IllegalArgumentException("preferredPageSize > 0 required but provided: " + preferredPageSize)); } <START> preferredPageSize = Integer.min(preferredPageSize, defaultPageSize); <END> return changefeed.getEvents() .window(preferredPageSize) .flatMap(eventWrappers -> { Flux<BlobChangefeedEventWrapper> c1 = eventWrappers.cache(); Mono<BlobChangefeedCursor> c = c1.last() .map(BlobChangefeedEventWrapper::getCursor); Mono<List<BlobChangefeedEvent>> e = c1 .map(BlobChangefeedEventWrapper::getEvent) .collectList(); return Mono.zip(e, c); }) .map(tuple2 -> new BlobChangefeedPagedResponse(tuple2.getT1(), tuple2.getT2())); }</code><technical_language>preferredPageSize</technical_language>

Target:
public Flux<BlobChangefeedPagedResponse> byPage(String continuationToken, int preferredPageSize) { if (preferredPageSize <= 0) { return Flux.error(new IllegalArgumentException("preferredPageSize > 0 required but provided: " + preferredPageSize)); } preferredPageSize = Integer.min(preferredPageSize, defaultPageSize); return changefeed.getEvents() .window(preferredPageSize) .flatMap(eventWrappers -> { Flux<BlobChangefeedEventWrapper> cachedEventWrappers = eventWrappers.cache(); Mono<BlobChangefeedCursor> c = cachedEventWrappers.last() .map(BlobChangefeedEventWrapper::getCursor); Mono<List<BlobChangefeedEvent>> e = cachedEventWrappers .map(BlobChangefeedEventWrapper::getEvent) .collectList(); return Mono.zip(e, c); }) .map(tuple2 -> new BlobChangefeedPagedResponse(tuple2.getT1(), tuple2.getT2())); }
Source:
<code>public Solution[] computeOptimizationProblem( SuitableOptions cloudOffers, QualityInformation requirements, Topology topology, int numPlansToGenerate) { <START> Solution[] bestSols = super.findInitialRandomSolutions(cloudOffers,numPlansToGenerate,topology); <END> super.setFitnessOfSolutions(bestSols, requirements, topology, cloudOffers); super.sortSolutionsByFitness(bestSols); Solution[] currentSol = new Solution[1]; int numItersNoImprovement = 0; while (numItersNoImprovement < super.getMaxIterNoImprove()) { currentSol[0] = super.findRandomSolution(cloudOffers,topology); currentSol[0].setSolutionFitness(super.fitness(currentSol[0], requirements, topology, cloudOffers)); if (log.isDebugEnabled()) { log.debug("Start checking the presence of quality attached to solutions after generating a new random solution in BLIND. With sol= " + currentSol[0].toString()); super.checkQualityAttachedToSolutions(currentSol); } if (currentSol[0].getSolutionFitness() > super .getMinimumFitnessOfSolutions(bestSols)) { if (!currentSol[0].isContainedIn(bestSols)) { super.insertOrdered(bestSols, currentSol[0]); log.debug("Better solution found after " + numItersNoImprovement + " iterations"); numItersNoImprovement = 0; } } numItersNoImprovement++; } return bestSols; }</code><technical_language>above. super methods avoiding super, right</technical_language>

Target:
public Solution[] computeOptimizationProblem( SuitableOptions cloudOffers, QualityInformation requirements, Topology topology, int numPlansToGenerate) { Solution[] bestSols = findInitialRandomSolutions(cloudOffers,numPlansToGenerate,topology); super.setFitnessOfSolutions(bestSols, requirements, topology, cloudOffers); super.sortSolutionsByFitness(bestSols); Solution[] currentSol = new Solution[1]; int numItersNoImprovement = 0; while (numItersNoImprovement < super.getMaxIterNoImprove()) { currentSol[0] = super.findRandomSolution(cloudOffers,topology); currentSol[0].setSolutionFitness(super.fitness(currentSol[0], requirements, topology, cloudOffers)); if (log.isDebugEnabled()) { log.debug("Start checking the presence of quality attached to solutions after generating a new random solution in BLIND. With sol= " + currentSol[0].toString()); super.checkQualityAttachedToSolutions(currentSol); } if (currentSol[0].getSolutionFitness() > super .getMinimumFitnessOfSolutions(bestSols)) { if (!currentSol[0].isContainedIn(bestSols)) { super.insertOrdered(bestSols, currentSol[0]); log.debug("Better solution found after " + numItersNoImprovement + " iterations"); numItersNoImprovement = 0; } } numItersNoImprovement++; } return bestSols; }
Source:
<code><START> public void afterPropertiesSet() throws Exception { <END> grantNumberMapping = getPropertyMappings().stream() .filter(propertyMapping -> StringUtils.equals( CuCGPropertyConstants.GRANT_NUMBER, propertyMapping.getBoPropertyName())) .findFirst() .orElseThrow(() -> new IllegalStateException("No property mapping was found for Grant Number")); }</code><technical_language>is this needed, mapping setup in cu-spring-rass.xml</technical_language>

Target:
public void afterPropertiesSet() throws Exception { grantNumberMapping = getPropertyMappings().stream() .filter(propertyMapping -> StringUtils.equals( CuCGPropertyConstants.GRANT_NUMBER, propertyMapping.getBoPropertyName())) .findFirst() .orElseThrow(() -> new IllegalStateException("No property mapping was found for Grant Number; " + "please add one to the 'propertyMappings' list")); }
Source:
<code><START> public void update() throws Exception { <END> Object id = repository.create(new NewServiceProvider("name", "Description")); ServiceProvider newService = new ServiceProvider(new ID(id), "New Name", "New Description"); repository.update(newService); ServiceProvider result = repository.findById(new ID(id)).get(); assertThat(result, deepEquals(newService)); }</code><technical_language>updateProviderName (this test 2nd)</technical_language>

Target:
public void update() throws Exception { Object id = repository.create(new NewServiceProvider("name", "Description")); ServiceProvider newService = new ServiceProvider(new ID(id), "name", "New Description"); repository.update(newService); ServiceProvider result = repository.findById(new ID(id)).get(); assertThat(result, deepEquals(newService)); }
Source:
<code>private boolean isOnPathNotAScript(String toFind) { String path = System.getenv("PATH"); if(path == null) return false; String[] split = path.split(File.pathSeparator); for(String s : split) { File f = new File(s); if(f.exists() && f.isDirectory()) { f = new File(f, toFind); if(f.exists() && f.canExecute()) { if(!f.canRead()) { Logger.error(this, "On path and can execute but not read, so can't check whether it is a script?!: "+f); return false; } if(f.length() < SCRIPT_HEAD.length) { Logger.error(this, "Found "+toFind+" on path but less than "+SCRIPT_HEAD+" bytes long, so can't check whether it is a script - will the shell try the next match? We can't tell whether it is a script or not ..."); return false; } try { FileInputStream fis = new FileInputStream(f); byte[] buf = new byte[SCRIPT_HEAD.length]; DataInputStream dis = new DataInputStream(fis); try { dis.read(buf); return !Arrays.equals(buf, SCRIPT_HEAD); } catch (IOException e) { Logger.error(this, "Unable to read "+f+" to check whether it is a script: "+e+" - disk corruption problems???", e); return false; } finally { try { fis.close(); <START> dis.close(); <END> } catch (IOException e) { Logger.warning(this, "Failed to close stream", e); } } } catch (FileNotFoundException e) { } } } } Logger.normal(this, "Could not find "+toFind+" on the path"); return false; }</code><technical_language>close() needs try-catch block, unfortunately. Fortunately, freenet.support.io.Closer reduces amount of code write for this job</technical_language>

Target:
private boolean isOnPathNotAScript(String toFind) { String path = System.getenv("PATH"); if(path == null) return false; String[] split = path.split(File.pathSeparator); for(String s : split) { File f = new File(s); if(f.exists() && f.isDirectory()) { f = new File(f, toFind); if(f.exists() && f.canExecute()) { if(!f.canRead()) { Logger.error(this, "On path and can execute but not read, so can't check whether it is a script?!: "+f); return false; } if(f.length() < SCRIPT_HEAD.length) { Logger.error(this, "Found "+toFind+" on path but less than "+SCRIPT_HEAD+" bytes long, so can't check whether it is a script - will the shell try the next match? We can't tell whether it is a script or not ..."); return false; } try { FileInputStream fis = new FileInputStream(f); byte[] buf = new byte[SCRIPT_HEAD.length]; DataInputStream dis = new DataInputStream(fis); try { dis.read(buf); return !Arrays.equals(buf, SCRIPT_HEAD); } catch (IOException e) { Logger.error(this, "Unable to read "+f+" to check whether it is a script: "+e+" - disk corruption problems???", e); return false; } finally { Closer.close(fis); Closer.close(dis); } } catch (FileNotFoundException e) { } } } } Logger.normal(this, "Could not find "+toFind+" on the path"); return false; }
Source:
<code><START> void addFeature(SimpleFeature feature) { <END> if (feature == null) { throw new IllegalArgumentException("Provided Feature is empty"); } else if (feature.getFeatureType() != schema ){ throw new IllegalArgumentException("addFeatures expected " + schema.getTypeName() + "(but was " + feature.getFeatureType().getTypeName() + ")"); } synchronized (this) { memory.put(feature.getID(), feature); } }</code><technical_language>Do want/need equivalently synchronized removeFeature method</technical_language>

Target:
void addFeature(SimpleFeature feature) { if (feature == null) { throw new IllegalArgumentException("Provided Feature is empty"); } else if (!feature.getFeatureType().equals(schema) ){ throw new IllegalArgumentException("addFeatures expected " + schema.getTypeName() + "(but was " + feature.getFeatureType().getTypeName() + ")"); } getMemory().put(feature.getID(), feature); }
Source:
<code>public RegisterRequest(String endpointName, Long lifetime, String lwVersion, BindingMode bindingMode, String smsNumber, Link[] objectLinks, Map<String, String> additionalAttributes) throws InvalidRequestException { if (endpointName == null || endpointName.isEmpty()) throw new InvalidRequestException("endpoint is mandatory"); if (objectLinks == null || objectLinks.length == 0) throw new InvalidRequestException( "supported object list is mandatory and mandatory objects should be present for endpoint %s", endpointName); this.endpointName = endpointName; this.lifetime = lifetime; this.lwVersion = lwVersion; this.bindingMode = bindingMode; this.smsNumber = smsNumber; this.objectLinks = objectLinks; if (additionalAttributes == null) this.additionalAttributes = Collections.emptyMap(); else <START> this.additionalAttributes = Collections.synchronizedMap(new HashMap<>(additionalAttributes)); <END> }</code><technical_language>RegisterRequest immutable</technical_language>

Target:
public RegisterRequest(String endpointName, Long lifetime, String lwVersion, BindingMode bindingMode, String smsNumber, Link[] objectLinks, Map<String, String> additionalAttributes) throws InvalidRequestException { if (endpointName == null || endpointName.isEmpty()) throw new InvalidRequestException("endpoint is mandatory"); if (objectLinks == null || objectLinks.length == 0) throw new InvalidRequestException( "supported object list is mandatory and mandatory objects should be present for endpoint %s", endpointName); this.endpointName = endpointName; this.lifetime = lifetime; this.lwVersion = lwVersion; this.bindingMode = bindingMode; this.smsNumber = smsNumber; this.objectLinks = objectLinks; if (additionalAttributes == null) this.additionalAttributes = Collections.emptyMap(); else this.additionalAttributes = Collections.unmodifiableMap(new HashMap<>(additionalAttributes)); }
Source:
<code><START> public List<String> getAvailableSearchFields(String opac) throws IllegalArgumentException { <END> try { HierarchicalConfiguration searchFields = OPACConfig.getSearchFields(opac); List<String> fields = new ArrayList<>(); for (HierarchicalConfiguration searchField : searchFields.configurationsAt("searchField")) { fields.add(searchField.getString("[@label]")); } return fields; } catch (IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw new IllegalArgumentException("Error: OPAC '" + opac + "' is not supported!"); } }</code><technical_language>need define "throws IllegalArgumentException" in function. extends RuntimeException. public List<String> getAvailableSearchFields(String opac) {</technical_language>

Target:
public List<String> getAvailableSearchFields(String opac) { try { HierarchicalConfiguration searchFields = OPACConfig.getSearchFields(opac); List<String> fields = new ArrayList<>(); for (HierarchicalConfiguration searchField : searchFields.configurationsAt("searchField")) { fields.add(searchField.getString("[@label]")); } return fields; } catch (IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw new IllegalArgumentException("Error: OPAC '" + opac + "' is not supported!"); } }
Source:
<code>public InputStream getInputStream() throws IOException { <START> return context.getEntry(path).getInputStream().get(); <END> }</code><technical_language>blindly call get(). Instead, I suggest orElseThrow(FileNotFoundException::new)</technical_language>

Target:
public InputStream getInputStream() throws IOException { return entry.getInputStream().orElseThrow(FileNotFoundException::new); }
Source:
<code>public void say(String text, String voiceName, String outputDevice) { logger.info("Executing GoogleTTS for text '{}' in language {}", text, ttsLanguage); BufferedInputStream stream = null; try { List<String> sentences = textProcessor.splitIntoChunks(text); InputStream completeStream = getSpeechForText(sentences); Player playMP3 = new Player(completeStream); playMP3.play(); } catch (IOException e) { logger.warn("Error while connecting to Google translate service", e); if (e instanceof FileNotFoundException) { logger.warn("Possibly unsupported language '{}'?", ttsLanguage); } } catch (JavaLayerException e) { logger.warn("Unable to play InputStream for text " + text, e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { logger.debug("Error while closing InputStream", e); } <START> } <END> } }</code><technical_language>IOUtils.closeQuitely() instead</technical_language>

Target:
public void say(String text, String voiceName, String outputDevice) { logger.info("Executing GoogleTTS for text '{}' in language {}", text, ttsLanguage); BufferedInputStream stream = null; try { List<String> sentences = textProcessor.splitIntoChunks(text); InputStream completeStream = getSpeechForText(sentences); Player playMP3 = new Player(completeStream); playMP3.play(); } catch (IOException e) { logger.warn("Error while connecting to Google translate service", e); if (e instanceof FileNotFoundException) { logger.warn("Possibly unsupported language '{}'?", ttsLanguage); } } catch (JavaLayerException e) { logger.warn("Unable to play InputStream for text " + text, e); } finally { IOUtils.closeQuietly(stream); } }
Source:
<code>public void setCheckedElements(Object[] elements) { fCheckedObjects = <START> new HashSet<>(); for (Object element : elements) { fCheckedObjects.add(element); } <END> fCheckboxTreeViewer.setCheckedElements(elements); }</code><technical_language>Sets.newHashSet(elements)</technical_language>

Target:
public void setCheckedElements(Object[] elements) { fCheckedObjects = Sets.newHashSet(elements); fCheckboxTreeViewer.setCheckedElements(elements); }
Source:
<code>public void testStripedAndReplicatedFileChecksum() throws Exception { prepareTestFiles(fileSize, new String[] {stripedFile1, replicatedFile}); FileChecksum stripedFileChecksum1 = getFileChecksum(stripedFile1, 10, false); FileChecksum replicatedFileChecksum = getFileChecksum(replicatedFile, 10, false); <START> if (expectComparableStripedAndReplicatedFiles) { <END> Assert.assertEquals(stripedFileChecksum1, replicatedFileChecksum); } else { Assert.assertNotEquals(stripedFileChecksum1, replicatedFileChecksum); } }</code><technical_language>methods returns isCompositeCRC flag. This reduce diff implementation flexible maintainable for future changes</technical_language>

Target:
public void testStripedAndReplicatedFileChecksum() throws Exception { prepareTestFiles(fileSize, new String[] {stripedFile1, replicatedFile}); FileChecksum stripedFileChecksum1 = getFileChecksum(stripedFile1, 10, false); FileChecksum replicatedFileChecksum = getFileChecksum(replicatedFile, 10, false); if (checksumCombineMode.equals(ChecksumCombineMode.COMPOSITE_CRC.name())) { Assert.assertEquals(stripedFileChecksum1, replicatedFileChecksum); } else { Assert.assertNotEquals(stripedFileChecksum1, replicatedFileChecksum); } }
Source:
<code>public LocationWithPosition parseLocationAndPosition(JSONObject location) throws JSONException { final LocationType locationType; String id = null; String name = null; String position = null; if (location.has("id")) { locationType = LocationType.STATION; id = location.getString("id"); name = location.getString("name"); for (Pattern pattern : nameWithPositionPatterns) { Matcher matcher = pattern.matcher(name); if (matcher.matches()) { name = matcher.group(1); position = matcher.group(2); break; } } } else if (location.has("street")) { locationType = LocationType.ADDRESS; id = location.getString("tempId"); name = (location.getString("street") + " " + location.getString("number")).trim(); } else if (location.has("name")) { locationType = LocationType.POI; id = location.getString("tempId"); name = location.getString("name"); } else { <START> locationType = LocationType.ANY; <END> } String place = location.optString("city", null); if (place != null) { if (location.has("district") && !location.getString("district").isEmpty()) { place += "-" + location.getString("district"); } } final int lat = (int) Math.round(location.optDouble("x", 0) * 1E6); final int lon = (int) Math.round(location.optDouble("y", 0) * 1E6); return new LocationWithPosition(new Location(locationType, id, lat, lon, place, name), position != null ? new Position(position.substring(position.lastIndexOf(" ") + 1)) : null); }</code><technical_language>throw exception here? unexpected case me</technical_language>

Target:
public LocationWithPosition parseLocationAndPosition(JSONObject location) throws JSONException { final LocationType locationType; String id = null; String name = null; String position = null; if (location.has("id")) { locationType = LocationType.STATION; id = location.getString("id"); name = location.getString("name"); for (Pattern pattern : nameWithPositionPatterns) { Matcher matcher = pattern.matcher(name); if (matcher.matches()) { name = matcher.group(1); position = matcher.group(2); break; } } } else if (location.has("street")) { locationType = LocationType.ADDRESS; name = (location.getString("street") + " " + location.getString("number")).trim(); } else if (location.has("name")) { locationType = LocationType.POI; id = location.getString("tempId"); name = location.getString("name"); } else if (location.has("x") && location.has("y")) { locationType = LocationType.ANY; } else { throw new IllegalArgumentException("unknown location JSONObject: " + location); } String place = location.optString("city", null); if (place != null) { if (location.has("district") && !location.getString("district").isEmpty()) { place += "-" + location.getString("district"); } } final int lat = (int) Math.round(location.optDouble("x", 0) * 1E6); final int lon = (int) Math.round(location.optDouble("y", 0) * 1E6); return new LocationWithPosition(new Location(locationType, id, lat, lon, place, name), position != null ? new Position(position.substring(position.lastIndexOf(" ") + 1)) : null); }
Source:
<code>protected boolean canDoAction() { boolean retVal = true; List<String> messages = getReturnValue().getCanDoActionMessages(); if (getVm() == null) { retVal = false; messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND.name()); } else { retVal = super.canDoAction() && isUnlockedOrForced(messages) && CanRemoveVm(getVmId(), messages); } <START> <END> setDescription(getVmName()); messages.add(VdcBllMessages.VAR__ACTION__REMOVE.toString()); messages.add(VdcBllMessages.VAR__TYPE__VM.toString()); return retVal; }</code><technical_language>nullpointer, if vm name</technical_language>

Target:
protected boolean canDoAction() { boolean retVal = true; List<String> messages = getReturnValue().getCanDoActionMessages(); if (getVm() == null) { retVal = false; messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND.name()); } else { retVal = super.canDoAction() && isUnlockedOrForced(messages) && CanRemoveVm(getVmId(), messages); setDescription(getVmName()); } messages.add(VdcBllMessages.VAR__ACTION__REMOVE.toString()); messages.add(VdcBllMessages.VAR__TYPE__VM.toString()); return retVal; }
Source:
<code>private void initializeConfiguration() { ITestObjectFactory factory = m_objectFactory; addServiceLoaderListeners(); for (XmlSuite s : m_suites) { <START> List<XmlSuite> childSuites = s.getChildSuites(); <END> for (XmlSuite c : childSuites) { addListeners(c); } addListeners(s); for (XmlMethodSelector methodSelector : s.getMethodSelectors() ) { addMethodSelector(methodSelector.getClassName(), methodSelector.getPriority()); } if (s.getObjectFactory() != null) { if (factory == null) { factory = s.getObjectFactory(); } else { throw new TestNGException("Found more than one object-factory tag in your suites"); } } } m_configuration.setAnnotationFinder(new JDK15AnnotationFinder(getAnnotationTransformer())); m_configuration.setHookable(m_hookable); m_configuration.setConfigurable(m_configurable); m_configuration.setObjectFactory(factory); }</code><technical_language>@email2vimalraj This is run listeners originally supposed part of a child suite only, executed for suites. For e.g., Lets consider : 1. Parent suite 3 listeners (p1, p2, p3) added listeners tag. 2. Child suite1 2 listeners (c1, c2) added listeners tag. 3. Child suite2 listeners attached it. expected behavior IMO Child suite1 is executed 5 listeners executed (p1,p2,p3,c1,c2) (because p1,p2,p3 part of parent suite global in scope) Child suite2 is executed 3 listeners executed (p1,p2,p3) global in nature. current changes I end causing 5 listeners executed for Child suite2 accumulating listeners defined child suites executed for suites.. if is desirable ? @juherr thoughts</technical_language>

Target:
private void initializeConfiguration() { ITestObjectFactory factory = m_objectFactory; addServiceLoaderListeners(); for (XmlSuite s : m_suites) { addListeners(s); for (XmlMethodSelector methodSelector : s.getMethodSelectors() ) { addMethodSelector(methodSelector.getClassName(), methodSelector.getPriority()); } if (s.getObjectFactory() != null) { if (factory == null) { factory = s.getObjectFactory(); } else { throw new TestNGException("Found more than one object-factory tag in your suites"); } } } m_configuration.setAnnotationFinder(new JDK15AnnotationFinder(getAnnotationTransformer())); m_configuration.setHookable(m_hookable); m_configuration.setConfigurable(m_configurable); m_configuration.setObjectFactory(factory); }
Source:
<code><T extends Enum<T>> OperationStatistic<T> findLowestTierStatistic(Cache<?, ?> cache, Class<T> type, String statName) { Query statQuery = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf(hasAttribute("name", statName), hasAttribute("type", type))))) .build(); Set<TreeNode> statResult = statQuery.execute(Collections.singleton(ContextManager.nodeFor(cache))); <START> if(statResult.size() < 1 || statResult.size() > 3) { <END> throw new RuntimeException("Failed to find lowest tier statistic: " + statName + " , valid result Set sizes must be between 1-3. Found result Set size of: " + statResult.size()); } if(statResult.size() == 1) { return (OperationStatistic) statResult.iterator().next().getContext().attributes().get("this"); } String lowestStoreType = "onheap"; TreeNode lowestTierNode = null; for(TreeNode treeNode : statResult) { if(((Set)treeNode.getContext().attributes().get("tags")).size() != 1) { throw new RuntimeException("Failed to find lowest tier statistic. \"tags\" set must be size 1"); } String storeType = treeNode.getContext().attributes().get("tags").toString(); if(storeType.compareToIgnoreCase(lowestStoreType) < 0) { lowestStoreType = treeNode.getContext().attributes().get("tags").toString(); lowestTierNode = treeNode; } } return (OperationStatistic)lowestTierNode.getContext().attributes().get("this"); }</code><technical_language>upper bound? I brings anything, long eviction stat, find proper one. upper bound means code change in case end allowing more 3 tiers</technical_language>

Target:
<T extends Enum<T>> OperationStatistic<T> findLowestTierStatistic(Cache<?, ?> cache, Class<T> type, String statName) { Query statQuery = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf(hasAttribute("name", statName), hasAttribute("type", type))))) .build(); Set<TreeNode> statResult = statQuery.execute(Collections.singleton(ContextManager.nodeFor(cache))); if(statResult.size() < 1) { throw new RuntimeException("Failed to find lowest tier statistic: " + statName + " , valid result Set sizes must 1 or more. Found result Set size of: " + statResult.size()); } if(statResult.size() == 1) { return (OperationStatistic) statResult.iterator().next().getContext().attributes().get("this"); } String lowestStoreType = "onheap"; TreeNode lowestTierNode = null; for(TreeNode treeNode : statResult) { if(((Set)treeNode.getContext().attributes().get("tags")).size() != 1) { throw new RuntimeException("Failed to find lowest tier statistic. \"tags\" set must be size 1"); } String storeType = treeNode.getContext().attributes().get("tags").toString(); if(storeType.compareToIgnoreCase(lowestStoreType) < 0) { lowestStoreType = treeNode.getContext().attributes().get("tags").toString(); lowestTierNode = treeNode; } } return (OperationStatistic)lowestTierNode.getContext().attributes().get("this"); }
Source:
<code><START> public List<PermissionSubject> getPermissionCheckSubjects() { <END> if (getParameters().getOperation() == ImageOperation.Copy) { return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, ActionGroup.COPY_TEMPLATE)); } else { return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, ActionGroup.MOVE_VM)); } }</code><technical_language>permission template/vm, storage need check quota (i guess in patch)</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { DiskImage image = getImage(); Guid guid = Guid.Empty; if (image != null) { guid = image.getvm_guid(); } if (getParameters().getOperation() == ImageOperation.Copy) { return Collections.singletonList(new PermissionSubject(guid, VdcObjectType.VmTemplate, ActionGroup.COPY_TEMPLATE)); } else { return Collections.singletonList(new PermissionSubject(guid, VdcObjectType.VM, ActionGroup.MOVE_VM)); } }
Source:
<code>public ArrayList<String> getInvalidityErrorLines() { var errors = new ArrayList<String>(); for (int i = 0; i < actions.size(); i++) { ScriptGeneratorAction action = actions.get(i); if (!action.isValid()) { String errorString = "Row: " + (i+1) + ", Reason: " + action.getInvalidityReason() + "\n"; <START> for(String line : errorString.split("\n")) { <END> errors.add(line); } } } return errors; }</code><technical_language>Bulk insertion operations done more efficiently standard library. suggestion errors.addAll(errorString.split("\n"));</technical_language>

Target:
public ArrayList<String> getInvalidityErrorLines() { var errors = new ArrayList<String>(); for (int i = 0; i < actions.size(); i++) { ScriptGeneratorAction action = actions.get(i); if (!action.isValid()) { String errorString = "Row: " + (i+1) + ", Reason: " + "\n" + action.getInvalidityReason().get() + "\n"; errors.addAll(Arrays.asList(errorString.split("\n"))); } } return errors; }
Source:
<code>protected boolean canDoAction() { if (!validate(new StoragePoolValidator(getStoragePool()).isUp())) { return false; } DiskImage diskImage = null; try { diskImage = getDiskImage(); } catch (OpenStackImageException e) { <START> log.errorFormat("Unable to get the disk image from the provider proxy: {0}", e.getMessage()); <END> switch (e.getErrorType()) { case UNSUPPORTED_CONTAINER_FORMAT: case UNSUPPORTED_DISK_FORMAT: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_NOT_SUPPORTED); case UNABLE_TO_DOWNLOAD_IMAGE: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_DOWNLOAD_ERROR); case UNRECOGNIZED_IMAGE_FORMAT: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_UNRECOGNIZED); } } if (diskImage == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } return true; }</code><technical_language>I problem e.getMessage() in this case (CDA, understand happen VdcBllMessage), message is exists (you created constructor message) need print stack trace</technical_language>

Target:
protected boolean canDoAction() { if (!validate(new StoragePoolValidator(getStoragePool()).isUp())) { return false; } DiskImage diskImage = null; try { diskImage = getDiskImage(); } catch (OpenStackImageException e) { log.errorFormat("Unable to get the disk image from the provider proxy: {0} ({1})", e.getMessage(), e.getErrorType()); switch (e.getErrorType()) { case UNSUPPORTED_CONTAINER_FORMAT: case UNSUPPORTED_DISK_FORMAT: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_NOT_SUPPORTED); case UNABLE_TO_DOWNLOAD_IMAGE: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_DOWNLOAD_ERROR); case UNRECOGNIZED_IMAGE_FORMAT: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_UNRECOGNIZED); } } if (diskImage == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } return true; }
Source:
<code>private GcsStorageService googleCloudStorageService(String dataFilename, GcsProperties gcsProperties) { String applicationVersion = Optional.ofNullable(getClass().getPackage().getImplementationVersion()).orElse("Unknown"); GcsStorageService service; if (dataFilename == null || dataFilename.isEmpty()) { service = new GcsStorageService(gcsProperties.getBucket(), gcsProperties.getBucketLocation(), gcsProperties.getRootFolder(), gcsProperties.getProject(), gcsProperties.getJsonPath(), applicationVersion, maxWaitInterval, retryIntervalBase, jitterMultiplier, maxRetries, taskScheduler, registry); } else { service = new GcsStorageService(gcsProperties.getBucket(), gcsProperties.getBucketLocation(), gcsProperties.getRootFolder(), gcsProperties.getProject(), gcsProperties.getJsonPath(), applicationVersion, dataFilename, maxWaitInterval, retryIntervalBase, jitterMultiplier, maxRetries, taskScheduler, registry); } service.ensureBucketExists(); log.info("Using Google Cloud Storage bucket={} in project={}", value("bucket", gcsProperties.getBucket()), value("project", gcsProperties.getProject())); log.info("Bucket versioning is {}.", value("versioning", service.supportsVersioning() ? "enabled" : "DISABLED")); taskScheduler.scheduleAtFixedRate( new Runnable() { public void run() { service.purgeBatchedVersionPaths(); } }, <START> 300 * 1000); <END> return service; }</code><technical_language>capture name magic constants above</technical_language>

Target:
private GcsStorageService googleCloudStorageService(String dataFilename, GcsProperties gcsProperties) { String applicationVersion = Optional.ofNullable(getClass().getPackage().getImplementationVersion()).orElse("Unknown"); GcsStorageService service; if (dataFilename == null || dataFilename.isEmpty()) { service = new GcsStorageService(gcsProperties.getBucket(), gcsProperties.getBucketLocation(), gcsProperties.getRootFolder(), gcsProperties.getProject(), gcsProperties.getJsonPath(), applicationVersion, maxWaitInterval, retryIntervalBase, jitterMultiplier, maxRetries, taskScheduler, registry); } else { service = new GcsStorageService(gcsProperties.getBucket(), gcsProperties.getBucketLocation(), gcsProperties.getRootFolder(), gcsProperties.getProject(), gcsProperties.getJsonPath(), applicationVersion, dataFilename, maxWaitInterval, retryIntervalBase, jitterMultiplier, maxRetries, taskScheduler, registry); } service.ensureBucketExists(); log.info("Using Google Cloud Storage bucket={} in project={}", value("bucket", gcsProperties.getBucket()), value("project", gcsProperties.getProject())); log.info("Bucket versioning is {}.", value("versioning", service.supportsVersioning() ? "enabled" : "DISABLED")); long period_ms = 300 * 1000; taskScheduler.scheduleAtFixedRate( new Runnable() { public void run() { service.purgeBatchedVersionPaths(); } }, period_ms); return service; }
Source:
<code>public BufferedEventSender(int maxCap) { this.queue = new ArrayBlockingQueue<>(maxCap, <START> true); <END> }</code><technical_language>Do need queue fair? understanding is is a kafka queue in transport, queue maintaining full order (if multiple partitions)</technical_language>

Target:
BufferedEventSender(int maxCap) { this.queue = new ArrayBlockingQueue<>(maxCap); }
Source:
<code>private boolean isKeyStoreAvailable(final Path keyStoreFilePath, String storeType, char[] password) throws KeyStoreException, IOException { <START> if (keyStoreFilePath.toFile().exists()) { <END> try (InputStream input = Files.newInputStream(keyStoreFilePath)) { final KeyStore keyStore = KeyStore.getInstance(storeType); keyStore.load(input, password); return true; } catch (NoSuchAlgorithmException | CertificateException e) { LOG.failedToLoadKeystore(keyStoreFilePath.toString(), storeType, e); } catch (IOException | KeyStoreException e) { LOG.failedToLoadKeystore(keyStoreFilePath.toString(), storeType, e); throw e; } } return false; }</code><technical_language>operate Path directly? Files.exists(keystorePath)</technical_language>

Target:
private boolean isKeyStoreAvailable(final Path keyStoreFilePath, String storeType, char[] password) throws KeyStoreException, IOException { if (Files.exists(keyStoreFilePath)) { try (InputStream input = Files.newInputStream(keyStoreFilePath)) { final KeyStore keyStore = KeyStore.getInstance(storeType); keyStore.load(input, password); return true; } catch (NoSuchAlgorithmException | CertificateException e) { LOG.failedToLoadKeystore(keyStoreFilePath.toString(), storeType, e); } catch (IOException | KeyStoreException e) { LOG.failedToLoadKeystore(keyStoreFilePath.toString(), storeType, e); throw e; } } return false; }
Source:
<code><START> public boolean configure(StaplerRequest request, JSONObject object) throws FormException { <END> save(); return super.configure(request, object); }</code><technical_language>is this deleted</technical_language>

Target:
public boolean configure(StaplerRequest request, JSONObject object) throws FormException { LOGGER.info(object.toString()); nativeLibraryPath = object.getString("nativeLibraryPath"); master = object.getString("master"); description = object.getString("description"); frameworkName = object.getString("frameworkName"); slaveAttributes = object.getString("slaveAttributes"); checkpoint = object.getBoolean("checkpoint"); slaveInfos = new ArrayList<MesosSlaveInfo>(); JSONArray labels = object.getJSONArray("slaveInfos"); if (labels != null) { for (int i = 0; i < labels.size(); i++) { JSONObject label = labels.getJSONObject(i); if (label != null) { MesosSlaveInfo.ExternalContainerInfo externalContainerInfo = null; if (label.has("externalContainerInfo")) { JSONObject externalContainerInfoJson = label .getJSONObject("externalContainerInfo"); externalContainerInfo = new MesosSlaveInfo.ExternalContainerInfo( externalContainerInfoJson.getString("image"), externalContainerInfoJson.getString("options")); } MesosSlaveInfo.ContainerInfo containerInfo = null; if (label.has("containerInfo")) { JSONObject containerInfoJson = label .getJSONObject("containerInfo"); List<MesosSlaveInfo.Volume> volumes = new ArrayList<MesosSlaveInfo.Volume>(); if (containerInfoJson.has("volumes")) { JSONArray volumesJson = containerInfoJson .getJSONArray("volumes"); for (Object obj : volumesJson) { JSONObject volumeJson = (JSONObject) obj; volumes .add(new MesosSlaveInfo.Volume(volumeJson .getString("containerPath"), volumeJson .getString("hostPath"), volumeJson .getBoolean("readOnly"))); } } containerInfo = new MesosSlaveInfo.ContainerInfo( containerInfoJson.getString("type"), containerInfoJson.getString("dockerImage"), volumes); } MesosSlaveInfo slaveInfo = new MesosSlaveInfo( object.getString("labelString"), object.getString("slaveCpus"), object.getString("slaveMem"), object.getString("maxExecutors"), object.getString("executorCpus"), object.getString("executorMem"), object.getString("remoteFSRoot"), object.getString("idleTerminationMinutes"), object.getString("slaveAttributes"), object.getString("jvmArgs"), externalContainerInfo, containerInfo); slaveInfos.add(slaveInfo); } } } save(); return super.configure(request, object); }
Source:
<code><START> public boolean remove(NormalizedResourcesWithMemory other) { <END> boolean negativeResources = normalizedResources.remove(other.getNormalizedResources(), null); totalMemoryMb -= other.getTotalMemoryMb(); if (totalMemoryMb < 0.0) { negativeResources = true; totalMemoryMb = 0.0; } return negativeResources; }</code><technical_language>change public boolean remove(NormalizedResourcesWithMemory other, ResourceMetrics resourceMetrics) call remove(other, null)</technical_language>

Target:
public boolean remove(NormalizedResourcesWithMemory other) { return remove(other, null); }
Source:
<code>public void testPrefixSuffix() { Bytes b1 = Bytes.of("abcde"); Bytes prefix = Bytes.of("ab"); Bytes suffix = Bytes.of("de"); Bytes mid = Bytes.of("cd"); Assert.assertEquals(true, b1.startsWith(prefix)); Assert.assertEquals(true, b1.endsWith(suffix)); Assert.assertEquals(false, b1.startsWith(mid)); <START> Assert.assertEquals(false, b1.endsWith(mid)); <END> }</code><technical_language>Assert.assertTrue Assert.assertFalse instead of Assert.assertEquals here. Also, a more cases helpful for full coverage (these, yours, I *think* cover cases): true =? "".startsWith("") // trivial empty check true =? "".endsWith("") // trivial empty check true =? "abc".startsWith("abc") // exact match true =? "abc".endsWith("abc") // exact match true =? "abc".startsWith("") // empty string exists start true =? "abc".endsWith("") // empty string exists end false =? "".startsWith("abc") // empty string start longer string false =? "".endsWith("abc") // empty string end longer string false =? "a".startsWith("abc") // regular string start longer string false =? "a".endsWith("abc") // regular string end longer string check Bytes.EMPTY Bytes.of(String) Bytes.of(CharSequence)</technical_language>

Target:
public void testPrefixSuffix() { Bytes b1 = Bytes.of("abcde"); Bytes prefix = Bytes.of("ab"); Bytes suffix = Bytes.of("de"); Bytes empty = new Bytes(); Bytes mid = Bytes.of("cd"); Assert.assertTrue(b1.startsWith(prefix)); Assert.assertTrue(b1.endsWith(suffix)); Assert.assertFalse(b1.startsWith(mid)); Assert.assertFalse(b1.endsWith(mid)); Assert.assertTrue(empty.startsWith(empty)); Assert.assertTrue(empty.endsWith(empty)); Assert.assertTrue(b1.startsWith(b1)); Assert.assertTrue(b1.endsWith(b1)); Assert.assertTrue(b1.startsWith(empty)); Assert.assertTrue(b1.endsWith(empty)); Assert.assertFalse(empty.startsWith(b1)); Assert.assertFalse(empty.endsWith(b1)); Assert.assertFalse(prefix.startsWith(b1)); Assert.assertFalse(prefix.endsWith(b1)); Assert.assertTrue(b1.startsWith(b1.subSequence(0, 2))); Assert.assertFalse(b1.subSequence(0, 2).startsWith(b1)); Assert.assertTrue(b1.endsWith(b1.subSequence(3, 5))); Assert.assertFalse(b1.endsWith(b1.subSequence(0, 2))); Assert.assertFalse(b1.subSequence(0, 2).endsWith(b1)); }
Source:
<code>private Guid addNewVmDevice(Guid vmId, XmlRpcStruct device) { Guid newDeviceId = Guid.Empty; String typeName = (String) device.getItem("type"); String deviceName = (String) device.getItem("device"); if (!StringUtils.isEmpty(typeName) && !StringUtils.isEmpty(deviceName)) { String address = ((Map<String, String>) device.getItem("address")).toString(); String specParams = ""; <START> Object o = device.getItem("specParams"); <END> newDeviceId = Guid.NewGuid(); if (o != null) { specParams = ((Map<String, String>) o).toString(); } VmDeviceId id = new VmDeviceId(newDeviceId, vmId); VmDevice newDevice = new VmDevice(id, typeName, deviceName, address, 0, specParams, false, true, false); DbFacade.getInstance().getVmDeviceDAO().save(newDevice); log.debugFormat("New device was added to VM Devices : {0}", newDevice.toString()); } else { log.error("Empty or NULL values were passed for a VM device, Device is skipped"); } return newDeviceId; }</code><technical_language>VdsProperties.SpecParams instead "specParams"</technical_language>

Target:
private Guid addNewVmDevice(Guid vmId, XmlRpcStruct device) { Guid newDeviceId = Guid.Empty; String typeName = (String) device.getItem(VdsProperties.Type); String deviceName = (String) device.getItem(VdsProperties.Device); if (!StringUtils.isEmpty(typeName) && !StringUtils.isEmpty(deviceName)) { String address = ((Map<String, String>) device.getItem(VdsProperties.Address)).toString(); String specParams = ""; Object o = device.getItem(VdsProperties.SpecParams); newDeviceId = Guid.NewGuid(); if (o != null) { specParams = ((Map<String, String>) o).toString(); } VmDeviceId id = new VmDeviceId(newDeviceId, vmId); VmDevice newDevice = new VmDevice(id, typeName, deviceName, address, 0, specParams, false, true, false); DbFacade.getInstance().getVmDeviceDAO().save(newDevice); log.debugFormat("New device was added to VM {0} Devices : {1}", vmId, newDevice.toString()); } else { log.errorFormat("Empty or NULL values were passed for a VM {0} device, Device is skipped", vmId); } return newDeviceId; }
Source:
<code>protected abstract void internalStart(Map<String, String> startOptions) throws InfrastructureException; public final void stop(Map<String, String> stopOptions) throws InfrastructureException { if (this.status != WorkspaceStatus.RUNNING && this.status != WorkspaceStatus.STARTING) { <START> throw new StateException("The environment must be running"); <END> } status = WorkspaceStatus.STOPPING; try { internalStop(stopOptions); } finally { status = WorkspaceStatus.STOPPED; } }</code><technical_language>Please, error message fit changed code</technical_language>

Target:
protected abstract void internalStart(Map<String, String> startOptions) throws InfrastructureException; public final void stop(Map<String, String> stopOptions) throws InfrastructureException { if (status != WorkspaceStatus.RUNNING && status != WorkspaceStatus.STARTING) { throw new StateException("The environment must be running or starting"); } status = WorkspaceStatus.STOPPING; try { internalStop(stopOptions); } catch (InternalInfrastructureException e) { LOG.error("Error occurs on stop of workspace {}. Error: {}", context.getIdentity().getWorkspaceId(), e.getMessage()); } catch (InfrastructureException e) { LOG.debug(e.getMessage(), e); } status = WorkspaceStatus.STOPPED; }
Source:
<code>public static String trimFieldName(String fieldName) { IPreferencesService preferences = Platform.getPreferencesService(); String prefix = preferences.getString(CUIPlugin.PLUGIN_ID, PreferenceConstants.NAME_STYLE_FIELD_PREFIX, "", null); if (fieldName.startsWith(prefix)) fieldName = fieldName.substring(prefix.length()); int firstWordStart = -1; int lastWordEnd = -1; for (int i = 0; i < fieldName.length(); ++i) { if (Character.isLetterOrDigit(fieldName.charAt(i))) { int pos = i + 1; <START> while (--pos >= i && !Character.isLetterOrDigit(fieldName.charAt(pos))) { <END> } lastWordEnd = pos + 1; if (firstWordStart < 0) { firstWordStart = i; } } } if (firstWordStart < 0) { return fieldName; } else { return fieldName.substring(firstWordStart, lastWordEnd); } }</code><technical_language>IIUC isLetterOrDigit is testing index line 950, true 950, false here. Therfore this loop pos == i time</technical_language>

Target:
public static String trimFieldName(String fieldName) { IPreferencesService preferences = Platform.getPreferencesService(); String prefix = preferences.getString(CUIPlugin.PLUGIN_ID, PreferenceConstants.NAME_STYLE_FIELD_PREFIX, "", null); if (fieldName.startsWith(prefix)) fieldName = fieldName.substring(prefix.length()); int firstWordStart = -1; int lastWordEnd = -1; for (int i = 0; i < fieldName.length(); ++i) { if (Character.isLetterOrDigit(fieldName.charAt(i))) { lastWordEnd = i + 1; if (firstWordStart < 0) { firstWordStart = i; } } } if (firstWordStart < 0) { return fieldName; } else { return fieldName.substring(firstWordStart, lastWordEnd); } }