auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private TestResult runAll4x() throws Exception { List<String> testClassNames = new ArrayList<>(); Files.walk(Paths.get(projectPath, "target", "test-classes")).forEach(filePath -> { if (Files.isRegularFile(filePath) && filePath.toString().toLowerCase().endsWith(".class")) { String path = Paths.get(projectPath, "target", "test-classes").relativize(filePath).toString(); <START> String className = path.replace('/', '.'); <END> className = className.replace('\\', '.'); className = className.substring(0, className.length() - 6); testClassNames.add(className); } }); List<Class> testableClasses = new ArrayList<>(); for (String className : testClassNames) { Class<?> clazz = Class.forName(className, false, projectClassLoader); if (isTestable4x(clazz)) { testableClasses.add(clazz); } } return run4xTestClasses(testableClasses.toArray(new Class[testableClasses.size()])); }</code><technical_language>file separator? BTW here</technical_language>

Target:
private TestResult runAll4x() throws Exception { List<String> testClassNames = new ArrayList<>(); Files.walk(Paths.get(projectPath, "target", "test-classes")).forEach(filePath -> { if (Files.isRegularFile(filePath) && filePath.toString().toLowerCase().endsWith(".class")) { String path = Paths.get(projectPath, "target", "test-classes").relativize(filePath).toString(); String className = path.replace(File.separatorChar, '.'); className = className.substring(0, className.length() - 6); testClassNames.add(className); } }); List<Class> testableClasses = new ArrayList<>(); for (String className : testClassNames) { Class<?> clazz = Class.forName(className, false, projectClassLoader); if (isTestable4x(clazz)) { testableClasses.add(clazz); } } return run4xTestClasses(testableClasses.toArray(new Class[testableClasses.size()])); }
Source:
<code>public String render(Model model, @SiteParam Site site, @PathVariable String sourcePage, @RequestParam(value="defaultTarget", required = false) String defaultTarget) throws IOException { Map<String, Object> redirectMap = site.getTheme().getConfigMap("redirects"); JSONObject redirects = new JSONObject(); redirects.accumulateAll(redirectMap); <START> model.addAttribute("redirects", redirects.toString()); <END> model.addAttribute("sourcePage", sourcePage); model.addAttribute("defaultTarget", defaultTarget != null ? defaultTarget : sourcePage); return site + "/ftl/redirect"; }</code><technical_language>I thought wanted code list of redirects a JavaScript constant in order avoid this sort of middle-tier support? if a redirectList.ftl javascript var redirects = {}; in webapp override actual stuff in plos-themes</technical_language>

Target:
public String render(Model model, @SiteParam Site site, @PathVariable String sourcePage, @RequestParam(value="defaultTarget", required = false) String defaultTarget) throws IOException { model.addAttribute("sourcePage", sourcePage); model.addAttribute("defaultTarget", defaultTarget != null ? defaultTarget : sourcePage); return site + "/ftl/redirect"; }
Source:
<code>public List<GroupRepresentation> getGroups(@QueryParam("search") String search, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) { auth.groups().requireList(); List<GroupModel> results; if (Objects.nonNull(search)) { <START> results = realm.searchForGroupByName(search.trim(),null, null); <END> } else { results = realm.getTopLevelGroups(); } List<GroupRepresentation> ret = results.stream() .map(group -> ModelToRepresentation.toGroupHierarchy(group, false)) .collect(Collectors.toList()); return checkGroupsPermissions(ret); }</code><technical_language>"firstResult, maxResults" instead of "null, null"</technical_language>

Target:
public List<GroupRepresentation> getGroups(@QueryParam("search") String search, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) { auth.groups().requireList(); List<GroupRepresentation> results; if (auth.users().canView()) { if (Objects.nonNull(search)) { results = ModelToRepresentation.searchForGroupByName(realm, search.trim(), firstResult, maxResults); } else if(Objects.nonNull(firstResult) && Objects.nonNull(maxResults)) { results = ModelToRepresentation.toGroupHierarchy(realm, false, firstResult, maxResults); } else { results = ModelToRepresentation.toGroupHierarchy(realm, false); } } else { Set<String> groups = auth.groups().getGroupsWithViewPermission(); Stream<String> s = groups.stream(); if (search!=null) s=s.filter(group->group.contains(search.trim())); if (firstResult != null) s=s.skip(firstResult); if (maxResults != null) s=s.limit(maxResults); results = s .map(group -> ModelToRepresentation.toGroupHierarchy(session.realms().getGroupById(group, session.getContext().getRealm()),false)) .collect(Collectors.toList()); } return results; }
Source:
<code>public Client( final String packageName, final ImmutableList<Command> commands) { this.packageName = packageName; this.commands = commands; helper = Helper.getInstance(); <START> javaHelper = JavaHelper.getInstance(); <END> }</code><technical_language>Instead of instance here, passed in in event want mock it</technical_language>

Target:
public Client( final String packageName, final ImmutableList<Command> commands) { this.packageName = packageName; this.commands = commands; }
Source:
<code>private String serializePersistenceAdapterStatistics() { if (persistenceAdapterStatistics != null) { try { <START> final ObjectMapper mapper = new ObjectMapper(); <END> Map<String, Object> result = new HashMap<String, Object>(); result.put("writeTime", getTimeStatisticAsMap(persistenceAdapterStatistics.getWriteTime())); result.put("readTime", getTimeStatisticAsMap(persistenceAdapterStatistics.getReadTime())); return mapper.writeValueAsString(result); } catch (IOException e) { return e.toString(); } } return null; }</code><technical_language>ObjectMapper is threadsafe create time for class need re-create over</technical_language>

Target:
private String serializePersistenceAdapterStatistics() { if (persistenceAdapterStatistics != null) { try { Map<String, Object> result = new HashMap<String, Object>(); result.put("writeTime", getTimeStatisticAsMap(persistenceAdapterStatistics.getWriteTime())); result.put("readTime", getTimeStatisticAsMap(persistenceAdapterStatistics.getReadTime())); return mapper.writeValueAsString(result); } catch (IOException e) { return e.toString(); } } return null; }
Source:
<code>public void testConcurrentViewCreationAndTableDrop() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl()); Statement stmt = conn.createStatement()) { String fullTableName = SchemaUtil.getTableName(SCHEMA1, generateUniqueName()); String fullViewName1 = SLOW_VIEWNAME_PREFIX + "_" + generateUniqueName(); latch1 = new CountDownLatch(1); latch2 = new CountDownLatch(1); String tableDdl = "CREATE TABLE " + fullTableName + " (k INTEGER NOT NULL PRIMARY KEY, v1 INTEGER, v2 INTEGER)" + tableDDLOptions; stmt.execute(tableDdl); <START> ExecutorService executorService = Executors.newFixedThreadPool( 1, new ThreadFactory() { <END> @Override public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); t.setPriority(Thread.MIN_PRIORITY); return t; } }); slowDownAddingChildLink = true; Future<Exception> future = executorService.submit( new CreateViewRunnable(fullTableName, fullViewName1)); latch1.await(); tableDdl = "DROP TABLE " + fullTableName; slowDownAddingChildLink = false; stmt.execute(tableDdl); latch2.countDown(); Exception e = future.get(); assertTrue("Expected TableNotFoundException since drop table" + " goes through first", e instanceof TableNotFoundException && fullTableName.equals(((TableNotFoundException) e) .getTableName())); } }</code><technical_language>nit: newSingleThreadExecutor() instead? (for similar places in this file)</technical_language>

Target:
public void testConcurrentViewCreationAndTableDrop() throws Exception { try (Connection conn = DriverManager.getConnection(getUrl()); Statement stmt = conn.createStatement()) { String fullTableName = SchemaUtil.getTableName(SCHEMA1, generateUniqueName()); String fullViewName1 = SLOW_VIEWNAME_PREFIX + "_" + generateUniqueName(); latch1 = new CountDownLatch(1); latch2 = new CountDownLatch(1); String tableDdl = "CREATE TABLE " + fullTableName + " (k INTEGER NOT NULL PRIMARY KEY, v1 INTEGER, v2 INTEGER)" + tableDDLOptions; stmt.execute(tableDdl); ExecutorService executorService = newSingleThreadExecutor( new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); t.setPriority(Thread.MIN_PRIORITY); return t; } }); slowDownAddingChildLink = true; Future<Exception> future = executorService.submit( new CreateViewRunnable(fullTableName, fullViewName1)); latch1.await(); tableDdl = "DROP TABLE " + fullTableName; slowDownAddingChildLink = false; stmt.execute(tableDdl); latch2.countDown(); Exception e = future.get(); assertTrue("Expected TableNotFoundException since drop table" + " goes through first", e instanceof TableNotFoundException && fullTableName.equals(((TableNotFoundException) e) .getTableName())); } }
Source:
<code>public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.MANA_PAID) { if (event.getData() != null && event.getData().equals(originalId.toString())) { <START> spells.put(event.getTargetId(), game.getObject(event.getTargetId()).getZoneChangeCounter(game)); <END> } } }</code><technical_language>Missing null check for game.getObject(event.getTargetId())</technical_language>

Target:
public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.MANA_PAID) { if (event.getData() != null && event.getData().equals(originalId.toString()) && event.getTargetId() != null) { spells.add(new MageObjectReference(game.getObject(event.getTargetId()), game)); } } }
Source:
<code>private void initCommonParams(LogReplicationMetadataManager metadataManager, LogReplicationConfig config) { <START> this.logReplicationMetadataManager = metadataManager; <END> this.config = config; this.rxState = RxState.LOG_ENTRY_SYNC; logReplicationMetadataManager.setDataConsistentOnStandby(String.valueOf(dataConsistent.get())); initWriterAndBufferMgr(); }</code><technical_language>init topologyConfigId in this function</technical_language>

Target:
private void initCommonParams(LogReplicationMetadataManager metadataManager, LogReplicationConfig config) { this.logReplicationMetadataManager = metadataManager; this.config = config; this.rxState = RxState.LOG_ENTRY_SYNC; setDataConsistent(dataConsistent.get()); initWriterAndBufferMgr(); }
Source:
<code>protected void initUserGroupCache() { String userRolesCacheEnabledString = (realmConfig .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_ROLES_CACHE_ENABLED)); String userCoreCacheIdentifier = realmConfig .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_USER_CORE_CACHE_IDENTIFIER); <START> if (userCoreCacheIdentifier != null && userCoreCacheIdentifier.trim().length() > 0) { <END> cacheIdentifier = userCoreCacheIdentifier; } else { cacheIdentifier = UserCoreConstants.DEFAULT_CACHE_IDENTIFIER; } if (userRolesCacheEnabledString != null && !userRolesCacheEnabledString.equals("")) { userRolesCacheEnabled = Boolean.parseBoolean(userRolesCacheEnabledString); if (log.isDebugEnabled()) { log.debug("User Roles Cache is configured to:" + userRolesCacheEnabledString); } } else { if (log.isDebugEnabled()) { log.info("User Roles Cache is not configured. Default value: " + userRolesCacheEnabled + " is taken."); } } if (userRolesCacheEnabled) { int timeOut = UserCoreConstants.USER_ROLE_CACHE_DEFAULT_TIME_OUT; String timeOutString = realmConfig. getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_USER_ROLE_CACHE_TIME_OUT); if (timeOutString != null) { timeOut = Integer.parseInt(timeOutString); } userGroupCache = userGroupCache.getInstance(); userGroupCache.setTimeOut(timeOut); } }</code><technical_language>suggestion if (StringUtils.isNotBlank(userCoreCacheIdentifier)) {</technical_language>

Target:
protected void initUserGroupCache() { String userRolesCacheEnabledString = (realmConfig .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_ROLES_CACHE_ENABLED)); String userCoreCacheIdentifier = realmConfig .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_USER_CORE_CACHE_IDENTIFIER); if (StringUtils.isNotBlank(userCoreCacheIdentifier)) { cacheIdentifier = userCoreCacheIdentifier; } else { cacheIdentifier = UserCoreConstants.DEFAULT_CACHE_IDENTIFIER; } if (StringUtils.isNotBlank(userRolesCacheEnabledString)) { userRolesCacheEnabled = Boolean.parseBoolean(userRolesCacheEnabledString); if (log.isDebugEnabled()) { log.debug("User Roles Cache is configured to:" + userRolesCacheEnabledString); } } else { if (log.isDebugEnabled()) { log.info("User Roles Cache is not configured. Default value: " + userRolesCacheEnabled + " is taken."); } } if (userRolesCacheEnabled) { int timeOut = UserCoreConstants.USER_ROLE_CACHE_DEFAULT_TIME_OUT; String timeOutString = realmConfig. getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_USER_ROLE_CACHE_TIME_OUT); if (timeOutString != null) { timeOut = Integer.parseInt(timeOutString); } userGroupCache = userGroupCache.getInstance(); userGroupCache.setTimeOut(timeOut); } }
Source:
<code>public StackedMutationContainer(final BucketCache buckets, final Set<Sequence> visibleSequences) { <START> this.level = (int) (Math.log(buckets.getNumberBuckets()) / Math.log(2) + 1); <END> fillStackedMutationContainer(this.level, buckets, visibleSequences); }</code><technical_language>Rounding errors induce unexpected behaviour</technical_language>

Target:
public StackedMutationContainer(final BucketCache buckets, final Set<Sequence> visibleSequences) { this.level = (int) Math.round(Math.log(buckets.getNumberBuckets()) / Math.log(2) + 1); fillStackedMutationContainer(this.level, buckets, visibleSequences); }
Source:
<code>protected VDSReturnValue performImageVdsmOperation() { boolean isShouldBeLocked = getParameters().getPerformDbOperationsStage() != PerformOperationStage.NEVER && getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport <START> && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport; <END> if (isShouldBeLocked) { getDiskImage().setImageStatus(ImageStatus.ILLEGAL); lockImageWithCompensation(); } freeLock(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.DeleteImageGroup, new DeleteImageGroupVDSCommandParameters(getDiskImage().getStoragePoolId().getValue(), getStorageDomainId().getValue(), getDiskImage().getId() .getValue(), getDiskImage().isWipeAfterDelete(), getParameters() .getForceDelete(), getStoragePool().getcompatibility_version().toString())); return returnValue; }</code><technical_language>do a condition getParentCommand()</technical_language>

Target:
protected VDSReturnValue performImageVdsmOperation() { boolean isShouldBeLocked = getParameters().getPerformDbOperationsStage() != PerformOperationsStage.NEVER && getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport; if (isShouldBeLocked) { getDiskImage().setImageStatus(ImageStatus.ILLEGAL); lockImageWithCompensation(); } VDSReturnValue returnValue = runVdsCommand(VDSCommandType.DeleteImageGroup, new DeleteImageGroupVDSCommandParameters(getDiskImage().getStoragePoolId().getValue(), getStorageDomainId().getValue(), getDiskImage().getId() .getValue(), getDiskImage().isWipeAfterDelete(), getParameters() .getForceDelete(), getStoragePool().getcompatibility_version().toString())); return returnValue; }
Source:
<code>public String getGatewayPublishedAPIArtifacts(String APIId, String gatewayLabel, String gatewayInstruction) throws APIManagementException { String gatewayRuntimeArtifacts = null; <START> try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection(); <END> PreparedStatement statement = connection.prepareStatement(SQLConstants.GET_API_ARTIFACT)) { statement.setString(1, APIId); statement.setString(2, gatewayLabel); statement.setString(3, gatewayInstruction); ResultSet rs = statement.executeQuery(); if (rs.next()) { try (InputStream inputStream = rs.getBinaryStream(1)) { gatewayRuntimeArtifacts = IOUtils.toString(inputStream, APIConstants.DigestAuthConstants.CHARSET); } catch (IOException e){ handleException("Error in generating gatewayRuntimeArtifacts " + APIId, e); } } } catch (SQLException e) { handleException("Failed to get artifacts of API with ID " + APIId, e); } return gatewayRuntimeArtifacts; }</code><technical_language>a practice a good idea call commit a connection is returned pool performing a SELECT operation. This ensures uncommitted data returned DB. pattern be, try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection(); connection.setAutoCommit(false); connection.commit(); PreparedStatement statement = connection.prepareStatement("SELECT ...")) { }</technical_language>

Target:
public String getGatewayPublishedAPIArtifacts(String APIId, String gatewayLabel, String gatewayInstruction) throws APIManagementException { ResultSet rs = null; String gatewayRuntimeArtifacts = null; try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection(); PreparedStatement statement = connection.prepareStatement(SQLConstants.GET_API_ARTIFACT)) { connection.setAutoCommit(false); connection.commit(); statement.setString(1, APIId); statement.setString(2, gatewayLabel); statement.setString(3, gatewayInstruction); rs = statement.executeQuery(); if (rs.next()) { try (InputStream inputStream = rs.getBinaryStream(1)) { gatewayRuntimeArtifacts = IOUtils.toString(inputStream, APIConstants.DigestAuthConstants.CHARSET); } catch (IOException e){ handleException("Error in generating gatewayRuntimeArtifacts " + APIId, e); } } } catch (SQLException e) { handleException("Failed to get artifacts of API with ID " + APIId, e); } finally { GatewayArtifactsMgtDBUtil.closeResultSet(rs); } return gatewayRuntimeArtifacts; }
Source:
<code>private List<Properties> createKerberosLdapConfigurations() { List<Properties> results = new ArrayList<>(); <START> for (String domain : LdapBrokerUtils.getDomainsList(true)) { <END> Properties authConfig = new Properties(); authConfig.put(ExtensionManager.CLASS, "org.ovirt.extensions.builtin.ldapkerberos.LdapKerberosAuthenticator"); authConfig.put(ExtensionManager.PROVIDES, "org.ovirt.engine.core.authentication"); authConfig.put(ExtensionManager.ENABLED, true); authConfig.put(ExtensionManager.MODULE, "org.ovirt.engine.extensions.builtin"); authConfig.put(ExtensionManager.NAME, String.format("builtin-authn-%1$s", domain)); authConfig.put("org.ovirt.engine.aaa.authn.profile.name", domain); authConfig.put("ovirt.engine.aaa.authn.authz.plugin", String.format("builitin-authz-%1$s", domain)); results.add(authConfig); Properties dirConfig = new Properties(); dirConfig.put(ExtensionManager.CLASS, "org.ovirt.extensions.builtin.ldapkerberos.LdapKerberosDirectory"); dirConfig.put(ExtensionManager.PROVIDES, "org.ovirt.engine.core.authorization"); dirConfig.put(ExtensionManager.ENABLED, true); dirConfig.put(ExtensionManager.MODULE, "org.ovirt.engine.extensions.builtin"); dirConfig.put(ExtensionManager.NAME, String.format("builtin-authz-%1$s", domain)); dirConfig.put("org.ovirt.engine.aaa.authz.profile.name", domain); results.add(authConfig); } return results; }</code><technical_language>vdc_options directly</technical_language>

Target:
private List<Properties> createKerberosLdapConfigurations() { List<Properties> results = new ArrayList<>(); for (String domain : Config.<String> getValue(ConfigValues.DomainName).split("[,]", -1)) { Properties authConfig = new Properties(); authConfig.put(ExtensionManager.CLASS, "org.ovirt.engine.extensions.aaa.builtin.kerberosldap.KerberosLdapAuthenticator"); authConfig.put(ExtensionManager.PROVIDES, "org.ovirt.engine.core.authentication"); authConfig.put(ExtensionManager.ENABLED, "true"); authConfig.put(ExtensionManager.MODULE, "org.ovirt.engine.extensions.builtin"); authConfig.put(ExtensionManager.NAME, String.format("builtin-authn-%1$s", domain)); authConfig.put("ovirt.engine.aaa.authn.profile.name", domain); authConfig.put("ovirt.engine.aaa.authn.authz.plugin", String.format("builtin-authz-%1$s", domain)); results.add(authConfig); Properties dirConfig = new Properties(); dirConfig.put(ExtensionManager.CLASS, "org.ovirt.engine.extensions.aaa.builtin.kerberosldap.KerberosLdapDirectory"); dirConfig.put(ExtensionManager.PROVIDES, "org.ovirt.engine.core.authorization"); dirConfig.put(ExtensionManager.ENABLED, "true"); dirConfig.put(ExtensionManager.MODULE, "org.ovirt.engine.extensions.builtin"); dirConfig.put(ExtensionManager.NAME, String.format("builtin-authz-%1$s", domain)); dirConfig.put("ovirt.engine.aaa.authz.profile.name", domain); results.add(dirConfig); } return results; }
Source:
<code>public void run() { CompoundCommand updateCmd = new CompoundCommand(); for(Object obj : getSelectedObjects()){ if (obj instanceof AbstractFBNElementEditPart) { <START> UpdateFBTypeCommand cmd; cmd = new UpdateFBTypeCommand(((AbstractFBNElementEditPart) obj).getModel(), entry); <END> if (cmd.canExecute()) { updateCmd.add(cmd); } } } execute(updateCmd); }</code><technical_language>merged line</technical_language>

Target:
public void run() { CompoundCommand updateCmd = new CompoundCommand(); for(Object obj : getSelectedObjects()){ if (obj instanceof AbstractFBNElementEditPart) { UpdateFBTypeCommand cmd = new UpdateFBTypeCommand(((AbstractFBNElementEditPart) obj).getModel(), entry); if (cmd.canExecute()) { updateCmd.add(cmd); } } } execute(updateCmd); }
Source:
<code>public void writeToXml(PrintWriter pw1, int indent) { writeToXmlBegin(pw1, indent); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "equipmentNum", equipmentNum); <START> MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "typeName", MekHqXmlUtil.escape(type.getInternalName())); <END> MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "size", size); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "equipTonnage", equipTonnage); writeToXmlEnd(pw1, indent); }</code><technical_language>suggestion MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "typeName", type.getInternalName());</technical_language>

Target:
public void writeToXml(PrintWriter pw1, int indent) { writeToXmlBegin(pw1, indent); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "equipmentNum", equipmentNum); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "typeName", type.getInternalName()); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "size", size); MekHqXmlUtil.writeSimpleXmlTag(pw1, indent + 1, "equipTonnage", equipTonnage); writeToXmlEnd(pw1, indent); }
Source:
<code>public void getSubstudyIds() { SUBSTUDIES.get(0).setId("substudyA"); <START> SUBSTUDIES.get(1).setId("substudyB"); <END> when(substudyDao.getSubstudies(TestConstants.TEST_STUDY, false)).thenReturn(SUBSTUDIES); Set<String> substudyIds = service.getSubstudyIds(TestConstants.TEST_STUDY); assertEquals(TestConstants.USER_SUBSTUDY_IDS, substudyIds); }</code><technical_language>modifying constants. If constants, statically initialized changed. If constants, create in before() ensure reset test</technical_language>

Target:
public void getSubstudyIds() { Substudy substudyA = Substudy.create(); substudyA.setId("substudyA"); Substudy substudyB = Substudy.create(); substudyB.setId("substudyB"); List<Substudy> substudies = ImmutableList.of(substudyA, substudyB); when(substudyDao.getSubstudies(TestConstants.TEST_STUDY, false)).thenReturn(substudies); Set<String> substudyIds = service.getSubstudyIds(TestConstants.TEST_STUDY); assertEquals(TestConstants.USER_SUBSTUDY_IDS, substudyIds); }
Source:
<code>public long nextIvl(Card card, int ease) { if (_previewingCard(card)) { if (ease == 1) { return _previewDelay(card); } return 0; } if (card.getQueue() == 0 || card.getQueue() == 1 || card.getQueue() == 3) { return _nextLrnIvl(card, ease); } else if (ease == 1) { JSONObject conf = _lapseConf(card); if (conf.getJSONArray("delays").length() > 0) { return (long) (conf.getJSONArray("delays").getDouble(0) * 60.0); } return _lapseIvl(card, conf) * 86400L; } else { boolean early = card.getODid() != 0 && (card.getODue() > mToday); if (early) { <START> return _earlyReviewIvl(card, ease) * 86400; <END> } else { return _nextRevIvl(card, ease, false) * 86400L; } } }</code><technical_language>I this is a problem is related some review bug recently? 'L' 'L'</technical_language>

Target:
public long nextIvl(Card card, int ease) { if (_previewingCard(card)) { if (ease == Consts.BUTTON_ONE) { return _previewDelay(card); } return 0; } if (card.getQueue() == Consts.QUEUE_TYPE_NEW || card.getQueue() == Consts.QUEUE_TYPE_LRN || card.getQueue() == Consts.QUEUE_TYPE_DAY_LEARN_RELEARN) { return _nextLrnIvl(card, ease); } else if (ease == Consts.BUTTON_ONE) { JSONObject conf = _lapseConf(card); if (conf.getJSONArray("delays").length() > 0) { return (long) (conf.getJSONArray("delays").getDouble(0) * 60.0); } return _lapseIvl(card, conf) * 86400L; } else { boolean early = card.getODid() != 0 && (card.getODue() > mToday); if (early) { return _earlyReviewIvl(card, ease) * 86400L; } else { return _nextRevIvl(card, ease, false) * 86400L; } } }
Source:
<code>public Optimizer() { <START> this(5,SearchMethodName.BLINDSEARCH,0.5); <END> }</code><technical_language>Constants, for example DAFAULT_NUMBER_OF_PLANS_GENERATED = 5</technical_language>

Target:
public Optimizer() { this(DEFAULT_NUMBER_OF_PLANS_GENERATED,SearchMethodName.BLINDSEARCH,DEFAULT_HYSTERESIS_PROPORTION); }
Source:
<code>public void setUp() throws Exception { <START> dashboard.open(); <END> createWsFromJavaMySqlStack(); }</code><technical_language>this command **dashboard.open()** redundant here. code clear I propose move **dashboard.open()** command **createWsFromJavaMySqlStack()** method, set **@BeforeClass** annotation remove **setUp()** method all</technical_language>

Target:
public void setUp() throws Exception { createMaps(); createWsFromJavaMySqlStack(); }
Source:
<code>private void proceedDisappearedVm() { if (System.nanoTime() - getVmManager().getPowerOffTimeout() < 0) { auditVmOnDownNormal(true); clearVm(VmExitStatus.Normal, getPowerOffExitMessage(), VmExitReason.Success); <START> resourceManager.removeAsyncRunningVm(dbVm.getId()); <END> return; } switch (dbVm.getStatus()) { case MigratingFrom: if (dbVm.getMigratingToVds() != null) { handOverVm(); break; } abortVmMigration(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", getVmManager().getName()), VmExitReason.GenericError); break; case PoweringDown: clearVm(VmExitStatus.Normal, String.format("VM %s shutdown complete", getVmManager().getName()), VmExitReason.Success); if (getVmManager().isColdReboot()) { setColdRebootFlag(); } break; default: clearVm(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", getVmManager().getName()), VmExitReason.GenericError); if (resourceManager.isVmInAsyncRunningList(dbVm.getId())) { setRerunFlag(); break; } if (getVmManager().isColdReboot()) { setColdRebootFlag(); break; } if (getVmManager().isAutoStart()) { setAutoRunFlag(); break; } } }</code><technical_language>this line moved up, too</technical_language>

Target:
private void proceedDisappearedVm() { if (System.nanoTime() - getVmManager().getPowerOffTimeout() < 0) { auditVmOnDownNormal(true); resourceManager.removeAsyncRunningVm(dbVm.getId()); clearVm(VmExitStatus.Normal, getPowerOffExitMessage(), VmExitReason.Success); return; } switch (dbVm.getStatus()) { case MigratingFrom: if (dbVm.getMigratingToVds() != null) { handOverVm(); break; } abortVmMigration(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", getVmManager().getName()), VmExitReason.GenericError); break; case PoweringDown: clearVm(VmExitStatus.Normal, String.format("VM %s shutdown complete", getVmManager().getName()), VmExitReason.Success); if (getVmManager().isColdReboot()) { setColdRebootFlag(); } break; default: clearVm(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", getVmManager().getName()), VmExitReason.GenericError); if (resourceManager.isVmInAsyncRunningList(dbVm.getId())) { setRerunFlag(); break; } if (getVmManager().isColdReboot()) { setColdRebootFlag(); break; } if (getVmManager().isAutoStart()) { setAutoRunFlag(); break; } } }
Source:
<code>public void testDisks() throws IOException { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); <START> if (hal.getDisksStores().length > 1) { <END> assertNotNull(hal.getDisksStores()[0].getName()); assertNotNull(hal.getDisksStores()[0].getModel()); assertNotNull(hal.getDisksStores()[0].getSerial()); assertNotNull(hal.getDisksStores()[0].getSize()); assertNotNull(hal.getDisksStores()[0].getReads()); assertNotNull(hal.getDisksStores()[0].getWrites()); } }</code><technical_language>Change this conditional iterate a counter 0 length, check counter 0 in lines below</technical_language>

Target:
public void testDisks() throws IOException { SystemInfo si = new SystemInfo(); for (HWDiskStore disk : si.getHardware().getDisksStores()) { assertNotNull(disk.getName()); assertNotNull(disk.getModel()); assertNotNull(disk.getSerial()); assertNotNull(disk.getSize()); assertNotNull(disk.getReads()); assertNotNull(disk.getWrites()); } }
Source:
<code><START> KeyType(String alg, int keySize){ <END> this.alg = alg; this.keySize = keySize; }</code><technical_language>for KeyPairType constructors</technical_language>

Target:
private KeyType(String alg, int keySize){ this.alg = alg; this.keySize = keySize; this.ivSize = keySize; }
Source:
<code>private String getPrivateKeyAlias(final KeyStore keyStore, final String keyStoreAlias) { try { final Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); if (keyStoreAlias == null) { return currentAlias; <START> } else if (currentAlias.equals(keyStoreAlias)) { <END> return currentAlias; } } throw new SAMLException("Keystore has no private keys"); } catch (final KeyStoreException e) { throw new SAMLException("Unable to get aliases from keyStore", e); } }</code><technical_language>I this condition merge previous one</technical_language>

Target:
private String getPrivateKeyAlias(final KeyStore keyStore, final String keyStoreAlias) { try { final Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); if (keyStoreAlias == null || currentAlias.equals(keyStoreAlias)) { return currentAlias; } } throw new SAMLException("Keystore has no private keys"); } catch (final KeyStoreException e) { throw new SAMLException("Unable to get aliases from keyStore", e); } }
Source:
<code>public void testLoadConfigurationFromClassPath() { try { final DefaultConfiguration config = (DefaultConfiguration) ConfigurationLoader.loadConfiguration( "/com/puppycrawl/tools/checkstyle/configs/" + "config_with_ignore.xml", new PropertiesExpander(new Properties()), true); final Configuration[] children = config.getChildren(); assertEquals(0, children[0].getChildren().length); } catch (CheckstyleException ignored) { <START> fail("unexpected exception"); <END> } }</code><technical_language>remove try-catch-fail</technical_language>

Target:
public void testLoadConfigurationFromClassPath() throws Exception { final DefaultConfiguration config = (DefaultConfiguration) ConfigurationLoader.loadConfiguration( "/com/puppycrawl/tools/checkstyle/configs/" + "config_with_ignore.xml", new PropertiesExpander(new Properties()), true); final Configuration[] children = config.getChildren(); assertEquals(0, children[0].getChildren().length); }
Source:
<code>private void uploadDirectory(String dirPath, String container) throws FileNotFoundException, InterruptedException, ExecutionException { File dir = new File(dirPath); if (!dir.isDirectory()) { throw new FileNotFoundException(dirPath + " is not a directory."); <START> } <END> System.out.println("Uploading " + dirPath + " to " + container); storage.createContainerInLocation(null, container); List<BlobDetail> blobDetails = Lists.newArrayList(); generateFileList(dir, "", blobDetails); uploadFiles(container, blobDetails); }</code><technical_language>checkArgument(dir.isDirectory, "%s is a directory", dirPath); ? I a exception type, still..</technical_language>

Target:
private void uploadDirectory(String dirPath, String container) throws InterruptedException, ExecutionException { File dir = new File(dirPath); checkArgument(dir.isDirectory(), "%s is not a directory", dirPath); System.out.println("Uploading " + dirPath + " to " + container); storage.createContainerInLocation(null, container); List<BlobDetail> blobDetails = Lists.newArrayList(); generateFileList(dir, "", blobDetails); uploadFiles(container, blobDetails); }
Source:
<code>public void onCompleted() { if (!empty) { <START> child.onCompleted(); <END> } else if (!child.isUnsubscribed()) { subscribeToAlternate(); } }</code><technical_language>Sorry, a typo here. return parent</technical_language>

Target:
public void onCompleted() { if (!empty) { child.onCompleted(); } else if (!child.isUnsubscribed()) { unsubscribe(); subscribeToAlternate(); } }
Source:
<code>public boolean productHasSubscriptions(Product prod) { ArrayList<Product> provided = new ArrayList<Product>(); <START> provided.add(prod); <END> return currentSession().createCriteria(Subscription.class) .createAlias("providedProducts", "providedProd", JoinType.LEFT_OUTER_JOIN) .createAlias("derivedProvidedProducts", "derivedProvidedProd", JoinType.LEFT_OUTER_JOIN) .add(Restrictions.or( Restrictions.eq("product", prod), Restrictions.eq("derivedProduct", prod), Restrictions.eq("providedProd.id", prod.getId()), Restrictions.eq("derivedProvidedProd.id", prod.getId()))) .setProjection(Projections.id()) .list().size() > 0; }</code><technical_language>lines unnecessary</technical_language>

Target:
public boolean productHasSubscriptions(Product prod) { return ((Long) currentSession().createCriteria(Subscription.class) .createAlias("providedProducts", "providedProd", JoinType.LEFT_OUTER_JOIN) .createAlias("derivedProvidedProducts", "derivedProvidedProd", JoinType.LEFT_OUTER_JOIN) .add(Restrictions.or( Restrictions.eq("product", prod), Restrictions.eq("derivedProduct", prod), Restrictions.eq("providedProd.id", prod.getId()), Restrictions.eq("derivedProvidedProd.id", prod.getId()))) .setProjection(Projections.count("id")) .uniqueResult()) > 0; }
Source:
<code>private void maybeAddReferenceCount(Node n) { Node refParent = getBaseQualifiedNameNode(n); if (refParent == null) { return; } String qName = refParent.getQualifiedName(); if (qName.startsWith("module.exports.")) { <START> qName = qName.substring(15); <END> } else if (qName.startsWith("exports.")) { qName = qName.substring(8); } else { return; } int assignCount = 1; if (propertyExportRefCount.containsKey(qName)) { assignCount = propertyExportRefCount.get(qName) + 1; propertyExportRefCount.remove(qName); } propertyExportRefCount.put(qName, assignCount); }</code><technical_language>nit: "module.exports.".length clear number (likewise 2 lines down)</technical_language>

Target:
private void maybeAddReferenceCount(Node n) { Node refParent = getBaseQualifiedNameNode(n); if (refParent == null) { return; } String qName = refParent.getQualifiedName(); if (qName.startsWith("module.exports.")) { qName = qName.substring("module.exports.".length()); } else if (qName.startsWith("exports.")) { qName = qName.substring("exports.".length()); } else { return; } propertyExportRefCount.add(qName); }
Source:
<code>public void onResume() { <START> if(client != null && reactActivityDelegate != null){ <END> reactActivityDelegate.onReadyCreate(); } super.onResume(); if (passcodeManager.onResume(this)) { try { client = clientManager.peekRestClient(); } catch (ClientManager.AccountInfoNotFoundException e) { client = null; } if (client == null) { onResumeNotLoggedIn(); } else { Log.i(TAG, "onResume - Already logged in"); } } }</code><technical_language>This call super.onResume(). Also, if this work for time load, client null time, peekRestClient() call is initiates login flow</technical_language>

Target:
public void onResume() { super.onResume(); if (passcodeManager.onResume(this)) { try { setRestClient(clientManager.peekRestClient()); } catch (ClientManager.AccountInfoNotFoundException e) { setRestClient(client); } if (client == null) { onResumeNotLoggedIn(); } else { Log.i(TAG, "onResume - Already logged in"); } } }
Source:
<code>public boolean isLocal() { for(EnvironmentConfig part : this) { <START> if(part.isLocal()) <END> return false; } return true; }</code><technical_language>!part.isLocal() instead of part.isLocal()</technical_language>

Target:
public boolean isLocal() { for(EnvironmentConfig part : this) { if(!part.isLocal()) return false; } return true; }
Source:
<code>public Anchor(String href, String text, AnchorTarget target) { setHref(href); setText(text); <START> setTargetEnum(target); <END> }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Remove this call a constructor overridable "setHref" method. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Anchor(String href, String text, AnchorTarget target) { setHref(href); setText(text); setTarget(target); }
Source:
<code><START> public Iterable<TmfXmlLocation> getLocations() { <END> return Collections.EMPTY_SET; }</code><technical_language>public @Nullable Iterable... EMPTY_SET is null though, supresswarning instead</technical_language>

Target:
public @Nullable Iterable<TmfXmlLocation> getLocations() { return Collections.EMPTY_SET; }
Source:
<code>protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error("Handling error for message type: " + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_CORE, "An unknown error occurred", e); } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error("Handling error for message type: " + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_CORE, "An unknown error occurred", e); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
<code>private Phenotype updatePhenotype( final Integer observationId, final Integer categoricalValueId, final String value, final Boolean draftMode) { final PhenotypeDao phenotypeDao = this.daoFactory.getPhenotypeDAO(); final Phenotype phenotype = phenotypeDao.getById(observationId); if (draftMode) { phenotype.setDraftValue(value); <START> phenotype.setDraftCValueId(categoricalValueId == null || categoricalValueId == 0 ? null : categoricalValueId); <END> } else { phenotype.setValue(value); phenotype.setcValue(categoricalValueId == null || categoricalValueId == 0 ? null : categoricalValueId); } final Integer observableId = phenotype.getObservableId(); this.resolveObservationStatus(observableId, phenotype); phenotype.setChanged(true); phenotypeDao.update(phenotype); return phenotype; }</code><technical_language>do java Integer.valueOf(0).equals(categoricalValueId) ? null : categoricalValueId)</technical_language>

Target:
private Phenotype updatePhenotype( final Integer observationId, final Integer categoricalValueId, final String value, final Boolean draftMode) { final PhenotypeDao phenotypeDao = this.daoFactory.getPhenotypeDAO(); final Phenotype phenotype = phenotypeDao.getById(observationId); if (draftMode) { phenotype.setDraftValue(value); phenotype.setDraftCValueId(Integer.valueOf(0).equals(categoricalValueId) ? null : categoricalValueId); } else { phenotype.setValue(value); phenotype.setcValue(Integer.valueOf(0).equals(categoricalValueId) ? null : categoricalValueId); } final Integer observableId = phenotype.getObservableId(); this.resolveObservationStatus(observableId, phenotype); phenotype.setChanged(true); phenotypeDao.update(phenotype); return phenotype; }
Source:
<code>public void addContents(@NonNull Container container, @NonNull AbstractItem item) { try { File itemRootDir = item.getRootDir(); Path relativeToRoot = new File(Jenkins.get().getRootDir(), "jobs").toPath() .relativize(itemRootDir.toPath()); list(itemRootDir, new FileVisitor() { @Override public void visitSymlink(File link, String target, String relativePath) { container.add(new PrintedContent("items/{0}/{1}", relativeToRoot.toString(), relativePath) { @Override protected void printTo(PrintWriter out) { out.println("symlink -> " + target); } @Override public boolean shouldBeFiltered() { <START> return true; <END> } }); } @Override public void visit(File file, String s) { container.add(new FileContent("items/{0}/{1}", new String[]{relativeToRoot.toString(), s}, file)); } @Override public boolean understandsSymlink() { return true; } }); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not list files from root directory of " + item.getFullName(), e); } }</code><technical_language>Is useful list this if filtered</technical_language>

Target:
public void addContents(@NonNull Container container, @NonNull AbstractItem item) { try { File itemRootDir = item.getRootDir(); String relativeToRoot = Functions.isWindows() ? new File(Jenkins.get().getRootDir(), "jobs").toPath() .relativize(itemRootDir.toPath()).toString().replace('\\','/') : new File(Jenkins.get().getRootDir(), "jobs").toPath() .relativize(itemRootDir.toPath()).toString(); list(itemRootDir, new FileVisitor() { @Override public void visitSymlink(File link, String target, String relativePath) { container.add(new PrintedContent("items/{0}/{1}", relativeToRoot, Functions.isWindows() ? relativePath.replace('\\','/') : relativePath) { @Override protected void printTo(PrintWriter out) { out.println("symlink -> " + target); } @Override public boolean shouldBeFiltered() { return true; } }); } @Override public void visit(File file, String s) { container.add(new FileContent("items/{0}/{1}", new String[]{relativeToRoot, Functions.isWindows() ? s.replace('\\','/') : s}, file) ); } @Override public boolean understandsSymlink() { return true; } }); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not list files from root directory of " + item.getFullName(), e); } }
Source:
<code>public <T extends LwM2mResponse> T send(final Client destination, final DownlinkRequest<T> request) throws InterruptedException { throw new UnsupportedOperationException( <START> "This is a deprecated message and better not use it for testing purposes"); <END> }</code><technical_language>I of this message > for testing purposes lines of _Sender supports asynchronous requests only_ fact this method is clear of exception, it</technical_language>

Target:
public <T extends LwM2mResponse> T send(final Client destination, final DownlinkRequest<T> request) throws InterruptedException { throw new UnsupportedOperationException("Server doesn't support synchronous sending of messages"); }
Source:
<code>public boolean isPageview( String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent, String rawXAnalyticsHeader ) { uriHost = uriHost.toLowerCase(); Webrequest wr = Webrequest.getInstance(); <START> if (!wr.getXAnalyticsValue(rawXAnalyticsHeader,"pageview").isEmpty()) <END> return true; if (!wr.getXAnalyticsValue(rawXAnalyticsHeader,"preview").isEmpty()) return false; return ( httpStatusesSet.contains(httpStatus) && ( (contentTypesSet.contains(contentType) && !Utilities.stringContains(uriPath, uriPathAPI)) || isAppPageview(uriPath, uriQuery, contentType, userAgent, rawXAnalyticsHeader) ) && ( Utilities.patternIsFound(uriHostWikimediaDomainPattern, uriHost) || Utilities.patternIsFound(uriHostOtherProjectsPattern, uriHost) || Utilities.patternIsFound(uriHostProjectDomainPattern, uriHost) ) && ( Utilities.patternIsFound(uriPathPattern, uriPath) || Utilities.patternIsFound(uriQueryPattern, uriQuery) ) && !Utilities.patternIsFound(uriPathUnwantedSpecialPagesPattern, uriPath) && !Utilities.patternIsFound(uriQueryUnwantedSpecialPagesPattern, uriQuery) && !Utilities.patternIsFound(uriQueryUnwantedActions, uriQuery) ); }</code><technical_language>I love lenient check, prefer checking it.trim().equalsIgnoreCase("1") preview below</technical_language>

Target:
public boolean isPageview( String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent, String rawXAnalyticsHeader ) { uriHost = uriHost.toLowerCase(); Webrequest wr = Webrequest.getInstance(); if (wr.getXAnalyticsValue(rawXAnalyticsHeader,"preview").trim().equalsIgnoreCase("1")) return false; if (wr.getXAnalyticsValue(rawXAnalyticsHeader,"pageview").trim().equalsIgnoreCase("1")) return true; return ( httpStatusesSet.contains(httpStatus) && ( (contentTypesSet.contains(contentType) && !Utilities.stringContains(uriPath, uriPathAPI)) || isAppPageview(uriPath, uriQuery, contentType, userAgent, rawXAnalyticsHeader) ) && ( Utilities.patternIsFound(uriHostWikimediaDomainPattern, uriHost) || Utilities.patternIsFound(uriHostOtherProjectsPattern, uriHost) || Utilities.patternIsFound(uriHostProjectDomainPattern, uriHost) ) && ( Utilities.patternIsFound(uriPathPattern, uriPath) || Utilities.patternIsFound(uriQueryPattern, uriQuery) ) && !Utilities.patternIsFound(uriPathUnwantedSpecialPagesPattern, uriPath) && !Utilities.patternIsFound(uriQueryUnwantedSpecialPagesPattern, uriQuery) && !Utilities.patternIsFound(uriQueryUnwantedActions, uriQuery) ); }