auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testValueOf() { Account genericAccount = new Account("id", "Joe", true, "joe@gmail.com", "Teammates Institute"); AccountAttributes observedAccountAttributes = AccountAttributes.valueOf(genericAccount); assertEquals(genericAccount.getGoogleId(), observedAccountAttributes.getGoogleId()); assertEquals(genericAccount.getName(), observedAccountAttributes.getName()); assertEquals(genericAccount.isInstructor(), observedAccountAttributes.isInstructor()); assertEquals(genericAccount.getEmail(), observedAccountAttributes.getEmail()); <START> assertEquals(genericAccount.getInstitute(), observedAccountAttributes.getInstitute()); <END> }</code><technical_language>Add checks for createdAt studentProfile well</technical_language>

Target:
public void testValueOf() { Account genericAccount = new Account("id", "Joe", true, "joe@example.com", "Teammates Institute"); AccountAttributes observedAccountAttributes = AccountAttributes.valueOf(genericAccount); assertEquals(genericAccount.getGoogleId(), observedAccountAttributes.getGoogleId()); assertEquals(genericAccount.getName(), observedAccountAttributes.getName()); assertEquals(genericAccount.isInstructor(), observedAccountAttributes.isInstructor()); assertEquals(genericAccount.getEmail(), observedAccountAttributes.getEmail()); assertEquals(genericAccount.getInstitute(), observedAccountAttributes.getInstitute()); assertEquals(genericAccount.getCreatedAt(), observedAccountAttributes.createdAt); assertEquals(genericAccount.getStudentProfile(), observedAccountAttributes.studentProfile); }
Source:
<code>private List<Observation> createNestedObservations(String configName, Encounter encounter, List<Observation> observationList) { List<Observation> createdObservations = new ArrayList<>(); Observation observationToCreate; for (Observation observation : observationList) { List<Observation> nestedObservations = new ArrayList<>(); List<Observation> groupMembers = new ArrayList<>(); observationToCreate = observation; if (observation.getGroupMembers() != null) { for (Observation nestedObservation : observation.getGroupMembers()) { if (CollectionUtils.isNotEmpty(nestedObservation.getGroupMembers())) { nestedObservations.add(nestedObservation); } else { groupMembers.add(nestedObservation); } } } observationToCreate.setGroupMembers(groupMembers); observationToCreate.setEncounter(encounter); Observation createdObservation = observationService.createObservation(configName, observationToCreate); <START> if (createdObservation.getGroupMembers() == null) { <END> createdObservation.setGroupMembers(new ArrayList<>()); } createdObservation.getGroupMembers().addAll(createNestedObservations(configName, encounter, nestedObservations)); createdObservations.add(createdObservation); } return createdObservations; }</code><technical_language>this is redundant, is handled in getter</technical_language>

Target:
private List<Observation> createNestedObservations(String configName, Encounter encounter, List<Observation> observationList) { List<Observation> createdObservations = new ArrayList<>(); Observation observationToCreate; for (Observation observation : observationList) { List<Observation> nestedObservations = new ArrayList<>(); List<Observation> groupMembers = new ArrayList<>(); observationToCreate = observation; for (Observation nestedObservation : observation.getGroupMembers()) { if (CollectionUtils.isNotEmpty(nestedObservation.getGroupMembers())) { nestedObservations.add(nestedObservation); } else { nestedObservation.setPerson(new Person(encounter.getPatient().getUuid())); groupMembers.add(nestedObservation); } } observationToCreate.setGroupMembers(groupMembers); observationToCreate.setEncounter(encounter); observationToCreate.setPerson(new Person(encounter.getPatient().getUuid())); Observation createdObservation = observationService.createObservation(configName, observationToCreate); createdObservation.getGroupMembers().addAll(createNestedObservations(configName, encounter, nestedObservations)); createdObservations.add(createdObservation); } return createdObservations; }
Source:
<code>private TimeoutConfiguration getGlobalTimeoutConfiguration(ExtensionContext extensionContext) { ExtensionContext root = extensionContext.getRoot(); <START> return root.getStore(NAMESPACE).getOrComputeIfAbsent("global_timeout_config", <END> key -> new TimeoutConfiguration(root), TimeoutConfiguration.class); }</code><technical_language>Please "global_timeout_config" a constant</technical_language>

Target:
private TimeoutConfiguration getGlobalTimeoutConfiguration(ExtensionContext extensionContext) { ExtensionContext root = extensionContext.getRoot(); return root.getStore(NAMESPACE).getOrComputeIfAbsent(GLOBAL_TIMEOUT_CONFIG_KEY, key -> new TimeoutConfiguration(root), TimeoutConfiguration.class); }
Source:
<code>public void initialize() { logger.debug("Initializing DigitalSTROM Scene handler."); if (this.getDssBridgeHandler() == null) { <START> updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_MISSING_ERROR, "Bridge is missig"); <END> } else { bridgeHandlerInitialized(dssBridgeHandler, this.getBridge()); } }</code><technical_language>remove this, is care of framework</technical_language>

Target:
public void initialize() { logger.debug("Initializing SceneHandler"); if (bridgeHandler != null) { bridgeHandlerInitialized(bridgeHandler, this.getBridge()); } }
Source:
<code><START> public TopologyInfo getTopologyInfoByName(String name) throws NotAliveException, AuthorizationException, TException { <END> try { getTopologyInfoByNameCalls.mark(); GetInfoOptions options = new GetInfoOptions(); options.set_num_err_choice(NumErrorsChoice.ALL); return getTopologyInfoByNameImpl(name, options); } catch (Exception e) { LOG.warn("get topology info exception. (topology name={})", name, e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }</code><technical_language>need NotAliveException, AuthorizationException</technical_language>

Target:
public TopologyInfo getTopologyInfoByName(String name) throws TException { try { getTopologyInfoByNameCalls.mark(); GetInfoOptions options = new GetInfoOptions(); options.set_num_err_choice(NumErrorsChoice.ALL); return getTopologyInfoByNameImpl(name, options); } catch (Exception e) { LOG.warn("get topology info exception. (topology name={})", name, e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }
Source:
<code>public Description matchAssert(AssertTree tree, VisitorState state) { ExpressionTree condition = tree.getCondition(); <START> if (kindIs(BOOLEAN_LITERAL).matches(condition, state)) { <END> Boolean value = (Boolean) ((JCLiteral) condition).getValue(); if (!value) { Fix fix = SuggestedFix.builder() .replace(tree, "throw new AssertionError()") .build(); return describeMatch(tree, fix); } else { return Description.NO_MATCH; } } else { return Description.NO_MATCH; } }</code><technical_language>replace this Matchers.booleanLiteral(false). Also, I generally useful a matcher takes a AssertTree a Matcher<ExpressionTree>, applies matcher condition. add Matchers class, here? like: java public static Matcher<AssertTree> assertionWithCondition(final Matcher<ExpressionTree> conditionMatcher) { return new Matcher<AssertTree>() { @Override public boolean matches(AssertTree tree, VisitorState state) { return conditionMatcher.matches(tree.getCondition(), state); } }; }</technical_language>

Target:
public Description matchAssert(AssertTree tree, VisitorState state) { if (assertionWithCondition(booleanLiteral(false)).matches(tree, state)) { Fix fix = SuggestedFix.builder() .replace(tree, "throw new AssertionError()") .build(); return describeMatch(tree, fix); } else { return Description.NO_MATCH; } }
Source:
<code>private static <T extends VmBase> void addOtherDevices(T entity, List<VmDevice> vmDeviceToAdd) { boolean hasCD = false; boolean hasSoundCard = false; for (VmDevice vmDevice : entity.getManagedDeviceMap().values()) { if (isDiskOrInterface(vmDevice)) { continue; } vmDevice.setIsManaged(true); if (vmDevice.getType() == VmDeviceGeneralType.VIDEO) { vmDevice.setSpecParams(getMemExpr(entity.getNumOfMonitors(), entity.getSingleQxlPci())); } <START> if (vmDevice.getDevice().equals(VmDeviceType.CDROM.getName())){ <END> hasCD = true; } if (vmDevice.getType() == VmDeviceGeneralType.SOUND) { hasSoundCard = true; } vmDeviceToAdd.add(vmDevice); } if (!hasCD) { addEmptyCD(entity.getId()); } Version ovfVer = new Version(entity.getOvfVersion()); if (!hasSoundCard && VmDeviceCommonUtils.isOldClusterVersion(ovfVer) && entity.getVmType() == VmType.Desktop) { addSoundCard(entity); } for (VmDevice vmDevice : entity.getUnmanagedDeviceList()) { vmDeviceToAdd.add(vmDevice); } }</code><technical_language>line 815 explain problem I cd-rom caused reason</technical_language>

Target:
private static <T extends VmBase> void addOtherDevices(T entity, List<VmDevice> vmDeviceToAdd) { boolean hasCD = false; boolean hasSoundCard = false; for (VmDevice vmDevice : entity.getManagedDeviceMap().values()) { if (isDiskOrInterface(vmDevice)) { continue; } vmDevice.setIsManaged(true); if (vmDevice.getType() == VmDeviceGeneralType.VIDEO) { vmDevice.setSpecParams(getMemExpr(entity.getNumOfMonitors(), entity.getSingleQxlPci())); } if (vmDevice.getDevice().equals(VmDeviceType.CDROM.getName())){ hasCD = true; } if (VmDeviceCommonUtils.isSound(vmDevice)) { hasSoundCard = true; } vmDeviceToAdd.add(vmDevice); } if (!hasCD) { addEmptyCD(entity.getId()); } Version ovfVer = new Version(entity.getOvfVersion()); if (!hasSoundCard && VmDeviceCommonUtils.isOldClusterVersion(ovfVer) && entity.getVmType() == VmType.Desktop) { addSoundCard(entity); } for (VmDevice vmDevice : entity.getUnmanagedDeviceList()) { vmDeviceToAdd.add(vmDevice); } }
Source:
<code>public abstract void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException; private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 2 * 60); <START> public void killAll(@Nullable Process proc, @Nullable Map<String, String> modelEnvVars) throws InterruptedException { <END> LOGGER.fine("killAll: process="+proc+" and envs="+modelEnvVars); OSProcess p = get(proc); if(p!=null) p.killRecursively(); if(modelEnvVars!=null) killAll(modelEnvVars); }</code><technical_language>suggestion public void killAll(@CheckForNull Process proc, @CheckForNull Map<String, String> modelEnvVars) throws InterruptedException {</technical_language>

Target:
public abstract void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException; private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 2 * 60); public void killAll(@CheckForNull Process proc, @CheckForNull Map<String, String> modelEnvVars) throws InterruptedException { LOGGER.fine("killAll: process="+proc+" and envs="+modelEnvVars); OSProcess p = get(proc); if(p!=null) p.killRecursively(); if(modelEnvVars!=null) killAll(modelEnvVars); }
Source:
<code>public Optional<byte[]> read() { try { <START> return Optional.of(readBuffer()); <END> } catch (CANMessageUnavailableException e) { return Optional.empty(); } }</code><technical_language>this readSafely instead of readBuffer read readSafely</technical_language>

Target:
public Optional<byte[]> read() { try { return Optional.of(readSafely()); } catch (CANMessageUnavailableException e) { return Optional.empty(); } }
Source:
<code>default Attributes asReadOnly() { return new Attributes() { @Override public Collection<Entry> entries() { Collection<Entry> entries = Attributes.this.entries(); <START> Iterator<Entry> iterator = entries.iterator(); <END> return new AbstractCollection<Entry>() { @Override public Iterator<Entry> iterator() { return new Iterator<Entry>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public void remove() { throw Assert.unsupported(); } @Override public Entry next() { Entry next = iterator.next(); return new ReadOnlyAttributesEntry(Attributes.this, next.getKey()); } }; } @Override public int size() { return entries.size(); } }; } @Override public int size(String key) { return Attributes.this.size(); } @Override public String get(String key, int idx) { return Attributes.this.get(key, idx); } @Override public int size() { return Attributes.this.size(); } @Override public Entry get(String key) { return Attributes.this.get(key); } }; }</code><technical_language>This line 608 return new Iterator... else able iterate time</technical_language>

Target:
default Attributes asReadOnly() { return new Attributes() { private Map<String, Entry> entryCache = new HashMap<>(); private Collection<Entry> cachedEntries; @Override public Collection<Entry> entries() { if (this.cachedEntries != null) { return this.cachedEntries; } return this.cachedEntries = new AbstractCollection<Entry>() { @Override public Iterator<Entry> iterator() { Iterator<String> iterator = Attributes.this.keySet().iterator(); return new Iterator<Entry>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry next() { return get(iterator.next()); } }; } @Override public int size() { return Attributes.this.keySet().size(); } }; } @Override public int size(String key) { return Attributes.this.size(key); } @Override public String get(String key, int idx) { return Attributes.this.get(key, idx); } @Override public int size() { return Attributes.this.size(); } @Override public Entry get(String key) { return this.entryCache.computeIfAbsent(key, s -> new SimpleAttributesEntry(this, s)); } }; }
Source:
<code>public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(filter), Const.UTF8_CHARSET) <START> .putString(Strings.nullToEmpty(pattern.pattern()), Const.UTF8_CHARSET) <END> .hash(); return hc; }</code><technical_language>This (And other filters) need type well. reason a TagValueRegexp a filter .* a FieldRegexp filter filter want hash different. For this other regex filters, omit pattern equals hash compiled versions of filter field. ok parsed version if puts a space in front back</technical_language>

Target:
public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(filter), Const.UTF8_CHARSET) .putString(Strings.nullToEmpty(getType()), Const.UTF8_CHARSET) .hash(); return hc; }
Source:
<code>Date getDateUploaded() { String date = CommonsDateUtil.getIso8601DateFormatShort().format(dateUploaded); Date uploadDate = dateUploaded; try { <START> uploadDate = CommonsDateUtil.getIso8601DateFormatShort().parse(date); <END> } catch (ParseException e) { e.printStackTrace(); } return uploadDate; }</code><technical_language>return CommonsDateUtil.getIso8601DateFormatShort().parse(dateUploaded.getTimestamp()) null if dateUploaded is null</technical_language>

Target:
Date getDateUploaded() { return dateUploaded; }
Source:
<code>private void validateAttributesType(List<Attribute> attributes) throws InvalidProductException { String msg="Attribute type is incorrect"; for(Attribute att:attributes){ if("".equals(att.getType())){ throw new InvalidProductException(msg); } <START> String availableTypes= systemPropertiesProvider.getProperty(SystemPropertiesProvider.AVAILABLE_ATTRIBUTE_TYPES); <END> if (att.getType().length()<2 || !availableTypes.contains(att.getType())){ throw new InvalidProductException(msg); } } }</code><technical_language>mmm if is gt 120 characters</technical_language>

Target:
private void validateAttributesType(List<Attribute> attributes) throws InvalidProductException { String msg = "Attribute type is incorrect"; for (Attribute att : attributes) { if ("".equals(att.getType())) { log.warning(msg); } String availableTypes = systemPropertiesProvider .getProperty(SystemPropertiesProvider.AVAILABLE_ATTRIBUTE_TYPES); if (att.getType().length() < 2 || !availableTypes.contains(att.getType())) { throw new InvalidProductException(msg); } } }
Source:
<code>private void initInfoBanner(CourseBannerInfoModel courseBannerInfo) { if (courseBannerInfo == null) { infoBanner.setVisibility(View.GONE); return; } TextView textView = (TextView) infoBanner.findViewById(R.id.banner_info); Button button = (Button) infoBanner.findViewById(R.id.btn_shift_dates); String buttonText = ""; switch (courseBannerInfo.getDatesBannerInfo().getCourseBannerType()) { case UPGRADE_TO_GRADED: textView.setText(getText(R.string.course_dates_banner_upgrade_to_graded)); break; case UPGRADE_TO_RESET: textView.setText(getText(R.string.course_dates_banner_upgrade_to_reset)); break; case RESET_DATES: textView.setText(getText(R.string.course_dates_banner_reset_date)); buttonText = getContextOrThrow().getString(R.string.course_dates_banner_reset_date_button); break; case INFO_BANNER: textView.setText(getText(R.string.course_dates_info_banner)); break; case BLANK: infoBanner.setVisibility(View.GONE); break; } if (!TextUtils.isEmpty(textView.getText())) { if (!TextUtils.isEmpty(buttonText)) { button.setText(buttonText); <START> button.setVisibility(View.VISIBLE); <END> button.setOnClickListener(v -> { courseDateViewModel.resetCourseDatesBanner(unit.getCourseId()); }); } infoBanner.setVisibility(View.VISIBLE); } }</code><technical_language>create util for initInfoBanner & showShiftDateSnackBar muitple classes</technical_language>

Target:
private void initInfoBanner(CourseBannerInfoModel courseBannerInfo) { if (courseBannerInfo == null) { infoBanner.setVisibility(View.GONE); return; } CourseDateUtil.INSTANCE.setupCourseDatesBanner(infoBanner, courseBannerInfo, v -> courseDateViewModel.resetCourseDatesBanner(unit.getCourseId())); }
Source:
<code>public void validate(FailureCollector collector) { super.validate(collector); if (!containsMacro("username") && (Strings.isNullOrEmpty(username) ^ Strings.isNullOrEmpty(password))) { collector.addFailure("You must either set both username and password or neither username nor " + <START> "password", null).withConfigProperty("username"); <END> } if (!containsMacro("sender")) { try { InternetAddress[] addresses = InternetAddress.parse(sender); if (addresses.length == 0) { collector.addFailure("Must specify a sender email address", null).withConfigProperty("sender"); } if (addresses.length > 1) { collector.addFailure(String.format("%s is an invalid sender email address", sender), "Only one sender is supported").withConfigProperty("sender"); } } catch (AddressException e) { collector.addFailure(String.format("%s is an invalid sender email address.", sender), String.format("Reason: %s", e.getMessage())).withConfigProperty("sender"); } } if (!containsMacro("recipients")) { try { InternetAddress.parse(recipients); } catch (AddressException e) { collector.addFailure(String.format("%s is an invalid list of recipient email addresses.", recipients), String.format("Reason: %s", e.getMessage())).withConfigProperty("recipients"); } } }</code><technical_language>constant avoid typos</technical_language>

Target:
public void validate(FailureCollector collector) { super.validate(collector); if (!containsMacro(USERNAME) && (Strings.isNullOrEmpty(username) ^ Strings.isNullOrEmpty(password))) { collector.addFailure("Both username and password must be given, or neither of them must be given.", "Leave username and password fields empty or provide values for both fields.") .withConfigProperty(USERNAME).withConfigProperty(PASSWORD); } if (!containsMacro(SENDER)) { try { InternetAddress[] addresses = InternetAddress.parse(sender); if (addresses.length == 0) { collector.addFailure("Sender email was not specified.", null).withConfigProperty(SENDER); } if (addresses.length > 1) { collector.addFailure( String.format("%s is an invalid sender email address. Only one sender is supported.", sender), "Only specify one sender email address.").withConfigProperty(SENDER); } } catch (AddressException e) { collector.addFailure(String.format("%s is an invalid sender email address. Reason: %s", sender, e.getMessage()), null).withConfigProperty(SENDER); } } if (!containsMacro(RECIPIENTS)) { try { InternetAddress.parse(recipients); } catch (AddressException e) { collector.addFailure(String.format("%s is an invalid list of recipient email addresses. Reason: %s", recipients, e.getMessage()), null) .withConfigProperty(RECIPIENTS); } } }
Source:
<code>private String obtainFailureMessage(PatchsetCreated event, AbstractBuild build, TaskListener listener) throws IOException, InterruptedException { AbstractProject project = build.getProject(); String content = null; GerritTrigger trigger = GerritTrigger.getTrigger(project); String filename = trigger.getBuildUnsuccessfulFilepath(); if (filename != null && !filename.isEmpty()) { <START> FilePath path = build.getWorkspace().child(filename); <END> if (path.exists()) { content = path.readToString(); } EnvVars envVars = (listener == null) ? build.getEnvironment() : build.getEnvironment(listener); content = envVars.expand(content); } return content; }</code><technical_language>If env vars in file name "gerrit-$BUILD_NUMBER-error.txt" problem preexisting error files in workspace previous builds avoided if user wants to</technical_language>

Target:
private String obtainFailureMessage(PatchsetCreated event, AbstractBuild build, TaskListener listener) throws IOException, InterruptedException { AbstractProject project = build.getProject(); String content = null; GerritTrigger trigger = GerritTrigger.getTrigger(project); if (trigger != null) { String filepath = trigger.getBuildUnsuccessfulFilepath(); logger.debug("Looking for failure message in file glob: {}", filepath); if (filepath != null && !filepath.isEmpty()) { EnvVars envVars; if (listener == null) { envVars = build.getEnvironment(); } else { envVars = build.getEnvironment(listener); } filepath = envVars.expand(filepath); FilePath[] matches = this.getMatchingWorkspaceFiles(build.getWorkspace(), filepath); logger.debug("Found matching workspace files: {}", matches); if (matches.length > 0) { FilePath path = matches[0]; content = this.getExpandedContent(path, envVars); logger.info("Obtained failure message from file: {}", content); } } } return content; }
Source:
<code>public LiveData<List<Allergy>> getAllergies(RestApi restApi, String uuid) { MutableLiveData<List<Allergy>> allergyLiveData = new MutableLiveData<>(); allergyEntitiesOffline = allergyRoomDAO.getAllAllergiesByPatientID(patientID); <START> allergyLiveData.setValue(AppDatabaseHelper.INSTANCE.allergyEntityListToAllergyList(allergyEntitiesOffline)); <END> if (NetworkUtils.isOnline()) { restApi.getAllergies(uuid).enqueue(new Callback<Results<Allergy>>() { @Override public void onResponse(@NotNull Call<Results<Allergy>> call, @NotNull Response<Results<Allergy>> response) { if (response.isSuccessful()) { allergyRoomDAO.deleteAllPatientAllergy(patientID); allergyList = response.body().getResults(); for (Allergy allergy : allergyList) { allergyRoomDAO.saveAllergy(AppDatabaseHelper.INSTANCE.convert(allergy, patientID)); } allergyLiveData.setValue(allergyList); } else { ToastUtil.error(OpenMRS.getInstance().getString(R.string.unable_to_fetch_allergies)); } } @Override public void onFailure(@NotNull Call<Results<Allergy>> call, @NotNull Throwable t) { ToastUtil.error(OpenMRS.getInstance().getString(R.string.unable_to_fetch_allergies)); } }); } return allergyLiveData; }</code><technical_language>suggestion allergyLiveData.setValue(AppDatabaseHelper.convertTo(allergyEntitiesOffline));</technical_language>

Target:
public LiveData<List<Allergy>> getAllergies(RestApi restApi, String uuid) { MutableLiveData<List<Allergy>> allergyLiveData = new MutableLiveData<>(); allergyEntitiesOffline = allergyRoomDAO.getAllAllergiesByPatientID(patientID); allergyLiveData.setValue(AppDatabaseHelper.convertTo(allergyEntitiesOffline)); if (NetworkUtils.isOnline()) { restApi.getAllergies(uuid).enqueue(new Callback<Results<Allergy>>() { @Override public void onResponse(@NotNull Call<Results<Allergy>> call, @NotNull Response<Results<Allergy>> response) { if (response.isSuccessful()) { allergyRoomDAO.deleteAllPatientAllergy(patientID); allergyList = response.body().getResults(); for (Allergy allergy : allergyList) { allergyRoomDAO.saveAllergy(AppDatabaseHelper.convert(allergy, patientID)); } allergyLiveData.setValue(allergyList); } else { ToastUtil.error(OpenMRS.getInstance().getString(R.string.unable_to_fetch_allergies)); } } @Override public void onFailure(@NotNull Call<Results<Allergy>> call, @NotNull Throwable t) { ToastUtil.error(OpenMRS.getInstance().getString(R.string.unable_to_fetch_allergies)); } }); } return allergyLiveData; }
Source:
<code>protected ConfigNodeObject changeValueOnPath(Path desiredPath, AbstractConfigNodeValue value) { ArrayList<AbstractConfigNode> childrenCopy = new ArrayList(super.children); AbstractConfigNodeValue valueCopy = value; for (int i = super.children.size() - 1; i >= 0; i--) { if (!(super.children.get(i) instanceof ConfigNodeField)) { continue; } ConfigNodeField node = (ConfigNodeField)super.children.get(i); Path key = node.path().value(); if (key.equals(desiredPath)) { if (valueCopy == null) childrenCopy.remove(i); else { childrenCopy.set(i, node.replaceValue(value)); valueCopy = null; } } else if (desiredPath.startsWith(key)) { if (node.value() instanceof ConfigNodeObject) { Path remainingPath = desiredPath.subPath(key.length()); childrenCopy.set(i, node.replaceValue(((ConfigNodeObject)node.value()).changeValueOnPath(remainingPath, valueCopy))); <START> if (valueCopy != null && node.render() != super.children.get(i).render()) <END> valueCopy = null; } } } return new ConfigNodeObject(childrenCopy); }</code><technical_language>I guess != equals, I if renders equal original nodes equal ... if want implement equals() render(), do in AbstractConfigNode</technical_language>

Target:
protected ConfigNodeObject changeValueOnPath(Path desiredPath, AbstractConfigNodeValue value) { ArrayList<AbstractConfigNode> childrenCopy = new ArrayList(super.children); AbstractConfigNodeValue valueCopy = value; for (int i = super.children.size() - 1; i >= 0; i--) { if (!(super.children.get(i) instanceof ConfigNodeField)) { continue; } ConfigNodeField node = (ConfigNodeField)super.children.get(i); Path key = node.path().value(); if (key.equals(desiredPath)) { if (valueCopy == null) childrenCopy.remove(i); else { childrenCopy.set(i, node.replaceValue(value)); valueCopy = null; } } else if (desiredPath.startsWith(key)) { if (node.value() instanceof ConfigNodeObject) { Path remainingPath = desiredPath.subPath(key.length()); childrenCopy.set(i, node.replaceValue(((ConfigNodeObject)node.value()).changeValueOnPath(remainingPath, valueCopy))); if (valueCopy != null && !node.equals(super.children.get(i))) valueCopy = null; } } } return new ConfigNodeObject(childrenCopy); }
Source:
<code>public StateItem(RGB stateColor, String stateString) { Map<String, Object> styleMap = new HashMap<>(); String hexColor = <START> X11ColorUtils.toHexColor(stateColor.red, <END> stateColor.green, stateColor.blue); styleMap.put(StyleProperties.BACKGROUND_COLOR, hexColor); styleMap.put(StyleProperties.COLOR, hexColor); styleMap.put(StyleProperties.STYLE_NAME, stateString); fStyleMap = styleMap; fOriginalStyleMap = ImmutableMap.copyOf(styleMap); }</code><technical_language>ColorUtils</technical_language>

Target:
public StateItem(RGB stateColor, String stateString) { Map<String, Object> styleMap = new HashMap<>(); String hexColor = ColorUtils.toHexColor(stateColor.red, stateColor.green, stateColor.blue); styleMap.put(StyleProperties.BACKGROUND_COLOR, hexColor); styleMap.put(StyleProperties.COLOR, hexColor); styleMap.put(StyleProperties.STYLE_NAME, stateString); fStyleMap = styleMap; fOriginalStyleMap = ImmutableMap.copyOf(styleMap); }
Source:
<code>RecordFlow evictAckedEventAndScheduleNextEvent(RecordsDeliveryAck recordsDeliveryAck) { final RecordsRetrievedContext recordsRetrievedContext = recordsDeliveryQueue.peek(); RecordFlow flowToBeReturned = null; if (recordsRetrievedContext != null && recordsRetrievedContext.getRecordsRetrieved().batchUniqueIdentifier() .equals(recordsDeliveryAck.batchUniqueIdentifier())) { recordsDeliveryQueue.poll(); takeDelayedDeliveryActionIfRequired(shardId, recordsRetrievedContext.getEnqueueTimestamp(), log); currentSequenceNumber = ((FanoutRecordsRetrieved)recordsRetrievedContext.getRecordsRetrieved()).continuationSequenceNumber(); flowToBeReturned = recordsRetrievedContext.getRecordFlow(); <START> if (recordsDeliveryQueue.peek() != null) { <END> scheduleNextEvent(recordsDeliveryQueue.peek().getRecordsRetrieved()); } } else { if (flow != null && recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier() .equals(flow.getSubscribeToShardId())) { log.error( "{}: Received unexpected ack for the active subscription {}. Throwing. ", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); throw new IllegalStateException("Unexpected ack for the active subscription"); } else { log.info("{}: Publisher received an ack for stale subscription {}. Ignoring.", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); } } return flowToBeReturned; }</code><technical_language>check isEmpty()</technical_language>

Target:
RecordFlow evictAckedEventAndScheduleNextEvent(RecordsDeliveryAck recordsDeliveryAck) { final RecordsRetrievedContext recordsRetrievedContext = recordsDeliveryQueue.peek(); RecordFlow flowToBeReturned = null; if (recordsRetrievedContext != null && recordsRetrievedContext.getRecordsRetrieved().batchUniqueIdentifier() .equals(recordsDeliveryAck.batchUniqueIdentifier())) { recordsDeliveryQueue.poll(); takeDelayedDeliveryActionIfRequired(shardId, recordsRetrievedContext.getEnqueueTimestamp(), log); currentSequenceNumber = ((FanoutRecordsRetrieved)recordsRetrievedContext.getRecordsRetrieved()).continuationSequenceNumber(); flowToBeReturned = recordsRetrievedContext.getRecordFlow(); if (!recordsDeliveryQueue.isEmpty()) { scheduleNextEvent(recordsDeliveryQueue.peek().getRecordsRetrieved()); } } else { if (flow != null && recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier() .equals(flow.getSubscribeToShardId())) { log.error( "{}: Received unexpected ack for the active subscription {}. Throwing. ", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); throw new IllegalStateException("Unexpected ack for the active subscription"); } else { log.info("{}: Publisher received an ack for stale subscription {}. Ignoring.", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); } } return flowToBeReturned; }
Source:
<code>public void sendTrainingData(int diseaseGroupId, List<DiseaseOccurrence> occurrences) throws JsonProcessingException, WebServiceClientException { <START> String url = rootUrl + diseaseGroupId + "/train"; <END> JsonDiseaseOccurrenceDataSet data = convertToDTO(occurrences); String bodyAsJson = writeRequestBodyAsJson(data); webServiceClient.makePostRequestWithJSON(url, bodyAsJson); }</code><technical_language>Constant</technical_language>

Target:
public void sendTrainingData(int diseaseGroupId, List<DiseaseOccurrence> occurrences) throws JsonProcessingException, WebServiceClientException { String url = buildUrl(diseaseGroupId, TRAIN_METHOD); JsonDiseaseOccurrenceDataSet data = convertToDTO(occurrences); String bodyAsJson = writeRequestBodyAsJson(data); webServiceClient.makePostRequestWithJSON(url, bodyAsJson); }
Source:
<code>default <T> T decode(Type type, String value) { <START> return decode((Class<T>)type, value); <END> }</code><technical_language>if type is Class type</technical_language>

Target:
default <T> T decode(Type type, String value) { if (type instanceof Class) { return decode((Class<T>)type, value); } else { throw new UnsupportedOperationException("This decoder " + getClass() + " does not support Type"); } }
Source:
<code>private List<TriggerEventRequest> buildCohortQueryTriggers(String configName) { List<TriggerEventRequest> triggers = new ArrayList<>(); List<EventParameterRequest> parameterRequests = new ArrayList<>(); parameterRequests.add(new EventParameterRequest(DisplayNames.PATIENT_UUID, Keys.PATIENT_UUID)); parameterRequests.add(new EventParameterRequest(DisplayNames.PATIENT_DISPLAY, Keys.PATIENT_DISPLAY)); parameterRequests.add(new EventParameterRequest(DisplayNames.COHORT_QUERY_UUID, Keys.COHORT_QUERY_UUID)); String displayName = DisplayNameHelper.buildDisplayName(DisplayNames.COHORT_QUERY_REPORTMEMBER, configName); <START> triggers.add(new TriggerEventRequest(displayName, EventSubjects.GET_COHORT_QUERY_MEMBER_EVENT.concat(".").concat(configName), <END> null, parameterRequests)); return triggers; }</code><technical_language>change event subject in 'Get CohortQuery Task Action'. Moreover, this provider mentioned action constant</technical_language>

Target:
private List<TriggerEventRequest> buildCohortQueryTriggers(String configName) { List<TriggerEventRequest> triggers = new ArrayList<>(); List<EventParameterRequest> parameterRequests = new ArrayList<>(); parameterRequests.add(new EventParameterRequest(DisplayNames.PATIENT_UUID, Keys.PATIENT_UUID)); parameterRequests.add(new EventParameterRequest(DisplayNames.PATIENT_DISPLAY, Keys.PATIENT_DISPLAY)); parameterRequests.add(new EventParameterRequest(DisplayNames.COHORT_QUERY_UUID, Keys.COHORT_QUERY_UUID)); String displayName = DisplayNameHelper.buildDisplayName(DisplayNames.COHORT_QUERY_REPORTMEMBER, configName); triggers.add(new TriggerEventRequest(displayName, EventSubjects.GET_COHORT_QUERY_MEMBER_EVENT.concat(configName), null, parameterRequests)); return triggers; }
Source:
<code>public void manageTransitions(RingGroup ringGroup) throws IOException { DomainGroup domainGroup = ringGroup.getDomainGroup(); if (domainGroup == null) { LOG.info("Domain group not found. Nothing to do."); return; } <START> int numRingGroups = ringGroup.getRings().size(); <END> Map<Domain, Map<Integer, Set<Host>>> domainToPartitionToHostsFullyServing = computeDomainToPartitionToHostsFullyServing(ringGroup); for (Ring ring : ringGroup.getRingsSorted()) { partitionAssigner.prepare(ring, domainGroup.getDomainVersions(), ringGroup.getRingGroupConductorMode()); for (Host host : ring.getHostsSorted()) { manageTransitions(host, domainGroup, domainToPartitionToHostsFullyServing); } } }</code><technical_language>unused</technical_language>

Target:
public void manageTransitions(RingGroup ringGroup) throws IOException { DomainGroup domainGroup = ringGroup.getDomainGroup(); if (domainGroup == null) { LOG.info("Domain group not found. Nothing to do."); return; } Map<Domain, Map<Integer, Set<Host>>> domainToPartitionToHostsFullyServing = computeDomainToPartitionToHostsFullyServing(ringGroup); for (Ring ring : ringGroup.getRingsSorted()) { partitionAssigner.prepare(ring, domainGroup.getDomainVersions(), ringGroup.getRingGroupConductorMode()); for (Host host : ring.getHostsSorted()) { manageTransitions(host, domainGroup, domainToPartitionToHostsFullyServing); } } }
Source:
<code><START> private Node maybeReassignAlias(Node assign) { <END> Node lhs = assign.getFirstChild(); if (!lhs.isGetProp()) { return null; } String alias = null; for (Node child = lhs; child != null; child = child.getFirstChild()) { if (child.isName()) { alias = child.getQualifiedName(); } } checkNotNull(alias, "Missing name for alias"); if (aliasToProvidedNamespace.containsKey(alias)) { String providedNamespace = aliasToProvidedNamespace.get(alias); String suffix = lhs.getQualifiedName().substring(alias.length()); Node fullName = NodeUtil.newQName(compiler, providedNamespace + suffix); assign.replaceChild(lhs, fullName); compiler.reportCodeChange(); } return null; }</code><technical_language>This function returns null? right</technical_language>

Target:
private void maybeReassignAlias(Node assign) { Node lhs = assign.getFirstChild(); if (!lhs.isGetProp()) { return; } String alias = null; for (Node child = lhs; child != null; child = child.getFirstChild()) { if (child.isName()) { alias = child.getQualifiedName(); } } checkNotNull(alias, "Missing name for alias"); if (aliasToProvidedNamespace.containsKey(alias)) { String providedNamespace = aliasToProvidedNamespace.get(alias); String suffix = lhs.getQualifiedName().substring(alias.length()); Node fullName = NodeUtil.newQName(compiler, providedNamespace + suffix); assign.replaceChild(lhs, fullName); compiler.reportCodeChange(); } return; }
Source:
<code>ProfileDescriptor getUserProfile() throws ApiException, IOException, JsonParseException { final String profileDescriptor = HttpJsonHelper.requestString(profileApiUrl, "GET", null); <START> return DtoFactory.getInstance().createDtoFromJson(profileDescriptor, ProfileDescriptor.class); <END> }</code><technical_language>DtoFactory.newDto</technical_language>

Target:
ProfileDescriptor getUserProfile() throws ApiException, IOException, JsonParseException { return HttpJsonHelper.request(ProfileDescriptor.class, profileApiUrl, HttpMethod.GET, null); }
Source:
<code>public static <T,V> FactorFilter<T,V> create(String factorName, Filter<T,V> filter){ if (null == factorName || factorName == "" || null == filter){ logger.error("failed to create instance of FactorFilter, at least one of the input paramters are invalid"); <START> return null; <END> } return new FactorFilter<T,V>(factorName,filter); }</code><technical_language>throw exception</technical_language>

Target:
public static <T,V> FactorFilter<T,V> create(String factorName, Filter<T,V> filter){ if (null == factorName || factorName.length() == 0 || null == filter){ logger.error("failed to create instance of FactorFilter, at least one of the input paramters are invalid"); return null; } return new FactorFilter<T,V>(factorName,filter); }
Source:
<code>private <A> Cases<A, SimpleExpression<A>> thenSimple(Expression<A> expr) { <START> return new Cases<A, SimpleExpression<A>>((Class)expr.getType()) { <END> @Override protected SimpleExpression<A> createResult(Class<A> type, Expression<A> last) { return Expressions.operation(type, Ops.CASE, last); } }.addCase(when, expr); }</code><technical_language>I relaxing type parameter in Cases' type,createResult constructor Class<? extends A> helps a lot eliminate casts **and** @SuppressWarnings</technical_language>

Target:
private <A> Cases<A, SimpleExpression<A>> thenSimple(Expression<A> expr) { return new Cases<A, SimpleExpression<A>>(expr.getType()) { @Override protected SimpleExpression<A> createResult(Class<? extends A> type, Expression<A> last) { return Expressions.operation(type, Ops.CASE, last); } }.addCase(when, expr); }
Source:
<code><START> public void updateItem(T item) { <END> mAlgorithm.lock(); try { mAlgorithm.updateItem(item); } finally { mAlgorithm.unlock(); } }</code><technical_language>Thoughts returning a bool here? helpful if item update updated (and if not, signal developer need implement equals hashcode)</technical_language>

Target:
public boolean updateItem(T item) { mAlgorithm.lock(); try { return mAlgorithm.updateItem(item); } finally { mAlgorithm.unlock(); } }
Source:
<code>long getWord(int index) { if (index == 0) { return elements1; <START> } else { <END> if (index == 1) { return elements2; } else { return 0L; } } }</code><technical_language>merge else if</technical_language>

Target:
long getWord(int index) { if (index == 0) { return elements1; } else if (index == 1) { return elements2; } else { throw new IndexOutOfBoundsException(); } }
Source:
<code>private Map<String, String> generateThirdPartyNameToFullModuleName(ClassLoader loader) { Map<String, String> returnValue; try { final ClassPath classPath = ClassPath.from(loader); <START> returnValue = packages.stream().map(pkg -> pkg.substring(0, pkg.length() - 1)) <END> .flatMap(pkg -> classPath.getTopLevelClasses(pkg).stream()) .map(ClassPath.ClassInfo::load) .filter(PackageObjectFactory::shouldAddToThirdPartyMap) .collect(Collectors.toMap(Class::getSimpleName, Class::getCanonicalName)); } catch (IOException ignore) { returnValue = new HashMap<>(); } return returnValue; }</code><technical_language>This complicated review easily. simplify it</technical_language>

Target:
private Map<String, String> generateThirdPartyNameToFullModuleName(ClassLoader loader) { Map<String, String> returnValue; try { returnValue = ModuleReflectionUtils.getCheckstyleModules(packages, loader).stream() .collect(Collectors.toMap(Class::getSimpleName, Class::getCanonicalName)); } catch (IOException ignore) { returnValue = new HashMap<>(); } return returnValue; }
Source:
<code>public void buyFromBank(Market <START> m, String <END> symbol, int volume) throws StockMarketExpection { if ((double)volume * m.getStockForSymbol(symbol).getPrice() > cashInHand) { throw new StockMarketExpection("Not enough cash in hand to place buy order."); } int previousVolume = 0; for (Order order: position) { if (order.getStockSymbol() == symbol) { previousVolume += order.getSize(); position.remove(order); break; } } Order newOrder = new BuyOrder(symbol, volume + previousVolume, m.getStockForSymbol(symbol).getPrice(), this); this.position.add(newOrder); this.cashInHand -= (double)volume * m.getStockForSymbol(symbol).getPrice(); }</code><technical_language>needs named more relevant market</technical_language>

Target:
public void buyFromBank(Market m, String symbol, int volume) throws StockMarketExpection { if ((double)volume * m.getStockForSymbol(symbol).getPrice() > cashInHand) { throw new StockMarketExpection("Not enough cash in hand to place buy order."); } int previousVolume = 0; for (Order order: possession) { if (order.getStockSymbol() == symbol) { previousVolume += order.getSize(); possession.remove(order); break; } } Order newOrder = new BuyOrder(symbol, volume + previousVolume, m.getStockForSymbol(symbol).getPrice(), this); this.possession.add(newOrder); this.cashInHand -= (double)volume * m.getStockForSymbol(symbol).getPrice(); }
Source:
<code>public void quotaTest() throws Exception { Properties props = new Properties(); props.setProperty(FrontendConfig.REST_REQUEST_QUOTA_STRING, "{\"PUT\": \"20\",\"GET\": \"20\",\"POST\": \"20\",\"HEAD\": \"20\",\"OPTIONS\": \"20\",\"UNKNOWN\": \"20\",\"DELETE\": \"20\"}"); FrontendConfig frontendConfig = new FrontendConfig(new VerifiableProperties(props)); RejectThrottlerTest.MockClock clock = new RejectThrottlerTest.MockClock(); QuotaManager quotaManager = new MockQuotaManager(frontendConfig, clock); for (int i = 0; i < 100; i++) { <START> for (RestMethod resetMethod : RestMethod.values()) { <END> RestRequest restRequest = createRestRequest(resetMethod, "<LINK_0>", null, null); Assert.assertFalse("Should not throttle", quotaManager.shouldThrottle(restRequest)); } } clock.tick(5); for (RestMethod resetMethod : RestMethod.values()) { RestRequest restRequest = createRestRequest(resetMethod, "<LINK_0>", null, null); Assert.assertTrue("Should throttle", quotaManager.shouldThrottle(restRequest)); } clock.tick(5); for (RestMethod resetMethod : RestMethod.values()) { RestRequest restRequest = createRestRequest(resetMethod, "<LINK_0>", null, null); Assert.assertFalse("Should not throttle", quotaManager.shouldThrottle(restRequest)); } }</code><technical_language>swap resetMethod restMethod in this method (48, 55, 61)</technical_language>

Target:
public void quotaTest() throws Exception { Properties props = new Properties(); props.setProperty(FrontendConfig.REST_REQUEST_QUOTA_STRING, "{\"PUT\": \"20\",\"GET\": \"20\",\"POST\": \"20\",\"HEAD\": \"20\",\"OPTIONS\": \"20\",\"DELETE\": \"20\"}"); FrontendConfig frontendConfig = new FrontendConfig(new VerifiableProperties(props)); RejectThrottlerTest.MockClock clock = new RejectThrottlerTest.MockClock(); QuotaManager quotaManager = new QuotaManager(createQuotaMock(frontendConfig, clock)); for (int i = 0; i < 100; i++) { for (RestMethod restMethod : RestMethod.values()) { RestRequest restRequest = createRestRequest(restMethod, "<LINK_0>", null, null); Assert.assertFalse("Should not throttle", quotaManager.shouldThrottle(restRequest)); } } clock.tick(5); for (RestMethod restMethod : RestMethod.values()) { RestRequest restRequest = createRestRequest(restMethod, "<LINK_0>", null, null); if (restMethod == RestMethod.UNKNOWN) { Assert.assertFalse("Should not throttle.", quotaManager.shouldThrottle(restRequest)); } else { Assert.assertTrue("Should throttle", quotaManager.shouldThrottle(restRequest)); } } clock.tick(5); for (RestMethod restMethod : RestMethod.values()) { RestRequest restRequest = createRestRequest(restMethod, "<LINK_0>", null, null); Assert.assertFalse("Should not throttle", quotaManager.shouldThrottle(restRequest)); } }
Source:
<code>protected void starting(org.junit.runner.Description description) { TestUtils.deleteTargetTestClassFolder(description); String methodName = description.getMethodName(); String className = description.getClassName(); this.dataDirectory = "target/" + className + "/" + methodName + "/data"; try { filePaths = createData(this.dataDirectory); } catch (IOException e) { throw new RuntimeException(e); } fileSplitterInput = new FileSplitterInput(); scanner = new MockScanner(); fileSplitterInput.setScanner(scanner); fileSplitterInput.getScanner().setScanIntervalMillis(500); fileSplitterInput.getScanner().setFilePatternRegularExp(".*[.]txt"); <START> fileSplitterInput.getScanner().setFiles(new File(dataDirectory).getAbsolutePath()); <END> Attribute.AttributeMap.DefaultAttributeMap attributes = new Attribute.AttributeMap.DefaultAttributeMap(); attributes.put(Context.DAGContext.APPLICATION_PATH, "target/" + className + "/" + methodName + "/" + Long.toHexString(System.currentTimeMillis())); context = new OperatorContextTestHelper.TestIdOperatorContext(0, attributes); fileSplitterInput.setup(context); fileMetadataSink = new CollectorTestSink<>(); TestUtils.setSink(fileSplitterInput.filesMetadataOutput, fileMetadataSink); blockMetadataSink = new CollectorTestSink<>(); TestUtils.setSink(fileSplitterInput.blocksMetadataOutput, blockMetadataSink); }</code><technical_language>@DT-Priyanka user add relative absolute path. imposing adding absolute path user</technical_language>

Target:
protected void starting(org.junit.runner.Description description) { TestUtils.deleteTargetTestClassFolder(description); String methodName = description.getMethodName(); String className = description.getClassName(); this.dataDirectory = "target/" + className + "/" + methodName + "/data"; try { filePaths = createData(this.dataDirectory); } catch (IOException e) { throw new RuntimeException(e); } fileSplitterInput = new FileSplitterInput(); scanner = new MockScanner(); fileSplitterInput.setScanner(scanner); fileSplitterInput.getScanner().setScanIntervalMillis(500); fileSplitterInput.getScanner().setFilePatternRegularExp(".*[.]txt"); fileSplitterInput.getScanner().setFiles(dataDirectory); Attribute.AttributeMap.DefaultAttributeMap attributes = new Attribute.AttributeMap.DefaultAttributeMap(); attributes.put(Context.DAGContext.APPLICATION_PATH, "target/" + className + "/" + methodName + "/" + Long.toHexString(System.currentTimeMillis())); context = new OperatorContextTestHelper.TestIdOperatorContext(0, attributes); fileSplitterInput.setup(context); fileMetadataSink = new CollectorTestSink<>(); TestUtils.setSink(fileSplitterInput.filesMetadataOutput, fileMetadataSink); blockMetadataSink = new CollectorTestSink<>(); TestUtils.setSink(fileSplitterInput.blocksMetadataOutput, blockMetadataSink); }