auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void createsFork() throws Exception { final String organization = RandomStringUtils.randomNumeric(10); final MkAnswer answer = new MkAnswer.Simple( HttpURLConnection.HTTP_OK, fork(organization).toString() ); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_ACCEPTED, fork(organization).toString() ) ).next(answer).start(); final Repo owner = Mockito.mock(Repo.class); <START> final Coordinates coordinates = Mockito.mock(Coordinates.class); <END> Mockito.doReturn(coordinates).when(owner).coordinates(); Mockito.doReturn("test_user").when(coordinates).user(); Mockito.doReturn("test_repo").when(coordinates).repo(); final RtForks forks = new RtForks( new JdkRequest(container.home()), owner ); final Fork fork = forks.create(organization); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( fork.json().getString(ORGANIZATION), Matchers.equalTo(organization) ); container.stop(); }</code><technical_language>mocking if Coordinates.Simple</technical_language>

Target:
public void createsFork() throws Exception { final String organization = RandomStringUtils.randomNumeric(10); final MkAnswer answer = new MkAnswer.Simple( HttpURLConnection.HTTP_OK, fork(organization).toString() ); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_ACCEPTED, fork(organization).toString() ) ).next(answer).start(); final Repo owner = Mockito.mock(Repo.class); final Coordinates coordinates = new Coordinates.Simple( "test_user", "test_repo" ); Mockito.doReturn(coordinates).when(owner).coordinates(); final RtForks forks = new RtForks( new JdkRequest(container.home()), owner ); final Fork fork = forks.create(organization); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( fork.json().getString(ORGANIZATION), Matchers.equalTo(organization) ); container.stop(); }
Source:
<code>public String[] listFiles(URI fileUri, boolean recursive) throws IOException { try { ImmutableList.Builder<String> builder = ImmutableList.builder(); String prefix = normalizeToDirectoryPrefix(fileUri); ListObjectsV2Response listObjectsV2Response; ListObjectsV2Request.Builder listObjectsV2RequestBuilder = ListObjectsV2Request.builder() .bucket(fileUri.getHost()) .prefix(prefix); if (recursive) { ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.build(); listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request); } else { ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.delimiter(DELIMITER).build(); <START> listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request); <END> } listObjectsV2Response.contents().stream() .forEach(object -> { if (!object.key().equals(fileUri.getPath()) && !object.key().endsWith(DELIMITER)) { builder.add(object.key()); } }); return builder.build().toArray(new String[0]); } catch (Throwable t) { throw new IOException(t); } }</code><technical_language>nit: move this repetitive line if-else blocks</technical_language>

Target:
public String[] listFiles(URI fileUri, boolean recursive) throws IOException { try { ImmutableList.Builder<String> builder = ImmutableList.builder(); String prefix = normalizeToDirectoryPrefix(fileUri); ListObjectsV2Response listObjectsV2Response; ListObjectsV2Request.Builder listObjectsV2RequestBuilder = ListObjectsV2Request.builder().bucket(fileUri.getHost()); if (!prefix.equals(DELIMITER)) { listObjectsV2RequestBuilder = listObjectsV2RequestBuilder.prefix(prefix); } if (!recursive) { listObjectsV2RequestBuilder = listObjectsV2RequestBuilder.delimiter(DELIMITER); } ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.build(); listObjectsV2Response = _s3Client.listObjectsV2(listObjectsV2Request); listObjectsV2Response.contents().stream().forEach(object -> { if (!object.key().equals(fileUri.getPath()) && !object.key().endsWith(DELIMITER)) { builder.add(object.key()); } }); return builder.build().toArray(new String[0]); } catch (Throwable t) { throw new IOException(t); } }
Source:
<code>private boolean useResizingImageView() { return !CommCarePreferences.isSmartInflationEnabled() && <START> (ResizingImageView.resizeMethod != null && <END> (ResizingImageView.resizeMethod.equals("full") || ResizingImageView.resizeMethod.equals("half") || ResizingImageView.resizeMethod.equals("width"))); }</code><technical_language>picky, instead of adding null check, change order of 3 statements implied in those, e.g. ("full".equals(ResizingImageView.resizeMethod))</technical_language>

Target:
private boolean useResizingImageView() { return !CommCarePreferences.isSmartInflationEnabled() && ("full".equals(ResizingImageView.resizeMethod) || "half".equals(ResizingImageView.resizeMethod) || "width".equals(ResizingImageView.resizeMethod)); }
Source:
<code>private static <BE> void preUpdate(TraversalContext<BE, ?> context, BE entity, MetricType.Update update) { MetricType mt = context.backend.convert(entity, MetricType.class); if (mt.getUnit() == update.getUnit()) { return; } if (isInMetadataPack(context, entity)) { <START> throw new IllegalArgumentException("Cannot delete a metric type that is a part of metadata pack."); <END> } }</code><technical_language>s/delete/update/</technical_language>

Target:
private static <BE> void preUpdate(TraversalContext<BE, ?> context, BE entity, MetricType.Update update) { MetricType mt = context.backend.convert(entity, MetricType.class); if (mt.getUnit() == update.getUnit()) { return; } if (isInMetadataPack(context, entity)) { throw new IllegalArgumentException("Cannot update a metric type that is a part of metadata pack."); } }
Source:
<code>private void readProperties(Map<String, Object> properties) { if (properties.get(PROPERTY_PING_INTERVAL) != null) { this.pingInterval = (Integer) properties.get(PROPERTY_PING_INTERVAL); } if (properties.get(PROPERTY_WD_DEVICE) != null && !((String) properties.get(PROPERTY_WD_DEVICE)).isEmpty()) { this.watchdogDevice = (String) properties.get(PROPERTY_WD_DEVICE); } if (properties.get(PROPERTY_ENABLED) != null) { this.configEnabled = (Boolean) properties.get(PROPERTY_ENABLED); if (this.configEnabled) { PrintWriter wdWriter = null; try { <START> wdWriter = new PrintWriter(WD_FILE); <END> wdWriter.write(this.watchdogDevice); } catch (IOException e) { logger.error("Unable to write watchdog config file", e); } finally { if (wdWriter != null) wdWriter.close(); } logger.debug("activating WatchdogService with watchdog enabled"); } else { logger.debug("activating WatchdogService with watchdog disabled"); } } }</code><technical_language>try-with-resources</technical_language>

Target:
private void readProperties(Map<String, Object> properties) { this.pingInterval = (Integer) properties.get(PROPERTY_PING_INTERVAL); if (!((String) properties.get(PROPERTY_WD_DEVICE)).isEmpty()) { this.watchdogDevice = (String) properties.get(PROPERTY_WD_DEVICE); } this.configEnabled = (Boolean) properties.get(PROPERTY_ENABLED); if (this.configEnabled) { try (PrintWriter wdWriter = new PrintWriter(WD_FILE);) { wdWriter.write(this.watchdogDevice); } catch (IOException e) { logger.error("Unable to write watchdog config file", e); } logger.debug("activating WatchdogService with watchdog enabled"); } else { logger.debug("activating WatchdogService with watchdog disabled"); } }
Source:
<code>public Command execute() throws RollBackCommandException { try { Session sess = this.getSecAdvisor().getReadOnlyHibernateSession(this.getUsername()); if(idDataTrack != null) { DataTrack dataTrack = (DataTrack) (sess.load(DataTrack.class, idDataTrack)); if (!this.getSecAdvisor().canRead(dataTrack)) { this.addInvalidField("perm", "Insufficient permission to access this data track"); } } else { this.addInvalidField("dataTrackNumber", "dataTrackNumber is either invalid or not provided"); } if (isValid()) { this.xmlResult = "<SUCCESS/>"; setResponsePage(this.SUCCESS_JSP); } else { setResponsePage(this.ERROR_JSP); } } catch (NamingException e){ LOG.error("An exception has occurred in CheckDataTrackPermission ", e); <START> e.printStackTrace(System.out); <END> throw new RollBackCommandException(e.getMessage()); } catch (SQLException e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); e.printStackTrace(System.out); throw new RollBackCommandException(e.getMessage()); } catch (Exception e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); e.printStackTrace(System.out); throw new RollBackCommandException(e.getMessage()); } finally { try { this.getSecAdvisor().closeReadOnlyHibernateSession(); } catch(Exception e) { } } return this; }</code><technical_language>This removed</technical_language>

Target:
public Command execute() throws RollBackCommandException { try { Session sess = this.getSecAdvisor().getReadOnlyHibernateSession(this.getUsername()); if(idDataTrack != null) { DataTrack dataTrack = (DataTrack) (sess.load(DataTrack.class, idDataTrack)); if (!this.getSecAdvisor().canRead(dataTrack)) { this.addInvalidField("perm", "Insufficient permission to access this data track"); } } else { this.addInvalidField("dataTrackNumber", "dataTrackNumber is either invalid or not provided"); } if (isValid()) { this.xmlResult = "<SUCCESS/>"; setResponsePage(this.SUCCESS_JSP); } else { setResponsePage(this.ERROR_JSP); } } catch (Exception e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); throw new RollBackCommandException(e.getMessage()); } finally { try { this.getSecAdvisor().closeReadOnlyHibernateSession(); } catch(Exception e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); } } return this; }
Source:
<code>public void clearFinishedDownloads(boolean delete) { if (delete && mIterator.hasFinishedMissions() && mHidden.isEmpty()) { for (int i = 0; i < mIterator.getOldListSize(); i++) { FinishedMission mission = mIterator.getItem(i).mission instanceof FinishedMission ? (FinishedMission) mIterator.getItem(i).mission : null; if (mission != null) { mIterator.hide(mission); mHidden.add(mission); } } applyChanges(); String msg = String.format(mContext.getString(R.string.deleted_downloads), String.valueOf(mHidden.size())); mSnackbar = Snackbar.make(mView, msg, Snackbar.LENGTH_INDEFINITE); mSnackbar.setAction(R.string.undo, s -> { Iterator<Mission> i = mHidden.iterator(); while (i.hasNext()) { mIterator.unHide(i.next()); i.remove(); } applyChanges(); mHandler.removeCallbacks(rDelete); }); mSnackbar.setActionTextColor(Color.YELLOW); mSnackbar.show(); <START> mHandler.postDelayed(rDelete, TIMEOUT); <END> } else if (!delete) { mDownloadManager.forgetFinishedDownloads(); applyChanges(); } }</code><technical_language>Please set delay directly. constant is once</technical_language>

Target:
public void clearFinishedDownloads(boolean delete) { if (delete && mIterator.hasFinishedMissions() && mHidden.isEmpty()) { for (int i = 0; i < mIterator.getOldListSize(); i++) { FinishedMission mission = mIterator.getItem(i).mission instanceof FinishedMission ? (FinishedMission) mIterator.getItem(i).mission : null; if (mission != null) { mIterator.hide(mission); mHidden.add(mission); } } applyChanges(); String msg = String.format(mContext.getString(R.string.deleted_downloads), mHidden.size()); mSnackbar = Snackbar.make(mView, msg, Snackbar.LENGTH_INDEFINITE); mSnackbar.setAction(R.string.undo, s -> { Iterator<Mission> i = mHidden.iterator(); while (i.hasNext()) { mIterator.unHide(i.next()); i.remove(); } applyChanges(); mHandler.removeCallbacks(rDelete); }); mSnackbar.setActionTextColor(Color.YELLOW); mSnackbar.show(); mHandler.postDelayed(rDelete, 5000); } else if (!delete) { mDownloadManager.forgetFinishedDownloads(); applyChanges(); } }
Source:
<code>protected void auditRequestMessage(RetrieveDocumentSetRequestType request, String direction, String connectInterface, AssertionType assertion, String requestCommunityID) { <START> gov.hhs.fha.nhinc.common.auditlog.DocRetrieveMessageType message = new gov.hhs.fha.nhinc.common.auditlog.DocRetrieveMessageType(); <END> message.setRetrieveDocumentSetRequest(request); message.setAssertion(assertion); AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logDocRetrieve(message, direction, connectInterface, requestCommunityID); if (auditLogMsg != null) { auditMessage(auditLogMsg, assertion); } }</code><technical_language>I this is existing code, changes made, this declaration need fully-qualified</technical_language>

Target:
protected void auditRequestMessage(RetrieveDocumentSetRequestType request, String direction, String connectInterface, AssertionType assertion, String requestCommunityID) { DocRetrieveMessageType message = new DocRetrieveMessageType(); message.setRetrieveDocumentSetRequest(request); message.setAssertion(assertion); AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logDocRetrieve(message, direction, connectInterface, requestCommunityID); if (auditLogMsg != null) { auditMessage(auditLogMsg, assertion); } }
Source:
<code>private void orderListByProgramName(List<TrialSummary> trialSummaryList, final String sortOrder) { if (StringUtil.isEmpty(sortOrder) || TrialResourceBrapi.DESCENDING.equalsIgnoreCase(sortOrder)) { Comparator desc = Collections.reverseOrder(getComparatorProgramName()); Collections.sort(trialSummaryList, desc); <START> }else { <END> Collections.sort(trialSummaryList, getComparatorProgramName()); } }</code><technical_language>format</technical_language>

Target:
private void orderListByProgramName(List<TrialSummary> trialSummaryList, final String sortOrder) { if (StringUtil.isEmpty(sortOrder) || TrialResourceBrapi.ORDER_BY_DESCENDING.equalsIgnoreCase(sortOrder)) { Comparator desc = Collections.reverseOrder(TrialResourceBrapi.getComparatorProgramName()); Collections.sort(trialSummaryList, desc); } else { Collections.sort(trialSummaryList, TrialResourceBrapi.getComparatorProgramName()); } }
Source:
<code>public JSONPathSpec( @JsonProperty("useFieldDiscovery") Boolean useFieldDiscovery, @JsonProperty("fields") List<JSONPathFieldSpec> fields ) { this.useFieldDiscovery = useFieldDiscovery == null ? true : useFieldDiscovery; <START> this.fields = fields == null ? new ArrayList<JSONPathFieldSpec>() : fields; <END> }</code><technical_language>ImmutableList.of() here</technical_language>

Target:
public JSONPathSpec( @JsonProperty("useFieldDiscovery") Boolean useFieldDiscovery, @JsonProperty("fields") List<JSONPathFieldSpec> fields ) { this.useFieldDiscovery = useFieldDiscovery == null ? true : useFieldDiscovery; this.fields = fields == null ? ImmutableList.<JSONPathFieldSpec>of() : fields; }
Source:
<code>private String trimUrlWebdav(String url){ if(url.toLowerCase().endsWith(WEBDAV_PATH)){ <START> url = url.substring(0, url.length() - WEBDAV_PATH.length()); <END> } return (url != null ? url : ""); }</code><technical_language>more, this method check AccountUtils.java#WEBDAV_PATH_**\* suffixes</technical_language>

Target:
private String trimUrlWebdav(String url){ if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){ url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length()); } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){ url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length()); } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){ url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length()); } return (url != null ? url : ""); }
Source:
<code>public static SQLException unwrapSqlException(SQLException root){ Exception e = root; while(e.getCause() != null){ e = (Exception) e.getCause(); if(e instanceof SQLException){ root = (SQLException) e; } } return root; <START> } <END></code><technical_language>Thanks for modification, @lomoree! fine for deepest SQLException. if catch RuntimeException unwrap if find SQLException wrap if not. @JamesRTaylor idea</technical_language>

Target:
public static SQLException unwrapSqlException(SQLException root){ Exception e = root; while(e.getCause() != null){ e = (Exception) e.getCause(); if(e instanceof RuntimeException && e.getCause() instanceof SQLException) { return (SQLException) e.getCause(); } if(e instanceof SQLException){ return (SQLException) e; } } return root; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { Shell activeShell= HandlerUtil.getActiveShell(event); Object newNameValue= HandlerUtil.getVariable(event, LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY); String newName= null; if (newNameValue instanceof String) { newName= (String) newNameValue; } else if (newNameValue != null) { RefactoringUIPlugin.logErrorMessage(NLS.bind(RefactoringUIMessages.RenameResourceHandler_ERROR_EXPECTED_STRING, newNameValue.getClass().getName())); } ISelection sel= HandlerUtil.getCurrentSelection(event); if (sel instanceof IStructuredSelection) { IResource resource= getCurrentResource((IStructuredSelection) sel); if (resource != null) { RenameResourceWizard refactoringWizard; if (newName != null) { refactoringWizard= new RenameResourceWizard(resource, newName); } else { refactoringWizard= new RenameResourceWizard(resource); } RefactoringProcessor processor= ((ProcessorBasedRefactoring) refactoringWizard.getRefactoring()).getProcessor(); Change change= getChange(refactoringWizard); RefactoringWizardOpenOperation op= new RefactoringWizardOpenOperation(refactoringWizard); try { if (isCompositeChange(change) || !(processor instanceof RenameResourceProcessor)) { <START> op.run(activeShell, RefactoringUIMessages.RenameResourceHandler_title); <END> } else { change.perform(new NullProgressMonitor()); } } catch (InterruptedException | CoreException e) { RefactoringUIPlugin.log(e); } } } return null; }</code><technical_language>reinstantiate wizard done line 65..69 alter state shown</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Shell activeShell= HandlerUtil.getActiveShell(event); Object newNameValue= HandlerUtil.getVariable(event, LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY); String newName= null; if (newNameValue instanceof String) { newName= (String) newNameValue; } else if (newNameValue != null) { RefactoringUIPlugin.logErrorMessage(NLS.bind(RefactoringUIMessages.RenameResourceHandler_ERROR_EXPECTED_STRING, newNameValue.getClass().getName())); } ISelection sel= HandlerUtil.getCurrentSelection(event); if (sel instanceof IStructuredSelection) { IResource resource= getCurrentResource((IStructuredSelection) sel); if (resource != null) { RenameResourceWizard refactoringWizard; if (newName != null) { refactoringWizard= new RenameResourceWizard(resource, newName); } else { refactoringWizard= new RenameResourceWizard(resource); } RefactoringProcessor processor= ((ProcessorBasedRefactoring) refactoringWizard.getRefactoring()).getProcessor(); Change change= getChange(refactoringWizard); try { if (isCompositeChange(change) || !(processor instanceof RenameResourceProcessor)) { refactoringWizard= newName == null ? new RenameResourceWizard(resource) : new RenameResourceWizard(resource, newName); RefactoringWizardOpenOperation op= new RefactoringWizardOpenOperation(refactoringWizard); op.run(activeShell, RefactoringUIMessages.RenameResourceHandler_title); } else { change.perform(new NullProgressMonitor()); } } catch (InterruptedException | CoreException e) { RefactoringUIPlugin.log(e); } } } return null; }
Source:
<code>public void setResize(int resize) { for(int i=1;i<10;i++) { if(resize == i*100) { this.resize = resize; return; } } <START> throw new IllegalArgumentException("Invalid resize value"); <END> }</code><technical_language>wish print valid range of resize values part of exception message</technical_language>

Target:
public void setResize(int resize) { for(int i=1;i<10;i++) { if(resize == i*100) { this.resize = resize; return; } } throw new IllegalArgumentException("Invalid resize value. Valid range of values is 100-900."); }
Source:
<code>public DefaultPlanPhase(final DefaultPlan parentPlan, final DefaultPlanPhase in, @Nullable final PlanPhasePriceOverride override) { this.type = in.getPhaseType(); this.duration = (DefaultDuration) in.getDuration(); this.fixed = override != null && override.getFixedPrice() != null ? new DefaultFixed((DefaultFixed) in.getFixed(), override) : (DefaultFixed) in.getFixed(); this.recurring = override != null && override.getRecurringPrice() != null ? new DefaultRecurring((DefaultRecurring) in.getRecurring(), override) : (DefaultRecurring) in.getRecurring(); this.usages = new DefaultUsage[in.getUsages().length]; for (int i = 0; i < in.getUsages().length; i++) { <START> if(override != null && override.getUsagePriceOverrides().get(i)!= null) { <END> usages[i] = new DefaultUsage(in.getUsages()[i], override.getUsagePriceOverrides().get(i), override.getCurrency()); } else { usages[i] = (DefaultUsage) in.getUsages()[i]; } } this.plan = parentPlan; }</code><technical_language>this is ordering (shouldn't check override section matches current entry?)</technical_language>

Target:
public DefaultPlanPhase(final DefaultPlan parentPlan, final DefaultPlanPhase in, @Nullable final PlanPhasePriceOverride override) { this.type = in.getPhaseType(); this.duration = (DefaultDuration) in.getDuration(); this.fixed = override != null && override.getFixedPrice() != null ? new DefaultFixed((DefaultFixed) in.getFixed(), override) : (DefaultFixed) in.getFixed(); this.recurring = override != null && override.getRecurringPrice() != null ? new DefaultRecurring((DefaultRecurring) in.getRecurring(), override) : (DefaultRecurring) in.getRecurring(); this.usages = new DefaultUsage[in.getUsages().length]; for (int i = 0; i < in.getUsages().length; i++) { final Usage curUsage = in.getUsages()[i]; if(override != null && override.getUsagePriceOverrides()!= null) { final UsagePriceOverride usagePriceOverride = Iterables.tryFind(override.getUsagePriceOverrides(), new Predicate<UsagePriceOverride>() { @Override public boolean apply(final UsagePriceOverride input) { return input !=null && input.getName().equals(curUsage.getName()); } }).orNull(); usages[i] = (usagePriceOverride !=null) ? new DefaultUsage(in.getUsages()[i], usagePriceOverride, override.getCurrency()) : (DefaultUsage)curUsage; } else { usages[i] = (DefaultUsage)curUsage; } } this.plan = parentPlan; }
Source:
<code><START> public synchronized MBeanInfo getMBeanInfo() { <END> return _mBeanInfo; }</code><technical_language>discussed, this sync work. lock attributes list in direct access method</technical_language>

Target:
public MBeanInfo getMBeanInfo() { return _mBeanInfo; }
Source:
<code>private void createNewWalk(Repository db, AnyObjectId headId) { currentHeadId = headId; if (currentWalk != null) currentWalk.release(); <START> if (getFollowRenames()) { <END> currentWalk = new FollowingSWTWalk(db); } else { currentWalk = new SWTWalk(db); } try { currentWalk.addAdditionalRefs(db.getRefDatabase().getAdditionalRefs()); currentWalk.addAdditionalRefs(db.getRefDatabase(). getRefs(Constants.R_NOTES).values()); } catch (IOException e) { throw new IllegalStateException(NLS.bind( UIText.GitHistoryPage_errorReadingAdditionalRefs, Activator .getDefault().getRepositoryUtil() .getRepositoryName(db)), e); } currentWalk.sort(RevSort.COMMIT_TIME_DESC, true); currentWalk.sort(RevSort.BOUNDARY, true); highlightFlag = currentWalk.newFlag("highlight"); }</code><technical_language>style-nit; surplus braces</technical_language>

Target:
private void createNewWalk(Repository db, AnyObjectId headId) { currentHeadId = headId; if (currentWalk != null) currentWalk.release(); if (getFollowRenames()) currentWalk = new FollowingSWTWalk(db); else currentWalk = new SWTWalk(db); try { currentWalk.addAdditionalRefs(db.getRefDatabase().getAdditionalRefs()); currentWalk.addAdditionalRefs(db.getRefDatabase(). getRefs(Constants.R_NOTES).values()); } catch (IOException e) { throw new IllegalStateException(NLS.bind( UIText.GitHistoryPage_errorReadingAdditionalRefs, Activator .getDefault().getRepositoryUtil() .getRepositoryName(db)), e); } currentWalk.sort(RevSort.COMMIT_TIME_DESC, true); currentWalk.sort(RevSort.BOUNDARY, true); highlightFlag = currentWalk.newFlag("highlight"); }
Source:
<code>public ForwardToContainer(Collection<InetAddressAndPort> targets, int[] messageIds) { <START> this.targets = targets; <END> this.messageIds = messageIds; }</code><technical_language>Good idea for fail construction</technical_language>

Target:
public ForwardToContainer(Collection<InetAddressAndPort> targets, int[] messageIds) { Preconditions.checkArgument(targets.size() == messageIds.length); this.targets = targets; this.messageIds = messageIds; }
Source:
<code>private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) { if (state == null || state.networkInfo == null || state.linkProperties == null) return; if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) { state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null); } if <START> (mLockdownTracker != <END> null) { mLockdownTracker.augmentNetworkInfo(state.networkInfo); } final long token = Binder.clearCallingIdentity(); try { state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state)); } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(token); } }</code><technical_language>need lock this ? mLockdownTracker changed test call</technical_language>

Target:
private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) { if (state == null || state.networkInfo == null || state.linkProperties == null) return; if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) { state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null); } synchronized (mVpns) { if (mLockdownTracker != null) { mLockdownTracker.augmentNetworkInfo(state.networkInfo); } } final long token = Binder.clearCallingIdentity(); try { state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state)); } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(token); } }
Source:
<code>protected List<String> getOptionalStringList(String... optionPath) { try { return getRequiredStringList(optionPath); } catch (InvalidConfigurationException e) { <START> return Lists.newArrayList(); <END> } }</code><technical_language>Collections.emptyList() instead</technical_language>

Target:
protected List<String> getOptionalStringList(String... optionPath) { try { return getRequiredStringList(optionPath); } catch (InvalidConfigurationException e) { return Collections.emptyList(); } }
Source:
<code>public String format(String projectName, String revision, ConfigSection cfg, String raw) throws IOException { File tmpFile = new File(baseDir, "tmp/asciidoctor-" + <START> System.currentTimeMillis() + <END> ".tmp"); try { Asciidoctor.Factory.create(AsciidoctorFormatter.class.getClassLoader()) .render(raw, createOptions(cfg, revision, tmpFile)); try (FileInputStream input = new FileInputStream(tmpFile)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteStreams.copy(input, out); return insertCss(out.toString(UTF_8.name())); } } finally { if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } }</code><technical_language>TimeUtil</technical_language>

Target:
public String format(String projectName, String revision, ConfigSection cfg, String raw) throws IOException { File tmpFile = new File(baseDir, "tmp/asciidoctor-" + TimeUtil.nowTs().getNanos() + ".tmp"); try { Asciidoctor.Factory.create(AsciidoctorFormatter.class.getClassLoader()) .render(raw, createOptions(cfg, revision, tmpFile)); try (FileInputStream input = new FileInputStream(tmpFile)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteStreams.copy(input, out); return insertCss(out.toString(UTF_8.name())); } } finally { if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } }
Source:
<code>public int hashCode() { final int prime = 31; <START> int result = 1; <END> result = prime * result + ((inboundAverage == null) ? 0 : inboundAverage.hashCode()); result = prime * result + ((inboundPeak == null) ? 0 : inboundPeak.hashCode()); result = prime * result + ((inboundBurst == null) ? 0 : inboundBurst.hashCode()); result = prime * result + ((outboundAverage == null) ? 0 : outboundAverage.hashCode()); result = prime * result + ((outboundPeak == null) ? 0 : outboundPeak.hashCode()); result = prime * result + ((outboundBurst == null) ? 0 : outboundBurst.hashCode()); return result; }</code><technical_language>result based super.hashCode(), distinct QoS entities values</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((inboundAverage == null) ? 0 : inboundAverage.hashCode()); result = prime * result + ((inboundPeak == null) ? 0 : inboundPeak.hashCode()); result = prime * result + ((inboundBurst == null) ? 0 : inboundBurst.hashCode()); result = prime * result + ((outboundAverage == null) ? 0 : outboundAverage.hashCode()); result = prime * result + ((outboundPeak == null) ? 0 : outboundPeak.hashCode()); result = prime * result + ((outboundBurst == null) ? 0 : outboundBurst.hashCode()); return result; }
Source:
<code>private Query applyEntityGraphConfiguration(Query query, JpaQueryMethod method) { JpaEntityGraph entityGraph = method.getEntityGraph(); if (entityGraph != null) { <START> List<QueryHintValue> hints = Jpa21Utils.tryGetFetchGraphHints(em, method.getEntityGraph(), <END> getQueryMethod().getEntityInformation().getJavaType()); for (QueryHintValue hint : hints) { query.setHint(hint.name, hint.value); } } return query; }</code><technical_language>this method returning QueryHints directly</technical_language>

Target:
private Query applyEntityGraphConfiguration(Query query, JpaQueryMethod method) { JpaEntityGraph entityGraph = method.getEntityGraph(); if (entityGraph != null) { SimpleQueryHints hints = Jpa21Utils.getFetchGraphHint(em, method.getEntityGraph(), getQueryMethod().getEntityInformation().getJavaType()); hints.forEach(query::setHint); } return query; }
Source:
<code>private UniqueEntityLoader getLoaderByLockMode(LockMode lockMode) { <START> if ( LockMode.NONE.equals( lockMode ) ) { <END> return noneLockLoader; } else if ( LockMode.READ.equals( lockMode ) ) { return readLockLoader; } return loaders.computeIfAbsent( lockMode, this::createLazyLoadedEntityLoader ); }</code><technical_language>is common practice in Hibernate '==' compare enum values for equality. follow this practice too</technical_language>

Target:
private UniqueEntityLoader getLoaderByLockMode(LockMode lockMode) { if ( LockMode.NONE == lockMode ) { return noneLockLoader; } else if ( LockMode.READ == lockMode ) { return readLockLoader; } return loaders.computeIfAbsent( lockMode, this::createLazyLoadedEntityLoader ); }
Source:
<code>public boolean add(SelectionKey key) { if (key == null) { return false; } <START> if (pos >= (keys.length - 1)) { <END> SelectionKey[] keys = new SelectionKey[this.keys.length << 1]; System.arraycopy(this.keys, 0, keys, 0, this.keys.length); this.keys = keys; } keys[pos++] = key; return true; }</code><technical_language>Good catch. avoid subtraction move check array copy pos is incremented. do of changing condition >= == pos instead of key.length in arraycopy</technical_language>

Target:
public boolean add(SelectionKey key) { if (key == null) { return false; } if (pos >= keys.length) { SelectionKey[] keys = new SelectionKey[this.keys.length << 1]; System.arraycopy(this.keys, 0, keys, 0, this.keys.length); this.keys = keys; } keys[pos++] = key; return true; }
Source:
<code>private static void findScrambleOptions( final PlayerId player, final Map<Territory, ProTerritory> moveMap) { final GameData data = ProData.getData(); if (!Properties.getScrambleRulesInEffect(data)) { return; } final var scrambleLogic = new ScrambleLogic(data, player, moveMap.keySet()); <START> for (final var territoryToScramblersEntry : <END> scrambleLogic.getUnitsThatCanScrambleByDestination().entrySet()) { final Territory to = territoryToScramblersEntry.getKey(); for (final var fromToScrambers : territoryToScramblersEntry.getValue().entrySet()) { final Territory from = fromToScrambers.getKey(); final Collection<Unit> airbases = fromToScrambers.getValue().getFirst(); final Collection<Unit> scramblers = fromToScrambers.getValue().getSecond(); final int maxCanScramble = ScrambleLogic.getMaxScrambleCount(airbases); final List<Unit> addTo = moveMap.get(to).getMaxScrambleUnits(); if (scramblers.size() <= maxCanScramble) { addTo.addAll(scramblers); } else { scramblers.stream() .sorted( Comparator.<Unit>comparingDouble( unit -> ProBattleUtils.estimateStrength(to, List.of(unit), List.of(), false)) .reversed()) .limit(maxCanScramble) .forEachOrdered(addTo::add); } } } }</code><technical_language>type instead of var obvious</technical_language>

Target:
private static void findScrambleOptions( final PlayerId player, final Map<Territory, ProTerritory> moveMap) { final GameData data = ProData.getData(); if (!Properties.getScrambleRulesInEffect(data)) { return; } final var scrambleLogic = new ScrambleLogic(data, player, moveMap.keySet()); for (final var territoryToScramblersEntry : scrambleLogic.getUnitsThatCanScrambleByDestination().entrySet()) { final Territory to = territoryToScramblersEntry.getKey(); for (final Tuple<Collection<Unit>, Collection<Unit>> airbasesAndScramblers : territoryToScramblersEntry.getValue().values()) { final Collection<Unit> airbases = airbasesAndScramblers.getFirst(); final Collection<Unit> scramblers = airbasesAndScramblers.getSecond(); final int maxCanScramble = ScrambleLogic.getMaxScrambleCount(airbases); final List<Unit> addTo = moveMap.get(to).getMaxScrambleUnits(); if (scramblers.size() <= maxCanScramble) { addTo.addAll(scramblers); } else { scramblers.stream() .sorted( Comparator.<Unit>comparingDouble( unit -> ProBattleUtils.estimateStrength(to, List.of(unit), List.of(), false)) .reversed()) .limit(maxCanScramble) .forEachOrdered(addTo::add); } } } }
Source:
<code>public PojoWithCollections(Collection fieldCollection, List fieldList, Set fieldSet) { <START> super(); <END> this.fieldCollection = fieldCollection; this.fieldList = fieldList; this.fieldSet = fieldSet; }</code><technical_language>redundant call super(); automatically inserted compiler. this class is child of Object</technical_language>

Target:
public PojoWithCollections(Collection fieldCollection, List fieldList, Set fieldSet) { this.fieldCollection = fieldCollection; this.fieldList = fieldList; this.fieldSet = fieldSet; }
Source:
<code>private static boolean isDuplicatedByStarImport(FullIdent starImp, FullIdent imp) { final String importSplitRegexp = "\\."; final String[] impSplitted = imp.getText().split(importSplitRegexp); final String[] starImpSplited = starImp.getText().split(importSplitRegexp); boolean isEquals = true; if (impSplitted.length == starImpSplited.length) { <START> for (int i = 0; i < impSplitted.length - 1 && isEquals; i++) { <END> isEquals = impSplitted[i].equals(starImpSplited[i]); } } else { isEquals = false; } return isEquals; }</code><technical_language>Is do split do lastIndexOf check for string equality way. faster especially regular expression split</technical_language>

Target:
private static boolean isDuplicatedByStarImport(FullIdent starImp, FullIdent imp) { final String impText = imp.getText(); final String starImpText = starImp.getText(); final int impLastDotIndex = impText.lastIndexOf('.'); final int starImpLastDotIndex = starImpText.lastIndexOf('.'); return impLastDotIndex == starImpLastDotIndex && impText.regionMatches(0, starImpText, 0, impLastDotIndex); }
Source:
<code>default void testEmptyMetadata() { ConnectorSession session = new TestingConnectorSession(ImmutableList.of()); <START> run(ImmutableList.of( <END> metadata -> assertEquals(metadata.listSchemaNames(session), systemSchemas()), metadata -> assertEquals(metadata.listTables(session, null), ImmutableList.of()))); }</code><technical_language>do need run method. use: withMetadata(metadata -> { assertEquals(metadata.listSchemaNames(session), systemSchemas()); assertEquals(metadata.listTables(session, null), ImmutableList.of()); }); cleaner IMO</technical_language>

Target:
default void testEmptyMetadata() throws Exception { ConnectorSession session = new TestingConnectorSession(ImmutableList.of()); withMetadata( ImmutableList.of( metadata -> assertEquals(metadata.listSchemaNames(session), systemSchemas()), metadata -> assertEquals(metadata.listTables(session, null), systemTables()))); }
Source:
<code>public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { assertValidBean(bean, beanName); final Environment environment = applicationContext.getBean(Environment.class); doWithFields(bean.getClass(), field -> { final TenantValue annotation = findAnnotation(field, TenantValue.class); final Object value = HELPER.replacePlaceholders(annotation.value(), placeholderName -> { final Tenant tenant = TenancyContextHolder.getContext().getTenant(); final String tenantId = String.valueOf(tenant.getIdentity()); final String configurationKey = tenantId + "." + placeholderName; LOGGER.debug("Looking for configuration key '{}' for tenant '{}'", placeholderName, tenantId); <START> LOGGER.debug("Resolved tenant configuration key '{}'", configurationKey); <END> return environment.getProperty(configurationKey); }); makeAccessible(field); setField(field, bean, value); }, f -> findAnnotation(f, TenantValue.class) != null ); return bean; }</code><technical_language>strange message for processing in-between. log moved line 71</technical_language>

Target:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }
Source:
<code>public BrooklynUserWithRandomPasswordSecurityProvider() { this.password = Identifiers.makeRandomId(10); <START> LOG.info("Allowing access to web console from localhost or with {}:{}", USER, password); <END> }</code><technical_language>I if this a sysout, a log. If a sysout, done caller passing in user+password. strong feelings. Wording improved if "or auto-generated username password {}:{}"</technical_language>

Target:
public BrooklynUserWithRandomPasswordSecurityProvider() { this.password = Identifiers.makeRandomId(10); LOG.warn("Allowing access to web console from localhost or with auto-generated username and password {}:{}", USER, password); }
Source:
<code>public NodeMetadata apply(Droplet input) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(String.valueOf(input.getId())); builder.name(input.getName()); builder.hostname(input.getName()); builder.group(groupNamingConvention.extractGroup(input.getName())); builder.hardware(hardwares.get().get(String.valueOf(input.getSizeId()))); final String regionIdPattern = input.getRegionId() + "/"; <START> builder.location(find(locations.get(), new Predicate<Location>() { <END> @Override public boolean apply(Location location) { return location.getDescription().startsWith(regionIdPattern); } })); Image image = images.get().get(String.valueOf(input.getImageId())); builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); builder.status(toPortableStatus.apply(input.getStatus())); builder.backendStatus(input.getStatus().name()); if (input.getIp() != null) { builder.publicAddresses(ImmutableSet.of(input.getIp())); } if (input.getPrivateIp() != null) { builder.privateAddresses(ImmutableSet.of(input.getPrivateIp())); } Credentials credentials = credentialStore.get("node#" + input.getId()); if (credentials != null && credentials instanceof LoginCredentials) { builder.credentials(LoginCredentials.class.cast(credentials)); } return builder.build(); }</code><technical_language>This is intended blow if a location exist? happen</technical_language>

Target:
public NodeMetadata apply(Droplet input) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(String.valueOf(input.getId())); builder.name(input.getName()); builder.hostname(input.getName()); builder.group(groupNamingConvention.extractGroup(input.getName())); builder.hardware(hardwares.get().get(String.valueOf(input.getSizeId()))); final String regionIdPattern = input.getRegionId() + "/"; builder.location(find(locations.get(), new Predicate<Location>() { @Override public boolean apply(Location location) { return location.getDescription().startsWith(regionIdPattern); } })); Image image = images.get().get(String.valueOf(input.getImageId())); builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); builder.status(toPortableStatus.apply(input.getStatus())); builder.backendStatus(input.getStatus().name()); if (input.getIp() != null) { builder.publicAddresses(ImmutableSet.of(input.getIp())); } if (input.getPrivateIp() != null) { builder.privateAddresses(ImmutableSet.of(input.getPrivateIp())); } Credentials credentials = credentialStore.get("node#" + input.getId()); if (credentials instanceof LoginCredentials) { builder.credentials(LoginCredentials.class.cast(credentials)); } return builder.build(); }
Source:
<code>public ResultSet<ContextualStatistics> execute() { Map<Context, ContextualStatistics> contextualStatistics = new LinkedHashMap<Context, ContextualStatistics>(contexts.size()); Collection<ManagementProvider<?>> managementProviders = capabilityManagement.getManagementProvidersByCapability(capabilityName); for (Context context : contexts) { <START> Map<String, Statistic<? extends Serializable>> statistics = new HashMap<>(); <END> for (ManagementProvider<?> managementProvider : managementProviders) { if (managementProvider.supports(context)) { statistics.putAll(managementProvider.collectStatistics(context, statisticNames)); } } contextualStatistics.put(context, new ContextualStatistics(capabilityName, context, statistics)); } return new DefaultResultSet<>(contextualStatistics); }</code><technical_language>Size contexts size</technical_language>

Target:
public ResultSet<ContextualStatistics> execute() { Map<Context, ContextualStatistics> contextualStatistics = new LinkedHashMap<Context, ContextualStatistics>(contexts.size()); Collection<ManagementProvider<?>> managementProviders = capabilityManagement.getManagementProvidersByCapability(capabilityName); for (Context context : contexts) { Map<String, Statistic<? extends Serializable>> statistics = null; for (ManagementProvider<?> managementProvider : managementProviders) { if (managementProvider.supports(context)) { if (statistics == null) { statistics = managementProvider.collectStatistics(context, statisticNames); } else { statistics.putAll(managementProvider.collectStatistics(context, statisticNames)); } } } contextualStatistics.put(context, new ContextualStatistics(capabilityName, context, statistics == null ? Collections.emptyMap() : statistics)); } return new DefaultResultSet<>(contextualStatistics); }
Source:
<code>private void updateHosts() { for (VdsStatic vdsStatic : <START> vdsStaticDao.getAllForCluster(getCluster().getId())) <END> { vdsStaticDao.updateVdsNeedsReinstall(vdsStatic.getId(), true); } }</code><technical_language>fetch store of cluster's hosts in 'allForCluster'. needed for this call is hosts' ids, reuse collection save fetch of hosts again, spare new dependency VdsStatisDao</technical_language>

Target:
private void updateHosts() { for (VDS vds : allForCluster) { vdsStaticDao.updateReinstallRequired(vds.getId(), true); } }
Source:
<code>boolean getPixel(int row, int column) { <START> if (row < 0 || column < 9 || row >= height || column >= height) return false; <END> return this.shape[row*width + column]; }</code><technical_language>brackets if</technical_language>

Target:
public boolean getPixel(int row, int column) { if (row < 0 || column < 9 || row >= this.height || column >= this.height) { return false; } return this.shape[row * this.width + column]; }
Source:
<code>public List<ServerComponentHealth> getResponses(String componentType, String componentScope, String componentInputs, DiagnosticsAware component) { List<String> hosts = getLiveInstances(); StringArray statues = new StringArray(); StringArray statuesDetails = new StringArray(); for (String hostName : hosts) { ServerComponentHealthRestClient restClient = null; try { String dmsUri = getDmsUri(hostName); LOG.info("Send restli status request to " + dmsUri); restClient = ServerComponentHealthRestClientFactory.getClient(dmsUri, Collections.singletonMap( HttpClientFactory.HTTP_REQUEST_TIMEOUT, HTTP_TIMEOUT)); List<ServerComponentHealth> response = <START> restClient.getServerComponentHealthStatues(componentType, componentScope, componentInputs); <END> if (response == null) { statues.add(DiagnosticsAware.UNHEALTHY_STATUS); String errorMessage = "No restli response from the host: " + dmsUri; LOG.error(errorMessage); statuesDetails.add(errorMessage); } else { if (!response.isEmpty()) { statues.add(response.get(0).getStatus()); if (!response.get(0).getStatusDetail().isEmpty()) { statuesDetails.add(response.get(0).getStatusDetail().get(0)); } else { LOG.error("Empty restli statusDetail response from the host: " + dmsUri); } } else { LOG.error("Empty restli status response from the host: " + dmsUri); } } } finally { if (restClient != null) { restClient.shutdown(); } } } ServerComponentHealth serverComponentHealth = new ServerComponentHealth(); serverComponentHealth.setStatus(component.mergeStatus(statues)); serverComponentHealth.setStatusDetail(component.mergeStatusDetail(statuesDetails)); serverComponentHealth.setName(componentScope + componentType); return Arrays.asList(serverComponentHealth); }</code><technical_language>similarly, if expose API return ServerComponentHealth, need lots of "get(0)"</technical_language>

Target:
public List<ServerComponentHealth> getResponses(String componentType, String componentScope, String componentInputs, DiagnosticsAware component) { List<String> hosts = getLiveInstances(); ConcurrentMap<String, String> responses = new ConcurrentHashMap<>(); hosts.parallelStream().forEach(hostName -> { ServerComponentHealthRestClient restClient = null; try { String dmsUri = getDmsUri(hostName); LOG.info("Send restli status request to " + dmsUri); restClient = ServerComponentHealthRestClientFactory.getClient(dmsUri, Collections.singletonMap( HttpClientFactory.HTTP_REQUEST_TIMEOUT, HTTP_TIMEOUT)); ServerComponentHealth response = restClient.getStatus(componentType, componentScope, componentInputs); if (response == null) { String errorMessage = "No restli response from the host: " + dmsUri; LOG.error(errorMessage); responses.put(hostName, errorMessage); } else { String message = "Get restli response from the host: " + dmsUri + " with status: " + response.getStatus(); LOG.info(message); responses.put(hostName, response.getStatus()); } } finally { if (restClient != null) { restClient.shutdown(); } } }); ServerComponentHealth serverComponentHealth = new ServerComponentHealth(); serverComponentHealth.setStatus(component.reduce(componentInputs, responses)); return Arrays.asList(serverComponentHealth); }