auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void changeSecurityRealmForHttpMngmntInterface(String securityRealmName) throws Exception { try (ModelControllerClient client = getNativeModelControllerClient()) { ModelNode operation = createOpNode("core-service=management/management-interface=http-interface", ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION); operation.get(NAME).set("security-realm"); operation.get(VALUE).set(securityRealmName); CoreUtils.applyUpdate(operation, client); <START> reloadServer(); <END> } }</code><technical_language>need for write-attribute reload if a read-attribute shows attribute desired value</technical_language>

Target:
private static void changeSecurityRealmForHttpMngmntInterface(String securityRealmName) throws Exception { try (ModelControllerClient client = getNativeModelControllerClient()) { String originSecurityRealm = ""; ModelNode operation = createOpNode("core-service=management/management-interface=http-interface", READ_ATTRIBUTE_OPERATION); operation.get(NAME).set("security-realm"); final ModelNode result = client.execute(operation); if (SUCCESS.equals(result.get(OUTCOME).asString())) { originSecurityRealm = result.get(RESULT).asString(); } if (!originSecurityRealm.equals(securityRealmName)) { operation = createOpNode("core-service=management/management-interface=http-interface", ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION); operation.get(NAME).set("security-realm"); operation.get(VALUE).set(securityRealmName); CoreUtils.applyUpdate(operation, client); reloadServer(); } } }
Source:
<code>public DynamicTableSink createDynamicTableSink(Context context) { FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); ReadableConfig tableOptions = helper.getOptions(); EncodingFormat<SerializationSchema<RowData>> encodingFormat = helper.discoverEncodingFormat( SerializationFormatFactory.class, FactoryUtil.FORMAT); helper.validateExcept(PROPERTIES_PREFIX); <START> validateTableOptions(tableOptions); if (tableOptions.getOptional(TOPIC_PATTERN).isPresent()){ throw new ValidationException("Flink Kafka sink currently doesn't support 'topic-pattern'."); } String[] topics = tableOptions.get(TOPIC).split(","); if (topics.length > 1) { throw new ValidationException("Flink Kafka sink currently doesn't support topic list."); } <END> DataType consumedDataType = context.getCatalogTable().getSchema().toPhysicalRowDataType(); return createKafkaTableSink( consumedDataType, topics[0], getKafkaProperties(context.getCatalogTable().getOptions()), getFlinkKafkaPartitioner(tableOptions, context.getClassLoader()), encodingFormat, getSinkSemantic(tableOptions)); }</code><technical_language>a validateTableSinkOptions validateTableSourceOptions ? move this validation validateSinkTopic()</technical_language>

Target:
public DynamicTableSink createDynamicTableSink(Context context) { FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); ReadableConfig tableOptions = helper.getOptions(); EncodingFormat<SerializationSchema<RowData>> encodingFormat = helper.discoverEncodingFormat( SerializationFormatFactory.class, FactoryUtil.FORMAT); validateTableSinkOptions(tableOptions); helper.validateExcept(PROPERTIES_PREFIX); DataType consumedDataType = context.getCatalogTable().getSchema().toPhysicalRowDataType(); return createKafkaTableSink( consumedDataType, tableOptions.get(TOPIC).get(0), getKafkaProperties(context.getCatalogTable().getOptions()), getFlinkKafkaPartitioner(tableOptions, context.getClassLoader()), encodingFormat, getSinkSemantic(tableOptions)); }
Source:
<code><START> public byte[] getValue() { <END> return address; }</code><technical_language>Remove this method</technical_language>

Target:
public String getValue() { return HexUtils.byteArrayToHexString(address).substring(1); }
Source:
<code>public CompareResult(Collection<T> oldItems, Collection<T> newItems) { T oldItemTemp; if (oldItems != null) { removed.addAll(oldItems); } if (newItems != null) { for (T newItem : newItems) { oldItemTemp = null; <START> if(removed.indexOf(newItem) >= 0) { oldItemTemp = removed.get(removed.indexOf(newItem)).clone(); } if (!removed.remove(newItem)) { added.add(newItem); } else if(oldItemTemp != null) { changed.add(new Pair(oldItemTemp, newItem)); } <END> } } }</code><technical_language>Update: I added LinkPropertiesUtil.CompareOrUpdateResult generic class do this. idea is lists of RouteInfo objects, do: CompareOrUpdateResult<IpPrefix, RouteInfo> result = new CompareOrUpdateResult<>( oldRoutes, newRoutes, (route) -> route.getDestination()); for (RouteInfo route : result.added) { // Add route. } for (RouteInfo route: result.removed) { // Remove route. } for (RouteInfo route: result.updated) { // Replace route. }</technical_language>

Target:
public CompareResult(Collection<T> oldItems, Collection<T> newItems) { if (oldItems != null) { removed.addAll(oldItems); } if (newItems != null) { for (T newItem : newItems) { if (!removed.remove(newItem)) { added.add(newItem); } } } }
Source:
<code>protected void setWebAppInitParameter(String property, String value) { if (!(j.jenkins.servletContext instanceof ContextHandler.Context)) { <START> throw new IllegalArgumentException("This only works with Jetty"); <END> } ((ContextHandler.Context)j.jenkins.servletContext).getContextHandler().getInitParams().put(property, value); }</code><technical_language>this is a test... Assume.assumeThat(j.jenkins.servletContext, Matchers.isInstance(ContextHandler.Context.class)); if run tests another servlet container skipped fail</technical_language>

Target:
protected void setWebAppInitParameter(String property, String value) { Assume.assumeThat(j.jenkins.servletContext, Matchers.instanceOf(ContextHandler.Context.class)); ((ContextHandler.Context)j.jenkins.servletContext).getContextHandler().getInitParams().put(property, value); }
Source:
<code>public CustomProgressDialog generateProgressDialog(int taskId) { if (CommCareApplication._().isConsumerApp()) { return ConsumerAppsUtil.getGenericConsumerAppsProgressDialog(taskId, false); } else if (taskId != DIALOG_UPGRADE_INSTALL) { Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareSetupActivity"); return null; } else { <START> return generateNormalUpdateDialog(taskId); <END> } }</code><technical_language>nice if this UpdateInstall Install instead of Update, this dialog is shown installing update, downloading it</technical_language>

Target:
public CustomProgressDialog generateProgressDialog(int taskId) { if (CommCareApplication._().isConsumerApp()) { return ConsumerAppsUtil.getGenericConsumerAppsProgressDialog(taskId, false); } else if (taskId != DIALOG_UPGRADE_INSTALL) { Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareSetupActivity"); return null; } else { return generateNormalUpdateInstallDialog(taskId); } }
Source:
<code>public void testAddBatchContextEntries() { BatchPropertyContext batchPropertyContext = new BatchPropertyContext(); batchPropertyContext.setBatchContextEntries(entries); Properties bean1 = batchPropertyContext.getBatchProperties("bean1"); assertEquals(4, bean1.size()); assertEquals("bean1readerName", bean1.getProperty("readerName")); assertEquals("bean1writerName", bean1.getProperty("readerWriter")); assertEquals("jobProperty1value", bean1.getProperty("jobProperty1")); assertEquals("jobProperty2value", bean1.getProperty("jobProperty2")); Properties bean2 = batchPropertyContext.getBatchProperties("bean2"); assertEquals(4, bean2.size()); assertEquals("bean2readerName", bean2.getProperty("readerName")); assertEquals("bean2writerName", bean2.getProperty("readerWriter")); assertEquals("jobProperty1value", bean2.getProperty("jobProperty1")); assertEquals("jobProperty2value", bean2.getProperty("jobProperty2")); <START> Properties jobProperties = batchPropertyContext.getBatchProperties("testJob.job-testJob"); <END> assertEquals(2, jobProperties.size()); assertEquals("jobProperty1value", jobProperties.getProperty("jobProperty1")); assertEquals("jobProperty2value", jobProperties.getProperty("jobProperty2")); }</code><technical_language>paths follow convention jobName.stepName.artifactName.beanName</technical_language>

Target:
public void testAddBatchContextEntries() { BatchPropertyContext batchPropertyContext = new BatchPropertyContext(); batchPropertyContext.setBatchContextEntries(entries); Properties step1BatchProperties = batchPropertyContext.getBatchProperties("job1.step1"); assertEquals(4, step1BatchProperties.size()); assertEquals("step1PropertyValue1", step1BatchProperties.getProperty("step1PropertyName1")); assertEquals("step1PropertyValue2", step1BatchProperties.getProperty("step1PropertyName2")); assertEquals("jobProperty1value", step1BatchProperties.getProperty("jobProperty1")); assertEquals("jobProperty2value", step1BatchProperties.getProperty("jobProperty2")); Properties step2BatchProperties = batchPropertyContext.getBatchProperties("job1.step2"); assertEquals(4, step2BatchProperties.size()); assertEquals("step2PropertyValue1", step2BatchProperties.getProperty("step2PropertyName1")); assertEquals("step2PropertyValue2", step2BatchProperties.getProperty("step2PropertyName2")); assertEquals("jobProperty1value", step2BatchProperties.getProperty("jobProperty1")); assertEquals("jobProperty2value", step2BatchProperties.getProperty("jobProperty2")); Properties jobProperties = batchPropertyContext.getBatchProperties("job1.job-job1"); assertEquals(2, jobProperties.size()); assertEquals("jobProperty1value", jobProperties.getProperty("jobProperty1")); assertEquals("jobProperty2value", jobProperties.getProperty("jobProperty2")); }
Source:
<code>public OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull String testFrameworkName, @NotNull TestConsoleProperties consoleProperties) { <START> if (testFrameworkName == "gotest") { <END> return new GotestEventsConverter(consoleProperties); } if (testFrameworkName == "gocheck") { return new GocheckEventsConverter(consoleProperties); } throw new RuntimeException("Unexpected test framework: " + testFrameworkName); }</code><technical_language>equals instead of ==</technical_language>

Target:
public OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull String testFrameworkName, @NotNull TestConsoleProperties consoleProperties) { if (myConfiguration.getType() == GotestRunConfigurationType.getInstance()) { return new GotestEventsConverter(consoleProperties); } if (myConfiguration.getType() == GocheckRunConfigurationType.getInstance()) { return new GocheckEventsConverter(consoleProperties); } throw new RuntimeException("Unexpected test framework: " + testFrameworkName); }
Source:
<code>public int getParentWeight(EObject a) { <START> return NORMAL; <END> }</code><technical_language>This SIGNIFICANT in ReflectiveWeightProvider,</technical_language>

Target:
public int getParentWeight(EObject a) { return SIGNIFICANT; }
Source:
<code>public void setValue(String value) { assertNotFrozen(); <START> this.setValue(value.toCharArray()); <END> }</code><technical_language>Redundant qualifier</technical_language>

Target:
public void setValue(String value) { assertNotFrozen(); setValue(fKind, value.toCharArray()); }
Source:
<code>private void addAll(Object array) throws JSONException { if (array.getClass().isArray()) { int length = Array.getLength(array); <START> this.myArrayList.ensureCapacity(length); <END> for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } }</code><technical_language>change java this.myArrayList.ensureCapacity(this.myArrayList.size() + length);</technical_language>

Target:
private void addAll(Object array) throws JSONException { if (array.getClass().isArray()) { int length = Array.getLength(array); this.myArrayList.ensureCapacity(this.myArrayList.size() + length); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } }
Source:
<code>public void scan() throws IOException { if (!rowGroupOpen) { openRowGroup(); } beginScan(presentStream, null); ensureValuesCapacity(); makeInnerQualifyingSet(); QualifyingSet input = hasNulls ? innerQualifyingSet : inputQualifyingSet; int numInput = input.getPositionCount(); if (inDictionaryStream != null) { if (inDictionaryFlags == null || inDictionaryFlags.length < numInput) { inDictionaryFlags = new boolean[roundupSize(numInput)]; } int begin = hasNulls ? innerPosInRowGroup : posInRowGroup; <START> int end = input.getEnd(); <END> inDictionaryStream.getSetBits(input.getPositions(), numInput, begin, end - begin, inDictionaryFlags); } if (filter != null) { outputQualifyingSet.reset(numInput); } if (numInput > 0) { if (filter != null) { outputQualifyingSet.reset(numInput); resultsProcessor.reset(); numInnerResults = dataStream.scan(input.getPositions(), 0, numInput, input.getEnd(), resultsProcessor); outputQualifyingSet.setPositionCount(numInnerResults); } else { resultsProcessor.reset(); numInnerResults = dataStream.scan(input.getPositions(), 0, numInput, input.getEnd(), resultsProcessor); } } if (hasNulls) { innerPosInRowGroup = innerQualifyingSet.getEnd(); } addNullsAfterScan(filter != null ? outputQualifyingSet : inputQualifyingSet, inputQualifyingSet.getEnd()); if (filter != null) { outputQualifyingSet.setEnd(inputQualifyingSet.getEnd()); } endScan(presentStream); }</code><technical_language>innerPosInRowGroup -> innerPositionInRowGroup posInRowGroup -> positionInRowGroup</technical_language>

Target:
public void scan() throws IOException { if (!rowGroupOpen) { openRowGroup(); } beginScan(presentStream, null); ensureValuesCapacity(); makeInnerQualifyingSet(); QualifyingSet input = hasNulls ? innerQualifyingSet : inputQualifyingSet; int numInput = input.getPositionCount(); if (inDictionaryStream != null) { if (inDictionaryFlags == null || inDictionaryFlags.length < numInput) { inDictionaryFlags = newBooleanArrayForReuse(numInput); } int begin = hasNulls ? innerPosInRowGroup : posInRowGroup; int end = input.getEnd(); inDictionaryStream.getSetBits(input.getPositions(), numInput, begin, end - begin, inDictionaryFlags); } if (filter != null) { outputQualifyingSet.reset(numInput); } if (numInput > 0) { resultsProcessor.reset(); if (filter != null) { numInnerResults = dataStream.scan(input.getPositions(), 0, numInput, input.getEnd(), resultsProcessor); outputQualifyingSet.setPositionCount(numInnerResults); } else { numInnerResults = dataStream.scan(input.getPositions(), 0, numInput, input.getEnd(), resultsProcessor); } } if (hasNulls) { innerPosInRowGroup = innerQualifyingSet.getEnd(); } addNullsAfterScan(filter != null ? outputQualifyingSet : inputQualifyingSet, inputQualifyingSet.getEnd()); if (filter != null) { outputQualifyingSet.setEnd(inputQualifyingSet.getEnd()); } endScan(presentStream); }
Source:
<code>public <T> T readEntity(Class<T> typeToReadAs) { <START> try { <END> return ObjectMapperSingleton.getContext(typeToReadAs).reader(typeToReadAs).readValue(body); } catch (Exception e) { LOG.error(e, e.getMessage()); throw new ClientResponseException(e.getMessage(), 0, e); } }</code><technical_language>This is method inputStream apply logic in HttpCommand read a String</technical_language>

Target:
public <T> T readEntity(Class<T> typeToReadAs) { try { return ObjectMapperSingleton.getContext(typeToReadAs).reader(typeToReadAs).readValue(responseInputStream); } catch (Exception e) { LOG.error(e, e.getMessage()); throw new ClientResponseException(e.getMessage(), 0, e); } }
Source:
<code>public void run() { List<CucumberFeature> features = featureSupplier.get(); bus.send(new TestRunStarted(bus.getTime())); StepDefinitionReporter stepDefinitionReporter = plugins.stepDefinitionReporter(); runnerSupplier.get().reportStepDefinitions(stepDefinitionReporter); final int requestedThreads = runtimeOptions.getThreads(); if (!features.isEmpty()) { <START> for (CucumberFeature feature : features) { <END> feature.sendTestSourceRead(bus); } ParallelFeatureRunner.run(new FeatureRunner(filters, runnerSupplier), features, requestedThreads); } bus.send(new TestRunFinished(bus.getTime())); }</code><technical_language>this moved</technical_language>

Target:
public void run() { final List<CucumberFeature> features = featureSupplier.get(); bus.send(new TestRunStarted(bus.getTime())); for (CucumberFeature feature : features) { feature.sendTestSourceRead(bus); } final StepDefinitionReporter stepDefinitionReporter = plugins.stepDefinitionReporter(); runnerSupplier.get().reportStepDefinitions(stepDefinitionReporter); final FeatureCompiler compiler = new FeatureCompiler(); for (CucumberFeature feature : features) { for (final PickleEvent pickleEvent : compiler.compileFeature(feature)) { if (filters.matchesFilters(pickleEvent)) { executor.execute(new Runnable() { @Override public void run() { runnerSupplier.get().runPickle(pickleEvent); } }); } } } executor.shutdown(); try { while (!executor.awaitTermination(1, TimeUnit.DAYS)) ; } catch (InterruptedException e) { throw new CucumberException(e); } bus.send(new TestRunFinished(bus.getTime())); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } <START> if (obj == null) { return false; } <END> if (!(obj instanceof ConnectionEndpoint)) { return false; } ConnectionEndpoint other = (ConnectionEndpoint) obj; return Arrays.equals(fAddress, other.fAddress) && fPort == other.fPort; }</code><technical_language>this is redundant next instanceof check</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ConnectionEndpoint)) { return false; } ConnectionEndpoint other = (ConnectionEndpoint) obj; return Arrays.equals(fAddress, other.fAddress) && fPort == other.fPort; }
Source:
<code>public URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException { URIBuilder uriBuilder = new URIBuilder(BASIC_SEARCH_URL); <START> uriBuilder.addParameter("query", query); <END> uriBuilder.addParameter("sort", "score"); URI uri = uriBuilder.build(); return uri.toURL(); }</code><technical_language>Please chain method calls: java return new URIBuilder(BASIC_SEARCH_URL)) .addParameter("query", query) .addParameter("sort", "score") .build() .toURL();</technical_language>

Target:
public URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException { return new URIBuilder(BASIC_SEARCH_URL) .addParameter("query", query) .addParameter("sort", "score") .build() .toURL(); }
Source:
<code><START> public boolean await() throws InterruptedException { <END> if (!latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT)) { throw new InterruptedException("Timeout elapsed."); } return latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT); }</code><technical_language>I this is needed. This method checks return of latch.await() throws failure. client need assert returning method success</technical_language>

Target:
public void await() throws InterruptedException { if (!latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT)) { throw new InterruptedException("Timeout elapsed."); } }
Source:
<code>private QueryResult executeQueryControl() { Query query = queryPair.getControl(); QueryResult setupResult = null; QueryResult queryResult = null; try { <START> setupResult = setup(query, testPreQueryResults, testPrequery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPrequery, testTimeout, sessionProperties)); <END> if (setupResult.getState() == State.SUCCESS) { queryResult = executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), query.getQuery(), testTimeout, sessionProperties); } } finally { int retry = 0; QueryResult tearDownResult; do { tearDownResult = tearDown(query, controlPostQueryResults, controlPostquery -> executeQuery(controlGateway, controlUsername, controlPassword, queryPair.getControl(), controlPostquery, controlTimeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } retry++; } while (retry < controlTeardownRetries); if (tearDownResult.getState() != State.SUCCESS) { queryResult = tearDownResult; if (tearDownResult.getException() != null) { if (setupResult.getException() != null) { tearDownResult.addSuppressed(setupResult.getException()); } if (queryResult.getException() != null) { tearDownResult.addSuppressed(queryResult.getException()); } } } } return queryResult; }</code><technical_language>changing test? typos</technical_language>

Target:
private QueryResult executeQueryControl() { Query query = queryPair.getControl(); QueryResult setupResult = null; QueryResult queryResult = null; try { setupResult = setup(query, controlPreQueryResults, controlPrequery -> executeQuery(controlGateway, controlUsername, controlPassword, queryPair.getControl(), controlPrequery, controlTimeout, sessionProperties)); if (setupResult.getState() == State.SUCCESS) { queryResult = executeQuery(controlGateway, controlUsername, controlPassword, queryPair.getControl(), query.getQuery(), controlTimeout, sessionProperties); } } finally { int retry = 0; QueryResult tearDownResult; do { tearDownResult = tearDown(query, controlPostQueryResults, controlPostquery -> executeQuery(controlGateway, controlUsername, controlPassword, queryPair.getControl(), controlPostquery, controlTimeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } retry++; } while (retry < controlTeardownRetries); if (tearDownResult.getState() != State.SUCCESS) { if (tearDownResult.getException() != null) { if (setupResult.getException() != null) { tearDownResult.addSuppressed(setupResult.getException()); } if (queryResult.getException() != null) { tearDownResult.addSuppressed(queryResult.getException()); } } queryResult = tearDownResult; } } return queryResult; }
Source:
<code>public void testConvertWeaselBeaconToSpan_withPageLoadBeacon_withBackendTraceId() throws ServletException, IOException { MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); mockHttpServletRequest.setParameter("ty", "pl"); mockHttpServletRequest.setParameter("d", "518"); mockHttpServletRequest.setParameter("r", "1496751574200"); mockHttpServletRequest.setParameter("ts", "-197"); mockHttpServletRequest.setParameter("t", "a6b5fd025be24191"); mockHttpServletRequest.setParameter("bt", "6210be349041096e"); servlet.doPost(mockHttpServletRequest, new MockHttpServletResponse()); final List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertThat(finishedSpans).hasSize(1); MockSpan span = finishedSpans.get(0); final String spanIdOfPageloadTrace = B3HeaderFormat.getB3Identifiers(mockTracer, span).getSpanId(); final B3HeaderFormat.B3Identifiers traceIdsOfServerSpan = B3HeaderFormat.B3Identifiers.builder() .traceId("6210be349041096e") .spanId("6210be349041096e") .build(); <START> verify(reportingSpanEventListener).update(eq(traceIdsOfServerSpan), newSpanIdentifiers, eq(Collections.singletonMap("parent_id", spanIdOfPageloadTrace))); <END> assertSoftly(softly -> softly.assertThat(span.tags()) .containsEntry("type", "pageload") .containsEntry("trace_id", "6210be349041096e") .doesNotContainEntry(Tags.SAMPLING_PRIORITY.getKey(), 0)); }</code><technical_language>compile -> newSpanIdentifiers is undefined</technical_language>

Target:
public void testConvertWeaselBeaconToSpan_withPageLoadBeacon_withBackendTraceId() throws ServletException, IOException { MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); mockHttpServletRequest.setParameter("ty", "pl"); mockHttpServletRequest.setParameter("d", "518"); mockHttpServletRequest.setParameter("r", "1496751574200"); mockHttpServletRequest.setParameter("ts", "-197"); mockHttpServletRequest.setParameter("t", "a6b5fd025be24191"); final String backendTraceId = "6210be349041096e"; mockHttpServletRequest.setParameter("bt", backendTraceId); final String backendSpanId = "6210be349041096e"; mockHttpServletRequest.setParameter("m_bs", backendSpanId); servlet.doPost(mockHttpServletRequest, new MockHttpServletResponse()); final List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertThat(finishedSpans).hasSize(1); MockSpan span = finishedSpans.get(0); final String spanIdOfPageloadTrace = B3HeaderFormat.getB3Identifiers(mockTracer, span).getSpanId(); final B3HeaderFormat.B3Identifiers traceIdsOfServerSpan = B3HeaderFormat.B3Identifiers.builder() .traceId(backendTraceId) .spanId(backendSpanId) .build(); final B3HeaderFormat.B3Identifiers newSpanIdentifiers = B3HeaderFormat.B3Identifiers.builder() .traceId(backendTraceId) .spanId(backendSpanId) .parentSpanId(spanIdOfPageloadTrace) .build(); verify(reportingSpanEventListener).update(eq(traceIdsOfServerSpan), eq(newSpanIdentifiers), eq(Collections.emptyMap())); assertSoftly(softly -> softly.assertThat(span.tags()) .containsEntry("type", "pageload") .containsEntry("trace_id", backendTraceId) .doesNotContainEntry(Tags.SAMPLING_PRIORITY.getKey(), 0)); }
Source:
<code>private void processDataOrChildChange(WatchedEvent event, long notificationTime) { final String path = event.getPath(); if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) { Set<IZkChildListener> childListeners = _childListener.get(path); if (childListeners != null && !childListeners.isEmpty()) { fireChildChangedEvents(path, childListeners); } } if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) { <START> boolean isPathExist = event.getType() != EventType.NodeDeleted; <END> Set<IZkDataListenerEntry> listeners = _dataListener.get(path); if (listeners != null && !listeners.isEmpty()) { fireDataChangedEvents(event.getPath(), listeners, notificationTime, isPathExist); } } }</code><technical_language>nit: doesPathExist pathExists</technical_language>

Target:
private void processDataOrChildChange(WatchedEvent event, long notificationTime) { final String path = event.getPath(); final boolean pathExists = event.getType() != EventType.NodeDeleted; if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) { Set<IZkChildListener> childListeners = _childListener.get(path); if (childListeners != null && !childListeners.isEmpty()) { fireChildChangedEvents(path, childListeners, pathExists); } } if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) { Set<IZkDataListenerEntry> listeners = _dataListener.get(path); if (listeners != null && !listeners.isEmpty()) { fireDataChangedEvents(event.getPath(), listeners, OptionalLong.of(notificationTime), pathExists); } } }
Source:
<code>public void testGetFields() throws Exception { BugzillaRestClient client = new BugzillaRestClient(actualFixture.location()); <START> assertNotNull(client.getClient()); <END> assertNull(client.getClient().getLoginToken()); File file = File.createTempFile("mylyn", "fields"); try { BugzillaRestFieldResponse fields = client.getFields(new NullOperationMonitor()); BugzillaRestField[] fieldArray = fields.getFields(); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); out.write(new Gson().toJson(fieldArray)); out.close(); assertEquals(IOUtils.toString(CommonTestUtil.getResource(this, "testdata/fields.json")), IOUtils.toString(new FileInputStream(file))); } finally { file.delete(); } }</code><technical_language>assertions relevant for this test</technical_language>

Target:
public void testGetFields() throws Exception { BugzillaRestClient client = BugzillaRestConnector.getDefault().getClient(actualFixture.repository().getId()); BugzillaRestFieldResponse fields = client.getFields(new NullOperationMonitor()); BugzillaRestField[] fieldArray = fields.getFields(); assertEquals(IOUtils.toString(CommonTestUtil.getResource(this, "testdata/fields.json")), new Gson().toJson(fieldArray)); assertConfigurationFieldNames(Arrays.asList(fields.getFields())); }
Source:
<code>public boolean isSampleCourse(String courseId) { if(courseId == null){ Assumption.fail("Course ID is null"); <START> } <END> return StringHelper.isMatching(courseId, FieldValidator.REGEX_SAMPLE_COURSE_ID); }</code><technical_language>This is Assumption.assertNotNull(courseId, "Course ID is null"); right</technical_language>

Target:
public boolean isSampleCourse(String courseId) { Assumption.assertNotNull("Course ID is null", courseId); return StringHelper.isMatching(courseId, FieldValidator.REGEX_SAMPLE_COURSE_ID); }
Source:
<code>public boolean canRegisterSynchronization() { return Assert.checkNotNullParam("transactionSynchronizationRegistry", transactionSynchronizationRegistry). <START> getTransactionStatus() == Status.STATUS_ACTIVE; <END> }</code><technical_language>this method restored, implemented as: TransactionSynchronizationRegistry curTsr = transactionSynchronizationRegistry; return curTsr != null ? curTsr : (TransactionSynchronizationRegistry) jndiService().locate(TSR_NAME); achieves desired perf benefit risk of bypassing current mechanism in favor of else. setTransactionSynchronizationRegistry method is called HibernatePersistenceProviderAdapater.injectJtaManager called deep logic some JPA related DUPs. If logic executed (which possible, e.g. if JPA deployments) if some small future change results in set in some scenario, this static field set</technical_language>

Target:
public boolean canRegisterSynchronization() { return locateTransactionSynchronizationRegistry(). getTransactionStatus() == Status.STATUS_ACTIVE; }
Source:
<code>protected boolean determinePageCompletion() { if (getElementViewer().getCheckedElements().length <= 0) { return false; } validateProject(); <START> <END> if ((fExperimentName != null) && (fCreateExperimentCheckbox.getSelection())) { String name = fExperimentNameText.getText(); if ((fTraceExperimentElement != null) && (name != null)) { TmfExperimentElement element = fTraceExperimentElement.getExperiment(name); if (element != null) { setMessage(null); setErrorMessage(NLS.bind(RemoteMessages.RemoteFetchLogWizardRemotePage_ErrorExperimentAlreadyExists, name)); return false; } } } return true; }</code><technical_language>similar checks import wizard: - trimmed text - allow empty - check for valid file name file system</technical_language>

Target:
protected boolean determinePageCompletion() { if (getElementViewer().getCheckedElements().length <= 0) { return false; } validateProject(); if ((fExperimentName != null) && (fCreateExperimentCheckbox.getSelection())) { String name = fExperimentNameText.getText().trim(); if (name.isEmpty()) { setMessage(null); setErrorMessage(RemoteMessages.RemoteFetchLogWizardRemotePage_ErrorEmptyExperimentName); return false; } IWorkspace workspace = ResourcesPlugin.getWorkspace(); if ((workspace != null) && (!workspace.validateName(name, IResource.FILE).isOK())) { setMessage(null); setErrorMessage(NLS.bind(RemoteMessages.RemoteFetchLogWizardRemotePage_ErrorExperimentNameInvalid, name)); return false; } TmfExperimentFolder experimentFolder = fExperimentFolderElement; if (experimentFolder != null) { TmfExperimentElement element = experimentFolder.getExperiment(name); if (element != null) { setMessage(null); setErrorMessage(NLS.bind(RemoteMessages.RemoteFetchLogWizardRemotePage_ErrorExperimentAlreadyExists, name)); return false; } IFolder expResource = experimentFolder.getResource(); IResource res = expResource.findMember(name); if (res != null) { setMessage(null); setErrorMessage(NLS.bind(RemoteMessages.RemoteFetchLogWizardRemotePage_ErrorResourceAlreadyExists, name)); return false; } } } return true; }
Source:
<code>public View getOverflowMenuAnchor() { View view = getToolbar().findViewById(R.id.menu_overflow_button); <START> return getToolbar(); <END> }</code><technical_language>reason check of view</technical_language>

Target:
public View getOverflowMenuAnchor() { View view = getToolbar().findViewById(R.id.menu_overflow_button); return view == null ? getToolbar() : view; }
Source:
<code>private void assertHasPillar(Grid grid, Point point, boolean needsPillar){ boolean hasPillar = false; for (Entity entity : grid.get(point)){ <START> if (entity instanceof Box && !((Box)entity).isDestructible()){ <END> hasPillar = true; } } assertEquals(hasPillar, needsPillar); }</code><technical_language>above, entity instanceof Pillar work</technical_language>

Target:
private void assertHasPillar(Grid grid, Point point, boolean needsPillar){ boolean hasPillar = false; for (Entity entity : grid.get(point)){ if (entity instanceof Pillar){ hasPillar = true; } } assertEquals(hasPillar, needsPillar); }
Source:
<code>public void serialize(MultimapAggregationState state, BlockBuilder out) { if (state.isEmpty()) { out.appendNull(); } <START> else { <END> BlockBuilder entryBuilder = out.beginBlockEntry(); state.forEach((keyBlock, valueBlock, position) -> { BlockBuilder rowBlockBuilder = entryBuilder.beginBlockEntry(); valueType.appendTo(valueBlock, position, rowBlockBuilder); keyType.appendTo(keyBlock, position, rowBlockBuilder); entryBuilder.closeEntry(); }); out.closeEntry(); } }</code><technical_language>nit: return in if block get rid of this else</technical_language>

Target:
public void serialize(MultimapAggregationState state, BlockBuilder out) { if (state.isEmpty()) { out.appendNull(); return; } BlockBuilder entryBuilder = out.beginBlockEntry(); state.forEach((keyBlock, valueBlock, position) -> { BlockBuilder rowBlockBuilder = entryBuilder.beginBlockEntry(); valueType.appendTo(valueBlock, position, rowBlockBuilder); keyType.appendTo(keyBlock, position, rowBlockBuilder); entryBuilder.closeEntry(); }); out.closeEntry(); }
Source:
<code>public FXDialogService() { <START> this(null, null); <END> }</code><technical_language>null argument lead a NPE in notify. Leaving this(null) work</technical_language>

Target:
public FXDialogService() { this(null); }
Source:
<code>public String toString() { StringBuffer buffer = new StringBuffer(); <START> boolean needParens=(getBoost() != 1.0) || (getMinimumNumberShouldMatch() > 0) ; <END> if (needParens) { buffer.append("("); } for (Query q : must) { buffer.append("+"); buffer.append("("); buffer.append(q); buffer.append(")"); } for (Query q : must_not) { buffer.append("~"); buffer.append("("); buffer.append(q); buffer.append(")"); } for (Query q : should) { buffer.append("("); buffer.append(q); buffer.append(")"); } if (needParens) { buffer.append(")"); } buffer.append("~"); buffer.append(getMinimumNumberShouldMatch()); buffer.append("^"); buffer.append(getBoost()); return buffer.toString(); }</code><technical_language>conditionals avoid appending boost info minimum match</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("("); if (must != null) { for (Query q : must) { builder.append("+").append("(").append(q).append(")"); } } if (must_not != null) { for (Query q : must_not) { builder.append("-").append("(").append(q).append(")"); } } if (should != null) { for (Query q : should) { builder.append("(").append(q).append(")"); } } builder.append("~").append(minimumNumberShouldMatch); builder.append("^").append(boost); builder.append(")"); return builder.toString(); }
Source:
<code>public NewAgileSprint createSprint(NewAgileSprint newSprint) { List<String> names = new LinkedList<String>(); if (Strings.isValid(newSprint.getName())) { names.add(newSprint.getName()); } names.addAll(newSprint.getNames()); if (names.isEmpty()) { throw new OseeArgumentException("name is not valid"); } if (newSprint.getTeamUuid() <= 0) { throw new OseeArgumentException("teamUuid is not valid"); } <START> <END> NewAgileSprint created = null; for (String name : names) { String guid = newSprint.getGuid(); if (guid == null) { guid = GUID.create(); } IAgileSprint sprint = atsServer.getAgileService().createAgileSprint(newSprint.getTeamUuid(), name, guid); created = new NewAgileSprint(); created.setGuid(sprint.getGuid()); created.setName(sprint.getName()); created.setUuid(sprint.getId()); created.setTeamUuid(sprint.getTeamUuid()); created.setActive(sprint.isActive()); } return created; }</code><technical_language>OseeWebApplicationException return Status.BAD_REQUEST instead of throwing argument exceptions</technical_language>

Target:
public NewAgileSprint createSprint(NewAgileSprint newSprint) { List<String> names = new LinkedList<String>(); if (Strings.isValid(newSprint.getName())) { names.add(newSprint.getName()); } names.addAll(newSprint.getNames()); if (names.isEmpty()) { throw new OseeWebApplicationException(Status.BAD_REQUEST, "name is not valid"); } if (newSprint.getTeamUuid() <= 0) { throw new OseeWebApplicationException(Status.BAD_REQUEST, "teamUuid is not valid"); } NewAgileSprint created = null; for (String name : names) { String guid = newSprint.getGuid(); if (guid == null) { guid = GUID.create(); } IAgileSprint sprint = atsServer.getAgileService().createAgileSprint(newSprint.getTeamUuid(), name, guid); created = new NewAgileSprint(); created.setGuid(sprint.getGuid()); created.setName(sprint.getName()); created.setUuid(sprint.getId()); created.setTeamUuid(sprint.getTeamUuid()); created.setActive(sprint.isActive()); } return created; }
Source:
<code>public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 1) { <START> throw new IAE("function '%s' needs 1 argument", name()); <END> } final String arg = args.get(0).eval(bindings).asString(); return ExprEval.of(Strings.nullToEmpty(arg).trim()); }</code><technical_language>above. move this common block a method of Function places</technical_language>

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 1) { throw new IAE("Function[%s] needs 1 argument", name()); } final String arg = args.get(0).eval(bindings).asString(); return ExprEval.of(Strings.nullToEmpty(arg).trim()); }
Source:
<code>@CheckForNull String getUserData() { Executor executor = Executor.currentExecutor(); if (executor != null) { <START> Queue.Executable currentExecutable = executor.getCurrentExecutable(); <END> if (currentExecutable != null) { Config userData = ConfigFiles.getByIdOrNull((Run<?, ?>) currentExecutable, getEffectiveSlaveOptions().getUserDataId()); return (userData == null || userData.content.isEmpty()) ? null : userData.content ; } } return null; }</code><technical_language>This is executed build generally</technical_language>

Target:
@CheckForNull String getUserData() { String userDataId = Util.fixEmpty(getEffectiveSlaveOptions().getUserDataId()); if(userDataId != null) { Config userData = ConfigFiles.getByIdOrNull(Jenkins.getActiveInstance(), userDataId); return (userData == null || userData.content.isEmpty()) ? null : userData.content ; } return null; }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeFacebookSdk(); setContentView(R.layout.activity_project); currentFragmentPosition = FRAGMENT_SCENES; if (getIntent() != null && getIntent().hasExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST)) { setReturnToProjectsList(true); } if (savedInstanceState == null) { Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { currentFragmentPosition = bundle.getInt(EXTRA_FRAGMENT_POSITION, FRAGMENT_SCENES); } } Project project = ProjectManager.getInstance().getCurrentProject(); <START> if (project.getSceneList() == null || project.getSceneList().size() == 1) { <END> currentFragmentPosition = FRAGMENT_SPRITES; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); updateCurrentFragment(currentFragmentPosition, fragmentTransaction); fragmentTransaction.commit(); showLegoInfoFragmentIfNeeded(this.getFragmentManager()); }</code><technical_language>get scenelist line</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeFacebookSdk(); setContentView(R.layout.activity_project); currentFragmentPosition = FRAGMENT_SCENES; if (getIntent() != null && getIntent().hasExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST)) { setReturnToProjectsList(true); } if (savedInstanceState == null) { Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { currentFragmentPosition = bundle.getInt(EXTRA_FRAGMENT_POSITION, FRAGMENT_SCENES); } } List<Scene> scenes = ProjectManager.getInstance().getCurrentProject().getSceneList(); if (scenes == null || scenes.size() == 1) { currentFragmentPosition = FRAGMENT_SPRITES; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); updateCurrentFragment(currentFragmentPosition, fragmentTransaction); fragmentTransaction.commit(); showLegoInfoFragmentIfNeeded(this.getFragmentManager()); }
Source:
<code>public final ValidationErrors validateModel(final Collection<DataSample> model) { final ValidationErrors validationErrors = new ValidationErrors(); int recordNumber = 2; for (final DataSample record : model) { final Set<ConstraintViolation<DataSample>> violations = this.validator.validate(record); for (final ConstraintViolation<DataSample> violation : violations) { int errorCode = 0; String errorType = "Unknown"; final Matcher errorKeyMatcher = ERROR_KEY_PATTERN.matcher(violation.getMessageTemplate()); if (errorKeyMatcher.matches()) { errorCode = Integer.parseInt(errorKeyMatcher.group("errorCode")); errorType = errorKeyMatcher.group("errorType"); } ValidationError error = null; if (errorType.equals(COMBINATION)) { <START> error = new DependencyValidationError( <END> (record.getReturnType() != null) ? record.getReturnType().getEntity().getName() : null, null, (record.getParameter() != null) ? record.getParameter().getEntity().getName() : null, (record.getUnit() != null) ? record.getUnit().getEntity().getName() : null ); } else { error = new ValidationError(); } String errorValue = null; FieldDefinition definition = getFieldForViolation(model, violation); if (violation.getInvalidValue() instanceof String) { errorValue = (String) violation.getInvalidValue(); } else if (violation.getInvalidValue() instanceof FieldValue) { errorValue = ((FieldValue) violation.getInvalidValue()).getInputValue(); } if (definition != null) { error.setFieldName(definition.getName()); error.setDefinition(definition.getDescription()); } error.setErrorValue(errorValue); error.setLineNumber(recordNumber); error.setErrorMessage(violation.getMessage()); error.setErrorCode(errorCode); error.setErrorType(errorType); validationErrors.addError(error); } recordNumber++; } return validationErrors; }</code><technical_language>discussed, lets add a static method AbstractEntityValue avoid inline null checks entities</technical_language>

Target:
public final ValidationErrors validateModel(final Collection<DataSample> model) { final ValidationErrors validationErrors = new ValidationErrors(); int recordNumber = 2; for (final DataSample record : model) { final Set<ConstraintViolation<DataSample>> violations = this.validator.validate(record); for (final ConstraintViolation<DataSample> violation : violations) { int errorCode = 0; String errorType = "Unknown"; final Matcher errorKeyMatcher = ERROR_KEY_PATTERN.matcher(violation.getMessageTemplate()); if (errorKeyMatcher.matches()) { errorCode = Integer.parseInt(errorKeyMatcher.group("errorCode")); errorType = errorKeyMatcher.group("errorType"); } List<FieldDefinition> fieldsForValidation = getFieldsForViolation(violation); ValidationError.ErrorData[] errorData = getErrorDataFromFields(record, fieldsForValidation); ValidationError error = new ValidationError(); error.setErrorData(errorData); error.setLineNumber(recordNumber); error.setErrorMessage(violation.getMessage()); error.setErrorCode(errorCode); error.setErrorType(errorType); validationErrors.addError(error); } recordNumber++; } return validationErrors; }
Source:
<code>private void initializePlayer() { if (player == null) { TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, new DefaultLoadControl()); player.addListener(this); player.setMetadataOutput(this); exoPlayerView.setPlayer(player); audioBecomingNoisyReceiver.setListener(this); playerNeedsSource = true; PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } <START> setPlayWhenReady(!isPaused); <END> if (playerNeedsSource && srcUri != null) { MediaSource mediaSource = buildMediaSource(srcUri, extension); mediaSource = repeat ? new LoopingMediaSource(mediaSource) : mediaSource; boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(mediaSource, !haveResumePosition, false); playerNeedsSource = false; eventEmitter.loadStart(); loadVideoStarted = true; } }</code><technical_language>this change made, does. testing changes, video plays automatically if I switch sources</technical_language>

Target:
private void initializePlayer() { if (player == null) { TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, new DefaultLoadControl()); player.addListener(this); player.setMetadataOutput(this); exoPlayerView.setPlayer(player); audioBecomingNoisyReceiver.setListener(this); setPlayWhenReady(!isPaused); playerNeedsSource = true; PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } if (playerNeedsSource && srcUri != null) { MediaSource mediaSource = buildMediaSource(srcUri, extension); mediaSource = repeat ? new LoopingMediaSource(mediaSource) : mediaSource; boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(mediaSource, !haveResumePosition, false); playerNeedsSource = false; eventEmitter.loadStart(); loadVideoStarted = true; } }
Source:
<code>public OVirtNodeUpgrade(VDS vds, String iso) { _vds = vds; _iso = Path.Combine(Config.resolveOVirtISOsRepositoryPath(), iso); _messages = new InstallerMessages(_vds); <START> _thread = new Thread(this); <END> _dialog = new EngineSSHDialog(); }</code><technical_language>Give a name thread</technical_language>

Target:
public OVirtNodeUpgrade(VDS vds, String iso) { _vds = vds; _iso = Path.Combine(Config.resolveOVirtISOsRepositoryPath(), iso); _messages = new InstallerMessages(_vds); _dialog = new EngineSSHDialog(); _thread = new Thread( new Runnable() { @Override public void run() { _threadMain(); } }, "OVirtNodeUpgrade" ); }
Source:
<code>public RetryOptions build() { return new RetryOptions( <START> options.retriesEnabled, <END> options.allowRetriesWithoutTimestamp, options.initialBackoffMillis, options.backoffMultiplier, options.maxElapsedBackoffMillis, options.streamingBufferSize, options.readPartialRowTimeoutMillis, options.maxScanTimeoutRetries, ImmutableSet.copyOf(options.statusToRetryOn)); }</code><technical_language>please fix whitespace. need return options here</technical_language>

Target:
public RetryOptions build() { return options; }