auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public PrologEnvironment newPrologEnvironment() throws CompileException { PrologEnvironment env = envFactory.create(getClass().getClassLoader()); String rules; try { rules = getPrologRules(); } catch (RepositoryNotFoundException err) { throw new CompileException("Local repository does not exist ", err); } if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.makeSymbol("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }

Target:
public PrologEnvironment newPrologEnvironment() throws CompileException { PrologEnvironment env = envFactory.create(getClass().getClassLoader()); String rules = getConfig().getPrologRules(); if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.makeSymbol("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }
Source:
private void addToSpeakQueue(String sectionText, TextToSpeech tts) { if (sectionText.length() >= tts.getMaxSpeechInputLength()) { Integer remainingCharStart = tts.getMaxSpeechInputLength(); String newSectionText = TextUtils.substring(sectionText, 0, tts.getMaxSpeechInputLength()); if (!isLastCharWhitespace(newSectionText)) { Integer count = 0; while (!isLastCharWhitespace(newSectionText)) { newSectionText = newSectionText.substring(0, newSectionText.length() - 1); count++; } remainingCharStart = remainingCharStart - count; } tts.speak(newSectionText, TextToSpeech.QUEUE_ADD, null, null); addToSpeakQueue( TextUtils.substring( sectionText, remainingCharStart, sectionText.length() ), tts ); } else { tts.speak(sectionText, TextToSpeech.QUEUE_ADD, null, null); } }

Target:
private void addToSpeakQueue(String sectionText, TextToSpeech tts) { Integer maxLength = 2000; if (ApiUtil.hasLollipop()) { maxLength = tts.getMaxSpeechInputLength(); } if (sectionText.length() >= maxLength) { Integer remainingCharStart = maxLength; String newSectionText = TextUtils.substring(sectionText, 0, maxLength); if (!isLastCharWhitespace(newSectionText)) { Integer count = 0; while (!isLastCharWhitespace(newSectionText)) { newSectionText = newSectionText.substring(0, newSectionText.length() - 1); count++; } remainingCharStart = remainingCharStart - count; } speak(newSectionText, null, tts); addToSpeakQueue( TextUtils.substring( sectionText, remainingCharStart, sectionText.length() ), tts ); } else { speak(sectionText, null, tts); } }
Source:
public PointSensitivityBuilder riskyAnnuitySensitivity( ResolvedCds cds, CreditRatesProvider ratesProvider, LocalDate referenceDate, ReferenceData refData) { ArgChecker.isTrue(cds.getProtectionEndDate().isAfter(ratesProvider.getValuationDate()), "CDS already expired"); LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); Pair<CreditDiscountFactors, LegalEntitySurvivalProbabilities> rates = reduceDiscountFactors(cds, ratesProvider); return riskyAnnuitySensitivity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate); }

Target:
public PointSensitivityBuilder riskyAnnuitySensitivity( ResolvedCds cds, CreditRatesProvider ratesProvider, LocalDate referenceDate, ReferenceData refData) { if (isExpired(cds, ratesProvider)) { return PointSensitivityBuilder.none(); } LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); Pair<CreditDiscountFactors, LegalEntitySurvivalProbabilities> rates = reduceDiscountFactors(cds, ratesProvider); return riskyAnnuitySensitivity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate); }
Source:
public Http2MultiplexedChannelPool(InetSocketAddress inetSocketAddress, SSLFactory sslFactory, EventLoopGroup eventLoopGroup, Http2ClientConfig http2ClientConfig, Http2ClientMetrics http2ClientMetrics, ChannelInitializer streamChannelInitializer) { this(new SimpleChannelPool(createBootStrap(eventLoopGroup, http2ClientConfig, inetSocketAddress), new Http2ChannelPoolHandler(sslFactory, inetSocketAddress.getHostName(), inetSocketAddress.getPort(), http2ClientConfig)), eventLoopGroup, ConcurrentHashMap.newKeySet(), inetSocketAddress, new Http2ClientConfig(new VerifiableProperties(new Properties())), http2ClientMetrics, streamChannelInitializer); }

Target:
public Http2MultiplexedChannelPool(InetSocketAddress inetSocketAddress, SSLFactory sslFactory, EventLoopGroup eventLoopGroup, Http2ClientConfig http2ClientConfig, Http2ClientMetrics http2ClientMetrics, ChannelInitializer streamChannelInitializer) { this(new SimpleChannelPool(createBootStrap(eventLoopGroup, http2ClientConfig, inetSocketAddress), new Http2ChannelPoolHandler(sslFactory, inetSocketAddress.getHostName(), inetSocketAddress.getPort(), http2ClientConfig)), eventLoopGroup, ConcurrentHashMap.newKeySet(), inetSocketAddress, http2ClientConfig, http2ClientMetrics, streamChannelInitializer); }
Source:
private List<PickerMilestone> cloneList(List<PickerMilestone> sourceList) { List<PickerMilestone> destList = new ArrayList<>(); sourceList.stream() .forEach(milestone -> destList.add(new PickerMilestone(milestone))); return destList; }

Target:
private List<PickerMilestone> cloneList(List<PickerMilestone> sourceList) { return sourceList.stream() .map(PickerMilestone::new) .collect(Collectors.toList()); }
Source:
public void onChange(WorkspaceProjectContextChangeEvent previous, WorkspaceProjectContextChangeEvent current) { if (current.getWorkspaceProject() != null) { if (Utils.hasProjectChanged(previous.getWorkspaceProject(), current.getWorkspaceProject()) && current.requiresRefresh()) { if (closeAllPlacesOrNothing()) { goToProject(); } } } }

Target:
public void onChange(WorkspaceProjectContextChangeEvent previous, WorkspaceProjectContextChangeEvent current) { if (current.getWorkspaceProject() != null) { if (Utils.hasRepositoryChanged(previous.getWorkspaceProject(), current.getWorkspaceProject())) { closeAllPlacesOrNothing(this::goToProject); } } }
Source:
protected void handleResponse(Request req, Address sender, byte[] buf, int offset, int length, boolean is_exception) { Object retval; try { ByteArrayInputStream is = new ByteArrayInputStream(buf, offset, length); retval = ispnMarshaller.objectFromInputStream(is); } catch (Exception e) { log.error(Util.getMessage("FailedUnmarshallingBufferIntoReturnValue"), e); retval = e; is_exception = true; } req.receiveResponse(retval, sender, is_exception); }

Target:
protected void handleResponse(Request req, Address sender, byte[] buf, int offset, int length, boolean is_exception) { Object retval; try { retval = ispnMarshaller.objectFromByteBuffer(buf, offset, length); } catch (Exception e) { log.error(Util.getMessage("FailedUnmarshallingBufferIntoReturnValue"), e); retval = e; is_exception = true; } req.receiveResponse(retval, sender, is_exception); }
Source:
private void onCloneVM() { UnitVmModel model = (UnitVmModel) getWindow(); CloneVmFromSnapshotModelBehavior behavior = (CloneVmFromSnapshotModelBehavior) model.getBehavior(); Snapshot snapshot = getSelectedItem(); if (snapshot == null) { cancel(); return; } if (!model.validate()) { return; } VM vm = behavior.getVm(); String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery<>( isNameUnique -> { if (!isNameUnique) { model.getInvalidityReasons().clear(); model.getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); model.getName().setIsValid(false); model.setIsValid(false); model.fireValidationCompleteEvent(); } else { postNameUniqueCheckVM(vm, snapshot, behavior, model); } }), name, null); }

Target:
private void onCloneVM() { UnitVmModel model = (UnitVmModel) getWindow(); CloneVmFromSnapshotModelBehavior behavior = (CloneVmFromSnapshotModelBehavior) model.getBehavior(); Snapshot snapshot = getSelectedItem(); if (snapshot == null) { cancel(); return; } if (!model.validate()) { return; } VM vm = behavior.getVm(); String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isVmNameUnique(new AsyncQuery<>( isNameUnique -> { if (!isNameUnique) { model.getInvalidityReasons().clear(); model.getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); model.getName().setIsValid(false); model.setIsValid(false); model.fireValidationCompleteEvent(); } else { postNameUniqueCheckVM(vm, snapshot, behavior, model); } }), name, model.getSelectedDataCenter().getId()); }
Source:
public boolean stopServer() { if (serverStarting) { LOGGER.info("[ws] JabRefWebsocketServer is currently starting up and cannot be stopped during this process"); return false; } else if (serverStarted) { LOGGER.info("[ws] stopping JabRefWebsocketServer..."); if (heartbeatExecutor != null) { heartbeatExecutor.shutdown(); this.heartbeatExecutor = null; } try { stop(1000); } catch (InterruptedException e) { e.printStackTrace(); } serverStarted = false; return true; } else { LOGGER.info("[ws] JabRefWebsocketServer is not started"); return false; } }

Target:
public synchronized boolean stopServer() { if (serverStarting) { LOGGER.info("[ws] JabRefWebsocketServer is currently starting up and cannot be stopped during this process"); return false; } if (serverStarted) { LOGGER.debug("[ws] stopping JabRefWebsocketServer..."); if (heartbeatExecutor != null) { heartbeatExecutor.shutdown(); this.heartbeatExecutor = null; } try { stop(1000); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } serverStarted = false; return true; } LOGGER.info("[ws] JabRefWebsocketServer is not started"); return false; }
Source:
public void handleStateChanged(Watcher.Event.KeeperState state) { LOG.info("ZkStateChangeListener:: handleStateChanged {}", state.toString()); switch (state) { case Expired: _timer.cancel(); onBecomeFollower(); exitOnSessionExpiryOrEstablishmentError(); return; case Disconnected: LOG.warn("Got event. Scheduling a system stop.", state.toString()); scheduleExpiryTimerAfterSessionTimeout(); return; case SyncConnected: LOG.info("ZkStateChangeListener::Connected. Canceling timer."); _timer.cancel(); return; default: } }

Target:
public void handleStateChanged(Watcher.Event.KeeperState state) { LOG.info("ZkStateChangeListener::handleStateChanged {}", state); switch (state) { case Expired: _zkSessionExpiryFuture.cancel(false); onSessionExpired(); return; case Disconnected: LOG.warn("ZkStateChangeListener::Got event. Scheduling a system stop.", state); scheduleExpiryTimerAfterSessionTimeout(); return; case SyncConnected: LOG.info("ZkStateChangeListener::Connected. Canceling timer."); _zkSessionExpiryFuture.cancel(false); return; default: } }
Source:
private static ArrayList<Artifact> asArtifacts(Collection<Change> changes) { ArrayList<Artifact> arts = new ArrayList<>(); for (Change artifactChange : changes) { Artifact changeArtifact = artifactChange.getChangeArtifact(); if (changeArtifact.isValid()) { arts.add(artifactChange.getChangeArtifact()); } } return arts; }

Target:
private static ArrayList<Artifact> asArtifacts(Collection<Change> changes) { ArrayList<Artifact> arts = new ArrayList<>(); for (Change artifactChange : changes) { Artifact changeArtifact = artifactChange.getChangeArtifact(); if (changeArtifact.isValid()) { arts.add(changeArtifact); } } return arts; }
Source:
public synchronized boolean disconnect(BluetoothDevice device) { if (DBG) { StringBuilder sb = new StringBuilder(); dump(sb); Log.d(TAG, "A2DP disconnect device: " + device + ", InstanceMap start state: " + sb.toString()); } A2dpSinkStateMachine stateMachine = mInstanceMap.get(device); if (stateMachine == null) { return false; } int connectionState = stateMachine.getState(); if (connectionState == BluetoothProfile.STATE_DISCONNECTED || connectionState == BluetoothProfile.STATE_DISCONNECTING) { return false; } stateMachine.disconnect(); return true; }

Target:
public synchronized boolean disconnect(BluetoothDevice device) { if (DBG) { StringBuilder sb = new StringBuilder(); dump(sb); Log.d(TAG, "A2DP disconnect device: " + device + ", InstanceMap start state: " + sb.toString()); } A2dpSinkStateMachine stateMachine = mDeviceStateMap.get(device); if (stateMachine == null) { return false; } int connectionState = stateMachine.getState(); if (connectionState == BluetoothProfile.STATE_DISCONNECTED || connectionState == BluetoothProfile.STATE_DISCONNECTING) { return false; } stateMachine.disconnect(); return true; }
Source:
public List<Community> findAuthorized(Context context, EPerson ePerson, List<Integer> actions) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, Community.class); Root<Community> communityRoot = criteriaQuery.from(Community.class); Join<Community, ResourcePolicy> join = communityRoot.join("resourcePolicies"); List<Predicate> orPredicates = new LinkedList<Predicate>(); for (Integer action : actions) { orPredicates.add(criteriaBuilder.equal(join.get(ResourcePolicy_.actionId), action)); } Predicate orPredicate = criteriaBuilder.or(orPredicates.toArray(new Predicate[] {})); criteriaQuery.select(communityRoot); criteriaQuery.where( criteriaBuilder.and(criteriaBuilder.equal(join.get(ResourcePolicy_.resourceTypeId), Constants.COLLECTION), criteriaBuilder.equal(join.get(ResourcePolicy_.eperson), ePerson), orPredicate ) ); return list(context, criteriaQuery, true, Community.class, -1, -1); }

Target:
public List<Community> findAuthorized(Context context, EPerson ePerson, List<Integer> actions) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, Community.class); Root<Community> communityRoot = criteriaQuery.from(Community.class); Join<Community, ResourcePolicy> join = communityRoot.join("resourcePolicies"); List<Predicate> orPredicates = new LinkedList<Predicate>(); for (Integer action : actions) { orPredicates.add(criteriaBuilder.equal(join.get(ResourcePolicy_.actionId), action)); } Predicate orPredicate = criteriaBuilder.or(orPredicates.toArray(new Predicate[] {})); criteriaQuery.select(communityRoot); criteriaQuery.where( criteriaBuilder.and(criteriaBuilder.equal(join.get(ResourcePolicy_.resourceTypeId), Constants.COMMUNITY), criteriaBuilder.equal(join.get(ResourcePolicy_.eperson), ePerson), orPredicate ) ); return list(context, criteriaQuery, true, Community.class, -1, -1); }
Source:
public void testOnlyVisibleGroupsReturned() throws OrmException, JSchException, IOException { List<String> expectedGroups = Lists.newLinkedList(); expectedGroups.add("Anonymous Users"); expectedGroups.add("Registered Users"); TestAccount user = accounts.create("user", "user@example.com", "User"); Reader r = (new RestSession(user)).get("/groups/"); @SuppressWarnings("serial") Map<String, GroupInfo> result = (new Gson()).fromJson(r, new TypeToken<Map<String, GroupInfo>>() {}.getType()); assertGroups(expectedGroups, result.keySet()); }

Target:
public void testOnlyVisibleGroupsReturned() throws OrmException, JSchException, IOException { Set<String> expectedGroups = Sets.newHashSet(); expectedGroups.add("Anonymous Users"); expectedGroups.add("Registered Users"); TestAccount user = accounts.create("user", "user@example.com", "User"); Reader r = (new RestSession(user)).get("/groups/"); @SuppressWarnings("serial") Map<String, GroupInfo> result = (new Gson()).fromJson(r, new TypeToken<Map<String, GroupInfo>>() {}.getType()); assertGroups(expectedGroups, result.keySet()); }
Source:
public String getRoomLocation(String displayName) { UI.doubleClick(driver.findElement(By.xpath(" return RoomLocationCmbBox.getText(); }

Target:
public String getRoomLocation(String displayName) { UI.doubleClick(driver.findElement(By.xpath(" + displayName + "')and@class='ng-binding']"))); return roomLocationCmbBox.getText(); }
Source:
Series(String string) { this.digits = Arrays.stream(string.split("")).collect(Collectors.toList()); if(!string.isEmpty()) { this.digitsSize = this.digits.size(); }else { this.digitsSize = 0; } }

Target:
Series(String string) { this.digits = Arrays.stream(string.split("")).collect(Collectors.toList()); this.digitsSize = string.isEmpty()?0:this.digits.size(); }
Source:
public static JobConfig fromJSON(JsonReader jsonReader) { JobRepresenter.jsonReader = jsonReader; JobConfig jobConfig = new JobConfig(); if (jsonReader == null) { return jobConfig; } jsonReader.readCaseInsensitiveStringIfPresent("name", jobConfig::setName); setRunInstanceCount(jobConfig); setTimeout(jobConfig); jsonReader.readStringIfPresent("elastic_profile_id", jobConfig::setElasticProfileId); setArtifacts(jobConfig); setEnvironmentVariables(jobConfig); setResources(jobConfig); setTabs(jobConfig); setProperties(jobConfig); setTasks(jobConfig); return jobConfig; }

Target:
public static JobConfig fromJSON(JsonReader jsonReader) { JobRepresenter.jsonReader = jsonReader; JobConfig jobConfig = new JobConfig(); jsonReader.readCaseInsensitiveStringIfPresent("name", jobConfig::setName); setRunInstanceCount(jobConfig); setTimeout(jobConfig); jsonReader.readStringIfPresent("elastic_profile_id", jobConfig::setElasticProfileId); setArtifacts(jobConfig); jobConfig.setVariables(EnvironmentVariableRepresenter.fromJSONArray(jsonReader)); setResources(jobConfig); jobConfig.setTabs(TabConfigRepresenter.fromJSONArray(jsonReader)); jobConfig.setProperties(PropertyConfigRepresenter.fromJSONArray(jsonReader)); jobConfig.setTasks(TaskRepresenter.fromJSONArray(jsonReader)); return jobConfig; }
Source:
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(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); } }

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:
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> 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())); }

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:
public Solution[] computeOptimizationProblem( SuitableOptions cloudOffers, QualityInformation requirements, Topology topology, int numPlansToGenerate) { Solution[] bestSols = super.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; }

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:
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")); }

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:
public void update() throws Exception { 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)); }

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:
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(); dis.close(); } 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; }

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:
void addFeature(SimpleFeature feature) { 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); } }

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:
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.synchronizedMap(new HashMap<>(additionalAttributes)); }

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:
public List<String> getAvailableSearchFields(String opac) throws IllegalArgumentException { 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!"); } }

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:
public InputStream getInputStream() throws IOException { return context.getEntry(path).getInputStream().get(); }

Target:
public InputStream getInputStream() throws IOException { return entry.getInputStream().orElseThrow(FileNotFoundException::new); }
Source:
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); } } } }

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:
public void setCheckedElements(Object[] elements) { fCheckedObjects = new HashSet<>(); for (Object element : elements) { fCheckedObjects.add(element); } fCheckboxTreeViewer.setCheckedElements(elements); }

Target:
public void setCheckedElements(Object[] elements) { fCheckedObjects = Sets.newHashSet(elements); fCheckboxTreeViewer.setCheckedElements(elements); }
Source:
public void testStripedAndReplicatedFileChecksum() throws Exception { prepareTestFiles(fileSize, new String[] {stripedFile1, replicatedFile}); FileChecksum stripedFileChecksum1 = getFileChecksum(stripedFile1, 10, false); FileChecksum replicatedFileChecksum = getFileChecksum(replicatedFile, 10, false); if (expectComparableStripedAndReplicatedFiles) { Assert.assertEquals(stripedFileChecksum1, replicatedFileChecksum); } else { Assert.assertNotEquals(stripedFileChecksum1, replicatedFileChecksum); } }

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:
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 { locationType = LocationType.ANY; } 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); }

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:
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; }

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:
private void initializeConfiguration() { ITestObjectFactory factory = m_objectFactory; addServiceLoaderListeners(); for (XmlSuite s : m_suites) { List<XmlSuite> childSuites = s.getChildSuites(); 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); }

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:
<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 || statResult.size() > 3) { 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"); }

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:
public List<PermissionSubject> getPermissionCheckSubjects() { 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)); } }

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:
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"; for(String line : errorString.split("\n")) { errors.add(line); } } } return errors; }

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:
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}", e.getMessage()); 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; }

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; }