auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private int[] calculateDetailWidths(int fullSize) { int[] hints = new int[mHints.length]; for (int i = 0; i < mHints.length; i++) { if (mHints[i] == null) { hints[i] = -1; } else if (mHints[i].contains("%")) { hints[i] = fullSize * Integer.parseInt(mHints[i].substring(0, mHints[i].indexOf("%"))) / 100; } else { hints[i] = Integer.parseInt(mHints[i]); } } int claimedSpace = 0; int indeterminateColumns = 0; for (int hint : hints) { if (hint != -1) { claimedSpace += hint; } else { indeterminateColumns++; } } <START> if ( <END> fullSize < claimedSpace + indeterminateColumns || fullSize > claimedSpace && indeterminateColumns == 0 ) { claimedSpace += indeterminateColumns; for (int i = 0; i < hints.length; i++) { if (hints[i] == -1) { hints[i] = 1; } else { hints[i] = fullSize * hints[i] / claimedSpace; } } } else if (indeterminateColumns > 0) { int defaultWidth = (fullSize - claimedSpace) / indeterminateColumns; for (int i = 0; i < hints.length; i++) { if (hints[i] == -1) { hints[i] = defaultWidth; } } } return hints; }</code><technical_language>a fan of atypical line breaks in this if's test expression</technical_language>

Target:
private int[] calculateDetailWidths(int fullSize) { int[] widths = new int[mHints.length]; for (int i = 0; i < mHints.length; i++) { if (mHints[i] == null) { widths[i] = -1; } else if (mHints[i].contains("%")) { widths[i] = fullSize * Integer.parseInt(mHints[i].substring(0, mHints[i].indexOf("%"))) / 100; } else { widths[i] = Integer.parseInt(mHints[i]); } } int claimedSpace = 0; int indeterminateColumns = 0; for (int width : widths) { if (width != -1) { claimedSpace += width; } else { indeterminateColumns++; } } if (fullSize < claimedSpace + indeterminateColumns || (fullSize > claimedSpace && indeterminateColumns == 0)) { claimedSpace += indeterminateColumns; for (int i = 0; i < widths.length; i++) { if (widths[i] == -1) { widths[i] = 1; } else { widths[i] = fullSize * widths[i] / claimedSpace; } } } else if (indeterminateColumns > 0) { int defaultWidth = (fullSize - claimedSpace) / indeterminateColumns; for (int i = 0; i < widths.length; i++) { if (widths[i] == -1) { widths[i] = defaultWidth; } } } return widths; }
Source:
<code>private void onGoogleSignInAccountReady(@NonNull GoogleSignInAccount signInAccount) { synchronized (initializationLock) { if (isInitializing.get()) { <START> AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() { <END> @Override protected String doInBackground(Void... params) { String token = null; try { final String scopes = "oauth2:" + DriveScopes.DRIVE_APPDATA + " " + DriveScopes.DRIVE_FILE; token = GoogleAuthUtil.getToken(context, signInAccount.getAccount(), scopes); } catch (UserRecoverableAuthException e) { activity.startActivityForResult(e.getIntent(), REQUEST_CODE_GOOGLE_SERVICE_REAUTH); } catch (IOException e) { } catch (GoogleAuthException e) { } return token; } @Override protected void onPostExecute(String result) { if (!TextUtils.isEmpty(result)) { GoogleSignInAccountFinalization(signInAccount); } } }; task.execute(); } } }</code><technical_language>get rid of this AsyncTask replace Rx Single. do like: Single.fromCallable(() -> { final String scopes = "oauth2:" + DriveScopes.DRIVE_APPDATA + " " + DriveScopes.DRIVE_FILE; token = GoogleAuthUtil.getToken(context, signInAccount.getAccount(), scopes); }) .onErrorReturn( /* Handle errors */) .subscribeOn(Schedulers.io) .subscribe(onSuccess -> GoogleSignInAccountFinalization(signInAccount), onError -> activity.startActivityForResult(e.getIntent(), REQUEST_CODE_GOOGLE_SERVICE_REAUTH)); achieve effect. In general, AsyncTasks super deprecated, avoid handle rotation generally lots of memory leaks,</technical_language>

Target:
private void onGoogleSignInAccountReady(@NonNull GoogleSignInAccount signInAccount) { synchronized (initializationLock) { if (isInitializing.get()) { Single.fromCallable(() -> { final String scopes = "oauth2:" + DriveScopes.DRIVE_APPDATA + " " + DriveScopes.DRIVE_FILE; return GoogleAuthUtil.getToken(context, signInAccount.getAccount(), scopes); }).doOnError(throwable -> { Logger.error(GoogleDriveBackupManager.this, "Failed to authenticate user with status: {}", throwable.getMessage()); }).subscribeOn(Schedulers.io()) .subscribe(onSuccess -> GoogleSignInAccountFinalization(signInAccount), onError -> { if (onError instanceof UserRecoverableAuthException) { activity.startActivityForResult(((UserRecoverableAuthException) onError).getIntent(), REQUEST_CODE_GOOGLE_SERVICE_REAUTH); } else if (onError instanceof UserRecoverableAuthIOException) { activity.startActivityForResult(((UserRecoverableAuthIOException) onError).getIntent(), REQUEST_CODE_GOOGLE_SERVICE_REAUTH); } }); } } }
Source:
<code>public double getDouble() { <START> return doubles[index] == null ? NullHandling.ZERO_DOUBLE : doubles[index]; <END> }</code><technical_language>this return 0 doubles[index] == null && NullHandling.replaceWithDefault() == true? throw exception</technical_language>

Target:
public double getDouble() { if (doubles[index] != null) { return doubles[index]; } else if (NullHandling.replaceWithDefault()) { return NullHandling.ZERO_DOUBLE; } else { throw new IllegalStateException("Should never be invoked when current value is null && SQL-compatible null handling is enabled!"); } }
Source:
<code>public Statement apply(Statement base, Description description) { if (description.isSuite()) { <START> throw new MockitoException("JUnitTestRule can not be used as a @ClassRule."); <END> } return createStatement(base, description.getDisplayName(), this.testInstance); }</code><technical_language>double checking - do coverage for this case</technical_language>

Target:
public Statement apply(Statement base, Description description) { return sessionStore.createStatement(base, description.getDisplayName(), this.testInstance); }
Source:
<code>private void postPrepareSanStorageForEdit(final SanStorageModelBase model, boolean isStorageActive, StorageDomain storage) { model.setStorageDomain(storage); VDS host = getContainer().getHost().getSelectedItem(); if (Objects.equals(previousGetLunsByVGIdHost, host) && isStorageActive) { return; } previousGetLunsByVGIdHost = host; Guid hostId = host != null && isStorageActive ? host.getId() : null; boolean isInMaintenance = false; Set<String> metadata = null; if (!model.getContainer().isNewStorage()) { isInMaintenance = model.getContainer().getStorage().getStatus() == StorageDomainStatus.Maintenance; metadata = model.getMetadataDevices(); } boolean <START> finalIsInMaintenance = <END> isInMaintenance; Set<String> finalMetadata = metadata; AsyncDataProvider.getInstance().getLunsByVgId(new AsyncQuery<>(lunList -> model.applyData(finalIsInMaintenance, finalMetadata, lunList, true, Linq.findSelectedItems((Collection<EntityModel<?>>) getSelectedItem()))), storage.getStorage(), hostId); }</code><technical_language>do 'final'</technical_language>

Target:
private void postPrepareSanStorageForEdit(final SanStorageModelBase model, boolean isStorageActive, StorageDomain storage) { model.setStorageDomain(storage); VDS host = getContainer().getHost().getSelectedItem(); if (Objects.equals(previousGetLunsByVGIdHost, host) && isStorageActive) { return; } previousGetLunsByVGIdHost = host; Guid hostId = host != null && isStorageActive ? host.getId() : null; boolean isInMaintenance = false; Set<String> metadata = null; if (!model.getContainer().isNewStorage()) { isInMaintenance = model.getContainer().getStorage().getStatus() == StorageDomainStatus.Maintenance; metadata = model.getMetadataDevices(); } boolean finalIsInMaintenance = isInMaintenance; Set<String> finalMetadata = metadata; AsyncDataProvider.getInstance().getLunsByVgId(new AsyncQuery<>(lunList -> model.applyData(lunList, true, Linq.findSelectedItems((Collection<EntityModel<?>>) getSelectedItem()), finalIsInMaintenance, finalMetadata)), storage.getStorage(), hostId); }
Source:
<code><START> public void <END> setPromiscuousBinding(IBinding binding) { promiscuousBinding = binding; }</code><technical_language>final</technical_language>

Target:
public final void setPromiscuousBinding(IBinding binding) { promiscuousBinding = binding; }
Source:
<code>private static void notifyCallbacks() { <START> synchronized (instance) { <END> if (workspace == null) return; } while (!callbacks.isEmpty()) { Function<Workspace,Void> callback = callbacks.poll(); callback.apply(workspace); } }</code><technical_language>instance null if this method is called onWorkspaceInit Central is inited. I suggest remove synchronized(instance) workspace field volatile</technical_language>

Target:
private static void notifyCallbacks() { if (workspace == null) return; for (Function<Workspace,Void> callback = callbacks.poll(); callback != null; callback = callbacks.poll()) { try { callback.apply(workspace); } catch (Throwable t) { } } }
Source:
<code>public void testHandlerMBeanRegistration() throws Exception { <START> System.out.println(server); <END> Set<ObjectName> names = this.server .queryNames(new ObjectName("org.springframework.integration:*,name=testGateway"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,name=foo"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,name=foo#2"), null); assertEquals(1, names.size()); }</code><technical_language>SOUT. I guess remove next push</technical_language>

Target:
public void testHandlerMBeanRegistration() throws Exception { Set<ObjectName> names = this.server .queryNames(new ObjectName("org.springframework.integration:*,name=testGateway"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,type=MessageSource,name=foo"), null); assertEquals(1, names.size()); names = this.server.queryNames(new ObjectName("org.springframework.integration:*,name=foo#2"), null); assertEquals(1, names.size()); }
Source:
<code>private void sendHeartbeat(Member target) { if (target == null) { return; } try { MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata(); Collection<MemberInfo> suspectedMembers; if (clusterService.getMembershipManager().isPartialDisconnectionDetectionEnabled() && !clusterService.isMaster() && target.getAddress().equals(clusterService.getMasterAddress())) { suspectedMembers = clusterService.getMembershipManager() .getSuspectedMembers() .stream() .map(MemberInfo::new) .collect(toSet()); } else { suspectedMembers = Collections.emptySet(); <START> } <END> long clusterTime = clusterClock.getClusterTime(); Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterTime, suspectedMembers); op.setCallerUuid(clusterService.getThisUuid()); node.nodeEngine.getOperationService().send(op, target.getAddress()); } catch (Exception e) { if (logger.isFineEnabled()) { logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage())); } } }</code><technical_language>minor: rewritten else: Collection<MemberInfo> suspectedMembers = Collections.emptySet(); if (clusterService.getMembershipManager().isPartialDisconnectionDetectionEnabled() && !clusterService.isMaster() && target.getAddress().equals(clusterService.getMasterAddress())) { suspectedMembers = clusterService.getMembershipManager() .getSuspectedMembers() .stream() .map(MemberInfo::new) .collect(toSet()); }</technical_language>

Target:
private void sendHeartbeat(Member target) { if (target == null) { return; } try { MembersViewMetadata membersViewMetadata = clusterService.getMembershipManager().createLocalMembersViewMetadata(); Collection<MemberInfo> suspectedMembers = Collections.emptySet(); if (clusterService.getMembershipManager().isPartialDisconnectionDetectionEnabled() && !clusterService.isMaster() && target.getAddress().equals(clusterService.getMasterAddress())) { suspectedMembers = clusterService.getMembershipManager() .getSuspectedMembers() .stream() .map(MemberInfo::new) .collect(toSet()); } long clusterTime = clusterClock.getClusterTime(); Operation op = new HeartbeatOp(membersViewMetadata, target.getUuid(), clusterTime, suspectedMembers); op.setCallerUuid(clusterService.getThisUuid()); node.nodeEngine.getOperationService().send(op, target.getAddress()); } catch (Exception e) { if (logger.isFineEnabled()) { logger.fine(format("Error while sending heartbeat -> %s[%s]", e.getClass().getName(), e.getMessage())); } } }
Source:
<code>private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) { try { <START> return SecurityActions.getConstructor(ClassFile.class, String.class, int.class, String.class, ClassLoader.class, Arrays2.EMPTY_STRING_ARRAY.getClass()) <END> .newInstance(name, accessFlags, superclass, classLoader, interfaces); } catch (Exception e) { throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause()); } }</code><technical_language>constructor right away, i.e. reflection</technical_language>

Target:
private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) { try { return new ClassFile(name, accessFlags, superclass, classLoader, interfaces); } catch (Exception e) { throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause()); } }
Source:
<code>public void testInvalidAddress() throws InterruptedException, IOException { final String invalidHost = "invalid.host"; final int port = 10501; Context context = new Context(); context.put("port", String.valueOf(port)); context.put("bind", invalidHost); Configurables.configure(source, context); try { source.start(); Assert.fail("Expected an exception during startup caused by binding on a invalid host"); } catch (FlumeException e) { logger.info("Received an expected exception.", e); <START> Assert.assertTrue("Expected a bind related root cause", <END> e.getMessage().contains("Failed to bind to")); } Assert.assertEquals("Server is stopped", LifecycleState.STOP, source.getLifecycleState()); }</code><technical_language>(line 150)</technical_language>

Target:
public void testInvalidAddress() throws InterruptedException, IOException { final String invalidHost = "invalid.host"; final int port = 10501; Context context = new Context(); context.put("port", String.valueOf(port)); context.put("bind", invalidHost); Configurables.configure(source, context); try { source.start(); Assert.fail("Expected an exception during startup caused by binding on a invalid host"); } catch (FlumeException e) { logger.info("Received an expected exception.", e); Assert.assertTrue("Expected a server socket setup related root cause", e.getMessage().contains("server socket")); } Assert.assertEquals("Server is stopped", LifecycleState.STOP, source.getLifecycleState()); }
Source:
<code>public VmSnapshotPreviewPopupWidget(CommonApplicationConstants constants) { <START> memoryEditor = new EntityModelCheckBoxEditor(Align.RIGHT); <END> initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); localize(constants); ViewIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); }</code><technical_language>extract init method - e.g. initEditors()</technical_language>

Target:
public VmSnapshotPreviewPopupWidget(CommonApplicationConstants constants) { initEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); localize(constants); ViewIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); }
Source:
<code>public static ProjectManager getInstance() { <START> return INSTANCE; <END> }</code><technical_language>[2019-10-01T07:16:01.665Z] /home/catroid/jenkins_slave/workspace/Catroid_PR-3353/catroid/src/main/java/org/catrobat/catroid/ProjectManager.java:98: error: find symbol [2019-10-01T07:16:01.665Z] return INSTANCE; [2019-10-01T07:16:01.665Z] ^ [2019-10-01T07:16:01.665Z] symbol: variable INSTANCE [2019-10-01T07:16:01.665Z] location: class ProjectManager</technical_language>

Target:
public static ProjectManager getInstance() { return instance; }
Source:
<code>public void should_fail_if_actual_is_not_a_package_private_class() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> classes.assertIsPackagePrivate(someInfo(), Object.class)) <START> .withMessage(shouldBePackagePrivate(Object.class).create()); <END> }</code><technical_language>more a style thingy prefer AssertionsUtil.expectAssertionError shown <LINK_0> java @Test void should_fail_if_optional_is_empty() { // Optional<Object> actual = Optional.empty(); // AssertionError assertionError = expectAssertionError(() -> assertThat(actual).containsInstanceOf(Object.class)); // then(assertionError).hasMessage(shouldBePresent(actual).create()); }</technical_language>

Target:
public void should_fail_if_actual_is_not_a_package_private_class() { Class clazz = Object.class; AssertionError assertionError = expectAssertionError(() -> assertThat(clazz).isPackagePrivate()); then(assertionError).hasMessage(shouldBePackagePrivate(Object.class).create()); }
Source:
<code>public void initialize() { if (state == null) { solenoids.shift(); } <START> else { <END> solenoids.shift(state); } }</code><technical_language>run formatter</technical_language>

Target:
public void initialize() { if (state == null) { solenoids.set(); } else { solenoids.set(state); } }
Source:
<code><START> public boolean delete(final String queryId) { <END> final PhysicalPlan<PartitionedQuery, StreamType.Direction> chainedPlan = physicalPlanMap.remove(queryId); if (chainedPlan != null) { final DAG<PartitionedQuery, StreamType.Direction> chainedOperators = chainedPlan.getOperators(); final Iterator<PartitionedQuery> partitionedQueryIterator = GraphUtils.topologicalSort(chainedOperators); while (partitionedQueryIterator.hasNext()) { final PartitionedQuery partitionedQuery = partitionedQueryIterator.next(); partitionedQueryManager.delete(partitionedQuery); } closeSourceAndSink(chainedPlan); return true; } return false; }</code><technical_language>I need delete stored plan delete query</technical_language>

Target:
public boolean delete(final String queryId) { try { planStore.delete(queryId); } catch (final IOException e) { e.printStackTrace(); } return deleteChainedPlan(queryId); }
Source:
<code>public void onStatusUpdate(QpidStatus oldStatus, QpidStatus newStatus) { if (newStatus.equals(oldStatus)) { return; } log.debug("EventSource was notified of a QpidStatus change: {}", newStatus); for (MessageReceiver receiver : this.messageReceivers) { if (!receiver.requiresQpid()) { continue; } <START> if (QpidStatus.FLOW_STOPPED.equals(newStatus) || QpidStatus.DOWN.equals(newStatus)) { <END> receiver.pause(); } else if (QpidStatus.CONNECTED.equals(newStatus)) { receiver.resume(); } } }</code><technical_language>a switch cleaner here</technical_language>

Target:
public void onStatusUpdate(QpidStatus oldStatus, QpidStatus newStatus) { if (newStatus.equals(oldStatus)) { return; } log.debug("EventSource was notified of a QpidStatus change: {}", newStatus); for (MessageReceiver receiver : this.messageReceivers) { if (!receiver.requiresQpid()) { continue; } switch (newStatus) { case FLOW_STOPPED: case DOWN: receiver.pause(); break; case CONNECTED: receiver.resume(); break; default: } } }
Source:
<code>public void run() { <START> IBuild build = editor.getEditorInput().getBuild(); <END> IBuildPlan plan = build.getPlan(); String label = build.getLabel(); EditorHandle handle = new EditorHandle(); handle.setPart(editor); GetBuildsRequest request = new GetBuildsRequest(plan, Collections.singletonList(label), Scope.FULL); GetBuildsOperation operation = BuildsUiInternal.getFactory().getGetBuildsOperation(request); operation.addOperationChangeListener(new RefreshBuildEditorOperationListener(build, handle)); operation.execute(); }</code><technical_language>this change</technical_language>

Target:
public void run() { IBuild build = getBuild(); IBuildPlan plan = build.getPlan(); String label = build.getLabel(); EditorHandle handle = new EditorHandle(); handle.setPart(editor); GetBuildsRequest request = new GetBuildsRequest(plan, Collections.singletonList(label), Scope.FULL); GetBuildsOperation operation = BuildsUiInternal.getFactory().getGetBuildsOperation(request); operation.addOperationChangeListener(new RefreshBuildEditorOperationListener(build, handle)); operation.execute(); }
Source:
<code>void resizeHandle (int width, int height) { if (OS.GTK3) { if (fixedHandle != 0) { <START> OS.swt_fixed_resize (OS.gtk_widget_get_parent(fixedHandle), <END> fixedHandle, width, height); } long child = scrolledHandle != 0 ? scrolledHandle : handle; int sizes = resizeCalculationsGTK3 (child, width, height); width = sizes[0]; height = sizes[1]; OS.swt_fixed_resize (OS.gtk_widget_get_parent(child), child, width, height); } else { if (fixedHandle != 0) OS.gtk_widget_set_size_request (fixedHandle, width, height); OS.gtk_widget_set_size_request (scrolledHandle != 0 ? scrolledHandle : handle, width, height); } }</code><technical_language>is case handled scrollhandle's height/width is changed y resizeCalculationsGTK3, fixed height/width is not</technical_language>

Target:
void resizeHandle (int width, int height) { if (OS.GTK3) { if (fixedHandle != 0) { OS.swt_fixed_resize (OS.gtk_widget_get_parent(fixedHandle), fixedHandle, width, height); } long child = scrolledHandle != 0 ? scrolledHandle : handle; Point sizes = resizeCalculationsGTK3 (child, width, height); width = sizes.x; height = sizes.y; OS.swt_fixed_resize (OS.gtk_widget_get_parent(child), child, width, height); } else { if (fixedHandle != 0) OS.gtk_widget_set_size_request (fixedHandle, width, height); OS.gtk_widget_set_size_request (scrolledHandle != 0 ? scrolledHandle : handle, width, height); } }
Source:
<code>public long getBucketKeyFor(T event) { long expiryKey = getExpiryKey(event); if (expiryKey < expiryPoint) { return -1; } long key = expiryKey / bucketSpan; synchronized (lock) { if (expiryKey > endOfBuckets) { long move = expiryKey - endOfBuckets; <START> endOfBuckets += move; <END> expiryPoint = endOfBuckets - expiryPeriod + 1; if (recordStats) { bucketCounters.getCounter(CounterKeys.HIGH).setValue(endOfBuckets); bucketCounters.getCounter(CounterKeys.LOW).setValue(expiryPoint); } } } return key; }</code><technical_language>move variable removed</technical_language>

Target:
public long getBucketKeyFor(T event) { long expiryKey = getExpiryKey(event); if (expiryKey < expiryPoint) { return -1; } synchronized (lock) { if (expiryKey > endOfBuckets) { endOfBuckets = expiryKey; expiryPoint = endOfBuckets - expiryPeriod + 1; if (recordStats) { bucketCounters.getCounter(CounterKeys.HIGH).setValue(endOfBuckets); bucketCounters.getCounter(CounterKeys.LOW).setValue(expiryPoint); } } } long key = expiryKey / bucketSpan; return key; }
Source:
<code>public void testDownsample_afterAggregation() { iterators = new SeekableView[] { new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG) }; start_time_ms = BASE_TIME + 01000L; end_time_ms = BASE_TIME + 100000; AggregationIterator sgai = AggregationIterator.createForTesting(iterators, start_time_ms, end_time_ms, aggregator, interpolation, rate); Downsampler downsampler = new Downsampler(sgai, 15000, SUM); DataPoint[] expected_data_points = new DataPoint[] { MutableDataPoint.ofDoubleValue(BASE_TIME + 00000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 15000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 30000L, 14), MutableDataPoint.ofDoubleValue(BASE_TIME + 45000L, 7) }; for (DataPoint expected: expected_data_points) { assertTrue(downsampler.hasNext()); DataPoint dp = downsampler.next(); assertEquals(expected.timestamp(), dp.timestamp()); <START> assertEquals(String.format("timestamp = %d", dp.timestamp()), <END> expected.doubleValue(), dp.doubleValue(), 0); } assertFalse(downsampler.hasNext()); }</code><technical_language>"timestamp = " + dp.timestamp()</technical_language>

Target:
public void testDownsample_afterAggregation() { iterators = new SeekableView[] { new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG), new Downsampler(SeekableViewsForTest.fromArray(DATA_5SEC), 10000, AVG) }; start_time_ms = BASE_TIME + 01000L; end_time_ms = BASE_TIME + 100000; AggregationIterator sgai = AggregationIterator.createForTesting(iterators, start_time_ms, end_time_ms, aggregator, interpolation, rate); Downsampler downsampler = new Downsampler(sgai, 15000, SUM); DataPoint[] expected_data_points = new DataPoint[] { MutableDataPoint.ofDoubleValue(BASE_TIME + 00000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 15000L, 7), MutableDataPoint.ofDoubleValue(BASE_TIME + 30000L, 14), MutableDataPoint.ofDoubleValue(BASE_TIME + 45000L, 7) }; for (DataPoint expected: expected_data_points) { assertTrue(downsampler.hasNext()); DataPoint dp = downsampler.next(); assertEquals(expected.timestamp(), dp.timestamp()); assertEquals("timestamp = %d" + dp.timestamp(), expected.doubleValue(), dp.doubleValue(), 0); } assertFalse(downsampler.hasNext()); }
Source:
<code>public void test_dotnet_core_checks_version_if_set_before() { ScannerForMSBuild build = ScannerForMSBuild.create(); build.setScannerVersion("4.2"); assertThat(build.isUsingDotNetCore()).isFalse(); build.setUseDotNetCore(true); assertThat(build.isUsingDotNetCore()).isTrue(); build = ScannerForMSBuild.create(); build.setScannerVersion("2.2"); <START> try { <END> build.setUseDotNetCore(true); fail("Should have failed"); } catch (IllegalStateException e) { assertThat(e.getMessage()).contains("Version of ScannerForMSBuild should be higher than or equals to 4.1.0.1148 to be able to use .Net Core."); } }</code><technical_language>JUnit rule ExpectedException simply: thrown.expect(IllegalStateException.class); thrown.expectMessage("Version of ScannerForMSBuild higher equals 4.1.0.1148 able .Net Core."); build.setUseDotNetCore(true);</technical_language>

Target:
public void test_dotnet_core_checks_version_if_set_before() { ScannerForMSBuild build = ScannerForMSBuild.create(); build.setScannerVersion("4.2"); assertThat(build.isUsingDotNetCore()).isFalse(); build.setUseDotNetCore(true); assertThat(build.isUsingDotNetCore()).isTrue(); build = ScannerForMSBuild.create(); assertThat(build.isUsingDotNetCore()).isFalse(); build.setDotNetCoreExecutable(new File(".")); assertThat(build.isUsingDotNetCore()).isTrue(); build = ScannerForMSBuild.create(); build.setScannerVersion("2.2"); build.setUseDotNetCore(true); build.setProjectDir(new File(".")); thrown.expect(IllegalStateException.class); thrown.expectMessage("Version of ScannerForMSBuild should be higher than or equals to 4.1.0.1148 to be able to use .Net Core."); build.check(); }
Source:
<code>Node createNode() { <START> <END> CommentNode node = new CommentNode(); node.setHtml(html); return node; }</code><technical_language>Remove empty line</technical_language>

Target:
Node createNode() { CommentNode node = new CommentNode(); node.setHtml(isHtml); return node; }
Source:
<code>protected void doDownloadContent(HttpServletResponse httpResponse, SrampAtomApiClient client, String uuid) throws Exception { InputStream ontologyContent = null; String contentType = "application/rdf+xml"; RDF ontologyRDF=client.getOntology(uuid); <START> Ontology ontology=null; <END> if (ontologyRDF != null) { ontology=ontologyRDF.getOntology(); } else{ throw new Exception(Messages.i18n.format("OntologyDownloadServlet.ontology.not.found",uuid)); } StringWriter writer=new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(RDF.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(ontologyRDF, writer); String content = writer.getBuffer().toString(); ontologyContent = new ByteArrayInputStream(content.getBytes("UTF-8")); httpResponse.setHeader("Content-Size", content.getBytes().length + ""); String base = ontologyRDF.getOtherAttributes().get( new QName("<LINK_0>", "base")); String name = "sramp-ontology.owl"; if (base.endsWith(".owl")) { name = base.substring(base.lastIndexOf("/") + 1); } String disposition = "attachment; filename=\"" + name + "\""; super.doDownloadContent(ontologyContent, contentType, disposition, httpResponse); }</code><technical_language>is this variable for</technical_language>

Target:
protected void doDownloadContent(HttpServletResponse httpResponse, SrampAtomApiClient client, String uuid) throws Exception { InputStream ontologyContent = null; String contentType = "application/rdf+xml"; RDF ontologyRDF=client.getOntology(uuid); StringWriter writer=new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(RDF.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(ontologyRDF, writer); String content = writer.getBuffer().toString(); ontologyContent = new ByteArrayInputStream(content.getBytes("UTF-8")); httpResponse.setHeader("Content-Size", content.getBytes().length + ""); String base = ontologyRDF.getOtherAttributes().get( new QName("<LINK_0>", "base")); String name = "sramp-ontology.owl"; if (base.endsWith(".owl")) { name = base.substring(base.lastIndexOf("/") + 1); } String disposition = "attachment; filename=\"" + name + "\""; super.doDownloadContent(ontologyContent, contentType, disposition, httpResponse); }
Source:
<code>public void testFailSlowHeaderTooLong() { EmbeddedChannel slowFailCh = new EmbeddedChannel(new HAProxyMessageDecoder(false)); String headerPart1 = "PROXY TCP4 192.168.0.1 192.168.0.11 56324 " + "000000000000000000000000000000000000000000000000000000000000000000000443"; slowFailCh.writeInbound(copiedBuffer(headerPart1, CharsetUtil.US_ASCII)); String headerPart2 = "more header data"; slowFailCh.writeInbound(copiedBuffer(headerPart2, CharsetUtil.US_ASCII)); String headerPart3 = "end of header\r\n"; int discarded = headerPart1.length() + headerPart2.length() + headerPart3.length() - 2; exceptionRule.expect(HAProxyProtocolException.class); exceptionRule.expectMessage("over " + discarded); <START> slowFailCh.writeInbound(copiedBuffer(headerPart3, CharsetUtil.US_ASCII)); <END> }</code><technical_language>please call slowFailCh.finishAndReleaseAll() in a finally block assert return value</technical_language>

Target:
public void testFailSlowHeaderTooLong() { EmbeddedChannel slowFailCh = new EmbeddedChannel(new HAProxyMessageDecoder(false)); try { String headerPart1 = "PROXY TCP4 192.168.0.1 192.168.0.11 56324 " + "000000000000000000000000000000000000000000000000000000000000000000000443"; assertFalse(slowFailCh.writeInbound(copiedBuffer(headerPart1, CharsetUtil.US_ASCII))); String headerPart2 = "more header data"; assertFalse(slowFailCh.writeInbound(copiedBuffer(headerPart2, CharsetUtil.US_ASCII))); String headerPart3 = "end of header\r\n"; int discarded = headerPart1.length() + headerPart2.length() + headerPart3.length() - 2; exceptionRule.expect(HAProxyProtocolException.class); exceptionRule.expectMessage("over " + discarded); assertFalse(slowFailCh.writeInbound(copiedBuffer(headerPart3, CharsetUtil.US_ASCII))); } finally { assertFalse(slowFailCh.finishAndReleaseAll()); } }
Source:
<code>protected void doUnicityCheck(DocumentModel doc2Check, CoreSession session, Event event) { <START> List<String> xpathFields = Framework.getRuntime().getService(FileManager.class).getFields(); <END> if (xpathFields == null || xpathFields.isEmpty()) { unicityCheckEnabled = false; log.info("Unicity check has been automatically disabled"); return; } for (String field : xpathFields) { Blob blob; try { blob = (Blob) doc2Check.getPropertyValue(field); } catch (PropertyNotFoundException pnfe) { continue; } if (blob == null) { log.debug("No blob retrieved"); continue; } String digest = blob.getDigest(); if (digest == null) { log.debug("Blob has no digest, can not check for unicity"); continue; } List<DocumentLocation> existingDocuments = null; existingDocuments = fileManager.findExistingDocumentWithFile(session, doc2Check.getPathAsString(), digest, session.getPrincipal()); if (!existingDocuments.isEmpty()) { Iterator<DocumentLocation> existingDocumentsIterator = existingDocuments.iterator(); while (existingDocumentsIterator.hasNext()) { if (existingDocumentsIterator.next().getDocRef() == doc2Check.getRef()) { existingDocumentsIterator.remove(); } } log.debug("Existing Documents[" + existingDocuments.size() + "]"); onDuplicatedDoc(session, session.getPrincipal(), doc2Check, existingDocuments, event); } } }</code><technical_language>suggestion List<String> xpathFields = Framework.getService(FileManager.class).getFields();</technical_language>

Target:
protected void doUnicityCheck(DocumentModel doc2Check, CoreSession session, Event event) { List<String> xpathFields = Framework.getService(FileManager.class).getFields(); if (xpathFields == null || xpathFields.isEmpty()) { unicityCheckEnabled = false; log.info("Unicity check has been automatically disabled"); return; } for (String field : xpathFields) { Blob blob; try { blob = (Blob) doc2Check.getPropertyValue(field); } catch (PropertyNotFoundException pnfe) { continue; } if (blob == null) { log.debug("No blob retrieved"); continue; } String digest = blob.getDigest(); if (digest == null) { log.debug("Blob has no digest, can not check for unicity"); continue; } List<DocumentLocation> existingDocuments = null; existingDocuments = fileManager.findExistingDocumentWithFile(session, doc2Check.getPathAsString(), digest, session.getPrincipal()); if (!existingDocuments.isEmpty()) { Iterator<DocumentLocation> existingDocumentsIterator = existingDocuments.iterator(); while (existingDocumentsIterator.hasNext()) { if (existingDocumentsIterator.next().getDocRef() == doc2Check.getRef()) { existingDocumentsIterator.remove(); } } log.debug("Existing Documents[" + existingDocuments.size() + "]"); onDuplicatedDoc(session, session.getPrincipal(), doc2Check, existingDocuments, event); } } }
Source:
<code>private boolean shouldOwnMorePartitions(final int minPartitionsPerEventProcessor, final Map<String, List<PartitionOwnership>> ownerPartitionMap) { int numberOfPartitionsOwned = ownerPartitionMap.get(this.ownerId).size(); int leastPartitionsOwnedByAnyEventProcessor = ownerPartitionMap.values().stream().min(Comparator.comparingInt(List::size)).get().size(); <START> if (numberOfPartitionsOwned < minPartitionsPerEventProcessor <END> || numberOfPartitionsOwned == leastPartitionsOwnedByAnyEventProcessor) { return true; } return false; }</code><technical_language>nit: remove conditional return result of this expression</technical_language>

Target:
private boolean shouldOwnMorePartitions(final int minPartitionsPerEventProcessor, final Map<String, List<PartitionOwnership>> ownerPartitionMap) { int numberOfPartitionsOwned = ownerPartitionMap.get(this.ownerId).size(); int leastPartitionsOwnedByAnyEventProcessor = ownerPartitionMap.values().stream().min(Comparator.comparingInt(List::size)).get().size(); return numberOfPartitionsOwned < minPartitionsPerEventProcessor || numberOfPartitionsOwned == leastPartitionsOwnedByAnyEventProcessor; }
Source:
<code>public void setUp() { if (Display.getCurrent() != null) { <START> log.warn("SWTBot <END> tests must NOT run in the UI Thread"); } }</code><technical_language>I message more useful. is in Trace Compass: fail("SWTBot test needs run in a non-UI thread. \"Run in UI thread\" is unchecked in launch configuration or" + " useUIThread is set false in pom.xml");</technical_language>

Target:
public void setUp() { if (Display.getCurrent() != null) { log.warn("SWTBot test needs to run in a non-UI thread.\n" + "Make sure that \"Run in UI thread\" is unchecked in your launch configuration or that useUIThread is set to false in the pom.xml"); } }
Source:
<code>protected String[] customCommandLineValidation() { <START> List<String> errors = new ArrayList<String>(); <END> ValidationUtil.validateSanitizeSortOrder(SANITIZE, SORT_ORDER, errors); ValidationUtil.validateOutputParams(OUTPUT_BY_READGROUP, OUTPUT, OUTPUT_MAP, errors); if (!errors.isEmpty()) { return errors.toArray(new String[errors.size()]); } return null; }</code><technical_language>final</technical_language>

Target:
protected String[] customCommandLineValidation() { final List<String> errors = new ArrayList<String>(); ValidationUtil.validateSanitizeSortOrder(SANITIZE, SORT_ORDER, errors); ValidationUtil.validateOutputParams(OUTPUT_BY_READGROUP, OUTPUT, OUTPUT_MAP, errors); if (!errors.isEmpty()) { return errors.toArray(new String[errors.size()]); } return null; }
Source:
<code>public void testJoinsOfInExists() throws Exception { Client client = getClient(); loadData(false); String sql; for (String tb: replicated_tbs) { sql = "select T1.id from R1 T1, " + tb + " T2 " + "where T1.id = T2.id " + "and exists " + " (select 1 from R1 where R1.dept * 2 = T2.dept) " + <START> "order by t1.id;"; <END> validateTableOfLongs(client, sql, new long[][] {{4}, {5}}); sql = "select t1.id, t2.id from r1 t1, " + tb + " t2 " + "where t1.id IN " + " (select id from r2 where t2.id = r2.id * 2) " + "order by t1.id;"; validateTableOfLongs(client, sql, new long[][] {{1,2}, {2,4}}); if (!isHSQL()) { sql = "select id, newid " + "from (select id, wage from R1) T1 " + " LEFT OUTER JOIN " + " (select id as newid, dept from " + tb + " where dept > 1) T2 " + " ON T1.id = T2.dept " + " and exists " + " (select 1 from R1 where R1.ID = T2.newid) " + "order by id, newid;"; validateTableOfLongs(client, sql, new long[][] { {1, Long.MIN_VALUE}, {2, 4}, {2, 5}, {3, Long.MIN_VALUE}, {4, Long.MIN_VALUE}, {5, Long.MIN_VALUE}}); } } }</code><technical_language>I posit code stood (also) treated unambiguous id matches T1.id's (implicit) alias column in select list alias. This assumes simple conventions that: -- implicit tag/alias equal weight explicit tag/alias in select list -- select list takes precedence from-clause-based column list resolving (unqualified) tags/aliases in order clause Agreed</technical_language>

Target:
public void testJoinsOfInExists() throws Exception { Client client = getClient(); loadData(false); String sql; for (String tb: replicated_tbs) { sql = "select T1.id from R1 T1, " + tb + " T2 " + "where T1.id = T2.id " + "and exists " + " (select 1 from R1 where R1.dept * 2 = T2.dept) " + "order by id;"; validateTableOfLongs(client, sql, new long[][] {{4}, {5}}); sql = "select t1.id, t2.id from r1 t1, " + tb + " t2 " + "where t1.id IN " + " (select id from r2 where t2.id = r2.id * 2) " + "order by t1.id;"; validateTableOfLongs(client, sql, new long[][] {{1,2}, {2,4}}); if (!isHSQL()) { sql = "select id, newid " + "from (select id, wage from R1) T1 " + " LEFT OUTER JOIN " + " (select id as newid, dept from " + tb + " where dept > 1) T2 " + " ON T1.id = T2.dept " + " and exists " + " (select 1 from R1 where R1.ID = T2.newid) " + "order by id, newid;"; validateTableOfLongs(client, sql, new long[][] { {1, Long.MIN_VALUE}, {2, 4}, {2, 5}, {3, Long.MIN_VALUE}, {4, Long.MIN_VALUE}, {5, Long.MIN_VALUE}}); } } }
Source:
<code>public SpectatorRequestMetricCollector(Registry registry, Map<String, String> customTags) { this.registry = Preconditions.checkNotNull(registry, "registry"); this.customTags = Preconditions.checkNotNull(customTags, "customTags"); <START> } <END></code><technical_language>map need get copied ensure mutated passed in. option list additional risks of thread safety issues</technical_language>

Target:
public SpectatorRequestMetricCollector(Registry registry, Map<String, String> customTags) { super(); this.registry = Preconditions.checkNotNull(registry, "registry"); Preconditions.checkNotNull(customTags, "customTags"); this.customTags = new HashMap<>(); customTags.forEach((key, value) -> { if (ALL_DEFAULT_TAGS.contains(key)) { registry.propagate(new IllegalArgumentException("Invalid custom tag " + key + " - cannot override built-in tag")); } else { this.customTags.put(key, value); } }); }
Source:
<code>public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); <START> description.addProperty("name"); <END> description.addProperty("location"); description.addProperty("description"); return description; }</code><technical_language>name description properties added super class</technical_language>

Target:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); description.addProperty("location"); return description; }
Source:
<code>public void testSimple() { <START> assertSymbolEquals("a > b"); <END> assertSymbolEquals("a + b > c"); assertSymbolEquals("sin(a) - b"); assertSymbolEquals("sin(a) + cos(a) - b"); assertSymbolEquals("sin(a) + cos(a) + a - b"); assertSymbolEquals("COALESCE(a, b, 1)"); assertSymbolEquals("a IN (a, b, c)"); assertSymbolEquals("transform(sequence(1, 5), a -> a + b)"); assertSymbolEquals("bigint '1'"); }</code><technical_language>name is confusing, assert equals 2 parameter same. I assert symbols Expression RowExpression same, here. call this assertSymbols</technical_language>

Target:
public void testSimple() { assertSymbols("a > b"); assertSymbols("a + b > c"); assertSymbols("sin(a) - b"); assertSymbols("sin(a) + cos(a) - b"); assertSymbols("sin(a) + cos(a) + a - b"); assertSymbols("COALESCE(a, b, 1)"); assertSymbols("a IN (a, b, c)"); assertSymbols("transform(sequence(1, 5), a -> a + b)"); assertSymbols("bigint '1'"); }
Source:
<code>public void testDisconnectWhenConnectionBreak() throws Exception { _zkServerRef.get().shutdown(); AtomicBoolean disconnected = new AtomicBoolean(false); Thread testThread = new Thread("Testing HelixManager disconnect") { @Override public void run() { _controller.disconnect(); disconnected.set(true); } }; try { testThread.start(); <START> testThread.join(5000); <END> Assert.assertTrue(disconnected.get()); Assert.assertFalse(_controller.isConnected()); } finally { testThread.interrupt(); _zkServerRef.set(TestHelper.startZkServer(_zkAddr, null, false)); } }</code><technical_language>Instead of giving a hard-coded timeout value, do a CountDownLatch for this test depend timing</technical_language>

Target:
public void testDisconnectWhenConnectionBreak() throws Exception { String controllerName = CONTROLLER_PREFIX + "_" + TestHelper.getTestMethodName(); ClusterControllerManager controllerManager = new ClusterControllerManager(_zkAddr, CLUSTER_NAME, controllerName); controllerManager.syncStart(); TestHelper.stopZkServer(_zkServerRef.get()); AtomicBoolean disconnected = new AtomicBoolean(false); Thread testThread = new Thread("Testing HelixManager disconnect") { @Override public void run() { controllerManager.disconnect(); disconnected.set(true); } }; try { testThread.start(); testThread.join(10000); Assert.assertTrue(disconnected.get()); Assert.assertFalse(controllerManager.isConnected()); } finally { testThread.interrupt(); _zkServerRef.set(TestHelper.startZkServer(_zkAddr, null, false)); } }
Source:
<code>private void setupCivicAPIListeners(View rootView) { voterInfoListener = (result) -> { if (result == null) { Log.d("HomeFragment", "Null result"); homeGoButton.setVisibility(View.INVISIBLE); return; } VoterInfo voterInfo = (VoterInfo) result; homeTextViewStatus.setVisibility(View.GONE); homeGoButton.setVisibility(View.VISIBLE); mListener.searchedAddress(voterInfo); }; voterInfoErrorListener = (result) -> { if (result == null) { Log.e("HomeFragment", "Null error result"); homeTextViewStatus.setText(R.string.home_error_no_address); <START> homeGoButton.setVisibility(View.INVISIBLE); <END> return; } CivicApiError error = (CivicApiError) result; Log.d("HomeFragment", "Civic API returned error"); Log.d("HomeFragment", error.code + ": " + error.message); CivicApiError.Error error1 = error.errors.get(0); if (error1 != null) { Log.d("HomeFragment", error1.domain + " " + error1.reason + " " + error1.message); if (CivicApiError.errorMessages.get(error1.reason) != null) { homeTextViewStatus.setText(CivicApiError.errorMessages.get(error1.reason)); } else { Log.d("HomeFragment", "Unknown API error reason: " + error1.reason); homeTextViewStatus.setText(R.string.home_error_unknown); } } else { homeTextViewStatus.setText(R.string.home_error_unknown); } }; }</code><technical_language>homeGoButton set INVISIBLE if error. moved if</technical_language>

Target:
private void setupCivicAPIListeners(View rootView) { voterInfoListener = (result) -> { if (result == null) { return; } VoterInfo voterInfo = (VoterInfo) result; homeTextViewStatus.setVisibility(View.GONE); homeGoButton.setVisibility(View.VISIBLE); mListener.searchedAddress(voterInfo); }; voterInfoErrorListener = (result) -> { try { homeGoButton.setVisibility(View.INVISIBLE); CivicApiError error = (CivicApiError) result; Log.d("HomeFragment", "Civic API returned error"); Log.d("HomeFragment", error.code + ": " + error.message); CivicApiError.Error error1 = error.errors.get(0); Log.d("HomeFragment", error1.domain + " " + error1.reason + " " + error1.message); if (CivicApiError.errorMessages.get(error1.reason) != null) { homeTextViewStatus.setText(CivicApiError.errorMessages.get(error1.reason)); } else { Log.d("HomeFragment", "Unknown API error reason: " + error1.reason); homeTextViewStatus.setText(R.string.home_error_unknown); } } catch(NullPointerException e) { Log.e("HomeFragment", "Null encountered in API error result"); homeTextViewStatus.setText(R.string.home_error_unknown); } }; }