auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Map<String, String> fetchResources(String path) throws DeploymentEnvironmentException { Map<String, String> resources = new HashMap<String, String>(); Map<String, Object> map; FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(path)); map = (Map<String, Object>) new Yaml().load(fileInputStream); } catch (FileNotFoundException e) { throw new DeploymentEnvironmentException("Unable to find the profile for the given product", e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException ignore) { } } } <START> if (map.get(KIND).toString().equalsIgnoreCase(KIND_LIST)) { <END> for (LinkedHashMap item : (List<LinkedHashMap>) map.get(ITEMS)) { resources.put(item.get(KIND).toString(), new Yaml().dump(item)); } } else { resources.put(map.get(KIND).toString(), new Yaml().dump(map)); } return resources; }</code><technical_language>this checked in other avoid NPEs ? consider a practice</technical_language>

Target:
private Map<String, String> fetchResources(String path) throws DeploymentEnvironmentException { Map<String, String> resources = new HashMap<String, String>(); Map<String, Object> map; FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(path)); map = (Map<String, Object>) new Yaml().load(fileInputStream); } catch (FileNotFoundException e) { throw new DeploymentEnvironmentException("Unable to find the profile for the given product", e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException ignore) { } } } String kindValue = (map.get(KIND) != null) ? map.get(KIND).toString() : null; if (kindValue == null) { throw new DeploymentEnvironmentException("Kind property not found in Kubernetes resource: " + path); } if (kindValue.equalsIgnoreCase(LIST)) { List<LinkedHashMap> items = (List<LinkedHashMap>) map.get(ITEMS); for (LinkedHashMap item : items) { resources.put(item.get(KIND).toString(), new Yaml().dump(item)); } } else { resources.put(kindValue, new Yaml().dump(map)); } return resources; }
Source:
<code>private void validateNodeSourceNameOrFail(String nodeSourceName) { if (nodeSourceName.length() == 0) { throw new IllegalArgumentException("Node Source Name cannot be empty"); } <START> if (undeployedNodeSources.containsKey(nodeSourceName) || deployedNodeSources.containsKey(nodeSourceName)) { <END> throw new NodeSourceNameAlreadyExistException("Node Source name " + nodeSourceName + " already exist"); } Pattern pattern = Pattern.compile("[^-\\w]"); Matcher matcher = pattern.matcher(nodeSourceName); if (matcher.find()) { throw new IllegalArgumentException("Node Source name \"" + nodeSourceName + "\" is invalid because it contains invalid characters. Only [-a-zA-Z_0-9] are valid."); } }</code><technical_language>add this</technical_language>

Target:
private void validateNodeSourceNameOrFail(String nodeSourceName) { if (nodeSourceName.length() == 0) { throw new IllegalArgumentException("Node Source Name cannot be empty"); } if (this.undeployedNodeSources.containsKey(nodeSourceName) || this.deployedNodeSources.containsKey(nodeSourceName)) { throw new NodeSourceNameAlreadyExistException("Node Source name " + nodeSourceName + " already exist"); } Pattern pattern = Pattern.compile("[^-\\w]"); Matcher matcher = pattern.matcher(nodeSourceName); if (matcher.find()) { throw new IllegalArgumentException("Node Source name \"" + nodeSourceName + "\" is invalid because it contains invalid characters. Only [-a-zA-Z_0-9] are valid."); } }
Source:
<code>public void getCohortsContainingPatient_shouldReturnCohortsThatHaveGivenPatient() throws Exception { executeDataSet(COHORT_XML); <START> Patient patientToAdd = new Patient(7); <END> service.addPatientToCohort(service.getCohort(2), patientToAdd); assertTrue(service.getCohort(2).contains(patientToAdd)); List<Cohort> cohortsWithGivenPatient = service.getCohortsContainingPatient(patientToAdd); assertTrue(cohortsWithGivenPatient.contains(service.getCohort(2))); }</code><technical_language>changing patient 7 too</technical_language>

Target:
public void getCohortsContainingPatient_shouldReturnCohortsThatHaveGivenPatient() throws Exception { executeDataSet(COHORT_XML); Patient patientToAdd = new Patient(7); service.addPatientToCohort(service.getCohort(2), patientToAdd); assertTrue(service.getCohort(2).contains(patientToAdd.getPatientId())); List<Cohort> cohortsWithGivenPatient = service.getCohortsContainingPatient(patientToAdd); assertTrue(cohortsWithGivenPatient.contains(service.getCohort(2))); }
Source:
<code>public Entitlement ueberCertEntitlement(Consumer consumer, Pool pool) throws EntitlementRefusedException { Map<String, Integer> poolQuantities = new HashMap<String, Integer>(); poolQuantities.put(pool.getId(), 1); List<Entitlement> result = addOrUpdateEntitlements(consumer, poolQuantities, null, true, CallerType.UNKNOWN); <START> if (result != null && !result.isEmpty()) { <END> return result.get(0); } return null; }</code><technical_language>this "is null && is empty" check a lot in this PR. Commons-collections 3.2 adds a null-safe CollectionUtils.isEmpty() method. add a dependency (we're 3.1 currently) cut a lot of this boilerplate</technical_language>

Target:
public Entitlement ueberCertEntitlement(Consumer consumer, Pool pool) throws EntitlementRefusedException { Map<String, Integer> poolQuantities = new HashMap<String, Integer>(); poolQuantities.put(pool.getId(), 1); List<Entitlement> result = addOrUpdateEntitlements(consumer, poolQuantities, null, true, CallerType.UNKNOWN); if (CollectionUtils.isNotEmpty(result)) { return result.get(0); } return null; }
Source:
<code>public Step addStep(Step step) { lastUpdateTime = new Date(); step.setJobId(id); step.setStepNumber(steps.size()); step.setJobRepository(jobRepository); if (step.getDescription() == null) { step.setDescription(step.getStepName()); } step.setCorrelationId(correlationId); <START> <END> steps.add(step); jobRepository.saveStep(step); jobRepository.updateJobLastUpdateTime(id, lastUpdateTime); return step; }</code><technical_language>lines of code for updates DB. of is clear, open a 2 transaction, updates related, I understand committed together</technical_language>

Target:
public Step addStep(Step step) { lastUpdateTime = new Date(); step.setJobId(id); step.setStepNumber(steps.size()); if (step.getDescription() == null) { step.setDescription(step.getStepName()); } step.setCorrelationId(correlationId); steps.add(step); return step; }
Source:
<code>public boolean onHttpResponseReceive(HttpMessage msg) { if (frontEndScannerEnabled && msg.getResponseHeader().isHtml()) { try { String html = msg.getResponseBody().toString(); Source document = new Source(html); List<Element> heads = document.getAllElements("head"); Element head = heads.isEmpty() ? null : heads.get(0); if (head != null && msg.getHistoryRef() != null) { String host = msg.getRequestHeader().getHeader("host"); String frontEndApiUrl = API .getInstance() .getCallBackUrl(this.api, "https://" + host); int historyReferenceId = msg.getHistoryRef().getHistoryId(); <START> StringBuilder injectedContentBuilder = new StringBuilder() <END> .append("<script type='text/javascript'>") .append("var frontEndScanner=(function() {") .append("const HISTORY_REFERENCE_ID = " + historyReferenceId + ";") .append("const CALLBACK_ENDPOINT = '" + frontEndApiUrl + "';"); appendUserScriptsTo(injectedContentBuilder); appendFrontEndScannerCodeTo(injectedContentBuilder); injectedContentBuilder .append("})();") .append("</script>"); OutputDocument newResponseBody = new OutputDocument(document); int insertPosition = head.getChildElements().get(0).getBegin(); newResponseBody.insert(insertPosition, injectedContentBuilder.toString()); msg.getResponseBody() .setBody(newResponseBody.toString()); int newLength = msg.getResponseBody().length(); msg.getResponseHeader().setContentLength(newLength); } else { LOGGER.debug("<head></head> is missing in the response"); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } return true; }</code><technical_language>This initialised a higher capacity (500?)</technical_language>

Target:
public boolean onHttpResponseReceive(HttpMessage msg) { if (frontEndScannerEnabled && msg.getResponseHeader().isHtml()) { try { String html = msg.getResponseBody().toString(); Source document = new Source(html); List<Element> heads = document.getAllElements("head"); Element head = heads.isEmpty() ? null : heads.get(0); if (head != null && msg.getHistoryRef() != null) { String host = msg.getRequestHeader().getHeader("host"); String frontEndApiUrl = API .getInstance() .getCallBackUrl(this.api, "https://" + host); int historyReferenceId = msg.getHistoryRef().getHistoryId(); StringBuilder injectedContentBuilder = new StringBuilder(67000) .append("<script type='text/javascript'>") .append("var frontEndScanner=(function() {") .append("const HISTORY_REFERENCE_ID = " + historyReferenceId + ";") .append("const CALLBACK_ENDPOINT = '" + frontEndApiUrl + "';"); appendUserScriptsTo(injectedContentBuilder); appendFrontEndScannerCodeTo(injectedContentBuilder); injectedContentBuilder .append("})();") .append("</script>"); OutputDocument newResponseBody = new OutputDocument(document); int insertPosition = head.getChildElements().get(0).getBegin(); newResponseBody.insert(insertPosition, injectedContentBuilder.toString()); msg.getResponseBody() .setBody(newResponseBody.toString()); int newLength = msg.getResponseBody().length(); msg.getResponseHeader().setContentLength(newLength); } else { LOGGER.debug("<head></head> is missing in the response"); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } return true; }
Source:
<code>public void testGetValidSafeHTML() throws Exception { System.out.println("getValidSafeHTML"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); HTMLValidationRule rule = new HTMLValidationRule("test"); ESAPI.validator().addRule(rule); assertEquals("Test.", ESAPI.validator().getRule("test").getValid("test", "Test. <script>alert(document.cookie)</script>")); String test1 = "<b>Jeff</b>"; String result1 = instance.getValidSafeHTML("test", test1, 100, false, errors); assertEquals(test1, result1); String test2 = "<a href=\"<LINK_0>\">Aspect Security</a>"; String result2 = instance.getValidSafeHTML("test", test2, 100, false, errors); assertEquals(test2, result2); String test3 = "Test. <script>alert(document.cookie)</script>"; assertEquals("Test.", rule.getSafe("test", test3)); assertEquals("Test. &lt;<div>load=alert()</div>", rule.getSafe("test", "Test. <<div on<script></script>load=alert()")); assertEquals("Test. <div>b</div>", rule.getSafe("test", "Test. <div style={xss:expression(xss)}>b</div>")); <START> assertEquals("Test.", rule.getSafe("test", "Test. <script>alert(document.cookie)</script>")); <END> assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>")); assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>")); }</code><technical_language>drop null-byte test here? tests it, this is verifying validation works a special character interrupts payload. null-byte attack is a valid payload verify</technical_language>

Target:
public void testGetValidSafeHTML() throws Exception { System.out.println("getValidSafeHTML"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); HTMLValidationRule rule = new HTMLValidationRule("test"); ESAPI.validator().addRule(rule); assertEquals("Test.", ESAPI.validator().getRule("test").getValid("test", "Test. <script>alert(document.cookie)</script>")); String test1 = "<b>Jeff</b>"; String result1 = instance.getValidSafeHTML("test", test1, 100, false, errors); assertEquals(test1, result1); String test2 = "<a href=\"<LINK_0>\">Aspect Security</a>"; String result2 = instance.getValidSafeHTML("test", test2, 100, false, errors); assertEquals(test2, result2); String test3 = "Test. <script>alert(document.cookie)</script>"; assertEquals("Test.", rule.getSafe("test", test3)); assertEquals("Test. &lt;<div>load=alert()</div>", rule.getSafe("test", "Test. <<div on<script></script>load=alert()")); assertEquals("Test. <div>b</div>", rule.getSafe("test", "Test. <div style={xss:expression(xss)}>b</div>")); assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s%00cript>alert(document.cookie)</script>")); assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>")); assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>")); }
Source:
<code>void appendOp(String op, boolean binOp) { if (binOp) { if (getLastChar() != ' ' && op.charAt(0) != ',') { append(" "); } append(op); append(" "); } else { <START> append(" "); <END> append(op); } }</code><technical_language>this easier read if reformulated conditions? Essentially prepending a whitespace, for lastchar/',' case (where op == ',' a binOp, right?). check for binOp case for appended whitespace</technical_language>

Target:
void appendOp(String op, boolean binOp) { if (getLastChar() != ' ' && op.charAt(0) != ',') { append(" "); } append(op); if (binOp) { append(" "); } }
Source:
<code>public Flux<RemoveResult> all() { return Flux.defer(() -> { String statement = assembleDeleteQuery(); return template.getCouchbaseClientFactory().getCluster().reactive().query(statement, buildQueryOptions()) .onErrorMap(throwable -> { if (throwable instanceof RuntimeException) { return template.potentiallyConvertRuntimeException((RuntimeException) throwable); } else { return throwable; } }).flatMapMany(ReactiveQueryResult::rowsAsObject) <START> .map(row -> new RemoveResult(row.getString("__id"), row.getLong("__cas"), Optional.empty())); <END> }); }</code><technical_language>names (__id, __cas) TemplateUtils, hard-coded in other places</technical_language>

Target:
public Flux<RemoveResult> all() { return Flux.defer(() -> { String statement = assembleDeleteQuery(); return template.getCouchbaseClientFactory().getCluster().reactive().query(statement, buildQueryOptions()) .onErrorMap(throwable -> { if (throwable instanceof RuntimeException) { return template.potentiallyConvertRuntimeException((RuntimeException) throwable); } else { return throwable; } }).flatMapMany(ReactiveQueryResult::rowsAsObject) .map(row -> new RemoveResult(row.getString(TemplateUtils.SELECT_ID), row.getLong(TemplateUtils.SELECT_CAS), Optional.empty())); }); }
Source:
<code>@Override protected Object newModule() { try { Constructor<?> constructor = moduleClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (InvocationTargetException e) { throw new IllegalArgumentException(e.getCause()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Could not construct " + moduleClass.getName() + " as it lacks a no-args constructor. If this was an upstream module of an extension" <START> + " graph then it should be noted by \"addsTo=\" and not \"includes=\". Otherwise," <END> + " this module must be passed in as an instance, or a no-args constructor must be" + " added.", e); } catch (InstantiationException e) { throw new IllegalArgumentException("Failed to construct " + moduleClass.getName(), e); } catch (IllegalAccessException e) { throw new AssertionError(); } }</code><technical_language>what? add addsTo</technical_language>

Target:
@Override protected Object newModule() { try { Constructor<?> constructor = moduleClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (InvocationTargetException e) { throw new IllegalArgumentException(e.getCause()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Could not construct " + moduleClass.getName() + " as it lacks an accessible no-args constructor. This module must be passed" + " in as an instance, or an accessible no-args constructor must be added.", e); } catch (InstantiationException e) { throw new IllegalArgumentException("Failed to construct " + moduleClass.getName(), e); } catch (IllegalAccessException e) { throw new AssertionError(); } }
Source:
<code>S3GuardFsck(S3AFileSystem fs, MetadataStore ms) throws InvalidParameterException { this.rawFS = fs; if (ms == null) { <START> throw new InvalidParameterException("S3AFileSystem should be guarded by" <END> + " a " + DynamoDBMetadataStore.class.getCanonicalName()); } this.metadataStore = (DynamoDBMetadataStore) ms; if (rawFS.hasMetadataStore()) { throw new InvalidParameterException("Raw fs should not have a " + "metadatastore."); } }</code><technical_language>"S3A Bucket s3a://bucket-name shoud...", bucket name included people debug things. avoid S3AFileSystem implementation detail</technical_language>

Target:
public S3GuardFsck(S3AFileSystem fs, MetadataStore ms) throws InvalidParameterException { this.rawFS = fs; if (ms == null) { throw new InvalidParameterException("S3A Bucket " + fs.getBucket() + " should be guarded by a " + DynamoDBMetadataStore.class.getCanonicalName()); } this.metadataStore = (DynamoDBMetadataStore) ms; Preconditions.checkArgument(!rawFS.hasMetadataStore(), "Raw fs should not have a metadatastore."); }
Source:
<code>ILogData read(long address, @NonNull ReadOptions options) { int count = 0; while (true) { try { <START> return readNative (address, options); <END> } catch (InterruptedException e) { if (++count == MAX_RETRIES) { log.error ("It has retried times, throw an exception {}", MAX_RETRIES, e); throw new UnrecoverableCorfuInterruptedError (e); } } } }</code><technical_language>name of readNative is misleading in java context. I a lot of XXXInner corfu code</technical_language>

Target:
ILogData read(long address, @NonNull ReadOptions options) { int count = 0; while (true) { try { return readInner (address, options); } catch (InterruptedException e) { if (++count == MAX_RETRIES) { log.error ("It has retried times, throw an exception ", MAX_RETRIES, e); throw new UnrecoverableCorfuInterruptedError (e); } } } }
Source:
<code>public static IPersistableElement createPersistableElement( final IExternalSourceModule module) { <START> final IPersistableElement element = (IPersistableElement) ADAPTER_MANAGER <END> .getAdapter(module, IPersistableElement.class); if (element != null) return element; return new IPersistableElement() { public String getFactoryId() { return FACTORY_ID; } public void saveState(IMemento memento) { memento.putString(KEY, module.getHandleIdentifier()); } }; }</code><technical_language>case for change? work .getHandleIdentifier()/ DLTKCore.create(identifier)</technical_language>

Target:
public static IPersistableElement createPersistableElement( final IExternalSourceModule module) { IAdapterManager ADAPTERS = Platform.getAdapterManager(); final IPersistableElement element = (IPersistableElement) ADAPTERS .getAdapter(module, IPersistableElement.class); if (element != null) return element; return new IPersistableElement() { public String getFactoryId() { return FACTORY_ID; } public void saveState(IMemento memento) { memento.putString(KEY, module.getHandleIdentifier()); } }; }
Source:
<code>public ARXClassificationConfiguration getCurrentConfiguration(){ <START> return configCurrent; <END> }</code><technical_language>if (configCurrent == null ) { configCurrent = getLogisticRegressionConfig(); }</technical_language>

Target:
public ARXClassificationConfiguration getCurrentConfiguration(){ if (this.configCurrent == null) { this.configCurrent = getLogisticRegressionConfiguration(); } return configCurrent; }
Source:
<code><START> public <T> T getData(Class<T> clazz, JsonSerializer dataDeserializer) { if (!parsed) { throw new IllegalStateException("This method should only be called on events created through the parse method"); } return dataDeserializer.deserialize(new ByteArrayInputStream((byte[]) this.event.getData()), TypeReference.createInstance(clazz)); } <END></code><technical_language>consider adding async overloads for dataDeserializer supports async deserialization</technical_language>

Target:
public <T> T getData(Class<T> clazz, JsonSerializer dataDeserializer) { return getDataAsync(clazz, dataDeserializer).block(); }
Source:
<code>public void testTimerBoundaryEventInterruptingOnTaskCancelTimer() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-TimerBoundaryEventInterruptingOnTaskCancelTimer.bpmn2"); ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); ProcessInstance processInstance = ksession.startProcess("TimerBoundaryEvent"); assertProcessInstanceActive(processInstance); Collection<TimerInstance> timers = getTimerManager(ksession).getTimers(); assertEquals(1, timers.size()); ksession = restoreSession(ksession, true); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); timers = getTimerManager(ksession).getTimers(); assertEquals(1, timers.size()); ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); ksession = restoreSession(ksession, true); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); timers = getTimerManager(ksession).getTimers(); <START> assertTrue(timers == null || timers.isEmpty()); <END> ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); assertProcessInstanceFinished(processInstance, ksession); }</code><technical_language>I avoid assertTrue (if asserting a of boolean variable, of course). Reason is assertTrue fails, - is null empty? Please a assertJ library, is provides decent asserts for (not only) collections</technical_language>

Target:
public void testTimerBoundaryEventInterruptingOnTaskCancelTimer() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-TimerBoundaryEventInterruptingOnTaskCancelTimer.bpmn2"); ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); ProcessInstance processInstance = ksession.startProcess("TimerBoundaryEvent"); assertProcessInstanceActive(processInstance); Collection<TimerInstance> timers = getTimerManager(ksession).getTimers(); assertEquals(1, timers.size()); ksession = restoreSession(ksession, true); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); timers = getTimerManager(ksession).getTimers(); assertEquals(1, timers.size()); ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); ksession = restoreSession(ksession, true); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); timers = getTimerManager(ksession).getTimers(); Assertions.assertThat(timers).isNullOrEmpty(); ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); assertProcessInstanceFinished(processInstance, ksession); }
Source:
<code>public void setXValues(String... values) { if (xValues == null) { xValues = new ArrayList<>(); } <START> xValues.clear(); <END> xValues.addAll(Arrays.asList(values)); }</code><technical_language>clear() in else clause</technical_language>

Target:
public void setXValues(String... values) { if (xValues == null) { xValues = new ArrayList<>(); } else { xValues.clear(); } xValues.addAll(Arrays.asList(values)); }
Source:
<code>static final public String[] fromBoolean(Boolean[] values) { <START> return (Stream.of(values).map(value->ValueConverter.BooleanToString(value)).toArray(String[]::new)); <END> }</code><technical_language>get rid of streams, I propose adding this convenience ValueConverter: static public <I> String[] convert(I[] in, Function<I, String> converter) { if (in == null) return null; String[] out = new String[in.length]; for (int i=0; i < in.length; i++) { out[i] = converter.apply(in[i]); } return out; } adding array converters in ValueConverter: static public String[] BooleanToString(Boolean[] values) { return convert(values, ValueConverter::BooleanToString); } calling BaseProxy similar return ValueConvert.BooleanToString(values); sense</technical_language>

Target:
static final public String[] fromBoolean(Boolean[] values) { return ValueConverter.convert(values, ValueConverter::BooleanToString); }
Source:
<code>private void createDoseUnitsWidget(FormEntryContext context) { doseUnitsWidget = new DropdownWidget(); List<Concept> concepts = Context.getOrderService().getDrugDosingUnits(); List<Option> options = new ArrayList<Option>(); if (context.getMode() != Mode.VIEW) { for (Concept concept : concepts) { options.add(new Option(concept.getName().getName(), concept.getId().toString(), false)); } if (!concepts.isEmpty()) { doseUnitsWidget.setInitialValue(concepts.get(0).getId()); } } <START> doseUnitsWidget.setOptions(options); <END> context.registerWidget(doseUnitsWidget); }</code><technical_language>Dose form entry automatically figure out current DB in edit mode preset in form</technical_language>

Target:
private void createDoseUnitsWidget(FormEntryContext context) { doseUnitsWidget = new DropdownWidget(); List<Concept> concepts = Context.getOrderService().getDrugDosingUnits(); List<Option> options = new ArrayList<Option>(); for (Concept concept : concepts) { options.add(new Option(concept.getName().getName(), concept.getId().toString(), false)); } setupDropdownWidget(context, doseUnitsWidget, options); }
Source:
<code>public boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { <START> Log_OC.d(TAG, "File NOT deleted " + children[i]); <END> return false; } else { Log_OC.d(TAG, "File deleted " + children[i]); } } } return dir.delete(); }</code><technical_language>I "w" level in case of unsuccessful deletion</technical_language>

Target:
public boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); if (children != null) { for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { Log_OC.w(TAG, "File NOT deleted " + children[i]); return false; } else { Log_OC.d(TAG, "File deleted " + children[i]); } } } else { return false; } } return dir.delete(); }
Source:
<code>public Query toQuery(Set<ValueIndexTerm> terms) { ValueSharedPartIndexTerm sharedPartIndexTerm = null; ValueModuleRootPathIndexTerm moduleRootPathIndexTerm = null; ValuePackageNameIndexTerm packageNameIndexTerm = null; for (ValueIndexTerm term : terms) { if (term instanceof ValueSharedPartIndexTerm) { sharedPartIndexTerm = (ValueSharedPartIndexTerm) term; } else if (term instanceof ValueModuleRootPathIndexTerm) { moduleRootPathIndexTerm = (ValueModuleRootPathIndexTerm) term; } else if (term instanceof ValuePackageNameIndexTerm) { packageNameIndexTerm = (ValuePackageNameIndexTerm) term; } } final SearchEmptyQueryBuilder queryBuilder = new SearchEmptyQueryBuilder() <START> .addTerm(sharedPartIndexTerm); <END> if (moduleRootPathIndexTerm != null) { queryBuilder.addTerm(moduleRootPathIndexTerm); } if (packageNameIndexTerm != null) { queryBuilder.addTerm(packageNameIndexTerm); } return queryBuilder.build(); }</code><technical_language>Null check here? java if (sharedPartIndexTerm != null) { queryBuilder.addTerm(sharedPartIndexTerm); }</technical_language>

Target:
public Query toQuery(Set<ValueIndexTerm> terms) { final SearchEmptyQueryBuilder queryBuilder = new SearchEmptyQueryBuilder(); for (ValueIndexTerm term : terms) { if (term instanceof ValueSharedPartIndexTerm) { queryBuilder.addTerm(term); } else if (term instanceof ValueModuleRootPathIndexTerm) { queryBuilder.addTerm(term); } else if (term instanceof ValuePackageNameIndexTerm) { queryBuilder.addTerm(term); } } return queryBuilder.build(); }
Source:
<code>private static HashMap<String, LinkedHashMap<String, String>> getCommonScopeByDomain(HashMap<String, Set<String>> beanKeysByDomain, HashMap<String, LinkedList<Filter>> filtersByDomain){ HashMap<String, LinkedHashMap<String, String>> commonScopeByDomain = new HashMap<String, LinkedHashMap<String, String>>(); Iterator<Entry<String, Set<String>>> commonParametersByDomainItr = beanKeysByDomain.entrySet().iterator(); while(commonParametersByDomainItr.hasNext()){ Entry<String, Set<String>> commonParametersByDomainEntry = commonParametersByDomainItr.next(); String domainName = (String) commonParametersByDomainEntry.getKey(); Set<String> commonParameters = (Set<String>) commonParametersByDomainEntry.getValue(); LinkedList<Filter> filters = filtersByDomain.get(domainName); LinkedHashMap<String, String> commonScope = new LinkedHashMap<String, String>(); for (String parameter : commonParameters) { String commonValue = null; Boolean hasCommonValue = true; Iterator<Filter> filtersItr = filters.iterator(); while(filtersItr.hasNext() && hasCommonValue){ Filter f = filtersItr.next(); ArrayList<String> parameterValues = f.getParameterValues(parameter); if (parameterValues.size() != 1 || (commonValue != null && !commonValue.equals(parameterValues.get(0)))) { hasCommonValue = false; continue; } commonValue = parameterValues.get(0); <START> } <END> if (hasCommonValue) { commonScope.put(parameter, commonValue); } } commonScopeByDomain.put(domainName, commonScope); } return commonScopeByDomain; }</code><technical_language>a personal taste, prefer a for loop here: for (Filter f : filters) { ArrayList<String> parameterValues = f.getParameterValues(parameter); if (parameterValues.size() != 1 || (commonValue != null && !commonValue.equals(parameterValues.get(0)))) { hasCommonValue = false; break; } commonValue = parameterValues.get(0); }</technical_language>

Target:
private static HashMap<String, LinkedHashMap<String, String>> getCommonScopeByDomain(HashMap<String, Set<String>> beanKeysByDomain, HashMap<String, LinkedList<Filter>> filtersByDomain){ HashMap<String, LinkedHashMap<String, String>> commonScopeByDomain = new HashMap<String, LinkedHashMap<String, String>>(); for (Entry<String, Set<String>> commonParametersByDomainEntry : beanKeysByDomain.entrySet()) { String domainName = commonParametersByDomainEntry.getKey(); Set<String> commonParameters = commonParametersByDomainEntry.getValue(); LinkedList<Filter> filters = filtersByDomain.get(domainName); LinkedHashMap<String, String> commonScope = new LinkedHashMap<String, String>(); for (String parameter : commonParameters) { String commonValue = null; Boolean hasCommonValue = true; for (Filter f : filters) { ArrayList<String> parameterValues = f.getParameterValues(parameter); if (parameterValues.size() != 1 || (commonValue != null && !commonValue.equals(parameterValues.get(0)))) { hasCommonValue = false; break; } commonValue = parameterValues.get(0); } if (hasCommonValue) { commonScope.put(parameter, commonValue); } } commonScopeByDomain.put(domainName, commonScope); } return commonScopeByDomain; }
Source:
<code>public void shouldRejectRequestWithInvalidTokenFormat() throws IOException, ServletException { <START> when(request.getHeader(eq("Authentication"))).thenReturn("xxx"); <END> filter.doFilter(request, response, filterChain); assertNotNull(capturedContext.get()); assertNull(capturedContext.get().getAuthentication()); }</code><technical_language>sure, Springboot headers uppercase</technical_language>

Target:
public void shouldRejectRequestWithInvalidTokenFormat() throws IOException, ServletException { when(request.getServletPath()).thenReturn("/actuator/prometheus"); when(request.getHeader(eq("Authorization"))).thenReturn("xxx"); filter.doFilter(request, response, filterChain); assertNull(capturedAuthentication.get()); }
Source:
<code>private QueryRequest createQueryRequestForSubscribedToWorkspaces() { Set<String> ids = new HashSet<>(); try { List<Map<String, Object>> subscriptions = persistentStore.get(SubscriptionsPersistentStore.SUBSCRIPTIONS_TYPE); <START> ids = <END> subscriptions .stream() .map(subscription -> subscription.get(ID_FIELD)) .filter(Objects::nonNull) .map(Object::toString) .collect(Collectors.toSet()); } catch (PersistenceException e) { LOGGER.debug("Failed to get subscriptions for workspaces: {}", e.getMessage(), e); } if (ids.isEmpty()) { return null; } return createQueryRequest(workspaceQueryBuilder.createFilter(ids)); }</code><technical_language>This need try/catch block. Consider moving persistentStore.get() call error handling a separate function this simplified</technical_language>

Target:
private Optional<QueryRequest> createQueryRequestForSubscribedToWorkspaces() { final List<Map<String, Object>> subscriptions = findSubscriptions(); if (subscriptions.isEmpty()) { return Optional.empty(); } final Set<String> ids = getIdsFromSubscriptions(subscriptions); return Optional.of(getQueryRequestFromIds(ids)); }
Source:
<code>public void searchPayments_withMandateId_whenCardPayment_shouldReturnABadRequestResponse() throws Exception { InputStream body = searchPayments(API_KEY, ImmutableMap.of("agreement_id", "my_agreement")) .statusCode(400) .contentType(JSON).extract() .body().asInputStream(); JsonAssert.with(body) .assertThat("$.*", hasSize(2)) .assertThat("$.code", is("P0401")) <START> .assertThat("$.description", is("Invalid parameters: agreement_id=my_agreement. See Public API documentation for the correct data formats")); <END> }</code><technical_language>this changed include value? agreement_id include this</technical_language>

Target:
public void searchPayments_withMandateId_whenCardPayment_shouldReturnABadRequestResponse() throws Exception { InputStream body = searchPayments(API_KEY, ImmutableMap.of("agreement_id", "my_agreement")) .statusCode(400) .contentType(JSON).extract() .body().asInputStream(); JsonAssert.with(body) .assertThat("$.*", hasSize(2)) .assertThat("$.code", is("P0401")) .assertThat("$.description", is("Invalid parameters: agreement_id. See Public API documentation for the correct data formats")); }
Source:
<code>private String resolveStringWithSymbols(String originalCellText) throws NoSuchSymbolException { <START> Pattern p = Pattern.compile(REGEX_STRING_WITH_SYMBOL); <END> Matcher m = p.matcher(originalCellText); String newText = null; while (m.matches()) { String symbolValue = getSymbolValue(m.group(3)); newText = m.group(1) + symbolValue + m.group(5); m = p.matcher(newText); } return newText; }</code><technical_language>store pattern in a final static (instead of String compiling time)</technical_language>

Target:
private String resolveStringWithSymbols(String originalCellText) throws NoSuchSymbolException { Matcher m = STRING_WITH_SYMBOL_PATTERN.matcher(originalCellText); String newText = null; while (m.matches()) { String symbolValue = getSymbolValue(m.group(3)); newText = m.group(1) + symbolValue + m.group(5); m = STRING_WITH_SYMBOL_PATTERN.matcher(newText); } return newText; }
Source:
<code><START> public void verifyImageRemoval() { <END> StoragePool pool = getStoragePoolDao().get(getParameters().getStoragePoolId()); if (pool.getStatus() != StoragePoolStatus.Up || pool.getSpmVdsId() == null) { log.info("Waiting on SPM availability to confirm image removal (timeout is minutes)", LIFETIME); setSucceeded(true); return; } List<Guid> failedGuids = getFailedVolumeIds(pool.getSpmVdsId()); if (failedGuids.isEmpty()) { log.info("Requested images were successfully removed"); setCommandStatus(CommandStatus.SUCCEEDED); persistCommand(getParameters().getParentCommand()); } else { log.error("The following images were not removed: {}", failedGuids); setCommandStatus(CommandStatus.FAILED); } setSucceeded(true); }</code><technical_language>I implementation changed. If want guarantee verb is executed SPM add IRS command call getVolumeInfo operate a wrapper ensure runs SPM while providing benefits of spm'ish infra (like failover, race conditions, etc). get add a getVolumeInfoSpmVdsCommand call regular getVolumeInfo do trick</technical_language>

Target:
public void verifyImageRemoval() { StoragePool pool = getStoragePoolDao().get(getParameters().getStoragePoolId()); if (pool.getStatus() != StoragePoolStatus.Up || pool.getSpmVdsId() == null) { log.info("Waiting on SPM availability to confirm image removal (timeout is minutes)", getParameters().getLifeInMinutes()); setSucceeded(true); return; } List<Guid> failedGuids = getFailedVolumeIds(pool.getSpmVdsId()); if (failedGuids.isEmpty()) { log.info("Requested images were successfully removed"); setCommandStatus(CommandStatus.SUCCEEDED); persistCommand(getParameters().getParentCommand()); } else { log.error("The following images were not removed: {}", failedGuids); setCommandStatus(CommandStatus.FAILED); } setSucceeded(true); }
Source:
<code><START> TaskAppDeploymentRequestCreator taskAppDeploymentRequestCreator( <END> CommonApplicationProperties commonApplicationProperties, ApplicationConfigurationMetadataResolver metadataResolver) { return new TaskAppDeploymentRequestCreator(commonApplicationProperties, metadataResolver, null); }</code><technical_language>Is reason this is public</technical_language>

Target:
public TaskAppDeploymentRequestCreator taskAppDeploymentRequestCreator( CommonApplicationProperties commonApplicationProperties, ApplicationConfigurationMetadataResolver metadataResolver) { return new TaskAppDeploymentRequestCreator(commonApplicationProperties, metadataResolver, null); }
Source:
<code>public void onResume() { super.onResume(); RecyclerView recyclerView = getListView(); <START> for (int i = 0; i <= recyclerView.getChildCount(); i++) { <END> View child = recyclerView.getChildAt(i); if (child != null) { mAdapter.updatePlusOne((NewsAdapter.ViewHolder) recyclerView.getChildViewHolder(child)); } } }</code><technical_language>cache size for loop? for (int i = 0, size = recyclerView.getChildCount(); i <= size; i++)</technical_language>

Target:
public void onResume() { super.onResume(); RecyclerView recyclerView = getListView(); for (int i = 0, size = recyclerView.getChildCount(); i <= size; i++) { View child = recyclerView.getChildAt(i); if (child != null) { mAdapter.updatePlusOne((NewsAdapter.ViewHolder) recyclerView.getChildViewHolder(child)); } } }
Source:
<code>public DefaultHttpContent(ByteBuf content) { ObjectUtil.checkNotNull(content, "content"); <START> this.content = content; <END> }</code><technical_language>nit: merge lines checkNotNull return argument</technical_language>

Target:
public DefaultHttpContent(ByteBuf content) { this.content = ObjectUtil.checkNotNull(content, "content"); }
Source:
<code>public void dragEnter(DropTargetDragEvent dragEvent) { NlDropEvent <START> event = <END> new NlDropEvent(dragEvent); if (myCurrentInteraction == null) { Point location = event.getLocation(); myLastMouseX = location.x; myLastMouseY = location.y; ScreenView screenView = mySurface.getScreenView(myLastMouseX, myLastMouseY); if (screenView == null) { event.reject(); return; } NlModel model = screenView.getModel(); DnDTransferItem item = NlModel.getTransferItem(event.getTransferable(), true ); if (item == null) { event.reject(); return; } DragType dragType = event.getDropAction() == DnDConstants.ACTION_COPY ? DragType.COPY : DragType.MOVE; InsertType insertType = model.determineInsertType(dragType, item, true ); List<NlComponent> dragged = model.createComponents(screenView, item, insertType); if (dragged == null) { event.reject(); return; } int yOffset = 0; for (NlComponent component : dragged) { component.x = Coordinates.getAndroidX(screenView, myLastMouseX) - component.w / 2; component.y = Coordinates.getAndroidY(screenView, myLastMouseY) - component.h / 2 + yOffset; yOffset += component.h; } DragDropInteraction interaction = new DragDropInteraction(mySurface, dragged); interaction.setType(dragType); interaction.setTransferItem(item); startInteraction(myLastMouseX, myLastMouseY, interaction, 0); event.accept(insertType.isCreate() ? DnDConstants.ACTION_COPY : event.getDropAction()); } }</code><technical_language>Initialize this if statement</technical_language>

Target:
public void dragEnter(DropTargetDragEvent dragEvent) { if (myCurrentInteraction == null) { NlDropEvent event = new NlDropEvent(dragEvent); Point location = event.getLocation(); myLastMouseX = location.x; myLastMouseY = location.y; ScreenView screenView = mySurface.getScreenView(myLastMouseX, myLastMouseY); if (screenView == null) { event.reject(); return; } NlModel model = screenView.getModel(); DnDTransferItem item = NlModel.getTransferItem(event.getTransferable(), true ); if (item == null) { event.reject(); return; } DragType dragType = event.getDropAction() == DnDConstants.ACTION_COPY ? DragType.COPY : DragType.MOVE; InsertType insertType = model.determineInsertType(dragType, item, true ); List<NlComponent> dragged = model.createComponents(screenView, item, insertType); if (dragged == null) { event.reject(); return; } int yOffset = 0; for (NlComponent component : dragged) { component.x = Coordinates.getAndroidX(screenView, myLastMouseX) - component.w / 2; component.y = Coordinates.getAndroidY(screenView, myLastMouseY) - component.h / 2 + yOffset; yOffset += component.h; } DragDropInteraction interaction = new DragDropInteraction(mySurface, dragged); interaction.setType(dragType); interaction.setTransferItem(item); startInteraction(myLastMouseX, myLastMouseY, interaction, 0); event.accept(insertType.isCreate() ? DnDConstants.ACTION_COPY : event.getDropAction()); } }
Source:
<code>protected boolean validate() { return super.validate() && isImageExist() && checkOperationIsCorrect() && checkOperationAllowedOnDiskContentType() && isImageNotLocked() && isSourceAndDestTheSame() && validateSourceStorageDomain() && validateDestStorage() && checkTemplateInDestStorageDomain() && validateSpaceRequirements() && validateVmSnapshotStatus() && checkCanBeMoveInVm() && checkIfNeedToBeOverride() && setAndValidateDiskProfiles() && validatePassDiscardSupportedForDestinationStorageDomain() <START> && isDiskInBackupDomain(); <END> }</code><technical_language>This validation in LiveMigrateVmDisksCommand in this command move disks VMs (checkCanBeMoveInVm verify this). LiveMigrateVmDisksCommand is command is responsible move disks a running VM</technical_language>

Target:
protected boolean validate() { return super.validate() && isImageExist() && checkOperationIsCorrect() && checkOperationAllowedOnDiskContentType() && isImageNotLocked() && isSourceAndDestTheSame() && validateSourceStorageDomain() && validateDestStorage() && checkTemplateInDestStorageDomain() && validateSpaceRequirements() && validateVmSnapshotStatus() && checkCanBeMoveInVm() && checkIfNeedToBeOverride() && setAndValidateDiskProfiles() && validatePassDiscardSupportedForDestinationStorageDomain(); }
Source:
<code>public InputStream anyBlobQuery(QueryBuilder query, Field<InputStream> field) { Connection c; boolean closeConnection = false; try { c = ds.getConnection(); } catch (SQLException ex) { throw new IllegalStateException("Could not connect to DataSource.",ex); } <START> try { <END> LOGGER.log(Level.FINEST, query.toString()); PreparedStatement stmt = query.toStatement(c); try { ResultSet rs = stmt.executeQuery(); try { if(rs.next()) { assert(rs.last()); InputStream is = field.getValue(rs); return is == null ? null : new ClosingInputStreamWrapper(is, c); } else { closeConnection = true; return null; } } finally { rs.close(); } } finally { stmt.close(); } } catch (SQLException ex) { throw new IllegalStateException("BlobQuery Failed", ex); } finally { if (closeConnection) { try { c.close(); } catch (SQLException ex) { throw new IllegalArgumentException("Error while closing connection.",ex); } } } }</code><technical_language>try-with-resources</technical_language>

Target:
public InputStream anyBlobQuery(QueryBuilder query, Field<InputStream> field) { LOGGER.log(Level.FINEST, query.toString()); Connection c; boolean closeConnection = false; try { c = ds.getConnection(); } catch (SQLException ex) { throw new IllegalStateException("Could not connect to DataSource.",ex); } try { try (PreparedStatement stmt = query.toStatement(c)){ try (ResultSet rs = stmt.executeQuery()) { if(rs.next()) { assert(rs.last()); InputStream is = field.getValue(rs); return is == null ? null : new ClosingInputStreamWrapper(is, c); } else { closeConnection = true; return null; } } } } catch (SQLException ex) { throw new IllegalStateException("BlobQuery Failed", ex); } finally { if (closeConnection) { try { c.close(); } catch (SQLException ex) { throw new IllegalArgumentException("Error while closing connection.",ex); } } } }
Source:
<code>public static UUID makeUUID(byte bytes[]) { long high = 0; long low = 0; if (bytes.length != Utils.UUID_LEN) { <START> throw new IllegalArgumentException("UUID byte field must be 16 bytes long"); <END> } final int bitsPerByte = Byte.SIZE; int bitMask = (1 << bitsPerByte) - 1; for (int i = 0; i < bitsPerByte; i++) { low = (low << bitsPerByte) | (bytes[i + bitsPerByte] & bitMask); high = (high << bitsPerByte) | (bytes[i] & bitMask); } UUID uuid = new UUID(high, low); return uuid; }</code><technical_language>ctf tests fail</technical_language>

Target:
public static UUID makeUUID(byte bytes[]) { long high = 0; long low = 0; if (bytes.length < Utils.UUID_LEN) { throw new IllegalArgumentException("UUID byte field must be 16 bytes long"); } final int bitsPerByte = Byte.SIZE; int bitMask = (1 << bitsPerByte) - 1; for (int i = 0; i < bitsPerByte; i++) { low = (low << bitsPerByte) | (bytes[i + bitsPerByte] & bitMask); high = (high << bitsPerByte) | (bytes[i] & bitMask); } UUID uuid = new UUID(high, low); return uuid; }
Source:
<code>public Statement apply(Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { AlluxioProperties props = ServerConfiguration.copyProperties(); try { statement.evaluate(); } finally { FileSystemMaster fsm = mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().getMasterProcess() .getMaster(FileSystemMaster.class); if (SecurityUtils.isAuthenticationEnabled(ServerConfiguration.global())) { try (AuthenticatedClientUserResource r = new AuthenticatedClientUserResource( fsm.getRootInodeOwner(), ServerConfiguration.global())) { resetFsm(fsm); } } else { resetFsm(fsm); } <START> BlockWorker blkWorker = mCluster.mLocalAlluxioCluster.getWorkerProcess() <END> .getWorker(BlockWorker.class); resetBlockWorker(blkWorker); ServerConfiguration.reset(); props.entrySet() .forEach(e -> { if (e.getValue() == null || e.getValue().equals("")) { ServerConfiguration.unset(e.getKey()); } else { ServerConfiguration.set(e.getKey(), e.getValue()); } }); } } }; }</code><technical_language>tests multiple workers</technical_language>

Target:
public Statement apply(Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { AlluxioProperties props = ServerConfiguration.copyProperties(); try { statement.evaluate(); } finally { FileSystemMaster fsm = mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().getMasterProcess() .getMaster(FileSystemMaster.class); if (SecurityUtils.isAuthenticationEnabled(ServerConfiguration.global())) { try (AuthenticatedClientUserResource r = new AuthenticatedClientUserResource( fsm.getRootInodeOwner(), ServerConfiguration.global())) { resetFsm(fsm); } } else { resetFsm(fsm); } mCluster.mLocalAlluxioCluster.getWorkerProcesses().stream() .map(w -> w.getWorker(BlockWorker.class)) .forEach(blkWorker -> resetBlockWorker(blkWorker)); ServerConfiguration.reset(); props.entrySet() .forEach(e -> { if (e.getValue() == null || e.getValue().equals("")) { ServerConfiguration.unset(e.getKey()); } else { ServerConfiguration.set(e.getKey(), e.getValue()); } }); } } }; }