auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testSqlCaseStorage() { try { PrototypeFactory mPrototypeFactory = new PrototypeFactory(); mPrototypeFactory.addClass(Case.class); String storageKey = "TFCase"; String username = "sql-storage-test"; caseStorage = new SqliteIndexedStorageUtility<Case>(Case.class, username, storageKey); caseStorage.write(a); Case readCase = caseStorage.read(1); assertEquals("a_case_name", readCase.getName()); assertEquals(1, readCase.getID()); assertEquals(1, caseStorage.getNumRecords()); int bID = caseStorage.add(b); readCase = caseStorage.read(bID); assertEquals(bID, readCase.getID()); assertEquals("b_case_id", readCase.getCaseId()); assertEquals(2, caseStorage.getNumRecords()); int id = caseStorage.add(c); assertEquals(3, caseStorage.getNumRecords()); readCase = caseStorage.getRecordForValue("case-id", "c_case_id"); assertEquals(id, readCase.getID()); assertEquals(caseStorage.getIDsForValue("case-type", "case_type_ipsum").size(), 3); caseStorage.remove(1); assertEquals(2, caseStorage.getNumRecords()); try { caseStorage.read(1); org.junit.Assert.fail(); } catch(NullPointerException e){ } Iterator iterator = caseStorage.iterator(); while(iterator.hasNext()){ <START> Case mCase = (Case)iterator.next(); <END> String caseId = mCase.getCaseId(); assertTrue(caseId.equals("b_case_id") || caseId.equals("c_case_id")); } caseStorage.removeAll(); assertEquals(0, caseStorage.getNumRecords()); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception " + e.getMessage()); } finally { SqlSandboxUtils.deleteDatabaseFolder(); } }</code><technical_language>replaced for (Case aCase : caseStorage) { ..</technical_language>

Target:
public void testSqlCaseStorage() { try { PrototypeFactory mPrototypeFactory = new PrototypeFactory(); mPrototypeFactory.addClass(Case.class); String storageKey = "TFCase"; String username = "sql-storage-test"; caseStorage = new SqliteIndexedStorageUtility<Case>(Case.class, username, storageKey); caseStorage.write(a); Case readCase = caseStorage.read(1); assertEquals("a_case_name", readCase.getName()); assertEquals(1, readCase.getID()); assertEquals(1, caseStorage.getNumRecords()); int bID = caseStorage.add(b); readCase = caseStorage.read(bID); assertEquals(bID, readCase.getID()); assertEquals("b_case_id", readCase.getCaseId()); assertEquals(2, caseStorage.getNumRecords()); int id = caseStorage.add(c); assertEquals(3, caseStorage.getNumRecords()); readCase = caseStorage.getRecordForValue("case-id", "c_case_id"); assertEquals(id, readCase.getID()); assertEquals(caseStorage.getIDsForValue("case-type", "case_type_ipsum").size(), 3); caseStorage.remove(1); assertEquals(2, caseStorage.getNumRecords()); try { caseStorage.read(1); org.junit.Assert.fail(); } catch(NullPointerException e){ } for (Case mCase : caseStorage) { String caseId = mCase.getCaseId(); assertTrue(caseId.equals("b_case_id") || caseId.equals("c_case_id")); } caseStorage.removeAll(); assertEquals(0, caseStorage.getNumRecords()); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception " + e.getMessage()); } finally { SqlSandboxUtils.deleteDatabaseFolder(); } }
Source:
<code>private List<List<MetadataField>> getMetadataFieldsList(org.dspace.core.Context context, List<String> query_field) throws SQLException { List<List<MetadataField>> listFieldList = new ArrayList<List<MetadataField>>(); for(String s: query_field) { ArrayList<MetadataField> fields = new ArrayList<MetadataField>(); listFieldList.add(fields); if (s.equals("*")) { continue; } String schema = ""; String element = ""; String qualifier = null; String[] parts = s.split("\\."); if (parts.length>0) { schema = parts[0]; } if (parts.length>1) { element = parts[1]; } if (parts.length>2) { qualifier = parts[2]; } <START> if ("*".equals(qualifier)) { <END> for(MetadataField mf: metadataFieldService.findByUnqualifiedElement(context, schema, element)){ fields.add(mf); } } else { MetadataField mf = metadataFieldService.findByElement(context, schema, element, qualifier); if (mf != null) { fields.add(mf); } } } return listFieldList; }</code><technical_language>Item.ANY instead of "*"</technical_language>

Target:
private List<List<MetadataField>> getMetadataFieldsList(org.dspace.core.Context context, List<String> query_field) throws SQLException { List<List<MetadataField>> listFieldList = new ArrayList<List<MetadataField>>(); for(String s: query_field) { ArrayList<MetadataField> fields = new ArrayList<MetadataField>(); listFieldList.add(fields); if (s.equals("*")) { continue; } String schema = ""; String element = ""; String qualifier = null; String[] parts = s.split("\\."); if (parts.length>0) { schema = parts[0]; } if (parts.length>1) { element = parts[1]; } if (parts.length>2) { qualifier = parts[2]; } if (Item.ANY.equals(qualifier)) { for(MetadataField mf: metadataFieldService.findFieldsByElementNameUnqualified(context, schema, element)){ fields.add(mf); } } else { MetadataField mf = metadataFieldService.findByElement(context, schema, element, qualifier); if (mf != null) { fields.add(mf); } } } return listFieldList; }
Source:
<code>public void close() { <START> synchronized(factory.cnxns){ <END> factory.removeCnxn(this); if (zkServer != null) { zkServer.removeCnxn(this); } closeSock(); if (sk != null) { try { sk.cancel(); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("ignoring exception during selectionkey cancel", e); } } } } }</code><technical_language>removeCnxn synchronizes cnxns this synchronization removed</technical_language>

Target:
public void close() { factory.removeCnxn(this); if (zkServer != null) { zkServer.removeCnxn(this); } closeSock(); if (sk != null) { try { sk.cancel(); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("ignoring exception during selectionkey cancel", e); } } } }
Source:
<code>public RegistryResponseType registerDocumentSetB(RegisterDocumentSetRequestType request, AssertionType assertion, NhinTargetSystemType targetSystem, NhincConstants.GATEWAY_API_LEVEL apiLevel) { LOG.debug("Begin registerDocumentSetb"); RegistryResponseType response = new RegistryResponseType(); try { String url = getWebServiceProxyHelper().getUrlFromTargetSystemByGatewayAPILevel(targetSystem, NhincConstants.NHINC_XDS_SERVICE_NAME, apiLevel); ServicePortDescriptor<DocumentRegistryXDSPortType> portDescriptor = new NhinDocDataSubmissionServicePortDescriptor(); CONNECTClient<DocumentRegistryXDSPortType> client = getCONNECTClientSecured(portDescriptor, assertion, url, targetSystem.getHomeCommunity().getHomeCommunityId(), NhincConstants.NHINC_XDS_SERVICE_NAME); <START> client.enableMtom(); <END> response = (RegistryResponseType) client.invokePort(DocumentRegistryXDSPortType.class, "documentRegistryXDSRegisterDocumentSetB", request); } catch (LargePayloadException lpe) { LOG.error("Failed to send message.", lpe); response = getMessageGeneratorUtils().createMissingDocumentRegistryResponse(); } catch (Exception ex) { LOG.error("Error calling registerDocumentSetB: " + ex.getMessage(), ex); response = getMessageGeneratorUtils().createRegistryErrorResponseWithAckFailure(ex.getMessage()); } LOG.debug("End registerDocumentSetb"); return response; }</code><technical_language>need enable mtom do doc meta data</technical_language>

Target:
public RegistryResponseType registerDocumentSetB(RegisterDocumentSetRequestType request, AssertionType assertion, NhinTargetSystemType targetSystem, NhincConstants.GATEWAY_API_LEVEL apiLevel) { LOG.debug("Begin registerDocumentSetb"); RegistryResponseType response = new RegistryResponseType(); try { String url = getWebServiceProxyHelper().getUrlFromTargetSystemByGatewayAPILevel(targetSystem, NhincConstants.NHINC_XDS_SERVICE_NAME, apiLevel); ServicePortDescriptor<DocumentRegistryXDSPortType> portDescriptor = new NhinDocDataSubmissionServicePortDescriptor(); CONNECTClient<DocumentRegistryXDSPortType> client = getCONNECTClientSecured(portDescriptor, assertion, url, targetSystem.getHomeCommunity().getHomeCommunityId(), NhincConstants.NHINC_XDS_SERVICE_NAME); response = (RegistryResponseType) client.invokePort(DocumentRegistryXDSPortType.class, "documentRegistryXDSRegisterDocumentSetB", request); } catch (Exception ex) { LOG.error("Error calling registerDocumentSetB: {}", ex.getMessage(), ex); response = getMessageGeneratorUtils().createRegistryErrorResponseWithAckFailure(ex.getMessage()); } LOG.debug("End registerDocumentSetb"); return response; }
Source:
<code>public void testUpdateExample() { createExampleIntent(); String exampleText = "Howdy " + UUID.randomUUID().toString(); String exampleText2 = "Howdy " + UUID.randomUUID().toString(); CreateExampleOptions createOptions = new CreateExampleOptions.Builder(workspaceId, exampleIntent, exampleText) .build(); service.createExample(createOptions).execute(); try { UpdateExampleOptions updateOptions = new UpdateExampleOptions.Builder(workspaceId, exampleIntent, exampleText) .newText(exampleText2) .build(); Example response = service.updateExample(updateOptions).execute(); assertNotNull(response); assertNotNull(response.getExampleText()); assertEquals(response.getExampleText(), exampleText2); } catch (Exception ex) { fail(ex.getMessage()); } finally { DeleteExampleOptions deleteOptions = new DeleteExampleOptions.Builder(workspaceId, exampleIntent, exampleText2) .build(); <START> service.deleteExample(deleteOptions).execute(); <END> } }</code><technical_language>reason removing mentions in Assistant? duplicates</technical_language>

Target:
public void testUpdateExample() { createExampleIntent(); String exampleText = "Howdy " + UUID.randomUUID().toString(); String exampleText2 = "Howdy " + UUID.randomUUID().toString(); CreateExampleOptions createOptions = new CreateExampleOptions.Builder(workspaceId, exampleIntent, exampleText) .build(); service.createExample(createOptions).execute(); try { Mentions mentions = new Mentions(); mentions.setEntity("entity"); mentions.setLocation(Arrays.asList(0L, 10L)); List<Mentions> mentionsList = new ArrayList<>(); mentionsList.add(mentions); UpdateExampleOptions updateOptions = new UpdateExampleOptions.Builder(workspaceId, exampleIntent, exampleText) .newText(exampleText2) .newMentions(mentionsList) .build(); Example response = service.updateExample(updateOptions).execute(); assertNotNull(response); assertNotNull(response.getExampleText()); assertEquals(response.getExampleText(), exampleText2); assertEquals(response.getMentions(), mentionsList); } catch (Exception ex) { fail(ex.getMessage()); } finally { DeleteExampleOptions deleteOptions = new DeleteExampleOptions.Builder(workspaceId, exampleIntent, exampleText2) .build(); service.deleteExample(deleteOptions).execute(); } }
Source:
<code>public Map<String, Boolean> getCollaboratorRoles(String userName, String projectId) { Map<String, Boolean> collaboratorRolesMap = new HashMap<String, Boolean>(); collaboratorRolesMap.put(RoleNames.ROLE_PROJ_COLLABORATOR_ADMIN, false); collaboratorRolesMap.put(RoleNames.ROLE_PROJ_COLLABORATOR_CONTRIBUTOR, false); collaboratorRolesMap.put(RoleNames.ROLE_PROJ_COLLABORATOR_EDITOR, false); List<String> userDBRoles = accessManager.getProjectCollaboratorRoles(userName, projectId); for (int i = 0; i < userDBRoles.size(); i++) { collaboratorRolesMap.put( roleManager.getQuadrigaRoleByDbId(IQuadrigaRoleManager.PROJECT_ROLES, userDBRoles.get(i)).getId(), true); } <START> return collaboratorRolesMap; <END> }</code><technical_language>return a list roles a user has</technical_language>

Target:
public List<String> getCollaboratorRoles(String userName, String projectId) { List<String> userDBRoles = accessManager.getProjectCollaboratorRoles(userName, projectId); List<String> collaboratorRoles = new ArrayList<String>(); userDBRoles.forEach(userDBRole -> collaboratorRoles .add(roleManager.getQuadrigaRoleByDbId(IQuadrigaRoleManager.PROJECT_ROLES, userDBRole).getId())); return collaboratorRoles; }
Source:
<code>SweepOutcome runOnce() { Optional<TableToSweep> tableToSweepOptional = getTableToSweep(); if (!tableToSweepOptional.isPresent()) { log.debug("Skipping sweep because no table has enough new writes to be worth sweeping at the moment."); return SweepOutcome.NOTHING_TO_SWEEP; } TableToSweep tableToSweep = tableToSweepOptional.get(); SweepBatchConfig batchConfig = sweepBatchConfigSource.getAdjustedSweepConfig(); <START> if (StreamTableType.isStreamStoreValueTable(tableToSweep.getTableRef())) { <END> batchConfig = SweepBatchConfig.min(batchConfig, STREAM_STORE_BATCH_CONFIG); } try { specificTableSweeper.runOnceAndSaveResults(tableToSweep, batchConfig); return SweepOutcome.SUCCESS; } catch (InsufficientConsistencyException e) { log.warn("Could not sweep because not all nodes of the database are online.", e); return SweepOutcome.NOT_ENOUGH_DB_NODES_ONLINE; } catch (RuntimeException e) { specificTableSweeper.getSweepMetrics().sweepError(); return determineCauseOfFailure(e, tableToSweep); } }</code><technical_language>I this is a bit odd. override config here, decreasing basic sweep config scenes, eventually get point this decreased onfig defer increases again. This a problems. Metrics batchSizeMultiplier wrong times, logging decrease metrics is incorrect backoff failure for 4 failures stream store. If push override config AdjustableBatchConfigSource (just rename SweepBatchConfigSource) hide complexity in there, get metrics logging right backoffs work normal. pass in table name figure out table type is. This some nice properties in future - other special cases for other table types remember reset batch config change table</technical_language>

Target:
SweepOutcome runOnce() { Optional<TableToSweep> tableToSweep = getTableToSweep(); if (!tableToSweep.isPresent()) { log.debug("Skipping sweep because no table has enough new writes to be worth sweeping at the moment."); return SweepOutcome.NOTHING_TO_SWEEP; } SweepBatchConfig batchConfig = sweepBatchConfigSource.getAdjustedSweepConfig(); try { specificTableSweeper.runOnceAndSaveResults(tableToSweep.get(), batchConfig); return SweepOutcome.SUCCESS; } catch (InsufficientConsistencyException e) { log.warn("Could not sweep because not all nodes of the database are online.", e); return SweepOutcome.NOT_ENOUGH_DB_NODES_ONLINE; } catch (RuntimeException e) { specificTableSweeper.getSweepMetrics().sweepError(); return determineCauseOfFailure(e, tableToSweep.get()); } }
Source:
<code>TopologySchedulingResources(Cluster cluster, TopologyDetails td) { remainingResourcesSet = false; metrics = new ResourceMetrics(new StormMetricsRegistry()); <START> clusterAvailableResources = cluster.getNonBlacklistedClusterAvailableResources(Collections.emptyList()); <END> clusterAvailableMemory = clusterAvailableResources.getTotalMemoryMb(); topologyRequiredResources = td.getApproximateTotalResources(); topologyRequiredNonSharedMemory = td.getRequestedNonSharedOffHeap() + td.getRequestedNonSharedOnHeap(); topologySharedMemoryLowerBound = td.getRequestedSharedOffHeap() + td.getRequestedSharedOnHeap(); setScheduledTopologyResources(cluster, td); }</code><technical_language>happen if some supervisors blacklisted</technical_language>

Target:
TopologySchedulingResources(Cluster cluster, TopologyDetails td) { remainingResourcesAreSet = false; clusterAvailableResources = cluster.getNonBlacklistedClusterAvailableResources(Collections.emptyList()); clusterAvailableMemory = clusterAvailableResources.getTotalMemoryMb(); topologyRequiredResources = td.getApproximateTotalResources(); topologyRequiredNonSharedMemory = td.getRequestedNonSharedOffHeap() + td.getRequestedNonSharedOnHeap(); topologySharedMemoryLowerBound = td.getRequestedSharedOffHeap() + td.getRequestedSharedOnHeap(); setScheduledTopologyResources(cluster, td); }
Source:
<code>public Set<String> getRoleViews(final String id) { String ref = getReference(id); LinkedHashSet<String> roleIds = new LinkedHashSet<String>(); AuthzGroup realm = null; try { realm = m_authzGroupService.getAuthzGroup(ref); } catch (GroupNotDefinedException e) { return roleIds; } <START> if (realm == null) { <END> return roleIds; } Set<Role> roles = realm.getRoles(); for (Role role : roles) { roleIds.add(role.getId()); } return roleIds; }</code><technical_language>I realm null</technical_language>

Target:
public Set<String> getRoleViews(final String id) { String ref = getReference(id); LinkedHashSet<String> roleIds = new LinkedHashSet<String>(); AuthzGroup realm = null; try { realm = m_authzGroupService.getAuthzGroup(ref); } catch (GroupNotDefinedException e) { return roleIds; } Set<Role> roles = realm.getRoles(); for (Role role : roles) { roleIds.add(role.getId()); } return roleIds; }
Source:
<code>public void testZstdConfWithMr() throws Exception { JobConf jobConf = new JobConf(); Configuration conf = new Configuration(); jobConf.setInt(ZstandardCodec.PARQUET_COMPRESS_ZSTD_LEVEL, 18); <START> jobConf.setInt(ZstandardCodec.PARQUET_COMPRESS_ZSTD_LEVEL, 4); <END> RunningJob mapRedJob = runMapReduceJob(CompressionCodecName.ZSTD, jobConf, conf); assert(mapRedJob.isSuccessful()); }</code><technical_language>setting level (and workers missing)</technical_language>

Target:
public void testZstdConfWithMr() throws Exception { long fileSizeLowLevel = runMrWithConf(1); CodecFactory.CODEC_BY_NAME.clear(); long fileSizeHighLevel = runMrWithConf(22); Assert.assertTrue(fileSizeLowLevel > fileSizeHighLevel); }
Source:
<code>public void saveOrUpdateCohorts(List<Cohort> cohorts) throws CohortSaveException { try { for(Cohort cohort: cohorts){ if(cohortService.getCohortByUuid(cohort.getUuid()) == null){ cohortService.saveCohort(cohort); } else { cohortService.updateCohort(cohort); } } <START> cohortService.saveCohorts(cohorts); <END> } catch (IOException e) { throw new CohortSaveException(e); } }</code><technical_language>Is this call supposed loop</technical_language>

Target:
public void saveOrUpdateCohorts(List<Cohort> cohorts) throws CohortSaveException { try { for(Cohort cohort:cohorts){ if(StringUtils.isEmpty(cohort.getUuid())){ cohortService.saveCohort(cohort); } else { cohortService.updateCohort(cohort); } } } catch (IOException e) { throw new CohortSaveException(e); } }
Source:
<code>public void testDesanitizeFromHtmlSet() { Set<String> sanitizedHtml = generateSanitizedHtmlSet(); Set<String> desanitizedHtml = generateUnsanitizedHtmlSet(); assertEquals(desanitizedHtml, SanitizationHelper.desanitizeFromHtml(sanitizedHtml)); assertEquals(new HashSet<>(), SanitizationHelper.desanitizeFromHtml(new HashSet<>())); <START> assertEquals(null, SanitizationHelper.desanitizeFromHtml((Set<String>) null)); <END> }</code><technical_language>assertNull</technical_language>

Target:
public void testDesanitizeFromHtmlSet() { Set<String> sanitizedHtml = new HashSet<>(Arrays.asList( "apple &lt;", "banana &#39; dogs ", "rollercoasters &amp; tycoons", "", null) ); Set<String> desanitizedHtml = new HashSet<>(Arrays.asList( "apple <", "banana ' dogs ", "rollercoasters & tycoons", "", null) ); assertEquals(desanitizedHtml, SanitizationHelper.desanitizeFromHtml(sanitizedHtml)); assertEquals(new HashSet<>(), SanitizationHelper.desanitizeFromHtml(new HashSet<>())); assertNull(SanitizationHelper.desanitizeFromHtml((Set<String>) null)); }
Source:
<code>private static Target lookupTarget(StructDefinition streamPacketContextDef, boolean hasDevice, Long cpuId) { Target ret = new Target(); if (hasDevice) { IDefinition def = streamPacketContextDef.lookupDefinition(CTFStrings.DEVICE); if (def instanceof SimpleDatatypeDefinition) { SimpleDatatypeDefinition simpleDefinition = (SimpleDatatypeDefinition) def; ret.string = simpleDefinition.getStringValue(); ret.number = simpleDefinition.getIntegerValue(); } else if (def instanceof StringDefinition) { StringDefinition stringDefinition = (StringDefinition) def; ret.string = stringDefinition.getValue(); <START> ret.number = Integer.parseInt(ret.string.replaceAll("[\\D]", "")); END> } } else if (cpuId != null) { ret.string = ("CPU" + cpuId.toString()); ret.number = cpuId; } return ret; }</code><technical_language>This fail if device is a String digits. extract string check length</technical_language>

Target:
private static Target lookupTarget(StructDefinition streamPacketContextDef, boolean hasDevice, Long cpuId) { Target ret = new Target(); if (hasDevice) { IDefinition def = streamPacketContextDef.lookupDefinition(CTFStrings.DEVICE); if (def instanceof SimpleDatatypeDefinition) { SimpleDatatypeDefinition simpleDefinition = (SimpleDatatypeDefinition) def; ret.string = simpleDefinition.getStringValue(); ret.number = simpleDefinition.getIntegerValue(); } else if (def instanceof StringDefinition) { StringDefinition stringDefinition = (StringDefinition) def; ret.string = stringDefinition.getValue(); final Matcher matcher = NUMBER_PATTERN.matcher(ret.string); if(matcher.find()){ String number = matcher.group(0); ret.number = Integer.parseInt(number); } } } else if (cpuId != null) { ret.string = ("CPU" + cpuId.toString()); ret.number = cpuId; } return ret; }
Source:
<code>private boolean isSequenceElement(Object notifier) { boolean isSequenceElement = false; <START> View view = null; <END> if (notifier instanceof EObject) { if (notifier instanceof View) { view = (View) notifier; } else if (((EObject) notifier).eContainer() instanceof View) { view = (View) ((EObject) notifier).eContainer(); } } if (view != null) { if (view.eContainer() instanceof View && (CombinedFragment.compartmentNotationPredicate().apply(view) || Operand.compartmentNotationPredicate().apply(view))) { view = (View) view.eContainer(); } Option<ISequenceElement> sequenceElementOption = ISequenceElementAccessor.getISequenceElement(view); isSequenceElement = sequenceElementOption.some(); } return isSequenceElement; }</code><technical_language>Add this part of code if (notifier instanceof EObject) {</technical_language>

Target:
private boolean isSequenceElement(Object notifier) { boolean isSequenceElement = false; if (notifier instanceof EObject) { View view = null; if (notifier instanceof View) { view = (View) notifier; } else if (((EObject) notifier).eContainer() instanceof View) { view = (View) ((EObject) notifier).eContainer(); } if (view != null) { isSequenceElement = ISequenceElementAccessor.isPartOfSequenceElement(view); } } return isSequenceElement; }
Source:
<code>public static <T extends MessageOrBuilder> List<T> readMessages(Path file, Class<T> messageClass) throws IOException { ParquetReader.Builder readerBuilder = ProtoParquetReader.builder(file); if (messageClass != null) { readerBuilder.set(ProtoReadSupport.PB_CLASS, messageClass.getName()).build(); } ParquetReader reader = readerBuilder.build(); <START> try { <END> List<T> result = new ArrayList<T>(); boolean hasNext = true; while (hasNext) { T item = (T) reader.read(); if (item == null) { hasNext = false; } else { result.add((T) asMessage(item)); } } return result; } finally { reader.close(); } }</code><technical_language>try-with-resource construct</technical_language>

Target:
public static <T extends MessageOrBuilder> List<T> readMessages(Path file, Class<T> messageClass) throws IOException { ParquetReader.Builder readerBuilder = ProtoParquetReader.builder(file); if (messageClass != null) { readerBuilder.set(ProtoReadSupport.PB_CLASS, messageClass.getName()).build(); } try (ParquetReader reader = readerBuilder.build()) { List<T> result = new ArrayList<T>(); boolean hasNext = true; while (hasNext) { T item = (T) reader.read(); if (item == null) { hasNext = false; } else { result.add((T) asMessage(item)); } } return result; } }
Source:
<code>public void init() { clearAll(); alertPolicy = policyService.alert().create( new AlertPolicyConfig() .name("Sample Alert Policy") .action(new AlertAction() .settings(new ActionSettingsEmail("sampleuser@samplecompany.com"))) .triggers( <START> new AlertTrigger().duration(5).metric(AlertTriggerMetric.CPU).threshold(52.0f) <END> ) ).waitUntilComplete().getResult(); antiAffinityPolicy = policyService.antiAffinity().create( new AntiAffinityPolicyConfig() .dataCenter(DataCenter.US_EAST_NEW_YORK) .name(antiAffinityPolicyName) ).waitUntilComplete().getResult(); server = serverService.create(new CreateServerConfig() .name("plc") .group(Group.refByName(DataCenter.US_EAST_NEW_YORK, Group.DEFAULT_GROUP)) .description("Sample server for policies") .type(HYPERSCALE) .machine(new Machine() .cpuCount(1) .ram(1) ) .template(Template.refByOs() .dataCenter(DataCenter.US_EAST_NEW_YORK) .type(CENTOS) .version("6") .architecture(x86_64) ) .timeToLive( ZonedDateTime.now().plusHours(2) ) .antiAffinityPolicy(antiAffinityPolicy) ) .waitUntilComplete().getResult().asRefById(); }</code><technical_language>if magic numbers 5 52.0f encapsulate separate variables informative names</technical_language>

Target:
public void init() { clearAll(); int initDuration = 5; float initThreshold = 52f; alertPolicy = policyService.alert().create( new AlertPolicyConfig() .name("Sample Alert Policy") .action(new AlertAction() .settings(new ActionSettingsEmail("sampleuser@samplecompany.com"))) .triggers( new AlertTrigger().duration(initDuration).metric(AlertTriggerMetric.CPU).threshold(initThreshold) ) ).waitUntilComplete().getResult(); antiAffinityPolicy = policyService.antiAffinity().create( new AntiAffinityPolicyConfig() .dataCenter(DataCenter.US_EAST_NEW_YORK) .name(antiAffinityPolicyName) ).waitUntilComplete().getResult(); server = serverService.create(new CreateServerConfig() .name("plc") .group(Group.refByName(DataCenter.US_EAST_NEW_YORK, Group.DEFAULT_GROUP)) .description("Sample server for policies") .type(HYPERSCALE) .machine(new Machine() .cpuCount(1) .ram(1) ) .template(Template.refByOs() .dataCenter(DataCenter.US_EAST_NEW_YORK) .type(CENTOS) .version("6") .architecture(x86_64) ) .timeToLive( ZonedDateTime.now().plusHours(2) ) .antiAffinityPolicy(antiAffinityPolicy) ) .waitUntilComplete().getResult().asRefById(); }
Source:
<code>protected A param(String key, int val) { params.put(key, Integer.toString(val)); <START> @SuppressWarnings("unchecked") END> A result = (A) this; return result; }</code><technical_language>minor nit: replace returns java private A getInstance() { @SuppressWarnings("unchecked"); return (A) this; } // return this.getInstance();</technical_language>

Target:
protected A param(String key, int val) { return this.param(key, Integer.toString(val)); }
Source:
<code>protected Schema generateSchema() { final Schema leftSchema = getLeft().getSchema(); if (leftSchema == null) { return null; } final Schema rightSchema = getRight().getSchema(); if (rightSchema == null) { return null; } ImmutableList.Builder<Type> types = ImmutableList.builder(); ImmutableList.Builder<String> names = ImmutableList.builder(); for (int i = 0; i < rightCompareColumns.length; ++i) { int leftIndex = leftCompareColumns[i]; int rightIndex = rightCompareColumns[i]; Type leftType = leftSchema.getColumnType(leftIndex); Type rightType = rightSchema.getColumnType(rightIndex); Preconditions.checkState( leftType == rightType, "column types do not match for join op %s at index %s: left column type %s [%s] != right column type %s [%s]", <START> getOpId() + "", <END> i, leftIndex, leftType, rightIndex, rightType); } for (int i : leftAnswerColumns) { types.add(leftSchema.getColumnType(i)); names.add(leftSchema.getColumnName(i)); } for (int i : rightAnswerColumns) { types.add(rightSchema.getColumnType(i)); names.add(rightSchema.getColumnName(i)); } if (outputColumns != null) { return new Schema(types.build(), outputColumns); } else { return new Schema(types, names); } }</code><technical_language>(Integer) result of getOpId() require coercion a String i not? In case, I %d work for int Integer</technical_language>

Target:
protected Schema generateSchema() { final Schema leftSchema = getLeft().getSchema(); if (leftSchema == null) { return null; } final Schema rightSchema = getRight().getSchema(); if (rightSchema == null) { return null; } ImmutableList.Builder<Type> types = ImmutableList.builder(); ImmutableList.Builder<String> names = ImmutableList.builder(); for (int i = 0; i < rightCompareColumns.length; ++i) { int leftIndex = leftCompareColumns[i]; int rightIndex = rightCompareColumns[i]; Type leftType = leftSchema.getColumnType(leftIndex); Type rightType = rightSchema.getColumnType(rightIndex); Preconditions.checkState( leftType == rightType, "column types do not match for join op %s at index %s: left column type %s [%s] != right column type %s [%s]", getOpId(), i, leftIndex, leftType, rightIndex, rightType); } for (int i : leftAnswerColumns) { types.add(leftSchema.getColumnType(i)); names.add(leftSchema.getColumnName(i)); } for (int i : rightAnswerColumns) { types.add(rightSchema.getColumnType(i)); names.add(rightSchema.getColumnName(i)); } if (outputColumns != null) { return new Schema(types.build(), outputColumns); } else { return new Schema(types, names); } }
Source:
<code>public void add(Edge<I, E> edge) { ExtendedDataOutput extendedDataOutput = getConf().createExtendedDataOutput( serializedEdges, serializedEdgesBytesUsed); try { WritableUtils.writeEdge(extendedDataOutput, edge); } catch (IOException e) { throw new IllegalStateException("add: Failed to write to the new " + "byte array"); } catch (NegativeArraySizeException negativeArraySizeException) { throw new IllegalStateException("add: Too many edges for a vertex, " + <START> edge.getTargetVertexId() + "hence failed to write to byte array"); <END> } serializedEdges = extendedDataOutput.getByteArray(); serializedEdgesBytesUsed = extendedDataOutput.getPos(); ++edgeCount; }</code><technical_language>suggestion edge.getTargetVertexId() + " failed write byte array");</technical_language>

Target:
public void add(Edge<I, E> edge) { ExtendedDataOutput extendedDataOutput = getConf().createExtendedDataOutput( serializedEdges, serializedEdgesBytesUsed); try { WritableUtils.writeEdge(extendedDataOutput, edge); } catch (IOException e) { throw new IllegalStateException("add: Failed to write to the new " + "byte array"); } catch (NegativeArraySizeException negativeArraySizeException) { throw new IllegalStateException("add: Too many edges for a vertex, " + "hence failed to write to byte array"); } serializedEdges = extendedDataOutput.getByteArray(); serializedEdgesBytesUsed = extendedDataOutput.getPos(); ++edgeCount; }
Source:
<code>public Diagnosis voidDiagnosis(Diagnosis diagnosis, String voidReason) { diagnosis.setVoided(true); <START> diagnosis.setVoidedBy(Context.getAuthenticatedUser()); <END> diagnosis.setVoidReason(voidReason); diagnosis.setDateVoided(new Date()); return save(diagnosis); }</code><technical_language>get a chance voidObs in ObsServiceImpl</technical_language>

Target:
public Diagnosis voidDiagnosis(Diagnosis diagnosis, String voidReason) { return Context.getDiagnosisService().save(diagnosis); }
Source:
<code>public void testWithCacheWithNoViolation() throws Exception { final TreeWalker treeWalker = new TreeWalker(); treeWalker.configure(createCheckConfig(TypeNameCheck.class)); final PackageObjectFactory factory = new PackageObjectFactory( new HashSet<>(), Thread.currentThread().getContextClassLoader()); treeWalker.setModuleFactory(factory); treeWalker.setupChild(createCheckConfig(TypeNameCheck.class)); final File file = temporaryFolder.newFile("file.java"); final List<String> lines = new ArrayList<>(); lines.add(" class a "); try { treeWalker.processFiltered(file, lines); } catch (CheckstyleException ex) { <START> fail("Exception is not expected"); <END> } }</code><technical_language>IMO, this expected build tests. Exceptions thrown method runner display full stacktrace user for debugging if is expected. catch fail a simple message. asserting some actual result in this test</technical_language>

Target:
public void testWithCacheWithNoViolation() throws Exception { final TreeWalker treeWalker = new TreeWalker(); treeWalker.configure(createCheckConfig(TypeNameCheck.class)); final PackageObjectFactory factory = new PackageObjectFactory( new HashSet<>(), Thread.currentThread().getContextClassLoader()); treeWalker.setModuleFactory(factory); treeWalker.setupChild(createCheckConfig(TypeNameCheck.class)); final File file = temporaryFolder.newFile("file.java"); final List<String> lines = new ArrayList<>(); lines.add(" class a "); treeWalker.processFiltered(file, lines); }
Source:
<code><START> public boolean equals(Object obj) { <END> if (caseType.equals(obj)) { return true; } return false; }</code><technical_language>fields included in equals hashcode methods? a side note, java7's Objects.equals reduce complexity retain effect</technical_language>

Target:
public boolean equals(Object obj) { CaseTypeWithApplicationName o = (CaseTypeWithApplicationName) obj; return Objects.equals(this.caseType, o.caseType) && Objects.equals(this.applicationName, o.applicationName) && Objects.equals(this.caseProperties, o.caseProperties); }
Source:
<code>private int getHorseFlags() { int value = 0; if (isTamed()) { value |= 0x02; } if (this instanceof GlowHorse) { GlowHorse horse = (GlowHorse) this; <START> if (getInventory() != null && getInventory().getSaddle() != null) { <END> value |= 0x04; } if (horse.hasReproduced()) { value |= 0x10; } if (horse.isEatingHay()) { value |= 0x20; } } if (this instanceof ChestedHorse) { ChestedHorse horse = (ChestedHorse) this; if (horse.isCarryingChest()) { value |= 0x08; } } return value; }</code><technical_language>Replace null check for saddle InventoryUtil.isEmpty</technical_language>

Target:
private int getHorseFlags() { int value = 0; if (isTamed()) { value |= 0x02; } if (this instanceof GlowHorse) { GlowHorse horse = (GlowHorse) this; if (getInventory() != null && !InventoryUtil.isEmpty(getInventory().getSaddle())) { value |= 0x04; } if (horse.hasReproduced()) { value |= 0x10; } if (horse.isEatingHay()) { value |= 0x20; } } if (this instanceof ChestedHorse) { ChestedHorse horse = (ChestedHorse) this; if (horse.isCarryingChest()) { value |= 0x08; } } return value; }
Source:
<code>public ApplicationInstance deletePendingInstance(String instanceId){ ResponseEntity<ApplicationInstance> respAppInstance = kernel.exchange(appsEndpoint + "/instance/{instance_id}", HttpMethod.GET, null, ApplicationInstance.class, user(), instanceId); <START> String eTag = respAppInstance.getHeaders().getETag(); <END> HttpHeaders headers = new HttpHeaders(); headers.add("If-Match", eTag); ResponseEntity<ApplicationInstance> object = kernel.exchange(appsEndpoint + "/instance/{instanceId}", HttpMethod.DELETE, new HttpEntity<>(null,headers), ApplicationInstance.class, user(), instanceId); logger.debug("Delete pending instance", object); return object.getBody(); }</code><technical_language>Verify instance is pending? (someone delete already, provisioned) Ideally (but rewrite portal point, sigh), etag (have been) data client, server action is user, this GET request is necessary. if action failed a 412 Precondition Failed portal possibly retry action (in this case, a GET checking status is pending) and/or bubble error client, refresh data: user updated data retry (if possible), decide else (for example, if instance provisioned in load of data moment user wanted cancel provisioning, choose app, delete it; decide do, depending reasons cancel provisioning with)</technical_language>

Target:
public ApplicationInstance deletePendingInstance(String instanceId){ ResponseEntity<ApplicationInstance> respAppInstance = kernel.exchange(appsEndpoint + "/instance/{instance_id}", HttpMethod.GET, null, ApplicationInstance.class, user(), instanceId); if(!Objects.requireNonNull(respAppInstance.getBody()).getStatus().equals(ApplicationInstance.InstantiationStatus.PENDING)){ throw new WrongQueryException("Instance is not pending",409); } String eTag = respAppInstance.getHeaders().getETag(); HttpHeaders headers = new HttpHeaders(); headers.add("If-Match", eTag); ResponseEntity<ApplicationInstance> object = kernel.exchange(appsEndpoint + "/instance/{instanceId}", HttpMethod.DELETE, new HttpEntity<>(null,headers), ApplicationInstance.class, user(), instanceId); logger.debug("Delete pending instance", object); return object.getBody(); }
Source:
<code>public void unbind() { <START> if (LiteDownloadMigrationService.isBound() && migrationCallback != null) { <END> context.unbindService(serviceConnection); context.stopService(new Intent(context, LiteDownloadMigrationService.class)); serviceConnection = null; } }</code><technical_language>bind here, hold a reference service this non-static. static access service is needed (regarding MigrationDownloadServiceBinder), check is done <LINK_0></technical_language>

Target:
public void unbind() { if (serviceConnection != null) { context.unbindService(serviceConnection); context.stopService(new Intent(context, LiteDownloadMigrationService.class)); serviceConnection = null; } }
Source:
<code>private void assertSuggestion(String query, String expectedName, List<LatLon> expectedGeo) { List<Suggestion> list = new LinkedList<>(); processor.enhanceResults(list, query); <START> assertThat(list, is(not(empty()))); <END> assertThat(list, hasSize(1)); LiteralSuggestion literalSuggestion = (LiteralSuggestion) list.get(0); assertThat(literalSuggestion.getId(), is("LITERAL-DMS")); assertThat(literalSuggestion.getName(), is(expectedName)); assertThat(literalSuggestion.hasGeo(), is(true)); List<LatLon> actualGeo = literalSuggestion.getGeo(); List<LatLon> diff = new ArrayList<>(); assertThat( "Actual geo and expected geo are the same size", actualGeo.size(), is(equalTo(expectedGeo.size()))); for (int i = 0; i < expectedGeo.size(); i++) { LatLon actual = actualGeo.get(i); LatLon expected = expectedGeo.get(i); Double latDiff = actual.getLat() - expected.getLat(); Double lonDiff = actual.getLon() - expected.getLon(); if (Math.abs(latDiff) > 0.00001 || Math.abs(lonDiff) > 0.00001) { diff.add(actual); } } assertThat("Actual geo is the same as the expected geo", diff, is(empty())); }</code><technical_language>need this a hasSize() assertion</technical_language>

Target:
private void assertSuggestion(String query, String expectedName, List<LatLon> expectedGeo) { List<Suggestion> list = new LinkedList<>(); processor.enhanceResults(list, query); assertThat(list, hasSize(1)); LiteralSuggestion literalSuggestion = (LiteralSuggestion) list.get(0); assertThat(literalSuggestion.getId(), is("LITERAL-DMS")); assertThat(literalSuggestion.getName(), is(expectedName)); assertThat(literalSuggestion.hasGeo(), is(true)); List<LatLon> actualGeo = literalSuggestion.getGeo(); List<LatLon> diff = new ArrayList<>(); assertThat( "Actual geo and expected geo are not the same size", actualGeo.size(), is(equalTo(expectedGeo.size()))); for (int i = 0; i < expectedGeo.size(); i++) { LatLon actual = actualGeo.get(i); LatLon expected = expectedGeo.get(i); Double latDiff = actual.getLat() - expected.getLat(); Double lonDiff = actual.getLon() - expected.getLon(); if (Math.abs(latDiff) > 0.00001 || Math.abs(lonDiff) > 0.00001) { diff.add(actual); } } assertThat("Actual geo is not the same as the expected geo", diff, is(empty())); }
Source:
<code>public void testAcceptNullFileContents() { final SuppressWithNearbyCommentFilter filter = new SuppressWithNearbyCommentFilter(); <START> final TreeWalkerAuditEvent auditEvent = new TreeWalkerAuditEvent(null, null, <END> new LocalizedMessage(1, null, null, null, null, Object.class, null), null); assertTrue("Filter should accept audit event", filter.accept(auditEvent)); }</code><technical_language>nulls in arguments, please variable content = null in constructor. Please apply for other test method changed</technical_language>

Target:
public void testAcceptNullFileContents() { final SuppressWithNearbyCommentFilter filter = new SuppressWithNearbyCommentFilter(); final FileContents contents = null; final TreeWalkerAuditEvent auditEvent = new TreeWalkerAuditEvent(contents, null, new LocalizedMessage(1, null, null, null, null, Object.class, null), null); assertTrue("Filter should accept audit event", filter.accept(auditEvent)); }
Source:
<code>public Builder withProtocolVersion(ProtocolVersion version) { if (allowBetaProtocolVersion) throw new IllegalStateException("Can not set the version explicitly if `allowBetaProtocolVersion` was used."); <START> if (version.toInt() > ProtocolVersion.NEWEST_SUPPORTED.toInt()) <END> throw new IllegalArgumentException("Can not use " + version + " protocol version. " + "Newest supported protocol version is: " + ProtocolVersion.NEWEST_SUPPORTED + ". " + "For beta versions, use `allowBetaProtocolVersion` instead"); this.protocolVersion = version; return this; }</code><technical_language>Small nit: I prefer version.compareTo(ProtocolVersion.NEWEST_SUPPORTED) > 0</technical_language>

Target:
public Builder withProtocolVersion(ProtocolVersion version) { if (allowBetaProtocolVersion) throw new IllegalStateException("Can not set the version explicitly if `allowBetaProtocolVersion` was used."); if (version.compareTo(ProtocolVersion.NEWEST_SUPPORTED) > 0) throw new IllegalArgumentException("Can not use " + version + " protocol version. " + "Newest supported protocol version is: " + ProtocolVersion.NEWEST_SUPPORTED + ". " + "For beta versions, use `allowBetaProtocolVersion` instead"); this.protocolVersion = version; return this; }
Source:
<code><START> public void spoutFailedTuple(String streamId) { <END> String key = streamId; String metricName = METRIC_NAME_FAILED + "-" + key; Counter c = this.counters.get(metricName); if (c == null) { c = metricRegistry.counter(metricName, this.topologyId, this.componentId, this.taskId, this.workerPort, streamId); this.counters.put(metricName, c); } c.inc(this.samplingRate); }</code><technical_language>related this PR. some point, need update <LINK_3> <LINK_0> " is average amount of time for ack fail called". latency is calculated ack fail. original code <LINK_1> is implemented same. I this is a mistake introduced in <LINK_2></technical_language>

Target:
public void spoutFailedTuple(String streamId) { String key = streamId; String metricName = METRIC_NAME_FAILED + "-" + key; Counter c = this.getCounter(metricName, streamId); c.inc(this.samplingRate); }
Source:
<code>private static Map<String, String> normalizeJUnitOutput(String input) throws IOException { <START> BufferedReader bufReader = new BufferedReader(new StringReader(input)); <END> String methodName = null; Map<String, String> resultMap = new HashMap<>(); StringBuilder result = new StringBuilder(); int index = 1; for (String line; (line = bufReader.readLine()) != null; ) { String indexStr = index + ") "; if (line.startsWith(indexStr)) { if (methodName != null) { resultMap.put(methodName, result.toString()); result.setLength(0); } methodName = line; index += 1; } else if (line.isEmpty()) { resultMap.put(methodName, result.toString()); break; } else if (methodName != null) { int lParenIndex = line.indexOf('('); if (lParenIndex >= 0) { line = line.substring(0, lParenIndex); } result.append(line).append(Globals.lineSep); } } bufReader.close(); return resultMap; }</code><technical_language>I suggest try-with-resources call close (and reader is closed if exception is thrown)</technical_language>

Target:
private static Map<String, String> normalizeJUnitOutput(String input) { BufferedReader bufReader = new BufferedReader(new StringReader(input)); String methodName = null; Map<String, String> resultMap = new HashMap<>(); StringBuilder result = new StringBuilder(); int index = 1; try { for (String line; (line = bufReader.readLine()) != null; ) { String indexStr = index + ") "; if (line.startsWith(indexStr)) { if (methodName != null) { resultMap.put(methodName, result.toString()); result.setLength(0); } methodName = line; index += 1; } else if (line.isEmpty()) { resultMap.put(methodName, result.toString()); break; } else if (methodName != null) { int lParenIndex = line.indexOf('('); if (lParenIndex >= 0) { line = line.substring(0, lParenIndex); } result.append(line).append(Globals.lineSep); } } bufReader.close(); } catch (IOException e) { throw new RuntimeException(e); } return resultMap; }
Source:
<code>public void testConcurrentModificationException() { org.robolectric.shadows.ShadowLog.stream = System.err; final Context applicationContext = ShadowApplication.getInstance().getApplicationContext(); final AndroidModel model = new AndroidModel("4.4.2", "KOT49H", "Nexus 4", "LGE"); final ModelSpecificDistanceCalculator distanceCalculator = new ModelSpecificDistanceCalculator(applicationContext, null, model); Runnable runnable2 = new Runnable() { @Override public void run() { try { while (true) { distanceCalculator._buildModelMapTest("{\n" + " \"models\":\n" + <START> " [\n" + <END> " {\n" + " \"coefficient1\": 0.42093,\n" + " \"coefficient2\": 6.9476,\n" + " \"coefficient3\": 0.54992,\n" + " \"version\":\"4.4.2\",\n" + " \"build_number\":\"KOT49H\",\n" + " \"model\":\"Nexus 4\",\n" + " \"manufacturer\":\"LGE\"\n" + " },\n" + " {\n" + " \"coefficient1\": 0.42093,\n" + " \"coefficient2\": 6.9476,\n" + " \"coefficient3\": 0.54992,\n" + " \"version\":\"4.4.2\",\n" + " \"build_number\":\"LPV79\",\n" + " \"model\":\"Nexus 5\",\n" + " \"manufacturer\":\"LGE\",\n" + " \"default\": true\n" + " }\n" + " ]\n" + "}"); } } catch (Exception ex) { ex.printStackTrace(); } } }; Thread thread2 = new Thread(runnable2); thread2.start(); int i = 0; while (++i < 1000 && thread2.getState() != Thread.State.TERMINATED) { distanceCalculator._findCalculatorForModelTest(model); } thread2.interrupt(); }</code><technical_language>Lots of whitespace</technical_language>

Target:
public void testConcurrentModificationException() { org.robolectric.shadows.ShadowLog.stream = System.err; final Context applicationContext = ShadowApplication.getInstance().getApplicationContext(); final AndroidModel model = new AndroidModel("4.4.2", "KOT49H", "Nexus 4", "LGE"); final String modelMapJson = "{\"models\":[ \"coefficient1\": 0.89976,\"coefficient2\": 7.7095,\"coefficient3\": 0.111," + "\"version\":\"4.4.2\",\"build_number\":\"KOT49H\",\"model\":\"Nexus 4\"," + "\"manufacturer\":\"LGE\"},{\"coefficient1\": 0.42093,\"coefficient2\": 6.9476," + "\"coefficient3\": 0.54992,\"version\":\"4.4.2\",\"build_number\":\"LPV79\"," + "\"model\":\"Nexus 5\",\"manufacturer\":\"LGE\",\"default\": true}]}"; final ModelSpecificDistanceCalculator distanceCalculator = new ModelSpecificDistanceCalculator(applicationContext, null, model); Runnable runnable2 = new Runnable() { @Override public void run() { try { while (true) { distanceCalculator.buildModelMapWithLock(modelMapJson); } } catch (Exception ex) { ex.printStackTrace(); } } }; Thread thread2 = new Thread(runnable2); thread2.start(); int i = 0; while (++i < 1000 && thread2.getState() != Thread.State.TERMINATED) { distanceCalculator.findCalculatorForModelWithLock(model); } thread2.interrupt(); }