auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public List<String> checkComplimentaryCriteriaAllRequired(List<String> criterionToCheck, <END> List<String> complimentaryCertNumbers, List<String> allCriteriaMet) { List<String> errors = new ArrayList<String>(); boolean hasAnyCert = hasAnyCert(criterionToCheck, allCriteriaMet); if (hasAnyCert) { for (String complimentaryCert : complimentaryCertNumbers) { boolean hasComplimentaryCert = hasCert(complimentaryCert, allCriteriaMet); if (!hasComplimentaryCert) { String criterionErrorString = ""; for(int i = 0; i < criterionToCheck.size(); i++) { String checkedCriteria = criterionToCheck.get(i); if(i > 0) { criterionErrorString += " or "; } criterionErrorString += checkedCriteria; } errors.add("Certification criterion " + criterionErrorString + " was found so " + complimentaryCert + " is required but was not found."); } } } return errors; }</code><technical_language>Do need public? if be, curious</technical_language>

Target:
protected List<String> checkComplimentaryCriteriaAllRequired(List<String> criterionToCheck, List<String> complimentaryCertNumbers, List<String> allCriteriaMet) { List<String> errors = new ArrayList<String>(); boolean hasAnyCert = hasAnyCert(criterionToCheck, allCriteriaMet); if (hasAnyCert) { for (String complimentaryCert : complimentaryCertNumbers) { boolean hasComplimentaryCert = hasCert(complimentaryCert, allCriteriaMet); if (!hasComplimentaryCert) { String criterionErrorString = ""; for(int i = 0; i < criterionToCheck.size(); i++) { String checkedCriteria = criterionToCheck.get(i); if(i > 0) { criterionErrorString += " or "; } criterionErrorString += checkedCriteria; } errors.add("Certification criterion " + criterionErrorString + " was found so " + complimentaryCert + " is required but was not found."); } } } return errors; }
Source:
<code>public void waitItemCheckBoxToBeIndeterminate(String itemName) { <START> new WebDriverWait(seleniumWebDriver, 5) <END> .until( (ExpectedCondition<Boolean>) webDriver -> seleniumWebDriver .findElement( By.xpath( String.format(Locators.TREE_ITEM_CHECK_BOX + " .getAttribute("id") .endsWith("indeterminate")); }</code><technical_language>constant wait 5sec</technical_language>

Target:
public void waitItemCheckBoxToBeIndeterminate(String itemName) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( (ExpectedCondition<Boolean>) webDriver -> seleniumWebDriver .findElement( By.xpath( String.format(Locators.TREE_ITEM_CHECK_BOX + " .getAttribute("id") .endsWith("indeterminate")); }
Source:
<code>public void addTable(TableDescriptor tableDescriptor) { <START> this.addTableDescriptor(tableDescriptor); <END> }</code><technical_language>For consistency: please remove "this", add "this" other calls instance methods</technical_language>

Target:
public void addTable(TableDescriptor tableDescriptor) { Preconditions.checkState(!tableDescriptors.containsKey(tableDescriptor.getTableId()), String.format("add table descriptors multiple times with the same tableId: %s", tableDescriptor.getTableId())); tableDescriptors.put(tableDescriptor.getTableId(), tableDescriptor); }
Source:
<code>public ListBoxModel doFillServerNameItems() { ListBoxModel items = new ListBoxModel(); <START> ArrayList<GerritServer> servers = PluginImpl.getInstance().getServers(); <END> for (GerritServer s : servers) { items.add(s.getName()); } return items; }</code><technical_language>is a getServerNames method in GerritManagement. Moving PliginImpl need implement twice</technical_language>

Target:
public ListBoxModel doFillServerNameItems() { ListBoxModel items = new ListBoxModel(); LinkedList<String> serverNames = PluginImpl.getInstance().getServerNames(); for (String s : serverNames) { items.add(s); } return items; }
Source:
<code>public int countUsedAndDeletedObjectsReference(String bucketName, String checksum) throws SQLException { PreparedStatement p = null; <START> ResultSet result = null; <END> try { StringBuilder q = new StringBuilder("SELECT COUNT(*) FROM objects a, buckets b WHERE a.bucketId = b.bucketId"); q.append(" AND a.status IN (?,?)"); q.append(" AND bucketName=?"); q.append(" AND checksum=?"); p = connectionLocal.get().prepareStatement(q.toString()); p.setInt(1, Status.USED.getValue()); p.setInt(2, Status.DELETED.getValue()); p.setString(3, bucketName); p.setString(4, checksum); result = p.executeQuery(); if (result.next()) return result.getInt(1); else return 0; } finally { closeDbStuff(result, p); } }</code><technical_language>above, try-with-resources</technical_language>

Target:
public int countUsedAndDeletedObjectsReference(String bucketName, String checksum) throws SQLException { PreparedStatement p = null; ResultSet result = null; StringBuilder q = new StringBuilder("SELECT COUNT(*) FROM objects a, buckets b WHERE a.bucketId = b.bucketId"); q.append(" AND a.status IN (?,?)"); q.append(" AND bucketName=?"); q.append(" AND checksum=?"); try { p = connectionLocal.get().prepareStatement(q.toString()); p.setInt(1, Status.USED.getValue()); p.setInt(2, Status.DELETED.getValue()); p.setString(3, bucketName); p.setString(4, checksum); result = p.executeQuery(); if (result.next()) return result.getInt(1); else return 0; } finally { closeDbStuff(result, p); } }
Source:
<code>public void copyFileToContainer(MountableFile mountableLocalFile, String containerPath) { if (!isRunning() && !isCreated()) { <START> throw new IllegalStateException("opyFileToContainer can only be used with created / running container"); <END> } this.dockerClient .copyArchiveToContainerCmd(this.containerId) .withHostResource(mountableLocalFile.getResolvedPath()) .withRemotePath(containerPath) .exec(); }</code><technical_language>Typo in exception message</technical_language>

Target:
public void copyFileToContainer(MountableFile mountableLocalFile, String containerPath) { if (!isCreated()) { throw new IllegalStateException("copyFileToContainer can only be used with created / running container"); } this.dockerClient .copyArchiveToContainerCmd(this.containerId) .withHostResource(mountableLocalFile.getResolvedPath()) .withRemotePath(containerPath) .exec(); }
Source:
<code>public void writeData(FeatureCollectionResponse featureCollection, OutputStream output, Operation getFeature) throws IOException, ServiceException { BufferedWriter w = new BufferedWriter(new OutputStreamWriter(output, this.gs.getGlobal().getSettings().getCharset())); FeatureCollection<?, ?> fc = (FeatureCollection)featureCollection.getFeature().get(0); Object att; SimpleFeatureType ft = (SimpleFeatureType)((FeatureCollection)fc).getSchema(); w.write("FID,"); for(int i = 0; i < ft.getAttributeCount(); ++i) { AttributeDescriptor ad = ft.getDescriptor(i); w.write(this.prepCSVField(ad.getLocalName())); if (i < ft.getAttributeCount() - 1) { w.write(","); } } w.write("\r\n"); NumberFormat coordFormatter = NumberFormat.getInstance(Locale.US); coordFormatter.setMaximumFractionDigits(this.getInfo().getGeoServer().getSettings().getNumDecimals()); coordFormatter.setGroupingUsed(false); FeatureIterator i = ((FeatureCollection)fc).features(); try { <START> for(; i.hasNext(); w.write("\r\n")) { <END> Feature f = i.next(); w.write(this.prepCSVField(f.getIdentifier().getID())); w.write(","); for(int j = 0; j < ((SimpleFeature)f).getAttributeCount(); ++j) { att = ((SimpleFeature)f).getAttribute(j); if (att != null) { String value = formatToString(att, coordFormatter); w.write(this.prepCSVField(value)); } if (j < ((SimpleFeature)f).getAttributeCount() - 1) { w.write(","); } } } } finally { i.close(); } w.flush(); }</code><technical_language>while (i.hasNext) { ... w.write("\r\n"); } more readable</technical_language>

Target:
public void writeData(FeatureCollectionResponse featureCollection, OutputStream output, Operation getFeature) throws IOException, ServiceException { BufferedWriter w = new BufferedWriter(new OutputStreamWriter(output, this.gs.getGlobal().getSettings().getCharset())); FeatureCollection<?, ?> fc = (FeatureCollection)featureCollection.getFeature().get(0); Object att; SimpleFeatureType ft = (SimpleFeatureType)((FeatureCollection)fc).getSchema(); w.write("FID,"); for(int i = 0; i < ft.getAttributeCount(); ++i) { AttributeDescriptor ad = ft.getDescriptor(i); w.write(this.prepCSVField(ad.getLocalName())); if (i < ft.getAttributeCount() - 1) { w.write(","); } } w.write("\r\n"); NumberFormat coordFormatter = NumberFormat.getInstance(Locale.US); coordFormatter.setMaximumFractionDigits(this.getInfo().getGeoServer().getSettings().getNumDecimals()); coordFormatter.setGroupingUsed(false); FeatureIterator i = ((FeatureCollection)fc).features(); try { while (i.hasNext()) { Feature f = i.next(); w.write(this.prepCSVField(f.getIdentifier().getID())); w.write(","); for(int j = 0; j < ((SimpleFeature)f).getAttributeCount(); ++j) { att = ((SimpleFeature)f).getAttribute(j); if (att != null) { String value = formatToString(att, coordFormatter); w.write(this.prepCSVField(value)); } if (j < ((SimpleFeature)f).getAttributeCount() - 1) { w.write(","); } } w.write("\r\n"); } } finally { i.close(); } w.flush(); }
Source:
<code>public void dropRowRange(String tableId, String rowKeyPrefix) { DropRowRangeRequest.Builder dropRequestProtoBuilder = DropRowRangeRequest.newBuilder() .setName(instanceName.toTableNameStr(tableId)) <START> .setDeleteAllDataFromTable(true); <END> if(!Strings.isNullOrEmpty(rowKeyPrefix)){ dropRequestProtoBuilder .setDeleteAllDataFromTable(false) .setRowKeyPrefix(ByteString.copyFromUtf8(rowKeyPrefix)); } adminClient.dropRowRange(dropRequestProtoBuilder.build()); }</code><technical_language>Please remove setDeleteAllDataFromTable here, move else statement of if below</technical_language>

Target:
public void dropRowRange(String tableId, String rowKeyPrefix) { adminClient.dropRowRange(buildDropRowRangeRequest(tableId, rowKeyPrefix)); }
Source:
<code>protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushTemporaryExpression(); <START> for (String a : getContext().getTemplateParser().getBody()) { <END> addElement(processElement(a, member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushTemporaryExpression(); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }</code><technical_language>change s</technical_language>

Target:
protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushTemporaryExpression(); for (String s : getContext().getTemplateParser().getBody()) { addElement(processElement(s, member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushTemporaryExpression(); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }
Source:
<code>public void send(HttpServletResponse resp) throws IOException { output.setRequestId(Config.getRequestId()); resp.setStatus(getStatusCode()); resp.setContentType("application/json"); PrintWriter pw = resp.getWriter(); <START> pw.print(JsonUtils.toJson(output)); <END> }</code><technical_language>need send cookie here</technical_language>

Target:
public void send(HttpServletResponse resp) throws IOException { output.setRequestId(Config.getRequestId()); for (Cookie cookie : cookies) { resp.addCookie(cookie); } resp.setStatus(getStatusCode()); resp.setContentType("application/json"); PrintWriter pw = resp.getWriter(); pw.print(JsonUtils.toJson(output)); }
Source:
<code>private GitSubscriberParticipant getParticipant(GitSynchronizeDataSet data) { <START> <END> ISynchronizeManager synchronizeManager = TeamUI.getSynchronizeManager(); ISynchronizeParticipantReference[] participants = synchronizeManager .get(GitSubscriberParticipant.PARTICIPANT_NAME); GitSubscriberParticipant participant; if (participants.length == 0) { participant = createDefaultParticipant(data); } else { try { participant = (GitSubscriberParticipant) participants[0].getParticipant(); participant.reset(data); } catch (TeamException e1) { participant = createDefaultParticipant(data); } } return participant; }</code><technical_language>style nit: unnecessary blank line</technical_language>

Target:
private GitSubscriberParticipant getParticipant(GitSynchronizeDataSet data) { ISynchronizeManager synchronizeManager = TeamUI.getSynchronizeManager(); ISynchronizeParticipantReference[] participants = synchronizeManager .get(GitSubscriberParticipant.PARTICIPANT_NAME); GitSubscriberParticipant participant; if (participants.length == 0) { participant = createDefaultParticipant(data); } else { try { participant = (GitSubscriberParticipant) participants[0].getParticipant(); participant.reset(data); } catch (TeamException e) { participant = createDefaultParticipant(data); } } return participant; }
Source:
<code>public Response clearCache() { Response response = null; try { CacheConfiguration ehConfig = new CacheConfiguration() .name(cacheName) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU) .persistence(new PersistenceConfiguration() .strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP)) .clearOnFlush(true); Configuration managerConfig = new Configuration() .diskStore(new DiskStoreConfiguration().path(cacheLocation)) .dynamicConfig(false) .cache(ehConfig); CacheManager cacheManager = CacheManager.create(managerConfig); Ehcache ehcache = cacheManager.getEhcache(cacheName); if (ehcache != null) { ehcache.flush(); ehcache.removeAll(); response = Response.ok().build(); } else { <START> response = Response.serverError().entity("Error location cache to clear").build(); <END> } } catch (Exception e) { log.error("Unable to clear cache", e); response = Response.serverError().entity("Error location cache to clear").build(); } return response; }</code><technical_language>this error mean</technical_language>

Target:
public Response clearCache() { Response response = null; try { CacheConfiguration ehConfig = new CacheConfiguration() .name(cacheName) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU) .persistence(new PersistenceConfiguration() .strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP)) .clearOnFlush(true); Configuration managerConfig = new Configuration() .diskStore(new DiskStoreConfiguration().path(cacheLocation)) .dynamicConfig(false) .cache(ehConfig); CacheManager cacheManager = CacheManager.create(managerConfig); Ehcache ehcache = cacheManager.getEhcache(cacheName); if (ehcache != null) { ehcache.flush(); ehcache.removeAll(); response = Response.ok().build(); } else { response = Response.serverError().entity("Error locating cache to clear").build(); } } catch (Exception e) { log.error("Unable to clear cache", e); response = Response.serverError().entity("Unable to clear cache").build(); } return response; }
Source:
<code>void shutdown() { logger.info("OperationController is shutting down"); boolean cleanShutdown = false; try { if (shutDownLatch.await(SHUTDOWN_WAIT_MS, TimeUnit.MILLISECONDS)) { cleanShutdown = true; } } catch (InterruptedException e) { <START> logger.trace("Exception while shuttind down"); <END> } finally { if (!cleanShutdown) { logger.error("RequestResponseHandler did not shut down gracefully, forcing shut down"); } } selector.close(); }</code><technical_language>typo "shutting down" This error add exception logger.error("message", e)</technical_language>

Target:
void shutdown() { logger.info("OperationController is shutting down"); try { if (shutDownLatch.await(SHUTDOWN_WAIT_MS, TimeUnit.MILLISECONDS)) { logger.error("RequestResponseHandler thread did not shut down gracefully, forcing shut down"); } } catch (InterruptedException e) { logger.error("Exception while shutting down, forcing shutdown", e); } selector.close(); }
Source:
<code>private ApiResponseSet addonToSet(AddOn ao) { Map<String, String> map = new HashMap<>(); <START> map.put("id", String.valueOf(ao.getId())); <END> map.put("name", String.valueOf(ao.getName())); map.put("author", String.valueOf(ao.getAuthor())); map.put("changes", String.valueOf(ao.getChanges())); map.put("description", String.valueOf(ao.getDescription())); map.put("hash", String.valueOf(ObjectUtils.toString(ao.getHash()))); map.put("info", String.valueOf(ObjectUtils.toString(ao.getInfo()))); map.put("sizeInBytes", String.valueOf(ao.getSize())); map.put("status", String.valueOf(ao.getStatus().toString())); map.put("url", String.valueOf(ObjectUtils.toString(ao.getUrl()))); Version version = ao.getVersion(); if (version != null) { map.put("version", String.valueOf(ao.getVersion().toString())); } return new ApiResponseSet("addon", map); }</code><technical_language>for size field String.valueOf() calls removed, needed</technical_language>

Target:
private ApiResponseSet addonToSet(AddOn ao) { Map<String, String> map = new HashMap<>(); map.put("id", ao.getId()); map.put("name", ao.getName()); map.put("author", ao.getAuthor()); map.put("changes", ao.getChanges()); map.put("description", ao.getDescription()); map.put("hash", ObjectUtils.toString(ao.getHash())); map.put("infoUrl", ObjectUtils.toString(ao.getInfo())); map.put("sizeInBytes", String.valueOf(ao.getSize())); map.put("status", ao.getStatus().toString()); map.put("url", ObjectUtils.toString(ao.getUrl())); map.put("fileVersion", String.valueOf(ao.getFileVersion())); map.put("version", ObjectUtils.toString(ao.getVersion())); return new ApiResponseSet("addon", map); }
Source:
<code>public void testImportVMFromConfigurationXMLCouldNotGetParsed() { OvfEntityData ovfEntity = getOvfEntityData(); ovfEntity.setOvfData("This is not a valid XML"); initCommand(ovfEntity); when(unregisteredOVFDataDao.getByEntityIdAndStorageDomain(vmId, storageDomainId)).thenReturn(ovfEntity); assertFalse(cmd.canDoAction()); <START> Assert.assertTrue(cmd.getReturnValue() <END> .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED.toString())); }</code><technical_language>remove 'Assert.' (there's a static import)</technical_language>

Target:
public void testImportVMFromConfigurationXMLCouldNotGetParsed() { OvfEntityData ovfEntity = getOvfEntityData(); ovfEntity.setOvfData("This is not a valid XML"); initCommand(ovfEntity); when(unregisteredOVFDataDao.getByEntityIdAndStorageDomain(vmId, storageDomainId)).thenReturn(ovfEntity); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED.toString())); }
Source:
<code>public MainPresenter(MainActivity mainActivity, DatabaseHandler databaseHandler) { db = databaseHandler; Log.i("msg::", "initiated db object"); if (db.getUser(1) == null) { mainActivity.startHelloActivity(); } else { mainActivity.getLocaleHelper().updateLanguage(mainActivity, <START> db.getUser(1).getPreferred_language()); <END> } }</code><technical_language>code in Application.onCreate(). do need here</technical_language>

Target:
public MainPresenter(MainActivity mainActivity, DatabaseHandler databaseHandler) { dB = databaseHandler; Log.i("msg::", "initiated dB object"); if (dB.getUser(1) == null) { mainActivity.startHelloActivity(); } else { mainActivity.getLocaleHelper().updateLanguage(mainActivity, dB.getUser(1).getPreferred_language()); } }
Source:
<code>private void commitFiles() { projectExplorer.selectItem(PROJECT_NAME); <START> menu.runCommand(TestMenuCommandsConstants.Git.GIT, TestMenuCommandsConstants.Git.COMMIT); <END> git.waitAndRunCommit(COMMIT_MSG); git.waitGitStatusBarWithMess(TestGitConstants.COMMIT_MESSAGE_SUCCESS); events.clickEventLogBtn(); events.waitExpectedMessage(TestGitConstants.COMMIT_MESSAGE_SUCCESS); }</code><technical_language>Please, divide operations identical page objects, empty rows, improve readability</technical_language>

Target:
private void commitFiles() { projectExplorer.selectItem(PROJECT_NAME); menu.runCommand(TestMenuCommandsConstants.Git.GIT, TestMenuCommandsConstants.Git.COMMIT); git.waitAndRunCommit(COMMIT_MSG); git.waitGitStatusBarWithMess(TestGitConstants.COMMIT_MESSAGE_SUCCESS); eventsPanel.clickEventLogBtn(); eventsPanel.waitExpectedMessage(TestGitConstants.COMMIT_MESSAGE_SUCCESS); }
Source:
<code><START> public void testFloatingPointCalcChunkPos() { <END> org.joml.Vector3i temp = new org.joml.Vector3i(); assertTrue(ChunkMath.calcChunkPos(31.9f, 64.1f, 32.5f, temp).equals(0, 1, 1), temp.toString()); assertTrue(ChunkMath.calcChunkPos(32.9f, 63.9f, 32.9f, temp).equals(1, 0, 1), temp.toString()); assertTrue(ChunkMath.calcChunkPos(31.3f, 63.9f, 31.9f, temp).equals(0, 0, 0), temp.toString()); assertTrue(ChunkMath.calcChunkPos(31.6f, 64.5f, 32.1f, temp).equals(0, 1, 1), temp.toString()); }</code><technical_language>some exactly-half, over-half, under-half, good. Throw in test some negative coordinates, if round-towards-zero round-towards -infinity. be... I guess x -0.1 is in chunk -1, x -63.9 x: -64 -64.1 chunk -2? bah, fencepost errors messing me. I confusing myself, I draw more diagrams</technical_language>

Target:
public void testFloatingPointCalcChunkPos() { org.joml.Vector3i temp = new org.joml.Vector3i(); assertTrue(ChunkMath.calcChunkPos(31.9f, 64.1f, 32.5f, temp).equals(0, 1, 1), temp.toString()); assertTrue(ChunkMath.calcChunkPos(32.9f, 63.9f, 32.9f, temp).equals(1, 0, 1), temp.toString()); assertTrue(ChunkMath.calcChunkPos(31.3f, 63.9f, 31.9f, temp).equals(0, 0, 0), temp.toString()); assertTrue(ChunkMath.calcChunkPos(31.6f, 64.5f, 32.1f, temp).equals(0, 1, 1), temp.toString()); assertTrue(ChunkMath.calcChunkPos(.1f, -.2f, -.8f, temp).equals(0, -1, -1), temp.toString()); assertTrue(ChunkMath.calcChunkPos(-.1f, -.99f, 2f, temp).equals(-1, -1, 0), temp.toString()); }
Source:
<code>public void getExecutionDurationPercentilesTest() { NoThreadSchedulerStatisticTracker scheduler = new NoThreadSchedulerStatisticTracker(); assertEquals(0, scheduler.getExecutionDurationPercentiles(50).get(50.), 0); scheduler.execute(new ClockUpdateRunnable()); scheduler.tick(null); assertEquals(1, scheduler.getExecutionDurationPercentiles(50).get(50.), 1); scheduler.execute(new ClockUpdateRunnable()); scheduler.execute(new ClockUpdateRunnable()); scheduler.execute(new ClockUpdateRunnable()); scheduler.execute(new ClockUpdateRunnable(DELAY_TIME)); scheduler.tick(null); assertEquals(1, scheduler.getExecutionDurationPercentiles(75).get(75.), 1); <START> System.out.println(scheduler.getExecutionDurationPercentiles(90).get(90.)); <END> assertTrue(scheduler.getExecutionDurationPercentiles(90).get(90.) >= (DELAY_TIME-ALLOWED_VARIANCE)); }</code><technical_language>good this stray System.out.println</technical_language>

Target:
public void getExecutionDurationPercentilesTest() { NoThreadSchedulerStatisticTracker scheduler = new NoThreadSchedulerStatisticTracker(); assertEquals(0, scheduler.getExecutionDurationPercentiles(50).get(50.), 0); scheduler.execute(new ClockUpdateRunnable()); scheduler.tick(null); assertEquals(1, scheduler.getExecutionDurationPercentiles(50).get(50.), 1); scheduler.execute(new ClockUpdateRunnable()); scheduler.execute(new ClockUpdateRunnable()); scheduler.execute(new ClockUpdateRunnable()); scheduler.execute(new ClockUpdateRunnable(DELAY_TIME)); scheduler.tick(null); assertEquals(1, scheduler.getExecutionDurationPercentiles(75).get(75.), 1); assertTrue(scheduler.getExecutionDurationPercentiles(90).get(90.) >= (DELAY_TIME-ALLOWED_VARIANCE)); }
Source:
<code>public void setup() throws InvalidSyntaxException { bundleContext = mock(BundleContext.class); transformerLocator = new TransformerLocatorTest(bundleContext); serviceMap = new HashMap<>(); when(bundleContext.getServiceReferences(isA(Class.class), anyString())) .thenAnswer( (Answer<Collection<ServiceReference>>) invocationOnMock -> { Class<?> clazz = (Class<?>) invocationOnMock.getArguments()[0]; String filter = (String) invocationOnMock.getArguments()[1]; if (filter != null) { Filter f = FrameworkUtil.createFilter(filter); return serviceMap .get(clazz) .stream() .filter(f::match) .collect(Collectors.toList()); } <START> if (serviceMap.containsKey(clazz)) { <END> return serviceMap.get(clazz); } return null; }); }</code><technical_language>If filter is null able return serviceMap.get(clazz) return null if mapping</technical_language>

Target:
public void setup() throws InvalidSyntaxException { bundleContext = mock(BundleContext.class); transformerLocator = new TransformerLocatorTest(bundleContext); serviceMap = new HashMap<>(); when(bundleContext.getServiceReferences(isA(Class.class), anyString())) .thenAnswer( (Answer<Collection<ServiceReference>>) invocationOnMock -> { Class<?> clazz = (Class<?>) invocationOnMock.getArguments()[0]; String filter = (String) invocationOnMock.getArguments()[1]; if (filter != null) { Filter f = FrameworkUtil.createFilter(filter); return serviceMap .get(clazz) .stream() .filter(f::match) .collect(Collectors.toList()); } return serviceMap.get(clazz); }); }
Source:
<code>public KeyStore loadKeyStore() throws IOException, GeneralSecurityException { KeyStore ks = keyStoreInstance(); <START> InputStream inputStream = null; <END> try { inputStream = new FileInputStream(new File(keyStorePath)); ks.load(inputStream, passwordStringToCharArray(keyStorePassword)); return ks; } finally { forceClose(inputStream); } }</code><technical_language>try-with-resources now. I this is a refactoring this opportunity clean code</technical_language>

Target:
public KeyStore loadKeyStore() throws IOException, GeneralSecurityException { try (InputStream inputStream = new FileInputStream(new File(keyStorePath))) { KeyStore ks = keyStoreInstance(); ks.load(inputStream, passwordStringToCharArray(keyStorePassword)); return ks; } }
Source:
<code>public LeanNode add(long nanos, FrameInfo child, boolean last) { data.add(nanos, false); return childMap.compute( child, (k, v) -> v == null ? (last ? new LeanNode(child, nanos, this) : new LeanNode(child, this)) : (last ? v.addSelf(nanos) : <START> v)); <END> }</code><technical_language>This part is a complex... I simplify this logic description this part. - create child LeanNode if childMap absent - addSelf if code turn code snipped if correct... public LeanNode add(long nanos, FrameInfo child, boolean last) { // Non-self add, updates total time sample count only. data.add(nanos, false); LeanNode childNode = childMap.computeIfAbsent(child, -> new LeanNode(k, this)); if (last) { childNode.addSelf(nanos); } return childNode; } do think</technical_language>

Target:
public LeanNode add(long nanos, FrameInfo child, boolean last) { data.add(nanos, false); LeanNode childNode = childMap.computeIfAbsent(child, k -> new LeanNode(k, this)); if (last) { childNode.addSelf(nanos); } return childNode; }
Source:
<code>private static void initApiToMongoDocNameMap() { apiToMongoDocNameMap = new HashMap<>(); apiToMongoDocNameMap.put("sourceEntries", "files"); apiToMongoDocNameMap.put("sourceEntries.statistics", "st"); <START> apiToMongoDocNameMap.put("annotation.statistics", "annot"); <END> }</code><technical_language>"annotation", nested "statistics"</technical_language>

Target:
private static Map<String, String> initApiToMongoDocNameMap() { Map<String, String> map = new HashMap<>(); map.put("sourceEntries", "files"); map.put("sourceEntries.statistics", "st"); map.put("annotation", "annot"); map.put("sourceEntries.attributes", "files.attrs"); return map; }
Source:
<code>public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { RunScriptByPathAction action = new RunScriptByPathAction(); String path = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, ""); action.init(PlatformUI.getWorkbench().getActiveWorkbenchWindow(), path); String userName = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_NAME_ATTR, ""); <START> ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.SCP_USER, userName); <END> String password = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_PASS_ATTR, ""); ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.SCP_PASSWORD, password); boolean runAsCurrentUser = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.CURRENT_USER_ATTR, true); boolean runLocal = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.LOCAL_HOST_ATTR, true); action.setLocalScript(runLocal && runAsCurrentUser); String hostName = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.HOST_NAME_ATTR, "localhost"); ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.HOST_NAME, hostName); action.run(); }</code><technical_language>Please extract preference store local variable</technical_language>

Target:
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { RunScriptByPathAction action = new RunScriptByPathAction(); IPreferenceStore preferenceStore = ConsoleLogPlugin.getDefault().getPreferenceStore(); String path = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, ""); action.init(PlatformUI.getWorkbench().getActiveWorkbenchWindow(), path); String userName = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_NAME_ATTR, ""); preferenceStore.setValue(ConsoleLogPreferenceConstants.SCP_USER, userName); String password = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_PASS_ATTR, ""); preferenceStore.setValue(ConsoleLogPreferenceConstants.SCP_PASSWORD, password); boolean runAsCurrentUser = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.CURRENT_USER_ATTR, true); boolean runLocal = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.LOCAL_HOST_ATTR, true); action.setLocalScript(runLocal && runAsCurrentUser); String hostName = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.HOST_NAME_ATTR, "localhost"); preferenceStore.setValue(ConsoleLogPreferenceConstants.HOST_NAME, hostName); action.run(); }
Source:
<code>private List<InterpreterCompletion> callCompletion(CompletionRequest req) throws LivyException { List<InterpreterCompletion> candidates = new ArrayList<>(); try { CompletionResponse resp = CompletionResponse.fromJson( callRestAPI("/sessions/" + sessionInfo.id + "/completion", "POST", req.toJson())); for (String candidate : resp.candidates) { candidates.add(new InterpreterCompletion(candidate, candidate, StringUtils.EMPTY)); } } catch (APINotFoundException e) { <START> logger.debug("completion api seems not to be availabele. (available from livy 0.5)", e); <END> } return candidates; }</code><technical_language>typo. availabele</technical_language>

Target:
private List<InterpreterCompletion> callCompletion(CompletionRequest req) throws LivyException { List<InterpreterCompletion> candidates = new ArrayList<>(); try { CompletionResponse resp = CompletionResponse.fromJson( callRestAPI("/sessions/" + sessionInfo.id + "/completion", "POST", req.toJson())); for (String candidate : resp.candidates) { candidates.add(new InterpreterCompletion(candidate, candidate, StringUtils.EMPTY)); } } catch (APINotFoundException e) { logger.debug("completion api seems not to be available. (available from livy 0.5)", e); } return candidates; }
Source:
<code>public void drawText(CharSequence text, int x, int y, int maxWidth, int lineHeight, Color color, TextAlign align) { if (isDisposed()) throw new ObjectDisposedException(); Rectangle bounds = measureText(text, lineHeight); <START> bounds.width = maxWidth; <END> mAwtGraphics2D.clipRect(x, y, bounds.width, bounds.height); final TextLayout layout = new TextLayout(text.toString(), mAwtTextFont, mAwtFontRenderContext); mAwtGraphics2D.setColor(convertToAwtColor(color)); layout.draw(mAwtGraphics2D, x, y); mAwtGraphics2D.clipRect(0, 0, mImage.getWidth(), mImage.getHeight()); }</code><technical_language>If maxWidth is -1, limitation</technical_language>

Target:
public void drawText(CharSequence text, int x, int y, int maxWidth, int lineHeight, Color color, TextAlign align) { if (isDisposed()) throw new ObjectDisposedException(); if (maxWidth != -1) { final Rectangle bounds = measureText(text, lineHeight); bounds.width = maxWidth; mAwtGraphics2D.clipRect(x, y, bounds.width, bounds.height); } final TextLayout layout = new TextLayout(text.toString(), mAwtTextFont, mAwtFontRenderContext); mAwtGraphics2D.setColor(convertToAwtColor(color)); layout.draw(mAwtGraphics2D, x, y); if (maxWidth != -1) { mAwtGraphics2D.clipRect(0, 0, mImage.getWidth(), mImage.getHeight()); } }
Source:
<code>public String getHowTo() { <START> return "This actionlet allows you to add a comment on the workflow task."; <END> }</code><technical_language>i18n</technical_language>

Target:
public String getHowTo() { String name = "This actionlet allows you to add a comment on the workflow task."; try { name = LanguageUtil.get("Workflow-Comment-on-workflow-howto"); } catch (LanguageException e) { name = "This actionlet allows you to add a comment on the workflow task."; } return name; }
Source:
<code>public void onEvent(InstanceStateEvent event) { if ((event.getType() == OOM) || (event.getType() == DIE)) { try { final Instance machine = getMachine(event.getMachineId()); String message = "Machine is destroyed."; if (event.getType() == OOM) { message = message + "The processes in this machine need more RAM. This machine started with " + machine.getMemorySize() + "MB. Create a new machine configuration that allocates additional RAM or increase " + "the workspace RAM limit in the user dashboard."; } cleanupOnDestroy(machine, message); } catch (NotFoundException | MachineException ignore) { <START> } <END> } }</code><technical_language>Log.warn</technical_language>

Target:
public void onEvent(InstanceStateEvent event) { if ((event.getType() == OOM) || (event.getType() == DIE)) { try { final Instance machine = getMachine(event.getMachineId()); String message = "Machine is destroyed."; if (event.getType() == OOM) { message = message + "The processes in this machine need more RAM. This machine started with " + machine.getMemorySize() + "MB. Create a new machine configuration that allocates additional RAM or increase " + "the workspace RAM limit in the user dashboard."; } cleanupOnDestroy(machine, message); } catch (NotFoundException | MachineException e) { LOG.debug(e.getLocalizedMessage(), e); } } }
Source:
<code>public AvoidReassigningLoopVariablesRule() { definePropertyDescriptor(FOREACH_REASSIGN); definePropertyDescriptor(FOR_REASSIGN); <START> } <END></code><technical_language>Rule store state visits of AST nodes (in fact in special case visit node type), rule chain get a big performance boost. do is add a call addRuleChainVisit(ASTLocalVariableDeclaration.class); in constructor</technical_language>

Target:
public AvoidReassigningLoopVariablesRule() { definePropertyDescriptor(FOREACH_REASSIGN); definePropertyDescriptor(FOR_REASSIGN); addRuleChainVisit(ASTLocalVariableDeclaration.class); }
Source:
<code>Options(String[] args) throws CmdLineException { CmdLineParser parser = new CmdLineParser(this); parser.parseArgument(args); if (filesToConvert.size() != 0 && sourcesManifest != null) { throw new CmdLineException( parser, "Don't specify a sources manifest file and source files at the same time."); } if (arguments.size() != 0 && dependenciesManifest != null) { throw new CmdLineException( parser, <START> "Don't specify a dependencies manifest file and dependency files at the same time."); <END> } if (sourcesManifest != null) { try { filesToConvert = Files.readAllLines(Paths.get(sourcesManifest), UTF_8); } catch (IOException e) { throw new CmdLineException( parser, "sources manifest file " + sourcesManifest + " not found.", e); } } if (dependenciesManifest == null) { srcFiles.addAll(arguments); } else { try { srcFiles.addAll(Files.readAllLines(Paths.get(dependenciesManifest), UTF_8)); } catch (IOException e) { throw new CmdLineException( parser, "dependencies manifest file " + dependenciesManifest + " not found.", e); } } srcFiles.addAll(filesToConvert); if (srcFiles.isEmpty()) { throw new CmdLineException(parser, "No files were given"); } try { externsMap = getExternsMap(); } catch (IOException e) { throw new CmdLineException(parser, "externs file " + externsMapFile + " not found.", e); } }</code><technical_language>"dependency files arguments"</technical_language>

Target:
Options(String[] args) throws CmdLineException { CmdLineParser parser = new CmdLineParser(this); parser.parseArgument(args); if (filesToConvert.size() != 0 && sourcesManifest != null) { throw new CmdLineException( parser, "Don't specify a sources manifest file and source files (\"--convert\") at the same time."); } if (arguments.size() != 0 && dependenciesManifest != null) { throw new CmdLineException( parser, "Don't specify a dependencies manifest file and dependency files as arguments at the same time."); } if (sourcesManifest != null) { try { filesToConvert = Files.readAllLines(Paths.get(sourcesManifest), UTF_8); } catch (IOException e) { throw new CmdLineException( parser, "sources manifest file " + sourcesManifest + " not found.", e); } } if (dependenciesManifest == null) { srcFiles.addAll(arguments); } else { try { srcFiles.addAll(Files.readAllLines(Paths.get(dependenciesManifest), UTF_8)); } catch (IOException e) { throw new CmdLineException( parser, "dependencies manifest file " + dependenciesManifest + " not found.", e); } } srcFiles.addAll(filesToConvert); if (srcFiles.isEmpty()) { throw new CmdLineException(parser, "No files were given"); } try { externsMap = getExternsMap(); } catch (IOException e) { throw new CmdLineException(parser, "externs file " + externsMapFile + " not found.", e); } }
Source:
<code>private boolean formingCyclicGraph(OnmsAlarm situation, OnmsAlarm relatedAlarm) { if (situation.getReductionKey().equals(relatedAlarm.getReductionKey())) { <START> return true; <END> } if (!relatedAlarm.getRelatedAlarms().isEmpty()) { for (OnmsAlarm alarm : relatedAlarm.getRelatedAlarms()) { boolean matched = formingCyclicGraph(situation, alarm); if (!matched) { continue; } return matched; } } return false; }</code><technical_language>This method simplified as: private boolean formingCyclicGraph(OnmsAlarm situation, OnmsAlarm relatedAlarm) { return situation.getReductionKey().equals(relatedAlarm.getReductionKey()) || relatedAlarm.getRelatedAlarms() .stream().anyMatch(ra -> situation.getReductionKey().equals(ra.getReductionKey())); }</technical_language>

Target:
private boolean formingCyclicGraph(OnmsAlarm situation, OnmsAlarm relatedAlarm) { return situation.getReductionKey().equals(relatedAlarm.getReductionKey()) || relatedAlarm.getRelatedAlarms().stream().anyMatch(ra -> formingCyclicGraph(situation, ra)); }
Source:
<code>public boolean performNextOperation(int completedChildCount) { switch(getParameters().getImportPhase()) { case CREATE_DISKS: getParameters().setImportPhase(Phase.CONVERT); if (getParameters().getProxyHostId() == null) { getParameters().setProxyHostId(selectProxyHost()); } break; case CONVERT: if (EnumSet.of(OriginType.KVM, OriginType.OVIRT).contains(getVm().getOrigin())) { <START> deleteV2VJob(); <END> return false; } getParameters().setImportPhase(Phase.POST_CONVERT); break; case POST_CONVERT: return false; default: } persistCommandIfNeeded(); executeNextOperation(); return true; }</code><technical_language>work, aligned common of performNextOperation executeNextOperation methods. performNextOperation - return true if operation execute next. preparations updating parameters executing next operation. executeNextOperation - relevant operation executed method. please remove lines 454-457 change POST_CONVERT part in executeNextOperation in a deleteV2VJob called for kvm updateVm called otherwise</technical_language>

Target:
public boolean performNextOperation(int completedChildCount) { switch(getParameters().getImportPhase()) { case CREATE_DISKS: getParameters().setImportPhase(Phase.CONVERT); if (getParameters().getProxyHostId() == null) { getParameters().setProxyHostId(selectProxyHost()); } break; case CONVERT: if (EnumSet.of(OriginType.OVIRT).contains(getVm().getOrigin())) { return false; } getParameters().setImportPhase(Phase.POST_CONVERT); break; case POST_CONVERT: return false; default: } persistCommandIfNeeded(); executeNextOperation(); return true; }
Source:
<code>static void registerMethod(MetricsRegistry metricsRegistry, Object osBean, String methodName, String name) { if (OperatingSystemMXBeanSupport.GET_FREE_PHYSICAL_MEMORY_SIZE_DISABLED <START> || methodName.equals("getFreePhysicalMemorySize")) { <END> metricsRegistry.registerStaticProbe(osBean, name, MANDATORY, (LongProbeFunction<Object>) source -> -1); } else { registerMethod(metricsRegistry, osBean, methodName, name, 1); } }</code><technical_language>read && instead of ||</technical_language>

Target:
static void registerMethod(MetricsRegistry metricsRegistry, Object osBean, String methodName, String name) { if (OperatingSystemMXBeanSupport.GET_FREE_PHYSICAL_MEMORY_SIZE_DISABLED && methodName.equals("getFreePhysicalMemorySize")) { metricsRegistry.registerStaticProbe(osBean, name, MANDATORY, (LongProbeFunction<Object>) source -> -1); } else { registerMethod(metricsRegistry, osBean, methodName, name, 1); } }
Source:
<code>public static Metric<Double> nullsFraction(String columnName) { return new Metric<Double>() { @Override public Optional<Double> getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext) { return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getNullsFraction()); } @Override public Optional<Double> getValueFromAggregationQueryResult(Object value) { return Optional.of(((Number) value).doubleValue()); } @Override public String getComputingAggregationSql() { return "(count(*) filter(where " + columnName + " is null)) / cast(count(*) as double)"; <START> } <END> @Override public String getName() { return "NULLS_FRACTION(" + columnName + ")"; } }; }</code><technical_language>filter upper case</technical_language>

Target:
public static Metric nullsFraction(String columnName) { return new Metric() { @Override public OptionalDouble getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext) { return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getNullsFraction()); } @Override public OptionalDouble getValueFromAggregationQueryResult(Object value) { return OptionalDouble.of(((Number) value).doubleValue()); } @Override public String getComputingAggregationSql() { return "(count(*) filter(where " + columnName + " is null)) / cast(count(*) as double)"; } @Override public String toString() { return "NULLS_FRACTION(" + columnName + ")"; } }; }
Source:
<code>private boolean isAllowedToClone(Object value) { if(value == null){ System.out.print("null"); <START> } <END> return Objects.nonNull(value) && ((value instanceof String) || (classUtils.isPrimitiveClass(value.getClass()))); }</code><technical_language>This method needs enhance. I If if is true, code bellow is false. I System.out.print("null"); replaced some log</technical_language>

Target:
private boolean isAllowedToClone(Object value) { return Objects.nonNull(value) && ((value instanceof String) || (classUtils.isPrimitiveClass(value.getClass()))); }
Source:
<code>private void createSkipLine(int row, SkippedLine line, boolean isWholeFile) { FlowPanel p = new FlowPanel(); InlineLabel l1 = new InlineLabel(" " + PatchUtil.C.patchSkipRegionStart() + " "); InlineLabel l2 = new InlineLabel(" " + PatchUtil.C.patchSkipRegionEnd() + " "); Anchor all = new Anchor(String.valueOf(line.getSize())); all.addClickHandler(expandAllListener); all.setStyleName(Gerrit.RESOURCES.css().skipLine()); if (line.getSize() > 30 && isWholeFile) { Anchor b = new Anchor(PatchUtil.M.expandBefore(NUM_ROWS_TO_EXPAND), true); Anchor a = new Anchor(PatchUtil.M.expandAfter(NUM_ROWS_TO_EXPAND), true); b.addClickHandler(expandBeforeListener); a.addClickHandler(expandAfterListener); b.setStyleName(Gerrit.RESOURCES.css().skipLine()); a.setStyleName(Gerrit.RESOURCES.css().skipLine()); p.add(b); p.add(l1); p.add(all); p.add(l2); p.add(a); <START> } else if(isWholeFile) { <END> p.add(l1); p.add(all); p.add(l2); } else { p.add(l1); InlineLabel allLabel = new InlineLabel(" " + String.valueOf(line.getSize()) + " "); p.add(allLabel); p.add(l2);; } table.setWidget(row, 1, p); }</code><technical_language>nit: space if (</technical_language>

Target:
private void createSkipLine(int row, SkippedLine line, boolean isWholeFile) { FlowPanel p = new FlowPanel(); InlineLabel l1 = new InlineLabel(" " + PatchUtil.C.patchSkipRegionStart() + " "); InlineLabel l2 = new InlineLabel(" " + PatchUtil.C.patchSkipRegionEnd() + " "); Anchor all = new Anchor(String.valueOf(line.getSize())); all.addClickHandler(expandAllListener); all.setStyleName(Gerrit.RESOURCES.css().skipLine()); if (line.getSize() > 30 && isWholeFile) { Anchor b = new Anchor(PatchUtil.M.expandBefore(NUM_ROWS_TO_EXPAND), true); Anchor a = new Anchor(PatchUtil.M.expandAfter(NUM_ROWS_TO_EXPAND), true); b.addClickHandler(expandBeforeListener); a.addClickHandler(expandAfterListener); b.setStyleName(Gerrit.RESOURCES.css().skipLine()); a.setStyleName(Gerrit.RESOURCES.css().skipLine()); p.add(b); p.add(l1); p.add(all); p.add(l2); p.add(a); } else if (isWholeFile) { p.add(l1); p.add(all); p.add(l2); } else { p.add(l1); p.add(new InlineLabel(" " + line.getSize() + " ")); p.add(l2); } table.setWidget(row, 1, p); }
Source:
<code>public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); <START> return player != null && !player.discard(amount.calculate(game, source, this), false, source, game).isEmpty(); <END> }</code><technical_language>Missing randomDiscard param</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); return player != null && !player.discard(amount.calculate(game, source, this), randomDiscard, source, game).isEmpty(); }