auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean datastreamExists(String datastreamName) { try { doGetDatastream(datastreamName); return true; } catch (RemoteInvocationException e) { <START> LOG.debug(String.format("Datastream {%s} is not found", datastreamName)); <END> return false; } }</code><technical_language>exception necessarily datastream found, right? check http status</technical_language>

Target:
public boolean datastreamExists(String datastreamName) { try { doGetDatastream(datastreamName); return true; } catch (RemoteInvocationException e) { if (isNotFoundHttpStatus(e)) { LOG.debug(String.format("Datastream %s is not found", datastreamName)); } else { String errorMessage = String.format("Get Datastream %s failed with error.", datastreamName); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e); } } return false; }
Source:
<code>private void onFragmentLoaded() { if (listAdapter == null) { <START> listAdapter = new AllEpisodesRecycleAdapter(activity.get(), activity.get(), itemAccess, <END> new DefaultActionButtonCallback(activity.get()), showOnlyNewEpisodes); listView.setAdapter(listAdapter); downloadObserver = new DownloadObserver(activity.get(), new Handler(), downloadObserverCallback); downloadObserver.onResume(); } listAdapter.notifyDataSetChanged(); restoreScrollPosition(); getActivity().supportInvalidateOptionsMenu(); updateShowOnlyEpisodesListViewState(); }</code><technical_language>wondering: do AtomicReference MainActivity? call getActivity? (and check for null)</technical_language>

Target:
private void onFragmentLoaded() { if (listAdapter == null) { listAdapter = new AllEpisodesRecycleAdapter(activity.get(), activity.get(), itemAccess, new DefaultActionButtonCallback(activity.get()), showOnlyNewEpisodes()); recyclerView.setAdapter(listAdapter); downloadObserver = new DownloadObserver(activity.get(), new Handler(), downloadObserverCallback); downloadObserver.onResume(); } listAdapter.notifyDataSetChanged(); restoreScrollPosition(); getActivity().supportInvalidateOptionsMenu(); updateShowOnlyEpisodesListViewState(); }
Source:
<code>public CommandImpl(String name, String commandLine, String type, Map<String, String> attributes) { this.name = name; this.commandLine = commandLine; this.type = type; <START> this.attributes = new HashMap<>(attributes); <END> }</code><technical_language>Do [unmodifiable map](<LINK_0> here</technical_language>

Target:
public CommandImpl(String name, String commandLine, String type, Map<String, String> attributes) { this.name = name; this.commandLine = commandLine; this.type = type; this.attributes = unmodifiableMap(attributes); }
Source:
<code>private static void setJobCommonProperties(Job job, InternalJob jobToSet) throws IllegalArgumentException, IllegalAccessException { autoCopyfields(CommonAttribute.class, job, jobToSet); autoCopyfields(Job.class, job, jobToSet); <START> jobToSet.setPriority(job.getPriority()); <END> }</code><technical_language>clarify remove this</technical_language>

Target:
private static void setJobCommonProperties(Job job, InternalJob jobToSet) throws IllegalArgumentException, IllegalAccessException { autoCopyfields(CommonAttribute.class, job, jobToSet); autoCopyfields(Job.class, job, jobToSet); jobToSet.setVariables(job.getVariables()); jobToSet.setGenericInformation(job.getGenericInformation()); jobToSet.setPriority(job.getPriority()); }
Source:
<code>private Guid determineSourceImageGroup(DiskImage image) { if (Guid.Empty.equals(image.getParentId())) { return Guid.Empty; } <START> else { if (!getParameters().getDestImages().isEmpty()) <END> { return getParameters().getDestImageGroupId(); } } return image.getImageTemplateId().equals(image.getParentId()) ? imageDao.get(image.getImageTemplateId()).getDiskId() : getParameters().getImageGroupID(); }</code><technical_language>I "else if" totally removing "else" is more readable. 1 indent</technical_language>

Target:
private Guid determineSourceImageGroup(DiskImage image) { if (Guid.Empty.equals(image.getParentId())) { return Guid.Empty; } else if (!getParameters().getDestImages().isEmpty()) { return getParameters().getDestImageGroupId(); } return image.getImageTemplateId().equals(image.getParentId()) ? imageDao.get(image.getImageTemplateId()).getDiskId() : getParameters().getImageGroupID(); }
Source:
<code>private void handleDispose() { <START> tree.removeListener(SWT.Expand, this); <END> tree.removeListener(SWT.Collapse, this); tree = null; session = null; }</code><technical_language>is generally a good idea dispose() methods fail if called times in a row. get NPE</technical_language>

Target:
private void handleDispose() { tree.removeListener(SWT.Dispose, this); tree.removeListener(SWT.Collapse, this); tree.removeListener(SWT.Expand, this); tree = null; session = null; }
Source:
<code>public void testCalculateSubscriptions() throws Exception { <START> long month = (long) 30 * 24 * 3600 * 1000; <END> Date startTime = new Date(); Date endTime = new Date(startTime.getTime() + month); List<CalcSubscription> subscriptionsToCalculate = ImmutableList.of( new CalcSubscription.Builder() .startTime(startTime) .resource(SubscriptionResource.IP) .endTime(endTime) .build(), new CalcSubscription.Builder() .startTime(startTime) .endTime(endTime) .resource(SubscriptionResource.VLAN) .discountAmount(10.5d) .build() ); SubscriptionCalculator subscriptionCalculator = api.calculateSubscriptions(subscriptionsToCalculate); List<CalcSubscription> calculatedSubscriptions = subscriptionCalculator.getSubscriptions(); assertEquals(calculatedSubscriptions.size(), subscriptionsToCalculate.size()); for (int i = 0; i < calculatedSubscriptions.size(); i++) { checkCalcSubscription(calculatedSubscriptions.get(i), subscriptionsToCalculate.get(i)); } }</code><technical_language>Rename monthInMillis more descriptive</technical_language>

Target:
public void testCalculateSubscriptions() throws Exception { long monthInMilliseconds = (long) 30 * 24 * 3600 * 1000; Date startTime = new Date(); Date endTime = new Date(startTime.getTime() + monthInMilliseconds); List<CalcSubscription> subscriptionsToCalculate = ImmutableList.of( new CalcSubscription.Builder() .startTime(startTime) .resource(SubscriptionResource.IP) .endTime(endTime) .build(), new CalcSubscription.Builder() .startTime(startTime) .endTime(endTime) .resource(SubscriptionResource.VLAN) .discountAmount(10.5d) .build() ); SubscriptionCalculator subscriptionCalculator = api.calculateSubscriptions(subscriptionsToCalculate); List<CalcSubscription> calculatedSubscriptions = subscriptionCalculator.getSubscriptions(); assertEquals(calculatedSubscriptions.size(), subscriptionsToCalculate.size()); for (int i = 0; i < calculatedSubscriptions.size(); i++) { assertEquals(calculatedSubscriptions.get(i).getResource(), subscriptionsToCalculate.get(i).getResource()); } }
Source:
<code><START> public void updateUserMetaData(Map<String, String> userMetaDataMap) { <END> StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + VersionInfoUtils.getVersion()); int baseLength = userMetadata.length(); for(Map.Entry<String, String> metaData : userMetaDataMap.entrySet()){ this.userMetaDataMap.put(metaData.getKey(), metaData.getValue()); } if (this.userMetaDataMap != null) { for (Map.Entry<String, String> metaData : this.userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); } else { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); } } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }</code><technical_language>this a new method deprecate existing</technical_language>

Target:
public void updateUserMetaData(Map<String, String> userMetaDataMap) { StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + VersionInfoUtils.getVersion()); int baseLength = userMetadata.length(); if (userMetaDataMap != null) { for (Map.Entry<String, String> metaData : userMetaDataMap.entrySet()) { this.userMetaDataMap.put(metaData.getKey(), metaData.getValue()); } } for (Map.Entry<String, String> metaData : this.userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { String metaDataValue = metaData.getValue(); if (metaDataValue == null || "".equals(metaDataValue)){ userMetadata.append("&" + metaData.getKey()); } else { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); } } else { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }
Source:
<code>public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { <START> if (attribute.valueAsString() == null) <END> throw new WrongReferenceAttributeValueException(attribute, "Attribute was not filled, therefore there is nothing to be checked."); }</code><technical_language>Nit: is necessary convert String</technical_language>

Target:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute was not filled, therefore there is nothing to be checked."); }
Source:
<code>private ModelAndView populateModelAndView(RadiologyOrder radiologyOrder, Obs obs) { ModelAndView result = new ModelAndView(RADIOLOGY_OBS_FORM_PATH); List<Obs> previousObs = radiologyService.getObsByOrderId(radiologyOrder.getOrderId()); result.addObject("obs", obs); result.addObject("previousObs", previousObs); Study study = radiologyOrder.getStudy(); result.addObject("studyUID", study.isCompleted() ? study.getStudyInstanceUid() : null); result.addObject("dicomViewerUrl", getDicomViewerUrl(study, radiologyOrder.getPatient())); if (obs.getId() != null && obs.getConcept().isComplex()) { Obs complexObsAsHtmlView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HTML_VIEW); ComplexData complexData = complexObsAsHtmlView.getComplexData(); <START> result.addObject("htmlView", complexData.getData()); <END> Obs complexObsAsHyperlinkView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HYPERLINK_VIEW); ComplexData complexData2 = complexObsAsHyperlinkView.getComplexData(); result.addObject("hyperlinkView", complexData2.getData()); } return result; }</code><technical_language>@bgeVam please inline complexObsAsHtmlView.getComplexData().getData()</technical_language>

Target:
private ModelAndView populateModelAndView(RadiologyOrder radiologyOrder, Obs obs) { ModelAndView result = new ModelAndView(RADIOLOGY_OBS_FORM_PATH); List<Obs> previousObs = radiologyService.getObsByOrderId(radiologyOrder.getOrderId()); result.addObject("obs", obs); result.addObject("previousObs", previousObs); Study study = radiologyOrder.getStudy(); result.addObject("studyUID", study.isCompleted() ? study.getStudyInstanceUid() : null); result.addObject("dicomViewerUrl", getDicomViewerUrl(study, radiologyOrder.getPatient())); if (obs.getId() != null && obs.getConcept().isComplex()) { Obs complexObsAsHtmlView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HTML_VIEW); result.addObject("htmlView", complexObsAsHtmlView.getComplexData().getData()); Obs complexObsAsHyperlinkView = obsService.getComplexObs(Integer.valueOf(obs.getId()), WebConstants.HYPERLINK_VIEW); result.addObject("hyperlinkView", complexObsAsHyperlinkView.getComplexData().getData()); } return result; }
Source:
<code>HystrixInvocationHandler(Target target, Map<Method, MethodHandler> dispatch) { this.target = checkNotNull(target, "target"); this.dispatch = checkNotNull(dispatch, "dispatch"); try { for (Map.Entry<Method, MethodHandler> entry : this.dispatch.entrySet()) { if (HystrixCommand.class.isAssignableFrom(entry.getKey().getReturnType())) { MethodMetadata methodMetadata = entry.getValue().getMethodMetadata(); Type type = methodMetadata.returnType(); Type actualType = ((ParameterizedType) type).getActualTypeArguments()[0]; methodMetadata.returnType(actualType); } } } catch (Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>logged printed</technical_language>

Target:
HystrixInvocationHandler(Target target, Map<Method, MethodHandler> dispatch) { this.target = checkNotNull(target, "target"); this.dispatch = checkNotNull(dispatch, "dispatch"); }
Source:
<code>protected boolean queryYesNoQuestion(String message) { MessageDialog dialog = new MessageDialog(getContainer().getShell(), IDEWorkbenchMessages.Question, (Image) null, message, MessageDialog.NONE, 0, <START> IDEWorkbenchMessages.WizardDataTransfer_overwrite_button_label, IDialogConstants.CANCEL_LABEL) { END> @Override protected int getShellStyle() { return super.getShellStyle() | SWT.SHEET; } }; return dialog.open() == 0; }</code><technical_language>This unrelated</technical_language>

Target:
protected boolean queryYesNoQuestion(String message) { MessageDialog dialog = new MessageDialog(getContainer().getShell(), IDEWorkbenchMessages.Question, (Image) null, message, MessageDialog.NONE, 0, IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL) { @Override protected int getShellStyle() { return super.getShellStyle() | SWT.SHEET; } }; return dialog.open() == 0; }
Source:
<code>public CsvOutputFormat(Class<? extends Value> ... types) { <START> this("\n", "|", types); <END> }</code><technical_language>"," default separator? is called "CSV" ... ;)</technical_language>

Target:
public CsvOutputFormat(Class<? extends Value>... types) { this("\n", ",", types); }
Source:
<code>private void reportToServerIfNeeded(String tokenString){ <START> if (isReportting){ <END> return; } boolean needResport = false; long currentTime = new Date().getTime(); if (recorderTempFile.exists()){ needResport = true; } else if ((recorderFile.length() > config.uploadThreshold) && (lastReportTime == 0 || (currentTime - lastReportTime) > config.interval * 60)){ boolean isSuccess = recorderFile.renameTo(recorderTempFile); if (isSuccess) { needResport = true; } } if (needResport && !this.isReportting){ reportToServer(tokenString); } }</code><technical_language>isReportting => isReporting</technical_language>

Target:
private void reportToServerIfNeeded(String tokenString){ if (isReporting){ return; } boolean needToResport = false; long currentTime = new Date().getTime(); if (recorderTempFile.exists()){ needToResport = true; } else if ((recorderFile.length() > config.uploadThreshold) && (lastReportTime == 0 || (currentTime - lastReportTime) > config.interval * 60)){ boolean isSuccess = recorderFile.renameTo(recorderTempFile); if (isSuccess) { needToResport = true; } } if (needToResport && !this.isReporting){ reportToServer(tokenString); } }
Source:
<code>public static void wait(int wait, Callable<Void> callable) throws ExecutionException { try { FutureTask<Void> task = new FutureTask<>(callable); task.run(); task.get(((wait == 0) ? 10 : wait) + 5, TimeUnit.SECONDS); } catch (@SuppressWarnings("unused") InterruptedException e) { Thread.currentThread().interrupt(); } catch (@SuppressWarnings("unused") TimeoutException e) { <START> } <END> }</code><technical_language>Goof question ;-) feeling simply continue waited configured time (and longer). said, happen. output a warning get noticed in case. wdyt</technical_language>

Target:
public static long wait(int wait, Callable<Void> callable) throws ExecutionException, WaitTimeoutException { long now = System.currentTimeMillis(); wait = (wait == 0) ? DEFAULT_DOCKER_TIMEOUT : wait; try { FutureTask<Void> task = new FutureTask<>(callable); task.run(); task.get(wait, TimeUnit.SECONDS); } catch (@SuppressWarnings("unused") InterruptedException e) { Thread.currentThread().interrupt(); } catch (@SuppressWarnings("unused") TimeoutException e) { throw new WaitTimeoutException("timed out waiting for execution to complete", delta(now)); } return delta(now); }
Source:
<code>public Class<? extends ComponentProperties>[] getNestedCompatibleComponentPropertiesClass() { return new Class[] { SalesforceConnectionProperties.class, SalesforceModuleProperties.class }; <START> } <END></code><technical_language>(please tSalesforceOutputBulkExec, tSalesforceInput, tSalesforceOutput)</technical_language>

Target:
public Class<? extends ComponentProperties>[] getNestedCompatibleComponentPropertiesClass() { return concatPropertiesClasses(super.getNestedCompatibleComponentPropertiesClass(), new Class[] { SalesforceModuleProperties.class }); }
Source:
<code>public List<String> findAnnotatedClassNames(Class annotationClass) throws ClassNotFoundException { <START> List<String> annotatedClasses = new ArrayList<String>(); <END> ArrayList<String> dynamicClasses = classNames; for (String dynamicClass : dynamicClasses) { Class<?> classz = getClassLoader().loadClass(dynamicClass); if (classz.getAnnotation(annotationClass) != null) { annotatedClasses.add(classz.getName()); } } return annotatedClasses; }</code><technical_language>rewritten as: java return findAnnotatedClasses(annotationClass) .stream .map(Class::getName) .collect(Collectors.toList());</technical_language>

Target:
public List<String> findAnnotatedClassNames(Class annotationClass) throws ClassNotFoundException { return findAnnotatedClasses(annotationClass) .stream() .map(Class::getName) .collect(Collectors.toList()); }
Source:
<code>public final JsonObject build(ElasticsearchSearchPredicateContext context) { JsonObject outerObject = new JsonObject(); JsonObject innerObject = new JsonObject(); if ( boost != null && !withConstantScore ) { BOOST_ACCESSOR.set( innerObject, boost ); } JsonObject result = doBuild( context, outerObject, innerObject ); if ( withConstantScore ) { result = applyConstantScore( result ); } <START> if ( !context.isExplicitNested() && nestedPathHierarchy != null && !nestedPathHierarchy.isEmpty() ) { <END> result = applyImplicitNested( result, new LinkedList<>( nestedPathHierarchy ) ); } return result; }</code><technical_language>I this more fine-grained: instead of checking explicit nesting, compare closest nested predicate nested path hierarchy of this predicate. For example, assume a field levels of nesting: nested1.nested2.stringField. If user applies a nested predicate nested1 only, forgets nested2 (which understandable in some situations) ... add nesting nested2 automatically detect "closest nested predicate" match path in nestedPathHierarchy</technical_language>

Target:
public JsonObject build(ElasticsearchSearchPredicateContext context) { JsonObject outerObject = new JsonObject(); JsonObject innerObject = new JsonObject(); if ( boost != null && !withConstantScore ) { BOOST_ACCESSOR.set( innerObject, boost ); } JsonObject result = doBuild( context, outerObject, innerObject ); return ( withConstantScore ) ? applyConstantScore( result ) : result; }
Source:
<code>public void testDebitResourceFields() throws HTTPError { Card card = createCard(); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); payload.put("description", "Some descriptive text for the debit in the dashboard"); payload.put("appears_on_statement_as", "Statement text"); payload.put("appears_on_statement_as", "Statement text"); Debit debit = card.debit(payload); Map<String, String> meta = new HashMap<String, String>(); meta.put("anykey", "valuegoeshere"); meta.put("facebook.id", "1234567890"); debit.meta = meta; debit.save(); assertNotNull(debit.appears_on_statement_as); assertNotNull(debit.created_at); assertNotNull(debit.currency); assertNotNull(debit.description); assertNull(debit.failure_reason); assertNull(debit.failure_reason_code); assertNotNull(debit.href); assertNotNull(debit.id); assertNotNull(debit.card_hold); assertNull(debit.customer); assertNull(debit.dispute); assertNull(debit.order); assertNotNull(debit.source); assertNotNull(debit.meta); assertNotNull(debit.status); assertNotNull(debit.transaction_number); assertNotNull(debit.updated_at); assertNotNull(debit.events); assertNotNull(debit.refunds); <START> } <END></code><technical_language>Assert values</technical_language>

Target:
public void testDebitResourceFields() throws HTTPError { Card card = createCard(); Customer customer = createPersonCustomer(); card.associateToCustomer(customer); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); payload.put("description", "Some descriptive text for the debit in the dashboard"); payload.put("appears_on_statement_as", "Statement text"); Debit debit = card.debit(payload); Map<String, String> meta = new HashMap<String, String>(); meta.put("facebook", "1234567890"); debit.meta = meta; debit.save(); assertEquals(debit.appears_on_statement_as, "BAL*Statement text"); assertNotNull(debit.created_at); assertEquals(debit.currency, "USD"); assertEquals(debit.description, "Some descriptive text for the debit in the dashboard"); assertNull(debit.failure_reason); assertNull(debit.failure_reason_code); assertTrue(debit.href.contains("/debits/WD")); assertTrue(debit.id.startsWith("WD")); assertTrue(debit.card_hold instanceof CardHold); assertEquals(debit.customer.href, customer.href); assertNull(debit.dispute); assertNull(debit.order); assertEquals(debit.source.href, card.href); assertEquals(debit.meta.get("facebook"), "1234567890"); assertEquals(debit.status, "succeeded"); assertTrue(debit.transaction_number.startsWith("W")); assertNotNull(debit.updated_at); assertTrue(debit.events instanceof Event.Collection); assertTrue(debit.refunds instanceof Refund.Collection); }
Source:
<code>public static String invokeComponentToString(final Component component, final ContentFilter filter) { <START> final ByteArrayOutputStream baos = new ByteArrayOutputStream(); <END> component.addContents( new Container() { @Override public void add(@CheckForNull Content content) { try { ((PrefilteredContent) Objects.requireNonNull(content)).writeTo(baos, filter); } catch (IOException e) { e.printStackTrace(); } } }); return baos.toString(); }</code><technical_language>suggestion try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {</technical_language>

Target:
public static String invokeComponentToString(final Component component, final ContentFilter filter) throws IOException { try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) { component.addContents( new Container() { @Override public void add(@CheckForNull Content content) { try { ((PrefilteredContent) Objects.requireNonNull(content)).writeTo(baos, filter); } catch (IOException e) { e.printStackTrace(); } } }); return baos.toString(); } }
Source:
<code>public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); <START> configurationBuilder.compatibility().disable(); <END> return configurationBuilder; }</code><technical_language>test methods require compatibility</technical_language>

Target:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); return configurationBuilder; }
Source:
<code>public void onResponse(Releasable releasable) { assert replica.getActiveOperationsCount() != 0 : "must perform shard operation under a permit"; <START> shardOperationOnReplica(replicaRequest.getRequest(), replica, ActionListener.wrap((replicaResult) -> <END> replicaResult.runPostReplicaActions( ActionListener.wrap(r -> { final ReplicaResponse response = new ReplicaResponse(replica.getLocalCheckpoint(), replica.getLastSyncedGlobalCheckpoint()); releasable.close(); if (logger.isTraceEnabled()) { logger.trace("action completed on shard for request [{}]", transportReplicaAction, replicaRequest.getRequest().shardId(), replicaRequest.getRequest()); } setPhase(task, "finished"); onCompletionListener.onResponse(response); }, e -> { Releasables.closeWhileHandlingException(releasable); responseWithFailure(e); }) ), e -> { Releasables.closeWhileHandlingException(releasable); AsyncReplicaAction.this.onFailure(e); })); }</code><technical_language>if shardOperationOnReplica throws exception? releasing releasable then</technical_language>

Target:
public void onResponse(Releasable releasable) { assert replica.getActiveOperationsCount() != 0 : "must perform shard operation under a permit"; try { shardOperationOnReplica(replicaRequest.getRequest(), replica, ActionListener.wrap((replicaResult) -> replicaResult.runPostReplicaActions( ActionListener.wrap(r -> { final ReplicaResponse response = new ReplicaResponse(replica.getLocalCheckpoint(), replica.getLastSyncedGlobalCheckpoint()); releasable.close(); if (logger.isTraceEnabled()) { logger.trace("action completed on shard for request [{}]", transportReplicaAction, replicaRequest.getRequest().shardId(), replicaRequest.getRequest()); } setPhase(task, "finished"); onCompletionListener.onResponse(response); }, e -> { Releasables.closeWhileHandlingException(releasable); responseWithFailure(e); }) ), e -> { Releasables.closeWhileHandlingException(releasable); AsyncReplicaAction.this.onFailure(e); })); } catch (Exception e) { Releasables.closeWhileHandlingException(releasable); AsyncReplicaAction.this.onFailure(e); } }
Source:
<code>public Set<String> getFreeVariables() { <START> throw new RuntimeException("Free variables of a JavaValue not yet implemented."); <END> }</code><technical_language>OK return empty set - JavaValue is a value, variables inside</technical_language>

Target:
public Set<String> getFreeVariables() { return new HashSet<>(); }
Source:
<code>private List<String> generateOptionList(String courseId) { List<String> optionList = new ArrayList<>(); switch (generateOptionsFor) { case NONE: optionList = msqChoices; break; case STUDENTS: List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); for (StudentAttributes student : studentList) { optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case STUDENTS_EXCLUDING_SELF: <START> List<StudentAttributes> studentListExcludingSelf = StudentsLogic.inst().getStudentsForCourse(courseId); <END> String thisStudentEmail = studentDoingQuestion.email; for (StudentAttributes student : studentListExcludingSelf) { if (thisStudentEmail.equals(student.email)) { continue; } optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case TEAMS: try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); for (TeamDetailsBundle team : teamList) { optionList.add(team.name); } optionList.sort(null); } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } break; case INSTRUCTORS: List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse( courseId); for (InstructorAttributes instructor : instructorList) { optionList.add(instructor.name); } optionList.sort(null); break; default: Assumption.fail("Trying to generate options for neither students, teams nor instructors"); break; } return optionList; }</code><technical_language>Similarly, this able compressed STUDENTS one</technical_language>

Target:
private List<String> generateOptionList(String courseId) { List<String> optionList = new ArrayList<>(); switch (generateOptionsFor) { case NONE: optionList = msqChoices; break; case STUDENTS: case STUDENTS_EXCLUDING_SELF: List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); if (generateOptionsFor == FeedbackParticipantType.STUDENTS_EXCLUDING_SELF) { studentList.removeIf(studentInList -> studentInList.email.equals(studentDoingQuestion.email)); } for (StudentAttributes student : studentList) { optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case TEAMS: try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); for (TeamDetailsBundle team : teamList) { optionList.add(team.name); } optionList.sort(null); } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } break; case INSTRUCTORS: List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse( courseId); for (InstructorAttributes instructor : instructorList) { optionList.add(instructor.name); } optionList.sort(null); break; default: Assumption.fail("Trying to generate options for neither students, teams nor instructors"); break; } return optionList; }
Source:
<code>public byte[] encrypt(byte[] plainTextBytes, String algorithm, boolean returnSelfContainedCipherText, String internalCryptoProviderType) throws CryptoException { failIfEncryptDecryptInputsAreInvalid(plainTextBytes, algorithm, internalCryptoProviderType); byte[] encryptedKey; try { CryptoService cryptoService = CarbonCoreDataHolder.getInstance().getCryptoService(); if (cryptoService == null) { throw new CryptoException("A crypto service implementation has not been registered."); } if (plainTextBytes.length == 0) { if (log.isDebugEnabled()) { log.debug("Plaintext is empty. An empty array will be used as the ciphertext bytes."); } encryptedKey = StringUtils.EMPTY.getBytes(); } else { if (log.isDebugEnabled()) { if (returnSelfContainedCipherText) { log.debug(String.format( "Encrypting data in self contained format, with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } else { log.debug(String.format( "Encrypting data with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } } encryptedKey = cryptoService .encrypt(plainTextBytes, algorithm, CRYPTO_API_PROVIDER_BC, returnSelfContainedCipherText, internalCryptoProviderType); } <START> } catch (Exception e) { <END> throw new CryptoException("An error occurred while encrypting data.", e); } return encryptedKey; }</code><technical_language>catch specific exception here</technical_language>

Target:
public byte[] encrypt(byte[] plainTextBytes, String algorithm, boolean returnSelfContainedCipherText, String internalCryptoProviderType) throws CryptoException { failIfEncryptDecryptInputsAreInvalid(plainTextBytes, algorithm, internalCryptoProviderType); byte[] encryptedKey; try { CryptoService cryptoService = CarbonCoreDataHolder.getInstance().getCryptoService(); if (cryptoService == null) { throw new CryptoException("A crypto service implementation has not been registered."); } if (plainTextBytes.length == 0) { if (log.isDebugEnabled()) { log.debug("Plaintext is empty. An empty array will be used as the ciphertext bytes."); } encryptedKey = StringUtils.EMPTY.getBytes(); } else { if (log.isDebugEnabled()) { if (returnSelfContainedCipherText) { log.debug(String.format( "Encrypting data in self contained format, with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } else { log.debug(String.format( "Encrypting data with algorithm: '%s' and internal crypto " + "provider: '%s'", algorithm, internalCryptoProviderType)); } } encryptedKey = cryptoService .encrypt(plainTextBytes, algorithm, CRYPTO_API_PROVIDER_BC, returnSelfContainedCipherText, internalCryptoProviderType); } } catch (org.wso2.carbon.crypto.api.CryptoException e) { throw new CryptoException("An error occurred while encrypting data.", e); } return encryptedKey; }
Source:
<code>public List<Container> getContainersForImage(String image, boolean all) throws DockerAccessException { String url; String serverApiVersion = getServerApiVersion(); if (EnvUtil.greaterOrEqualsVersion(serverApiVersion, "1.23")) { url = urlBuilder.listContainers(all, "ancestor",image); } else { url = urlBuilder.listContainers(all); } try { <START> log.verbose(Logger.LogVerboseCategory.API,"GETing %s", url); <END> String response = delegate.get(url, HTTP_OK); JsonArray array = JsonFactory.newJsonArray(response); List<Container> containers = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { JsonObject element = array.get(i).getAsJsonObject(); if (image.equals(element.get("Image").getAsString())) { containers.add(new ContainersListElement(element)); } } return containers; } catch (IOException e) { throw new DockerAccessException(e.getMessage()); } }</code><technical_language>suggestion log.verbose(Logger.LogVerboseCategory.API,"GET %s", url);</technical_language>

Target:
public List<Container> getContainersForImage(String image, boolean all) throws DockerAccessException { String url; String serverApiVersion = getServerApiVersion(); if (EnvUtil.greaterOrEqualsVersion(serverApiVersion, "1.23")) { url = urlBuilder.listContainers(all, "ancestor",image); } else { url = urlBuilder.listContainers(all); } try { log.verbose(Logger.LogVerboseCategory.API,"GET %s", url); String response = delegate.get(url, HTTP_OK); JsonArray array = JsonFactory.newJsonArray(response); List<Container> containers = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { JsonObject element = array.get(i).getAsJsonObject(); if (image.equals(element.get("Image").getAsString())) { containers.add(new ContainersListElement(element)); } } return containers; } catch (IOException e) { throw new DockerAccessException(e.getMessage()); } }
Source:
<code>public void placeNewMarketOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (orderType == OrderType.BUY) { if ((price*volume) > this.cashInHand) { <START> throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since there is not enough money." <END> + " Trader: " + this.name); } for(int i = 0; i < this.ordersPlaced.size(); i++) { if (this.ordersPlaced.get(i).getStockSymbol().equals(symbol)) { throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since this trader already has" + "an order for this stock. Trader: " + this.name); } } Order order = new BuyOrder(symbol, volume, true, this); this.ordersPlaced.add(order); m.addOrder(order); } if (orderType == OrderType.SELL) { boolean owns = false; int numberStocksOwned = 0; for (int i = 0; i < this.position.size(); i++) { if (this.position.get(i).getStockSymbol() == symbol) { owns = true; numberStocksOwned = this.position.get(i).getSize(); } } if (!owns) { throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since this trader does not" + "own this stock. Trader: " + this.name); } if (numberStocksOwned < volume){ throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since this trader does not" + "own enough shares of this stock. Trader: " + this.name); } Order order = new SellOrder(symbol, volume, true, this); this.ordersPlaced.add(order); m.addOrder(order); } }</code><technical_language>Indent lines if statement</technical_language>

Target:
public void placeNewMarketOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (orderType == OrderType.BUY) { if ((price * volume) > this.cashInHand) { throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since there is not enough money." + " Trader: " + this.name); } for(int i = 0; i < this.ordersPlaced.size(); i++) { if (this.ordersPlaced.get(i).getStockSymbol().equals(symbol)) { throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since this trader already has" + "an order for this stock. Trader: " + this.name); } } Order order = new BuyOrder(symbol, volume, true, this); this.ordersPlaced.add(order); m.addOrder(order); } if (orderType == OrderType.SELL) { boolean owns = false; int numberStocksOwned = 0; for (int i = 0; i < this.position.size(); i++) { if (this.position.get(i).getStockSymbol().equals(symbol)) { owns = true; numberStocksOwned = this.position.get(i).getSize(); } } if (!owns) { throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since this trader does not" + "own this stock. Trader: " + this.name); } if (numberStocksOwned < volume){ throw new StockMarketExpection("Cannot place order for stock: " + symbol + " since this trader does not" + "own enough shares of this stock. Trader: " + this.name); } Order order = new SellOrder(symbol, volume, true, this); this.ordersPlaced.add(order); m.addOrder(order); } }
Source:
<code>public static PaletteGroup getPaletteGroupWithAdd(Palette palette, IContainer groupDst) { String[] groups = groupDst.getProjectRelativePath().toString().split("/"); if ((0 == groups.length) || ((1 == groups.length) && (0 == groups[0].length()))) { return palette.getRootGroup(); } <START> ArrayList<String> <END> groupList = new ArrayList<String>(); groupList.addAll(Arrays.asList(groups)); if (TypeLibraryTags.TOOL_LIBRARY_PROJECT_NAME.equals(groupList.get(0))) { groupList.remove(0); } return palette.getGroup(groupList, false); }</code><technical_language>replace List interface</technical_language>

Target:
public static PaletteGroup getPaletteGroupWithAdd(Palette palette, IContainer groupDst) { String[] groups = groupDst.getProjectRelativePath().toString().split("/"); if ((0 == groups.length) || ((1 == groups.length) && (0 == groups[0].length()))) { return palette.getRootGroup(); } List<String> groupList = new ArrayList<>(); groupList.addAll(Arrays.asList(groups)); if (TypeLibraryTags.TOOL_LIBRARY_PROJECT_NAME.equals(groupList.get(0))) { groupList.remove(0); } return palette.getGroup(groupList, false); }
Source:
<code>private void deleteKubernetesVersionIso(long templateId) throws IllegalAccessException, NoSuchFieldException, IllegalArgumentException { <START> DeleteIsoCmd deleteIsoCmd = new DeleteIsoCmd(); <END> deleteIsoCmd = ComponentContext.inject(deleteIsoCmd); Field f = deleteIsoCmd.getClass().getDeclaredField("id"); f.setAccessible(true); f.set(deleteIsoCmd, templateId); templateService.deleteIso(deleteIsoCmd); }</code><technical_language>here. add setters constructor deal this</technical_language>

Target:
private void deleteKubernetesVersionIso(long templateId) throws IllegalAccessException, NoSuchFieldException, IllegalArgumentException { DeleteIsoCmd deleteIsoCmd = new DeleteIsoCmd(); deleteIsoCmd = ComponentContext.inject(deleteIsoCmd); deleteIsoCmd.setId(templateId); templateService.deleteIso(deleteIsoCmd); }
Source:
<code>public void testComplete() { assertFalse(TestUtils.getPropertyValue(this.splitter, "iterator", Boolean.class)); assertTrue(TestUtils.getPropertyValue(this.splitter, "markers", Boolean.class)); assertTrue(TestUtils.getPropertyValue(this.splitter, "requiresReply", Boolean.class)); assertTrue(TestUtils.getPropertyValue(this.splitter, "applySequence", Boolean.class)); assertEquals(Charset.forName("UTF-8"), TestUtils.getPropertyValue(this.splitter, "charset")); assertEquals(5L, TestUtils.getPropertyValue(this.splitter, "messagingTemplate.sendTimeout")); <START> assertEquals(out, TestUtils.getPropertyValue(this.splitter, "outputChannel")); <END> assertEquals(2, TestUtils.getPropertyValue(this.splitter, "order")); assertEquals(this.in, TestUtils.getPropertyValue(this.fullBoat, "inputChannel")); assertFalse(TestUtils.getPropertyValue(this.fullBoat, "autoStartup", Boolean.class)); assertEquals(1, TestUtils.getPropertyValue(this.fullBoat, "phase")); }</code><technical_language>Nit-pick: this.out</technical_language>

Target:
public void testComplete() { assertFalse(TestUtils.getPropertyValue(this.splitter, "iterator", Boolean.class)); assertTrue(TestUtils.getPropertyValue(this.splitter, "markers", Boolean.class)); assertTrue(TestUtils.getPropertyValue(this.splitter, "requiresReply", Boolean.class)); assertTrue(TestUtils.getPropertyValue(this.splitter, "applySequence", Boolean.class)); assertEquals(Charset.forName("UTF-8"), TestUtils.getPropertyValue(this.splitter, "charset")); assertEquals(5L, TestUtils.getPropertyValue(this.splitter, "messagingTemplate.sendTimeout")); assertEquals(this.out, TestUtils.getPropertyValue(this.splitter, "outputChannel")); assertEquals(2, TestUtils.getPropertyValue(this.splitter, "order")); assertEquals(this.in, TestUtils.getPropertyValue(this.fullBoat, "inputChannel")); assertFalse(TestUtils.getPropertyValue(this.fullBoat, "autoStartup", Boolean.class)); assertEquals(1, TestUtils.getPropertyValue(this.fullBoat, "phase")); }
Source:
<code>public static String getConfigValue(String catalogName, String parameter) throws ParameterNotFoundException { HierarchicalConfiguration opacConfiguration = getCatalog(catalogName); if (Objects.isNull(opacConfiguration)) { <START> throw new ParameterNotFoundException("No configuration foudn for catalog '" + catalogName + "'!"); <END> } else { String parameterValue = opacConfiguration.getString(parameter); if (parameterValue.isEmpty()) { throw new ParameterNotFoundException("Parameter '" + parameter + "' not found in OPAC configuration for catalog '" + catalogName + "'!"); } return parameterValue; } }</code><technical_language>suggestion throw new ParameterNotFoundException("No configuration for catalog '" + catalogName + "'!");</technical_language>

Target:
public static String getConfigValue(String catalogName, String parameter) throws ParameterNotFoundException { HierarchicalConfiguration opacConfiguration = getCatalog(catalogName); if (Objects.isNull(opacConfiguration)) { throw new ParameterNotFoundException("No configuration found for catalog '" + catalogName + "'!"); } else { String parameterValue = opacConfiguration.getString(parameter); if (StringUtils.isBlank(parameterValue)) { throw new ParameterNotFoundException("Parameter '" + parameter + "' not found in OPAC configuration for catalog '" + catalogName + "'!"); } return parameterValue; } }
Source:
<code>protected boolean isCPOEValid() { for (String crit : CPOE_CRITERIA) { if (null != criteriaMet.get(crit)) { this.counts.put("criteriaCpoeRequiredMet", 1); return true; } } <START> ArrayList<String> missing1 = new ArrayList<String>(); <END> missing1.addAll(CPOE_CRITERIA); missingOr.add(missing1); return false; }</code><technical_language>"1" end of variable name? variable ally</technical_language>

Target:
protected boolean isCPOEValid() { for (String crit : CPOE_CRITERIA) { if (null != criteriaMet.get(crit)) { this.counts.put("criteriaCpoeRequiredMet", 1); return true; } } ArrayList<String> missing = new ArrayList<String>(); missing.addAll(CPOE_CRITERIA); missingOr.add(missing); return false; }
Source:
<code>public static void main(String[] args) { final AmbryServer ambryServer; int exitCode = 0; try { InvocationOptions options = new InvocationOptions(args); Properties properties = Utils.loadProps(options.serverPropsFilePath); <START> properties.setProperty("clustermap.cluster.name", "dev"); <END> properties.setProperty("clustermap.datacenter.name", "DataCenter"); properties.setProperty("clustermap.host.name", "localhost"); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(verifiableProperties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, options.hardwareLayoutFilePath, options.partitionLayoutFilePath); logger.info("Bootstrapping AmbryServer"); ambryServer = new AmbryServer(verifiableProperties, clusterAgentsFactory, SystemTime.getInstance()); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { logger.info("Received shutdown signal. Shutting down AmbryServer"); ambryServer.shutdown(); } }); ambryServer.startup(); ambryServer.awaitShutdown(); } catch (Exception e) { logger.error("Exception during bootstrap of AmbryServer", e); exitCode = 1; } logger.info("Exiting AmbryMain"); System.exit(exitCode); }</code><technical_language>hardcoded now? want able override these</technical_language>

Target:
public static void main(String[] args) { final AmbryServer ambryServer; int exitCode = 0; try { InvocationOptions options = new InvocationOptions(args); Properties properties = Utils.loadProps(options.serverPropsFilePath); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(verifiableProperties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, options.hardwareLayoutFilePath, options.partitionLayoutFilePath); logger.info("Bootstrapping AmbryServer"); ambryServer = new AmbryServer(verifiableProperties, clusterAgentsFactory, SystemTime.getInstance()); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { logger.info("Received shutdown signal. Shutting down AmbryServer"); ambryServer.shutdown(); } }); ambryServer.startup(); ambryServer.awaitShutdown(); } catch (Exception e) { logger.error("Exception during bootstrap of AmbryServer", e); exitCode = 1; } logger.info("Exiting AmbryMain"); System.exit(exitCode); }
Source:
<code>public File getFile(File workingDir) throws IOException { File file = new File(path); String name = file.getName(); if (path.equals(DiffEntry.DEV_NULL)) { <START> file = new File(workingDir, "nul"); END> } else if ((stream != null)) { tempFile = File.createTempFile(".__", "__" + name); try (OutputStream outStream = new FileOutputStream(tempFile)) { int read = 0; byte[] bytes = new byte[8 * 1024]; while ((read = stream.read(bytes)) != -1) { outStream.write(bytes, 0, read); } } return tempFile; } return file; }</code><technical_language>This is a problem linux. leaving /dev/null works</technical_language>

Target:
public File getFile(File workingDir) throws IOException { File file = new File(path); String name = file.getName(); if (path.equals(DiffEntry.DEV_NULL)) { file = new File(workingDir, "nul"); } else if (stream != null) { tempFile = File.createTempFile(".__", "__" + name); try (OutputStream outStream = new FileOutputStream(tempFile)) { int read = 0; byte[] bytes = new byte[8 * 1024]; while ((read = stream.read(bytes)) != -1) { outStream.write(bytes, 0, read); } } return tempFile; } return file; }
Source:
<code>public void onNext(final AggregationMessage aggregationMessage) { final String slaveId = aggregationMessage.getSourceId().toString(); if (blockedWorkerIds.contains(slaveId)) { <START> LOG.log(Level.INFO, "Multiple synchronization requests from {0}", slaveId); <END> } else { blockedWorkerIds.add(slaveId); } if (blockedWorkerIds.size() == numWorkers) { LOG.log(Level.INFO, "{0} workers are blocked. Sending response messages to awake them", numWorkers); broadcastResponseMessages(); } }</code><technical_language>This unexpected case... in fact, error. raise log level WARNING, throw exception</technical_language>

Target:
public void onNext(final AggregationMessage aggregationMessage) { final String slaveId = aggregationMessage.getSourceId().toString(); if (blockedWorkerIds.contains(slaveId)) { LOG.log(Level.WARNING, "Multiple synchronization requests from {0}", slaveId); } else { blockedWorkerIds.add(slaveId); } if (blockedWorkerIds.size() == numWorkers) { LOG.log(Level.INFO, "{0} workers are blocked. Sending response messages to awake them", numWorkers); broadcastResponseMessages(); } }
Source:
<code>private PgClassTable.Entry primaryKeyToPgClassEntry(RelationInfo info) { <START> return new PgClassTable.Entry(OidHash.primaryKeyOid(info), OidHash.schemaOid(info.ident().schema()), info.ident(), info.ident().name() + "_pkey", info.relationType(), info.columns().size(), info.primaryKey().size() > 0); <END> }</code><technical_language>suggestion return new PgClassTable.Entry( OidHash.primaryKeyOid(info), OidHash.schemaOid(info.ident().schema()), info.ident(), info.ident().name() + "_pkey", info.relationType(), info.columns().size(), info.primaryKey().size() > 0);</technical_language>

Target:
private PgClassTable.Entry primaryKeyToPgClassEntry(RelationInfo info) { return new PgClassTable.Entry( OidHash.primaryKeyOid(info), OidHash.schemaOid(info.ident().schema()), info.ident(), info.ident().name() + "_pkey", PgClassTable.Entry.Type.INDEX, info.columns().size(), info.primaryKey().size() > 0); }