auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void greenTerraConvert(Player player, Block block) { Material type = block.getType(); if (Misc.blockBreakSimulate(block, player, false)) { if (Config.getInstance().getHerbalismGreenThumbSmoothbrickToMossy() && type == Material.SMOOTH_BRICK && block.getData() == 0) { block.setTypeIdAndData(block.getTypeId(), (byte) 1, false); } else if (Config.getInstance().getHerbalismGreenThumbDirtToGrass() && type == Material.DIRT) { block.setType(Material.GRASS); } else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLESTONE) { block.setType(Material.MOSSY_COBBLESTONE); mcMMO.placeStore.setTrue(block); } else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLE_WALL && (block.getData() == 0) { block.setData(1); } } }

Target:
public static void greenTerraConvert(Player player, Block block) { Material type = block.getType(); if (Misc.blockBreakSimulate(block, player, false)) { if (Config.getInstance().getHerbalismGreenThumbSmoothbrickToMossy() && type == Material.SMOOTH_BRICK && block.getData() == 0) { block.setTypeIdAndData(block.getTypeId(), (byte) 1, false); } else if (Config.getInstance().getHerbalismGreenThumbDirtToGrass() && type == Material.DIRT) { block.setType(Material.GRASS); } else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLESTONE) { block.setType(Material.MOSSY_COBBLESTONE); mcMMO.placeStore.setTrue(block); } else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLE_WALL && (block.getData() == 0)) { block.setData((Byte) 1); } } }
Source:
public void onPlayerDeath(LivingDeathEvent event) { if (!(event.getEntityLiving() instanceof EntityPlayer) || event.isCanceled()) { return; } EntityPlayer player = (EntityPlayer) event.getEntityLiving(); if (!player.isServerWorld()) { return; } ArmorSummery summery = new ArmorSummery().getSummery(player); if (summery == null || event.getSource() == ADMIN_KILL) { return; } if (summery.protectionPoints > 500 && player.getCapability(PlayerCapabilitiesProvider.PLAYER_CAP, null).getShieldState()) { event.setCanceled(true); event.getEntityLiving().setHealth(10); return; } if (!summery.hasDraconic) { return; } int[] charge = new int[summery.armorStacks.size()]; long totalCharge = 0; for (int i = 0; i < summery.armorStacks.size(); i++) { if (!summery.armorStacks.get(i).isEmpty()) { charge[i] = ((ICustomArmor) summery.armorStacks.get(i).getItem()).getEnergyStored(summery.armorStacks.get(i)); totalCharge += charge[i]; } } if (totalCharge < ToolStats.LAST_STAND_ENERGY) { return; } for (int i = 0; i < summery.armorStacks.size(); i++) { if (!summery.armorStacks.get(i).isEmpty()) { ((ICustomArmor) summery.armorStacks.get(i).getItem()).modifyEnergy(summery.armorStacks.get(i), -(int) ((charge[i] / (double) totalCharge) * 10000000L)); } } summery.saveStacks(player); player.sendMessage(new TextComponentTranslation("msg.de.shieldDepleted.txt").setStyle(new Style().setColor(TextFormatting.DARK_RED))); event.setCanceled(true); player.setHealth(1); }

Target:
public void onPlayerDeath(LivingDeathEvent event) { if (!(event.getEntityLiving() instanceof EntityPlayer) || event.isCanceled()) { return; } EntityPlayer player = (EntityPlayer) event.getEntityLiving(); if (!player.isServerWorld()) { return; } ArmorSummery summery = new ArmorSummery().getSummery(player); if (summery == null || event.getSource() == ADMIN_KILL) { return; } if (summery.protectionPoints > 500 && player.getCapability(ShieldStateProvider.PLAYER_CAP, null).getShieldState()) { event.setCanceled(true); event.getEntityLiving().setHealth(10); return; } if (!summery.hasDraconic) { return; } int[] charge = new int[summery.armorStacks.size()]; long totalCharge = 0; for (int i = 0; i < summery.armorStacks.size(); i++) { if (!summery.armorStacks.get(i).isEmpty()) { charge[i] = ((ICustomArmor) summery.armorStacks.get(i).getItem()).getEnergyStored(summery.armorStacks.get(i)); totalCharge += charge[i]; } } if (totalCharge < ToolStats.LAST_STAND_ENERGY) { return; } for (int i = 0; i < summery.armorStacks.size(); i++) { if (!summery.armorStacks.get(i).isEmpty()) { ((ICustomArmor) summery.armorStacks.get(i).getItem()).modifyEnergy(summery.armorStacks.get(i), -(int) ((charge[i] / (double) totalCharge) * 10000000L)); } } summery.saveStacks(player); player.sendMessage(new TextComponentTranslation("msg.de.shieldDepleted.txt").setStyle(new Style().setColor(TextFormatting.DARK_RED))); event.setCanceled(true); player.setHealth(1); }
Source:
public void checkMessageOnCoordinatorChangeTest() throws Exception { Ignite server1 = startGrid("server1"); Ignite client = startClientGrid("client"); Ignite server2 = startGrid("server2"); MockLogger log = new MockLogger(); log.setLevel(Level.INFO); setLogger(log, server2); server1.close(); client.close(); assertEquals("There should be no message that the client was the coordinator", 0, F.view(log.logs(), msg -> msg.contains("Coordinator changed") && (msg.contains("isClient=true"))) .size() ); }

Target:
public void checkMessageOnCoordinatorChangeTest() throws Exception { startGrid(1); startClientGrid("client"); Ignite server2 = startGrid(2); MockLogger log = new MockLogger(); log.setLevel(Level.INFO); setLogger(log, server2); stopGrid(1); stopGrid("client"); assertFalse(log.logs().stream().anyMatch(msg -> msg.contains("Coordinator changed") && msg.contains("isClient=true"))); }
Source:
public void process() { if (renderingConfig.isSsao()) { PerformanceMonitor.startActivity("rendering/ambientOcclusionPasses"); sceneOpaque = dynamicFBM.getFBO(DefaultDynamicFBOs.ReadOnlyGBuffer.getResourceUrn()); ssaoBlurredFBO = dynamicFBM.getFBO(SSAO_BLURRED_URN); ssaoFBO = dynamicFBM.getFBO(SSAO_URN); generateSSAO(); generateBlurredSSAO(); PerformanceMonitor.endActivity(); } }

Target:
public void process() { if (renderingConfig.isSsao()) { PerformanceMonitor.startActivity("rendering/ambientOcclusionPasses"); ssaoBlurredFBO = displayResolutionDependentFBOs.get(SSAO_BLURRED); ssaoFBO = displayResolutionDependentFBOs.get(SSAO); generateSSAO(); generateBlurredSSAO(); PerformanceMonitor.endActivity(); } }
Source:
@Override public void setLenient(boolean lenient) { this.lenient = true; }

Target:
@Override public void setLenient(boolean lenient) { this.lenient = lenient; }
Source:
private GatewayOrder buildAuthoriseOrder(CardAuthorisationGatewayRequest request) { logMissingDdcResultFor3dsFlexIntegration(request); boolean is3dsRequired = request.getAuthCardDetails().getWorldpay3dsFlexDdcResult().isPresent() || request.getGatewayAccount().isRequires3ds(); boolean exemptionEngine = request.getGatewayAccount().isRequires3ds() ? Optional.ofNullable(request.getGatewayAccount().getWorldpay3dsFlexCredentials()) .map(Worldpay3dsFlexCredentials::isExemptionEngine) .orElse(false) : false; var builder = aWorldpayAuthoriseOrderRequestBuilder() .withSessionId(WorldpayAuthoriseOrderSessionId.of(request.getChargeExternalId())) .with3dsRequired(is3dsRequired) .withExemptionEngine(exemptionEngine); if (request.getGatewayAccount().isSendPayerIpAddressToGateway()) { request.getAuthCardDetails().getIpAddress().ifPresent(builder::withPayerIpAddress); } return builder .withTransactionId(request.getTransactionId().orElse("")) .withMerchantCode(request.getGatewayAccount().getCredentials().get(CREDENTIALS_MERCHANT_ID)) .withDescription(request.getDescription()) .withAmount(request.getAmount()) .withAuthorisationDetails(request.getAuthCardDetails()) .build(); }

Target:
private GatewayOrder buildAuthoriseOrder(CardAuthorisationGatewayRequest request) { logMissingDdcResultFor3dsFlexIntegration(request); boolean is3dsRequired = request.getAuthCardDetails().getWorldpay3dsFlexDdcResult().isPresent() || request.getGatewayAccount().isRequires3ds(); boolean exemptionEngineEnabled = Optional.ofNullable(request.getGatewayAccount().getWorldpay3dsFlexCredentials()) .map(Worldpay3dsFlexCredentials::isExemptionEngineEnabled) .orElse(false); var builder = aWorldpayAuthoriseOrderRequestBuilder() .withSessionId(WorldpayAuthoriseOrderSessionId.of(request.getChargeExternalId())) .with3dsRequired(is3dsRequired) .withExemptionEngine(exemptionEngineEnabled); if (request.getGatewayAccount().isSendPayerIpAddressToGateway()) { request.getAuthCardDetails().getIpAddress().ifPresent(builder::withPayerIpAddress); } return builder .withTransactionId(request.getTransactionId().orElse("")) .withMerchantCode(request.getGatewayAccount().getCredentials().get(CREDENTIALS_MERCHANT_ID)) .withDescription(request.getDescription()) .withAmount(request.getAmount()) .withAuthorisationDetails(request.getAuthCardDetails()) .build(); }
Source:
public Void call() throws Exception { log.debug("Invoked launch command"); if (verbose) { System.out.println("Launching brooklyn app: "+app+" in "+Iterables.toString(locations)); } ResourceUtils utils = new ResourceUtils(this); ClassLoader parent = utils.getLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); log.debug("Load the user's application"); AbstractApplication application = loadApplicationFromClasspathOrParse(utils, loader, app); if (script != null) { log.debug("Running the user povided script: " + script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } List<Location> brooklynLocations = new LocationRegistry().getLocationsById( (locations==null || Iterables.isEmpty(locations)) ? ImmutableSet.of(CommandLineLocations.LOCALHOST) : locations); log.info("Adding application under brooklyn management"); BrooklynLauncher.manage(application, port, !noShutdownOnExit, !noConsole); log.info("Starting brooklyn application: "+app); application.start(brooklynLocations); if (verbose) { Entities.dumpInfo(application); } log.info("Blocking and waiting for cntrl-c or kill"); waitUntilInterrupted(); return null; }

Target:
public Void call() throws Exception { log.debug("Invoked launch command"); if (verbose) { System.out.println("Launching brooklyn app: "+app+" in "+Iterables.toString(locations)); } ResourceUtils utils = new ResourceUtils(this); ClassLoader parent = utils.getLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); log.debug("Load the user's application: {}", app); AbstractApplication application = loadApplicationFromClasspathOrParse(utils, loader, app); if (script != null) { log.debug("Running the user povided script: {}", script); String content = utils.getResourceAsString(script); GroovyShell shell = new GroovyShell(loader); shell.evaluate(content); } List<Location> brooklynLocations = new LocationRegistry().getLocationsById( (locations==null || Iterables.isEmpty(locations)) ? ImmutableSet.of(CommandLineLocations.LOCALHOST) : locations); log.info("Adding application under brooklyn management"); BrooklynLauncher.manage(application, port, !noShutdownOnExit, !noConsole); log.info("Starting brooklyn application: {}", app); application.start(brooklynLocations); if (verbose) { Entities.dumpInfo(application); } log.info("Launched application; now blocking to wait for cntrl-c or kill"); waitUntilInterrupted(); return null; }
Source:
public void executeTransaction(Transaction transaction) { if (transaction == null) { throw new IllegalArgumentException("Transaction should not be null"); } if (sharedRealm.capabilities.isMainThread()) { if (getConfiguration().isAllowWritesOnUiThread()) { RealmLog.warn("It is not recommended to run transactions on the UI thread as it may lead to a drop of frames or ANRs. Please consider using 'executeTransactionAsync' instead."); } else { throw new RealmException("Running transactions on the UI thread is disabled by default. You can opt in by using 'RealmConfiguration.allowWritesOnUiThread'."); } } beginTransaction(); try { transaction.execute(this); commitTransaction(); } catch (Throwable e) { if (isInTransaction()) { cancelTransaction(); } else { RealmLog.warn("Could not cancel transaction, not currently in a transaction."); } throw e; } }

Target:
public void executeTransaction(Transaction transaction) { if (transaction == null) { throw new IllegalArgumentException("Transaction should not be null"); } checkAllowWritesOnUiThread(); beginTransaction(); try { transaction.execute(this); commitTransaction(); } catch (Throwable e) { if (isInTransaction()) { cancelTransaction(); } else { RealmLog.warn("Could not cancel transaction, not currently in a transaction."); } throw e; } }
Source:
public void accessingSyncRealmResultInsideAsyncResultListener() { final Realm realm = looperThread.realm; final AtomicInteger asyncResultCallback = new AtomicInteger(0); final RealmResults<AllTypes> syncResults = realm.where(AllTypes.class).findAll(); RealmResults<AllTypes> results = realm.where(AllTypes.class).findAll(); looperThread.keepStrongReference.add(results); results.addChangeListener(new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> results) { switch (asyncResultCallback.incrementAndGet()) { case 1: assertEquals(0, results.size()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.createObject(AllTypes.class); } }); break; case 2: assertEquals(1, results.size()); assertEquals(1, syncResults.size()); looperThread.testComplete(); break; } } }); }

Target:
public void accessingSyncRealmResultInsideAsyncResultListener() { final Realm realm = looperThread.realm; final AtomicInteger asyncResultCallback = new AtomicInteger(0); final RealmResults<AllTypes> syncResults = realm.where(AllTypes.class).findAll(); RealmResults<AllTypes> results = realm.where(AllTypes.class).findAllAsync(); looperThread.keepStrongReference.add(results); results.addChangeListener(new RealmChangeListener<RealmResults<AllTypes>>() { @Override public void onChange(RealmResults<AllTypes> results) { switch (asyncResultCallback.incrementAndGet()) { case 1: assertEquals(0, results.size()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.createObject(AllTypes.class); } }); break; case 2: assertEquals(1, results.size()); assertEquals(1, syncResults.size()); looperThread.testComplete(); break; } } }); }
Source:
public void saveMethod() { this.method.script = (ScriptWrapper) this.scriptsComboBox.getSelectedItem(); if (this.dynamicFieldsPanel != null) this.method.paramValues = this.dynamicFieldsPanel.getFieldValues(); else this.method.paramValues = Collections.emptyMap(); }

Target:
public void saveMethod() { this.method.script = (ScriptWrapper) this.scriptsComboBox.getSelectedItem(); if (this.dynamicFieldsPanel != null) { this.method.paramValues = this.dynamicFieldsPanel.getFieldValues(); } else { this.method.paramValues = Collections.emptyMap(); } }
Source:
public void load(String payload) { for (Handler h : loadHandlers) { h.handle(payload); } }

Target:
public void load(String payload) { List<JsonNode> objects = objectReconstructor.reconstruct(payload.split("\n")); for(JsonNode singleObject : objects) { entryValidator.validateEntry(register, singleObject); } loadHandler.load(objects); }
Source:
public TaskStatus run(TaskToolbox toolbox) throws Exception { final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox)); if(!myLock.getDataSource().equals(getDataSource())) { throw new ISE("WTF?! Lock dataSource[%s] != task dataSource[%s]", myLock.getDataSource(), getDataSource()); } if(!myLock.getInterval().equals(getInterval())) { throw new ISE("WTF?! Lock interval[%s] != task interval[%s]", myLock.getInterval(), getInterval()); } final List<DataSegment> unusedSegments = toolbox .getTaskActionClient() .submit(new SegmentListUnusedAction(myLock.getDataSource(), myLock.getInterval())); for(final DataSegment unusedSegment : unusedSegments) { if(unusedSegment.getVersion().compareTo(myLock.getVersion()) > 0) { throw new ISE( "WTF?! Unused segment[%s] has version[%s] > task version[%s]", unusedSegment.getIdentifier(), unusedSegment.getVersion(), myLock.getVersion() ); } log.info("OK to move segment: %s", unusedSegment.getIdentifier()); } List<DataSegment> movedSegments = Lists.newLinkedList(); for (DataSegment segment : unusedSegments) { movedSegments.add(toolbox.getDataSegmentMover().move(segment, targetLoadSpec)); } toolbox.getTaskActionClient().submit(new SegmentMoveAction( ImmutableSet.copyOf(movedSegments) )); return TaskStatus.success(getId()); }

Target:
public TaskStatus run(TaskToolbox toolbox) throws Exception { final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox)); if(!myLock.getDataSource().equals(getDataSource())) { throw new ISE("WTF?! Lock dataSource[%s] != task dataSource[%s]", myLock.getDataSource(), getDataSource()); } if(!myLock.getInterval().equals(getInterval())) { throw new ISE("WTF?! Lock interval[%s] != task interval[%s]", myLock.getInterval(), getInterval()); } final List<DataSegment> unusedSegments = toolbox .getTaskActionClient() .submit(new SegmentListUnusedAction(myLock.getDataSource(), myLock.getInterval())); for(final DataSegment unusedSegment : unusedSegments) { if(unusedSegment.getVersion().compareTo(myLock.getVersion()) > 0) { throw new ISE( "WTF?! Unused segment[%s] has version[%s] > task version[%s]", unusedSegment.getIdentifier(), unusedSegment.getVersion(), myLock.getVersion() ); } log.info("OK to move segment: %s", unusedSegment.getIdentifier()); } List<DataSegment> movedSegments = Lists.newLinkedList(); for (DataSegment segment : unusedSegments) { movedSegments.add(toolbox.getDataSegmentMover().move(segment, targetLoadSpec)); } toolbox.getTaskActionClient().submit(new SegmentMetadataUpdateAction( ImmutableSet.copyOf(movedSegments) )); return TaskStatus.success(getId()); }
Source:
public List<Pair<Guid, Integer>> score(Cluster cluster, List<VDS> hosts, VM vm, Map<String, String> parameters) { List<VDS> acceptableHostsList = getAcceptableHosts(false, hosts, vm, new PerHostMessages()); Map<Guid, VDS> acceptableHostsMap = acceptableHostsList.stream().collect(Collectors.toMap(VDS::getId, h -> h)); List<Pair<Guid, Integer>> retList = new ArrayList<>(); int score; for (VDS host : hosts) { score = DEFAULT_SCORE; if (!acceptableHostsMap.containsKey(host.getId())) { score = MaxSchedulerWeight; } retList.add(new Pair<>(host.getId(), score)); } return retList; }

Target:
public List<Pair<Guid, Integer>> score(Cluster cluster, List<VDS> hosts, VM vm, Map<String, String> parameters) { calculateHostViolationCount(false, hosts, vm, new PerHostMessages()); List<Pair<Guid, Integer>> retList = new ArrayList<>(); int score; for (VDS host : hosts) { score = getHostViolationCount(host.getId()); retList.add(new Pair<>(host.getId(), score)); } return retList; }
Source:
public void testAcceptAll() throws ValidationException { String value = "my value"; Assert.assertEquals(value, new AcceptAllValidator().validate(value)); }

Target:
public void testAcceptAll() throws ValidationException { String value = "my value"; Assert.assertEquals(value, new AcceptAllValidator<String>().validate(value)); }
Source:
protected AbstractXStreamSerializer(Builder builder) { builder.validate(); this.charset = builder.charset; this.xStream = builder.xStream; this.converter = builder.converter; this.revisionResolver = builder.revisionResolver; if (builder.classLoader != null) { this.xStream.setClassLoader(builder.classLoader); } if (converter instanceof ChainingConverter) { registerConverters((ChainingConverter) converter); } xStream.addImmutableType(UUID.class, true); xStream.alias("domain-event", GenericDomainEventMessage.class); xStream.alias("event", GenericEventMessage.class); xStream.alias("command", GenericCommandMessage.class); xStream.alias("uuid", UUID.class); xStream.alias("meta-data", MetaData.class); xStream.registerConverter(new MetaDataConverter(xStream.getMapper())); }

Target:
protected AbstractXStreamSerializer(Builder builder) { builder.validate(); this.charset = builder.charset; this.xStream = builder.xStream; this.converter = builder.converter; this.revisionResolver = builder.revisionResolver; if (converter instanceof ChainingConverter) { registerConverters((ChainingConverter) converter); } xStream.addImmutableType(UUID.class, true); xStream.alias("domain-event", GenericDomainEventMessage.class); xStream.alias("event", GenericEventMessage.class); xStream.alias("command", GenericCommandMessage.class); xStream.alias("uuid", UUID.class); xStream.alias("meta-data", MetaData.class); xStream.registerConverter(new MetaDataConverter(xStream.getMapper())); }
Source:
private File zipFile(File file) { new File(tempDir).mkdir(); File result = new File(tempDir + File.separator + file.getName() + ".zip"); try { FileOutputStream dest = new FileOutputStream(result); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte[] data = new byte[BUFFER]; File[] files; if (file.isDirectory()) { files = file.listFiles(); } else { files = new File[1]; files[0] = file; } for (File f : files) { FileInputStream fi = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); int count; while ((count = bis.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } bis.close(); } out.close(); } catch (FileNotFoundException ex) { LOGGER.error("File " + file.getAbsolutePath() + " was not found", ex); } catch (IOException ex) { LOGGER.error("IOException while zipping file " + file.getAbsolutePath(), ex); } return result; }

Target:
private File zipFile(File file) { File result = new File(tempDir + File.separator + file.getName() + ".zip"); result.getParentFile().mkdir(); ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(result))); byte[] data = new byte[BUFFER]; File[] files; if (file.isDirectory()) { files = file.listFiles(); } else { files = new File[1]; files[0] = file; } for (File f : files) { FileInputStream fi = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); int count; while ((count = bis.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } bis.close(); } } catch (FileNotFoundException ex) { LOGGER.error("File " + file.getAbsolutePath() + " was not found", ex); } catch (IOException ex) { LOGGER.error("IOException while zipping file " + file.getAbsolutePath(), ex); } finally { try { out.close(); } catch (IOException ex) { LOGGER.error("Error while closing ZipOutputStream", ex); } } return result; }
Source:
private void initPeopleQueryEvaluator() throws HumanTaskServerException { try { PeopleQueryEvaluator peopleQueryEvaluator = (PeopleQueryEvaluator) Class.forName(serverConfig.getPeopleQueryEvaluatorClass()).newInstance(); taskEngine.setPeopleQueryEvaluator(peopleQueryEvaluator); } catch (Exception ex) { String errMsg = "Error instantiating the PeopleQueryEvaluator Class :" + serverConfig.getPeopleQueryEvaluatorClass(); log.error(errMsg); throw new HumanTaskServerException(errMsg, ex); } }

Target:
private void initPeopleQueryEvaluator() throws HumanTaskServerException { try { PeopleQueryEvaluator peopleQueryEvaluator = (PeopleQueryEvaluator) Class.forName(serverConfig.getPeopleQueryEvaluatorClass()).newInstance(); taskEngine.setPeopleQueryEvaluator(peopleQueryEvaluator); } catch (Exception ex) { String errMsg = "Error instantiating the PeopleQueryEvaluator Class :" + serverConfig.getPeopleQueryEvaluatorClass(); throw new HumanTaskServerException(errMsg, ex); } }
Source:
public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(100); taskScheduler.initialize(); return taskScheduler; }

Target:
public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(taskSchedulerPoolSize); taskScheduler.initialize(); return taskScheduler; }
Source:
public static Collection<Object[]> data() { return asList(new Object[][] { { "org.openqa.selenium.chrome.ChromeDriver", DriverManagerType.CHROME }, { "org.openqa.selenium.chromium.ChromiumDriver", DriverManagerType.CHROMIUM }, { "org.openqa.selenium.firefox.FirefoxDriver", DriverManagerType.FIREFOX }, { "org.openqa.selenium.opera.OperaDriver", DriverManagerType.OPERA }, { "org.openqa.selenium.edge.EdgeDriver", DriverManagerType.EDGE }, { "org.openqa.selenium.phantomjs.PhantomJSDriver", DriverManagerType.PHANTOMJS }, { "org.openqa.selenium.ie.InternetExplorerDriver", DriverManagerType.IEXPLORER }, { "org.openqa.selenium.remote.server.SeleniumServer", DriverManagerType.SELENIUM_SERVER_STANDALONE } }); }

Target:
public static Collection<Object[]> data() { return asList(new Object[][] { { "org.openqa.selenium.chrome.ChromeDriver", DriverManagerType.CHROME }, { "org.openqa.selenium.chrome.ChromeDriver", DriverManagerType.CHROMIUM }, { "org.openqa.selenium.firefox.FirefoxDriver", DriverManagerType.FIREFOX }, { "org.openqa.selenium.opera.OperaDriver", DriverManagerType.OPERA }, { "org.openqa.selenium.edge.EdgeDriver", DriverManagerType.EDGE }, { "org.openqa.selenium.phantomjs.PhantomJSDriver", DriverManagerType.PHANTOMJS }, { "org.openqa.selenium.ie.InternetExplorerDriver", DriverManagerType.IEXPLORER }, { "org.openqa.selenium.remote.server.SeleniumServer", DriverManagerType.SELENIUM_SERVER_STANDALONE } }); }
Source:
public ParameterAveragingTrainingMaster(boolean saveUpdater, Integer numWorkers, int rddDataSetNumExamples, int batchSizePerWorker, int averagingFrequency, int aggregationDepth, int prefetchNumBatches, Repartition repartition, RepartitionStrategy repartitionStrategy, StorageLevel storageLevel, boolean collectTrainingStats) { if (numWorkers <= 0) throw new IllegalArgumentException("Invalid number of workers: " + numWorkers + " (must be >= 1)"); if (rddDataSetNumExamples <= 0) throw new IllegalArgumentException( "Invalid rdd data set size: " + rddDataSetNumExamples + " (must be >= 1)"); if (averagingFrequency <= 0) throw new IllegalArgumentException("Invalid input: averaging frequency must be >= 1"); if (aggregationDepth <= 0) { throw new IllegalArgumentException("Invalid input: tree aggregation depth must be >= 1"); } this.saveUpdater = saveUpdater; this.numWorkers = numWorkers; this.rddDataSetNumExamples = rddDataSetNumExamples; this.batchSizePerWorker = batchSizePerWorker; this.averagingFrequency = averagingFrequency; this.aggregationDepth = aggregationDepth; this.prefetchNumBatches = prefetchNumBatches; this.collectTrainingStats = collectTrainingStats; this.repartition = repartition; this.repartitionStrategy = repartitionStrategy; this.storageLevel = storageLevel; if (collectTrainingStats) stats = new ParameterAveragingTrainingMasterStats.ParameterAveragingTrainingMasterStatsHelper(); String jvmuid = UIDProvider.getJVMUID(); this.trainingMasterUID = System.currentTimeMillis() + "_" + (jvmuid.length() <= 8 ? jvmuid : jvmuid.substring(0, 8)); this.rng = new Random(); }

Target:
public ParameterAveragingTrainingMaster(boolean saveUpdater, Integer numWorkers, int rddDataSetNumExamples, int batchSizePerWorker, int averagingFrequency, int aggregationDepth, int prefetchNumBatches, Repartition repartition, RepartitionStrategy repartitionStrategy, StorageLevel storageLevel, boolean collectTrainingStats) { checkArgument(numWorkers > 0, "Invalid number of workers: " + numWorkers + " (must be >= 1)"); checkArgument(rddDataSetNumExamples > 0, "Invalid rdd data set size: " + rddDataSetNumExamples + " (must be >= 1)"); checkArgument(averagingFrequency > 0, "Invalid input: averaging frequency must be >= 1"); checkArgument(aggregationDepth > 0, "Invalid input: tree aggregation depth must be >= 1"); this.saveUpdater = saveUpdater; this.numWorkers = numWorkers; this.rddDataSetNumExamples = rddDataSetNumExamples; this.batchSizePerWorker = batchSizePerWorker; this.averagingFrequency = averagingFrequency; this.aggregationDepth = aggregationDepth; this.prefetchNumBatches = prefetchNumBatches; this.collectTrainingStats = collectTrainingStats; this.repartition = repartition; this.repartitionStrategy = repartitionStrategy; this.storageLevel = storageLevel; if (collectTrainingStats) stats = new ParameterAveragingTrainingMasterStats.ParameterAveragingTrainingMasterStatsHelper(); String jvmuid = UIDProvider.getJVMUID(); this.trainingMasterUID = System.currentTimeMillis() + "_" + (jvmuid.length() <= 8 ? jvmuid : jvmuid.substring(0, 8)); this.rng = new Random(); }
Source:
public void testNoBytesSkipped() throws Exception { ResultCallbackTest callback = new ResultCallbackTest(); HttpResponseStreamHandler streamHandler = new HttpResponseStreamHandler(callback); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); ByteBuf buffer = generateByteBuf(); streamHandler.channelRead0(ctx, buffer); streamHandler.channelReadComplete(ctx); Assert.assertTrue(IOUtils.contentEquals(callback.getInputStream(), new ByteBufInputStream(buffer))); }

Target:
public void testNoBytesSkipped() throws Exception { ResultCallbackTest callback = new ResultCallbackTest(); HttpResponseStreamHandler streamHandler = new HttpResponseStreamHandler(callback); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); ByteBuf buffer = generateByteBuf(); streamHandler.channelRead0(ctx, buffer); streamHandler.channelReadComplete(ctx); assertTrue(IOUtils.contentEquals(callback.getInputStream(), new ByteBufInputStream(buffer))); }
Source:
protected Optional<ExampleProjectError> getError(Path projectPath) { POM pom = getPom(this.pomService, projectPath); boolean containsPlugin = pom.getBuild() != null && pom.getBuild() .getPlugins() .stream() .anyMatch(plugin -> this.kieArtifactId.equalsIgnoreCase(plugin.getArtifactId()) && this.kieGroupId.equalsIgnoreCase(plugin.getGroupId()) && this.kieVersion.equalsIgnoreCase(plugin.getVersion())); if (containsPlugin) { return Optional.empty(); } else { return Optional.of(new ExampleProjectError(KieMavenPluginValidator.class.getCanonicalName(), this.kiePluginExample)); } }

Target:
protected Optional<ExampleProjectError> getError(Path projectPath) { POM pom = getPom(this.pomService, projectPath); boolean containsPlugin = pom.getBuild() != null && pom.getBuild() .getPlugins() .stream() .anyMatch(plugin -> this.kieArtifactId.equalsIgnoreCase(plugin.getArtifactId()) && this.kieGroupId.equalsIgnoreCase(plugin.getGroupId())); if (containsPlugin) { return Optional.empty(); } else { return Optional.of(new ExampleProjectError(KieMavenPluginValidator.class.getCanonicalName(), this.kiePluginExample)); } }
Source:
public void testSuspendResume() throws Exception { Set<? extends NodeMetadata> suspendedNodes = client.suspendNodesMatching(inGroup(group)); for (ComputeMetadata node : suspendedNodes) { assert node.getProviderId() != null : node; assert node.getLocation() != null : node; assertEquals(node.getType(), ComputeType.NODE); } Set<? extends NodeMetadata> stoppedNodes = refreshNodes(); assert Iterables.all(stoppedNodes, new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { boolean returnVal = input.getStatus() == Status.SUSPENDED; if (!returnVal) getAnonymousLogger().warning(format("node %s in state %s%n", input.getId(), input.getStatus())); return returnVal; } }) : stoppedNodes; Set<? extends NodeMetadata> resumedNodes = client.resumeNodesMatching(inGroup(group)); for (ComputeMetadata node : resumedNodes) { assert node.getProviderId() != null : node; assert node.getLocation() != null : node; assertEquals(node.getType(), ComputeType.NODE); } testGet(); }

Target:
public void testSuspendResume() throws Exception { Set<? extends NodeMetadata> suspendedNodes = client.suspendNodesMatching(inGroup(group)); for (ComputeMetadata node : suspendedNodes) { assertNotNull(node); assert node.getProviderId() != null : node; assert node.getLocation() != null : node; } Set<? extends NodeMetadata> stoppedNodes = refreshNodes(); assert Iterables.all(stoppedNodes, new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { boolean returnVal = input.getStatus() == Status.SUSPENDED; if (!returnVal) getAnonymousLogger().warning(format("node %s in state %s%n", input.getId(), input.getStatus())); return returnVal; } }) : stoppedNodes; Set<? extends NodeMetadata> resumedNodes = client.resumeNodesMatching(inGroup(group)); for (ComputeMetadata node : resumedNodes) { assertNotNull(node); assert node.getProviderId() != null : node; assert node.getLocation() != null : node; } testGet(); }
Source:
public static File indexFile(final File file, final String extension) { return new File(file.getAbsoluteFile() + extension); }

Target:
private static File indexFile(final File file, final String extension) { return new File(file.getAbsoluteFile() + extension); }
Source:
private void initApp() { pref = PreferenceManager.getDefaultSharedPreferences(this); pref.edit().putString("version", BuildConfig.VERSION_NAME).commit(); Utils.VISUALIZATION_DIR = new File(getExternalCacheDir(), "Visualization"); Utils.VISUALIZATION_DIR.mkdirs(); if (pref.getString("current_directory", null) == null) { pref.edit().putString("current_directory", Environment.getExternalStoragePublicDirectory("TranslationRecorder").toString()).commit(); } pref.edit().putString("root_directory", Environment.getExternalStoragePublicDirectory("TranslationRecorder").toString()).commit(); File dir = new File(getExternalCacheDir(), STACKTRACE_DIR); dir.mkdirs(); GlobalExceptionHandler.register(dir); int minLogLevel = Integer.parseInt(pref.getString(KEY_PREF_LOGGING_LEVEL, PREF_DEFAULT_LOGGING_LEVEL)); configureLogger(minLogLevel, dir); String[] stacktraces = GlobalExceptionHandler.getStacktraces(dir); if (stacktraces.length > 0) { FragmentManager fm = getFragmentManager(); BugReportDialog brd = new BugReportDialog(); brd.setStyle(DialogFragment.STYLE_NO_TITLE, 0); brd.show(fm, "Bug Report Dialog"); } db = ((TranslationRecorderApp)getApplication()).getDatabase(); removeUnusedVisualizationFiles(); }

Target:
private void initApp() { pref = PreferenceManager.getDefaultSharedPreferences(this); pref.edit().putString("version", BuildConfig.VERSION_NAME).commit(); Utils.VISUALIZATION_DIR = new File(getExternalCacheDir(), "Visualization"); Utils.VISUALIZATION_DIR.mkdirs(); if (pref.getString("current_directory", null) == null) { pref.edit().putString( "current_directory", Environment.getExternalStoragePublicDirectory("TranslationRecorder").toString() ).commit(); } pref.edit().putString( "root_directory", Environment.getExternalStoragePublicDirectory("TranslationRecorder").toString() ).commit(); File dir = new File(getExternalCacheDir(), STACKTRACE_DIR); dir.mkdirs(); GlobalExceptionHandler.register(dir); int minLogLevel = Integer.parseInt(pref.getString(KEY_PREF_LOGGING_LEVEL, PREF_DEFAULT_LOGGING_LEVEL)); configureLogger(minLogLevel, dir); String[] stacktraces = GlobalExceptionHandler.getStacktraces(dir); if (stacktraces.length > 0) { FragmentManager fm = getFragmentManager(); BugReportDialog brd = new BugReportDialog(); brd.setStyle(DialogFragment.STYLE_NO_TITLE, 0); brd.show(fm, "Bug Report Dialog"); } removeUnusedVisualizationFiles(); }
Source:
public void testFunctionDeletion() { onFormulaEditor() .performOpenCategory(FUNCTIONS); onView(withText(containsString(random))) .perform(click()); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .performOpenCategory(FUNCTIONS); onView(allOf(withText(containsString(random)), withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE))) .perform(click()); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .checkShows(" "); }

Target:
public void testFunctionDeletion() { String random = getResourcesString(R.string.formula_editor_function_rand) + "(0,1)"; onFormulaEditor() .performOpenCategory(FUNCTIONS) .performSelect(random); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .performOpenCategory(FUNCTIONS) .performSelect(random); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .performClickOn(BACKSPACE); onFormulaEditor() .checkShows(" "); }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof RandomPaddingAffixElement)) { return false; } if (this == obj) { return true; } return Objects.equals(getPadding(), ((RandomPaddingAffixElement) obj).getPadding()); }

Target:
public boolean equals(Object obj) { return EqualsUtil.equals(this, obj, (e, o) -> e.append(getPadding(), o.getPadding())); }
Source:
private void skipUntil(byte... expected) throws IOException { while (!expect(expected)) { if (stream.skip(1) == 0) return; } }

Target:
private void skipUntil(byte... expected) throws IOException { while (!expect(expected)) { if (stream.read() == -1) return; } }
Source:
public CSVReader setLineEnd(final String lineEnd) { if ("\n".equals(lineEnd) || "\r\n".equals(lineEnd)) { this.lineEnd = null; } else { this.lineEnd = lineEnd; if (lineEnd != null && lineEnd.length() > 1) { log.warn("Line end params is too long", lineEnd); } } return this; }

Target:
public CSVReader setLineEnd(final String lineEnd) { if ("\n".equals(lineEnd) || "\r\n".equals(lineEnd)) { this.lineEnd = null; } else { this.lineEnd = lineEnd; if (lineEnd != null && lineEnd.length() != 1) { log.warn("Line end params must be single character", lineEnd); } } return this; }
Source:
private static void reduceSubtitles(ArrayList<SubtitleItem> subtitles, int limit) { int remove = subtitles.size() - limit; if (remove <= 0) { return; } LinkedHashMap<String, Integer> languages = new LinkedHashMap<>(); for (SubtitleItem subtitle : subtitles) { String languageCode = isBlank(subtitle.getLanguageCode()) ? null : subtitle.getLanguageCode(); if (!languages.containsKey(languageCode)) { languages.put(languageCode, 1); } else { languages.put(languageCode, languages.get(languageCode).intValue() + 1); } } if (languages.containsKey(null)) { remove -= removeLanguage(subtitles, languages, null, remove); } if (remove > 0) { ArrayList<LanguageRankedItem> languageRankedSubtitles = new ArrayList<>(); int languagePreference = 0; String languageCode = null; for (SubtitleItem subtitle : subtitles) { if (languageCode == null) { languageCode = subtitle.getLanguageCode(); languagePreference = languages.size() * 30; } else if (languageCode != subtitle.getLanguageCode()) { languageCode = subtitle.getLanguageCode(); languagePreference -= 30; } languageRankedSubtitles.add(new LanguageRankedItem( subtitle.getScore() + languagePreference, subtitle )); } Collections.sort(languageRankedSubtitles); for (LanguageRankedItem languageRankedItem : languageRankedSubtitles) { if (remove <= 0) { break; } if (subtitles.remove(languageRankedItem.subtitleItem)) { remove--; } } } }

Target:
private static void reduceSubtitles(ArrayList<SubtitleItem> subtitles, int limit) { int remove = subtitles.size() - limit; if (remove <= 0) { return; } LinkedHashMap<String, Integer> languages = new LinkedHashMap<>(); for (SubtitleItem subtitle : subtitles) { String languageCode = isBlank(subtitle.getLanguageCode()) ? null : subtitle.getLanguageCode(); if (!languages.containsKey(languageCode)) { languages.put(languageCode, 1); } else { languages.put(languageCode, languages.get(languageCode).intValue() + 1); } } if (languages.containsKey(null)) { remove -= removeLanguage(subtitles, languages, null, remove); } if (remove > 0) { ArrayList<LanguageRankedItem> languageRankedSubtitles = new ArrayList<>(); int languagePreference = 0; String languageCode = null; for (SubtitleItem subtitle : subtitles) { if (languageCode == null) { languageCode = subtitle.getLanguageCode(); languagePreference = languages.size() * 30; } else if (!languageCode.equals(subtitle.getLanguageCode())) { languageCode = subtitle.getLanguageCode(); languagePreference -= 30; } languageRankedSubtitles.add(new LanguageRankedItem( subtitle.getScore() + languagePreference, subtitle )); } Collections.sort(languageRankedSubtitles); for (LanguageRankedItem languageRankedItem : languageRankedSubtitles) { if (remove <= 0) { break; } if (subtitles.remove(languageRankedItem.subtitleItem)) { remove--; } } } }
Source:
public void execute(ApplicationContext currentContext) throws CLIException { SchedulerRestInterface scheduler = currentContext.getRestClient().getScheduler(); try { List<String> tasks = null; if(this.tag != null){ if (this.limit == 0) { tasks = scheduler.getJobTasksIdsByTag(currentContext.getSessionId(), jobId, tag); } else { tasks = scheduler.getJobTasksIdsByTagPaginated(currentContext.getSessionId(), jobId, tag, offset, limit); } } else{ if (this.limit == 0) { tasks = scheduler.getJobTasksIds(currentContext.getSessionId(), jobId); } else { tasks = scheduler.getJobTasksIdsPaginated(currentContext.getSessionId(), jobId, offset, limit); } } resultStack(currentContext).push(tasks); if (!currentContext.isSilent()) { writeLine(currentContext, "%s", tasks); } } catch (Exception e) { String message = null; if(this.tag == null){ message = String.format("An error occurred while retrieving %s tasks:", job()); } else{ message = String.format("An error occurred while retrieving %s tasks filtered by tag %s:", job(), tag); } handleError(message, e, currentContext); } }

Target:
public void execute(ApplicationContext currentContext) throws CLIException { SchedulerRestInterface scheduler = currentContext.getRestClient().getScheduler(); try { List<String> tasks = null; if (this.tag != null) { if (this.limit == 0) { tasks = scheduler.getJobTasksIdsByTag(currentContext.getSessionId(), jobId, tag) .getTaskIds(); } else { tasks = scheduler.getJobTasksIdsByTagPaginated(currentContext.getSessionId(), jobId, tag, offset, limit).getTaskIds(); } } else { if (this.limit == 0) { tasks = scheduler.getTasksNames(currentContext.getSessionId(), jobId).getTaskIds(); } else { tasks = scheduler .getTasksNamesPaginated(currentContext.getSessionId(), jobId, offset, limit) .getTaskIds(); } } resultStack(currentContext).push(tasks); if (!currentContext.isSilent()) { writeLine(currentContext, "%s", tasks); } } catch (Exception e) { String message = null; if (this.tag == null) { message = String.format("An error occurred while retrieving %s tasks:", job()); } else { message = String.format("An error occurred while retrieving %s tasks filtered by tag %s:", job(), tag); } handleError(message, e, currentContext); } }
Source:
private void initialize(String json) throws JSONException, IOException { JSONObject jo = new JSONObject(json); JSONArray fieldArray = jo.getJSONArray(FIELDS); if (jo.has(GLOBAL_PADDING_CHARACTER)) { globalPadding = jo.getString(GLOBAL_PADDING_CHARACTER).charAt(0); } else { globalPadding = DEFAULT_PADDING_CHARACTER; } if (jo.has(GLOBAL_ALIGNMENT)) { globalAlignment = jo.getString(GLOBAL_ALIGNMENT); } else { globalAlignment = DEFAULT_ALIGNMENT; } for (int i = 0; i < fieldArray.length(); i++) { JSONObject obj = fieldArray.getJSONObject(i); Field field = new Field(obj.getString(NAME), obj.getString(TYPE).toUpperCase(), obj.getInt(FIELD_LEN)); if(obj.has(FIELD_PADDING)) field.setPadding(obj.getString(FIELD_PADDING).charAt(0)); else field.setPadding(globalPadding); if(obj.has(FIELD_ALIGNMENT)) field.setAlignment(obj.getString(FIELD_ALIGNMENT)); else field.setAlignment(globalAlignment); if (field.getType() == FieldType.DATE) { if (obj.has(DATE_FORMAT)) { field.setDateFormat(obj.getString(DATE_FORMAT)); } else { field.setDateFormat(DEFAULT_DATE_FORMAT); } } if (field.getType() == FieldType.BOOLEAN) { if (obj.has(TRUE_VALUE)) { field.setTrueValue(obj.getString(TRUE_VALUE)); } else { field.setTrueValue(DEFAULT_TRUE_VALUE); } if (obj.has(FALSE_VALUE)) { field.setFalseValue(obj.getString(FALSE_VALUE)); } else { field.setFalseValue(DEFAULT_FALSE_VALUE); } } fields.add(field); fieldNames.add(field.name); } }

Target:
private void initialize(String json) throws JSONException, IOException { JSONObject jo = new JSONObject(json); JSONArray fieldArray = jo.getJSONArray(FIELDS); if (jo.has(FIELD_PADDING_CHARACTER)) { globalPadding = jo.getString(FIELD_PADDING_CHARACTER).charAt(0); } else { globalPadding = DEFAULT_PADDING_CHARACTER; } if (jo.has(FIELD_ALIGNMENT)) { globalAlignment = jo.getString(FIELD_ALIGNMENT); } else { globalAlignment = DEFAULT_ALIGNMENT; } for (int i = 0; i < fieldArray.length(); i++) { JSONObject obj = fieldArray.getJSONObject(i); Field field = new Field(obj.getString(NAME), obj.getString(TYPE).toUpperCase(), obj.getInt(FIELD_LENGTH)); if(obj.has(FIELD_PADDING_CHARACTER)) { field.setPadding(obj.getString(FIELD_PADDING_CHARACTER).charAt(0)); } else { field.setPadding(globalPadding); } if(obj.has(FIELD_ALIGNMENT)) { field.setAlignment(obj.getString(FIELD_ALIGNMENT)); } else { field.setAlignment(globalAlignment); } if (field.getType() == FieldType.DATE) { if (obj.has(DATE_FORMAT)) { field.setDateFormat(obj.getString(DATE_FORMAT)); } else { field.setDateFormat(DEFAULT_DATE_FORMAT); } } if (field.getType() == FieldType.BOOLEAN) { if (obj.has(TRUE_VALUE)) { field.setTrueValue(obj.getString(TRUE_VALUE)); } else { field.setTrueValue(DEFAULT_TRUE_VALUE); } if (obj.has(FALSE_VALUE)) { field.setFalseValue(obj.getString(FALSE_VALUE)); } else { field.setFalseValue(DEFAULT_FALSE_VALUE); } } fields.add(field); fieldNames.add(field.name); } }
Source:
protected void ExecuteVmCommand() { if (!getImagesList().isEmpty()) { lockVmWithCompensationIfNeeded(); if (!isInternalExecution()) { freeLock(); } } restoreSnapshotAndRemoveObsoleteSnapshots(); boolean succeeded = true; if (!getImagesList().isEmpty()) { for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); VdcReturnValueBase returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); if (succeeded && !returnValue.getSucceeded()) { succeeded = false; getReturnValue().setFault(returnValue.getFault()); } } } } removeSnapshotsFromDB(); if (!getTaskIdList().isEmpty()) { deleteOrphanedImages(); } else { endActionOnVmConfiguration(); } setSucceeded(succeeded); }

Target:
protected void ExecuteVmCommand() { if (!getImagesList().isEmpty()) { lockVmWithCompensationIfNeeded(); if (!isInternalExecution()) { freeLock(); } } restoreSnapshotAndRemoveObsoleteSnapshots(); boolean succeeded = true; for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); VdcReturnValueBase returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); if (succeeded && !returnValue.getSucceeded()) { succeeded = false; getReturnValue().setFault(returnValue.getFault()); } } } removeSnapshotsFromDB(); if (!getTaskIdList().isEmpty()) { deleteOrphanedImages(); } else { endActionOnVmConfiguration(); } setSucceeded(succeeded); }
Source:
public void updatingValues(TransactionBase tx, Iterator<Update<String, UriInfo>> updates) { Map<String, Long> domainUpdates = new HashMap<>(); while (updates.hasNext()) { Update<String, UriInfo> update = updates.next(); String uri = update.getKey(); UriInfo oldVal = update.getOldValue().orElse(UriInfo.ZERO); UriInfo newVal = update.getNewValue().orElse(UriInfo.ZERO); exportQ.add(tx, uri, new UriUpdate(uri, oldVal, newVal)); String pageDomain = URL.fromUri(uri).getReverseDomain(); if (oldVal.equals(UriInfo.ZERO) && !newVal.equals(UriInfo.ZERO)) { domainUpdates.merge(pageDomain, 1L, (o, n) -> o + n); linksNew.mark(); } else if (newVal.equals(UriInfo.ZERO) && !oldVal.equals(UriInfo.ZERO)) { domainUpdates.merge(pageDomain, -1L, (o, n) -> o + n); } } domainMap.update(tx, domainUpdates); }

Target:
public void updatingValues(TransactionBase tx, Iterator<Update<String, UriInfo>> updates) { Map<String, Long> domainUpdates = new HashMap<>(); while (updates.hasNext()) { Update<String, UriInfo> update = updates.next(); String uri = update.getKey(); UriInfo oldVal = update.getOldValue().orElse(UriInfo.ZERO); UriInfo newVal = update.getNewValue().orElse(UriInfo.ZERO); exportQ.add(tx, uri, new UriUpdate(uri, oldVal, newVal)); linksChanged.mark(); String pageDomain = URL.fromUri(uri).getReverseDomain(); if (oldVal.equals(UriInfo.ZERO) && !newVal.equals(UriInfo.ZERO)) { domainUpdates.merge(pageDomain, 1L, (o, n) -> o + n); linksNew.mark(); } else if (newVal.equals(UriInfo.ZERO) && !oldVal.equals(UriInfo.ZERO)) { domainUpdates.merge(pageDomain, -1L, (o, n) -> o + n); } } domainMap.update(tx, domainUpdates); }