auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void doExecute() throws Exception { if (skip) { return; } if (isInstall) { installServerAssembly(); } else { log.info(MessageFormat.format(messages.getString("info.install.type.preexisting"), "")); checkServerHomeExists(); } boolean createServer = false; if (!serverDirectory.exists()) { createServer = true; } else if (refresh) { FileUtils.forceDelete(serverDirectory); createServer = true; } if (createServer) { log.info(MessageFormat.format(messages.getString("info.server.start.create"), serverName)); ServerTask serverTask = initializeJava(); serverTask.setOperation("create"); serverTask.setTemplate(template); serverTask.execute(); copyConfigFiles(true); exportParametersToXml(); log.info(MessageFormat.format(messages.getString("info.server.create.created"), serverName, serverDirectory.getCanonicalPath())); } else { copyConfigFiles(); <START> exportParametersToXml(); <END> } }</code><technical_language>overwrite away, remove else 2 lines if? copyConfigFiles(true); exportParametersToXml();</technical_language>

Target:
protected void doExecute() throws Exception { if (skip) { return; } if (isInstall) { installServerAssembly(); } else { log.info(MessageFormat.format(messages.getString("info.install.type.preexisting"), "")); checkServerHomeExists(); } boolean createServer = false; if (!serverDirectory.exists()) { createServer = true; } else if (refresh) { FileUtils.forceDelete(serverDirectory); createServer = true; } if (createServer) { log.info(MessageFormat.format(messages.getString("info.server.start.create"), serverName)); ServerTask serverTask = initializeJava(); serverTask.setOperation("create"); serverTask.setTemplate(template); serverTask.execute(); log.info(MessageFormat.format(messages.getString("info.server.create.created"), serverName, serverDirectory.getCanonicalPath())); } copyConfigFiles(true); exportParametersToXml(); }
Source:
<code>public FromAttributesAuthorizationGenerator() { <START> this.roleAttributes = Arrays.asList(new String[] {}); <END> this.permissionAttributes = Arrays.asList(new String[] {}); }</code><technical_language>new ArrayList<String>();</technical_language>

Target:
public FromAttributesAuthorizationGenerator() { this.roleAttributes = new ArrayList(); this.permissionAttributes = new ArrayList(); }
Source:
<code>public SELF withRowGroupSize(int rowGroupSize) { <START> this.blockSize = rowGroupSize; <END> return self(); }</code><technical_language>rename this.blockSize this.rowGroupSize</technical_language>

Target:
public SELF withRowGroupSize(int rowGroupSize) { this.rowGroupSize = rowGroupSize; return self(); }
Source:
<code>public void insertToMemberGroup(PerunSession sess, Member member, Vo vo) throws InternalErrorException, AlreadyMemberException { try { getPerunBl().getVosManagerBl().checkVoExists(sess, vo); Group g = getPerunBl().getGroupsManagerBl().getGroupByName(sess, vo, VosManager.MEMBERS_GROUP); getPerunBl().getGroupsManagerBl().addMemberToMembersGroup(sess, g, member); } catch (NotMemberOfParentGroupException ex) { throw new ConsistencyErrorException(ex); } catch (GroupNotExistsException e) { throw new InternalErrorException(e); } catch (VoNotExistsException e) { throw new InternalErrorException(e); } catch (WrongAttributeValueException e) { throw new ConsistencyErrorException(e); } catch (WrongReferenceAttributeValueException e) { throw new ConsistencyErrorException(e); <START> } catch (NotGroupMemberException e) { <END> throw new ConsistencyErrorException(e); } }</code><technical_language>GroupOperationException</technical_language>

Target:
public void insertToMemberGroup(PerunSession sess, Member member, Vo vo) throws InternalErrorException, AlreadyMemberException, GroupOperationsException { try { getPerunBl().getVosManagerBl().checkVoExists(sess, vo); Group g = getPerunBl().getGroupsManagerBl().getGroupByName(sess, vo, VosManager.MEMBERS_GROUP); getPerunBl().getGroupsManagerBl().addMemberToMembersGroup(sess, g, member); } catch (GroupNotExistsException e) { throw new InternalErrorException(e); } catch (VoNotExistsException e) { throw new InternalErrorException(e); } catch (WrongAttributeValueException e) { throw new ConsistencyErrorException(e); } catch (WrongReferenceAttributeValueException e) { throw new ConsistencyErrorException(e); } }
Source:
<code>public void retriesOnExceptionTillCount() throws Exception { final int count = 3; final int delay = 1000; final Take take = Mockito.mock(Take.class); final Request req = new RqFake(RqMethod.GET); Mockito.when(take.act(Mockito.any(Request.class))).thenThrow( new IOException() ); <START> final long minTimeToFail = count * delay; <END> final long startTime = System.currentTimeMillis(); try { new TkRetry(count, delay, take).act(req); } catch (final IOException exception) { MatcherAssert.assertThat( minTimeToFail, Matchers.lessThanOrEqualTo( System.currentTimeMillis() - startTime ) ); throw exception; } }</code><technical_language>@aschworer need this variable</technical_language>

Target:
public void retriesOnExceptionTillCount() throws Exception { final int count = 3; final int delay = 1000; final Take take = Mockito.mock(Take.class); final Request req = new RqFake(RqMethod.GET); Mockito.when(take.act(Mockito.any(Request.class))).thenThrow( new IOException() ); final long startTime = System.currentTimeMillis(); try { new TkRetry(count, delay, take).act(req); } catch (final IOException exception) { MatcherAssert.assertThat( new Long(count * delay), Matchers.lessThanOrEqualTo( System.currentTimeMillis() - startTime ) ); throw exception; } }
Source:
<code>public void canHandleMultipleClearsWithNoCorrrespondingProblemAlarm() throws Exception { final MockNode node = m_mockNetwork.getNode(1); sendNodeUpEvent(node); sendNodeUpEvent(node); <START> await().until(() -> m_alarmDao.findAll().size() == 1 && m_alarmDao.findAll().get(0).getCounter() == 2); <END> }</code><technical_language>This broken out multiple assertions - if fails match</technical_language>

Target:
public void canHandleMultipleClearsWithNoCorrrespondingProblemAlarm() throws Exception { final MockNode node = m_mockNetwork.getNode(1); sendNodeUpEvent(node); sendNodeUpEvent(node); await().until(() -> m_alarmDao.findAll(), hasSize(1)); await().until(() -> m_alarmDao.findAll().get(0).getCounter(), equalTo(2)); }
Source:
<code>public ImportTableDesc tableDesc(String dbName) throws SemanticException { try { Table table = new Table(metadata.getTable()); if (!AcidUtils.isTransactionalTable(table) && hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_STRICT_MANAGED_TABLES) && (table.getTableType() == TableType.MANAGED_TABLE)) { Hive hiveDb = Hive.get(hiveConf); HiveStrictManagedMigration.TableMigrationOption migrationOption = HiveStrictManagedMigration.determineMigrationTypeAutomatically(table.getTTable(), table.getTableType(),null, (Configuration)hiveConf, hiveDb.getMSC(),true); HiveStrictManagedMigration.migrateTable(table.getTTable(), table.getTableType(), migrationOption, false, getHiveUpdater(hiveConf), hiveDb.getMSC(), (Configuration)hiveConf); if (AcidUtils.isTransactionalTable(table)) { replicationSpec().setDoingMigration(); } } ImportTableDesc tableDesc = new ImportTableDesc(StringUtils.isBlank(dbName) ? table.getDbName() : dbName, table); tableDesc.setReplicationSpec(replicationSpec()); if (table.getTableType() == TableType.EXTERNAL_TABLE) { <START> tableDesc.setExternal(true); <END> } return tableDesc; } catch (Exception e) { throw new SemanticException(e); } }</code><technical_language>set external flag in ImportTableDesc constructor itself</technical_language>

Target:
public ImportTableDesc tableDesc(String dbName) throws SemanticException { try { Table table = new Table(metadata.getTable()); if (!AcidUtils.isTransactionalTable(table) && hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_STRICT_MANAGED_TABLES) && (table.getTableType() == TableType.MANAGED_TABLE)) { Hive hiveDb = Hive.get(hiveConf); HiveStrictManagedMigration.TableMigrationOption migrationOption = HiveStrictManagedMigration.determineMigrationTypeAutomatically(table.getTTable(), table.getTableType(),null, (Configuration)hiveConf, hiveDb.getMSC(),true); HiveStrictManagedMigration.migrateTable(table.getTTable(), table.getTableType(), migrationOption, false, getHiveUpdater(hiveConf), hiveDb.getMSC(), (Configuration)hiveConf); if (AcidUtils.isTransactionalTable(table)) { replicationSpec().setMigratingToTxnTable(); } } ImportTableDesc tableDesc = new ImportTableDesc(StringUtils.isBlank(dbName) ? table.getDbName() : dbName, table); tableDesc.setReplicationSpec(replicationSpec()); if (table.getTableType() == TableType.EXTERNAL_TABLE) { tableDesc.setExternal(true); } return tableDesc; } catch (Exception e) { throw new SemanticException(e); } }
Source:
<code>protected boolean checkTemplateInStorageDomain() { boolean retValue = validate(getImportValidator().verifyDisks(imageList, imageToDestinationDomainMap)); if (retValue && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { for (DiskImage diskImage : imageList) { if (!diskImage.getImageTemplateId().equals(Guid.Empty)) { DiskImage templateDisk = <START> getDbFacade().getDiskImageDao().get(diskImage.getImageTemplateId()); <END> if (!templateDisk.getStorageIds().contains(diskImage.getStorageIds().get(0))) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } } } return retValue; }</code><technical_language>DAOs injected - there</technical_language>

Target:
protected boolean checkTemplateInStorageDomain() { boolean retValue = validate(getImportValidator().verifyDisks(imageList, imageToDestinationDomainMap)); if (retValue && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getVmtGuid()) && !getParameters().getCopyCollapse()) { for (DiskImage diskImage : imageList) { if (!diskImage.getImageTemplateId().equals(Guid.Empty)) { DiskImage templateDisk = diskImageDao.get(diskImage.getImageTemplateId()); if (!templateDisk.getStorageIds().contains(diskImage.getStorageIds().get(0))) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN); } } } } return retValue; }
Source:
<code>private void waitForReconciliationToComplete() { long startedAt = System.currentTimeMillis(); while (!deltaReconciliationCompleted() && (System.currentTimeMillis() - startedAt) <= MAX_TIME_TO_WAIT_FOR_RECONCILIATION) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.interrupted(); break; } } if (!deltaReconciliationCompleted()) { throw new SystemFailureException(JcrI18n.journalHasNotCompletedReconciliation.text(journalId(), clusterName(), MAX_TIME_TO_WAIT_FOR_RECONCILIATION)); } <START> } <END></code><technical_language>I more efficient simpler a CountDownLatch for reconciliation. Basically, startup wait for reconciliation complete latch.await(MAX_TIME_TO_WAIT_FOR_RECONCILIATION,TimeUnit.MILLIS), while markDeltaReconciliationAsCompleted() simply call latch.countDown(). able get rid of deltaReconciliationCompleted, answered latch (which is threadsafe)</technical_language>

Target:
private void waitForReconciliationToComplete() { try { reconciliationLatch.await(MAX_MINUTES_TO_WAIT_FOR_RECONCILIATION, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.interrupted(); } if (!deltaReconciliationCompleted()) { throw new SystemFailureException(JcrI18n.journalHasNotCompletedReconciliation.text(journalId(), clusterName(), MAX_MINUTES_TO_WAIT_FOR_RECONCILIATION)); } }
Source:
<code><START> public void classSetup() throws Exception { <END> removeAndRestoreDataBundle(dataBundle); }</code><technical_language>Is this change necessary</technical_language>

Target:
public void classSetup() { removeAndRestoreDataBundle(dataBundle); }
Source:
<code>public static String canonical(String path) { <START> if (path == null || path.isEmpty()){ <END> return path; } if(path.startsWith("/..")) { return null; } List<String> directories = new ArrayList<>(Arrays.asList(path.split("(?<=\\/)"))); directories.removeIf(dir-> dir.isEmpty() || dir.equals(".")); for(ListIterator<String> iterator = directories.listIterator(); iterator.hasNext();){ String currentDir = iterator.next(); if (currentDir.equals("./")){ if (iterator.nextIndex()>1) iterator.remove(); else if (iterator.hasNext()){ if(!iterator.next().equals("/")) { iterator.previous(); iterator.previous(); iterator.remove(); } } else { return ""; } } else if(currentDir.equals("../") || currentDir.equals("..")) { iterator.remove(); if (iterator.hasPrevious()) { iterator.previous(); iterator.remove(); if (directories.isEmpty() && path.startsWith("/")) return null; } else { return null; } } } return directories.stream().collect(Collectors.joining()); }</code><technical_language>StringUtils (apache commons) "isBlank" "isEmpty"</technical_language>

Target:
public static String canonical(String path) { if (path == null || path.isEmpty() || !path.contains(".")) return path; if(path.startsWith("/..")) return null; List<String> directories = new LinkedList<>(); Collections.addAll(directories, __PATH_SPLIT.split(path)); for(ListIterator<String> iterator = directories.listIterator(); iterator.hasNext();) { switch (iterator.next()) { case "./": case ".": if (iterator.hasNext() && directories.get(iterator.nextIndex()).equals("/")) break; iterator.remove(); break; case "../": case "..": if(iterator.previousIndex() == 0) return null; iterator.remove(); if(iterator.previous().equals("/") && iterator.nextIndex() == 0) return null; iterator.remove(); break; } } return String.join("", directories); }
Source:
<code><START> private void pruneHardDeleteRecoveryRange() { <END> StoreFindToken logFlushedTillToken = (StoreFindToken) startTokenSafeToPersist; if (logFlushedTillToken != null && !logFlushedTillToken.isUninitialized()) { if (logFlushedTillToken.equals(endToken)) { hardDeleteRecoveryRange.clear(); rangePrunedTillToken = logFlushedTillToken; } else if (logFlushedTillToken.getStoreKey() == null) { } else if (!logFlushedTillToken.equals(rangePrunedTillToken)) { Iterator<HardDeletePersistInfo> hardDeleteRecoveryRangeIterator = hardDeleteRecoveryRange.iterator(); while (hardDeleteRecoveryRangeIterator.hasNext()) { StoreKey key = hardDeleteRecoveryRangeIterator.next().getBlobReadOptions().getStoreKey(); if (logFlushedTillToken.getStoreKey().equals(key)) { break; } else { hardDeleteRecoveryRangeIterator.remove(); } } rangePrunedTillToken = logFlushedTillToken; } } }</code><technical_language>sufficient trace logging. Also, of metric useful</technical_language>

Target:
protected void pruneHardDeleteRecoveryRange() { StoreFindToken logFlushedTillToken = (StoreFindToken) startTokenSafeToPersist; if (logFlushedTillToken != null && !logFlushedTillToken.isUninitialized()) { if (logFlushedTillToken.equals(endToken)) { hardDeleteRecoveryRange.clear(); } else if (logFlushedTillToken.getStoreKey() != null) { hardDeleteRecoveryRange.pruneTill(logFlushedTillToken.getStoreKey()); } } }
Source:
<code>public ByteBuffer[] nioBuffers(int index, int length) { if (b1.nioBufferCount() == 1 && b2.nioBufferCount() == 1) { return new ByteBuffer[] { b1.nioBuffer(), b2.nioBuffer() }; } <START> return ObjectArrays.concat(b1.nioBuffers(), b2.nioBuffers(), ByteBuffer.class); <END> }</code><technical_language>yup, this is incorrect, I failed somewhere, this logic in public ByteBuffer[] nioBuffers(), gonna change</technical_language>

Target:
public ByteBuffer[] nioBuffers(int index, int length) { return new ByteBuffer[] { nioBuffer(index, length) }; }
Source:
<code>public AutodetectResult(StreamInput in) throws IOException { if (in.readBoolean()) { this.bucket = new Bucket(in); } else { this.bucket = null; } if (in.readBoolean()) { this.records = in.readList(AnomalyRecord::new); } else { this.records = null; } if (in.readBoolean()) { this.influencers = in.readList(Influencer::new); } else { this.influencers = null; } if (in.readBoolean()) { this.quantiles = new Quantiles(in); } else { this.quantiles = null; } if (in.readBoolean()) { this.modelSnapshot = new ModelSnapshot(in); } else { this.modelSnapshot = null; } if (in.readBoolean()) { this.modelSizeStats = new ModelSizeStats(in); } else { this.modelSizeStats = null; } if (in.readBoolean()) { this.modelPlot = new ModelPlot(in); } else { this.modelPlot = null; } if (in.readBoolean()) { this.annotation = new Annotation(in); } else { this.annotation = null; } if (in.readBoolean()) { this.categoryDefinition = new CategoryDefinition(in); } else { this.categoryDefinition = null; } <START> if (in.getVersion().onOrAfter(Version.V_8_0_0) && in.readBoolean()) { this.categorizerStats = new CategorizerStats(in); <END> } else { this.categorizerStats = null; } if (in.readBoolean()) { this.flushAcknowledgement = new FlushAcknowledgement(in); } else { this.flushAcknowledgement = null; } if (in.readBoolean()) { this.forecast = new Forecast(in); } else { this.forecast = null; } if (in.readBoolean()) { this.forecastRequestStats = new ForecastRequestStats(in); } else { this.forecastRequestStats = null; } }</code><technical_language>suggestion if (in.getVersion().onOrAfter(Version.V_8_0_0)) { this.categorizerStats = in.readOptionalWriteable(CategorizerStats::new);</technical_language>

Target:
public AutodetectResult(StreamInput in) throws IOException { if (in.readBoolean()) { this.bucket = new Bucket(in); } else { this.bucket = null; } if (in.readBoolean()) { this.records = in.readList(AnomalyRecord::new); } else { this.records = null; } if (in.readBoolean()) { this.influencers = in.readList(Influencer::new); } else { this.influencers = null; } if (in.readBoolean()) { this.quantiles = new Quantiles(in); } else { this.quantiles = null; } if (in.readBoolean()) { this.modelSnapshot = new ModelSnapshot(in); } else { this.modelSnapshot = null; } if (in.readBoolean()) { this.modelSizeStats = new ModelSizeStats(in); } else { this.modelSizeStats = null; } if (in.readBoolean()) { this.modelPlot = new ModelPlot(in); } else { this.modelPlot = null; } if (in.readBoolean()) { this.annotation = new Annotation(in); } else { this.annotation = null; } if (in.readBoolean()) { this.categoryDefinition = new CategoryDefinition(in); } else { this.categoryDefinition = null; } if (in.getVersion().onOrAfter(Version.V_8_0_0)) { this.categorizerStats = in.readOptionalWriteable(CategorizerStats::new); } else { this.categorizerStats = null; } if (in.readBoolean()) { this.flushAcknowledgement = new FlushAcknowledgement(in); } else { this.flushAcknowledgement = null; } if (in.readBoolean()) { this.forecast = new Forecast(in); } else { this.forecast = null; } if (in.readBoolean()) { this.forecastRequestStats = new ForecastRequestStats(in); } else { this.forecastRequestStats = null; } }
Source:
<code>public boolean equals(Object other) { if (!super.equals(other)) { return false; } <START> if (other instanceof ExpressionStartsWith) { <END> if (noOptimisation == ((ExpressionStartsWith)other).noOptimisation) { return true; } } return false; }</code><technical_language>abitrary starts expression equals other starts expression, if is optimized</technical_language>

Target:
public boolean equals(Object other) { if (!super.equals(other)) { return false; } if (other instanceof ExpressionStartsWith) { if (noOptimization == ((ExpressionStartsWith)other).noOptimization) { return true; } } return false; }
Source:
<code>public RichGroup getRichGroupByIdWithAttributesByNames(PerunSession sess, int groupId, List<String> attrNames)throws InternalErrorException, GroupNotExistsException{ Utils.checkPerunSession(sess); this.getGroupsManagerBl().checkGroupExists(sess, this.getGroupsManagerBl().getGroupById(sess, groupId)); return this.getGroupsManagerBl().getRichGroupByIdWithAttributesByNames(sess, groupId, attrNames); <START> } <END></code><technical_language>For 3 new methods add Authorization. Inspiration in methods: -> getAllRichUsersWithAttributes in UsersManagerEntry.java file -> getAllGroups in GroupsManagerEntry.java file Summarize: 1] add authorization for voadmin, voobserver groupadmin 2] for groupadmin remove groups rights 3] create method filterOnlyAllowedAttributes for list of richGroups (similar in UsersManagerBlImpl) 4] method filterOnlyAllowedAttribute for list of RichGroups filtering attributes of richGroups</technical_language>

Target:
public RichGroup getRichGroupByIdWithAttributesByNames(PerunSession sess, int groupId, List<String> attrNames) throws InternalErrorException, GroupNotExistsException, VoNotExistsException, PrivilegeException { Utils.checkPerunSession(sess); this.getGroupsManagerBl().checkGroupExists(sess, this.getGroupsManagerBl().getGroupById(sess, groupId)); Group group = groupsManagerBl.getGroupById(sess, groupId); Vo vo = perunBl.getVosManagerBl().getVoById(sess, group.getVoId()); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, vo) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "getRichGroupByIdWithAttributesByNames"); } return getGroupsManagerBl().filterOnlyAllowedAttributes(sess, getGroupsManagerBl().getRichGroupByIdWithAttributesByNames(sess, groupId, attrNames)); }
Source:
<code>public AuditAssociationQuery<? extends AuditAssociationQuery<Q>> traverseRelation( String associationName, JoinType joinType, String alias) { AbstractAuditAssociationQuery<AbstractAuditAssociationQuery<Q>> result = associationQueryMap.get( associationName ); if ( result == null ) { result = new RevisionsOfEntityAssociationQuery<>( enversService, auditReader, this, queryBuilder, associationName, joinType, aliasToEntityNameMap, this.alias, alias ); associationQueries.add( (RevisionsOfEntityAssociationQuery<Q>) result ); associationQueryMap.put( associationName, result ); <START> } <END> return result; }</code><technical_language>code pattern involves a duplicated casting, avoided follows: if ( !associationQueryMap.containsKey( associationName ) ) { RevisionsOfEntityAssociationQuery<Q> query = new RevisionsOfEntityAssociationQuery<>( enversService, auditReader, this, queryBuilder, associationName, joinType, aliasToEntityNameMap, this.alias, alias ); associationQueries.add( query ); associationQueryMap.put( associationName, query ); } a bit more elegant, different. code follows: associationQueryMap.computeIfAbsent( associationName, name -> { final RevisionsOfEntityAssociationQuery<Q> query = new RevisionsOfEntityAssociationQuery<>( enversService, auditReader, this, queryBuilder, associationName, joinType, aliasToEntityNameMap, this.alias, alias ); associationQueries.add( query ); return query; } ); is big fan of it</technical_language>

Target:
public AuditAssociationQuery<? extends AuditAssociationQuery<Q>> traverseRelation( String associationName, JoinType joinType, String alias) { return associationQueryMap.computeIfAbsent( associationName, name -> { AbstractAuditAssociationQuery<AbstractAuditAssociationQuery<Q>> query = new RevisionsOfEntityAssociationQuery<>( enversService, auditReader, this, queryBuilder, name, joinType, aliasToEntityNameMap, this.alias, alias ); associationQueries.add( query ); return query; } ); }
Source:
<code>protected <K extends Comparable<K>, V> LinkedHashMultimap<K, V> mapOf(K key, V value) { switch (containerType) { case SEQ: return LinkedHashMultimap.withSeq().of(key, value); case SET: return LinkedHashMultimap.withSet().of(key, value); case SORTED_SET: return LinkedHashMultimap.withSortedSet(naturalComparator()).of(key, value); } <START> throw new RuntimeException(); <END> }</code><technical_language>matter I created a default: case for throwing case... a matter of taste</technical_language>

Target:
protected <K extends Comparable<K>, V> LinkedHashMultimap<K, V> mapOf(K key, V value) { switch (containerType) { case SEQ: return LinkedHashMultimap.withSeq().of(key, value); case SET: return LinkedHashMultimap.withSet().of(key, value); case SORTED_SET: return LinkedHashMultimap.withSortedSet(naturalComparator()).of(key, value); default: throw new RuntimeException(); } }
Source:
<code>public void testFormName() throws Exception { Long pid = processClient.startProcess(CONTAINER_ID, HIRING_2_PROCESS_ID); assertNotNull(pid); assertTrue(pid.longValue() > 0); try { changeUser(USER_ADMINISTRATOR); List<TaskSummary> tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); assertNotNull(tasks); Long taskId = tasks.get(0).getId(); TaskInstance ti = taskClient.getTaskInstance(CONTAINER_ID, taskId); assertEquals("HRInterview2", ti.getFormName()); taskClient.startTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR); taskClient.completeTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR, new HashMap<>()); <START> <END> tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); assertNotNull(tasks); taskId = tasks.get(0).getId(); ti = taskClient.findTaskById(taskId); assertEquals("Tech Interview", ti.getName()); assertEquals("TechInterview", ti.getFormName()); taskClient.startTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR); taskClient.completeTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR, new HashMap<>()); tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); assertNotNull(tasks); ti = taskClient.findTaskByWorkItemId(tasks.get(0).getId()); assertEquals("Create Proposal", ti.getName()); assertEquals("CreateProposal", ti.getFormName()); } finally { changeUser(TestConfig.getUsername()); processClient.abortProcessInstance(CONTAINER_ID, pid); } }</code><technical_language>Collections.emptyMap()</technical_language>

Target:
public void testFormName() throws Exception { Long pid = processClient.startProcess(CONTAINER_ID, HIRING_2_PROCESS_ID); assertNotNull(pid); assertTrue(pid.longValue() > 0); try { changeUser(USER_ADMINISTRATOR); List<TaskSummary> tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); assertNotNull(tasks); Long taskId = tasks.get(0).getId(); TaskInstance ti = taskClient.getTaskInstance(CONTAINER_ID, taskId); assertEquals("HRInterview2", ti.getFormName()); taskClient.startTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR); taskClient.completeTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR, Collections.emptyMap()); tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); assertNotNull(tasks); taskId = tasks.get(0).getId(); ti = taskClient.findTaskById(taskId); assertEquals("Tech Interview", ti.getName()); assertEquals("TechInterview", ti.getFormName()); taskClient.startTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR); taskClient.completeTask(CONTAINER_ID, taskId, USER_ADMINISTRATOR, Collections.emptyMap()); List<WorkItemInstance> workItems = processClient.getWorkItemByProcessInstance(CONTAINER_ID, pid); assertNotNull(workItems); ti = taskClient.findTaskByWorkItemId(workItems.get(0).getId()); assertEquals("Create Proposal", ti.getName()); assertEquals("CreateProposal", ti.getFormName()); } finally { changeUser(TestConfig.getUsername()); processClient.abortProcessInstance(CONTAINER_ID, pid); } }
Source:
<code>public MockChart(SimpleEditor editor) { <START> super(editor, TYPE, images.image(), new MockChartLayout()); <END> rootPanel.setStylePrimaryName("ode-SimpleMockComponent"); setTypeProperty("0"); initComponent(rootPanel); }</code><technical_language>prefer if a icon repurposing Image icon</technical_language>

Target:
public MockChart(SimpleEditor editor) { super(editor, TYPE, images.chart(), new MockChartLayout()); rootPanel.setStylePrimaryName("ode-SimpleMockComponent"); setTypeProperty("0"); initComponent(rootPanel); }
Source:
<code>public OnlineBackup incremental( String targetDirectory ) { outcome = new BackupService().doIncrementalBackup( hostNameOrIp, port, new File( targetDirectory ), <START> getConsistencyCheck( true ), timeoutMillis, defaultConfig() ); <END> return this; }</code><technical_language>This changes default behaviour, right? it</technical_language>

Target:
public OnlineBackup incremental( String targetDirectory ) { outcome = new BackupService().doIncrementalBackup( hostNameOrIp, port, new File( targetDirectory ), getConsistencyCheck( false ), timeoutMillis, defaultConfig() ); return this; }
Source:
<code>public Configuration getDefaultConfiguration() { List<String> metadataProviders = MutableList.of( BrooklynToscaTypeProvider.class.getName(), <START> DefaultToscaTypeProvider.class.getName()); <END> return new Configuration("http://localhost:8081/", "brooklyn", "brooklyn", "localhost", metadataProviders); }</code><technical_language>in wrong order - DefaultToscaTypeProvider lowest priority i.e in this list</technical_language>

Target:
public Configuration getDefaultConfiguration() { List<String> metadataProviders = MutableList.of( DefaultToscaTypeProvider.class.getName(), BrooklynToscaTypeProvider.class.getName()); return new Configuration("http://localhost:8081/", "brooklyn", "brooklyn", "localhost", metadataProviders); }
Source:
<code>public void completeQuery(AsyncQuery query, User user, String apiVersion) { if (query.getQueryUpdateWorker() != null) { log.info("Task has not completed"); updater.execute(query.getQueryUpdateWorker()); } else { <START> log.info("Task has completed"); <END> } }</code><technical_language>Log debug - info</technical_language>

Target:
public void completeQuery(AsyncQuery query, User user, String apiVersion) { if (query.getQueryUpdateWorker() != null) { log.debug("Task has not completed"); updater.execute(query.getQueryUpdateWorker()); } else { log.debug("Task has completed"); } }
Source:
<code>public Response delete(@PathParam("application") String application) { manager.destroyInBackground(application); <START> return Response.status(Response.Status.ACCEPTED).build(); <END> }</code><technical_language>this return Response.status(Response.Status.NOT_FOUND).build() if application name is found? I destroyInBackground a no-op if found</technical_language>

Target:
public Response delete(@PathParam("application") String application) { if (!manager.registry().containsKey(application)) throw notFound("Application '%s' not found.", application); manager.destroyInBackground(application); return Response.status(Response.Status.ACCEPTED).build(); }
Source:
<code><START> private static JsonValue getDatasetDescription(String dsName) { <END> try (TypedInputStream in = execHttpGet(urlRoot + "$/" + opDatasets + "/" + dsName)) { assertEqualsIgnoreCase(WebContent.contentTypeJSON, in.getContentType()); JsonValue v = JSON.parse(in); return v; } }</code><technical_language>A useful verb (reflect lack of code for batch task handling)</technical_language>

Target:
private static JsonValue getDatasetDescription(String dsName) { try (TypedInputStream in = execHttpGet(ServerCtl.urlRoot() + "$/" + opDatasets + "/" + dsName)) { assertEqualsIgnoreCase(WebContent.contentTypeJSON, in.getContentType()); JsonValue v = JSON.parse(in); return v; } }
Source:
<code>public View getView(int position, View view, ViewGroup parent) { if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.list_item_weapon, parent, false); } Weapon weapon = itemsList.get(position); <START> ((TextView) view.findViewById(R.id.index)).setText(String.valueOf(position + 1)); <END> ((ImageView)view.findViewById(R.id.weapon_image)).setImageResource(WeaponsImageMap.get(weapon.getUniqueName())); ((TextView) view.findViewById(R.id.service_star_count)).setText(String.valueOf(weapon.getServiceStarsCount())); ((TextView) view.findViewById(R.id.weapon_name)).setText(weapon.getName().toUpperCase()); ((TextView)view.findViewById(R.id.weapon_kills)).setText(String.valueOf(weapon.getKills())); if(weapon.getServiceStarsCount() > 0) { view.findViewById(R.id.weapon_progress).setVisibility(View.GONE); } else { ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.weapon_progress); progressBar.setVisibility(View.VISIBLE); progressBar.setProgress(weapon.getServiceStarsProgress()); } return view; }</code><technical_language>Supposed a new line row? L31-39</technical_language>

Target:
public View getView(int position, View view, ViewGroup parent) { if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.list_item_weapon, parent, false); } Weapon weapon = itemsList.get(position); ((TextView) view.findViewById(R.id.index)).setText(String.valueOf(position + 1)); ((ImageView) view.findViewById(R.id.weapon_image)).setImageResource(WeaponsImageMap.get(weapon.getUniqueName())); ((TextView) view.findViewById(R.id.service_star_count)).setText(String.valueOf(weapon.getServiceStarsCount())); ((TextView) view.findViewById(R.id.weapon_name)).setText(weapon.getName().toUpperCase()); ((TextView) view.findViewById(R.id.weapon_kills)).setText(String.valueOf(weapon.getKills())); ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.weapon_progress); progressBar.setVisibility(View.VISIBLE); progressBar.setProgress(weapon.getServiceStarsProgress()); return view; }
Source:
<code>public void migrateMarkAsRead() { if (preferences.contains(MARK_AS_READ.key)) { if (!preferences.getBoolean(MARK_AS_READ.key, true)) { preferences.edit().putString(MARK_AS_READ_TYPES.key, "unread").commit(); } <START> preferences.edit().remove(MARK_AS_READ.key).commit(); <END> } }</code><technical_language>get a reference editor do final commit()</technical_language>

Target:
public void migrateMarkAsRead() { if (preferences.contains(MARK_AS_READ.key)) { SharedPreferences.Editor editor = preferences.edit(); boolean markAsRead = preferences.getBoolean(MARK_AS_READ.key, true); editor.putString(MARK_AS_READ_TYPES.key, markAsRead ? MarkAsReadTypes.READ.name() : MarkAsReadTypes.UNREAD.name()); editor.remove(MARK_AS_READ.key); editor.commit(); } }
Source:
<code>public void invalidateAll(String id) { <START> synchronized (this) { <END> latestSessionAttributes.remove(id); } super.invalidateAll(id); }</code><technical_language>map is concurrent need synchronize. Instead check result of remove if return other null invalidate it</technical_language>

Target:
public void invalidateAll(String id) { Map sessionAttributes = latestSessionAttributes.remove(id); if (sessionAttributes != null) { super.invalidateAll(id); } }
Source:
<code>private Map<String, Float> classify(Model model, Translator translator, File input) throws Exception { try { return classify(model, translator, ImageIO.read(input)); } catch (IOException e) { LOG.error("Couldn't transform input into a BufferedImage"); <START> throw new Exception("Couldn't transform input into a BufferedImage", e); <END> } }</code><technical_language>favour narrow exception thrown here, Exception is generic. inherits is RuntimeExceptioon</technical_language>

Target:
private Map<String, Float> classify(Model model, Translator translator, File input) throws Exception { try { return classify(model, translator, ImageIO.read(input)); } catch (IOException e) { LOG.error("Couldn't transform input into a BufferedImage"); throw new RuntimeException("Couldn't transform input into a BufferedImage", e); } }
Source:
<code>@Test public void malformedAnnotationRelativeUrlThrows() { class Example { @GET("ftp://example.org") Call<ResponseBody> get() { return null; } } try { buildRequest(Example.class); <START> } catch (IllegalArgumentException e) { <END> assertThat(e).hasMessage( "Malformed URL. Base: <LINK_0>, Relative: ftp://example.org"); } }</code><technical_language>fail</technical_language>

Target:
@Test public void malformedAnnotationRelativeUrlThrows() { class Example { @GET("ftp://example.org") Call<ResponseBody> get() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Malformed URL. Base: <LINK_0>, Relative: ftp://example.org"); } }
Source:
<code>public static RebalanceAlgorithm getInstance( Map<ClusterConfig.GlobalRebalancePreferenceKey, Integer> preferences) { List<HardConstraint> hardConstraints = ImmutableList.of(new FaultZoneAwareConstraint(), new NodeCapacityConstraint(), new ReplicaActivateConstraint(), new NodeMaxPartitionLimitConstraint(), new ValidGroupTagConstraint(), new SamePartitionOnInstanceConstraint()); int evennessPreference = preferences.getOrDefault(ClusterConfig.GlobalRebalancePreferenceKey.EVENNESS, 1); int movementPreference = preferences.getOrDefault(ClusterConfig.GlobalRebalancePreferenceKey.LESS_MOVEMENT, 1); float evennessRatio = (float) evennessPreference / (evennessPreference + movementPreference); float movementRatio = (float) movementPreference / (evennessPreference + movementPreference); Map<SoftConstraint, Float> softConstraints = ImmutableMap.<SoftConstraint, Float> builder() <START> .put(new PartitionMovementConstraint(), movementRatio * 0.5f) <END> .put(new InstancePartitionsCountConstraint(), 0.5f * evennessRatio) .put(new ResourcePartitionAntiAffinityConstraint(), 0.1f * evennessRatio) .put(new ResourceTopStateAntiAffinityConstraint(), 0.1f * evennessRatio) .put(new MaxCapacityUsageInstanceConstraint(), 0.25f * evennessRatio).build(); return new ConstraintBasedAlgorithm(hardConstraints, softConstraints); }</code><technical_language>need this 0.5f, right? movementRatio normalized</technical_language>

Target:
public static RebalanceAlgorithm getInstance( Map<ClusterConfig.GlobalRebalancePreferenceKey, Integer> preferences) { List<HardConstraint> hardConstraints = ImmutableList.of(new FaultZoneAwareConstraint(), new NodeCapacityConstraint(), new ReplicaActivateConstraint(), new NodeMaxPartitionLimitConstraint(), new ValidGroupTagConstraint(), new SamePartitionOnInstanceConstraint()); int evennessPreference = preferences.getOrDefault(ClusterConfig.GlobalRebalancePreferenceKey.EVENNESS, 1); int movementPreference = preferences.getOrDefault(ClusterConfig.GlobalRebalancePreferenceKey.LESS_MOVEMENT, 1); float evennessRatio = (float) evennessPreference / (evennessPreference + movementPreference); float movementRatio = (float) movementPreference / (evennessPreference + movementPreference); Map<SoftConstraint, Float> softConstraints = ImmutableMap.<SoftConstraint, Float> builder() .put(new PartitionMovementConstraint(), movementRatio) .put(new InstancePartitionsCountConstraint(), 0.3f * evennessRatio) .put(new ResourcePartitionAntiAffinityConstraint(), 0.1f * evennessRatio) .put(new ResourceTopStateAntiAffinityConstraint(), 0.1f * evennessRatio) .put(new MaxCapacityUsageInstanceConstraint(), 0.5f * evennessRatio).build(); return new ConstraintBasedAlgorithm(hardConstraints, softConstraints); }
Source:
<code>public void testUpdateLastHeartbeatPollWhenCoordinatorUnknown() throws Exception { GroupRebalanceConfig rebalanceConfig = buildRebalanceConfig(Optional.empty()); <START> ConsumerCoordinator coordinator = buildCoordinator(rebalanceConfig, <END> new Metrics(), assignors, false); subscriptions.subscribe(singleton(topic1), rebalanceListener); client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE)); client.prepareResponse(joinGroupFollowerResponse(1, "consumer", "leader", Errors.NONE)); client.prepareResponse(syncGroupResponse(singletonList(t1p), Errors.NONE)); client.prepareResponse(heartbeatResponse(Errors.NOT_COORDINATOR)); coordinator.poll(time.timer(Long.MAX_VALUE)); time.sleep(heartbeatIntervalMs); TestUtils.waitForCondition(() -> !client.hasPendingResponses(), "Failed to observe expected heartbeat from background thread"); assertTrue(coordinator.coordinatorUnknown()); assertFalse(coordinator.poll(time.timer(0))); assertEquals(time.milliseconds(), coordinator.heartbeat().lastPollTime()); time.sleep(rebalanceTimeoutMs - 1); assertFalse(coordinator.heartbeat().pollTimeoutExpired(time.milliseconds())); }</code><technical_language>In test cases advantage of initialization of coordinator in setup method. reason this changed</technical_language>

Target:
public void testUpdateLastHeartbeatPollWhenCoordinatorUnknown() throws Exception { subscriptions.subscribe(singleton(topic1), rebalanceListener); client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE)); client.prepareResponse(joinGroupFollowerResponse(1, "consumer", "leader", Errors.NONE)); client.prepareResponse(syncGroupResponse(singletonList(t1p), Errors.NONE)); client.prepareResponse(heartbeatResponse(Errors.NOT_COORDINATOR)); coordinator.poll(time.timer(Long.MAX_VALUE)); time.sleep(heartbeatIntervalMs); TestUtils.waitForCondition(() -> !client.hasPendingResponses(), "Failed to observe expected heartbeat from background thread"); assertTrue(coordinator.coordinatorUnknown()); assertFalse(coordinator.poll(time.timer(0))); assertEquals(time.milliseconds(), coordinator.heartbeat().lastPollTime()); time.sleep(rebalanceTimeoutMs - 1); assertFalse(coordinator.heartbeat().pollTimeoutExpired(time.milliseconds())); }
Source:
<code>public int hashCode() { <START> int result = uri.hashCode(); <END> result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); return result; }</code><technical_language>looked class HashCodeBuilder commons lang library (that use)? helps build a hashcode, append() method supports null require explicit testing. do (untested): java return new HashCodeBuilder().append(uri).append(title).append(description).build();</technical_language>

Target:
public int hashCode() { return new HashCodeBuilder().append(uri).append(title).append(description).build(); }
Source:
<code>protected void setActionMessageParameters() { <START> addCanDoActionMessage(VdcBllMessages.VAR__ACTION__MOVE); <END> addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK); }</code><technical_language>change import instead of move</technical_language>

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__IMPORT); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK); }
Source:
<code><START> public VDS clone() { <END> VDS vds = new VDS( getvds_group_id(), getvds_group_name(), getvds_group_description(), getId(), getvds_name(), getManagmentIp(), gethost_name(), getport(), getstatus().getValue(), getcpu_cores(), getcpu_model(), getcpu_speed_mh(), getif_total_speed(), getkvm_enabled(), getphysical_mem_mb(), getcpu_idle(), getcpu_load(), getcpu_sys(), getcpu_user(), getmem_commited(), getvm_active(), getvm_count(), getvm_migrating(), getusage_mem_percent(), getusage_cpu_percent(), getusage_network_percent(), getreserved_mem(), getguest_overhead(), getprevious_status(), getsoftware_version(), getversion_name(), getbuild_name(), getmem_available(), getmem_shared(), getserver_SSL_enabled(), getvds_group_cpu_name(), "", getnet_config_dirty(), getpm_type(), getpm_user(), getpm_password(), getpm_port(), getpm_options(), getpm_enabled()); vds.setcpu_flags(getcpu_flags()); vds.setVdsSpmPriority(getVdsSpmPriority()); vds.setOtpValidity(getOtpValidity()); vds.setkernel_version(getkernel_version()); vds.setkvm_version(getkvm_version()); vds.setHooksStr(getHooksStr()); return vds; }</code><technical_language>i some fields classes new object references</technical_language>

Target:
public VDS clone() { VDS vds = new VDS( Guid.createGuidFromString(getvds_group_id().toString()), getvds_group_name(), getvds_group_description(), Guid.createGuidFromString(getId().toString()), getvds_name(), getManagmentIp(), gethost_name(), getport(), getstatus().getValue(), getcpu_cores(), getcpu_model(), getcpu_speed_mh(), getif_total_speed(), getkvm_enabled(), getphysical_mem_mb(), getcpu_idle(), getcpu_load(), getcpu_sys(), getcpu_user(), getmem_commited(), getvm_active(), getvm_count(), getvm_migrating(), getusage_mem_percent(), getusage_cpu_percent(), getusage_network_percent(), getreserved_mem(), getguest_overhead(), getprevious_status(), getsoftware_version(), getversion_name(), getbuild_name(), getmem_available(), getmem_shared(), getserver_SSL_enabled(), getvds_group_cpu_name(), "", getnet_config_dirty(), getpm_type(), getpm_user(), getpm_password(), getpm_port(), getpm_options(), getpm_enabled()); vds.setcpu_flags(getcpu_flags()); vds.setVdsSpmPriority(getVdsSpmPriority()); vds.setOtpValidity(getOtpValidity()); vds.setkernel_version(getkernel_version()); vds.setkvm_version(getkvm_version()); vds.setHooksStr(getHooksStr()); return vds; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { RevCommit commit = (RevCommit) getSelection(getPage()).getFirstElement(); Repository repo = getRepository(event); final BranchOperationUI op; <START> List<RefNode> nodes = getRefNodes(commit, repo, Constants.R_HEADS, <END> Constants.R_REMOTES); if (nodes.isEmpty()) op = BranchOperationUI.checkout(repo, commit.name()); else if (nodes.size() == 1) op = BranchOperationUI.checkout(repo, nodes.get(0).getObject().getName()); else { BranchSelectionDialog<RefNode> dlg = new BranchSelectionDialog<RefNode>( HandlerUtil.getActiveShellChecked(event), nodes, UIText.CheckoutHandler_SelectBranchTitle, UIText.CheckoutHandler_SelectBranchMessage, SWT.SINGLE); if (dlg.open() == Window.OK) { op = BranchOperationUI.checkout(repo, dlg.getSelectedNode() .getObject().getName()); } else { op = null; } } if (op == null) return null; op.start(); return null; }</code><technical_language>nodes sorted name</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { RevCommit commit = (RevCommit) getSelection(getPage()).getFirstElement(); Repository repo = getRepository(event); final BranchOperationUI op; List<RefNode> nodes = getRefNodes(commit, repo, Constants.R_HEADS, Constants.R_REMOTES); Collections.sort(nodes); if (nodes.isEmpty()) op = BranchOperationUI.checkout(repo, commit.name()); else if (nodes.size() == 1) op = BranchOperationUI.checkout(repo, nodes.get(0).getObject().getName()); else { BranchSelectionDialog<RefNode> dlg = new BranchSelectionDialog<RefNode>( HandlerUtil.getActiveShellChecked(event), nodes, UIText.CheckoutHandler_SelectBranchTitle, UIText.CheckoutHandler_SelectBranchMessage, SWT.SINGLE); if (dlg.open() == Window.OK) { op = BranchOperationUI.checkout(repo, dlg.getSelectedNode() .getObject().getName()); } else { op = null; } } if (op == null) return null; op.start(); return null; }