auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<EmailWrapper> generateFeedbackSessionReminderEmails( FeedbackSessionAttributes session, List<StudentAttributes> students, List<InstructorAttributes> instructorsToRemind, List<InstructorAttributes> instructorsToNotify) { CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); String template = EmailTemplates.USER_FEEDBACK_SESSION; List<EmailWrapper> emails = generateFeedbackSessionEmailBasesForInstructorReminders(course, session, instructorsToRemind, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject()); emails.addAll(generateFeedbackSessionEmailBases(course, session, students, instructorsToNotify, <START> template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject())); <END> for (EmailWrapper email : emails) { email.setContent(email.getContent().replace("${status}", "is still open for submissions")); } return emails; }</code><technical_language>Revert changes here</technical_language>

Target:
public List<EmailWrapper> generateFeedbackSessionReminderEmails( FeedbackSessionAttributes session, List<StudentAttributes> students, List<InstructorAttributes> instructorsToRemind, List<InstructorAttributes> instructorsToNotify) { CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); String template = EmailTemplates.USER_FEEDBACK_SESSION.replace("${status}", FEEDBACK_STATUS_SESSION_OPEN); List<EmailWrapper> emails = generateFeedbackSessionEmailBasesForInstructorReminders(course, session, instructorsToRemind, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject()); emails.addAll(generateFeedbackSessionEmailBases(course, session, students, instructorsToNotify, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject())); return emails; }
Source:
<code>public void serialize(ServiceItemLease lease, JsonGenerator writer, SerializerProvider serializerProvider) { try { writer.writeStartObject(); writer.writeStringField(Constants.Properties.ID, lease.getId()); writer.writeStringField(Constants.Properties.E_TAG, lease.getETag()); writer.writeStringField("LeaseToken", lease.getLeaseToken()); writer.writeStringField("ContinuationToken", lease.getContinuationToken()); writer.writeStringField("timestamp", lease.getTimestamp()); <START> writer.writeStringField("Owner", lease.getOwner()); <END> writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } }</code><technical_language>LeaseToken, ContinuationToken, Owner Camel case, timestamp, id, etag is expected? for Owner, timestamp, ContinuationToken, LeaseToken define constants</technical_language>

Target:
public void serialize(ServiceItemLease lease, JsonGenerator writer, SerializerProvider serializerProvider) { try { writer.writeStartObject(); writer.writeStringField(Constants.Properties.ID, lease.getId()); writer.writeStringField(Constants.Properties.E_TAG, lease.getETag()); writer.writeStringField(PROPERTY_NAME_LEASE_TOKEN, lease.getLeaseToken()); writer.writeStringField(PROPERTY_NAME_CONTINUATION_TOKEN, lease.getContinuationToken()); writer.writeStringField(PROPERTY_NAME_TIMESTAMP, lease.getTimestamp()); writer.writeStringField(PROPERTY_NAME_OWNER, lease.getOwner()); writer.writeEndObject(); } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
<code>protected String getVersion(KieServerMode mode) { <START> return mode.equals(KieServerMode.DEVELOPMENT) ? DEVELOPMENT_MODE_VERSION : REGULAR_MODE_VERSION; <END> }</code><technical_language>Regular</technical_language>

Target:
protected String getVersion(KieServerMode mode) { return mode.equals(KieServerMode.DEVELOPMENT) ? DEVELOPMENT_MODE_VERSION : PRODUCTION_MODE_VERSION; }
Source:
<code><START> protected boolean togglePauseMenu(boolean pauseScreenOpened, Input input) { <END> if ((currentGame.isPaused() && pauseScreenOpened) || !(currentGame.isPaused() || pauseScreenOpened)) { Game.LOGGER.log(LogSeverity.DEBUG, "Game", "Player " + (currentGame.isPaused() ? "resumed" : "paused") + " the game"); input.disableKeyRepeat(); currentGame.setPaused(!currentGame.isPaused()); pauseScreenOpened = !pauseScreenOpened; } return pauseScreenOpened; }</code><technical_language>Passing <code>pauseScreenOpened</code> boolean is necessary, simply ask GameState this controller belongs for state, assuming pass constructor (instead of a game). < interface</technical_language>

Target:
protected boolean togglePauseMenu(boolean pauseScreenOpened, Input input) { if (currentGame.isPaused() && pauseScreenOpened || !(currentGame.isPaused() || pauseScreenOpened)) { Game.LOGGER.log(LogSeverity.DEBUG, "Game", "Player " + (currentGame.isPaused() ? "resumed" : "paused") + " the game"); input.disableKeyRepeat(); currentGame.setPaused(!currentGame.isPaused()); pauseScreenOpened = !pauseScreenOpened; } return pauseScreenOpened; }
Source:
<code>private void updateHigherWaterMark(long msgId) { if (msgId < higerWaterMark.get()) { return; } while(true) { long old = higerWaterMark.get(); <START> if (higerWaterMark.compareAndSet(old, msgId)) { <END> break; } } }</code><technical_language>checking msgId is risks making higher watermark move</technical_language>

Target:
private void updateHigherWaterMark(long msgId) { while(true) { long old = higherWaterMark.get(); if (msgId < old) { return; } if (higherWaterMark.compareAndSet(old, msgId)) { break; } } }
Source:
<code><START> protected void initialize(String fileName) { <END> if (fileSystemPersistenceProvider == null) { fileSystemPersistenceProvider = new FileSystemPersistenceProvider(getClass().getSimpleName()); } if (jsonSerializer == null) { jsonSerializer = new JsonPersistantStore(getClass().getSimpleName()); } if (observer == null && fileName != null) { observer = AsyncFileAlterationObserver.load(new File(fileName), jsonSerializer); if (observer == null && isOldVersion(fileName)) { observer = backwardsCompatibility(fileName); } else { observer = new AsyncFileAlterationObserver(new File(fileName), jsonSerializer); } } }</code><technical_language>reason for creating fileSystemPersistenceProvider jsonSerializer in constructor instead of this checking for null</technical_language>

Target:
protected void initialize(String fileName) { if (fileSystemPersistenceProvider == null) { fileSystemPersistenceProvider = new FileSystemPersistenceProvider(getClass().getSimpleName()); } if (jsonSerializer == null) { jsonSerializer = new JsonPersistantStore(getClass().getSimpleName()); } if (observer == null && fileName != null) { observer = AsyncFileAlterationObserver.load(new File(fileName), jsonSerializer); if (observer == null && isOldVersion(fileName)) { observer = backwardsCompatibility(fileName); } else if (observer == null) { observer = new AsyncFileAlterationObserver(new File(fileName), jsonSerializer); } } }
Source:
<code>private Configuration getConfigurationWithContext(String pidWithContext) throws IOException, InvalidSyntaxException { if (!pidWithContext.contains(ConfigConstants.SERVICE_CONTEXT_MARKER)) { throw new IllegalArgumentException("Given PID should be followed by a context"); } String pid = pidWithContext.split(ConfigConstants.SERVICE_CONTEXT_MARKER)[0]; String context = pidWithContext.split(ConfigConstants.SERVICE_CONTEXT_MARKER)[1]; Configuration[] configs = configAdmin.listConfigurations( <START> "(&(service.factoryPid=" + pid + ")(" + ConfigConstants.SERVICE_CONTEXT + "=" + context + "))"); <END> if (configs == null || configs.length == 0) { return null; } Configuration configuration = configs[0]; if (configs.length > 1) { logger.error("More than one configuration with PID '{}' exists, using entry '{}'.", pidWithContext, configuration.getProperties().get(Constants.SERVICE_PID)); } return configuration; }</code><technical_language>service.factoryPid -> ConfigurationAdmin.SERVICE_FACTORYPID</technical_language>

Target:
private Configuration getConfigurationWithContext(String pidWithContext) throws IOException, InvalidSyntaxException { if (!pidWithContext.contains(ConfigConstants.SERVICE_CONTEXT_MARKER)) { throw new IllegalArgumentException("Given PID should be followed by a context"); } String pid = pidWithContext.split(ConfigConstants.SERVICE_CONTEXT_MARKER)[0]; String context = pidWithContext.split(ConfigConstants.SERVICE_CONTEXT_MARKER)[1]; Configuration[] configs = configAdmin.listConfigurations("(&(" + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + pid + ")(" + ConfigConstants.SERVICE_CONTEXT + "=" + context + "))"); if (configs == null || configs.length == 0) { return null; } Configuration configuration = configs[0]; if (configs.length > 1) { logger.error("More than one configuration with PID '{}' exists, using entry '{}'.", pidWithContext, configuration.getProperties().get(Constants.SERVICE_PID)); } return configuration; }
Source:
<code>public void testStoreAndQueryCorrelationsInclude() { Trace trace1 = new Trace(); trace1.setId("1"); <START> trace1.setStartTime(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis()) - 4000); <END> CorrelationIdentifier cid = new CorrelationIdentifier(); cid.setScope(Scope.ControlFlow); cid.setValue("myid"); Consumer c1 = new Consumer(); c1.getCorrelationIds().add(cid); trace1.getNodes().add(c1); List<Trace> traces = new ArrayList<Trace>(); traces.add(trace1); try { tracePublisher.publish(null, traces); } catch (Exception e1) { fail("Failed to store: " + e1); } Criteria criteria = new Criteria(); criteria.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, "myid")); Wait.until(() -> traceService.searchFragments(null, criteria).size() == 1); List<Trace> result = traceService.searchFragments(null, criteria); assertEquals(1, result.size()); assertEquals("1", result.get(0).getId()); }</code><technical_language>4000 -> FOUR_MS_IN_MICRO_SEC</technical_language>

Target:
public void testStoreAndQueryCorrelationsInclude() { Trace trace1 = new Trace(); trace1.setId("1"); trace1.setStartTime(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis()) - FOUR_MS_IN_MICRO_SEC); CorrelationIdentifier cid = new CorrelationIdentifier(); cid.setScope(Scope.ControlFlow); cid.setValue("myid"); Consumer c1 = new Consumer(); c1.getCorrelationIds().add(cid); trace1.getNodes().add(c1); List<Trace> traces = new ArrayList<Trace>(); traces.add(trace1); try { tracePublisher.publish(null, traces); } catch (Exception e1) { fail("Failed to store: " + e1); } Criteria criteria = new Criteria(); criteria.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, "myid")); Wait.until(() -> traceService.searchFragments(null, criteria).size() == 1); List<Trace> result = traceService.searchFragments(null, criteria); assertEquals(1, result.size()); assertEquals("1", result.get(0).getId()); }
Source:
<code>public void startApp() { try { platformRequest("x-contacts:add?number=+393333333333"); } catch (ConnectionNotFoundException e) { System.out.println("Error while adding contact"); <START> } <END> }</code><technical_language>Nit: if call throw exception, this print a "success" message</technical_language>

Target:
public void startApp() { try { platformRequest("x-contacts:add?number=+393333333333"); System.out.println("Success"); } catch (ConnectionNotFoundException e) { System.out.println("Error while adding contact"); } }
Source:
<code>@Override protected Void doInBackground(Integer... params) { if (params.length != 2) <START> throw new IllegalArgumentException("MKCollectorResubmitTask require 2 nullable params: result_id, measurement_id"); <END> List<Measurement> measurements = MeasurementDao.queryList(params[0], params[1], false, false); for (int i = 0; i < measurements.size() && getActivity() != null; i++) { publishProgress(getActivity().getString(R.string.Modal_ResultsNotUploaded_Uploading, getActivity().getString(R.string.paramOfParam, Integer.toString(i + 1), Integer.toString(measurements.size())))); Measurement m = measurements.get(i); m.result.load(); try { perform(getActivity(), m); } catch (IOException e) { e.printStackTrace(); } } return null; }</code><technical_language>Typo: require => requires</technical_language>

Target:
@Override protected Void doInBackground(Integer... params) { if (params.length != 2) throw new IllegalArgumentException("MKCollectorResubmitTask requires 2 nullable params: result_id, measurement_id"); Where<Measurement> msmQuery = SQLite.select().from(Measurement.class) .where(Measurement_Table.is_failed.eq(false)) .and(OperatorGroup.clause() .or(Measurement_Table.is_uploaded.eq(false)) .or(Measurement_Table.report_id.isNull())); if (params[0] != null) { msmQuery.and(Measurement_Table.result_id.eq(params[0])); } if (params[1] != null) { msmQuery.and(Measurement_Table.id.eq(params[1])); } List<Measurement> measurements = msmQuery.queryList(); for (int i = 0; i < measurements.size(); i++) { A activity = getActivity(); if (activity == null) break; String paramOfParam = activity.getString(R.string.paramOfParam, Integer.toString(i + 1), Integer.toString(measurements.size())); publishProgress(activity.getString(R.string.Modal_ResultsNotUploaded_Uploading, paramOfParam)); Measurement m = measurements.get(i); m.result.load(); try { perform(activity, m); } catch (IOException e) { e.printStackTrace(); } } return null; }
Source:
<code>public String getXRegistryAuthHeaderValue(@Nullable String registry, @Nullable AuthConfigs paramAuthConfigs) { if (DEFAULT_REGISTRY_SYNONYMS.contains(registry)) { registry = DEFAULT_REGISTRY; } AuthConfig authConfig = null; if (paramAuthConfigs != null && paramAuthConfigs.getConfigs() != null) { <START> normalizeDockerHubRegistryUrl(paramAuthConfigs.getConfigs()); <END> authConfig = paramAuthConfigs.getConfigs().get(registry); } if (authConfig == null) { normalizeDockerHubRegistryUrl(initialAuthConfig.getAuthConfigs().getConfigs()); authConfig = initialAuthConfig.getAuthConfigs().getConfigs().get(registry); } String authConfigJson; if (authConfig == null) { authConfigJson = "{}"; } else { authConfigJson = JsonHelper.toJson(authConfig); } return Base64.getEncoder().encodeToString(authConfigJson.getBytes()); }</code><technical_language>change arguments</technical_language>

Target:
public String getXRegistryAuthHeaderValue(@Nullable String registry, @Nullable AuthConfigs paramAuthConfigs) { String normalizedRegistry = DEFAULT_REGISTRY_SYNONYMS.contains(registry) ? DEFAULT_REGISTRY : registry; AuthConfig authConfig = null; if (paramAuthConfigs != null && paramAuthConfigs.getConfigs() != null) { authConfig = normalizeDockerHubRegistryUrl(paramAuthConfigs.getConfigs()).get(normalizedRegistry); } if (authConfig == null) { authConfig = normalizeDockerHubRegistryUrl(initialAuthConfig.getAuthConfigs().getConfigs()).get(normalizedRegistry); } String authConfigJson; if (authConfig == null) { authConfigJson = "{}"; } else { authConfigJson = JsonHelper.toJson(authConfig); } return Base64.getEncoder().encodeToString(authConfigJson.getBytes()); }
Source:
<code>public ProjectQualityGate getQualityGateMeasures() throws Exception { String url = serverUrl + API_MEASURES + <START> "?componentKey=" + projectKey + <END> "&metricKeys=alert_status"; String text = client.getHttp(url, username, password); JSONObject json = (JSONObject) JSONSerializer.toJSON(text); if (json.containsKey("errors")) { throw new MessageException(parseError(json)); } JSONObject component = json.getJSONObject("component"); String projectName = component.getString("name"); JSONArray measuresArray = component.getJSONArray("measures"); for (Object o : measuresArray) { JSONObject jsonObj = (JSONObject) o; String metric = jsonObj.getString("metric"); if ("alert_status".equals(metric)) { return new ProjectQualityGate(projectName, jsonObj.getString("value")); } } return null; }</code><technical_language>URL Encode</technical_language>

Target:
public ProjectQualityGate getQualityGateMeasures() throws Exception { String url = serverUrl + API_MEASURES + encode(projectKey); String text = client.getHttp(url, username, password); JSONObject json = (JSONObject) JSONSerializer.toJSON(text); if (json.containsKey("errors")) { throw new MessageException(parseError(json)); } JSONObject component = json.getJSONObject("component"); String projectName = component.getString("name"); JSONArray measuresArray = component.getJSONArray("measures"); for (Object o : measuresArray) { JSONObject jsonObj = (JSONObject) o; String metric = jsonObj.getString("metric"); if ("alert_status".equals(metric)) { return new ProjectQualityGate(projectName, jsonObj.getString("value")); } } return null; }
Source:
<code>public Node visitSpecialDateTimeFunction(SqlBaseParser.SpecialDateTimeFunctionContext context) { <START> CurrentTime.Operation operation = getDateTimeFunctionType(context.name); <END> if (context.precision != null) { return new CurrentTime(getLocation(context), operation, Integer.parseInt(context.precision.getText())); } return new CurrentTime(getLocation(context), operation); }</code><technical_language>Commit message wrong. is Operation Function</technical_language>

Target:
public Node visitSpecialDateTimeFunction(SqlBaseParser.SpecialDateTimeFunctionContext context) { CurrentTime.Function function = getDateTimeFunctionType(context.name); if (context.precision != null) { return new CurrentTime(getLocation(context), function, Integer.parseInt(context.precision.getText())); } return new CurrentTime(getLocation(context), function); }
Source:
<code>public Condition getCondition(String uuid) { List<String> errors = new ArrayList<>(); org.openmrs.Condition condition = Context.getService(ConditionService.class).getConditionByUuid(uuid); if (condition == null) { errors.add("Condition with given uuid doesn't exits"); return null; } <START> FHIRUtils.checkGeneratorErrorList(errors); <END> return this.generateFHIRCondition(condition); }</code><technical_language>returning null condition null, do need checkGeneratorErrorList</technical_language>

Target:
public Condition getCondition(String uuid) { org.openmrs.Condition condition = Context.getService(ConditionService.class).getConditionByUuid(uuid); if (condition == null) { return null; } return this.generateFHIRCondition(condition); }
Source:
<code>protected void onResume() { super.onResume(); try { if (CommCareApplication._().getSession().isActive() && CommCareApplication._().getSession().getLoggedInUser() != null) { Intent i = new Intent(); i.putExtra(ALREADY_LOGGED_IN, true); setResult(RESULT_OK, i); CommCareApplication._().clearNotifications(NOTIFICATION_MESSAGE_LOGIN); finish(); return; } } catch (SessionUnavailableException sue) { } <START> if (CommCareApplication._().getReadyAppRecords().size() == 0) { <END> Intent i = new Intent(this, CommCareHomeActivity.class); startActivity(i); } refreshView(); }</code><technical_language>I this query more "is app seated (IE: Is a current app CommCareApplication._().getApp()" more "is app", right</technical_language>

Target:
protected void onResume() { super.onResume(); try { if (CommCareApplication._().getSession().isActive() && CommCareApplication._().getSession().getLoggedInUser() != null) { Intent i = new Intent(); i.putExtra(ALREADY_LOGGED_IN, true); setResult(RESULT_OK, i); CommCareApplication._().clearNotifications(NOTIFICATION_MESSAGE_LOGIN); finish(); return; } } catch (SessionUnavailableException sue) { } CommCareApp currentApp = CommCareApplication._().getCurrentApp(); if (currentApp == null || !currentApp.getAppRecord().isUsable()) { Intent i = new Intent(this, CommCareHomeActivity.class); startActivity(i); return; } refreshView(); }
Source:
<code>private synchronized FileSessionCredentialsProvider getUnderlyingProvider() { if (provider == null) { <START> provider = new FileSessionCredentialsProvider(config.getFileSessionCredentials()); <END> } return provider; }</code><technical_language>Please add @Nullable provider field</technical_language>

Target:
private FileSessionCredentialsProvider getUnderlyingProvider() { FileSessionCredentialsProvider syncedProvider = provider; if (syncedProvider == null) { synchronized (config) { syncedProvider = provider; if (syncedProvider == null) { syncedProvider = new FileSessionCredentialsProvider(config.getFileSessionCredentials()); provider = syncedProvider; } } } return syncedProvider; }
Source:
<code>public Task getMySchritt() { try { <START> loadStepByParameter(); <END> } catch (DAOException | NumberFormatException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } return this.mySchritt; }</code><technical_language>Small remark: decided translate schritt task</technical_language>

Target:
public Task getMySchritt() { try { loadTaskByParameter(); } catch (DAOException | NumberFormatException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } return this.mySchritt; }
Source:
<code>protected ContainerDelegate initializeProxy(Object delegate) { if (this.getAdviceChain().length == 0) { return null; } ProxyFactory factory = new ProxyFactory(); for (Advice advice : getAdviceChain()) { <START> factory.addAdvisor(new DefaultPointcutAdvisor(Pointcut.TRUE, advice)); <END> } factory.setProxyTargetClass(false); factory.addInterface(ContainerDelegate.class); factory.setTarget(delegate); return (ContainerDelegate) factory.getProxy(ContainerDelegate.class.getClassLoader()); }</code><technical_language>This is redundant. Another ctor that: public DefaultPointcutAdvisor(Advice advice) { this(Pointcut.TRUE, advice); }</technical_language>

Target:
protected void initializeProxy(Object delegate) { if (this.getAdviceChain().length == 0) { return; } ProxyFactory factory = new ProxyFactory(); for (Advice advice : getAdviceChain()) { factory.addAdvisor(new DefaultPointcutAdvisor(advice)); } factory.addInterface(ContainerDelegate.class); factory.setTarget(delegate); this.proxy = (ContainerDelegate) factory.getProxy(ContainerDelegate.class.getClassLoader()); }
Source:
<code>public Map<String, Set<ExecutableElement>> setters() { <START> return Maps.transformValues(setters.asMap(), Sets::newHashSet); <END> }</code><technical_language>Move constructor? do a defensive copy front-load this work instead</technical_language>

Target:
public Map<String, Set<ExecutableElement>> setters() { return setters; }
Source:
<code><START> private static void addPropertyVariableToResult(Collection<Pair<Object, String>> result, String element) { <END> if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } }</code><technical_language>I this method need static</technical_language>

Target:
private void addPropertyVariableToResult(Collection<Pair<Object, String>> result, String element) { if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } }
Source:
<code>public void loadCentersInOffice(int id, Map<String, Object> params) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getCentersInOffice(id, params) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Center>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); <START> try { <END> if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(List<Center> centers) { getMvpView().showProgressbar(false); getMvpView().showCentersInOffice(centers); } })); }</code><technical_language>this utils method show error <LINK_0></technical_language>

Target:
public void loadCentersInOffice(int id, Map<String, Object> params) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getCentersInOffice(id, params) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Center>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(List<Center> centers) { getMvpView().showProgressbar(false); getMvpView().showCentersInOffice(centers); } })); }
Source:
<code>public void deleteWireConfiguration(final WireConfiguration wireConfiguration) { requireNonNull(wireConfiguration, message.wireConfigurationNonNull()); logger.info(message.removingWires()); try { final Wire[] wiresList = this.wireAdmin.getWires(null); if (wiresList != null) { for (final Wire wire : wiresList) { final Dictionary<?, ?> props = wire.getProperties(); final String producerPid = props.get(WIREADMIN_PRODUCER_PID).toString(); final String consumerPid = props.get(WIREADMIN_CONSUMER_PID).toString(); final String emitterFactoryPid = this.wireHelperService .getServicePid(wireConfiguration.getEmitterPid()); final String receiverFactoryPid = this.wireHelperService .getServicePid(wireConfiguration.getReceiverPid()); if (emitterFactoryPid != null && receiverFactoryPid != null && producerPid.equals(emitterFactoryPid) && consumerPid.equals(receiverFactoryPid)) { synchronized (this.wireConfigs) { for (final Iterator<WireConfiguration> iter = this.wireConfigs.iterator(); iter .hasNext();) { final WireConfiguration configuration = iter.next(); if (configuration.equals(wireConfiguration)) { iter.remove(); this.wireAdmin.deleteWire(wire); break; } } } } } } } catch (final InvalidSyntaxException e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); <START> throw new KuraRuntimeException(KuraErrorCode.INTERNAL_ERROR, sw.toString()); <END> } logger.info(message.removingWiresDone()); }</code><technical_language>DRY - Do repeat yourself. I prefer ThrowableUtil used. Do drop it. is proven useful</technical_language>

Target:
public void deleteWireConfiguration(final WireConfiguration wireConfiguration) { requireNonNull(wireConfiguration, message.wireConfigurationNonNull()); logger.info(message.removingWires()); try { final Wire[] wiresList = this.wireAdmin.getWires(wireConfiguration.getFilter()); if (wiresList != null) { for (final Wire wire : wiresList) { final Dictionary<?, ?> props = wire.getProperties(); final String producerPid = props.get(WIREADMIN_PRODUCER_PID).toString(); final String consumerPid = props.get(WIREADMIN_CONSUMER_PID).toString(); final String emitterFactoryPid = this.wireHelperService .getServicePid(wireConfiguration.getEmitterPid()); final String receiverFactoryPid = this.wireHelperService .getServicePid(wireConfiguration.getReceiverPid()); if (emitterFactoryPid != null && receiverFactoryPid != null && producerPid.equals(emitterFactoryPid) && consumerPid.equals(receiverFactoryPid)) { synchronized (this.wireConfigs) { for (final Iterator<WireConfiguration> iter = this.wireConfigs.iterator(); iter .hasNext();) { final WireConfiguration configuration = iter.next(); if (configuration.equals(wireConfiguration)) { iter.remove(); this.wireAdmin.deleteWire(wire); break; } } } } } } } catch (final InvalidSyntaxException e) { throw new IllegalArgumentException(e); } logger.info(message.removingWiresDone()); }
Source:
<code>protected CollectionRest createAndReturn(Context context) throws AuthorizeException { <START> throw new DSpaceBadRequestException("Missing parent parameter."); <END> }</code><technical_language>While this error message is accurate, odd in this class (as parent param in CollectionRestRepository anymore. So, I reword this slightly like: "Cannot create a Collection providing a parent Community"</technical_language>

Target:
protected CollectionRest createAndReturn(Context context) throws AuthorizeException { throw new DSpaceBadRequestException("Cannot create a Collection without providing a parent Community."); }
Source:
<code>public void shouldGetDivOfLogicalStructMapFromExistingFile() throws DatatypeConfigurationException, IOException, JAXBException, TransformerException { MetsKitodoWrapper metsKitodoWrapper = new MetsKitodoWrapper(xmlfile, xsltFile); DivType rootDiv = metsKitodoWrapper.getLogicalStructMap().getDiv(); DivType rootDivFromMets = metsKitodoWrapper.getMets().getStructMap().get(1).getDiv(); MetsKitodoWriter writer = new MetsKitodoWriter(); <START> System.out.println(writer.writeSerializedToString(metsKitodoWrapper.getMets())); <END> Assert.assertEquals("Div elements from getter and directly from mets objects were not the same", rootDiv, rootDivFromMets); }</code><technical_language>Is this System.out.println call needed? If remove if this call is needed replace a logger call</technical_language>

Target:
public void shouldGetDivOfLogicalStructMapFromExistingFile() throws DatatypeConfigurationException, IOException, JAXBException, TransformerException { MetsKitodoWrapper metsKitodoWrapper = new MetsKitodoWrapper(xmlfile, xsltFile); DivType rootDiv = metsKitodoWrapper.getLogicalStructMap().getDiv(); DivType rootDivFromMets = metsKitodoWrapper.getMets().getStructMap().get(1).getDiv(); Assert.assertEquals("Div elements from getter and directly from mets objects were not the same", rootDiv, rootDivFromMets); }
Source:
<code>public void onTrainingStart(SyncTrainingEvent event) { try { dataManager.writeInfo(event.getLearning()); } catch (Exception e) { log.error("Training failed.", e); <START> e.printStackTrace(); <END> event.setCanContinue(false); } }</code><technical_language>print stack trace, log.error print it. other instances below</technical_language>

Target:
public ListenerResponse onTrainingStart(SyncTrainingEvent event) { try { dataManager.writeInfo(event.getLearning()); } catch (Exception e) { log.error("Training failed.", e); return ListenerResponse.STOP; } return ListenerResponse.CONTINUE; }
Source:
<code>protected <T extends LoginAPI> T getLoginAPI(Class<T> apiClass) { try { final ServerAPI serverAPI = getServerAPI(); <START> final ClientInterceptor interceptor = new ClientInterceptor(LoginAPI.class.getName(), serverAPI); <END> T result = (T) Proxy.newProxyInstance(APIAccessor.class.getClassLoader(), new Class[]{apiClass}, interceptor); return result; } catch (BonitaHomeNotSetException | ServerAPIException | UnknownAPITypeException e) { throw new IllegalStateException(e.getMessage(), e); } }</code><technical_language>apiClass.getName() instead of LoginAPI.class.getName()</technical_language>

Target:
protected <T extends LoginAPI> T getLoginAPI(Class<T> apiClass) { try { final ClientInterceptor interceptor = new ClientInterceptor(apiClass.getName(), getServerAPI()); @SuppressWarnings("unchecked") final T api = (T) Proxy.newProxyInstance(APIAccessor.class.getClassLoader(), new Class[] { apiClass }, interceptor); return api; } catch (BonitaHomeNotSetException | ServerAPIException | UnknownAPITypeException e) { throw new IllegalStateException(e.getMessage(), e); } }
Source:
<code>public void initialize() { logger.debug("Initializing thing {}", getThing().getUID()); String thingUid = getThing().getUID().toString(); thingConfig = getConfigAs(AstroThingConfig.class); thingConfig.setThingUid(thingUid); boolean validConfig = true; <START> logger.debug("Initializing Scheduler for thing {}", getThing().getUID()); <END> if (StringUtils.trimToNull(thingConfig.getGeolocation()) == null) { logger.error("Astro parameter geolocation is mandatory and must be configured, disabling thing '{}'", thingUid); validConfig = false; } else { thingConfig.parseGeoLocation(); } if (thingConfig.getLatitude() == null || thingConfig.getLongitude() == null) { logger.error( "Astro parameters geolocation could not be split into latitude and longitude, disabling thing '{}'", thingUid); validConfig = false; } if (thingConfig.getInterval() == null || thingConfig.getInterval() < 1 || thingConfig.getInterval() > 86400) { logger.error("Astro parameter interval must be in the range of 1-86400, disabling thing '{}'", thingUid); validConfig = false; } if (validConfig) { logger.debug("{}", thingConfig); updateStatus(ONLINE); restartJobs(); } else { updateStatus(OFFLINE); } logger.debug("Thing initialized {}", getThing().getUID(), getThing().getStatus()); }</code><technical_language>This is done constructor, please move this line</technical_language>

Target:
public void initialize() { logger.debug("Initializing thing {}", getThing().getUID()); String thingUid = getThing().getUID().toString(); thingConfig = getConfigAs(AstroThingConfig.class); thingConfig.setThingUid(thingUid); boolean validConfig = true; if (StringUtils.trimToNull(thingConfig.getGeolocation()) == null) { logger.error("Astro parameter geolocation is mandatory and must be configured, disabling thing '{}'", thingUid); validConfig = false; } else { thingConfig.parseGeoLocation(); } if (thingConfig.getLatitude() == null || thingConfig.getLongitude() == null) { logger.error( "Astro parameters geolocation could not be split into latitude and longitude, disabling thing '{}'", thingUid); validConfig = false; } if (thingConfig.getInterval() == null || thingConfig.getInterval() < 1 || thingConfig.getInterval() > 86400) { logger.error("Astro parameter interval must be in the range of 1-86400, disabling thing '{}'", thingUid); validConfig = false; } if (validConfig) { logger.debug("{}", thingConfig); updateStatus(ONLINE); restartJobs(); } else { updateStatus(OFFLINE); } logger.debug("Thing initialized {}", getThing().getUID(), getThing().getStatus()); }
Source:
<code>public void testTimestamp() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_time", "2014-10-02T15:01:23.045123456Z"); Notification notification = mpPushSpy.createNotification(intent); Instant instant = Instant.parse( "2011-05-03T11:58:01Z" ); <START> verify(builderSpy).setWhen(instant.toEpochMilli()); <END> }</code><technical_language>I understand this test. do set time "2014-10-02T15:01:23.045123456Z" verify set "2011-05-03T11:58:01Z"</technical_language>

Target:
public void testTimestamp() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_time", "2014-10-02T15:01:23.045123456Z"); Notification notification = mpPushSpy.createNotification(intent); Instant instant = Instant.parse( "2014-10-02T15:01:23.045123456Z" ); verify(builderSpy).setShowWhen(true); verify(builderSpy).setWhen(instant.toEpochMilli()); }
Source:
<code>protected final String retrievePasswordUsingProxyTicket(final String proxyTicket) { try { final String url = this.clearPassUrl + (this.clearPassUrl.contains("?") ? "&" : "?") + "ticket=" + proxyTicket; final String response = retrieveResponseFromServer(url, "UTF-8"); final String password = XmlUtils.getTextForElement(response, "credentials"); if (log.isTraceEnabled()) { log.trace(String.format("ClearPass Response was:\n %s", response)); } if (CommonUtils.isNotBlank(password)) { return password; } log.error("Unable to Retrieve Password. If you see a [403] HTTP response code returned from" +" CommonUtils then it most likely means the proxy configuration on the CAS server is not" <START> + " correct.\n\nFull Response from ClearPass was [" + response + "]."); <END> return null; } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Unable to retrieve the credential from the ClearPass " + "service for proxy ticket: " + proxyTicket, e); } return null; } }</code><technical_language><credentials> element blank, this ClearPass response end user's password, fine log raw response</technical_language>

Target:
protected final String retrievePasswordUsingProxyTicket(final String proxyTicket) { try { final String url = this.clearPassUrl + (this.clearPassUrl.contains("?") ? "&" : "?") + "ticket=" + proxyTicket; final String response = retrieveResponseFromServer(url, "UTF-8"); final String password = XmlUtils.getTextForElement(response, "credentials"); if (CommonUtils.isNotBlank(password)) { return password; } log.error("Unable to Retrieve Password using url {}. If you see a [403] HTTP response code returned from" +" CommonUtils then it most likely means the proxy configuration on the CAS server is not" + " correct.\n\nFull Response from ClearPass was [{}]", url, response); return null; } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Unable to retrieve the credential from the ClearPass " + "service for proxy ticket {}", proxyTicket, e); } return null; } }
Source:
<code>protected static void validatePageIfNotNull(String pageNumber, List<String> validationErrors) { <START> if (isNotBlank(pageNumber) && (!StringUtils.isNumeric(pageNumber) || Integer.valueOf(pageNumber) < 1)) { <END> validationErrors.add("page"); } }</code><technical_language>is a NumericValidator in PublicApi for this. If ask isNumeric, <LINK_0></technical_language>

Target:
protected static void validatePageIfNotNull(String pageNumber, List<String> validationErrors) { if (isNotBlank(pageNumber) && (!NumericValidator.isValid(pageNumber) || Integer.valueOf(pageNumber) < 1)) { validationErrors.add("page"); } }
Source:
<code>public void dragCentered(final String label, final Class<? extends EditPart> editPartClass, final int toXPosition, final int toYPosition) { final SWTBotGefEditPart selectedEP = <START> getEditPart(label, editPartClass); <END> if (selectedEP == null) { throw new WidgetNotFoundException(String.format(SWTBotSiriusDiagramEditor.EXPECTED_TO_FIND_WIDGET_S, label)); } final Rectangle bounds = ((GraphicalEditPart) selectedEP.part()).getFigure().getBounds(); drag(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2, toXPosition, toYPosition); }</code><technical_language>This is difference method above. factorize code</technical_language>

Target:
public void dragCentered(final String label, final Class<? extends EditPart> editPartClass, final int toXPosition, final int toYPosition) { final SWTBotGefEditPart selectedEP; if(editPartClass != null) { selectedEP = getEditPart(label, editPartClass); } else { selectedEP = getEditPart(label); } if (selectedEP == null) { throw new WidgetNotFoundException(String.format(SWTBotSiriusDiagramEditor.EXPECTED_TO_FIND_WIDGET_S, label)); } final Rectangle bounds = ((GraphicalEditPart) selectedEP.part()).getFigure().getBounds(); drag(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2, toXPosition, toYPosition); }
Source:
<code>public boolean discoverPatient(final PatientSearchBean patientQuerySearch) { final gov.hhs.fha.nhinc.patientdiscovery.model.Patient patientBean = new gov.hhs.fha.nhinc.patientdiscovery.model.Patient(); patientBean.setOrganization(patientQuerySearch.getOrganization()); final DateFormat df = new SimpleDateFormat(UTCDateUtil.DATE_ONLY_FORMAT); patientBean.setBirthDate(df.format(patientQuerySearch.getDateOfBirth())); patientBean.setFirstName(patientQuerySearch.getFirstName()); patientBean.setLastName(patientQuerySearch.getLastName()); patientBean.setGender(patientQuerySearch.getGender()); try { final PatientSearchResults patientDiscoveryResults = patientService.queryPatient(patientBean, assertion); LOG.debug("Patient Discovery call successful. Total number of patients found: {}", patientDiscoveryResults.getPatientList().size()); if (patientDiscoveryResults.getPatientList().isEmpty()) { return false; } <START> localCorrelation = correlationService.getLocalPatient(patientDiscoveryResults); <END> if(localCorrelation == null) { correlationService.queryForCorrelations(patientDiscoveryResults, assertion); localCorrelation = correlationService.getLocalPatient(patientDiscoveryResults.getPatientList().get(0).getCorrelations()); } if(localCorrelation == null) { localCorrelation = correlationService.addCorrelation(patientDiscoveryResults, assertion); } populatePatientBean(patientDiscoveryResults, patientQuerySearch); return true; } catch (final PatientSearchException ex) { LOG.error("Failed to Retrieve Patient Data: {}", ex.getLocalizedMessage(), ex); return false; } }</code><technical_language>I feel this bit of logic added implemented service itself. "retrieveOrCreateCorrelation" ensure return a local correlation if find in database, if not, created</technical_language>

Target:
public boolean discoverPatient(final PatientSearchBean patientQuerySearch) { final gov.hhs.fha.nhinc.patientdiscovery.model.Patient patientBean = new gov.hhs.fha.nhinc.patientdiscovery.model.Patient(); patientBean.setOrganization(patientQuerySearch.getOrganization()); final DateFormat df = new SimpleDateFormat(UTCDateUtil.DATE_ONLY_FORMAT); patientBean.setBirthDate(df.format(patientQuerySearch.getDateOfBirth())); patientBean.setFirstName(patientQuerySearch.getFirstName()); patientBean.setLastName(patientQuerySearch.getLastName()); patientBean.setGender(patientQuerySearch.getGender()); try { final PatientSearchResults patientDiscoveryResults = patientService.queryPatient(patientBean, assertion); LOG.debug("Patient Discovery call successful. Total number of patients found: {}", patientDiscoveryResults.getPatientList().size()); if (patientDiscoveryResults.getPatientList().isEmpty()) { return false; } localCorrelation = correlationService.retrieveOrGenerateCorrelation(patientDiscoveryResults, assertion); populatePatientBean(patientDiscoveryResults, patientQuerySearch); return true; } catch (final PatientSearchException ex) { LOG.error("Failed to Retrieve Patient Data: {}", ex.getLocalizedMessage(), ex); return false; } }
Source:
<code>public void killQuery(String queryHash) { lock.lock(); try { <START> runningQueries.get(queryHash).getSecond().interrupt(); END> } finally { lock.unlock(); } }</code><technical_language>need check for null get query finished call this kill it</technical_language>

Target:
public void killQuery(String queryHash) { lock.lock(); try { if (runningQueries.get(queryHash) != null) { runningQueries.get(queryHash).getSecond().interrupt(); } } finally { lock.unlock(); } }
Source:
<code>public Collection<?> <START> getStructuredContentProviderElements(EObject <END> self) { IStructuredItemContentProvider scp = getStructuredItemContentProvider(self); if (scp != null) { return scp.getElements(self); } else { return null; } }</code><technical_language>getStructuredItemContentProviderElements respect pattern</technical_language>

Target:
public Collection<?> getStructuredContentProviderElements(EObject self) { IStructuredItemContentProvider scp = getStructuredItemContentProviderElements(self); if (scp != null) { return scp.getElements(self); } else { return null; } }
Source:
<code>public void testMultipleStreamReads() throws Exception { <START> System.out.println("go time"); <END> String myMessage = "{this is my message: héÿ}\n"; byte[] bytes = myMessage.substring(0, myMessage.length()/2).getBytes(Charsets.UTF_8); byte[] bytes2 = myMessage.substring(myMessage.length()/2, myMessage.length()).getBytes(Charsets.UTF_8); InputStream miniStream = new ByteArrayInputStream(bytes); InputStream miniStream2 = new ByteArrayInputStream(bytes2); InputStream stream = new SplitInputStream(Lists.newArrayList(miniStream, miniStream2)); DelimitedStreamReader r = new DelimitedStreamReader(stream, Charsets.UTF_8, myMessage.length() / 3); String msg = r.read(myMessage.length()); assertEquals(msg, myMessage); }</code><technical_language>time println</technical_language>

Target:
public void testMultipleStreamReads() throws Exception { String myMessage = "{this is my message: héÿ}\n"; byte[] bytes = myMessage.substring(0, myMessage.length()/2).getBytes(Charsets.UTF_8); byte[] bytes2 = myMessage.substring(myMessage.length()/2, myMessage.length()).getBytes(Charsets.UTF_8); InputStream miniStream = new ByteArrayInputStream(bytes); InputStream miniStream2 = new ByteArrayInputStream(bytes2); InputStream stream = new SplitInputStream(Lists.newArrayList(miniStream, miniStream2)); DelimitedStreamReader r = new DelimitedStreamReader(stream, Charsets.UTF_8, myMessage.length() / 3); String msg = r.read(myMessage.length()); assertEquals(msg, myMessage); }
Source:
<code>public void testBatchBySize() throws Exception { BatchIterator<Integer> batchIterator = InMemoryBatchIterator.of(() -> IntStream.range(0, 5).iterator(), null, <START> true); <END> BatchIterator<List<Integer>> batchedIt = BatchIterators.partition(batchIterator, 2, ArrayList::new, List::add, r -> false); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(0, 1))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(2, 3))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Collections.singletonList(4))); }</code><technical_language>minor: iterators in this suite non-io bound</technical_language>

Target:
public void testBatchBySize() throws Exception { var batchIterator = InMemoryBatchIterator.of(() -> IntStream.range(0, 5).iterator(), null, false); BatchIterator<List<Integer>> batchedIt = BatchIterators.partition(batchIterator, 2, ArrayList::new, List::add, r -> false); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(0, 1))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Arrays.asList(2, 3))); assertThat(batchedIt.moveNext(), is(true)); assertThat(batchedIt.currentElement(), is(Collections.singletonList(4))); }
Source:
<code>public static SchedulingPolicy map(VDSGroup entity, SchedulingPolicy template) { SchedulingPolicy model = template != null ? template : new SchedulingPolicy(); if (entity.getClusterPolicyName() != null) { <START> model.setPolicy(entity.getClusterPolicyName()); <END> if (entity.getClusterPolicyProperties() != null && !entity.getClusterPolicyProperties().isEmpty()) { model.setThresholds(new SchedulingPolicyThresholds()); String lowUtilization = entity.getClusterPolicyProperties().get(LOW_UTILIZATION); String highUtilization = entity.getClusterPolicyProperties().get(HIGH_UTILIZATION); String cpuOverCommitDurationMinutes = entity.getClusterPolicyProperties().get(CPU_OVER_COMMIT_DURATION_MINUTES); if (lowUtilization != null) { model.getThresholds().setLow(Integer.parseInt(lowUtilization)); } if (highUtilization != null) { model.getThresholds().setHigh(Integer.parseInt(highUtilization)); } if (cpuOverCommitDurationMinutes != null) { int duration = Integer.parseInt(cpuOverCommitDurationMinutes) * 60; model.getThresholds().setDuration(duration); } } } return model; }</code><technical_language>1. ^ this in lowercase 2. /capabilities resource exposed VdsSelectionAlgorithm enum members, if removed implementing this feature, break ..</technical_language>

Target:
public static SchedulingPolicy map(VDSGroup entity, SchedulingPolicy template) { SchedulingPolicy model = template != null ? template : new SchedulingPolicy(); if (entity.getClusterPolicyName() != null) { model.setPolicy(entity.getClusterPolicyName().toLowerCase()); if (entity.getClusterPolicyProperties() != null && !entity.getClusterPolicyProperties().isEmpty()) { model.setThresholds(new SchedulingPolicyThresholds()); String lowUtilization = entity.getClusterPolicyProperties().get(LOW_UTILIZATION); String highUtilization = entity.getClusterPolicyProperties().get(HIGH_UTILIZATION); String cpuOverCommitDurationMinutes = entity.getClusterPolicyProperties().get(CPU_OVER_COMMIT_DURATION_MINUTES); if (lowUtilization != null) { model.getThresholds().setLow(Integer.parseInt(lowUtilization)); } if (highUtilization != null) { model.getThresholds().setHigh(Integer.parseInt(highUtilization)); } if (cpuOverCommitDurationMinutes != null) { int duration = Integer.parseInt(cpuOverCommitDurationMinutes) * 60; model.getThresholds().setDuration(duration); } } } return model; }