auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SAMLocusAndReference next() { final LocusInfo locus = locusIterator.next(); final ReferenceSequence referenceSequence = referenceSequenceFileWalker.get(locus.getSequenceIndex(), locus.getSequenceName(), locus.getSequenceLength()); final int position = locus.getPosition(); <START> final byte referenceBase = 0 == position ? (byte)'N' : referenceSequence.getBases()[locus.getPosition() - 1]; <END> return new SAMLocusAndReference(locus, referenceBase); }</code><technical_language>mind a) adding a final byte N = (byte) 'N' referencing here. please wrap 0 == position in parentheses? I ternary easier read</technical_language>

Target:
public SAMLocusAndReference next() { final LocusInfo locus = locusIterator.next(); final ReferenceSequence referenceSequence = referenceSequenceFileWalker.get(locus.getSequenceIndex(), locus.getSequenceName(), locus.getSequenceLength()); if (locus.getPosition() == 0) { return new SAMLocusAndReference(locus, BASE_BEFORE_REFERENCE_START); } else { return new SAMLocusAndReference(locus, referenceSequence.getBases()[locus.getPosition() - 1]); } }
Source:
<code>private Observer<List<Location>> getLocationList() { return new Observer<List<Location>>() { @Override public void onCompleted() { showLocationDialog(locationList); } @Override public void onError(Throwable e) { <START> e.printStackTrace(); <END> } @Override public void onNext(List<Location> locations) { for (Location locationItem : locations) { locationList.add(locationItem.getName()); } } }; }</code><technical_language>a this? <LINK_0></technical_language>

Target:
private Observer<List<Location>> getLocationList() { return new Observer<List<Location>>() { @Override public void onCompleted() { showLocationDialog(locationList); } @Override public void onError(Throwable e) { mOpenMRSLogger.e(e.getMessage()); } @Override public void onNext(List<Location> locations) { for (Location locationItem : locations) { locationList.add(locationItem.getName()); } } }; }
Source:
<code>private List<VmTemplate> getTemplatesForUpdate(List<Guid> templatesIds) { if (templatesIds.isEmpty()) { return Collections.emptyList(); } List<Guid> idsToProcess = getIdsToProcess(templatesIds); List<VmTemplate> toReturn = new ArrayList<VmTemplate>(); List<VmTemplate> templates = getVmTemplateDao().getVmTemplatesByIds(idsToProcess); for (VmTemplate template : templates) { if (VmTemplateStatus.Locked != template.getstatus()) { VmTemplateHandler.UpdateDisksFromDb(template); long currentDbGeneration = getVmAndTemplatesGenerationsDAO().getDbGeneration(template.getId()); <START> if (template.getDb_generation() == currentDbGeneration) { <END> boolean verifyDisksNotLocked = verifyDisksNotLocked(template.getDiskList()); if (verifyDisksNotLocked) { toReturn.add(template); } } } } return toReturn; }</code><technical_language>try check if some disk is locked run a DB query</technical_language>

Target:
private List<VmTemplate> getTemplatesForUpdate(List<Guid> templatesIds) { if (templatesIds.isEmpty()) { return Collections.emptyList(); } List<Guid> idsToProcess = getIdsToProcess(templatesIds); List<VmTemplate> toReturn = new LinkedList<VmTemplate>(); List<VmTemplate> templates = getVmTemplateDao().getVmTemplatesByIds(idsToProcess); for (VmTemplate template : templates) { if (VmTemplateStatus.Locked != template.getstatus()) { VmTemplateHandler.UpdateDisksFromDb(template); boolean verifyDisksNotLocked = verifyDisksNotLocked(template.getDiskList()); if (verifyDisksNotLocked) { Long currentDbGeneration = getVmAndTemplatesGenerationsDAO().getDbGeneration(template.getId()); if (template.getDb_generation() == currentDbGeneration) { toReturn.add(template); } } } } return toReturn; }
Source:
<code>public void testGetRangeOfTimestampsOmitsTimestampsLessThanMax() { keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t0), TEST_TIMESTAMP); keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t1), TEST_TIMESTAMP + 10); <START> RangeRequest range = RangeRequest.all().withBatchHint(1); <END> List<RowResult<Set<Long>>> results = ImmutableList.copyOf( keyValueService.getRangeOfTimestamps(TEST_TABLE, range, TEST_TIMESTAMP + 1)); assertEquals(1, results.size()); assertArrayEquals(row0, results.get(0).getRowName()); assertEquals(TEST_TIMESTAMP, (long)results.get(0).getOnlyColumnValue().iterator().next()); }</code><technical_language>a batch hint of 2 here, guard weird failure case returned value, earlier in list</technical_language>

Target:
public void testGetRangeOfTimestampsOmitsTimestampsLessThanMax() { keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t0), TEST_TIMESTAMP); keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t1), TEST_TIMESTAMP + 10); RangeRequest range = RangeRequest.all().withBatchHint(2); List<RowResult<Set<Long>>> results = ImmutableList.copyOf( keyValueService.getRangeOfTimestamps(TEST_TABLE, range, TEST_TIMESTAMP + 1)); assertEquals(1, results.size()); assertArrayEquals(row0, results.get(0).getRowName()); assertEquals(TEST_TIMESTAMP, (long) results.get(0).getOnlyColumnValue().iterator().next()); }
Source:
<code>protected AbstractMergeViewer createMergeViewer(final Composite parent, final MergeViewerSide side) { final TreeMergeViewer mergeTreeViewer = new TreeMergeViewer(parent, side, this, getCompareConfiguration()); final IContentProvider contentProvider = createMergeViewerContentProvider(); mergeTreeViewer.setContentProvider(contentProvider); <START> final IBaseLabelProvider labelProvider = new PapyrusTreeContentMergeViewerItemLabelProvider( <END> getResourceBundle(), getAdapterFactory(), side); mergeTreeViewer.setLabelProvider(labelProvider); hookListeners(mergeTreeViewer); return mergeTreeViewer; }</code><technical_language>if want enable customizing LabelProvider this PS</technical_language>

Target:
protected AbstractMergeViewer createMergeViewer(final Composite parent, final MergeViewerSide side) { final TreeMergeViewer mergeTreeViewer = new TreeMergeViewer(parent, side, this, getCompareConfiguration()); final IContentProvider contentProvider = createMergeViewerContentProvider(side); mergeTreeViewer.setContentProvider(contentProvider); final IBaseLabelProvider labelProvider = new PapyrusTreeContentMergeViewerItemLabelProvider( getResourceBundle(), getAdapterFactory(), side); mergeTreeViewer.setLabelProvider(labelProvider); hookListeners(mergeTreeViewer); return mergeTreeViewer; }
Source:
<code>protected boolean canDoAction() { Guid vdsId = getVm().getDedicatedVmForVds(); if (vdsId == null) { <START> return failCanDoAction(VdcBllMessages.VM_NUMA_PINNED_VDS_NOT_EXIST); <END> } List<VdsNumaNode> vdsNumaNodes = getDbFacade().getVdsNumaNodeDAO().getAllVdsNumaNodeByVdsId(vdsId); List<VmNumaNode> vmNumaNodes = getParameters().getVmNumaNodeList(); for (VmNumaNode vmNumaNode : vmNumaNodes) { for (Pair<Guid, Pair<Boolean, Integer>> pair : vmNumaNode.getVdsNumaNodeList()) { int index = pair.getSecond().getSecond(); for (VdsNumaNode vdsNumaNode : vdsNumaNodes) { if (vdsNumaNode.getIndex() == index) { if (vmNumaNode.getMemTotal() > vdsNumaNode.getMemTotal()) { return failCanDoAction(VdcBllMessages.VM_NUMA_NODE_MEMRORY_ERROR); } break; } } } } return true; }</code><technical_language>configurable</technical_language>

Target:
protected boolean canDoAction() { return checkNumaValid(); }
Source:
<code><START> public void runOnContentField(Consumer<WebElement> action) <END> { List<WebElement> textareas = getContainer() .findElements(By.tagName("textarea")) .stream() .filter(it -> !it.getAttribute("class").contains("ckeditor-textarea")) .collect(Collectors.toList()); if (textareas.size() == 0 || !textareas.get(0).isDisplayed()) { WebElement iframe = getContainer().findElement(By.tagName("iframe")); getDriver().switchTo().frame(iframe); action.accept(getDriver().findElement(By.tagName("body"))); getDriver().switchTo().parentFrame(); } else { action.accept(textareas.get(0)); } }</code><technical_language>a business API for a PO IMO: a more explicit API setContent more aligned users want perform action field</technical_language>

Target:
private void runOnContentField(Consumer<WebElement> action) { List<WebElement> textareas = getContainer() .findElements(By.tagName("textarea")) .stream() .filter(it -> !it.getAttribute("class").contains("ckeditor-textarea")) .collect(Collectors.toList()); if (textareas.size() == 0 || !textareas.get(0).isDisplayed()) { WebElement iframe = getContainer().findElement(By.tagName("iframe")); getDriver().switchTo().frame(iframe); action.accept(getDriver().findElement(By.tagName("body"))); getDriver().switchTo().parentFrame(); } else { action.accept(textareas.get(0)); } }
Source:
<code>public synchronized T get() { if (container==null) { Class<T> fixture = (Class<T>) type.getRawType(); <START> File buildlog = diag.touch("docker-" + fixture.getSimpleName() + ".build.log"); <END> File runlog = diag.touch("docker-" + fixture.getSimpleName() + ".run.log"); try { System.out.println("Setting up docker container for " + fixture.getSimpleName()); container = docker.build(fixture, buildlog).start(fixture).withPortOffset(portOffset).withLog(runlog).start(); } catch (InterruptedException | IOException e) { throw new AssertionError("Failed to start container " + fixture.getName(), e); } } return container; }</code><technical_language>this change means a failure build image for a test in junit log for specific test, in multiple places. get this log need archive logs, this means for case of successful building throw logs (like do junit trim successful tests output)</technical_language>

Target:
public synchronized T get() { if (container==null) { Class<T> fixture = (Class<T>) type.getRawType(); File buildlog = diag.touch("docker-" + fixture.getSimpleName() + ".build.log"); File runlog = diag.touch("docker-" + fixture.getSimpleName() + ".run.log"); try { container = docker.build(fixture, buildlog).start(fixture).withPortOffset(portOffset).withLog(runlog).start(); } catch (InterruptedException | IOException e) { throw new Error("Failed to start container " + fixture.getName(), e); } } return container; }
Source:
<code>public static void init() { CRS.reset("all"); <START> System.setProperty("org.geotools.referencing.forceXY", "true"); <END> }</code><technical_language>I is a bad habit of this "as string" fault for this, nicer GeoTools.FORCE_LONGITUDE_FIRST_AXIS_ORDER</technical_language>

Target:
public static void init() { CRS.reset("all"); System.setProperty(GeoTools.FORCE_LONGITUDE_FIRST_AXIS_ORDER, "true"); }
Source:
<code>public double estimateFwhmMs(int numberOfScansForFWHMCalc) { double sigma = 0; int countProperIteration = 0; int countTotalIteration = 0; while (countProperIteration < numberOfScansForFWHMCalc) { countTotalIteration++; int matrixIndex = 0; if (countTotalIteration > objSliceSparseMatrix.getSizeOfRawDataFile()) { System.out.println(countTotalIteration); throw new IllegalArgumentException("Cannot calculate FWHM."); } Random generator = new Random(); int randInt = generator.nextInt(objSliceSparseMatrix.getSizeOfRawDataFile()); List<SliceSparseMatrix.VerticalSliceDataPoint> verticalSlice = objSliceSparseMatrix.getVerticalSlice(randInt); if (verticalSlice == null) continue; WeightedObservedPoints obs = new WeightedObservedPoints(); for (SliceSparseMatrix.VerticalSliceDataPoint datapoint : verticalSlice) { obs.add(datapoint.mz, datapoint.intensity); matrixIndex++; } try { double[] parameters = GaussianCurveFitter.create().fit(obs.toList()); sigma += 2.35482 * parameters[2]; } catch (Exception e) { <START> continue; <END> } countProperIteration++; } double fwhm = sigma / numberOfScansForFWHMCalc; return fwhm; }</code><technical_language>Do swallow exceptions</technical_language>

Target:
public double estimateFwhmMs(int numberOfScansForFWHMCalc) { double sigma = 0; int countProperIteration = 0; int countTotalIteration = 0; while (countProperIteration < numberOfScansForFWHMCalc) { countTotalIteration++; if (countTotalIteration > objSliceSparseMatrix.getSizeOfRawDataFile()) { System.out.println(countTotalIteration); throw new IllegalArgumentException("Cannot calculate FWHM."); } Random generator = new Random(); int randInt = generator.nextInt(objSliceSparseMatrix.getSizeOfRawDataFile()); List<SliceSparseMatrix.VerticalSliceDataPoint> verticalSlice = objSliceSparseMatrix.getVerticalSlice(randInt); if (verticalSlice == null) continue; WeightedObservedPoints obs = new WeightedObservedPoints(); for (SliceSparseMatrix.VerticalSliceDataPoint datapoint : verticalSlice) { obs.add(datapoint.mz, datapoint.intensity); } try { double[] parameters = GaussianCurveFitter.create().fit(obs.toList()); sigma += fwhmConstant * parameters[2]; } catch (MathIllegalArgumentException e) { continue; } countProperIteration++; } double fwhm = sigma / numberOfScansForFWHMCalc; return fwhm; }
Source:
<code>protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final long start = System.currentTimeMillis(); try { filterChain.doFilter(request, response); <START> } finally { <END> final long time = System.currentTimeMillis(); final Long timing = time - start; final Optional<String> userAgent = Optional.ofNullable(request.getHeader("User-Agent")); final Optional<String> user = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName); LOG.info("{} \"{}\" \"{}\" \"{}\" ms", request.getMethod(), request.getRequestURI(), userAgent.orElse("-"), user.orElse("-"), response.getStatus(), timing); } }</code><technical_language>log async consumption requests? In beginning of request stream is finished</technical_language>

Target:
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final long start = System.currentTimeMillis(); final String userAgent = Optional.ofNullable(request.getHeader("User-Agent")).orElse("-"); final String user = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName).orElse("-"); final String method = request.getMethod(); final String path = request.getRequestURI(); LOG.info("[ACCESS_LOG_BEGIN] \"{}\" \"{}\" \"{}\"", method, path, userAgent, user); try { filterChain.doFilter(request, response); } finally { final long time = System.currentTimeMillis(); final Long timing = time - start; LOG.info("[ACCESS_LOG_END] \"{}\" \"{}\" \"{}\" ms", method, path, userAgent, user, response.getStatus(), timing); } }
Source:
<code>public VoidResult call() throws NoSuchChangeException, InvalidChangeOperationException, OrmException { final Change.Id changeId = patchSetId.getParentKey(); final ChangeControl ctl = changeControlFactory.validateFor(changeId); change = ctl.getChange(); patchSet = db.patchSets().get(patchSetId); if (patchSet == null) { throw new NoSuchChangeException(changeId); } drafts = drafts(); db.changes().beginTransaction(changeId); try { publishDrafts(); final boolean isCurrent = patchSetId.equals(change.currentPatchSetId()); if (isCurrent && change.getStatus().isOpen()) { publishApprovals(ctl); } else if (approvals.isEmpty() || forceMessage) { publishMessageOnly(); } else { throw new InvalidChangeOperationException("Change is closed"); } touchChange(); db.commit(); } finally { db.rollback(); } <START> if (!suppressMails) { <END> email(); } fireHook(); return VoidResult.INSTANCE; }</code><technical_language>Optional: email() check for empty message, I this suppressMails check moved email() method. is a style preference</technical_language>

Target:
public VoidResult call() throws NoSuchChangeException, InvalidChangeOperationException, OrmException { final Change.Id changeId = patchSetId.getParentKey(); final ChangeControl ctl = changeControlFactory.validateFor(changeId); change = ctl.getChange(); patchSet = db.patchSets().get(patchSetId); if (patchSet == null) { throw new NoSuchChangeException(changeId); } drafts = drafts(); db.changes().beginTransaction(changeId); try { publishDrafts(); final boolean isCurrent = patchSetId.equals(change.currentPatchSetId()); if (isCurrent && change.getStatus().isOpen()) { publishApprovals(ctl); } else if (approvals.isEmpty() || forceMessage) { publishMessageOnly(); } else { throw new InvalidChangeOperationException("Change is closed"); } touchChange(); db.commit(); } finally { db.rollback(); } email(); fireHook(); return VoidResult.INSTANCE; }
Source:
<code>private int getLimit(ResourceInfo resource, Object clientLimit, HttpServletResponse response) throws OWSException { if (clientLimit != null) { Integer value = Converters.convert(clientLimit, Integer.class); if (value == null) { throw new OWSException( 400, "InvalidParameterValue", LIMIT, "Invalid " + LIMIT + " " + "value " + clientLimit + ", expected an integer value"); } int limitMax = LIMIT_MAX_DEFAULT; if (value < limitMax) { return value; } else { String message = "Client provided a limit value higher than the configured max, using the " + "internal value (provided/max): " + value + "/" + limitMax; <START> LOGGER.log(Level.INFO, message); <END> response.addHeader(HttpHeaders.WARNING, "299 " + message); return limitMax; } } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log( Level.FINE, "Client did not provide a limit, using the internal default value: " + LIMIT_DEFAULT); } return LIMIT_DEFAULT; } }</code><technical_language>sense log warning</technical_language>

Target:
private int getLimit(ResourceInfo resource, Object clientLimit, HttpServletResponse response) throws OWSException { if (clientLimit != null) { Integer value = Converters.convert(clientLimit, Integer.class); if (value == null) { throw new OWSException( 400, "InvalidParameterValue", DOMAIN_VALUES_LIMIT, "Invalid " + DOMAIN_VALUES_LIMIT + " " + "value " + clientLimit + ", expected an integer value"); } int limitMax = DOMAIN_VALUES_LIMIT_MAX_DEFAULT; if (value < limitMax) { return value; } else { String message = "Client provided a limit value higher than the configured max, using the " + "internal value (provided/max): " + value + "/" + limitMax; LOGGER.log(Level.INFO, message); response.addHeader(HttpHeaders.WARNING, "299 " + message); return limitMax; } } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log( Level.FINE, "Client did not provide a limit, using the internal default value: " + DOMAIN_VALUES_LIMIT_DEFAULT); } return DOMAIN_VALUES_LIMIT_DEFAULT; } }
Source:
<code>public static ExpectedCondition<WebDriverElement> hasAttribute(final Hook hook, final String attribute, <START> final String value, final boolean expectValue) { <END> return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); String[] values = element.getAttribute(attribute).split("\\s"); for (int x = 0; x < values.length; x++) { if (values[x].equals(value)) { return expectValue ? createWebDriverElement(hook, element, driver) : null; } } return expectValue ? null : createWebDriverElement(hook, element, driver); } catch (CandybeanException | StaleElementReferenceException e) { return null; } } @Override public String toString() { return attribute + (expectValue? " is ": " isn't ") + value; } }; }</code><technical_language>Formatting? indent this line</technical_language>

Target:
public static ExpectedCondition<WebDriverElement> hasAttribute(final Hook hook, final String attribute, final String value, final boolean expectValue) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); for (String currentValue : element.getAttribute(attribute).split("\\s")) { if (currentValue.equals(value)) { return expectValue ? createWebDriverElement(hook, element, driver) : null; } } return expectValue ? null : createWebDriverElement(hook, element, driver); } catch (CandybeanException | StaleElementReferenceException e) { return null; } } @Override public String toString() { return attribute + (expectValue? " is ": " isn't ") + value; } }; }
Source:
<code>@Test public void shouldCheckIfRemoteRepoExists() throws Exception { try { GitCommand.checkConnection(git.workingRepositoryUrl(), "master"); } catch (Exception e) { <START> fail(); <END> } }</code><technical_language>This is redundant. Test fail exception is thrown</technical_language>

Target:
@Test public void shouldCheckIfRemoteRepoExists() throws Exception { final TestSubprocessExecutionContext executionContext = new TestSubprocessExecutionContext(); GitCommand.checkConnection(git.workingRepositoryUrl(), "master", executionContext.getDefaultEnvironmentVariables()); }
Source:
<code>private ReplaceOptions buildReplaceOptions(T object) { final ReplaceOptions options = ReplaceOptions.replaceOptions(); if (persistTo != PersistTo.NONE || replicateTo != ReplicateTo.NONE) { options.durability(persistTo, replicateTo); } else if (durabilityLevel != DurabilityLevel.NONE) { options.durability(durabilityLevel); } long cas = template.support().getCas(object); <START> if (cas != 0) { <END> options.cas(cas); } return options; }</code><technical_language>0 cas == present if 0 is passed in fine</technical_language>

Target:
private ReplaceOptions buildReplaceOptions(T object) { final ReplaceOptions options = ReplaceOptions.replaceOptions(); if (persistTo != PersistTo.NONE || replicateTo != ReplicateTo.NONE) { options.durability(persistTo, replicateTo); } else if (durabilityLevel != DurabilityLevel.NONE) { options.durability(durabilityLevel); } long cas = template.support().getCas(object); options.cas(cas); return options; }
Source:
<code>public String toString() { <START> return ToStringBuilder.forInstance(this) <END> .append("DB Name", dbName) .append("Done At", doneAt) .append("Passed", passed) .append("Output Message", outputMessage) .build(); }</code><technical_language>Eli, please attribute names appending ToStringBuilder(). IMHO this is more readable: "EngineBackupLog:{dbName='engine', doneAt='2015...', passed='true', outputMessage='Blah'}" this "EngineBackupLog:{DB Name='engine', Done At='2015...', Passed='true', Output Message='Blah'}"</technical_language>

Target:
public String toString() { return ToStringBuilder.forInstance(this) .append("dbName", dbName) .append("doneAt", doneAt) .append("passed", passed) .append("outputMessage", outputMessage) .build(); }
Source:
<code>private static void resetDownloadFolder(SharedPreferences prefs, String key, String defaultDirectoryName) { final File folder = getFolder(defaultDirectoryName); SharedPreferences.Editor spEditor = prefs.edit(); <START> spEditor.putString(key, new File(folder, "NewPipe").getAbsolutePath()); <END> spEditor.apply(); }</code><technical_language>want extract new File(folder, "NewPipe").getAbsolutePath() a variable is reused a couple lines above</technical_language>

Target:
private static void resetDownloadFolder(SharedPreferences prefs, String key, String defaultDirectoryName) { SharedPreferences.Editor spEditor = prefs.edit(); spEditor.putString(key, getNewPipeChildFolderPathForDir(getDir(defaultDirectoryName))); spEditor.apply(); }
Source:
<code>public void getEffectiveFeatures( ) throws Exception { List<ProfileFeature> effectiveFeatures = policyManagerService. getEffectiveFeatures(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A)); Assert.assertNotNull(effectiveFeatures); Assert.assertEquals(POLICY1_FEATURE1_CODE,effectiveFeatures.get(0).getFeatureCode()); try{ policyManagerService.getEffectiveFeatures(new DeviceIdentifier(DEVICE_2, DEVICE_TYPE_B)); }catch(FeatureManagementException e){ <START> Assert.assertTrue(e.getCause()instanceof PolicyEvaluationException); <END> } }</code><technical_language>Please throw exception if exception is instance of PolicyEvaluationException. need throw exceptions, assert exceptions there, else test failures due unexpected exceptions, get full trace</technical_language>

Target:
public void getEffectiveFeatures( ) throws Exception { List<ProfileFeature> effectiveFeatures = policyManagerService. getEffectiveFeatures(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A)); Assert.assertNotNull(effectiveFeatures); Assert.assertEquals(POLICY1_FEATURE1_CODE,effectiveFeatures.get(0).getFeatureCode()); try{ policyManagerService.getEffectiveFeatures(new DeviceIdentifier(DEVICE_2, DEVICE_TYPE_B)); }catch(FeatureManagementException ex){ if(ex.getCause() instanceof PolicyEvaluationException){ Assert.assertTrue(ex.getCause() instanceof PolicyEvaluationException); }else { throw ex; } } }
Source:
<code>private Optional<Authentication> extractSourceAuthentication(Authentication currentAuthentication) { <START> return currentAuthentication.getAuthorities().stream() <END> .filter(a -> a instanceof SwitchUserGrantedAuthority) .map(a -> (SwitchUserGrantedAuthority) a) .map(SwitchUserGrantedAuthority::getSource) .findFirst(); }</code><technical_language>In order reduce overhead of creating additional objects, prefer for loops instead of streams. For more information gh-7154</technical_language>

Target:
private Optional<Authentication> extractSourceAuthentication(Authentication currentAuthentication) { for (GrantedAuthority authority : currentAuthentication.getAuthorities()) { if (authority instanceof SwitchUserGrantedAuthority) { final SwitchUserGrantedAuthority switchAuthority = (SwitchUserGrantedAuthority) authority; return Optional.of(switchAuthority.getSource()); } } return Optional.empty(); }
Source:
<code>public int indexOf(ICTFPacketDescriptor element) { int indexOf = -1; if (element != null) { indexOf = Collections.binarySearch(fEntries, element, new MonotonicComparator()); <START> } <END> return (indexOf < 0) ? -1 : indexOf; }</code><technical_language>this need fix</technical_language>

Target:
public int indexOf(ICTFPacketDescriptor element) { int indexOf = -1; if (element != null) { indexOf = Collections.binarySearch(fEntries, element, (o1, o2) -> Long.compare(o1.getOffsetBytes(), o2.getOffsetBytes())); } return (indexOf < 0) ? -1 : indexOf; }
Source:
<code>public void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket) { <START> checkArgument(!isNullOrEmpty(host), "Expected non empty host"); <END> checkArgument(!isNullOrEmpty(databaseName), "Expected non empty databaseName"); checkArgument(!isNullOrEmpty(awsAccessKey), "Expected non empty awsAccessKey"); checkArgument(!isNullOrEmpty(awsSecretKey), "Expected non empty awsSecretKey"); checkArgument(!isNullOrEmpty(writableBucket), "Expected non empty writableBucket"); super.setup(host, port, databaseName, awsAccessKey, awsSecretKey, writableBucket, true); }</code><technical_language>Remove checkArgument performed in parent classes. is expected is argument validate appropriate. If passed through, generally leave (rather duplicating validations)</technical_language>

Target:
public void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket) { super.setup(host, port, databaseName, awsAccessKey, awsSecretKey, writableBucket, true); }
Source:
<code>public RenameResourceWizard(IResource resource, String newName) { <START> super(new RenameRefactoring(new RenameResourceProcessor(resource)), DIALOG_BASED_USER_INTERFACE); <END> RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); }</code><technical_language>this(resource); fRenameResourceProcessor.setNewResourceName(newName); improve factorization</technical_language>

Target:
public RenameResourceWizard(IResource resource, String newName) { this(resource); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); }
Source:
<code>VoltFormatter (String name, Properties prop) { if (!("csv".equalsIgnoreCase(name) || "tsv".equalsIgnoreCase(name))) { <START> throw new RuntimeException("Invalid format " + name + ", choices are either \"csv\" or \"tsv\"."); <END> } m_parser = new CSVParser("csv".equalsIgnoreCase(name) ? ',' : '\t'); }</code><technical_language>please IllegalArgumentException</technical_language>

Target:
VoltFormatter (String name, Properties prop) { if (!("csv".equalsIgnoreCase(name) || "tsv".equalsIgnoreCase(name))) { throw new IllegalArgumentException("Invalid format " + name + ", choices are either \"csv\" or \"tsv\"."); } m_parser = new CSVParser("csv".equalsIgnoreCase(name) ? ',' : '\t'); }
Source:
<code>void flush() throws IOException { <START> for (Map.Entry<String, LogSegment> entry : segmentsByName.entrySet()) { <END> entry.getValue().flush(); } }</code><technical_language>do flush for segments ? in other words, this method called calls</technical_language>

Target:
void flush() throws IOException { logger.trace("Flushing log"); for (LogSegment segment : segmentsByName.values()) { segment.flush(); } }
Source:
<code>private void configureHttp1OrH2C(ChannelPipeline pipeline, HandlerHolder<? extends Handler<HttpServerConnection>> holder) { if (logEnabled) { pipeline.addLast("logging", new LoggingHandler()); } if (HttpServerImpl.USE_FLASH_POLICY_HANDLER) { pipeline.addLast("flashpolicy", new FlashPolicyHandler()); } <START> pipeline.addLast("optionalHAProxyMessageDecoder", new OptionalHAProxyMessageDecoder()); <END> pipeline.addLast("httpDecoder", new VertxHttpRequestDecoder(options)); pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder()); if (options.isDecompressionSupported()) { pipeline.addLast("inflater", new HttpContentDecompressor(false)); } if (options.isCompressionSupported()) { pipeline.addLast("deflater", new HttpChunkContentCompressor(options.getCompressionLevel())); } if (sslHelper.isSSL() || options.isCompressionSupported()) { pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout(), options.getIdleTimeoutUnit())); } if (disableH2C) { configureHttp1(pipeline, holder); } else { pipeline.addLast("h2c", new Http1xUpgradeToH2CHandler(this, holder, options.isCompressionSupported(), options.isDecompressionSupported())); } }</code><technical_language>add this pipeline option is configured. pipeline handlers effect performance avoid adding is necessary</technical_language>

Target:
private void configureHttp1OrH2C(ChannelPipeline pipeline, HandlerHolder<? extends Handler<HttpServerConnection>> holder) { if (logEnabled) { pipeline.addLast("logging", new LoggingHandler()); } if (HttpServerImpl.USE_FLASH_POLICY_HANDLER) { pipeline.addLast("flashpolicy", new FlashPolicyHandler()); } pipeline.addLast("httpDecoder", new VertxHttpRequestDecoder(options)); pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder()); if (options.isDecompressionSupported()) { pipeline.addLast("inflater", new HttpContentDecompressor(false)); } if (options.isCompressionSupported()) { pipeline.addLast("deflater", new HttpChunkContentCompressor(options.getCompressionLevel())); } if (sslHelper.isSSL() || options.isCompressionSupported()) { pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout(), options.getIdleTimeoutUnit())); } if (disableH2C) { configureHttp1(pipeline, holder); } else { pipeline.addLast("h2c", new Http1xUpgradeToH2CHandler(this, holder, options.isCompressionSupported(), options.isDecompressionSupported())); } }
Source:
<code>public void precache() { <START> cacheSignatureList((List)methodSignatures(), (List)(newSignatures()), <END> (List)(staticMethodSignatures()), (List)(fieldSignatures()), (List)(staticFieldSignatures())); }</code><technical_language>Unchecked warnings here. @SafeVarargs</technical_language>

Target:
final void precache() { if (!permittedCache.isEmpty()) { this.permittedCache.clear(); } cacheSignatureList((List)methodSignatures(), (List)(newSignatures()), (List)(staticMethodSignatures()), (List)(fieldSignatures()), (List)(staticFieldSignatures())); }
Source:
<code>public String getMessageInfo() { if (message.toLowerCase(Locale.ENGLISH).contains(Const.ACTION_RESULT_FAILURE.toLowerCase(Locale.ENGLISH))) { message = message.replace(Const.ACTION_RESULT_FAILURE, "<span class=\"text-danger\"><strong>" + Const.ACTION_RESULT_FAILURE + "</strong><br>"); message = message + "</span><br>"; } else if (message.toLowerCase(Locale.ENGLISH).contains( <START> Const.ACTION_RESULT_SYSTEM_ERROR_REPORT.toLowerCase(Locale.ENGLISH))) { <END> message = message.replace(Const.ACTION_RESULT_SYSTEM_ERROR_REPORT, "<span class=\"text-danger\"><strong>" + Const.ACTION_RESULT_SYSTEM_ERROR_REPORT + "</strong><br>"); message = message + "</span><br>"; } return message; }</code><technical_language>align toLowerCase contains</technical_language>

Target:
public String getMessageInfo() { if (message.toLowerCase().contains(Const.ACTION_RESULT_FAILURE.toLowerCase())) { message = message.replace(Const.ACTION_RESULT_FAILURE, "<span class=\"text-danger\"><strong>" + Const.ACTION_RESULT_FAILURE + "</strong><br>"); message = message + "</span><br>"; } else if (message.toLowerCase().contains(Const.ACTION_RESULT_SYSTEM_ERROR_REPORT.toLowerCase())) { message = message.replace(Const.ACTION_RESULT_SYSTEM_ERROR_REPORT, "<span class=\"text-danger\"><strong>" + Const.ACTION_RESULT_SYSTEM_ERROR_REPORT + "</strong><br>"); message = message + "</span><br>"; } return message; }
Source:
<code>private static void updateStepMessage(CommandBase<?> cmd, Guid vdsForExecution) { try { Step step = cmd.getExecutionContext().getStep(); Map<String, String> jobProperties = cmd.getJobMessageProperties(); jobProperties.put("vds", getVdsDao().get(vdsForExecution).getName()); <START> StepEnum stepEnum = StepEnum.valueOf(cmd.getCommandStep().toString() + "_ON_HOST"); <END> step.setDescription(ExecutionMessageDirector.resolveStepMessage(stepEnum, jobProperties)); getStepDao().update(step); } catch (IllegalArgumentException e) { } }</code><technical_language>please surround this part try-catch clause</technical_language>

Target:
private static void updateStepMessage(CommandBase<?> cmd, Guid vdsForExecution) { StepEnum stepEnum = null; try { stepEnum = StepEnum.valueOf(cmd.getCommandStep().toString() + "_ON_HOST"); } catch (IllegalArgumentException e) { } if (stepEnum != null) { Step step = cmd.getExecutionContext().getStep(); Map<String, String> jobProperties = cmd.getJobMessageProperties(); jobProperties.put("VDS", getVdsDao().get(vdsForExecution).getName()); step.setDescription(ExecutionMessageDirector.resolveStepMessage(stepEnum, jobProperties)); getStepDao().update(step); } }
Source:
<code>Optional<Instant> getPlayerMuteExpiration(final InetAddress inetAddress, final Clock clock) { <START> return Optional.ofNullable(playerMutes.get(inetAddress)) .map( muteInstant -> { if (muteInstant.isAfter(clock.instant())) { return muteInstant; } else { playerMutes.remove(inetAddress); return null; } }); <END> }</code><technical_language>I yesterday either, I finally a use-case for this method ^^</technical_language>

Target:
Optional<Instant> getPlayerMuteExpiration(final InetAddress inetAddress, final Clock clock) { return Optional.ofNullable( playerMutes.computeIfPresent( inetAddress, (address, existingBan) -> existingBan.isAfter(clock.instant()) ? existingBan : null)); }
Source:
<code>protected MoveSelector buildBaseMoveSelector( HeuristicConfigPolicy configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { assertThat(minimumCacheType).isEqualTo(expectedMinimumCacheType); if (expectedRandomSelection) { assertThat(randomSelection).isTrue(); } else { assertThat(randomSelection).isFalse(); <START> } <END> return baseMoveSelector; }</code><technical_language>this if</technical_language>

Target:
protected MoveSelector buildBaseMoveSelector( HeuristicConfigPolicy configPolicy, SelectionCacheType minimumCacheType, boolean randomSelection) { assertThat(minimumCacheType).isEqualTo(expectedMinimumCacheType); assertThat(randomSelection).isEqualTo(expectedRandomSelection); return baseMoveSelector; }
Source:
<code>public void toFile(String krb5ConfPath, StringBuffer sb) throws FileNotFoundException, IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(krb5ConfPath); fos.write(sb.toString().getBytes()); } finally { if (fos != null) { fos.close(); } <START> } <END> }</code><technical_language>consider doing: try (FileOutputStream fos = new FileOutputStream(krb5ConfPath)) { fos.write(sb.toString().getBytes()); } is equivalent above, lines of code :-)</technical_language>

Target:
public void toFile(String krb5ConfPath, StringBuffer sb) throws FileNotFoundException, IOException { try (FileOutputStream fos = new FileOutputStream(krb5ConfPath)) { fos.write(sb.toString().getBytes()); } }
Source:
<code>public void getLabel_labelWithDate() throws ItemNotFoundException { String testLabel = "Label [%1$td.%1$tm.%1$tY]"; Widget w = mock(Widget.class); Item item = mock(Item.class); when(w.getLabel()).thenReturn(testLabel); when(w.getItem()).thenReturn("Item"); when(registry.getItem("Item")).thenReturn(item); <START> when(item.getState()).thenReturn(new DateTimeType("2011-06-01T00:00:00Z")); <END> String label = uiRegistry.getLabel(w); assertEquals("Label [01.06.2011]", label); }</code><technical_language>accept format 2011-06-01T00:00:00, i.e. is backward-compatible</technical_language>

Target:
public void getLabel_labelWithDate() throws ItemNotFoundException { String testLabel = "Label [%1$td.%1$tm.%1$tY]"; Widget w = mock(Widget.class); Item item = mock(Item.class); when(w.getLabel()).thenReturn(testLabel); when(w.getItem()).thenReturn("Item"); when(registry.getItem("Item")).thenReturn(item); when(item.getState()).thenReturn(new DateTimeType("2011-06-01T00:00:00")); String label = uiRegistry.getLabel(w); assertEquals("Label [01.06.2011]", label); }
Source:
<code>private void addSSLConfigResource(Configuration config) { SSLConfig sslConfig = dag.getValue(Context.DAGContext.SSL_CONFIG); if (sslConfig != null) { String nodeLocalConfig = sslConfig.getNodeLocalConfigPath(); if (StringUtils.isNotEmpty(nodeLocalConfig)) { config.addResource(new Path(nodeLocalConfig)); } else { Configuration sslConfigResource = new Configuration(false); String keyStorePath = sslConfig.getKeyStorePath(); keyStorePath = (new File(keyStorePath)).getName(); <START> sslConfigResource.set("ssl.server.keystore.location", new File(keyStorePath).getName(), Context.DAGContext.SSL_CONFIG.getLongName()); <END> sslConfigResource.set("ssl.server.keystore.password", sslConfig.getKeyStorePassword(), Context.DAGContext.SSL_CONFIG.getLongName()); sslConfigResource.set("ssl.server.keystore.keypassword", sslConfig.getKeyStoreKeyPassword(), Context.DAGContext.SSL_CONFIG.getLongName()); config.addResource(sslConfigResource); } } }</code><technical_language>hadoop constants for ssl parameters</technical_language>

Target:
private void addSSLConfigResource(Configuration config) { SSLConfig sslConfig = dag.getValue(Context.DAGContext.SSL_CONFIG); if (sslConfig != null) { String nodeLocalConfig = sslConfig.getConfigPath(); if (StringUtils.isNotEmpty(nodeLocalConfig)) { config.addResource(new Path(nodeLocalConfig)); } else { Configuration sslConfigResource = new Configuration(false); final String SSL_CONFIG_LONG_NAME = Context.DAGContext.SSL_CONFIG.getLongName(); sslConfigResource.set(SSL_SERVER_KEYSTORE_LOCATION, new Path(sslConfig.getKeyStorePath()).getName(), SSL_CONFIG_LONG_NAME); sslConfigResource.set(WebAppUtils.WEB_APP_KEYSTORE_PASSWORD_KEY, sslConfig.getKeyStorePassword(), SSL_CONFIG_LONG_NAME); sslConfigResource.set(WebAppUtils.WEB_APP_KEY_PASSWORD_KEY, sslConfig.getKeyStoreKeyPassword(), SSL_CONFIG_LONG_NAME); config.addResource(sslConfigResource); } } }
Source:
<code>public boolean isEmpty(String node) { <START> return count(node) == 0; <END> }</code><technical_language>Generally, replacing isEmpty check count is a good idea easily regress in performance. In this case, deque implementation a cheap size(), brittle I do</technical_language>

Target:
public boolean isEmpty(String node) { Deque<NetworkClient.InFlightRequest> queue = requests.get(node); return queue == null || queue.isEmpty(); }
Source:
<code>public void test() throws Exception { AbstractReport<ClassReport,MethodReport> report = new AbstractReport<ClassReport,MethodReport>() { }; assertNotNull(report); report.setParent(new ClassReport()); report.getParent().setParent(new PackageReport()); <START> TaskListener taskListener = new TaskListener() { <END> public PrintStream getLogger() { return null; } public void annotate(ConsoleNote consoleNote) throws IOException { } public void hyperlink(String s, String s1) throws IOException { } public PrintWriter error(String s) { return null; } public PrintWriter error(String s, Object... objects) { return null; } public PrintWriter fatalError(String s) { return null; } public PrintWriter fatalError(String s, Object... objects) { return null; } }; JacocoBuildAction action = new JacocoBuildAction(null, null, taskListener, null, null); report.getParent().getParent().setParent(new CoverageReport(action, null)); assertNull(report.getBuild()); assertNull(report.getName()); assertNull(report.getDisplayName()); report.setName("testname"); assertEquals("testname", report.getName()); assertEquals("testname", report.getDisplayName()); }</code><technical_language>StreamTaskListener.fromStdout() easier</technical_language>

Target:
public void test() throws Exception { AbstractReport<ClassReport,MethodReport> report = new AbstractReport<ClassReport,MethodReport>() { }; assertNotNull(report); report.setParent(new ClassReport()); report.getParent().setParent(new PackageReport()); TaskListener taskListener = StreamTaskListener.fromStdout(); JacocoBuildAction action = new JacocoBuildAction(null, null, taskListener, null, null); report.getParent().getParent().setParent(new CoverageReport(action, null)); assertNull(report.getBuild()); assertNull(report.getName()); assertNull(report.getDisplayName()); report.setName("testname"); assertEquals("testname", report.getName()); assertEquals("testname", report.getDisplayName()); }
Source:
<code>protected void processOptions(Widget widget, ObjectNode schema) { Map<String, String> optionsMap = UiSchemaConstants.getWidgetOptionsMapping().get(widget.getWidgetType()); Map<String, List<String>> optionsMapMultipleValues = UiSchemaConstants.getWidgetOptionsMappingMultipleValues() .get(widget.getWidgetType()); if (optionsMap != null) { ObjectNode options = JsonNodeFactory.instance.objectNode(); for (Map.Entry<String, String> entry : optionsMap.entrySet()) { options.put(entry.getKey(), entry.getValue()); } schema.set(UiSchemaConstants.TAG_OPTIONS, options); } <START> if (optionsMapMultipleValues != null) { <END> ObjectNode options = JsonNodeFactory.instance.objectNode(); for (Map.Entry<String, List<String>> entry : optionsMapMultipleValues.entrySet()) { for (String value : entry.getValue()) { if (value.equals(widget.getWidgetCode().name())) { options.put(entry.getKey(), value); } } } schema.set(UiSchemaConstants.TAG_OPTIONS, options); } }</code><technical_language>This entire code block replaced by: if (widget.getWidgetCode() != null) { ObjectNode options = JsonNodeFactory.instance.objectNode(); options.put("language", widget.getWidgetCode() schema.set(UiSchemaConstants.TAG_OPTIONS, options); } hard-coding requirements Widget a WidgetCode -- need add complexity of optionsMapMultipleValues</technical_language>

Target:
protected void processOptions(Widget widget, ObjectNode schema) { Map<String, String> optionsMap = UiSchemaConstants.getWidgetOptionsMapping().get(widget.getWidgetType()); if (optionsMap != null) { ObjectNode options = JsonNodeFactory.instance.objectNode(); for (Map.Entry<String, String> entry : optionsMap.entrySet()) { if (widget.getConfigurationValue(entry.getKey()) != null) { options.put(entry.getKey(), widget.getConfigurationValue(entry.getKey()).toString()); } else { options.put(entry.getKey(), entry.getValue()); } } schema.set(UiSchemaConstants.TAG_OPTIONS, options); } }
Source:
<code>protected BluetoothConnectionBase(OutputStream outputStream, InputStream inputStream) { <START> this((Form) null, (String) null, SdkLevel.LEVEL_CUPCAKE); <END> this.connectedBluetoothSocket = "Not Null"; this.outputStream = outputStream; this.inputStream = inputStream; }</code><technical_language>earliest SDK version target is 7, LEVEL_ECLAIR_MR1 LEVEL_CUPCAKE</technical_language>

Target:
protected BluetoothConnectionBase(OutputStream outputStream, InputStream inputStream) { this((Form) null, (String) null, SdkLevel.LEVEL_ECLAIR_MR1); this.connectedBluetoothSocket = "Not Null"; this.outputStream = outputStream; this.inputStream = inputStream; }
Source:
<code>public void setup(Context.OperatorContext context) { if (store == null) { store = new ManagedStateSpillableStateStore(); } sccImpl = new SpillableComplexComponentImpl(store); <START> internValues = sccImpl.newSpillableByteMap((identifier + "#values").getBytes(), bucket, windowKeyPairSerde, valueSerde); <END> internKeys = sccImpl.newSpillableByteArrayListMultimap((identifier + "#keys").getBytes(), bucket, windowSerde, keySerde); sccImpl.setup(context); }</code><technical_language>is a constraint identifiers right number of bytes in length. want identifiers small keys stored in managed state prefixed it. For this case identifier. If identifier a single byte identifier automatically generated for data structure</technical_language>

Target:
public void setup(Context.OperatorContext context) { if (bucket == 0) { bucket = (context.getValue(Context.DAGContext.APPLICATION_NAME) + "#" + context.getId()).hashCode(); } if (windowSerde == null) { windowSerde = new SerdeKryoSlice<>(); } if (windowKeyPairSerde == null) { windowKeyPairSerde = new SerdeKryoSlice<>(); } if (keySerde == null) { keySerde = new SerdeKryoSlice<>(); } if (valueSerde == null) { valueSerde = new SerdeKryoSlice<>(); } if (windowKeyToValueMap == null) { windowKeyToValueMap = scc.newSpillableByteMap(bucket, windowKeyPairSerde, valueSerde); } if (windowToKeysMap == null) { windowToKeysMap = scc.newSpillableByteArrayListMultimap(bucket, windowSerde, keySerde); } }