auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void fetchVmsStatus(Guid storageDomainId, List<StorageOvfExtraData> storageExtraData, Map<String, Object> diskDescriptionMap) { Map<String, String> vmsStatus = (Map<String, String>) diskDescriptionMap.get(OvfInfoFileConstants.VmStatus); if (vmsStatus == null) { log.error("VMs status could not be fetched from metadata json file for storage id '{}'.", storageDomainId); } else { <START> for (Map.Entry<String, <END> String> entry : vmsStatus.entrySet()) { log.debug("VM '{}' fetched from metadata json file with status '{}' for storage domain id '{}.", entry.getKey(), entry.getValue(), storageDomainId); storageExtraData.add(new StorageOvfExtraData(storageDomainId, VdcObjectType.VM, storageDomainId, vmsStatus.get(entry.getKey()))); } } }</code><technical_language>suggestion: Map#forEach</technical_language>

Target:
private void fetchVmsStatus(Guid storageDomainId, List<StorageOvfExtraData> storageExtraData, Map<String, Object> diskDescriptionMap) { Map<String, String> vmsStatus = (Map<String, String>) diskDescriptionMap.get(OvfInfoFileConstants.VmStatus); if (vmsStatus == null) { log.error("VMs status could not be fetched from metadata json file for storage id '{}'.", storageDomainId); } else { for (Map.Entry<String, String> entry : vmsStatus.entrySet()) { log.debug("VM '{}' fetched from metadata json file with status '{}' for storage domain id '{}.", entry.getKey(), entry.getValue(), storageDomainId); storageExtraData.add(new StorageOvfExtraData(storageDomainId, VdcObjectType.VM, Guid.createGuidFromString(entry.getKey()), vmsStatus.get(entry.getKey()))); } } }
Source:
<code>public void testCreateProjectCheckGoodName() throws Exception{ String xmlFile = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<project>\n" + "<description></description>\n" + "<keepDependencies>false</keepDependencies>\n" + "<properties/>\n" + "<triggers/>\n" + "<concurrentBuild>false</concurrentBuild>\n" + "<builders/>\n" + "<publishers/>\n" + "<buildWrappers/>\n" + "</project>"; String[] illegalNames = {"ab\\c", "abc/", "ab/c", "", " ", " ", "..", ".", "?", "*", "6%", "x!", "-@", "#", "$", "^", "&", "|", "<", ">", "[", "]", ":", ";", "../.", null}; Jenkins j = Jenkins.getInstance(); int created = 0; for (String name : illegalNames){ try{ InputStream is = new ByteArrayInputStream(xmlFile.getBytes()); j.createProjectFromXML(name, is); created++; } catch (Failure e){ assertEquals(Failure.class, e.getClass()); } catch (IOException e){ <START> assertEquals(IOException.class, e.getClass()); <END> } } for (String name : illegalNames){ try{ j.createProject(FreeStyleProject.class, name); created++; } catch (Failure e){ assertEquals(Failure.class, e.getClass()); } catch (IOException e){ assertEquals(IOException.class, e.getClass()); } } assertEquals(0, created); }</code><technical_language>I if IOException is thrown test exception thrown fail. of calls fail exception thrown anyway</technical_language>

Target:
public void testCreateProjectCheckGoodName() throws Exception{ String xmlFile = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<project>\n" + "<description></description>\n" + "<keepDependencies>false</keepDependencies>\n" + "<properties/>\n" + "<triggers/>\n" + "<concurrentBuild>false</concurrentBuild>\n" + "<builders/>\n" + "<publishers/>\n" + "<buildWrappers/>\n" + "</project>"; String[] illegalNames = {"ab\\c", "abc/", "ab/c", "", " ", " ", "..", ".", "?", "*", "6%", "x!", "-@", "#", "$", "^", "&", "|", "<", ">", "[", "]", ":", ";", "../.", null}; Jenkins j = Jenkins.getInstance(); int created = 0; for (String name : illegalNames){ try{ InputStream is = new ByteArrayInputStream(xmlFile.getBytes()); j.createProjectFromXML(name, is); created++; } catch (IOException e){} } for (String name : illegalNames){ try{ j.createProject(FreeStyleProject.class, name); created++; } catch (IOException e){} } assertEquals(0, created); }
Source:
<code>public Timestamp getSessionCreatedTime(String key, String type) { Timestamp timestamp = null; if (!enablePersist) { return timestamp; } Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = jdbcPersistenceManager.getDBConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(SQL_SELECT_TIME_CREATED); preparedStatement.setString(1, key); preparedStatement.setString(2, type); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { timestamp = resultSet.getTimestamp(1); } if (preparedStatement != null) { <START> preparedStatement.close(); <END> } } catch (IdentityException e) { log.error("Error while getting session data", e); } catch (SQLException e) { log.error("Error while getting session data", e); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { log.error("Error while closing the stream", e); } } return timestamp; }</code><technical_language>close preparedStatement closed finally block</technical_language>

Target:
public Timestamp getSessionCreatedTime(String key, String type) { Timestamp timestamp = null; if (!enablePersist) { return timestamp; } Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = jdbcPersistenceManager.getDBConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(SQL_SELECT_TIME_CREATED); preparedStatement.setString(1, key); preparedStatement.setString(2, type); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { timestamp = resultSet.getTimestamp(1); } } catch (IdentityException e) { log.error("Error while getting session data", e); } catch (SQLException e) { log.error("Error while getting session data", e); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { log.error("Error while closing the stream", e); } } return timestamp; }
Source:
<code>public void foo() { Properties props = new Properties(); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session s = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username@gmail.com", "password"); <START> } <END> }); }</code><technical_language>This piece of code create Authenticator is duplicated 4 times, relevant test. test cases shorter easily differences them</technical_language>

Target:
public void foo() { Properties props = new Properties(); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }
Source:
<code>public void initializeDefaultPreferences() { IEclipsePreferences node = DefaultScope.INSTANCE .getNode(CodanCorePlugin.getDefault().getBundle().getSymbolicName()); <START> node.putBoolean(PreferenceConstants.P_RUN_ON_BUILD, true); <END> node.putBoolean(PreferenceConstants.P_RUN_IN_EDITOR, true); node.putBoolean(PreferenceConstants.P_USE_PARENT, true); }</code><technical_language>Setting this true initially effect codan builder is added property changes, BuildPropertyPage. impose a big change in behavior</technical_language>

Target:
public void initializeDefaultPreferences() { IEclipsePreferences node = DefaultScope.INSTANCE .getNode(CodanCorePlugin.getDefault().getBundle().getSymbolicName()); node.putBoolean(PreferenceConstants.P_RUN_ON_BUILD, false); node.putBoolean(PreferenceConstants.P_RUN_IN_EDITOR, true); node.putBoolean(PreferenceConstants.P_USE_PARENT, true); }
Source:
<code>public void readValues() { SML_File smlFile = null; do { clearValueCache(); if(connector == null){ <START> logger.error(this.toString() + " connector is not instantiated"); <END> break; } try { smlFile = connector.getMeterValues(); } catch(ConnectorException ex) { logger.error(this.toString() + ": Error during receive values from device: " + ex.getMessage()); break; } populateValueCache(smlFile); }while (false); }</code><technical_language>parametrised logging "logger.error("{} connector is instantiated", this.toString()) (valid for statements in classes)</technical_language>

Target:
public void readValues() { SML_File smlFile = null; do { clearValueCache(); if(connector == null){ logger.error("{}: connector is not instantiated", this.toString()); break; } try { smlFile = connector.getMeterValues(); } catch(Exception ex) { logger.error("{}: Error during receive values from device: {}", this.toString(), ex.getMessage()); break; } populateValueCache(smlFile); }while (false); }
Source:
<code>public void testStarted(Description description){ <START> Log.i("test started", description.getDisplayName()); <END> if(description.isTest()) { currentTest = new TestResults(description.getDisplayName()); } else { currentTest = null; } }</code><technical_language>Upper case T Test in log message</technical_language>

Target:
public void testStarted(Description description){ Log.i("Test started", description.getDisplayName()); if(description.isTest()) { currentTest = new TestResults(description.getDisplayName()); } else { currentTest = null; } }
Source:
<code>public String toString() { return "TaskSummary{" + "description='" + description + '\'' + ", status='" + status + '\'' + ", priority=" + priority + ", actualOwner='" + actualOwner + '\'' + ", createdBy='" + createdBy + '\'' + ", createdOn=" + createdOn + ", activationTime=" + activationTime + ", expirationTime=" + expirationTime + ", lastModificationDate=" + lastModificationDate + ", processInstanceId=" + processInstanceId + ", processInstanceCorrelationKey='" + processInstanceCorrelationKey + '\'' + ", processInstanceDescription='" + processInstanceDescription + '\'' + ", processId='" + processId + '\'' + <START> ", errorCount=" + errorCount + <END> ", deploymentId='" + deploymentId + '\'' + ", isForAdmin=" + isForAdmin + ", isLogOnly=" + isLogOnly + ", parentId=" + parentId + ", domainData=" + domainData + "} " + super.toString(); }</code><technical_language>need update toString in _errorCount_ included in parent _toString_ method</technical_language>

Target:
public String toString() { return "TaskSummary{" + "description='" + description + '\'' + ", status='" + status + '\'' + ", priority=" + priority + ", actualOwner='" + actualOwner + '\'' + ", createdBy='" + createdBy + '\'' + ", createdOn=" + createdOn + ", activationTime=" + activationTime + ", expirationTime=" + expirationTime + ", lastModificationDate=" + lastModificationDate + ", processInstanceId=" + processInstanceId + ", processInstanceCorrelationKey='" + processInstanceCorrelationKey + '\'' + ", processInstanceDescription='" + processInstanceDescription + '\'' + ", processId='" + processId + '\'' + ", deploymentId='" + deploymentId + '\'' + ", isForAdmin=" + isForAdmin + ", isLogOnly=" + isLogOnly + ", parentId=" + parentId + ", domainData=" + domainData + "} " + super.toString(); }
Source:
<code>public List<ExchangeDownloadStatus> refreshExchangeManager() { <START> LOG.info("force the exchangeManager to refresh: {}"); <END> ExchangeManagerUtil exUtil = new ExchangeManagerUtil(); return exUtil.forceRefreshExchanges(); }</code><technical_language>I need LOG.info any-more; LOG.debug removed</technical_language>

Target:
public List<ExchangeDownloadStatus> refreshExchangeManager() { ExchangeManagerUtil exUtil = new ExchangeManagerUtil(); return exUtil.forceRefreshExchanges(); }
Source:
<code>private String getUrl() throws CoreException { String urlString = null; IServer server = getServer(); if(server!=null && server.getServerState() == IServer.STATE_STARTED) { ModuleServer ms = getModuleServer(); if(ms!=null) { urlString = getWelcomePageURL(ms); } else { ServerExtendedProperties props = (ServerExtendedProperties)server.loadAdapter(ServerExtendedProperties.class, new NullProgressMonitor()); if( props != null ) { try { urlString = props.getWelcomePageUrl(); } catch (GetWelcomePageURLException e) { Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openWarning( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), <START> "No Welcome URL to Show", e.getMessage()); <END> } }); } } } } return urlString; }</code><technical_language>I action is called Show-in -> Web Browser, welcome page. welcome page terms legacy hidden. change this message more generic? URL for current selection" that</technical_language>

Target:
private String getUrl() throws CoreException { String urlString = null; IServer server = getServer(); if(server!=null && server.getServerState() == IServer.STATE_STARTED) { ModuleServer ms = getModuleServer(); if(ms!=null) { urlString = getWelcomePageURL(ms); } else { ServerExtendedProperties props = (ServerExtendedProperties)server.loadAdapter(ServerExtendedProperties.class, new NullProgressMonitor()); if( props != null ) { try { urlString = props.getWelcomePageUrl(); } catch (GetWelcomePageURLException e) { if(e.getCause() != null) { JBossServerUIPlugin.log(new Status(IStatus.WARNING, JBossServerUIPlugin.PLUGIN_ID, "No URL found for current selection '" + server.getName() + "'.")); } Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openWarning( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "No URL found for current selection", e.getMessage()); } }); } } } } return urlString; }
Source:
<code>private void transitionToMain() { <START> Thread.dumpStack(); <END> Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); }</code><technical_language>& forget this</technical_language>

Target:
private void transitionToMain() { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); }
Source:
<code>public void testRetainUntilDateSaved() throws InterruptedException { <START> RetentionRule testRule = createManualImmediateRuleMillis(100L); <END> file = service.attachRule(file, testRule, session); Calendar original = file.getRetainUntil(); awaitRetentionExpiration(1000L); Record record = session.getDocument(file.getRef()).getAdapter(Record.class); Calendar saved = record.getSavedRetainUntil(); assertNotNull(saved); assertEquals(original.getTimeInMillis(), saved.getTimeInMillis()); }</code><technical_language>throw InterruptedException is needed</technical_language>

Target:
public void testRetainUntilDateSaved() throws InterruptedException { RetentionRule testRule = createManualImmediateRuleMillis(100); file = service.attachRule(file, testRule, session); Calendar original = file.getRetainUntil(); awaitRetentionExpiration(1000); Record record = session.getDocument(file.getRef()).getAdapter(Record.class); Calendar saved = record.getSavedRetainUntil(); assertNotNull(saved); assertEquals(original.getTimeInMillis(), saved.getTimeInMillis()); }
Source:
<code>cfg != null ? cfg.getBoolean(ENABLE_AST_RBE_PNAME, ENABLE_AST_RBE_DEFAULT) : ENABLE_AST_RBE_DEFAULT; private static final long SS_THRESHOLD = 30; private final RemoteBitrateObserver observer; private int minBitrateBps = -1; private int astExtensionID = -1; private int tccExtensionID = -1; private boolean supportsRemb = false; private boolean usingAbsoluteSendTime = false; private int packetsSinceAbsoluteSendTime = 0; private RemoteBitrateEstimator rbe; private final DiagnosticContextProvider diagnosticContextProvider; public RemoteBitrateEstimatorWrapper( RemoteBitrateObserver observer, DiagnosticContextProvider diagnosticContextProvider) { this.observer = observer; this.rbe = new RemoteBitrateEstimatorSingleStream( observer, diagnosticContextProvider); <START> this.diagnosticContextProvider = diagnosticContextProvider; <END> }</code><technical_language>move requireNonNull</technical_language>

Target:
cfg != null ? cfg.getBoolean(ENABLE_AST_RBE_PNAME, ENABLE_AST_RBE_DEFAULT) : ENABLE_AST_RBE_DEFAULT; private static final long SS_THRESHOLD = 30; private final RemoteBitrateObserver observer; private int minBitrateBps = -1; private int astExtensionID = -1; private int tccExtensionID = -1; private boolean supportsRemb = false; private boolean usingAbsoluteSendTime = false; private int packetsSinceAbsoluteSendTime = 0; private RemoteBitrateEstimator rbe; private final DiagnosticContext diagnosticContext; public RemoteBitrateEstimatorWrapper( RemoteBitrateObserver observer, @NotNull DiagnosticContext diagnosticContext) { this.observer = observer; this.diagnosticContext = diagnosticContext; this.rbe = new RemoteBitrateEstimatorSingleStream( observer, diagnosticContext); }
Source:
<code><START> private JobEventMonitor removeJobEvent(JobId id, SchedulerEvent event) { <END> JobEventMonitor tmp = new JobEventMonitor(event, id); if (jobsEvents.containsKey(id) && jobsEvents.get(id).contains(tmp)) { return jobsEvents.get(id).remove((jobsEvents.get(id).indexOf(tmp))); } else return null; }</code><technical_language>removing optional ? I is more clear method return null if in prototype is optional</technical_language>

Target:
private Optional<JobEventMonitor> removeJobEvent(JobId id, SchedulerEvent event) { JobEventMonitor tmp = new JobEventMonitor(event, id); if (jobsEvents.containsKey(id) && jobsEvents.get(id).contains(tmp)) { return Optional.of(jobsEvents.get(id).remove((jobsEvents.get(id).indexOf(tmp)))); } else return Optional.empty(); }
Source:
<code><START> public void testTokenRenewal_Enabled_WithConfigurableMaxTokenLifetime() throws Exception { <END> final String caller = "yarn"; Pair<TestTokenStateService, Response> testResult = doTestTokenRenewal(true, caller, 10L, createTestSubject(caller)); TestTokenStateService tss = testResult.getLeft(); assertEquals(1, tss.issueTimes.size()); String token = tss.issueTimes.keySet().iterator().next(); assertEquals(10L, tss.getMaxLifetime(token) - tss.getIssueTime(token)); }</code><technical_language>Do need underscores in method name (see in another new method too)</technical_language>

Target:
public void testTokenRenewal_Enabled_WithConfigurableMaxTokenLifetime() throws Exception { final String caller = "yarn"; Map.Entry<TestTokenStateService, Response> testResult = doTestTokenRenewal(true, caller, 10L, createTestSubject(caller)); TestTokenStateService tss = testResult.getKey(); assertEquals(1, tss.issueTimes.size()); String token = tss.issueTimes.keySet().iterator().next(); assertEquals(10L, tss.getMaxLifetime(token) - tss.getIssueTime(token)); }
Source:
<code>UserAgent() { String version = UNKNOWN_VERSION; try { ; Properties props = new Properties(); props.load(UserAgent.class.getResourceAsStream(VERSION_TXT)); version = props.getProperty("version", UNKNOWN_VERSION); } catch (Throwable t) { LOG.warn("Could not resolve 'VERSION' for user-agent"); } <START> this.agentName = PREFIX + " (" + version + ")"; <END> }</code><technical_language>I strongly suggest "standard" User-Agent format (curl Python it), i.e. "<APP-NAME>/<VER>": Examples: - User-Agent: curl/7.43.0 - User-Agent: python-requests/2.9.1</technical_language>

Target:
UserAgent() { String version = UNKNOWN_VERSION; try { ; Properties props = new Properties(); props.load(UserAgent.class.getResourceAsStream(VERSION_TXT)); version = props.getProperty("version", UNKNOWN_VERSION); } catch (Throwable t) { LOG.warn("Could not resolve 'VERSION' for user-agent"); } this.agentName = PREFIX + "/" + version; }
Source:
<code>protected void execute(Context context) throws SQLException { MassUpdate massUpdate = context.prepareMassUpdate(); <START> massUpdate.select("select id, prop_key from properties " + <END> " where prop_key like ?") .setString(1, "%" + LICENSE_HASH_SECURED_SUFFIX); massUpdate.update("delete from properties where prop_key = ? or prop_key = ?"); massUpdate.rowPluralName("old license properties"); massUpdate.execute((row, update) -> { String key = row.getString(2); String prefix = key.replace(LICENSE_HASH_SECURED_SUFFIX, ""); update.setString(1, key); update.setString(2, prefix + LICENSE_SECURED_SUFFIX); return true; }); }</code><technical_language>select id</technical_language>

Target:
protected void execute(Context context) throws SQLException { MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select prop_key from properties where prop_key like ?") .setString(1, "%" + LICENSE_HASH_SECURED_SUFFIX); massUpdate.update("delete from properties where prop_key = ? or prop_key = ?"); massUpdate.rowPluralName("old license properties"); massUpdate.execute((row, update) -> { String licenseHashKey = row.getString(1); String licenseKey = licenseHashKey.replace(LICENSE_HASH_SECURED_SUFFIX, "") + LICENSE_SECURED_SUFFIX; update.setString(1, licenseHashKey); update.setString(2, licenseKey); return true; }); }
Source:
<code>static URL[] getClasspathAsURLs(File jarsLocation) { validateCanAccess(jarsLocation); File[] filesInJarsLocation = jarsLocation.listFiles(); if (filesInJarsLocation == null) { throw new SamzaException( String.format("Could not find any files inside %s, probably because it is not a directory", jarsLocation.getPath())); } URL[] urls = Stream.of(filesInJarsLocation) .filter(file -> file.getName().endsWith(".jar") || file.getName().endsWith(".war")) .map(IsolatingClassLoaderFactory::fileURL) .toArray(URL[]::new); <START> LOG.info("Found items to load into classpath from {}", urls.length, jarsLocation); <END> return urls; }</code><technical_language>useful for debugging log actual directory contents, in buildClassLoader()</technical_language>

Target:
static URL[] getClasspathAsURLs(File jarsLocation) { validateCanAccess(jarsLocation); File[] filesInJarsLocation = jarsLocation.listFiles(); if (filesInJarsLocation == null) { throw new SamzaException( String.format("Could not find any files inside %s, probably because it is not a directory", jarsLocation.getPath())); } URL[] urls = Stream.of(filesInJarsLocation) .filter(file -> file.getName().endsWith(".jar") || file.getName().endsWith(".war")) .map(IsolatingClassLoaderFactory::fileURL) .toArray(URL[]::new); LOG.info("Found items to load into classpath from {}", urls.length, jarsLocation); Stream.of(urls).forEach(url -> LOG.debug("Found from {}", url, jarsLocation)); return urls; }
Source:
<code>private String getQualifiedClassName(DetailAST classAst) { final String className = classAst.findFirstToken(TokenTypes.IDENT).getText(); String outerClassQualifiedName = null; if (currentDepthLevel > 1) { final Iterator<ClassDesc> iterator = classes.iterator(); while (outerClassQualifiedName == null) { final ClassDesc desc = iterator.next(); if (desc.depthLevel == currentDepthLevel - 1) { outerClassQualifiedName = desc.qualifiedName; } } } return getQualifiedClassName(packageName, outerClassQualifiedName, className); <START> } <END></code><technical_language>example</technical_language>

Target:
private String getQualifiedClassName(DetailAST classAst) { final String className = classAst.findFirstToken(TokenTypes.IDENT).getText(); String outerClassQualifiedName = null; for (ClassDesc desc : classes) { if (desc.depthLevel == currentDepthLevel - 1) { outerClassQualifiedName = desc.getQualifiedName(); break; } } return getQualifiedClassName(packageName, outerClassQualifiedName, className); }
Source:
<code>public void addData(final String key, final byte[] data) { <START> ModelNode dataNode = get(SECRET_DATA); <END> if (dataNode == null) { dataNode = new ModelNode(); get(SECRET_DATA).set(dataNode); } dataNode.get(key).set(Base64Coder.encode(data)); }</code><technical_language>This null DMR returns</technical_language>

Target:
public void addData(final String key, final byte[] data) { ModelNode dataNode = get(SECRET_DATA); dataNode.get(key).set(Base64Coder.encode(data)); }
Source:
<code>private void updateDeploymentConfigValues(IReplicationController replicationController, DebuggingContext debugContext) { Collection<IContainer> originalContainers = replicationController.getContainers(); if (originalContainers != null && !originalContainers.isEmpty() && debugContext.isDebugEnabled()) { Collection<IContainer> containers = new ArrayList<>(originalContainers); IContainer container = containers.iterator().next(); Set<IPort> ports = new HashSet<>(container.getPorts()); IPort existing = ports.stream().filter(p -> p.getContainerPort() == debugContext.getDebugPort()) .findFirst().orElse(null); boolean added = false; if (existing == null) { PortSpecAdapter newPort = new PortSpecAdapter("debug", "TCP", debugContext.getDebugPort()); added = ports.add(newPort); } else { PortSpecAdapter newPort = new PortSpecAdapter(existing.getName(), existing.getProtocol(), debugContext.getDebugPort()); if (!existing.equals(newPort)) { ports.remove(existing); added = ports.add(newPort); } } if (added) { container.setPorts(ports); replicationController.setContainers(containers); } } if (debugContext.isDebugEnabled()) { replicationController.setEnvironmentVariable(DEBUG_PORT_KEY, String.valueOf(debugContext.getDebugPort())); <START> } else { <END> replicationController.setEnvironmentVariable(DEBUG_PORT_KEY, ""); } replicationController.setEnvironmentVariable(DEBUG_KEY, String.valueOf(debugContext.isDebugEnabled())); }</code><technical_language>I remove variable</technical_language>

Target:
private void updateDeploymentConfigValues(IReplicationController replicationController, DebuggingContext debugContext) { Collection<IContainer> originalContainers = replicationController.getContainers(); if (originalContainers != null && !originalContainers.isEmpty() && debugContext.isDebugEnabled()) { Collection<IContainer> containers = new ArrayList<>(originalContainers); IContainer container = containers.iterator().next(); Set<IPort> ports = new HashSet<>(container.getPorts()); IPort existing = ports.stream().filter(p -> p.getContainerPort() == debugContext.getDebugPort()) .findFirst().orElse(null); boolean added = false; if (existing == null) { PortSpecAdapter newPort = new PortSpecAdapter("debug", "TCP", debugContext.getDebugPort()); added = ports.add(newPort); } else { PortSpecAdapter newPort = new PortSpecAdapter(existing.getName(), existing.getProtocol(), debugContext.getDebugPort()); if (!existing.equals(newPort)) { ports.remove(existing); added = ports.add(newPort); } } if (added) { container.setPorts(ports); replicationController.setContainers(containers); } } if (debugContext.isDebugEnabled()) { replicationController.setEnvironmentVariable(DEBUG_PORT_KEY, String.valueOf(debugContext.getDebugPort())); } else { replicationController.removeEnvironmentVariable(DEBUG_PORT_KEY); } replicationController.setEnvironmentVariable(DEBUG_KEY, String.valueOf(debugContext.isDebugEnabled())); }
Source:
<code>protected Wallet createWallet(boolean isBsqWallet) { <START> Script.ScriptType preferredOutputScriptType = isBsqWallet ? Script.ScriptType.P2PKH : Script.ScriptType.P2PKH; <END> KeyChainGroupStructure structure = new BisqKeyChainGroupStructure(isBsqWallet); KeyChainGroup.Builder kcg = KeyChainGroup.builder(params, structure); if (restoreFromSeed != null) kcg.fromSeed(restoreFromSeed, preferredOutputScriptType).build(); else if (restoreFromKey != null) kcg.addChain(DeterministicKeyChain.builder().spend(restoreFromKey).outputScriptType(preferredOutputScriptType).build()); else kcg.fromRandom(preferredOutputScriptType); if (walletFactory != null) { return walletFactory.create(params, kcg.build()); } else { return new Wallet(params, kcg.build()); } }</code><technical_language>I guess else case P2WPKH</technical_language>

Target:
protected Wallet createWallet(boolean isBsqWallet) { Script.ScriptType preferredOutputScriptType = Script.ScriptType.P2PKH; KeyChainGroupStructure structure = new BisqKeyChainGroupStructure(isBsqWallet); KeyChainGroup.Builder kcg = KeyChainGroup.builder(params, structure); if (restoreFromSeed != null) { kcg.fromSeed(restoreFromSeed, preferredOutputScriptType).build(); } else if (restoreFromKey != null) { kcg.addChain(DeterministicKeyChain.builder().spend(restoreFromKey).outputScriptType(preferredOutputScriptType).build()); } else { if (!isBsqWallet) { kcg.fromRandom(preferredOutputScriptType); } else { kcg.fromSeed(vBtcWallet.getKeyChainSeed(), preferredOutputScriptType); } } if (walletFactory != null) { return walletFactory.create(params, kcg.build()); } else { return new Wallet(params, kcg.build()); } }
Source:
<code><START> public void testSkipKeyValueIteratorCorrectness() { <END> Header[] headers = {new RecordHeader("k1", "v1".getBytes()), new RecordHeader("k2", "v2".getBytes())}; MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.LZ4, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes()), new SimpleRecord(1000L, "abc".getBytes(), "0".getBytes()), new SimpleRecord(9999L, "abc".getBytes(), "0".getBytes(), headers) ); DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer()); try (CloseableIterator<Record> streamingIterator = batch.skipKeyValueIterator()) { assertEquals(Arrays.asList( new PartialDefaultRecord(9, (byte) 0, 0L, 1L, -1, 1, 1), new PartialDefaultRecord(9, (byte) 0, 1L, 2L, -1, 1, 1), new PartialDefaultRecord(9, (byte) 0, 2L, 3L, -1, 1, 1), new PartialDefaultRecord(12, (byte) 0, 3L, 1000L, -1, 3, 1), new PartialDefaultRecord(25, (byte) 0, 4L, 9999L, -1, 3, 1) ), Utils.toList(streamingIterator) ); } }</code><technical_language>I want some test cases for invalid data. some reuse. I want cover cases: 1. invalid key size (too big, small) 2. invalid size (too big, small) 3. invalid num headers (null, many, few) 4. invalid header key (too big, small) 5. invalid key (too big, small) 6. missing header value</technical_language>

Target:
public void testSkipKeyValueIteratorCorrectness() { Header[] headers = {new RecordHeader("k1", "v1".getBytes()), new RecordHeader("k2", "v2".getBytes())}; MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.LZ4, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes()), new SimpleRecord(1000L, "abc".getBytes(), "0".getBytes()), new SimpleRecord(9999L, "abc".getBytes(), "0".getBytes(), headers) ); DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer()); try (CloseableIterator<Record> streamingIterator = batch.skipKeyValueIterator(BufferSupplier.NO_CACHING)) { assertEquals(Arrays.asList( new PartialDefaultRecord(9, (byte) 0, 0L, 1L, -1, 1, 1), new PartialDefaultRecord(9, (byte) 0, 1L, 2L, -1, 1, 1), new PartialDefaultRecord(9, (byte) 0, 2L, 3L, -1, 1, 1), new PartialDefaultRecord(12, (byte) 0, 3L, 1000L, -1, 3, 1), new PartialDefaultRecord(25, (byte) 0, 4L, 9999L, -1, 3, 1) ), Utils.toList(streamingIterator) ); } }
Source:
<code>void createStreams(String planId, List<StreamSpec> intStreams) throws TimeoutException { if (intStreams.isEmpty()) { LOG.info("Set of intermediate streams is empty. Nothing to create."); <START> System.out.println("1"); <END> return; } String coordinationId = new ApplicationConfig(config).getGlobalAppId() + APPLICATION_RUNNER_ZK_PATH_SUFFIX; CoordinationUtils coordinationUtils = CoordinationUtilsFactory.getCoordinationUtilsFactory(config).getCoordinationUtils(coordinationId, uid, config); System.out.println(" create streams." + uid); if (coordinationUtils == null) { getStreamManager().createStreams(intStreams); System.out.println("failed to create utils" + uid); return; } DistributedLockWithState lockWithState = coordinationUtils.getLockWithState(planId); System.out.println("Init NEEDED for streams" + uid); try { if (lockWithState.lockIfNotSet(1000, TimeUnit.MILLISECONDS)) { System.out.println("CREATING STREAMS" + uid); getStreamManager().createStreams(intStreams); lockWithState.unlockAndSet(); } else { System.out.println("SOMEONE ELSE CREATING STREAMS" + uid); } } catch (TimeoutException e) { LOG.error("Failed to get the lock for stream initialization"); } finally { lockWithState.close(); } }</code><technical_language>interesting output :). a bunch of System.out need removed</technical_language>

Target:
void createStreams(String planId, List<StreamSpec> intStreams) throws TimeoutException { if (intStreams.isEmpty()) { LOG.info("Set of intermediate streams is empty. Nothing to create."); return; } LOG.info("A single processor must create the intermediate streams. Processor will attempt to acquire the lock.", uid); String coordinationId = new ApplicationConfig(config).getGlobalAppId() + APPLICATION_RUNNER_PATH_SUFFIX; CoordinationUtils coordinationUtils = CoordinationUtilsFactory.getCoordinationUtilsFactory(config).getCoordinationUtils(coordinationId, uid, config); if (coordinationUtils == null) { LOG.warn("Processor failed to create utils. Each processor will attempt to create streams.", uid); getStreamManager().createStreams(intStreams); return; } DistributedLockWithState lockWithState = coordinationUtils.getLockWithState(planId); try { if (lockWithState.lockIfNotSet(1000, TimeUnit.MILLISECONDS)) { LOG.info("lock acquired for streams creation by " + uid); getStreamManager().createStreams(intStreams); lockWithState.unlockAndSet(); } else { LOG.info("Processor did not obtain the lock for streams creation. They must've been created by another processor.", uid); } } catch (TimeoutException e) { String msg = String.format("Processor failed to get the lock for stream initialization", uid); throw new SamzaException(msg, e); } finally { coordinationUtils.close(); } }
Source:
<code>private static Block projectWithYield(PageProjectionOutput output, DriverYieldSignal yieldSignal) { for (int i = 0; i < 10; i++) { yieldSignal.setWithDelay(1, executor); yieldSignal.forceYieldForTesting(); assertFalse(output.compute().isPresent()); yieldSignal.reset(); } <START> return output.compute().orElseThrow(IllegalStateException::new); <END> }</code><technical_language>This useful test. Yielding beginning essentially means compute call do return immediately. I assume reason wrote this test is code produce correct results of forced a yield. I feel a YieldSignal implementation tosses a coin isSet call helpful here</technical_language>

Target:
private static Block projectWithYield(PageProjectionOutput output, DriverYieldSignal yieldSignal) { int yieldCount = 0; while (true) { yieldSignal.setWithDelay(1, executor); yieldSignal.forceYieldForTesting(); Optional<Block> block = output.compute(); if (block.isPresent()) { assertGreaterThan(yieldCount, 0); return block.get(); } yieldCount++; if (yieldCount > 1_000_000) { fail("projection is not making progress"); } yieldSignal.reset(); } }
Source:
<code>public static Pipeline buildPipeline(HBaseExportOptions options) throws IOException { if(options.getDiskSizeGb() == 0) { options.setDiskSizeGb(20); } if(options.getBigtableProjectId() == null) { options.setBigtableProjectId(options.getProject()); } <START> final Scan scan = new Scan() <END> .setStartRow(options.getStartRow().getBytes()) .setStopRow(options.getStopRow().getBytes()) .setMaxVersions(options.getMaxVersions()); if (!options.getFilter().isEmpty()) { scan.setFilter(new ParseFilter().parseFilterString(options.getFilter())); } final String bigtableProject = Objects.firstNonNull(options.getBigtableProjectId(), options.getProject()); final CloudBigtableScanConfiguration scanConfig = new CloudBigtableScanConfiguration.Builder() .withProjectId(bigtableProject) .withInstanceId(options.getBigtableInstanceId()) .withTableId(options.getBigtableTableId()) .withScan(scan) .build(); final BoundedSource<Result> source = CloudBigtableIO.read(scanConfig); final Pipeline pipeline = Pipeline.create(options); final SerializableCoder<BoundedSource<Result>> sourceCoder = SerializableCoder.of(new TypeDescriptor<BoundedSource<Result>>() {}); final KvCoder<String, BoundedSource<Result>> kvCoder = KvCoder.of(StringUtf8Coder.of(), sourceCoder); pipeline .apply("Initialize", Create.of(source).withCoder(sourceCoder)) .apply("Shard", ParDo.of(new ShardScans<Result>())).setCoder(kvCoder) .apply("Fanout", Reshuffle.<String, BoundedSource<Result>>of()) .apply("Write", ParDo.of(new WriteResultsToSeq(options.getDestination()))); return pipeline; }</code><technical_language>I a commandline configured Scan. I Scan a parameter in a buildPipeline(HBaseExportOptions options, Scan scan) method for more sophisticated cases</technical_language>

Target:
public static Pipeline buildPipeline(HBaseExportOptions options) throws IOException { if (options.getDiskSizeGb() == 0) { options.setDiskSizeGb(20); } if (options.getBigtableProjectId() == null) { options.setBigtableProjectId(options.getProject()); } final Scan scan = new Scan() .setStartRow(options.getStartRow().getBytes()) .setStopRow(options.getStopRow().getBytes()) .setMaxVersions(options.getMaxVersions()); if (!options.getFilter().isEmpty()) { scan.setFilter(new ParseFilter().parseFilterString(options.getFilter())); } final String bigtableProject = Objects.firstNonNull(options.getBigtableProjectId(), options.getProject()); final CloudBigtableScanConfiguration scanConfig = new CloudBigtableScanConfiguration.Builder() .withProjectId(bigtableProject) .withInstanceId(options.getBigtableInstanceId()) .withTableId(options.getBigtableTableId()) .withScan(scan) .build(); return buildPipeline(options, scanConfig, options.getDestination()); }
Source:
<code>public String loadPreviousInput() { MetadataMap filters = (MetadataMap) getSession().getAttribute(FILTER_INPUTS); if (filters == null) return null; <START> else if (filters.get(dataProvider.getClass().getName()) == null) return null; <END> return (String) filters.get(dataProvider.getClass().getName()); }</code><technical_language>Straight returning results of filters.get(...) effect, not? Mind, safer ask metadata map produce a String.class get parameter</technical_language>

Target:
private String loadPreviousInput() { MetadataMap filters = getMetaDataMapFromSession(FILTER_INPUTS); if (filters == null) return null; else if (filters.get(dataProvider.getClass().getName(), String.class) == null) return null; return filters.get(dataProvider.getClass().getName(), String.class); }
Source:
<code>public File findArtifact(org.mule.maven.client.api.model.BundleDescriptor bundleDescriptor) { if (checkArtifact(bundleDescriptor)) { <START> if (bundleDescriptor.getType().equals("pom")) { <END> return pomFile; } else { return artifactFile; } } return null; }</code><technical_language>constant</technical_language>

Target:
public File findArtifact(org.mule.maven.client.api.model.BundleDescriptor bundleDescriptor) { if (checkArtifact(bundleDescriptor)) { if (bundleDescriptor.getType().equals(POM)) { return pomFile; } else { return artifactFile; } } return null; }
Source:
<code>public void deferred() throws Exception { <START> tester.getApplication().setHeaderResponseDecorator(new IHeaderResponseDecorator() <END> { @Override public IHeaderResponse decorate(IHeaderResponse response) { return new ResourceAggregator(new JavaScriptDeferHeaderResponse(response)); } }); executeTest(DeferredPage.class, "DeferredPageExpected.html"); }</code><technical_language>this simplified tester.getApplication().setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response)));</technical_language>

Target:
public void deferred() throws Exception { tester.getApplication().setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response))); executeTest(DeferredPage.class, "DeferredPageExpected.html"); }
Source:
<code>public int compare(IPath arg0, IPath arg1) { if <START> (arg0.equals(arg1)) <END> { return 0; } int res = 0; if (arg0.getDevice() != null && arg1.getDevice() == null) { return +1; } if (arg0.getDevice() == null && arg1.getDevice() != null) { return -1; } if (arg0.getDevice() != null && arg1.getDevice() != null) { res = arg0.getDevice().compareTo(arg1.getDevice()); if (res != 0) { return res; } } res = Boolean.compare(arg0.isAbsolute(), arg1.isAbsolute()); if (res != 0) { return res; } res = Boolean.compare(arg0.isUNC(), arg1.isUNC()); if (res != 0) { return res; } for (int i = 0; i < Math.min(arg0.segmentCount(), arg1.segmentCount()); i++) { res = arg0.segment(i).compareTo(arg1.segment(i)); if (res != 0) { return res; } } return arg0.segmentCount() - arg1.segmentCount(); }</code><technical_language>do equals here? enough check for identity == avoid cost for full path compare in equals()</technical_language>

Target:
public int compare(IPath arg0, IPath arg1) { if (arg0 == arg1) { return 0; } int res = 0; String device0 = arg0.getDevice(); String device1 = arg1.getDevice(); if (device0 != null && device1 == null) { return +1; } if (device0 == null && device1 != null) { return -1; } if (device0 != null && device1 != null) { res = device0.compareTo(device1); if (res != 0 && !device0.equalsIgnoreCase(device1)) { return res; } } res = Boolean.compare(arg0.isAbsolute(), arg1.isAbsolute()); if (res != 0) { return res; } res = Boolean.compare(arg0.isUNC(), arg1.isUNC()); if (res != 0) { return res; } for (int i = 0; i < Math.min(arg0.segmentCount(), arg1.segmentCount()); i++) { res = arg0.segment(i).compareTo(arg1.segment(i)); if (res != 0) { return res; } } return arg0.segmentCount() - arg1.segmentCount(); }
Source:
<code>protected CalciteSchema getImplicitSubSchema(String schemaName, boolean caseSensitive) { if (caseSensitive) { Schema s = schema.getSubSchema(schemaName); if (s != null) { return new SimpleCalciteSchema(this, s, schemaName); } } else { final String schemaName2 = caseInsensitiveLookup( schema.getSubSchemaNames(), schemaName); if (schemaName2 != null) { <START> return new SimpleCalciteSchema(this, schema.getSubSchema(schemaName2), schemaName2); <END> } } return null; }</code><technical_language>This code duplication. please factor out of if statement? For instance: 1. determine schema name 2. return candidate</technical_language>

Target:
protected CalciteSchema getImplicitSubSchema(String schemaName, boolean caseSensitive) { final String schemaName2 = caseSensitive ? schemaName : caseInsensitiveLookup( schema.getSubSchemaNames(), schemaName); if (schemaName2 == null) { return null; } final Schema s = schema.getSubSchema(schemaName2); if (s == null) { return null; } return new SimpleCalciteSchema(this, s, schemaName2); }
Source:
<code>protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable key, value, qmc; try { abvs.reset(); ob.reset(abvs); int len = args.length; pointables = new TaggedValuePointable[len / 3]; for (int i = 0; i < len; i += 3) { key = args[i]; value = args[i + 1]; qmc = args[i + 2]; if (!isDuplicate(key)) { pointables[i / 3] = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); key.getValue(pointables[i / 3]); sp.set(vp); if (value.getTag() == ValueTag.SEQUENCE_TAG) { qmc.getValue(bp); value.getValue(seqp); <START> if (bp.getBoolean()) { <END> continue; } if (seqp.getEntryCount() == 0) { XDMConstants.setJsNull(value); ob.addItem(sp, value); } else { abvs1.reset(); ab.reset(abvs1); int l = seqp.getEntryCount(); for (int j = 0; j < l; j++) { seqp.getEntry(j, value); ab.addItem(value); } ab.finish(); vp.set(abvs1); ob.addItem(sp, vp); } } else { ob.addItem(sp, value); } } else { throw new SystemException(ErrorCode.JNDY0003); } } ob.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } }</code><technical_language>this case? {"test" ?: (1,2,3)}</technical_language>

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable key, value, qmc; try { abvs.reset(); ob.reset(abvs); int len = args.length; pointables = new TaggedValuePointable[len / 3]; for (int i = 0; i < len; i += 3) { key = args[i]; value = args[i + 1]; qmc = args[i + 2]; if (!isDuplicate(key)) { pointables[i / 3] = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); key.getValue(pointables[i / 3]); sp.set(vp); if (value.getTag() == ValueTag.SEQUENCE_TAG) { qmc.getValue(bp); value.getValue(seqp); if (seqp.getEntryCount() == 0) { if (bp.getBoolean()) { continue; } XDMConstants.setJsNull(value); ob.addItem(sp, value); } else { abvs1.reset(); ab.reset(abvs1); int l = seqp.getEntryCount(); for (int j = 0; j < l; j++) { seqp.getEntry(j, value); ab.addItem(value); } ab.finish(); vp.set(abvs1); ob.addItem(sp, vp); } } else { ob.addItem(sp, value); } } else { throw new SystemException(ErrorCode.JNDY0003); } } ob.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } }
Source:
<code>public LabelMetadataBuilder(String ID, String description) { <START> super(ID); this.description = description; this.priority = Integer.MAX_VALUE; <END> }</code><technical_language>replace this this(ID, description, Integer.MAX_VALUE);</technical_language>

Target:
public LabelMetadataBuilder(String ID, String description) { this(ID, description, Integer.MAX_VALUE); }
Source:
<code>public static List<FileFormat> getFileFormats() throws IOException, JAXBException { <START> KitodoServiceLoader<FileManagementInterface> fileManagementInterface = new KitodoServiceLoader<>( <END> FileManagementInterface.class); try (InputStream bytes = fileManagementInterface.loadModule().read(CONFIG_FILE_URI)) { Unmarshaller fileFormatsConfig = JAXBContext.newInstance(FileFormatsConfig.class).createUnmarshaller(); FileFormatsConfig read = (FileFormatsConfig) fileFormatsConfig.unmarshal(bytes); return read.fileFormat; } }</code><technical_language>Accessing local application configuration files done file management module this is for accessing meta data pictures delivered a remote repository in other implementation</technical_language>

Target:
public static List<FileFormat> getFileFormats() throws IOException, JAXBException { Unmarshaller fileFormatsConfig = JAXBContext.newInstance(FileFormatsConfig.class).createUnmarshaller(); FileFormatsConfig read = (FileFormatsConfig) fileFormatsConfig.unmarshal(CONFIG_FILE); return read.fileFormat; }
Source:
<code>public void onShowPostPopup(View view, final ReaderPost post) { if (view == null || post == null || !isAdded()) { return; } Context context = view.getContext(); final ListPopupWindow listPopup = new ListPopupWindow(context); listPopup.setAnchorView(view); listPopup.setWidth(context.getResources().getDimensionPixelSize(R.dimen.menu_item_width)); listPopup.setModal(true); List<Integer> menuItems = new ArrayList<>(); boolean isFollowed = ReaderPostTable.isPostFollowed(post); if (isFollowed) { menuItems.add(ReaderMenuAdapter.ITEM_UNFOLLOW); } else { menuItems.add(ReaderMenuAdapter.ITEM_FOLLOW); } if (getPostListType() == ReaderPostListType.TAG_FOLLOWED) { menuItems.add(ReaderMenuAdapter.ITEM_BLOCK); } listPopup.setAdapter(new ReaderMenuAdapter(context, menuItems)); listPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (!isAdded()) { return; } listPopup.dismiss(); switch ((int) id) { case ReaderMenuAdapter.ITEM_FOLLOW: <START> showPostNotificationsSnackbar(post); <END> case ReaderMenuAdapter.ITEM_UNFOLLOW: toggleFollowStatusForPost(post); break; case ReaderMenuAdapter.ITEM_BLOCK: blockBlogForPost(post); break; } } }); listPopup.show(); }</code><technical_language>missing break threw for a :)</technical_language>

Target:
public void onShowPostPopup(View view, final ReaderPost post) { if (view == null || post == null || !isAdded()) { return; } Context context = view.getContext(); final ListPopupWindow listPopup = new ListPopupWindow(context); listPopup.setAnchorView(view); listPopup.setWidth(context.getResources().getDimensionPixelSize(R.dimen.menu_item_width)); listPopup.setModal(true); List<Integer> menuItems = new ArrayList<>(); boolean isFollowed = ReaderPostTable.isPostFollowed(post); if (isFollowed) { menuItems.add(ReaderMenuAdapter.ITEM_UNFOLLOW); } else { menuItems.add(ReaderMenuAdapter.ITEM_FOLLOW); } if (getPostListType() == ReaderPostListType.TAG_FOLLOWED) { menuItems.add(ReaderMenuAdapter.ITEM_BLOCK); } listPopup.setAdapter(new ReaderMenuAdapter(context, menuItems)); listPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (!isAdded()) { return; } listPopup.dismiss(); switch ((int) id) { case ReaderMenuAdapter.ITEM_FOLLOW: case ReaderMenuAdapter.ITEM_UNFOLLOW: toggleFollowStatusForPost(post); break; case ReaderMenuAdapter.ITEM_BLOCK: blockBlogForPost(post); break; } } }); listPopup.show(); }