auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void createTestDepartment(String name, String description, List<Person> members, List<Person> departmentHeads, List<Person> secondStageAuthorities) { Department department = new Department(); department.setName(name); department.setDescription(description); department.setLastModification(ZonedDateTime.now(UTC).toLocalDate()); department.setMembers(members); department.setDepartmentHeads(departmentHeads); department.setSecondStageAuthorities(secondStageAuthorities); if (!secondStageAuthorities.isEmpty()) { department.setTwoStageApproval(true); } departmentService.create(department); }

Target:
void createTestDepartment(String name, String description, List<Person> members, List<Person> departmentHeads, List<Person> secondStageAuthorities) { Department department = new Department(); department.setName(name); department.setDescription(description); department.setLastModification(LocalDate.now(UTC)); department.setMembers(members); department.setDepartmentHeads(departmentHeads); department.setSecondStageAuthorities(secondStageAuthorities); if (!secondStageAuthorities.isEmpty()) { department.setTwoStageApproval(true); } departmentService.create(department); }
Source:
private String createText(String message, boolean success) { String textToSend = uuid + ": " + message; if (!success) { textToSend = uuid + ": failed-" + message; } return textToSend; }

Target:
private String createText(String message, boolean success) { String textToSend = message; if (!success) { textToSend = "failed-" + message; } return textToSend; }
Source:
public Object[] value(SearchHit hit) { Object[] value = super.value(hit); if (value.length == 0) { return new Object[0]; } if (value.length > 1) { throw new IllegalStateException("Unexpected values for a geo_point field: " + Arrays.toString(value)); } if (value[0] instanceof String) { value[0] = handleString((String) value[0]); } else { throw new IllegalStateException("Unexpected value type for a geo_point field: " + value[0].getClass()); } return value; }

Target:
public Object[] value(SearchHit hit) { Object[] value = super.value(hit); if (value.length == 0) { return value; } if (value.length > 1) { throw new IllegalStateException("Unexpected values for a geo_point field: " + Arrays.toString(value)); } if (value[0] instanceof String) { value[0] = handleString((String) value[0]); } else { throw new IllegalStateException("Unexpected value type for a geo_point field: " + value[0].getClass()); } return value; }
Source:
protected List<String> getProcessOutput(Process p) { List<String> lines = new ArrayList<String>(); if (p == null) { return lines; } InputStream in = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; try { while ((line = reader.readLine()) != null) { lines.add(line); } } catch (IOException ignore) { } return lines; }

Target:
protected List<String> getProcessOutput(Process p) { List<String> lines = new ArrayList<String>(); if (p == null) { return lines; } InputStream in = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; try { while ((line = reader.readLine()) != null) { if (lines.size() < 10000) { lines.add(line); } else { lines.add("(log output truncated)"); break; } } } catch (IOException e) { lines.add("Failed to read log output due to " + e.getClass().getName()); lines.add(e.getMessage()); } finally { try { reader.close(); } catch (IOException ignore) } return lines; }
Source:
public boolean contains(Object o) { return fInnerElements.containsValue(o); }

Target:
public boolean contains(Object o) { return (o == null && size() > fInnerElements.size()) || fInnerElements.containsValue(o); }
Source:
public boolean hasSpaceForSnapthosts(VM vm) { Map<storage_domains, Integer> map = mapStorageDomainsToNumOfDisks(vm); Integer minSnapshotSize = Config.<Integer> GetValue(ConfigValues.InitStorageSparseSizeInGB); for (storage_domains domain : map.keySet()) { if (!StorageDomainSpaceChecker.hasSpaceForRequest(domain, minSnapshotSize * map.get(domain))) { log.error("not enough space to create snapshot on domain {0}" + domain.getId()); return false; } } return true; }

Target:
public boolean hasSpaceForSnapthosts(VM vm) { Map<storage_domains, Integer> map = mapStorageDomainsToNumOfDisks(vm); Integer minSnapshotSize = Config.<Integer> GetValue(ConfigValues.InitStorageSparseSizeInGB); for (storage_domains domain : map.keySet()) { if (!StorageDomainSpaceChecker.hasSpaceForRequest(domain, minSnapshotSize * map.get(domain))) { log.error("not enough space to create snapshot on domain " + domain.getId()); return false; } } return true; }
Source:
CryptoJobHandler(int threadCount, long cryptoJobTimeoutMs, Time time) { this.cryptoJobTimeoutMs = cryptoJobTimeoutMs; enabled.set(true); scheduler = Executors.newFixedThreadPool(threadCount); this.time = time; }

Target:
CryptoJobHandler(int threadCount, long cryptoJobTimeoutMs, Time time) { this.cryptoJobTimeoutMs = cryptoJobTimeoutMs; enabled.set(true); executor = Executors.newFixedThreadPool(threadCount); this.time = time; }
Source:
public int compareTo(@Nullable ISegment o) { if (o == null) { throw new IllegalArgumentException(); } Comparator<ISegment> comparator = Ordering .from(SegmentComparators.INTERVAL_START_COMPARATOR) .compound(SegmentComparators.INTERVAL_END_COMPARATOR) .compound(Ordering.usingToString()); return comparator.compare(this, o); }

Target:
public int compareTo(@Nullable ISegment o) { if (o == null) { throw new IllegalArgumentException(); } return COMPARATOR.compare(this, o); }
Source:
protected boolean sendDataOut(SimpleBinaryItemData data) { if (LINE_STABILIZATION_TIME > 0) { while (Math.abs(System.currentTimeMillis() - receiveTime) <= LINE_STABILIZATION_TIME) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } if (logger.isDebugEnabled()) { logger.debug("Port - Sending data to device with length bytes", this.deviceID, data.getDeviceId(), data.getData().length); logger.debug("Port - data: {}", this.deviceID, SimpleBinaryProtocol.arrayToString(data.getData(), data.getData().length)); } if (compareAndSetWaitingForAnswer()) { try { if (this.forceRTS) { if (logger.isDebugEnabled()) { logger.debug("Port - RTS set", this.deviceID); } sentTimeTicks = System.currentTimeMillis() + (((data.getData().length * 8) + 4) * 1000 / this.baud); serialPort.setRTS(invertedRTS ? false : true); } outputStream.write(data.getData()); outputStream.flush(); setLastSentData(data); } catch (IOException e) { logger.error("Port - Error while writing", this.deviceID); reconnect(); return false; } return true; } else { if (logger.isDebugEnabled()) { logger.debug("Port - Sending data to device discarted. Another send/wait is processed.", this.deviceID, data.getDeviceId()); } return false; } }

Target:
protected boolean sendDataOut(SimpleBinaryItemData data) { if (!this.connected) { logger.debug("{} - Port is closed. Try to reopen."); if (!this.open()) { logger.warn("{} - Port is closed. Unable to send data to device {}.", this.toString(), data.getDeviceId()); return false; } } if (LINE_STABILIZATION_TIME > 0) { while (Math.abs(System.currentTimeMillis() - receiveTime) <= LINE_STABILIZATION_TIME) { try { Thread.sleep(10); } catch (InterruptedException e) { } } } if (logger.isDebugEnabled()) { logger.debug("{} - Sending data to device with length bytes", this.toString(), data.getDeviceId(), data.getData().length); logger.debug("{} - data: {}", this.toString(), SimpleBinaryProtocol.arrayToString(data.getData(), data.getData().length)); } if (compareAndSetWaitingForAnswer()) { try { if (this.forceRTS) { if (logger.isDebugEnabled()) { logger.debug("{} - RTS set", this.toString()); } sentTimeTicks = System.currentTimeMillis() + (((data.getData().length * 8) + 4) * 1000 / this.baud); serialPort.setRTS(invertedRTS ? false : true); } outputStream.write(data.getData()); outputStream.flush(); setLastSentData(data); } catch (Exception e) { logger.error("{} - Error while writing", this.toString()); reconnect(); return false; } return true; } else { if (logger.isDebugEnabled()) { logger.debug("{} - Sending data to device discarted. Another send/wait is processed.", this.toString(), data.getDeviceId()); } return false; } }
Source:
public void testToDate() throws Exception { DateFormat dateFormat = DateUtils .createDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); assertEquals("2008-11-04 00:00:00.000", dateFormat.format(TimeComparator.toDate("08-11-04"))); assertEquals("2010-09-21 14:06:00.000", dateFormat.format(TimeComparator.toDate("2010-09-21 14:06"))); assertEquals("2010-09-21 14:06:13.000", dateFormat.format(TimeComparator.toDate("2010-09-21 14:06:13"))); assertEquals("2010-09-21 14:06:13.009", dateFormat.format(TimeComparator .toDate("2010-09-21 14:06:13.009"))); assertEquals("2000-12-31 02:30:05.100", dateFormat.format(TimeComparator .toDate("2000-12-31 02:30:05.100"))); assertEquals("Fri Jan 04 15:55:51 CET 2013", TimeComparator.toDate("2013-01-04T15:55:51.217+01:00").toString()); }

Target:
public void testToDate() throws Exception { DateFormat dateFormat = DateUtils .createDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); assertEquals("2008-11-04 00:00:00.000", dateFormat.format(TimeComparator.toDate("08-11-04"))); assertEquals("2010-09-21 14:06:00.000", dateFormat.format(TimeComparator.toDate("2010-09-21 14:06"))); assertEquals("2010-09-21 14:06:13.000", dateFormat.format(TimeComparator.toDate("2010-09-21 14:06:13"))); assertEquals("2010-09-21 14:06:13.009", dateFormat.format(TimeComparator .toDate("2010-09-21 14:06:13.009"))); assertEquals("2000-12-31 02:30:05.100", dateFormat.format(TimeComparator .toDate("2000-12-31 02:30:05.100"))); }
Source:
public Pair<String, String> get(RuntimeIdentity runtimeIdentity) throws InfrastructureException { if (wsAgentCorsAllowCredentials == null) { return null; } else { return Pair.of("CHE_WSAGENT_CORS_ALLOW__CREDENTIALS", wsAgentCorsAllowCredentials); } }

Target:
public Pair<String, String> get(RuntimeIdentity runtimeIdentity) throws InfrastructureException { return wsAgentCorsAllowCredentials == null ? null : Pair.of("CHE_WSAGENT_CORS_ALLOW__CREDENTIALS", wsAgentCorsAllowCredentials); }
Source:
static CompletionStage<ImmutableMap<ReportFormat, RenderedReport>> renderAll( final Injector injector, final ImmutableSet<ReportFormat> formats, final ReportSource source, final Instant scheduled ) { final Map<ReportFormat, RenderedReport> result = Maps.newHashMap(); final CompletableFuture<?>[] resultSettingFutures = formats .stream() .map(format -> render(injector, source, format, scheduled) .thenApply(rendered -> result.put(format, rendered)) .toCompletableFuture()) .toArray(CompletableFuture[]::new); return CompletableFuture.allOf(resultSettingFutures).thenApply(nothing -> ImmutableMap.copyOf(result)); }

Target:
static CompletionStage<ImmutableMap<ReportFormat, RenderedReport>> renderAll( final Injector injector, final ImmutableSet<ReportFormat> formats, final ReportSource source, final Instant scheduled ) { final Map<ReportFormat, RenderedReport> result = Maps.newConcurrentMap(); final CompletableFuture<?>[] resultSettingFutures = formats .stream() .map(format -> getRenderer(injector, source, format) .render(source, format, scheduled) .thenApply(rendered -> result.put(format, rendered)) .toCompletableFuture()) .toArray(CompletableFuture[]::new); return CompletableFuture.allOf(resultSettingFutures).thenApply(nothing -> ImmutableMap.copyOf(result)); }
Source:
public Rule Reserved() { return FirstOf( Aggregate(), Find(), FindOne(), FindAndModify(), Insert(), Remove(), Update(), Count() ); }

Target:
public Rule Reserved() { return FirstOf( Find(), FindOne(), FindAndModify(), Insert(), Remove(), Update(), Count(), Aggregate() ); }
Source:
public void removeFromInstanceSet(final Object keyClass, final EObject value) { final Set<EObject> set = instanceMap.get(keyClass); if (set != null) { if(!set.remove(value)) { String msg = String.format("Notification received to remove %s as a %s, but feature was not indexed. This indicates some errors in underlying model representation.", value, keyClass); logNotificationHandlingError(msg); } if (set.isEmpty()) { instanceMap.remove(keyClass); } } isDirty = true; navigationHelper.notifyInstanceListeners(keyClass, value, false); }

Target:
public void removeFromInstanceSet(final Object keyClass, final EObject value) { final Set<EObject> set = instanceMap.get(keyClass); if (set != null) { if(!set.remove(value)) { String msg = String.format("Notification received to remove %s as a %s, but it is missing from the index. This indicates some errors in underlying model representation.", value, keyClass); logNotificationHandlingError(msg); } if (set.isEmpty()) { instanceMap.remove(keyClass); } } isDirty = true; navigationHelper.notifyInstanceListeners(keyClass, value, false); }
Source:
public void activateProcessInstanceCmdExecutorTest() { ActivateProcessInstanceCmd activateProcessInstanceCmd = new ActivateProcessInstanceCmd("x"); assertThat(activateProcessInstanceCmdExecutor).isNotNull(); assertThat(activateProcessInstanceCmdExecutor.getHandledType()).isEqualTo(ActivateProcessInstanceCmd.class); activateProcessInstanceCmdExecutor.execute(activateProcessInstanceCmd); verify(processEngine).activate(activateProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<ActivateProcessInstanceResults>>any()); }

Target:
public void activateProcessInstanceCmdExecutorTest() { ActivateProcessInstanceCmd activateProcessInstanceCmd = new ActivateProcessInstanceCmd("x"); assertThat(activateProcessInstanceCmdExecutor.getHandledType()).isEqualTo(ActivateProcessInstanceCmd.class); activateProcessInstanceCmdExecutor.execute(activateProcessInstanceCmd); verify(processEngine).activate(activateProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<ActivateProcessInstanceResults>>any()); }
Source:
private String composeSwitchLocation() { if (switchView.isSwitchToTrunk()) { return projectUri + "/trunk"; } else if (switchView.isSwitchToBranch()) { return projectUri + "/branches/" + (isNullOrEmpty(switchView.getSwitchToLocation()) ? "" : switchView.getSwitchToLocation()); } else if (switchView.isSwitchToTag()) { return projectUri + "/tags/" + (isNullOrEmpty(switchView.getSwitchToLocation()) ? "" : switchView.getSwitchToLocation()); } else { return switchView.getLocation(); } }

Target:
private String composeSwitchLocation() { if (switchView.isSwitchToTrunk()) { return projectUri + "/trunk"; } else { String switchToLocation = switchView.getSwitchToLocation(); if (switchView.isSwitchToBranch()) { return projectUri + "/branches/" + (isNullOrEmpty(switchToLocation) ? "" : switchToLocation); } else if (switchView.isSwitchToTag()) { return projectUri + "/tags/" + (isNullOrEmpty(switchToLocation) ? "" : switchToLocation); } else { return switchView.getLocation(); } } }
Source:
private ResponseErrors parseResponseErrors(HttpResponse response) { ResponseErrors responseErrors = null; if (response.getEntity() != null) { try { String responseEntity = EntityUtils.toString(response.getEntity()); LOGGER.debug(responseEntity); responseErrors = JsonParser.DEFAULT.parse(responseEntity, ResponseErrors.class); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } return responseErrors; }

Target:
private ResponseErrors parseResponseErrors(HttpResponse response) { ResponseErrors responseErrors = null; if (response.getEntity() != null) { try { String responseEntity = EntityUtils.toString(response.getEntity()); LOGGER.debug(responseEntity); responseErrors = JsonParser.DEFAULT.parse(responseEntity, ResponseErrors.class); } catch (IOException ex) { LOGGER.error("IOException", ex); } catch (ParseException ex) { LOGGER.error("ParseException", ex); } } return responseErrors; }
Source:
public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { View v = inflater.inflate(R.layout.select_playlist_fragment, container, false); recyclerView = v.findViewById(R.id.items_list); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); SelectPlaylistAdapter playlistAdapter = new SelectPlaylistAdapter(); recyclerView.setAdapter(playlistAdapter); progressBar = v.findViewById(R.id.progressBar); emptyView = v.findViewById(R.id.empty_state_view); progressBar.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); emptyView.setVisibility(View.GONE); final AppDatabase database = NewPipeDatabase.getInstance(this.getContext()); LocalPlaylistManager localPlaylistManager = new LocalPlaylistManager(database); RemotePlaylistManager remotePlaylistManager = new RemotePlaylistManager(database); Flowable.combineLatest(localPlaylistManager.getPlaylists(), remotePlaylistManager.getPlaylists(), PlaylistItemsUtils::merge) .toObservable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(getPlaylistsObserver()); return v; }

Target:
public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.select_playlist_fragment, container, false); recyclerView = v.findViewById(R.id.items_list); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); SelectPlaylistAdapter playlistAdapter = new SelectPlaylistAdapter(); recyclerView.setAdapter(playlistAdapter); progressBar = v.findViewById(R.id.progressBar); emptyView = v.findViewById(R.id.empty_state_view); progressBar.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); emptyView.setVisibility(View.GONE); final AppDatabase database = NewPipeDatabase.getInstance(requireContext()); final LocalPlaylistManager localPlaylistManager = new LocalPlaylistManager(database); final RemotePlaylistManager remotePlaylistManager = new RemotePlaylistManager(database); playlistsSubscriber = Flowable.combineLatest(localPlaylistManager.getPlaylists(), remotePlaylistManager.getPlaylists(), PlaylistLocalItem::merge) .subscribe(this::displayPlaylists, this::onError); return v; }
Source:
public void onPartitionsAssigned(final Collection<TopicPartition> assignedPartitions) { switch (taskManager.rebalanceProtocol()) { case EAGER: eagerOnPartitionsAssigned(assignedPartitions); break; case COOPERATIVE: cooperativeOnPartitionsAssigned(assignedPartitions); break; } }

Target:
public void onPartitionsAssigned(final Collection<TopicPartition> assignedPartitions) { log.debug("Current state {}: assigned partitions at the end of consumer rebalance.\n" + "\tpreviously assigned active tasks: {}\n" + "\tpreviously assigned standby tasks: {}\n", streamThread.state(), assignedPartitions, taskManager.previousActiveTaskIds(), taskManager.previousStandbyTaskIds()); if (streamThread.getAssignmentErrorCode() == AssignorError.INCOMPLETE_SOURCE_TOPIC_METADATA.code()) { log.error("Received error code - shutdown", streamThread.getAssignmentErrorCode()); streamThread.shutdown(); return; } final long start = time.milliseconds(); List<TopicPartition> revokedStandbyPartitions = null; try { if (streamThread.setState(State.PARTITIONS_ASSIGNED) == null) { log.debug( "Skipping task creation in rebalance because we are already in state.", streamThread.state() ); } else if (streamThread.getAssignmentErrorCode() != AssignorError.NONE.code()) { log.debug( "Encountered assignment error during partition assignment: {}. Skipping task initialization", streamThread.getAssignmentErrorCode() ); } else { revokedStandbyPartitions = taskManager.closeRevokedStandbyTasks(); taskManager.closeRevokedSuspendedTasks(); taskManager.createTasks(assignedPartitions); } } catch (final Throwable t) { log.error( "Error caught during partition assignment, " + "will abort the current process and re-throw at the end of rebalance", t); streamThread.setRebalanceException(t); } finally { if (revokedStandbyPartitions != null) { streamThread.clearStandbyRecords(revokedStandbyPartitions); } log.info("partition assignment took ms.\n" + "\tcurrently assigned active tasks: {}\n" + "\tcurrently assigned standby tasks: {}\n" + "\trevoked active tasks: {}\n" + "\trevoked standby tasks: {}\n", time.milliseconds() - start, taskManager.activeTaskIds(), taskManager.standbyTaskIds(), taskManager.revokedActiveTaskIds(), taskManager.revokedStandbyTaskIds()); } }
Source:
public Tuple destruct() { LinkedList<T> vals = new LinkedList<>(); for (T v : this) { vals.add(v); } return Tuple.fromArray(vals.toArray()); }

Target:
public Tuple destruct() { Object[] data = new Object[this.size()]; int i = 0; for (T v : this) { data[i] = v; i++; } return Tuple.fromArray(data); }
Source:
private Set<String> getStringSet(String key) { String prefSetting = getIndexer().getProperty(key); if (prefSetting != null && prefSetting.length() > 0) { return new HashSet<String>(Arrays.asList(prefSetting.split(","))); } return Collections.emptySet(); }

Target:
private Set<String> getStringSet(String key) { String prefSetting = getIndexer().getProperty(key); if (prefSetting != null && !prefSetting.isEmpty()) { return new HashSet<String>(Arrays.asList(prefSetting.split(","))); } return Collections.emptySet(); }
Source:
public static AmazonEC2Client createAmazonEC2Mock(@Nullable Answer defaultAnswer) { AmazonEC2Client mock; if (defaultAnswer != null) { mock = Mockito.mock(AmazonEC2Client.class, defaultAnswer); } else { mock = Mockito.mock(AmazonEC2Client.class); mockDescribeRegions(mock); mockDescribeInstances(mock); mockDescribeImages(mock); mockDescribeKeyPairs(mock); mockDescribeSecurityGroups(mock); mockDescribeSubnets(mock); mockRunInstances(mock); mockTerminateInstances(mock); } return mock; }

Target:
public static AmazonEC2Client createAmazonEC2Mock(@Nullable Answer defaultAnswer) { AmazonEC2Client mock; if (defaultAnswer != null) { mock = mock(AmazonEC2Client.class, defaultAnswer); } else { mock = mock(AmazonEC2Client.class); mockDescribeRegions(mock); mockDescribeInstances(mock); mockDescribeImages(mock); mockDescribeKeyPairs(mock); mockDescribeSecurityGroups(mock); mockDescribeSubnets(mock); mockRunInstances(mock); mockTerminateInstances(mock); } return mock; }
Source:
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions() .setContentType(FormContentType.APPLICATION_PDF) .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageBusinessData(syncPoller.getFinalResult()); }, MULTIPAGE_BUSINESS_CARD_PDF); }

Target:
public void recognizeMultipageBusinessCardUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormRecognizerClient(httpClient, serviceVersion); urlRunner(sourceUrl -> { SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller = client.beginRecognizeBusinessCardsFromUrl(sourceUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(true) .setPollInterval(durationTestMode), Context.NONE); syncPoller.waitForCompletion(); validateMultipageBusinessData(syncPoller.getFinalResult()); }, MULTIPAGE_BUSINESS_CARD_PDF); }
Source:
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()); assertEquals(genericAccount.getInstitute(), observedAccountAttributes.getInstitute()); }

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:
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); if (createdObservation.getGroupMembers() == null) { createdObservation.setGroupMembers(new ArrayList<>()); } createdObservation.getGroupMembers().addAll(createNestedObservations(configName, encounter, nestedObservations)); createdObservations.add(createdObservation); } return createdObservations; }

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:
private TimeoutConfiguration getGlobalTimeoutConfiguration(ExtensionContext extensionContext) { ExtensionContext root = extensionContext.getRoot(); return root.getStore(NAMESPACE).getOrComputeIfAbsent("global_timeout_config", key -> new TimeoutConfiguration(root), TimeoutConfiguration.class); }

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:
public void initialize() { logger.debug("Initializing DigitalSTROM Scene handler."); if (this.getDssBridgeHandler() == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_MISSING_ERROR, "Bridge is missig"); } else { bridgeHandlerInitialized(dssBridgeHandler, this.getBridge()); } }

Target:
public void initialize() { logger.debug("Initializing SceneHandler"); if (bridgeHandler != null) { bridgeHandlerInitialized(bridgeHandler, this.getBridge()); } }
Source:
public TopologyInfo getTopologyInfoByName(String name) throws NotAliveException, AuthorizationException, 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); } }

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:
public Description matchAssert(AssertTree tree, VisitorState state) { ExpressionTree condition = tree.getCondition(); if (kindIs(BOOLEAN_LITERAL).matches(condition, state)) { 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; } }

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:
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 (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); } }

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:
public abstract void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException; private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 2 * 60); public void killAll(@Nullable Process proc, @Nullable 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); }

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:
public void run() { running.set(true); while (running.get()) { j = new Jedis(host, port); if (null != sentinelPassword && !sentinelPassword.isEmpty()) { j.auth(sentinelPassword); } try { if (!running.get()) { break; } List<String> masterAddr = j.sentinelGetMasterAddrByName(masterName); if (masterAddr == null || masterAddr.size() != 2) { log.warn("Can not get master addr, master name: {}. Sentinel: {}:{}.", masterName, host, port); } else { initPool(toHostAndPort(masterAddr)); } j.subscribe(new JedisPubSub() { @Override public void onMessage(String channel, String message) { log.debug("Sentinel {}:{} published: {}.", host, port, message); String[] switchMasterMsg = message.split(" "); if (switchMasterMsg.length > 3) { if (masterName.equals(switchMasterMsg[0])) { initPool(toHostAndPort(Arrays.asList(switchMasterMsg[3], switchMasterMsg[4]))); } else { log.debug( "Ignoring message on +switch-master for master name {}, our master name is {}", switchMasterMsg[0], masterName); } } else { log.error( "Invalid message received on Sentinel {}:{} on channel +switch-master: {}", host, port, message); } } }, "+switch-master"); } catch (JedisException e) { if (running.get()) { log.error("Lost connection to Sentinel at {}:{}. Sleeping 5000ms and retrying.", host, port, e); try { Thread.sleep(subscribeRetryWaitTimeMillis); } catch (InterruptedException e1) { log.error("Sleep interrupted: ", e1); } } else { log.debug("Unsubscribing from Sentinel at {}:{}", host, port); } } finally { j.close(); } } }

Target:
public void run() { running.set(true); while (running.get()) { try { if (!running.get()) { break; } j = new Jedis(host, port, sentinelConnectionTimeout, sentinelSoTimeout); if (sentinelPassword != null) { j.auth(sentinelPassword); } if (sentinelClientName != null) { j.clientSetname(sentinelClientName); } List<String> masterAddr = j.sentinelGetMasterAddrByName(masterName); if (masterAddr == null || masterAddr.size() != 2) { log.warn("Can not get master addr, master name: {}. Sentinel: {}:{}.", masterName, host, port); } else { initPool(toHostAndPort(masterAddr)); } j.subscribe(new JedisPubSub() { @Override public void onMessage(String channel, String message) { log.debug("Sentinel {}:{} published: {}.", host, port, message); String[] switchMasterMsg = message.split(" "); if (switchMasterMsg.length > 3) { if (masterName.equals(switchMasterMsg[0])) { initPool(toHostAndPort(Arrays.asList(switchMasterMsg[3], switchMasterMsg[4]))); } else { log.debug( "Ignoring message on +switch-master for master name {}, our master name is {}", switchMasterMsg[0], masterName); } } else { log.error( "Invalid message received on Sentinel {}:{} on channel +switch-master: {}", host, port, message); } } }, "+switch-master"); } catch (JedisException e) { if (running.get()) { log.error("Lost connection to Sentinel at {}:{}. Sleeping 5000ms and retrying.", host, port, e); try { Thread.sleep(subscribeRetryWaitTimeMillis); } catch (InterruptedException e1) { log.error("Sleep interrupted: ", e1); } } else { log.debug("Unsubscribing from Sentinel at {}:{}", host, port); } } finally { if (j != null) { j.close(); } } } }
Source:
public Optional<byte[]> read() { try { return Optional.of(readBuffer()); } catch (CANMessageUnavailableException e) { return Optional.empty(); } }

Target:
public Optional<byte[]> read() { try { return Optional.of(readSafely()); } catch (CANMessageUnavailableException e) { return Optional.empty(); } }
Source:
default Attributes asReadOnly() { return new Attributes() { @Override public Collection<Entry> entries() { Collection<Entry> entries = Attributes.this.entries(); Iterator<Entry> iterator = entries.iterator(); 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); } }; }

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:
public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(filter), Const.UTF8_CHARSET) .putString(Strings.nullToEmpty(pattern.pattern()), Const.UTF8_CHARSET) .hash(); return hc; }

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:
Date getDateUploaded() { String date = CommonsDateUtil.getIso8601DateFormatShort().format(dateUploaded); Date uploadDate = dateUploaded; try { uploadDate = CommonsDateUtil.getIso8601DateFormatShort().parse(date); } catch (ParseException e) { e.printStackTrace(); } return uploadDate; }

Target:
Date getDateUploaded() { return dateUploaded; }
Source:
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); } String availableTypes= systemPropertiesProvider.getProperty(SystemPropertiesProvider.AVAILABLE_ATTRIBUTE_TYPES); if (att.getType().length()<2 || !availableTypes.contains(att.getType())){ throw new InvalidProductException(msg); } } }

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:
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); button.setVisibility(View.VISIBLE); button.setOnClickListener(v -> { courseDateViewModel.resetCourseDatesBanner(unit.getCourseId()); }); } infoBanner.setVisibility(View.VISIBLE); } }

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:
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 " + "password", null).withConfigProperty("username"); } 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"); } } }

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:
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()) { FilePath path = build.getWorkspace().child(filename); if (path.exists()) { content = path.readToString(); } EnvVars envVars = (listener == null) ? build.getEnvironment() : build.getEnvironment(listener); content = envVars.expand(content); } return content; }

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:
public LiveData<List<Allergy>> getAllergies(RestApi restApi, String uuid) { MutableLiveData<List<Allergy>> allergyLiveData = new MutableLiveData<>(); allergyEntitiesOffline = allergyRoomDAO.getAllAllergiesByPatientID(patientID); allergyLiveData.setValue(AppDatabaseHelper.INSTANCE.allergyEntityListToAllergyList(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.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; }

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; }