auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void verifyBasicResponse() { String expected = "{\"data\":" + "{\"book\":" + "{\"edges\":" + "[{\"node\":" + "{\"id\":\"1\"," + "\"title\":\"My first book\"," + "\"authors\":{\"edges\":[{\"node\":{" + "\"name\":\"Ricky Carmichael\"}}]}}}]}}}"; String actual = document( selection( field( <START> RESPONSE, <END> "book", selections( field("id", "1"), field("title", "My first book"), field( RESPONSE, "authors", selection( field("name", "Ricky Carmichael") ) ) ) ) ) ).toResponse(); Assert.assertEquals(actual, expected); }</code><technical_language>I feel need RESPONSE defined a separate method called toResponse. remove this extra field parameter</technical_language>

Target:
public void verifyBasicResponse() { String expected = "{\"data\":" + "{\"book\":" + "{\"edges\":" + "[{\"node\":" + "{\"id\":\"1\"," + "\"title\":\"My first book\"," + "\"authors\":{\"edges\":[{\"node\":{" + "\"name\":\"Ricky Carmichael\"}}]}}}]}}}"; String actual = document( selection( field( "book", selections( field("id", "1"), field("title", "My first book"), field( "authors", selection( field("name", "Ricky Carmichael") ) ) ) ) ) ).toResponse(); assertEquals(expected, actual); }
Source:
<code>public static Disk map(org.ovirt.engine.core.common.businessentities.Disk entity, Disk template) { Disk model = template != null ? template : new Disk(); model.setName(entity.getDiskAlias()); model.setAlias(entity.getDiskAlias()); if (entity.getId() != null) { model.setId(entity.getId().toString()); } if (entity.getDiskInterface() != null) { model.setInterface(map(entity.getDiskInterface(), null)); } model.setBootable(entity.isBoot()); model.setPropagateErrors(PropagateErrors.On == entity.getPropagateErrors()); model.setWipeAfterDelete(entity.isWipeAfterDelete()); model.setActive(entity.getPlugged()); model.setReadOnly(entity.getReadOnly()); model.setShareable(entity.isShareable()); model.setDescription(entity.getDiskDescription()); model.setLogicalName(entity.getLogicalName()); if (entity.getDiskStorageType() == DiskStorageType.IMAGE) { mapDiskImageToDiskFields((DiskImage) entity, model); } else { model.setLunStorage(StorageLogicalUnitMapper.map(((LunDisk) entity).getLun(), new Storage())); if (entity.getSgio() != null && entity.getDiskInterface() == map(DiskInterface.VIRTIO_SCSI, null)) { model.setSgio(map(entity.getSgio(), null)); <START> model.setUsesScsiReservation(((LunDisk)entity).isUsingScsiReservation()); <END> } } return model; }</code><technical_language>is this if? if entity is lun set. if wrong fail in command. please test DiskMapperTest</technical_language>

Target:
public static Disk map(org.ovirt.engine.core.common.businessentities.Disk entity, Disk template) { Disk model = template != null ? template : new Disk(); model.setName(entity.getDiskAlias()); model.setAlias(entity.getDiskAlias()); if (entity.getId() != null) { model.setId(entity.getId().toString()); } if (entity.getDiskInterface() != null) { model.setInterface(map(entity.getDiskInterface(), null)); } model.setBootable(entity.isBoot()); model.setPropagateErrors(PropagateErrors.On == entity.getPropagateErrors()); model.setWipeAfterDelete(entity.isWipeAfterDelete()); model.setActive(entity.getPlugged()); model.setReadOnly(entity.getReadOnly()); model.setShareable(entity.isShareable()); model.setDescription(entity.getDiskDescription()); model.setLogicalName(entity.getLogicalName()); if (entity.getDiskStorageType() == DiskStorageType.IMAGE) { mapDiskImageToDiskFields((DiskImage) entity, model); } else { model.setLunStorage(StorageLogicalUnitMapper.map(((LunDisk) entity).getLun(), new Storage())); model.setUsesScsiReservation(((LunDisk) entity).isUsingScsiReservation()); if (entity.getSgio() != null && entity.getDiskInterface() == map(DiskInterface.VIRTIO_SCSI, null)) { model.setSgio(map(entity.getSgio(), null)); } } return model; }
Source:
<code>List<InputRow> parse(List<byte[]> streamChunk) throws IOException { if (parser != null) { return parseWithParser(parser, streamChunk); } else { <START> return parseWithInputFormat(lazyByteEntityReaderSupplier.get(), streamChunk); <END> } }</code><technical_language>prefer inputFormat if exists</technical_language>

Target:
List<InputRow> parse(List<byte[]> streamChunk) throws IOException { if (byteEntityReader != null) { return parseWithInputFormat(byteEntityReader, streamChunk); } else { return parseWithParser(parser, streamChunk); } }
Source:
<code>public String raw() { if (raw == null) { <START> throw new RuntimeException("JSON document has no \"raw\" field"); <END> } return raw; }</code><technical_language>way, I this is right error message... "raw" a field in JSON..</technical_language>

Target:
public String raw() { return raw; }
Source:
<code>public void executeAction(final WorkflowProcessor processor, <START> final Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { <END> final Map<Relationship, List<Contentlet>> contentRelationships = new HashMap<Relationship, List<Contentlet>>(); try { final Contentlet contentlet = processor.getContentlet(); final User user = processor.getUser(); final List<Category > categories = this.categoryAPI.getParents(contentlet, user, false); final List< Permission > permissions = this.permissionAPI.getPermissions(contentlet, false, true); Logger.debug(this, "Saving the content as draft of the contentlet: " + contentlet.getIdentifier()); contentlet.setProperty(Contentlet.WORKFLOW_IN_PROGRESS, Boolean.TRUE); this.buildRelationships(processor.getUser(), contentRelationships, contentlet); this.contentletAPI.saveDraft( processor.getContentlet(), contentRelationships, categories, permissions, user, true); Logger.debug(this, "content draft already saved for the contentlet: " + contentlet.getIdentifier()); } catch (Exception e) { Logger.error(this.getClass(),e.getMessage(),e); throw new WorkflowActionFailureException(e.getMessage()); } }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove declaration of thrown exception 'com.dotmarketing.portlets.workflows.model.WorkflowActionFailureException' is a runtime exception. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public void executeAction(final WorkflowProcessor processor, final Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { final Map<Relationship, List<Contentlet>> contentRelationships = new HashMap<Relationship, List<Contentlet>>(); try { final Contentlet contentlet = processor.getContentlet(); final User user = processor.getUser(); final List<Category > categories = this.categoryAPI.getParents(contentlet, user, false); final List< Permission > permissions = this.permissionAPI.getPermissions(contentlet, false, true); Logger.debug(this, "Saving the content as draft of the contentlet: " + contentlet.getIdentifier()); contentlet.setProperty(Contentlet.WORKFLOW_IN_PROGRESS, Boolean.TRUE); this.buildRelationships(processor.getUser(), contentRelationships, contentlet); final Contentlet contentletNew = this.contentletAPI.saveDraft( contentlet, contentRelationships, categories, permissions, user, true); processor.setContentlet(contentletNew); Logger.debug(this, "content draft already saved for the contentlet: " + contentlet.getIdentifier()); } catch (Exception e) { Logger.error(this.getClass(),e.getMessage(),e); throw new WorkflowActionFailureException(e.getMessage()); } }
Source:
<code>public void contextInitialized(ServletContextEvent sce) { <START> ServletContext ctx = sce.getServletContext(); <END> RelationshipCheckerRegistry.registerRelationshipChecker(new InfoContentEntityChecker()); RelationshipCheckerRegistry.registerRelationshipChecker(new GrantChecker()); RelationshipCheckerRegistry.registerRelationshipChecker(new ProjectOrServiceChecker()); RelationshipCheckerRegistry.registerRelationshipChecker(new PresentationChecker()); RelationshipCheckerRegistry.registerRelationshipChecker(new CourseChecker()); RelationshipCheckerRegistry.registerRelationshipChecker(new AdvisingRelationshipChecker()); }</code><technical_language>ctx variable used... removed</technical_language>

Target:
public void contextInitialized(ServletContextEvent sce) { RelationshipChecker.getQueryBuilder() .addRelationshipThroughContext(URI_BEARER_OF, URI_ADVISOR_ROLE, URI_RELATED_BY, URI_ADVISING_RELATIONSHIP_TYPE) .addRelationshipThroughContext(URI_BEARER_OF, URI_TEACHER_ROLE_TYPE, URI_REALIZED_IN, URI_COURSE_TYPE) .addRelationshipThroughContext(URI_BEARER_OF, URI_PI_ROLE_TYPE, URI_RELATED_BY, URI_GRANT_TYPE) .addRelationshipThroughContext(URI_BEARER_OF, URI_CO_PI_ROLE_TYPE, URI_RELATED_BY, URI_GRANT_TYPE) .addRelationshipThroughContext(URI_RELATED_BY, URI_AUTHORSHIP_TYPE, URI_RELATES, URI_INFO_CONTENT_TYPE) .addRelationshipThroughContext(URI_RELATED_BY, URI_EDITORSHIP_TYPE, URI_RELATES, URI_INFO_CONTENT_TYPE) .addRelationshipThroughContext(URI_BEARER_OF, URI_PRESENTER_ROLE_TYPE, URI_REALIZED_IN, URI_PRESENTATION_TYPE) .addRelationshipThroughContext(URI_BEARER_OF, URI_CLINICAL_ROLE_TYPE, URI_CONTRIBUTES_TO, URI_PROJECT_TYPE) .addRelationshipThroughContext(URI_BEARER_OF, URI_CLINICAL_ROLE_TYPE, URI_CONTRIBUTES_TO, URI_SERVICE_TYPE) .finish(); }
Source:
<code>private static Long invoke(Method method) { try { return method == null ? null : (Long) method.invoke(ManagementFactory.getOperatingSystemMXBean()); } catch (Throwable throwable) { if (throwable instanceof Error) { throw (Error) throwable; } if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } <START> throw new RuntimeException(throwable); <END> } }</code><technical_language>throwing exceptions returning null here</technical_language>

Target:
private static Long invoke(Method method) { try { return method == null ? null : (Long) method.invoke(ManagementFactory.getOperatingSystemMXBean()); } catch (IllegalAccessException e) { LOGGER.trace("Error invoking method '{}': {}", method, e.getMessage(), e); return null; } catch (InvocationTargetException e) { LOGGER.trace("Error invoking method '{}': {}", method, e.getTargetException().getMessage(), e.getTargetException()); return null; } }
Source:
<code>public void setElements(Object[] elements) { if (elements == null) { fElements = new Object[0]; } else { fElements = new Object[elements.length]; System.arraycopy(elements, 0, fElements, 0, elements.length); } <START> fList.deselectAll(); <END> int length = fElements.length; fLabels = new Label[length]; Set imageSet = new HashSet(); for (int i = 0; i != length; i++) { String text = fLabelProvider.getText(fElements[i]); Image image = fLabelProvider.getImage(fElements[i]); fLabels[i] = new Label(text, image); imageSet.add(image); } fImages.clear(); fImages.addAll(imageSet); fSorter.sort(fLabels, fElements); fFilteredIndices = new int[length]; fFoldedIndices = new int[length]; updateList(); }</code><technical_language>a matter of taste: I move down, e.g. fImages.clear();</technical_language>

Target:
public void setElements(Object[] elements) { if (elements == null) { fElements = new Object[0]; } else { fElements = new Object[elements.length]; System.arraycopy(elements, 0, fElements, 0, elements.length); } int length = fElements.length; fLabels = new Label[length]; Set imageSet = new HashSet(); for (int i = 0; i != length; i++) { String text = fLabelProvider.getText(fElements[i]); Image image = fLabelProvider.getImage(fElements[i]); fLabels[i] = new Label(text, image); imageSet.add(image); } fList.deselectAll(); fImages.clear(); fImages.addAll(imageSet); fSorter.sort(fLabels, fElements); fFilteredIndices = new int[length]; fFoldedIndices = new int[length]; updateList(); }
Source:
<code>public QueryParameters queryParameters(SqlFieldsQuery qry) { NestedTxMode nestedTxMode = NestedTxMode.DEFAULT; boolean autoCommit = true; List<Object[]> batchedArgs = null; if (qry instanceof SqlFieldsQueryEx) { SqlFieldsQueryEx qry0 = (SqlFieldsQueryEx)qry; if (qry0.getNestedTxMode() != null) nestedTxMode = qry0.getNestedTxMode(); autoCommit = qry0.isAutoCommit(); batchedArgs = qry0.batchedArguments(); } int timeout; <START> if (qry.getTimeout() >= 0) { <END> timeout = qry.getTimeout(); } else { timeout = (int)idx.kernalContext().config().getDefaultQueryTimeout(); A.ensure(timeout >= 0 && timeout <= Integer.MAX_VALUE, "timeout value should be valid Integer."); } return new QueryParameters( qry.getArgs(), qry.getPartitions(), timeout, qry.isLazy(), qry.getPageSize(), null, nestedTxMode, autoCommit, batchedArgs, qry.getUpdateBatchSize() ); }</code><technical_language>Curly braces redundant code style</technical_language>

Target:
public QueryParameters queryParameters(SqlFieldsQuery qry) { NestedTxMode nestedTxMode = NestedTxMode.DEFAULT; boolean autoCommit = true; List<Object[]> batchedArgs = null; if (qry instanceof SqlFieldsQueryEx) { SqlFieldsQueryEx qry0 = (SqlFieldsQueryEx)qry; if (qry0.getNestedTxMode() != null) nestedTxMode = qry0.getNestedTxMode(); autoCommit = qry0.isAutoCommit(); batchedArgs = qry0.batchedArguments(); } int timeout; if (qry.getTimeout() >= 0) timeout = qry.getTimeout(); else timeout = (int)idx.kernalContext().config().getDefaultQueryTimeout(); return new QueryParameters( qry.getArgs(), qry.getPartitions(), timeout, qry.isLazy(), qry.getPageSize(), null, nestedTxMode, autoCommit, batchedArgs, qry.getUpdateBatchSize() ); }
Source:
<code>private void searchAgentJar() { File agentJar = null; try { URL entry = org.jboss.tools.jmx.jvmmonitor.core.Activator.getDefault().getBundle() .getEntry(IConstants.JVMMONITOR_AGENT_JAR); URL entryFileUrl = FileLocator.toFileURL(entry); <START> URI entryFileURI = new URI(entryFileUrl.getProtocol(), null, entryFileUrl.getPath(), null); <END> agentJar = new File(entryFileURI); } catch (IOException e) { Activator.log(IStatus.ERROR, Messages.corePluginNoFoundMsg, new Exception(e)); return; } catch (URISyntaxException e) { Activator.log(IStatus.ERROR, Messages.corePluginNoFoundMsg, new Exception(e)); return; } if( agentJar != null ) { agentJarPath = agentJar.getAbsolutePath(); if (!agentJar.exists()) { Activator.log( IStatus.ERROR, NLS.bind(Messages.agentJarNotFoundMsg, agentJar.getAbsolutePath()), new Exception()); } else { Activator.log(IStatus.INFO, NLS.bind(Messages.agentJarFoundMsg, agentJarPath), new Exception()); } } }</code><technical_language>reason create URI getPath()</technical_language>

Target:
private void searchAgentJar() { File agentJar = null; try { URL entry = org.jboss.tools.jmx.jvmmonitor.core.Activator.getDefault().getBundle() .getEntry(IConstants.JVMMONITOR_AGENT_JAR); URL entryFileUrl = FileLocator.toFileURL(entry); agentJar = new File(entryFileUrl.getPath()); } catch (IOException e) { Activator.log(IStatus.ERROR, Messages.corePluginNoFoundMsg, new Exception(e)); return; } if( agentJar != null ) { agentJarPath = agentJar.getAbsolutePath(); if (!agentJar.exists()) { Activator.log( IStatus.ERROR, NLS.bind(Messages.agentJarNotFoundMsg, agentJar.getAbsolutePath()), new Exception()); } else { Activator.log(IStatus.INFO, NLS.bind(Messages.agentJarFoundMsg, agentJarPath), new Exception()); } } }
Source:
<code>public void lowerBoundMismatchTokens() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(1)); newTokens.put("token3", new GlobalSequenceTrackingToken(2)); Map<String, TrackingToken> expectedTokens = new HashMap<>(); expectedTokens.put("token1", new GlobalSequenceTrackingToken(0)); expectedTokens.put("token2", new GlobalSequenceTrackingToken(0)); <START> ; <END> MultiSourceTrackingToken newMultiToken = (MultiSourceTrackingToken) testSubject .lowerBound(new MultiSourceTrackingToken(newTokens)); }</code><technical_language>Nit: this ; necessary I think</technical_language>

Target:
public void lowerBoundMismatchTokens() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(1)); newTokens.put("token3", new GlobalSequenceTrackingToken(2)); testSubject.lowerBound(new MultiSourceTrackingToken(newTokens)); }
Source:
<code>public void apply(final EntityLocal entity) { new MachineLifecycleEffectorTasks() { @Override protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) { DynamicTasks.queue( SshEffectorTasks.ssh( "mkdir "+dir(entity), "cd "+dir(entity), BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz" ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); if (isLinux(machineS)) { DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1"))); } DynamicTasks.queue( SshEffectorTasks.put(".my.cnf") .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))), SshEffectorTasks.ssh( "cd "+dir(entity)+" data data/*.pid")).block().getStdout().trim())); entity().setAttribute(Attributes.SERVICE_UP, true); } @Override protected String stopProcessesAtMachine() { <START> entity().setAttribute(Attributes.SERVICE_UP, true); <END> Integer pid = entity().getAttribute(Attributes.PID); if (pid==null) { log.info("mysql not running"); return "No pid -- is it running?"; } DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./support-files/mysql.server stop" ).summary("stop mysql")); return "submitted stop"; } }.attachLifecycleEffectors(entity); }</code><technical_language>true</technical_language>

Target:
public void apply(final EntityLocal entity) { new MachineLifecycleEffectorTasks() { @Override protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) { DynamicTasks.queue( SshEffectorTasks.ssh( "mkdir "+dir(entity), "cd "+dir(entity), BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz" ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); if (isLinux(machineS)) { DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1"))); } DynamicTasks.queue( SshEffectorTasks.put(".my.cnf") .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))), SshEffectorTasks.ssh( "cd "+dir(entity)+" data data/*.pid")).block().getStdout().trim())); entity().setAttribute(Attributes.SERVICE_UP, true); } @Override protected String stopProcessesAtMachine() { entity().setAttribute(Attributes.SERVICE_UP, false); Integer pid = entity().getAttribute(Attributes.PID); if (pid==null) { log.info("mysql not running"); return "No pid -- is it running?"; } DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./support-files/mysql.server stop" ).summary("stop mysql")); return "submitted stop"; } }.attachLifecycleEffectors(entity); }
Source:
<code>protected void addPermission(DocumentModel doc) { <START> if (user == null && (Objects.isNull(users) || users.isEmpty()) && email == null) { <END> throw new IllegalParameterException("'users' or 'email' parameters must be set"); } else if (Objects.nonNull(email) && end == null) { throw new IllegalParameterException("'end' parameter must be set when adding a permission for an 'email'"); } ConfigurationService configService = Framework.getService(ConfigurationService.class); if (configService.isBooleanPropertyFalse(ALLOW_VIRTUAL_USER)) { if (Objects.nonNull(user)) { checkUserExistence(user); } if (Objects.nonNull(users) && !users.isEmpty()) { for (String username : users) { checkUserExistence(username); } } } ensureUserListIsUsed(); ACP acp = doc.getACP() != null ? doc.getACP() : new ACPImpl(); Map<String, Serializable> contextData = new HashMap<>(); contextData.put(NOTIFY_KEY, notify); contextData.put(COMMENT_KEY, comment); String creator = session.getPrincipal().getName(); boolean permissionChanged = false; if (blockInheritance) { permissionChanged = acp.blockInheritance(aclName, creator); } for (String username : users) { ACE ace = ACE.builder(username, permission) .creator(creator) .begin(begin) .end(end) .contextData(contextData) .build(); permissionChanged = acp.addACE(aclName, ace) || permissionChanged; } if (permissionChanged) { doc.setACP(acp, true); } }</code><technical_language>Objects.isNull(users) -> users == null</technical_language>

Target:
protected void addPermission(DocumentModel doc) { ACP acp = doc.getACP() != null ? doc.getACP() : new ACPImpl(); Map<String, Serializable> contextData = new HashMap<>(); contextData.put(NOTIFY_KEY, notify); contextData.put(COMMENT_KEY, comment); String creator = session.getPrincipal().getName(); boolean permissionChanged = false; if (blockInheritance) { permissionChanged = acp.blockInheritance(aclName, creator); } for (String username : users) { ACE ace = ACE.builder(username, permission) .creator(creator) .begin(begin) .end(end) .contextData(contextData) .build(); permissionChanged = acp.addACE(aclName, ace) || permissionChanged; } if (permissionChanged) { doc.setACP(acp, true); } }
Source:
<code>EmbeddedElasticsearchNode() <START> throws Exception <END> { elasticsearchDirectory = File.createTempFile("elasticsearch-test", Long.toString(System.nanoTime())); elasticsearchDirectory.delete(); elasticsearchDirectory.mkdir(); String clusterName = "test"; Settings setting = Settings.builder() .put("cluster.name", clusterName) .put("path.home", elasticsearchDirectory.getPath()) .put("path.data", new File(elasticsearchDirectory, "data").getAbsolutePath()) .put("path.logs", new File(elasticsearchDirectory, "logs").getAbsolutePath()) .put("transport.type.default", "local") .put("transport.type", "netty4") .put("http.type", "netty4") .put("http.enabled", "true") .put("path.home", "elasticsearch-test-data") .build(); node = new ElasticsearchNode(setting, Arrays.asList(Netty4Plugin.class)); }</code><technical_language>catch IOException throw unchecked IO exception? I caller able handle this exception throw</technical_language>

Target:
EmbeddedElasticsearchNode() { try { elasticsearchDirectory = File.createTempFile("elasticsearch-test", Long.toString(System.nanoTime())); elasticsearchDirectory.delete(); elasticsearchDirectory.mkdir(); } catch (IOException e) { throw new UncheckedIOException(e); } String clusterName = "test"; Settings setting = Settings.builder() .put("cluster.name", clusterName) .put("path.home", elasticsearchDirectory.getPath()) .put("path.data", new File(elasticsearchDirectory, "data").getAbsolutePath()) .put("path.logs", new File(elasticsearchDirectory, "logs").getAbsolutePath()) .put("transport.type.default", "local") .put("transport.type", "netty4") .put("http.type", "netty4") .put("http.enabled", "true") .put("path.home", "elasticsearch-test-data") .build(); node = new ElasticsearchNode(setting, Arrays.asList(Netty4Plugin.class)); }
Source:
<code>synchronized public String getPreviewOfLastMessage(){ if (mMessages.size() > 0){ return getLastMessage().getPreview(); } else{ <START> return ""; <END> } }</code><technical_language>Typically rewrite this a ternary op</technical_language>

Target:
synchronized public String getPreviewOfLastMessage(){ return mMessages.size() > 0 ? getLastMessage().getPreview() : ""; }
Source:
<code><START> void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket, boolean s3SelectPushdownEnabled) <END> { this.awsAccessKey = awsAccessKey; this.awsSecretKey = awsSecretKey; this.writableBucket = writableBucket; super.setup(host, port, databaseName, this::createHdfsConfiguration, s3SelectPushdownEnabled); }</code><technical_language>this protected this is called subclasses</technical_language>

Target:
protected void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket, boolean s3SelectPushdownEnabled) { checkArgument(!isNullOrEmpty(host), "Expected non empty host"); checkArgument(!isNullOrEmpty(databaseName), "Expected non empty databaseName"); checkArgument(!isNullOrEmpty(awsAccessKey), "Expected non empty awsAccessKey"); checkArgument(!isNullOrEmpty(awsSecretKey), "Expected non empty awsSecretKey"); checkArgument(!isNullOrEmpty(writableBucket), "Expected non empty writableBucket"); this.awsAccessKey = awsAccessKey; this.awsSecretKey = awsSecretKey; this.writableBucket = writableBucket; super.setup(host, port, databaseName, this::createHdfsConfiguration, s3SelectPushdownEnabled); }
Source:
<code>public static OrbotStatusReceiver getInstance() { <START> if(instance == null) instance = new OrbotStatusReceiver(); <END> return instance; }</code><technical_language>if else {}</technical_language>

Target:
public static OrbotStatusReceiver getInstance() { if(instance == null) { instance = new OrbotStatusReceiver(); } return instance; }
Source:
<code>public String getTechnicalCode() { <START> return "invalid-virtual-host"; <END> }</code><technical_language>please syntax other tech codes</technical_language>

Target:
public String getTechnicalCode() { return "virtualHost.invalid"; }
Source:
<code>private void initConfig(SystemProperties config) { logger.info("Running {}, core version: {}-{}", config.genesisInfo(), config.projectVersion(), config.projectVersionModifier()); BuildInfo.printInfo(); if (config.databaseReset()){ FileUtil.recursiveDelete(config.databaseDir()); logger.info("Database reset done"); } checkDatabaseVersion.validateDatabaseVersion(config); <START> if (config.getConfig().getBoolean("database.autoResetOldVersion")) { <END> FileUtil.recursiveDelete(config.databaseDir()); logger.info("Auto database reset due to not compatible database version"); } if (logger.isInfoEnabled()) { StringBuilder versions = new StringBuilder(); for (EthVersion v : EthVersion.supported()) { versions.append(v.getCode()).append(", "); } versions.delete(versions.length() - 2, versions.length()); logger.info("capability eth version: [{}]", versions); } logger.info("capability shh version: [{}]", ShhHandler.VERSION); logger.info("capability bzz version: [{}]", BzzHandler.VERSION); }</code><technical_language>resetting db if database.autoResetOldVersion == true ? I.e. database reset time starting. I missing smth</technical_language>

Target:
private void initConfig(SystemProperties config) { logger.info("Running {}, core version: {}-{}", config.genesisInfo(), config.projectVersion(), config.projectVersionModifier()); BuildInfo.printInfo(); if (config.databaseReset()){ FileUtil.recursiveDelete(config.databaseDir()); logger.info("Database reset done"); } databaseVersionHandler.process(config); if (logger.isInfoEnabled()) { StringBuilder versions = new StringBuilder(); for (EthVersion v : EthVersion.supported()) { versions.append(v.getCode()).append(", "); } versions.delete(versions.length() - 2, versions.length()); logger.info("capability eth version: [{}]", versions); } logger.info("capability shh version: [{}]", ShhHandler.VERSION); logger.info("capability bzz version: [{}]", BzzHandler.VERSION); }
Source:
<code>public void shouldFailFastIfNoDriverFound() { AtomicInteger connectionAttempts = new AtomicInteger(); <START> final JdbcDatabaseContainer container = new JdbcDatabaseContainer("mysql:5.7.22") { <END> @Override public String getDriverClassName() { return "nonexistent.ClassName"; } @Override public String getJdbcUrl() { return ""; } @Override public String getUsername() { return ""; } @Override public String getPassword() { return ""; } @Override protected String getTestQueryString() { return ""; } @Override public Connection createConnection(String queryString) throws SQLException, NoDriverFoundException { connectionAttempts.incrementAndGet(); return super.createConnection(queryString); } }; try { container.start(); fail("The container is expected to fail to start"); } catch (Exception e) { final Throwable rootCause = Throwables.getRootCause(e); assertTrue("ClassNotFoundException is the root cause", rootCause instanceof ClassNotFoundException); } finally { container.stop(); } assertEquals("only one connection attempt should have been made", 1, connectionAttempts.get()); }</code><technical_language>I extract a static class :)</technical_language>

Target:
public void shouldFailFastIfNoDriverFound() { final MissingDriverContainer container = new MissingDriverContainer(); try { container.start(); fail("The container is expected to fail to start"); } catch (Exception e) { final Throwable rootCause = Throwables.getRootCause(e); assertTrue("ClassNotFoundException is the root cause", rootCause instanceof ClassNotFoundException); } finally { container.stop(); } assertEquals("only one connection attempt should have been made", 1, container.getConnectionAttempts()); }
Source:
<code>public void loadBinderTypeRegistry() throws Exception { try { <START> ConfigurableApplicationContext context = createBinderTestContext( <END> new String[]{}); } catch (BeanCreationException e) { assertThat(e.getMessage(),containsString("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath")); } }</code><technical_language>add a fail() this line ensure Exception is thrown</technical_language>

Target:
public void loadBinderTypeRegistry() throws Exception { try { ConfigurableApplicationContext context = createBinderTestContext(new String[]{}); fail(); } catch (BeanCreationException e) { assertThat(e.getMessage(),containsString("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath")); } }
Source:
<code>private synchronized void checkExpired() { <START> if (timerID >= 0) { <END> long timestamp = System.currentTimeMillis(); endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp)); timerID = client.getVertx().setTimer(1, id -> checkExpired()); } }</code><technical_language>please elaborate of this checkExpired()? is expired, Is synchronized, is this a stop app synchronized. (If timeID, consider AtomicInteger ?). do think</technical_language>

Target:
private synchronized void checkExpired() { long timestamp = System.currentTimeMillis(); endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp)); timerID = client.getVertx().setTimer(1, id -> checkExpired()); }
Source:
<code>public static void setup() { FloatMixing.pumpWhen(QuasarHelios.globalControl, FloatMixing.addition.of((FloatInputPoll) spinOverride, motorSpeed), allRollers); Igneous.joystick3.getButtonSource(1).send(new EventOutput() { public void event() { frontRollers.set(1.0f); } <START> }); <END> Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Arm", armRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Front", frontRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Internal", internalRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Open", open); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtMost(pneumaticOverride, -0.3f)), Igneous.makeSolenoid(1)); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtLeast(pneumaticOverride, 0.3f)), Igneous.makeSolenoid(2)); }</code><technical_language>do this</technical_language>

Target:
public static void setup() { FloatMixing.pumpWhen(QuasarHelios.globalControl, FloatMixing.addition.of((FloatInputPoll) spinOverride, motorSpeed), allRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Arm", armRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Front", frontRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Internal", internalRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Open", open); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtMost(pneumaticOverride, -0.3f)), Igneous.makeSolenoid(1)); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtLeast(pneumaticOverride, 0.3f)), Igneous.makeSolenoid(2)); }
Source:
<code>public void highestCardWins() { String highest8 = "4D 5S 6S 8D 3C"; String highest10 = "2S 4C 7S 9H 10H"; String highestJ = "3S 4S 5D 6H JH"; <START> assertEquals(Arrays.asList(highestJ), new Poker(Arrays.asList(highest8, highest10, highestJ)).getBestHands()); <END> }</code><technical_language>This line is a bit long I add some linebreaks (120 chars is a common limit for long a line be). considered good practice put argument a new line if expression is long fit line. For example, in this case: assertEquals( Arrays.asList(highestJ), new Poker(Arrays.asList(highest8, highest10, highestJ)).getBestHands() );</technical_language>

Target:
public void highestCardWins() { String highest8 = "4D 5S 6S 8D 3C"; String highest10 = "2S 4C 7S 9H 10H"; String highestJ = "3S 4S 5D 6H JH"; assertEquals(Collections.singletonList(highestJ), new Poker(Arrays.asList(highest8, highest10, highestJ)).getBestHands()); }
Source:
<code>public final String lastString() { return lastValue().toString(); <START> } <END></code><technical_language>nextvalue() lastValue() null? this throw a NPE in case</technical_language>

Target:
public final String lastString() { V ret = lastValue(); return ret == null ? null : ret.toString(); }
Source:
<code>public int cancelObservations(Client client) { String registrationId = client.getRegistrationId(); if (registrationId == null) return 0; Set<Observation> observations = getObservations(registrationId); int removed = 0; for (Observation observation : observations) { <START> removed = doCancelObservation(observation) ? ++removed : removed; <END> } return removed; }</code><technical_language>mean: if (doCancelObservation(observation)) { removed++; }</technical_language>

Target:
public int cancelObservations(Client client) { String registrationId = client.getRegistrationId(); if (registrationId == null) return 0; Set<Observation> observations = getObservations(registrationId); int removed = 0; for (Observation observation : observations) { if (doCancelObservation(observation)) { removed++; } } return removed; }
Source:
<code>public SchedulerImpl( @Nonnull SlotSelectionStrategy slotSelectionStrategy, @Nonnull SlotPool slotPool, @Nonnull Map<SlotSharingGroupId, SlotSharingManager> slotSharingManagers) { this.slotSelectionStrategy = slotSelectionStrategy; this.slotSharingManagers = slotSharingManagers; this.slotPool = slotPool; this.componentMainThreadExecutor = new ComponentMainThreadExecutor.DummyComponentMainThreadExecutor( "Scheduler is not initialized with proper main thread executor. " + "Call to Scheduler.start(...) required."); this.slotRequestBulkChecker = PhysicalSlotRequestBulkCheckerImpl.fromSlotPool(slotPool, SystemClock.getInstance()); this.bulkSlotProvider = new BulkSlotProviderImpl(slotSelectionStrategy, slotPool, slotRequestBulkChecker); <START> this.physicalSlotProvider = new PhysicalSlotProviderImpl(slotSelectionStrategy, slotPool); <END> }</code><technical_language>PhysicalSlotProviderImpl ctor invoke slotPool.disableBatchSlotRequestTimeoutCheck() unconditionally. move invocation PhysicalSlotProviderImpl#requestNewSlot()</technical_language>

Target:
public SchedulerImpl( @Nonnull SlotSelectionStrategy slotSelectionStrategy, @Nonnull SlotPool slotPool, @Nonnull Map<SlotSharingGroupId, SlotSharingManager> slotSharingManagers) { this.slotSelectionStrategy = slotSelectionStrategy; this.slotSharingManagers = slotSharingManagers; this.slotPool = slotPool; this.componentMainThreadExecutor = new ComponentMainThreadExecutor.DummyComponentMainThreadExecutor( "Scheduler is not initialized with proper main thread executor. " + "Call to Scheduler.start(...) required."); }
Source:
<code>public void purgeConcept_shouldPurgeTheConceptIfNotBeingUsedByAnObs() throws Exception { conceptService.purgeConcept(conceptService.getConcept(88)); <START> assertNull(conceptService.getConcept(88)); <END> }</code><technical_language>@mavrk generally if reuse numbers/strings/... good create a local variable in test. this if id changes in test data change is needed here. this advice applied tests</technical_language>

Target:
public void purgeConcept_shouldPurgeTheConceptIfNotBeingUsedByAnObs() throws Exception { int conceptId = 88; conceptService.purgeConcept(conceptService.getConcept(conceptId)); assertNull(conceptService.getConcept(conceptId)); }
Source:
<code>public String getResourcesUrl() { <START> return getHostPortScheme(baseURI)+ getResourcesPath(); <END> }</code><technical_language>work is cleaner manually building hostname bit: Urls.themeRoot(baseURI).toString() + "/" + theme.getType().toString().toLowerCase() +"/" + theme.getName()</technical_language>

Target:
public String getResourcesUrl() { return Urls.themeRoot(baseURI).toString() + "/" + theme.getType().toString().toLowerCase() +"/" + theme.getName(); }
Source:
<code>Object listMoves() { Map<String, Boolean> moves = new HashMap<>(this.activeMoveRequests.size()); Iterator<Entry<String, MoveRequest>> moveIt = activeMoveRequests.entrySet().iterator(); while (moveIt.hasNext()) { Entry<String, MoveRequest> move = moveIt.next(); long finishedAt = move.getValue().finishedAt; if (finishedAt == -1 || finishedAt + TIME_TO_LIVE_AFTER_FINISH > System.currentTimeMillis()) { <START> moves.put(move.getKey(), finishedAt == -1); <END> } else { moveIt.remove(); } } return moves; }</code><technical_language>is difference moves a of false for a key pair present</technical_language>

Target:
Object listMoves() { Map<String, Object> results = new HashMap<>(2); List<String> active = new ArrayList<>(); List<String> complete = new ArrayList<>(); Iterator<Entry<String, MoveRequest>> moveIt = moveRequests.entrySet().iterator(); while (moveIt.hasNext()) { Entry<String, MoveRequest> move = moveIt.next(); long finishedAt = move.getValue().finishedAt; if (finishedAt == -1 || finishedAt + TIME_TO_LIVE_AFTER_FINISH > System.currentTimeMillis()) { if (finishedAt == -1) { active.add(move.getKey()); } else { complete.add(move.getKey()); } } else { moveIt.remove(); } } results.put("active", active); results.put("complete", complete); return results; }
Source:
<code>private SiriusServerDashboardDto getDashboard() { int projectsCount = this.getModelingProjects().mapToInt(e -> 1).sum(); int viewpointsCount = ViewpointRegistry.getInstance().getViewpoints().size(); List<SiriusServerDashboardProjectDto> projects = this.getModelingProjects() <START> .limit(8) <END> .map(this::convertToProject) .collect(Collectors.toList()); return new SiriusServerDashboardDto(projectsCount, viewpointsCount, projects); }</code><technical_language>number of project displayed in dashboard. I extracted this magic number in a constant</technical_language>

Target:
private SiriusServerDashboardDto getDashboard() { int projectsCount = this.getModelingProjects().mapToInt(e -> 1).sum(); int viewpointsCount = ViewpointRegistry.getInstance().getViewpoints().size(); int metamodelsCount = EPackage.Registry.INSTANCE.size(); List<SiriusServerDashboardProjectDto> projects = this.getModelingProjects() .limit(7) .map(this::convertToProject) .collect(Collectors.toList()); return new SiriusServerDashboardDto(projectsCount, viewpointsCount, metamodelsCount, projects); }
Source:
<code>protected IInteractionContext getContext() { <START> IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); <END> IEditorPart activeEditor = activePage.getActiveEditor(); IInteractionContext context = null; if (activeEditor != null && activePage.getActivePart().equals(activeEditor)) { context = (IInteractionContext) activeEditor.getEditorInput().getAdapter(IInteractionContext.class); } if (context == null && ContextCorePlugin.getContextManager().isContextActive()) { context = ContextCorePlugin.getContextManager().getActiveContext(); } if (context == null) { throw new IllegalStateException("error determining action context"); } return context; }</code><technical_language>check if active workbench window active page null</technical_language>

Target:
protected IInteractionContext getContext() { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IInteractionContext context = null; if (!(activeWorkbenchWindow == null || activeWorkbenchWindow.getActivePage() == null)) { IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage(); IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor != null && activePage.getActivePart().equals(activeEditor)) { context = (IInteractionContext) activeEditor.getEditorInput().getAdapter(IInteractionContext.class); } } if (context == null && ContextCorePlugin.getContextManager().isContextActive()) { context = ContextCorePlugin.getContextManager().getActiveContext(); } if (context == null) { throw new IllegalStateException("error determining action context"); } return context; }
Source:
<code>private static Optional<FileStoreAttributes> readFromConfig( FileStore s) { FileBasedConfig userConfig = SystemReader.getInstance() .openUserConfig(null, FS.DETECTED); try { <START> userConfig.load(); <END> } catch (IOException e) { LOG.error(MessageFormat.format(JGitText.get().readConfigFailed, userConfig.getFile().getAbsolutePath()), e); } catch (ConfigInvalidException e) { LOG.error(MessageFormat.format( JGitText.get().repositoryConfigFileInvalid, userConfig.getFile().getAbsolutePath(), e.getMessage())); } String key = getConfigKey(s); Duration resolution = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); if (UNDEFINED_DURATION.equals(resolution)) { return Optional.empty(); } Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); FileStoreAttributes c = new FileStoreAttributes(resolution); if (!UNDEFINED_DURATION.equals(minRacyThreshold)) { c.minimalRacyInterval = minRacyThreshold; } return Optional.of(c); }</code><technical_language>a package-private FileBasedConfig.load(boolean useFileSnapshotWithConfig) called "false". FileBasedConfig.load(boolean useFileSnapshotWithConfig) check: final FileSnapshot newSnapshot; if (useFileSnapshotWithConfig) { newSnapshot = FileSnapshot.save(getFile()); } else { newSnapshot = FileSnapshot.saveNoConfig(getFile()); } FileBasedConfig.load() call FileBasedConfig.load(true). This way, FileBasedConfig work userConfig read in FileStoreAttributes config options disabled break recursion</technical_language>

Target:
private static Optional<FileStoreAttributes> readFromConfig( FileStore s) { FileBasedConfig userConfig = SystemReader.getInstance() .openUserConfig(null, FS.DETECTED); try { userConfig.load(false); } catch (IOException e) { LOG.error(MessageFormat.format(JGitText.get().readConfigFailed, userConfig.getFile().getAbsolutePath()), e); } catch (ConfigInvalidException e) { LOG.error(MessageFormat.format( JGitText.get().repositoryConfigFileInvalid, userConfig.getFile().getAbsolutePath(), e.getMessage())); } String key = getConfigKey(s); Duration resolution = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); if (UNDEFINED_DURATION.equals(resolution)) { return Optional.empty(); } Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); FileStoreAttributes c = new FileStoreAttributes(resolution); if (!UNDEFINED_DURATION.equals(minRacyThreshold)) { c.minimalRacyInterval = minRacyThreshold; } return Optional.of(c); }
Source:
<code>public ParquetTupleScheme(FilterPredicate filterPredicate) { <START> this.filterPredicate = Objects.requireNonNull(filterPredicate, "filterPredicate"); <END> }</code><technical_language>Put a more explicit error message</technical_language>

Target:
public ParquetTupleScheme(FilterPredicate filterPredicate) { this.filterPredicate = Objects.requireNonNull(filterPredicate, "filterPredicate cannot be null"); }
Source:
<code>protected void writeToFile(String data) { Connection conn = null; try { conn = DriverManager.getConnection(dbUrl); } catch (SQLException e) { e.printStackTrace(); } try { Statement sta = conn.createStatement(); String payload = "CREATE TABLE PROPERTIES (Name VARCHAR(100), Type VARCHAR(20), Value VARCHAR(50))"; <START> int count = sta.executeUpdate(payload); <END> sta.close(); } catch (SQLException e) { } String[] splitData = data.split(lineSeperator); for (String line : splitData) { String[] values = line.split(propertyDelimiter); String payload = "UPDATE PROPERTIES SET TYPE='" + values[0] + "', VALUE='" + values[2] + "' WHERE NAME = '" + values[1] + "'"; Statement sta; try { sta = conn.createStatement(); int count = sta.executeUpdate(payload); if (count == 0) { payload = "INSERT INTO PROPERTIES VALUES ('" + values[1] + "', '" + values[0] + "', '" + values[2] + "')"; Statement insert = conn.createStatement(); count = insert.executeUpdate(payload); } } catch (SQLException e) { e.printStackTrace(); } } }</code><technical_language>If validating create database count variable, remove it, it</technical_language>

Target:
protected void writeToFile(String data) { Connection conn = null; try { conn = DriverManager.getConnection(dbUrl); } catch (SQLException e) { e.printStackTrace(); } try { Statement sta = conn.createStatement(); String payload = "CREATE TABLE PROPERTIES (Name VARCHAR(100), Type VARCHAR(20), Value VARCHAR(50))"; sta.executeUpdate(payload); sta.close(); } catch (SQLException e) { } String[] splitData = data.split(lineSeperator); for (String line : splitData) { String[] values = line.split(propertyDelimiter); String payload = "UPDATE PROPERTIES SET TYPE='" + values[0] + "', VALUE='" + values[2] + "' WHERE NAME = '" + values[1] + "'"; Statement sta; try { sta = conn.createStatement(); int count = sta.executeUpdate(payload); if (count == 0) { payload = "INSERT INTO PROPERTIES VALUES ('" + values[1] + "', '" + values[0] + "', '" + values[2] + "')"; Statement insert = conn.createStatement(); count = insert.executeUpdate(payload); } } catch (SQLException e) { e.printStackTrace(); } } }
Source:
<code>private void runUserRestrictionsChange( boolean currentDisallow, boolean nextDisallow, String[] activeTetheringIfacesList, int expectedInteractionsWithShowNotification) throws Exception { final Bundle newRestrictions = new Bundle(); newRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_TETHERING, nextDisallow); final Tethering mockTethering = mock(Tethering.class); when(mockTethering.getTetheredIfaces()).thenReturn(activeTetheringIfacesList); when(mUserManager.getUserRestrictions()).thenReturn(newRestrictions); final Tethering.UserRestrictionActionListener ural = new Tethering.UserRestrictionActionListener( mUserManager, mockTethering, mNotificationUpdater); ural.mDisallowTethering = currentDisallow; ural.onUserRestrictionsChanged(); verify(mNotificationUpdater, times(expectedInteractionsWithShowNotification)) .notifyTetheringDisabledByRestriction(); final boolean hasActiveTetheringIfaces = activeTetheringIfacesList.length > 0; verify(mockTethering, <START> times(hasActiveTetheringIfaces ? expectedInteractionsWithShowNotification : 0)) <END> .untetherAll(); }</code><technical_language>This ad-hoc difficult understand caller. unify code paths</technical_language>

Target:
private void runUserRestrictionsChange( boolean currentDisallow, boolean nextDisallow, String[] activeTetheringIfacesList, int expectedInteractionsWithShowNotification) throws Exception { final Bundle newRestrictions = new Bundle(); newRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_TETHERING, nextDisallow); final Tethering mockTethering = mock(Tethering.class); when(mockTethering.getTetheredIfaces()).thenReturn(activeTetheringIfacesList); when(mUserManager.getUserRestrictions()).thenReturn(newRestrictions); final Tethering.UserRestrictionActionListener ural = new Tethering.UserRestrictionActionListener( mUserManager, mockTethering, mNotificationUpdater); ural.mDisallowTethering = currentDisallow; ural.onUserRestrictionsChanged(); verify(mNotificationUpdater, times(expectedInteractionsWithShowNotification)) .notifyTetheringDisabledByRestriction(); verify(mockTethering, times(expectedInteractionsWithShowNotification)).untetherAll(); }