auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldAttemptMethodAndRetry_withExceptionThrownAndRetryEnabledAndDelayAdjusted() throws Throwable { final RetryableAspect retryableAspect = new RetryableAspect(); final ProceedingJoinPoint mockProceedingJoinPoint = setupSimpleProceedingJoinPointMock(); final int retryDelayInMillis = 3000; <START> final int maxRetries = randomIntInRange(2, 6); <END> final int expectedRuntime = retryDelayInMillis * (maxRetries - 1); final Retryable mockRetryable = setupMockRetryable(maxRetries, retryDelayInMillis); RetryableConfiguration.setRetryableEnabled(true); when(mockProceedingJoinPoint.proceed()).thenThrow(new RetryAspectTestException()); DateTime startDateTime = null; DateTime endDateTime = null; RetryAspectTestException actualException = null; try { startDateTime = DateTime.now(); retryableAspect.attemptMethodAndRetryIfNeeded(mockProceedingJoinPoint, mockRetryable); } catch (final RetryAspectTestException e) { endDateTime = DateTime.now(); actualException = e; } verify(mockProceedingJoinPoint, times(maxRetries)).proceed(); assertNotNull(actualException); assertTrue(startDateTime.plusMillis(expectedRuntime).getMillis() <= endDateTime.getMillis()); }</code><technical_language>above, this maxAttempts</technical_language>

Target:
public void shouldAttemptMethodAndRetry_withExceptionThrownAndRetryEnabledAndDelayAdjusted() throws Throwable { final RetryableAspect retryableAspect = new RetryableAspect(); final ProceedingJoinPoint mockProceedingJoinPoint = setupSimpleProceedingJoinPointMock(); final long EPSILON_MS = 300; final int retryDelayInMillis = 400; final int maxAttempts = randomIntInRange(2, 6); final int expectedRuntime = retryDelayInMillis * (maxAttempts - 1); final Retryable mockRetryable = setupMockRetryable(maxAttempts, retryDelayInMillis); RetryableConfiguration.setRetryableEnabled(true); when(mockProceedingJoinPoint.proceed()).thenThrow(new RetryAspectTestException()); DateTime startDateTime = null; RetryAspectTestException actualException = null; try { startDateTime = DateTime.now(); retryableAspect.attemptMethodAndRetryIfNeeded(mockProceedingJoinPoint, mockRetryable); } catch (final RetryAspectTestException e) { actualException = e; } verify(mockProceedingJoinPoint, times(maxAttempts)).proceed(); assertNotNull(actualException); final long elapsedMillis = DateTime.now().getMillis() - startDateTime.getMillis(); assertTrue(Math.abs(elapsedMillis - expectedRuntime) < EPSILON_MS); }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(Tree.Kind.CLASS)) { Symbol.TypeSymbol clazz = ((ClassTree) tree).symbol(); clazz.memberSymbols().stream() .filter(Symbol::isVariableSymbol) .filter(s -> s.type().is(THREAD_LOCAL)) .filter(ThreadLocalCleanupCheck::isNotSuper) .forEach(this::checkThreadLocalField); } else { MethodInvocationTree mit = (MethodInvocationTree) tree; if (THREADLOCAL_SET.matches(mit) && mit.arguments().get(0).is(Tree.Kind.NULL_LITERAL)) { reportIssue(mit, "Use \"remove()\" instead of \"set(null)\"."); } <START> } <END> }</code><technical_language>I why, in description, this work. If a common mistake, I add a small text explicit</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(Tree.Kind.CLASS)) { Symbol.TypeSymbol clazz = ((ClassTree) tree).symbol(); if (clazz.type().isSubtypeOf(THREAD_LOCAL)) { return; } clazz.memberSymbols().stream() .filter(Symbol::isVariableSymbol) .filter(s -> s.isPrivate() && s.type().is(THREAD_LOCAL)) .forEach(this::checkThreadLocalField); } else { MethodInvocationTree mit = (MethodInvocationTree) tree; if (THREADLOCAL_SET.matches(mit) && mit.arguments().get(0).is(Tree.Kind.NULL_LITERAL)) { reportIssue(mit, "Use \"remove()\" instead of \"set(null)\"."); } } }
Source:
<code>private NdefMessage decodeNfcBarcodeUri(NfcBarcode nfcBarcode) { final byte URI_PREFIX_HTTP_WWW = (byte) 0x01; final byte URI_PREFIX_HTTPS_WWW = (byte) 0x02; final byte URI_PREFIX_HTTP = (byte) 0x03; final byte URI_PREFIX_HTTPS = (byte) 0x04; NdefMessage message = null; byte[] tagId = nfcBarcode.getTag().getId(); <START> if (tagId[1] == URI_PREFIX_HTTP_WWW || tagId[1] == URI_PREFIX_HTTPS_WWW <END> || tagId[1] == URI_PREFIX_HTTP || tagId[1] == URI_PREFIX_HTTPS) { int end = 2; for (; end < tagId.length - 2; end++) { if (tagId[end] == (byte) 0xfe) { break; } } byte[] payload = new byte[end - 1]; System.arraycopy(tagId, 1, payload, 0, payload.length); NdefRecord uriRecord = new NdefRecord( NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, tagId, payload); message = new NdefMessage(uriRecord); } return message; }</code><technical_language>do a length check here, ensure tagId is of expected length (or > 4?)</technical_language>

Target:
private NdefMessage decodeNfcBarcodeUri(NfcBarcode nfcBarcode) { final byte URI_PREFIX_HTTP_WWW = (byte) 0x01; final byte URI_PREFIX_HTTPS_WWW = (byte) 0x02; final byte URI_PREFIX_HTTP = (byte) 0x03; final byte URI_PREFIX_HTTPS = (byte) 0x04; NdefMessage message = null; byte[] tagId = nfcBarcode.getTag().getId(); if (tagId.length >= 16 && tagId.length % 16 == 0 && (tagId[1] == URI_PREFIX_HTTP_WWW || tagId[1] == URI_PREFIX_HTTPS_WWW || tagId[1] == URI_PREFIX_HTTP || tagId[1] == URI_PREFIX_HTTPS)) { int end = 2; for (; end < tagId.length - 2; end++) { if (tagId[end] == (byte) 0xfe) { break; } } byte[] payload = new byte[end - 1]; System.arraycopy(tagId, 1, payload, 0, payload.length); NdefRecord uriRecord = new NdefRecord( NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, tagId, payload); message = new NdefMessage(uriRecord); } return message; }
Source:
<code>public static Insert addWriteOptions(Insert insert, WriteOptions writeOptions) { Assert.notNull(insert, "Insert must not be null"); addQueryOptions(insert, writeOptions); if (!writeOptions.getTtl().isNegative()) { insert.using(QueryBuilder.ttl(Math.toIntExact(writeOptions.getTtl().getSeconds()))); } <START> if (!(writeOptions.getTimestamp() < 0)) { <END> insert.using(QueryBuilder.timestamp(writeOptions.getTimestamp())); } return insert; }</code><technical_language>WriteOptions (and QueryOptions in general) nullable properties presence/absence of options</technical_language>

Target:
public static Insert addWriteOptions(Insert insert, WriteOptions writeOptions) { Assert.notNull(insert, "Insert must not be null"); addQueryOptions(insert, writeOptions); if (!writeOptions.getTtl().isNegative()) { insert.using(QueryBuilder.ttl(Math.toIntExact(writeOptions.getTtl().getSeconds()))); } if (writeOptions.getTimestamp() != null) { insert.using(QueryBuilder.timestamp(writeOptions.getTimestamp())); } return insert; }
Source:
<code>private Set<String> convertGroups(String groups) { if (groups == null) { return Collections.emptySet(); } String[] groupArray = groups.split(","); Set<String> groupsSet = new HashSet<>(groupArray.length); for (String current : groupArray) { String value = current.trim(); if (value.length() > 0) { groupsSet.add(value); } } <START> return Collections.unmodifiableSet(groupsSet); <END> }</code><technical_language>simplified to: java return Arrays.stream(groups.split(",")) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));</technical_language>

Target:
private Set<String> convertGroups(String groups) { if (groups == null) { return Collections.emptySet(); } return Arrays.stream(groups.split(",")) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); }
Source:
<code>private Date getDateFromDiskDescription(Map<String, Object> map) { try { <START> if (getLastUpdate(map) != null) { <END> return new SimpleDateFormat(OvfParser.formatStrFromDiskDescription).parse(getLastUpdate(map).toString()); } else { log.info("LastUpdate Date is not initialized in the OVF_STORE disk."); } } catch (java.text.ParseException e) { log.errorFormat("LastUpdate Date could not be parsed from disk desscription. Exception: {0}", e); } return null; }</code><technical_language>please export a variable eliminate method</technical_language>

Target:
private Date getDateFromDiskDescription(Map<String, Object> map) { try { Object lastUpdate = map.get(OvfInfoFileConstants.LastUpdated); if (lastUpdate != null) { return new SimpleDateFormat(OvfParser.formatStrFromDiskDescription).parse(lastUpdate.toString()); } else { log.info("LastUpdate Date is not initialized in the OVF_STORE disk."); } } catch (java.text.ParseException e) { log.errorFormat("LastUpdate Date could not be parsed from disk desscription. Exception: {0}", e); } return null; }
Source:
<code>public void renameAndAddField() { RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.schema.get("MigrationFieldRenameAndAdd") .renameField("string1", "string2") <START> .addField("string1", String.class); <END> } }; RealmConfiguration config = configFactory.createConfigurationBuilder() .schema(MigrationFieldRenameAndAdd.class) .schemaVersion(2) .migration(migration) .assetFile("rename-and-add.realm") .build(); Realm realm = Realm.getInstance(config); assertTrue(realm.getSchema().get("MigrationFieldRenameAndAdd").hasField("string1")); assertTrue(realm.getSchema().get("MigrationFieldRenameAndAdd").hasField("string2")); realm.close(); }</code><technical_language>more interesting if another type String. original string1 a String, if wrong this works anyway</technical_language>

Target:
public void renameAndAddField() { final Class<MigrationFieldRenameAndAdd> schemaClass = MigrationFieldRenameAndAdd.class; RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.getSchema().get(schemaClass.getSimpleName()) .renameField("string1", "string2") .addField("string1", String.class); } }; RealmConfiguration config = configFactory.createConfigurationBuilder() .schema(schemaClass) .schemaVersion(2) .migration(migration) .assetFile("rename-and-add.realm") .build(); Realm realm = Realm.getInstance(config); RealmObjectSchema schema = realm.getSchema().get(schemaClass.getSimpleName()); assertTrue(schema.hasField("string1")); assertTrue(schema.hasField("string2")); realm.close(); }
Source:
<code>Set<BeanDefinition> findCandidateBeanDefinitions(String className, Iterable<String> basePackages, Iterable<TypeFilter> excludeFilters) { Pattern pattern = Pattern.compile(".*\\." + className); ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.setEnvironment(environment); provider.setResourceLoader(resourceLoader); provider.setResourcePattern(String.format(CUSTOM_IMPLEMENTATION_RESOURCE_PATTERN, className)); provider.setMetadataReaderFactory(metadataReaderFactory); provider.addIncludeFilter(new RegexPatternTypeFilter(pattern)); for (TypeFilter excludeFilter : excludeFilters) { provider.addExcludeFilter(excludeFilter); } Set<BeanDefinition> definitions = new HashSet<BeanDefinition>(); for (String basePackage : basePackages) { definitions.addAll(provider.findCandidateComponents(basePackage)); } <START> return definitions; <END> }</code><technical_language>Blank line (see above)</technical_language>

Target:
Set<BeanDefinition> findCandidateBeanDefinitions(String className, Iterable<String> basePackages, Iterable<TypeFilter> excludeFilters) { Pattern pattern = Pattern.compile(".*\\." + className); ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.setEnvironment(environment); provider.setResourceLoader(resourceLoader); provider.setResourcePattern(String.format(CUSTOM_IMPLEMENTATION_RESOURCE_PATTERN, className)); provider.setMetadataReaderFactory(metadataReaderFactory); provider.addIncludeFilter(new RegexPatternTypeFilter(pattern)); for (TypeFilter excludeFilter : excludeFilters) { provider.addExcludeFilter(excludeFilter); } Set<BeanDefinition> definitions = new HashSet<>(); for (String basePackage : basePackages) { definitions.addAll(provider.findCandidateComponents(basePackage)); } return definitions; }
Source:
<code>public MotorInfoStdView(Composite parent, int style, MinimalMotorViewModel minimalMotorViewModel) { super(parent, style, minimalMotorViewModel); GridLayout glMotorComposite = new GridLayout(1, false); glMotorComposite.verticalSpacing = MOTOR_COMPOSITE_VERTIAL_SPACING; glMotorComposite.marginWidth = MOTOR_COMPOSITE_MARGIN_WIDTH; glMotorComposite.marginHeight = MOTOR_COMPOSITE_MARGIN_HEIGHT; setLayout(glMotorComposite); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); motorName = new Label(this, SWT.NONE); motorName.setAlignment(SWT.CENTER); GridData gdMotorName = new GridData(SWT.FILL, SWT.TOP, true, false); gdMotorName.minimumWidth = MOTOR_NAME_MINIMUM_WIDTH; gdMotorName.widthHint = MOTOR_NAME_WIDTHHINT; motorName.setLayoutData(gdMotorName); motorName.setText("Motor name"); value = new Label(this, SWT.NONE); value.setAlignment(SWT.CENTER); value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); value.setText(""); setpoint = new Label(this, SWT.NONE); setpoint.setAlignment(SWT.CENTER); setpoint.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); <START> setpoint.setText(""); <END> minimalMotionIndicator = new MinimalMotionIndicator(this, SWT.NONE); minimalMotionIndicator.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false)); minimalMotionIndicator.setMotor(this.getViewModel().getMotor()); setMouseListeners(); bind(); }</code><technical_language>tool tips describing fields please</technical_language>

Target:
public MotorInfoStdView(Composite parent, int style, MinimalMotorViewModel minimalMotorViewModel) { super(parent, style, minimalMotorViewModel); GridLayout glMotorComposite = new GridLayout(1, false); glMotorComposite.verticalSpacing = MOTOR_COMPOSITE_VERTIAL_SPACING; glMotorComposite.marginWidth = MOTOR_COMPOSITE_MARGIN_WIDTH; glMotorComposite.marginHeight = MOTOR_COMPOSITE_MARGIN_HEIGHT; setLayout(glMotorComposite); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); motorName = new Label(this, SWT.NONE); motorName.setAlignment(SWT.CENTER); GridData gdMotorName = new GridData(SWT.FILL, SWT.TOP, true, false); gdMotorName.minimumWidth = MOTOR_NAME_MINIMUM_WIDTH; gdMotorName.widthHint = MOTOR_NAME_WIDTHHINT; motorName.setLayoutData(gdMotorName); motorName.setText("Motor name"); value = new Label(this, SWT.NONE); value.setAlignment(SWT.CENTER); value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); value.setText(""); value.setToolTipText("The actual position of this motor"); setpoint = new Label(this, SWT.NONE); setpoint.setAlignment(SWT.CENTER); setpoint.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); setpoint.setText(""); setpoint.setToolTipText("The requested position of this motor"); minimalMotionIndicator = new MinimalMotionIndicator(this, SWT.NONE); minimalMotionIndicator.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false)); minimalMotionIndicator.setMotor(this.getViewModel().getMotor()); setMouseListeners(); bind(); }
Source:
<code>private String getTargetWithDialog() { AbstractBranchSelectionDialog dialog; switch (mode) { case MODE_CHECKOUT: dialog = new CheckoutDialog(getShell(), repository); break; case MODE_CREATE: <START> CreateBranchWizard wiz = new CreateBranchWizard(repository); <END> new WizardDialog(getShell(), wiz).open(); return null; case MODE_DELETE: new DeleteBranchDialog(getShell(), repository).open(); return null; case MODE_RENAME: new RenameBranchDialog(getShell(), repository).open(); return null; default: return null; } if (dialog.open() != Window.OK) { return null; } return dialog.getRefName(); }</code><technical_language>currently checked out branch preselected</technical_language>

Target:
private String getTargetWithDialog() { AbstractBranchSelectionDialog dialog; switch (mode) { case MODE_CHECKOUT: dialog = new CheckoutDialog(getShell(), repository); break; case MODE_CREATE: CreateBranchWizard wiz; try { wiz = new CreateBranchWizard(repository, repository.getFullBranch()); } catch (IOException e) { wiz = new CreateBranchWizard(repository); } new WizardDialog(getShell(), wiz).open(); return null; case MODE_DELETE: new DeleteBranchDialog(getShell(), repository).open(); return null; case MODE_RENAME: new RenameBranchDialog(getShell(), repository).open(); return null; default: return null; } if (dialog.open() != Window.OK) { return null; } return dialog.getRefName(); }
Source:
<code>private void setLayoutRestrictions(boolean allowScrollThumb, boolean allowAlphaJump, boolean bias) { ImageView upButton = mPagedListView.findViewById(androidx.car.test.R.id.page_up); ImageView downButton = mPagedListView.findViewById(androidx.car.test.R.id.page_down); Button alphaJump = mPagedListView.findViewById(androidx.car.test.R.id.alpha_jump); View scrollThumb = mPagedListView.findViewById(androidx.car.test.R.id.scrollbar_thumb); View scrollBarView = mPagedListView.findViewById(androidx.car.test.R.id.paged_scroll_view); ViewGroup.LayoutParams params = scrollBarView.getLayoutParams(); int seperateMargin = mPagedListView.getContext().getResources() .getDimensionPixelSize(androidx.car.R.dimen.car_padding_4); int restrictedHeight = mPagedListView.getPaddingTop() + upButton.getHeight() + downButton.getHeight() + mPagedListView.getPaddingBottom() + seperateMargin; if (allowScrollThumb) { restrictedHeight += scrollThumb.getHeight() + seperateMargin; } if (allowAlphaJump) { restrictedHeight += alphaJump.getHeight() + seperateMargin; } if (bias) { restrictedHeight += -1; } params.height = restrictedHeight; try { mActivityRule.runOnUiThread(() -> <START> { scrollBarView.requestLayout(); }); <END> } catch (Throwable throwable) { throwable.printStackTrace(); throw new RuntimeException(throwable); } }</code><technical_language>Remove brackets fits line: () -> scrollBarView.requestLayout()</technical_language>

Target:
private void setLayoutRestrictions(boolean allowScrollThumb, boolean allowAlphaJump, boolean bias) { ImageView upButton = mPagedListView.findViewById(R.id.page_up); ImageView downButton = mPagedListView.findViewById(R.id.page_down); Button alphaJump = mPagedListView.findViewById(R.id.alpha_jump); View scrollThumb = mPagedListView.findViewById(R.id.scrollbar_thumb); View scrollBarView = mPagedListView.findViewById(R.id.paged_scroll_view); ViewGroup.LayoutParams params = scrollBarView.getLayoutParams(); int seperateMargin = mPagedListView.getContext().getResources() .getDimensionPixelSize(androidx.car.R.dimen.car_padding_4); int restrictedHeight = mPagedListView.getPaddingTop() + upButton.getHeight() + downButton.getHeight() + mPagedListView.getPaddingBottom() + seperateMargin; if (allowScrollThumb) { restrictedHeight += scrollThumb.getHeight() + seperateMargin; } if (allowAlphaJump) { restrictedHeight += alphaJump.getHeight() + seperateMargin; } if (bias) { restrictedHeight += -1; } params.height = restrictedHeight; try { mActivityRule.runOnUiThread(() -> scrollBarView.requestLayout()); } catch (Throwable throwable) { throwable.printStackTrace(); throw new RuntimeException(throwable); } }
Source:
<code>public void incrementCommentCount() { ++this.commentCount; <START> ++this.unreadCommentCount; <END> setRead(false); }</code><technical_language>Again, get rid of this. I guess</technical_language>

Target:
public void incrementCommentCount() { ++commentCount; ++unreadCommentCount; read = false; }
Source:
<code>private static Config expand(Config config, int previousTokensCount) { Config.Builder cb = Config.newBuilder(); int tokensCount = 0; for (String key : config.getKeySet()) { Object value = config.get(key); if (value instanceof String) { String expandedValue = Misc.substitute(config, (String) value); if (expandedValue.contains("${")) { tokensCount++; } cb.put(key, expandedValue); } else { cb.put(key, value); } } <START> if (previousTokensCount != tokensCount) { <END> LOG.info(String.format( "Config expansion found %s values with tokens, will recurse", tokensCount)); return expand(config, tokensCount); } else { return cb.build(); } }</code><technical_language>tokens recursive expansion here...</technical_language>

Target:
private static Config expand(Config config, int previousTokensCount) { Config.Builder cb = Config.newBuilder().putAll(config); int tokensCount = 0; for (String key : config.getKeySet()) { Object value = config.get(key); if (value instanceof String) { String expandedValue = Misc.substitute(config, (String) value); if (expandedValue.contains("${")) { tokensCount++; } cb.put(key, expandedValue); } else { cb.put(key, value); } } if (previousTokensCount != tokensCount) { return expand(cb.build(), tokensCount); } else { return cb.build(); } }
Source:
<code>public boolean equals(Object obj) { if (obj instanceof GitModelCommit) { GitModelCommit objCommit = (GitModelCommit) obj; <START> return objCommit.getBaseCommit().equals(baseCommit) <END> && objCommit.getRemoteCommit().equals(remoteCommit) && objCommit.getLocation().equals(getLocation()); } return false; }</code><technical_language>NPE occur here. In GitModelCommit's constructors, is a code path 'baseCommit' field is set 'null'</technical_language>

Target:
public boolean equals(Object obj) { if (obj instanceof GitModelCommit) { GitModelCommit objCommit = (GitModelCommit) obj; RevCommit objBaseCommit = objCommit.getBaseCommit(); return objBaseCommit == null ? baseCommit == null : objBaseCommit .equals(baseCommit) && objCommit.getRemoteCommit().equals(remoteCommit) && objCommit.getLocation().equals(getLocation()); } return false; }
Source:
<code>public Date getDate() { <START> return getDate(); <END> }</code><technical_language>Stack overflow? :)</technical_language>

Target:
public Date getDate() { return getPickerDate(); }
Source:
<code>protected String[] customCommandLineValidation() { if (PROGRAM.isEmpty()) { return new String[]{"No programs specified with PROGRAM"}; } if ( (PROGRAM.contains(Program.CollectSequencingArtifactMetrics)) ) { List<String> errs = new ArrayList<String>(); if (DB_SNP == null) { errs.add("DB_SNP must be specified for CollectSequencingArtifactMetrics."); } if (INTERVALS == null) { errs.add("INTERVALS must be specified for CollectSequencingArtifactMetrics."); } if (!errs.isEmpty()) { return errs.toArray(new String[errs.size()]); } <START> } <END> programsToRun = new ArrayList<ProgramInterface>(PROGRAM); return super.customCommandLineValidation(); }</code><technical_language>caveat: _sometimes_ want pass in null values, validation (yeah, pretty sketchy...). for clear that</technical_language>

Target:
protected String[] customCommandLineValidation() { if (PROGRAM.isEmpty()) { return new String[]{"No programs specified with PROGRAM"}; } programsToRun = new ArrayList<ProgramInterface>(PROGRAM); return super.customCommandLineValidation(); }
Source:
<code>private boolean useCamera(Instrumentation instrumentation, String mode) throws Exception { final UiDevice device = UiDevice.getInstance(instrumentation); <START> AppLauncher.launchPath(instrumentation, new String[]{"Camera"}); new CameraAccessPermissionsWatcher(device).checkForCondition(); device.pressBack(); device.pressHome(); AppLauncher.launchPath(instrumentation, new String[]{"Camera"}); <END> UiObject cameraFrame = device.findObject(new UiSelector().resourceId(Res.CAMERA_FRAME_RES)); if (cameraFrame.waitForExists(3L)) { cameraFrame.click(); cameraFrame.swipeRight(3); } try { UiObject2 cameraModeButton = UiAutomatorPlus.findObjectByRelative( instrumentation, By.res("com.android.camera2:id/selector_icon"), By.text(mode), By.res("com.android.camera2:id/mode_list")); cameraModeButton.click(); } catch(UiObjectNotFoundException e) { Log.d(TAG, "Selected camera mode button not found"); } createTestFile(device); deleteTestFile(device); String originalFileList = listGalleryFiles(instrumentation); AppLauncher.launchPath(instrumentation, new String[]{"Camera"}); new CameraAccessPermissionsWatcher(device).checkForCondition(); createTestFile(device); String fileExt = mode.equals("Camera") ? ".jpg" : ".mp4"; String newFileList = listGalleryFiles(instrumentation); Assert.assertTrue("New file was not added to the gallery", !originalFileList.equals(newFileList) && newFileList.contains(fileExt)); deleteTestFile(device); String lastFileList = listGalleryFiles(instrumentation); return originalFileList.equals(lastFileList); }</code><technical_language>need re-launch Camera app</technical_language>

Target:
private boolean useCamera(Instrumentation instrumentation, String mode) throws Exception { final UiDevice device = UiDevice.getInstance(instrumentation); AppLauncher.launchPath(instrumentation, new String[]{"Camera"}); new CameraAccessPermissionsWatcher(device).checkForCondition(); device.pressBack(); device.pressHome(); AppLauncher.launchPath(instrumentation, new String[]{"Camera"}); UiObject cameraFrame = device.findObject(new UiSelector().resourceId(Res.CAMERA_FRAME_RES)); if (cameraFrame.waitForExists(3L)) { cameraFrame.click(); cameraFrame.swipeRight(3); } try { UiObject2 cameraModeButton = UiAutomatorPlus.findObjectByRelative( instrumentation, By.res("com.android.camera2:id/selector_icon"), By.text(mode), By.res("com.android.camera2:id/mode_list")); cameraModeButton.click(); } catch(UiObjectNotFoundException e) { Assert.assertTrue("Button to select " + mode + " mode not found", false); } createTestFile(device); deleteTestFile(device); String originalFileList = listGalleryFiles(instrumentation); AppLauncher.launchPath(instrumentation, new String[]{"Camera"}); new CameraAccessPermissionsWatcher(device).checkForCondition(); createTestFile(device); String fileExt = mode.equals("Camera") ? ".jpg" : ".mp4"; String newFileList = listGalleryFiles(instrumentation); Assert.assertTrue("New file was not added to the gallery", !originalFileList.equals(newFileList) && newFileList.contains(fileExt)); deleteTestFile(device); String lastFileList = listGalleryFiles(instrumentation); return originalFileList.equals(lastFileList); }
Source:
<code>private int binarySearch(Tuple[] arr, Tuple key, int startPos, int endPos) { int offset = -1; int start = startPos; int end = endPos; int prevCenter = -1; int centerPos = (start + end) >>> 1; if (arr.length == 0) { LOG.error("arr.length: 0, loadNum: " + loadNum + ", inited: " + inited.get()); return -1; } correctable = false; if (arr.length == 1) { int comp = comparator.compare(arr[0], key); if (comp < 0) { return 0; } else if (comp > 0) { return -1; } correctable = true; return 0; } while (true) { if (end - start == 1) { int comp; if (end == prevCenter) { comp = comparator.compare(arr[start], key); if (comp == 0) { correctable = true; offset = start; } else if (comp < 0) { offset = start; } break; } else { if (end == arr.length) { if (comparator.compare(arr[start], key) == 0) { correctable = true; } offset = start; break; } comp = comparator.compare(arr[end], key); if (comp == 0) { correctable = true; offset = end; } else if (comp > 0) { offset = start; } break; } } int compareResult = comparator.compare(arr[centerPos], key); if (compareResult == 0) { correctable = true; offset = centerPos; break; } else { prevCenter = centerPos; if (compareResult > 0) { end = centerPos; } else { start = centerPos; } <START> centerPos = (start + end) / 2; <END> } } return offset; }</code><technical_language>This line changed centerPos = (start + end) >>> 1;</technical_language>

Target:
private int binarySearch(Tuple[] arr, Tuple key, int startPos, int endPos) { int offset = -1; int start = startPos; int end = endPos; int prevCenter = -1; int centerPos = (start + end) >>> 1; if (arr.length == 0) { LOG.error("arr.length: 0, loadNum: " + loadNum + ", inited: " + inited.get()); return -1; } correctable = false; if (arr.length == 1) { int comp = comparator.compare(arr[0], key); if (comp < 0) { return 0; } else if (comp > 0) { return -1; } correctable = true; return 0; } while (true) { if (end - start == 1) { int comp; if (end == prevCenter) { comp = comparator.compare(arr[start], key); if (comp == 0) { correctable = true; offset = start; } else if (comp < 0) { offset = start; } break; } else { if (end == arr.length) { if (comparator.compare(arr[start], key) == 0) { correctable = true; } offset = start; break; } comp = comparator.compare(arr[end], key); if (comp == 0) { correctable = true; offset = end; } else if (comp > 0) { offset = start; } break; } } int compareResult = comparator.compare(arr[centerPos], key); if (compareResult == 0) { correctable = true; offset = centerPos; break; } else { prevCenter = centerPos; if (compareResult > 0) { end = centerPos; } else { start = centerPos; } centerPos = (start + end) >>> 1; } } return offset; }
Source:
<code>private static long getSize(final String propertyKey, final long defaultValue) { final String propertyValue = getProperty(propertyKey); if (propertyValue != null) { <START> return parseSize(propertyKey, propertyValue); <END> } else { return defaultValue; } }</code><technical_language>parseSize method supports int. do a long method a range check for if int is allowed</technical_language>

Target:
private static long getSize(final String propertyKey, final long defaultValue) { final String propertyValue = getProperty(propertyKey); if (propertyValue != null) { final long size = parseSize(propertyKey, propertyValue); if (0 <= size && size <= Integer.MAX_VALUE) { return size; } else { throw new ConfigurationException("Value " + size + " for property " + propertyKey + " is too large, must be " + 0 + " <= " + propertyKey + " <= " + Long.MAX_VALUE); } } else { return defaultValue; } }
Source:
<code>public String toString() { <START> return String.format("spUUID = %s, poolVersion = %s", <END> getStoragePoolId().toString(), getCompatibilityVersion()); }</code><technical_language>put "storagePoolId" instead of "spUUID"</technical_language>

Target:
public String toString() { return String.format("storagePoolId = %s, poolVersion = %s", getStoragePoolId().toString(), getCompatibilityVersion()); }
Source:
<code><START> private String getMessagesFromMap(final Map<String, String> keyValues) { <END> boolean first = true; StringBuilder builder = new StringBuilder(); builder.append('{'); for (Map.Entry<String, String> entry : keyValues.entrySet()) { if (!first) { builder.append(','); } first = false; builder.append('\''); builder.append(entry.getKey()); builder.append("':'"); builder.append(entry.getValue()); builder.append('\''); } builder.append('}'); return builder.toString(); }</code><technical_language>I Jackson (JSON) library here, instead of constructing JSON hand. E.g. similar GwtDynamicHostPageServlet.getUserInfoObject() method, calling toString() resulting ObjectNode</technical_language>

Target:
private String getMessagesFromMap(final Map<String, String> keyValues) { ObjectNode node = new ObjectMapper().createObjectNode(); for (Map.Entry<String, String> entry : keyValues.entrySet()) { node.put(entry.getKey(), entry.getValue()); } return node.toString(); }
Source:
<code>public synchronized String getActivePackageId(String name) throws PackageException { for (Entry<String, PackageState> entry : states.entrySet()) { if (entry.getKey().startsWith(name) && entry.getValue().isInstalled() && getPackage(entry.getKey()).getName().equals(name)) { <START> return entry.getKey(); <END> } } return null; }</code><technical_language>Please put entry.getKey() in a local variable</technical_language>

Target:
public synchronized String getActivePackageId(String name) throws PackageException { for (Entry<String, PackageState> entry : states.entrySet()) { String pkgId = entry.getKey(); if (pkgId.startsWith(name) && entry.getValue().isInstalled() && getPackage(pkgId).getName().equals(name)) { return pkgId; } } return null; }
Source:
<code>public Boolean getEmailVerified() { if (emailVerified == null && email != null && phone == null && status == AccountStatus.ENABLED) { return Boolean.TRUE; <START> } <END> return emailVerified; }</code><technical_language>If moving this logic DAO HibernateAccount, move tests DAO HibernateAccount. Similarly for getSharingScope() getNotifyByEmail()</technical_language>

Target:
public Boolean getEmailVerified() { return emailVerified; }
Source:
<code>public void disposeVMInstall(String id) { IVMInstall vm = null; synchronized (this) { for (int i= 0; i < fVMs.size(); i++) { vm = fVMs.get(i); if (vm.getId().equals(id)) { fVMs.remove(i); break; } } } if <START> (vm != <END> null) { JavaRuntime.fireVMRemoved(vm); } }</code><technical_language>If fVms size > 0 condition vm.getId().equals(id) satisfy for vm, vm null fireVMRemoved invoked</technical_language>

Target:
public void disposeVMInstall(String id) { IVMInstall removedVM = null; synchronized (this) { for (int i= 0; i < fVMs.size(); i++) { if (fVMs.get(i).getId().equals(id)) { removedVM = fVMs.remove(i); break; } } } if (removedVM != null) { JavaRuntime.fireVMRemoved(removedVM); } }
Source:
<code><START> public void trianglesWithNoSizeAreIllegal() throws Exception { <END> thrown.expect(TriangleException.class); new Triangle(0, 0, 0); }</code><technical_language>I add this, great if change throws Exception throws TriangleException specific :)</technical_language>

Target:
public void trianglesWithNoSizeAreIllegal() throws TriangleException { thrown.expect(TriangleException.class); new Triangle(0, 0, 0); }
Source:
<code><T> T getConnection(ConfigurationInstance config) throws ConnectionException { <START> lock.lock(); <END> try { ConnectionHandler<Object> connectionHandler = connectionManager.getConnection(config.getValue()); Object connection = connectionHandler.getConnection(); Reference<Object> connReference = new Reference<>(connection); int count = getConnectionRefCount(connReference) + 1; connections.put(connReference, new Pair(count, connectionHandler)); return (T) connection; } finally { lock.unlock(); } }</code><technical_language>AtomicInteger need for this lock unnecessary. for future reference, notice critical resource is map. if synchronize, synchronoize part. doesnt sense syncrhonize connect part</technical_language>

Target:
<T> T getConnection(ConfigurationInstance config) throws ConnectionException { ConnectionHandler<Object> connectionHandler = connectionManager.getConnection(config.getValue()); Object connection = connectionHandler.getConnection(); Reference<Object> connReference = new Reference<>(connection); withLock(lock, () -> { ((AtomicInteger) connections.get(connReference, k -> new Pair(new AtomicInteger(0), connectionHandler)) .getFirst()).incrementAndGet(); }); return (T) connection; }
Source:
<code>public void testHappyPath() { DataSize maxResponseSize = new DataSize(10, MEGABYTE); MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize); URI location = URI.create("http://localhost:8080"); processor.addPage(location, createPage(1)); processor.addPage(location, createPage(2)); processor.addPage(location, createPage(3)); processor.setComplete(location); @SuppressWarnings("resource") ExchangeClient exchangeClient = new ExchangeClient( new DataSize(32, MEGABYTE), maxResponseSize, 1, new Duration(1, MINUTES), true, 0.2, new TestingHttpClient(processor, scheduler), <START> (context, header) -> null, <END> scheduler, new SimpleLocalMemoryContext(newSimpleAggregatedMemoryContext(), "test"), pageBufferClientCallbackExecutor); exchangeClient.addLocation(location, TaskId.valueOf("queryid.0.0.0")); exchangeClient.noMoreLocations(); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(1)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(2)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(3)); assertNull(getNextPage(exchangeClient)); assertEquals(exchangeClient.isClosed(), true); ExchangeClientStatus status = exchangeClient.getStatus(); assertEquals(status.getBufferedPages(), 0); assertEquals(status.getBufferedBytes(), 0); assertStatus(status.getPageBufferClientStatuses().get(0), location, "closed", 3, 3, 3, "not scheduled"); }</code><technical_language>a TestingDriftExchangeClient throws ? -- this pattern in other place create for test</technical_language>

Target:
public void testHappyPath() { DataSize maxResponseSize = new DataSize(10, MEGABYTE); MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize); URI location = URI.create("http://localhost:8080"); processor.addPage(location, createPage(1)); processor.addPage(location, createPage(2)); processor.addPage(location, createPage(3)); processor.setComplete(location); @SuppressWarnings("resource") ExchangeClient exchangeClient = new ExchangeClient( new DataSize(32, MEGABYTE), maxResponseSize, 1, new Duration(1, MINUTES), true, 0.2, new TestingHttpClient(processor, scheduler), new TestingDriftClient<>(), scheduler, new SimpleLocalMemoryContext(newSimpleAggregatedMemoryContext(), "test"), pageBufferClientCallbackExecutor); exchangeClient.addLocation(location, TaskId.valueOf("queryid.0.0.0")); exchangeClient.noMoreLocations(); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(1)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(2)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(3)); assertNull(getNextPage(exchangeClient)); assertEquals(exchangeClient.isClosed(), true); ExchangeClientStatus status = exchangeClient.getStatus(); assertEquals(status.getBufferedPages(), 0); assertEquals(status.getBufferedBytes(), 0); assertStatus(status.getPageBufferClientStatuses().get(0), location, "closed", 3, 3, 3, "not scheduled"); }
Source:
<code>public Object getValue(final Object element, final String property) { if (IV_NAME.equals(property)) { return ((VarDeclaration) element).getName(); } else if (IV_TYPE.equals(property)) { int i = 0; <START> for(String item : typeDropDown.getItems()){ if(item.equals(((VarDeclaration) element).getType().getName())){ return i; } i++; } <END> return 0; } else if (IV_COMMENT.equals(property)) { return ((VarDeclaration) element).getComment(); } else if (IV_ARRAY.equals(property)) { return Integer.toString(((VarDeclaration) element).getArraySize()); } else{ return ((VarDeclaration) element).getValue().getValue(); } }</code><technical_language>this replaced a regular for loop, benefit scope of int i limited loop</technical_language>

Target:
public Object getValue(final Object element, final String property) { VarDeclaration var = (VarDeclaration) element; switch(property) { case IV_NAME: return var.getName(); case IV_TYPE: for(int i = 0; i < typeDropDown.getItems().length; i++) { if(typeDropDown.getItems()[i].equals(var.getType().getName())){ return i; } } return 0; case IV_COMMENT: return var.getComment(); case IV_ARRAY: return Integer.toString(var.getArraySize()); default: return var.getValue().getValue(); } }
Source:
<code>public void clientSupplierInvokedOnStreamsBuilderFactoryBean() { <START> Assert.assertTrue("StreamsBuilderFactoryBean#setClientSupplier(KafkaClientSupplier) not called", <END> bean.isClientSupplierInvoked()); }</code><technical_language>Please AssertJ, preferably BDDAssertions</technical_language>

Target:
public void clientSupplierInvokedOnStreamsBuilderFactoryBean() { then(streamsBuilderFactoryBean.clientSupplierInvoked).isTrue(); }
Source:
<code>private VisitableSampledSpectrum signal(final double throughput) { final VisitableSampledSpectrum signal = (VisitableSampledSpectrum) sourceFlux.clone(); final int lastPixel = lastCcdPixel(signal.getLength()); Log.fine("Calculating signal with " + throughput + " throughput on detector pixels " + firstCcdPixel + " - " + lastPixel); <START> for (int i = 0; i < firstCcdPixel; ++i) { signal.setY(i, 0); } <END> for (int i = firstCcdPixel; i <= lastPixel; ++i) { signal.setY(i, totalFlux(sourceFlux.getY(i), throughput)); } for (int i = lastPixel+1; i < signal.getLength(); ++i) { signal.setY(i, 0); } return signal; }</code><technical_language>for loops reseting signal array combined. explicitly set array zero set valid values loop</technical_language>

Target:
private VisitableSampledSpectrum signal(final double throughput) { final VisitableSampledSpectrum signal = (VisitableSampledSpectrum) sourceFlux.clone(); final int lastPixel = lastCcdPixel(signal.getLength()); Log.fine("Calculating signal with " + throughput + " throughput on detector pixels " + firstCcdPixel + " - " + lastPixel); for (int i = 0; i < signal.getLength(); ++i) { signal.setY(i, 0); } for (int i = firstCcdPixel; i <= lastPixel; ++i) { signal.setY(i, totalFlux(sourceFlux.getY(i), throughput)); } return signal; }
Source:
<code><START> public void shouldNotRaiseAlertIfRequestParamValuesNotUsedInJsEvent() throws URIException, NullPointerException { <END> HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.setResponseBody("<html><img src=\"x.jpg\" onerror=alert(\"Error\")></img></html>"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(0)); }</code><technical_language>throw Exception instead (same for other tests in other classes)</technical_language>

Target:
public void shouldNotRaiseAlertIfRequestParamValuesNotUsedInJsEvent() throws Exception { HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.setResponseBody("<html><img src=\"x.jpg\" onerror=alert(\"Error\")></img></html>"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(0)); }
Source:
<code>public double getPopulationMean() { if (populationCount == 0) { return Double.NaN; } <START> return populationSum.divide(new BigDecimal(populationCount), 8, RoundingMode.HALF_UP).doubleValue(); <END> }</code><technical_language>a fixed scale 8 this mess values small numbers require unnecessary scale for large numbers. Suggested alternative: sum.scale() + count.precision() scale is current number of digits for sum, count.precision is a proxy for log10 of count. This way, add digits count realistically justify. Example: sum = 0.0000001 (precision 1, scale 8) count = 1000 (precision 3, scale 0) sum / count -> 0.0000000001 (precision 1, scale 11) Otherwise, a fixed scale, this 0. Alternatively, sum.scale() + 1. scale of population sum minimum scale of values occurred: of rule for a+b, scale = max(a.scale, b.scale). digits actual values had, one, instead of adding digits of division. Adding digit means of integers a single digit</technical_language>

Target:
public double getPopulationMean() { if (populationCount == 0) { return Double.NaN; } BigDecimal popCount = BigDecimal.valueOf(populationCount); return populationSum.divide(popCount, populationSum.scale() + popCount.precision(), RoundingMode.HALF_UP).doubleValue(); }
Source:
<code>public void testSameFieldMultipleConverts() throws Exception { ProjectionTransform.ProjectionTransformConfig config = new ProjectionTransform .ProjectionTransformConfig(null, null, "x:int,x:long", null); Transform<StructuredRecord, StructuredRecord> transform = new ProjectionTransform(config); TransformContext transformContext = new MockTransformContext(); String caughtException = ""; try { transform.initialize(transformContext); <START> } catch (Exception e) { <END> caughtException = e.getMessage(); } Assert.assertEquals(validationExceptionMessage, caughtException); FailureCollector collector = transformContext.getFailureCollector(); Assert.assertEquals(1, collector.getValidationFailures().size()); Assert.assertEquals(1, collector.getValidationFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, convert); expectedCause.addAttribute(stage, mockStage); Assert.assertEquals(expectedCause, collector.getValidationFailures().get(0).getCauses().get(0)); }</code><technical_language>this catch ValidationException get ValidationFailures exception</technical_language>

Target:
public void testSameFieldMultipleConverts() throws Exception { ProjectionTransform.ProjectionTransformConfig config = new ProjectionTransform .ProjectionTransformConfig(null, null, "x:int,x:long", null); Transform<StructuredRecord, StructuredRecord> transform = new ProjectionTransform(config); TransformContext transformContext = new MockTransformContext(); try { transform.initialize(transformContext); Assert.fail(); } catch (ValidationException e) { Assert.assertEquals(1, e.getFailures().size()); Assert.assertEquals(1, e.getFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, ProjectionTransform.ProjectionTransformConfig.CONVERT); expectedCause.addAttribute(STAGE, MOCK_STAGE); Assert.assertEquals(expectedCause, e.getFailures().get(0).getCauses().get(0)); } }
Source:
<code>private static ConcurStandardAccountingExtractDetailLine buildConcurStandardAccountingExtractDetailLine(String debitCredit, KualiDecimal amount) { ConcurStandardAccountingExtractDetailLine line = new ConcurStandardAccountingExtractDetailLine(); line.setJounalDebitCredit(debitCredit); line.setJournalAmount(amount); <START> line.setEmployeeGroupId("CORNELL"); <END> return line; }</code><technical_language>this parameter lookup for CONCUR_CUSTOMER_PROFILE_GROUP_ID</technical_language>

Target:
private static ConcurStandardAccountingExtractDetailLine buildConcurStandardAccountingExtractDetailLine(String debitCredit, KualiDecimal amount) { ConcurStandardAccountingExtractDetailLine line = new ConcurStandardAccountingExtractDetailLine(); line.setJounalDebitCredit(debitCredit); line.setJournalAmount(amount); line.setEmployeeGroupId(EMPLOYEE_GROUP_ID); return line; }
Source:
<code><START> public void testNoRecursiveNesting() { <END> System.out.println("No Recursive Nesting"); FieldProcessor<TestClassM> instance = new FieldProcessor(TestClassM.class); TestClassE nested = new TestClassE("10"); TestClassM testClass = new TestClassM("20", nested); instance.processLinks(testClass, mockUriInfo, mockRmc); assertEquals("widgets/20", testClass.thelink); assertEquals(null, testClass.nested.link); }</code><technical_language>Gerard, I well, please explain a bit</technical_language>

Target:
public void testNoRecursiveNesting() { LOG.info("No Recursive Nesting"); FieldProcessor<TestClassM> instance = new FieldProcessor(TestClassM.class); TestClassE nested = new TestClassE("10"); TestClassE transientNested = new TestClassE("30"); TestClassM testClass = new TestClassM("20", nested, transientNested); instance.processLinks(testClass, mockUriInfo, mockRmc); assertEquals("widgets/20", testClass.thelink); assertEquals(null, testClass.nested.link); assertEquals(null, testClass.transientNested.link); }