auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { private final Deque<T> deque = new LinkedList<T>(); @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onNext(T value) { if (count == 0) { subscriber.onNext(value); return; } deque.offerLast(value); if (deque.size() > count) { subscriber.onNext(deque.removeFirst()); } } }; }

Target:
public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { private final NotificationLite<T> on = NotificationLite.instance(); private final Deque<Object> deque = new ArrayDeque<Object>(); @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onNext(T value) { if (count == 0) { subscriber.onNext(value); return; } if (deque.size() == count) { subscriber.onNext(on.getValue(deque.removeFirst())); } deque.offerLast(on.next(value)); } }; }
Source:
public CommandCallback getCallback() { return ImagesHandler.filterDisksBasedOnCinder(images).isEmpty() ? null : new GenericCinderCommandCallback<AddVmTemplateCommand<T>>(); }

Target:
public CommandCallback getCallback() { return getCinderDisks().isEmpty() ? null : new ConcurrentChildCommandsExecutionCallback(); }
Source:
public void testIPv6() { HostPort hostPort = new HostPort("1:2::3:4:5555"); assertThat(hostPort.getHost(), is("1:2::3:4")); assertThat(hostPort.getPort(), is(5555)); }

Target:
public void testIPv6() { HostPort hostPort = new HostPort("[1:2::3:4]:5555"); assertThat(hostPort.getHost(), is("1:2::3:4")); assertThat(hostPort.getPort(), is(5555)); }
Source:
static void processBatch( EncodingTransactionService delegate, List<BatchElement<TimestampPair, Void>> batchElements) { Map<Long, Long> accumulatedRequest = Maps.newConcurrentMap(); Map<Long, SettableFuture<Void>> futures = Maps.newConcurrentMap(); failDuplicateRequestsOnStartTimestamp(batchElements, accumulatedRequest, futures); while (!accumulatedRequest.isEmpty()) { try { delegate.putUnlessExistsMultiple(accumulatedRequest); batchElements.forEach(element -> element.result().set(null)); return; } catch (KeyAlreadyExistsException exception) { Set<Long> failedTimestamps = getAlreadyExistingStartTimestamps(delegate, exception); failedTimestamps.forEach(timestamp -> futures.get(timestamp).setException(exception)); accumulatedRequest = Maps.filterKeys( accumulatedRequest, timestamp -> !failedTimestamps.contains(timestamp)); } } }

Target:
static void processBatch( EncodingTransactionService delegate, List<BatchElement<TimestampPair, Void>> batchElements) { Map<Long, Long> accumulatedRequest = Maps.newConcurrentMap(); Map<Long, SettableFuture<Void>> futures = Maps.newConcurrentMap(); failDuplicateRequestsOnStartTimestamp(batchElements, accumulatedRequest, futures); while (!accumulatedRequest.isEmpty()) { try { delegate.putUnlessExistsMultiple(accumulatedRequest); batchElements.forEach(element -> markSuccessful(element.result())); return; } catch (KeyAlreadyExistsException exception) { Set<Long> failedTimestamps = getAlreadyExistingStartTimestamps(delegate, accumulatedRequest, exception); failedTimestamps.forEach(timestamp -> futures.get(timestamp).setException(exception)); Set<Long> successfulTimestamps = getTimestampsSuccessfullyPutUnlessExists(delegate, exception); successfulTimestamps.forEach(timestamp -> markSuccessful(futures.get(timestamp))); accumulatedRequest = Maps.filterKeys(accumulatedRequest, timestamp -> !failedTimestamps.contains(timestamp) && !successfulTimestamps.contains(timestamp)); } } }
Source:
public ElasticsearchContainer waitingForShards() { waitingFor((new HttpWaitStrategy()) .forPath("/_cat/shards") .forPort(ELASTICSEARCH_DEFAULT_PORT) .forResponsePredicate(response -> response.contains("STARTED") && !response.contains("INITIALIZING")) .withStartupTimeout(Duration.ofMinutes(2))); return self(); }

Target:
public ElasticsearchContainer waitingForShards() { waitingFor(new HttpWaitStrategy() .forPath("/_cat/shards") .forPort(ELASTICSEARCH_DEFAULT_PORT) .forResponsePredicate(response -> response.contains("STARTED") && !response.contains("INITIALIZING")) .withStartupTimeout(Duration.ofMinutes(2))); return self(); }
Source:
public static void removeMembers(AccountGroup.UUID groupUUID, Set<Account.Id> ids, AsyncCallback<VoidResult> cb) { RestApi call = new RestApi(membersBase(groupUUID)); MemberInput input = MemberInput.create(); for (Account.Id id : ids) { input.add_member(Integer.toString(id.get())); } call.data(input).delete(cb); }

Target:
public static void removeMembers(AccountGroup.UUID groupUUID, Set<Account.Id> ids, AsyncCallback<VoidResult> cb) { RestApi call = new RestApi(membersBase(groupUUID)); MemberInput input = MemberInput.create(); for (Account.Id id : ids) { input.add_member(id.toString()); } call.data(input).delete(cb); }
Source:
private void queryVideos(String query) { List<UUID> ids; try { ids = VideoInfoRepository.FindResult.toIds(App.videoInfoRepository.getAllSorted()); } catch (IOException e) { e.printStackTrace(); return; } for (UUID id : ids) { try { if (isMatch(id, query)) { this.matches.add(id); } } catch (IOException e) { e.printStackTrace(); } } this.browserFragment.setVideos(this.matches); }

Target:
private void queryVideos(String query) { FindResults results; try { results = App.videoInfoRepository.getAll(); } catch (IOException e) { e.printStackTrace(); return; } FindResults matching = new FindResults(new ArrayList<FindResult>(results.size())); for (FindResult result : results) { try { if (isMatch(result.getId(), query)) { matching.add(result); } } catch (IOException e) { e.printStackTrace(); } } this.matches.addAll(matching.sortDescending().getIDs()); this.browserFragment.setVideos(this.matches); }
Source:
public void setup() { Function<Map<String, Result>, Set<String>> titles = m -> m.entrySet() .stream() .map(Map.Entry::getValue) .map(Result::getMetacard) .map(Metacard::getTitle) .collect(Collectors.toSet()); Set<String> queryTitles = queryAsAdmin(FormAttributes.Query.TAG, titles); Set<String> resultTitles = queryAsAdmin(FormAttributes.Result.TAG, titles); List<Metacard> initialTemplates = config().get(); initialTemplates .stream() .filter(QueryTemplateMetacardImpl::isQueryTemplateMetacard) .filter(m -> !queryTitles.contains(m.getTitle())) .forEach(this::saveMetacard); initialTemplates .stream() .filter(ResultTemplateMetacardImpl::isResultTemplateMetacard) .filter(m -> !resultTitles.contains(m.getTitle())) .forEach(this::saveMetacard); }

Target:
public void setup() { List<Metacard> systemTemplates = SearchFormsLoader.config().get(); if (systemTemplates.isEmpty()) { return; } SearchFormsLoader.bootstrap(catalogFramework, util, systemTemplates); }
Source:
private List<LanguageRange> getMetadataLanguage() { User user = ServiceManager.getUserService().getAuthenticatedUser(); String metadataLanguage = user != null ? user.getMetadataLanguage() : Helper.getRequestParameter("Accept-Language"); return LanguageRange .parse(Objects.nonNull(metadataLanguage) && !metadataLanguage.isEmpty() ? metadataLanguage : "en"); }

Target:
private List<LanguageRange> getMetadataLanguage() { User user = ServiceManager.getUserService().getAuthenticatedUser(); String metadataLanguage = user != null ? user.getMetadataLanguage() : Helper.getRequestParameter("Accept-Language"); return LanguageRange .parse(StringUtils.isBlank(metadataLanguage) ? metadataLanguage : "en"); }
Source:
public String replaceSingle(String line, RegexFindReplace findReplace, String startTag, String endTag) { int currPos = 0; StringBuilder replacedLine = new StringBuilder(); Matcher patternMatcher = Pattern.compile(findReplace.find()).matcher(line); while (patternMatcher.find()) { String replacedString = patternMatcher.group().replaceFirst(findReplace.find(), findReplace.replace()); currPos = appendReplacedTextFragmentInHTML(startTag, endTag, replacedLine, line, currPos, replacedString, patternMatcher); } replacedLine.append(line.substring(currPos)); line = replacedLine.toString(); return line; }

Target:
public String replaceSingle(String line, RegexFindReplace findReplace, String startTag, String endTag) { int currPos = 0; StringBuilder replacedLine = new StringBuilder(); Matcher patternMatcher = regexPatterns.get(findReplace.find()).matcher(line); while (patternMatcher.find()) { String replacedString = patternMatcher.group().replaceFirst(findReplace.find(), findReplace.replace()); currPos = appendReplacedTextFragmentInHTML(startTag, endTag, replacedLine, line, currPos, replacedString, patternMatcher); } replacedLine.append(line.substring(currPos)); line = replacedLine.toString(); return line; }
Source:
void addNutrient() { String[] nutrients = getResources().getStringArray(R.array.nutrients_array); Arrays.sort(nutrients, Collator.getInstance(Locale.US)); new MaterialDialog.Builder(activity) .title(R.string.choose_nutrient) .items(nutrients) .itemsCallback((dialog, itemView, position, text) -> { if (!index.contains(position)) { index.add(position); final CustomValidatingEditTextView textView = addNutrientRow(position, text, false, null, 0); allEditViews.add(textView); addValidListener(textView); } else { Toast.makeText(activity, getString(R.string.nutrient_already_added, nutrients[position]), Toast.LENGTH_SHORT).show(); } }) .show(); }

Target:
void addNutrient() { String[] nutrients = getResources().getStringArray(R.array.nutrients_array); Stringi18nUtils.sortAlphabetically(nutrients, Collator.getInstance(Locale.getDefault())); new MaterialDialog.Builder(activity) .title(R.string.choose_nutrient) .items(nutrients) .itemsCallback((dialog, itemView, position, text) -> { if (!index.contains(position)) { index.add(position); final CustomValidatingEditTextView textView = addNutrientRow(position, text, false, null, 0); allEditViews.add(textView); addValidListener(textView); } else { Toast.makeText(activity, getString(R.string.nutrient_already_added, nutrients[position]), Toast.LENGTH_SHORT).show(); } }) .show(); }
Source:
public Result apply(LateralJoinNode parent, Captures captures, Context context) { List<ValuesNode> values = searchFrom(parent.getSubquery(), context.getLookup()) .recurseOnlyWhen(ProjectNode.class::isInstance) .where(ValuesNode.class::isInstance) .findAll(); if (values.size() != 1 || !isSingleRowValuesWithNoColumns(values.get(0))) { return Result.empty(); } List<ProjectNode> subqueryProjections = searchFrom(parent.getSubquery(), context.getLookup()) .where(ProjectNode.class::isInstance) .findAll(); List<ProjectNode> mutableSubQueryProjections = new ArrayList<>(subqueryProjections); if (mutableSubQueryProjections.size() > 1) { for (int i = 0; i < mutableSubQueryProjections.size(); i++) { ProjectNode currentProjectNode = mutableSubQueryProjections.get(i); if (parent.getInput().getOutputSymbols().containsAll(currentProjectNode.getOutputSymbols())) { mutableSubQueryProjections.remove(i); } } } if (mutableSubQueryProjections.size() == 0) { return Result.ofPlanNode(parent.getInput()); } else if (mutableSubQueryProjections.size() == 1) { Assignments assignments = Assignments.builder() .putIdentities(parent.getInput().getOutputSymbols()) .putAll(mutableSubQueryProjections.get(0).getAssignments()) .build(); return Result.ofPlanNode(projectNode(parent.getInput(), assignments, context)); } return Result.empty(); }

Target:
public Result apply(LateralJoinNode parent, Captures captures, Context context) { List<ValuesNode> values = searchFrom(parent.getSubquery(), context.getLookup()) .recurseOnlyWhen(ProjectNode.class::isInstance) .where(ValuesNode.class::isInstance) .findAll(); if (values.size() != 1 || !isSingleRowValuesWithNoColumns(values.get(0))) { return Result.empty(); } List<ProjectNode> subqueryProjections = searchFrom(parent.getSubquery(), context.getLookup()) .where(node -> node instanceof ProjectNode && !node.getOutputSymbols().equals(parent.getCorrelation())) .findAll(); if (subqueryProjections.size() == 0) { return Result.ofPlanNode(parent.getInput()); } else if (subqueryProjections.size() == 1) { Assignments assignments = Assignments.builder() .putIdentities(parent.getInput().getOutputSymbols()) .putAll(subqueryProjections.get(0).getAssignments()) .build(); return Result.ofPlanNode(projectNode(parent.getInput(), assignments, context)); } return Result.empty(); }
Source:
public static ViewHighlighter newInstance() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return new OverlayHighlighter(); } else { return new NullHighlighter(); } }

Target:
public static ViewHighlighter newInstance() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { return new OverlayHighlighter(); } else { LogUtil.w(TAG, "Running on pre-JBMR2: View highlighting is not supported"); return new NoopHighlighter(); } }
Source:
protected Function<Object, IterableWithMarker<Router>> markerToNextForArg0(Optional<Object> arg0) { String zone = arg0.isPresent() ? arg0.get().toString() : null; final RouterApi routerApi = api.getRouterExtensionForZone(zone).get(); return new Function<Object, IterableWithMarker<Router>>() { @SuppressWarnings("unchecked") @Override public IterableWithMarker<Router> apply(Object input) { return IterableWithMarker.class.cast(routerApi.listInDetail(marker(input.toString()))); } @Override public String toString() { return "list()"; } }; }

Target:
protected Function<Object, IterableWithMarker<Router>> markerToNextForArg0(Optional<Object> arg0) { String zone = arg0.isPresent() ? arg0.get().toString() : null; final RouterApi routerApi = api.getRouterExtensionForZone(zone).get(); return new Function<Object, IterableWithMarker<Router>>() { @SuppressWarnings("unchecked") @Override public IterableWithMarker<Router> apply(Object input) { return IterableWithMarker.class.cast(routerApi.listInDetail(marker(input.toString()))); } @Override public String toString() { return "listRoutersInDetail()"; } }; }
Source:
protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); super.onCreate(savedInstanceState); Bundle parameters = savedInstanceState; if (parameters == null) { parameters = getIntent().getExtras(); } mEditedModelFileName = parameters.getString(CardTemplateEditor.INTENT_MODEL_FILENAME); mCardList = parameters.getLongArray("cardList"); mIndex = parameters.getInt("index"); if (mEditedModelFileName != null) { Timber.d("onCreate() loading edited model from %s", mEditedModelFileName); mEditedModel = CardTemplateEditor.getTempModel(mEditedModelFileName); } if (mEditedModel != null && mIndex != -1) { Timber.d("onCreate() Previewer started with edited model and template index, displaying blank to preview formatting"); mCurrentCard = getDummyCard(mEditedModel, mIndex); if (mCurrentCard == null) { UIUtils.showSimpleSnackbar(this, R.string.invalid_template, false); finishWithoutAnimation(); return; } } if (mCurrentCard == null && (mCardList == null || mCardList.length == 0 || mIndex < 0 || mIndex > mCardList.length - 1)) { Timber.e("Previewer started with empty card list or invalid index"); finishWithoutAnimation(); return; } showBackIcon(); disableDrawerSwipe(); startLoadingCollection(); }

Target:
protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); super.onCreate(savedInstanceState); mCardList = getIntent().getLongArrayExtra("cardList"); mIndex = getIntent().getIntExtra("index", -1); if (savedInstanceState != null){ mIndex = savedInstanceState.getInt("index", mIndex); mShowingAnswer = savedInstanceState.getBoolean("showingAnswer", mShowingAnswer); } if (mCardList.length == 0 || mIndex < 0 || mIndex > mCardList.length - 1) { Timber.e("Previewer started with empty card list or invalid index"); finishWithoutAnimation(); return; } showBackIcon(); disableDrawerSwipe(); startLoadingCollection(); }
Source:
public void getClaimAsInstantWhenISODateStringThenReturnInstant() { Instant expectedClaimValue = Instant.now(); String claimName = "isoDate"; this.claims.put(claimName, expectedClaimValue.toString()); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); }

Target:
public void getClaimAsInstantWhenISODateStringThenReturnInstant() { Instant expectedClaimValue = Instant.parse("2011-12-03T09:15:30Z"); String claimName = "isoDate"; this.claims.put(claimName, "2011-12-03T09:15:30Z"); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); this.claims.put(claimName, "2011-12-03T10:15:30+01:00"); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); this.claims.put(claimName, "2011-12-03T10:15:30+01:00[Europe/Paris]"); assertThat(this.claimAccessor.getClaimAsInstant(claimName)).isBetween( expectedClaimValue.minusSeconds(1), expectedClaimValue.plusSeconds(1)); }
Source:
public void authenticateWithWrongAuthentication() throws SecurityException, SecurityProviderNotFoundException { when(provider.authenticate(authentication)).thenThrow(UnauthorisedException.class); manager.addProvider(provider); expected.expect(UnauthorisedException.class); manager.authenticate(authentication); verify(provider).authenticate(authentication); }

Target:
public void authenticateWithWrongAuthentication() throws SecurityException, SecurityProviderNotFoundException { when(provider.authenticate(authentication)).thenThrow(UnauthorisedException.class); manager.addProvider(provider); expected.expect(UnauthorisedException.class); try { manager.authenticate(authentication); } finally { verify(provider).authenticate(authentication); } }
Source:
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag) { DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompoundTag("DimensionData") : null); if (tag.hasKey("DefaultFluidList", 9)) { PersistentRegistryManager.GameDataSnapshot snapshot = PersistentRegistryManager.takeSnapshot(); PersistentRegistryManager.GameDataSnapshot.Entry entry = new PersistentRegistryManager.GameDataSnapshot.Entry(); snapshot.entries.put(PersistentRegistryManager.FLUIDS, entry); NBTTagList fluidList = tag.getTagList("DefaultFluidList", 8); for (int id = 0; id < fluidList.tagCount(); id++) entry.ids.put(new ResourceLocation(fluidList.getStringTagAt(id).toLowerCase()), id); PersistentRegistryManager.injectSnapshot(snapshot, true, true); } }

Target:
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag) { DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompoundTag("DimensionData") : null); if (tag.hasKey("DefaultFluidList", 9)) { Map<ResourceLocation, ForgeRegistry.Snapshot> snapshots = RegistryManager.ACTIVE.takeSnapshot(true); ForgeRegistry.Snapshot snapshot = new ForgeRegistry.Snapshot(); snapshots.put(GameData.FLUIDS, snapshot); NBTTagList fluidList = tag.getTagList("DefaultFluidList", 8); for (int id = 0; id < fluidList.tagCount(); id++) snapshot.ids.put(new ResourceLocation(fluidList.getStringTagAt(id).toLowerCase(Locale.ENGLISH)), id); GameData.injectSnapshot(snapshots, true, true); } }
Source:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> { handle.execute("DROP TABLE IF EXISTS foo"); handle.execute("CREATE TABLE foo(url URL);"); }); }

Target:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> handle.execute("CREATE TABLE foo(url URL);")); }
Source:
public AbstractMessageInterpolator(ResourceBundleLocator userResourceBundleLocator, ResourceBundleLocator contributorResourceBundleLocator, boolean cacheMessages) { this( userResourceBundleLocator, contributorResourceBundleLocator, Collections.emptySet(), Locale.getDefault(), cacheMessages ); }

Target:
public AbstractMessageInterpolator(ResourceBundleLocator userResourceBundleLocator, ResourceBundleLocator contributorResourceBundleLocator, boolean cacheMessages) { this( userResourceBundleLocator, contributorResourceBundleLocator, Collections.emptySet(), Locale.getDefault(), new DefaultLocaleResolver(), cacheMessages ); }
Source:
public void testReportDoneOncePerSchedule() throws InterruptedException { BusyLoopJob job = new BusyLoopJob(); EventCount eventCount = new EventCount(); job.addJobChangeListener(eventCount); try { for (int i = 0; i < 10000; i++) { job.schedule(); job.cancel(); } assertTrue(job.join(5000, null)); Thread.sleep(100); assertEquals("Job should be completed once per schedule.", eventCount.scheduledCount.get(), eventCount.doneCount.get()); } finally { job.cancelWithoutRelyingOnFramework = true; waitForCompletion(job); } }

Target:
public void testReportDoneOncePerSchedule() throws InterruptedException { BusyLoopJob job = new BusyLoopJob(); EventCount eventCount = new EventCount(); job.addJobChangeListener(eventCount); try { for (int i = 0; i < 10000; i++) { job.schedule(); job.cancel(); } assertTrue(job.join(5000, null)); Thread.sleep(200); assertEquals("Job should be completed once per schedule.", eventCount.scheduledCount.get(), eventCount.doneCount.get()); } finally { job.cancelWithoutRelyingOnFramework = true; waitForCompletion(job); } }
Source:
public HealthCheckResult(Collection<ProbeInfo> probesToCheck) { this.probes = probesToCheck; for (ProbeInfo probeInfo : probesToCheck) { healthy = healthy && probeInfo.getStatus().isSuccess(); } }

Target:
public HealthCheckResult(Collection<ProbeInfo> probesToCheck) { this.probes = probesToCheck; healthy = probes.stream().allMatch(p -> p.getStatus().isSuccess()); }
Source:
public void test_unzipInMemory_zip() { ArrayByteSource source1 = ArrayByteSource.ofUtf8("Hello World").withFileName("TestFile1.txt"); ArrayByteSource source2 = ArrayByteSource.ofUtf8("Hello Planet").withFileName("TestFile2.txt"); ArrayByteSource zipFile = ZipUtils.zipInMemory(ImmutableList.of(source1, source2)).withFileName("Test.foo"); ZipUtils.unzipInMemory(zipFile, (name, extracted) -> { if (name.equals("TestFile1.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile1.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello World"); } else if (name.equals("TestFile2.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile2.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello Planet"); } else { fail("Unexpected file: " + name); } }); }

Target:
public void test_unzipInMemory_zip() { ArrayByteSource source1 = ArrayByteSource.ofUtf8("Hello World").withFileName("TestFile1.txt"); ArrayByteSource source2 = ArrayByteSource.ofUtf8("Hello Planet").withFileName("TestFile2.txt"); ArrayByteSource zipFile = ZipUtils.zipInMemory(ImmutableList.of(source1, source2)).withFileName("Test.foo"); AtomicInteger counter = new AtomicInteger(); ZipUtils.unzipInMemory(zipFile, (name, extracted) -> { counter.incrementAndGet(); if (name.equals("TestFile1.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile1.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello World"); } else if (name.equals("TestFile2.txt")) { assertThat(extracted.getFileName()).hasValue("TestFile2.txt"); assertThat(extracted.readUtf8()).isEqualTo("Hello Planet"); } else { fail("Unexpected file: " + name); } }); assertThat(counter).hasValue(2); }
Source:
public T injectItems( final T input, final Actionable mode, final IActionSource src ) { if( mode == Actionable.SIMULATE ) { return null; } if( input != null ) { this.target.addPower( input.getStackSize() / this.channel.transferFactor() ); } return null; }

Target:
public T injectItems( final T input, final Actionable mode, final IActionSource src ) { if( mode == Actionable.SIMULATE ) { return null; } if( input != null ) { this.target.addPower( input.getStackSize() / (double) this.channel.transferFactor() ); } return null; }
Source:
public GenericShuffleProducer construct(ConstructArgs args) throws MyriaApiException { return new GenericShuffleProducer( null, getRealOperatorIds().toArray(new ExchangePairID[] {}), MyriaUtils.integerSetToIntArray( args.getServer().getRandomWorkers(distributeFunction.getAllDestinations().size())), distributeFunction); }

Target:
public GenericShuffleProducer construct(ConstructArgs args) throws MyriaApiException { return new GenericShuffleProducer( null, getRealOperatorIds().toArray(new ExchangePairID[] {}), Ints.toArray( args.getServer().getRandomWorkers(distributeFunction.getAllDestinations().size())), distributeFunction); }
Source:
private void applyFilter() { SWTBotToolbarButton filterButton = fViewBot.toolbarButton(FILTER_ACTION); filterButton.click(); SWTBotShell shell = fBot.shell(FILTER_DIALOG_TITLE).activate(); SWTBot bot = shell.bot(); SWTBotTree treeBot = bot.tree(); bot.button(UNCHECK_ALL).click(); Integer checked = SWTBotUtils.getTreeCheckedItemCount(treeBot); assertEquals("default", 0, checked.intValue()); checkFilterTreeItems(bot, treeBot, SYSTEMD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, KTHREAD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, LTTNG_CONSUMER_PROCESS_NAME); bot.button(OK_BUTTON).click(); }

Target:
private void applyFilter() { SWTBotToolbarButton filterButton = fViewBot.toolbarButton(FILTER_ACTION); filterButton.click(); SWTBotShell shell = fBot.shell(FILTER_DIALOG_TITLE).activate(); SWTBot bot = shell.bot(); SWTBotTree treeBot = bot.tree(); bot.button(UNCHECK_ALL).click(); int checked = SWTBotUtils.getTreeCheckedItemCount(treeBot); assertEquals("default", 0, checked); checkFilterTreeItems(bot, treeBot, SYSTEMD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, KTHREAD_PROCESS_NAME); checkFilterTreeItems(bot, treeBot, LTTNG_CONSUMER_PROCESS_NAME); bot.button(OK_BUTTON).click(); }
Source:
public static void setupAccountAsNeeded(Context context) { try { AccountManager manager = AccountManager.get(context); Account[] accounts = manager.getAccountsByType(Constants.ACCOUNT_TYPE); if (accounts.length == 0) { Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE); if (manager.addAccountExplicitly(account, null, null)) { ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true); KeyserverSyncAdapterService.enableKeyserverSync(context); } else { Log.e(Constants.TAG, "Adding account failed!"); } } else { if (!Preferences.getPreferences(context).isKeyserverSyncInitialized()) { KeyserverSyncAdapterService.enableKeyserverSync(context); } } } catch (SecurityException e) { Log.e(Constants.TAG, "SecurityException when adding the account", e); Toast.makeText(context, R.string.reinstall_openkeychain, Toast.LENGTH_LONG).show(); } }

Target:
public static void setupAccountAsNeeded(Context context) { try { AccountManager manager = AccountManager.get(context); Account[] accounts = manager.getAccountsByType(Constants.ACCOUNT_TYPE); if (accounts.length == 0) { Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE); if (manager.addAccountExplicitly(account, null, null)) { ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true); KeyserverSyncAdapterService.enableKeyserverSync(context); } else { Log.e(Constants.TAG, "Adding account failed!"); } } } catch (SecurityException e) { Log.e(Constants.TAG, "SecurityException when adding the account", e); Toast.makeText(context, R.string.reinstall_openkeychain, Toast.LENGTH_LONG).show(); } }
Source:
private Map<Guid, ManageNetworkClustersParameters> mapParametersByClusterId() { final ManageNetworkClustersParameters parameters = getParameters(); final Map<Guid, List<NetworkCluster>> attachmentByClusterId = groupByClusterId(parameters.getAttachments()); final Map<Guid, List<NetworkCluster>> detachmentByClusterId = groupByClusterId(parameters.getDetachments()); final Map<Guid, List<NetworkCluster>> updatesByClusterId = groupByClusterId(parameters.getUpdates()); final Set<Guid> clusterIds = Stream.of(attachmentByClusterId, detachmentByClusterId, updatesByClusterId) .flatMap(e -> e.keySet().stream()) .collect(Collectors.toSet()); return clusterIds .stream() .collect(Collectors.toMap(Function.identity(), clusterId -> new ManageNetworkClustersParameters( nullToEmptyList(attachmentByClusterId.get(clusterId)), nullToEmptyList(detachmentByClusterId.get(clusterId)), nullToEmptyList(updatesByClusterId.get(clusterId))))); }

Target:
private Map<Guid, ManageNetworkClustersParameters> mapParametersByClusterId() { ManageNetworkClustersParameters parameters = getParameters(); Map<Guid, List<NetworkCluster>> attachmentByClusterId = groupByClusterId(parameters.getAttachments()); Map<Guid, List<NetworkCluster>> detachmentByClusterId = groupByClusterId(parameters.getDetachments()); Set<Guid> clusterIds = Stream.of(attachmentByClusterId, detachmentByClusterId) .flatMap(e -> e.keySet().stream()) .collect(Collectors.toSet()); return clusterIds .stream() .collect(Collectors.toMap(Function.identity(), clusterId -> new ManageNetworkClustersParameters( nullToEmptyList(attachmentByClusterId.get(clusterId)), nullToEmptyList(detachmentByClusterId.get(clusterId))))); }
Source:
public Iterator<SpectraUser> getObjIterator() { SpectraUserList userlist = getuserList(); if (userlist != null) { List<SpectraUser> users = userlist.getSpectraUsers(); if (users != null) { return users.iterator(); } } return Collections.emptyListIterator(); }

Target:
public Iterator<SpectraUser> getObjIterator() { final SpectraUserList userlist = getuserList(); if (userlist != null) { final List<SpectraUser> users = userlist.getSpectraUsers(); if (Guard.isNotNullAndNotEmpty(users)) { return users.iterator(); } } return Collections.emptyListIterator(); }
Source:
public void testDontDeserializeOtherThanMuleSession() throws MuleException { DefaultMuleMessage message = new DefaultMuleMessage("Test Message", muleContext); SessionHandler handler = new SerializeAndEncodeSessionHandler(); String encodedSet = new String(Base64.encode(SerializationUtils.serialize(new HashSet<String>()))); message.setInboundProperty(MULE_SESSION_PROPERTY, encodedSet); MuleSession session = handler.retrieveSessionInfoFromMessage(message); assertNull(session); }

Target:
public void testDontDeserializeOtherThanMuleSession() throws MuleException { DefaultMuleMessage message = new DefaultMuleMessage("Test Message", muleContext); SessionHandler handler = new SerializeAndEncodeSessionHandler(); String encodedSet = new String(encode(serialize(new HashSet<String>()))); message.setInboundProperty(MULE_SESSION_PROPERTY, encodedSet); MuleSession session = handler.retrieveSessionInfoFromMessage(message); assertNull(session); }
Source:
private void initialize(ScoreBoard sb) { updateMap.put("ScoreBoard." + ScoreBoard.EVENT_IN_PERIOD, sb.isInPeriod()); updateMap.put("ScoreBoard." + ScoreBoard.EVENT_IN_OVERTIME, sb.isInOvertime()); updateMap.put("ScoreBoard." + ScoreBoard.EVENT_OFFICIAL_SCORE, sb.isOfficialScore()); updateMap.put("ScoreBoard." + ScoreBoard.EVENT_RULESET, sb.getRuleset()); updateMap.put("ScoreBoard." + ScoreBoard.EVENT_TIMEOUT_OWNER, sb.getTimeoutOwner()); updateMap.put("ScoreBoard." + ScoreBoard.EVENT_OFFICIAL_REVIEW, sb.isOfficialReview()); processSettings("ScoreBoard", sb.getSettings()); processPenalties(sb.getSettings()); for (Team t : sb.getTeams()) { processTeam("ScoreBoard", t, false); } for (Clock c : sb.getClocks()) { processClock("ScoreBoard", c, false); } for (Policy p : sb.getPolicies()) { processPolicy("ScoreBoard", p, false); } updateState(); }

Target:
private void initialize(ScoreBoard sb) { updates.add(new WSUpdate("ScoreBoard." + ScoreBoard.EVENT_IN_PERIOD, sb.isInPeriod())); updates.add(new WSUpdate("ScoreBoard." + ScoreBoard.EVENT_IN_OVERTIME, sb.isInOvertime())); updates.add(new WSUpdate("ScoreBoard." + ScoreBoard.EVENT_OFFICIAL_SCORE, sb.isOfficialScore())); updates.add(new WSUpdate("ScoreBoard." + ScoreBoard.EVENT_RULESET, sb.getRuleset())); updates.add(new WSUpdate("ScoreBoard." + ScoreBoard.EVENT_TIMEOUT_OWNER, sb.getTimeoutOwner())); updates.add(new WSUpdate("ScoreBoard." + ScoreBoard.EVENT_OFFICIAL_REVIEW, sb.isOfficialReview())); processSettings("ScoreBoard", sb.getSettings()); processPenaltyCodes(sb.getSettings()); for (Team t : sb.getTeams()) { processTeam("ScoreBoard", t, false); } for (Clock c : sb.getClocks()) { processClock("ScoreBoard", c, false); } for (Policy p : sb.getPolicies()) { processPolicy("ScoreBoard", p, false); } updateState(); }
Source:
public void markAsRead() throws InterruptedException { getDriver().navigate().to("http://localhost:" + config.getHttpPort() + "/notifications/" + NET_ID); LoginView loginView = new LoginView(getDriver()); loginView.setPasswordField(PASSWORD); loginView.setUsernameField(NET_ID); String url = getDriver().getCurrentUrl(); loginView.clickLoginButton(); loginView.waitUntilCurrentUrlDiffersFrom(url); NotificationView notificationView = new NotificationView(getDriver()); notificationView.invariant(); WebElement button = getDriver().findElement(MARK_READ_BUTTON); assertNotNull(button); assertEquals(1,getDriver().findElements(NOTIFICATIONS_READ).size()); assertEquals(1,getDriver().findElements(NOTIFICATIONS_UNREAD).size()); assertNotNull(getDriver().findElement(NOTIFICATION_INDICATOR)); button.click(); notificationView = new NotificationView(getDriver()); notificationView.invariant(); assertEquals(2,getDriver().findElements(NOTIFICATIONS_READ).size()); assertEquals(0,getDriver().findElements(NOTIFICATIONS_UNREAD).size()); }

Target:
public void markAsRead() { CoursesView coursesView = openLoginScreen().login(NET_ID,PASSWORD); NotificationView notificationView = coursesView.toNotificationView(); assertThatNumberOfReadAndUnreadNotificationsMatch(notificationView); notificationView.getUnreadNotifications().iterator().next() .clickAndMarkAsRead() .toNotificationView(); assertThatNumberOfReadAndUnreadNotificationsMatch(notificationView); }
Source:
private void edit(String key, Object value) throws IOException { root.retrieve().method("POST").with(key, value).method("PATCH").withUrlPath(getApiRoute()).to(); }

Target:
private void edit(String key, Object value) throws IOException { root.createRequest().with(key, value).method("PATCH").withUrlPath(getApiRoute()).send(); }
Source:
void should_rethrow_any_extractor_function_exception() { RuntimeException explosion = new RuntimeException("boom!"); Function<Employee, Object> extractor = employee -> { throw explosion; }; Throwable error = catchThrowable(() -> assertThat(luke).extracting(firstName, extractor)); then(error).isSameAs(explosion); }

Target:
void should_rethrow_any_extractor_function_exception() { RuntimeException explosion = new RuntimeException("boom!"); Function<Employee, Object> bomb = employee -> { throw explosion; }; Throwable error = catchThrowable(() -> assertThat(luke).extracting(firstName, bomb)); then(error).isSameAs(explosion); }
Source:
public FedoraResource getResourceFromPath(final String externalPath) { final FedoraId fedoraId = identifierConverter().pathToInternalId(externalPath); try { final FedoraResource fedoraResource = resourceFactory.getResource(transaction(), fedoraId); final FedoraResource originalResource; if (fedoraId.isMemento()) { originalResource = fedoraResource.getOriginalResource(); } else { originalResource = fedoraResource; } if (originalResource instanceof Tombstone) { final String tombstoneUri = identifierConverter().toExternalId( fedoraResource.getFedoraId().resolve(FCR_TOMBSTONE).getFullId() ); throw new TombstoneException(fedoraResource, tombstoneUri); } return fedoraResource; } catch (final PathNotFoundException exc) { throw new PathNotFoundRuntimeException(exc); } }

Target:
public FedoraResource getResourceFromPath(final String externalPath) { final FedoraId fedoraId = identifierConverter().pathToInternalId(externalPath); try { final FedoraResource fedoraResource = resourceFactory.getResource(transaction(), fedoraId); final FedoraResource originalResource; if (fedoraId.isMemento()) { originalResource = fedoraResource.getOriginalResource(); } else { originalResource = fedoraResource; } if (originalResource instanceof Tombstone) { final String tombstoneUri = identifierConverter().toExternalId( originalResource.getFedoraId().resolve(FCR_TOMBSTONE).getFullId() ); throw new TombstoneException(fedoraResource, tombstoneUri); } return fedoraResource; } catch (final PathNotFoundException exc) { throw new PathNotFoundRuntimeException(exc); } }
Source:
public UserResourceProfile getUserResourceProfile(String userId, String gatewayId) throws AppCatalogException { Map<String, Object> queryParameters = new HashMap<>(); queryParameters.put(DBConstants.UserResourceProfile.USER_ID, userId); queryParameters.put(DBConstants.UserResourceProfile.GATEWAY_ID, gatewayId); List<UserResourceProfile> userResourceProfileList = select(QueryConstants.GET_USER_RESOURCE_PROFILE, -1, 0, queryParameters); if(!userResourceProfileList.isEmpty() && userResourceProfileList != null) { logger.debug("Return the record (there is only one record)"); return userResourceProfileList.get(0); } return null; }

Target:
public UserResourceProfile getUserResourceProfile(String userId, String gatewayId) throws AppCatalogException { UserResourceProfilePK userResourceProfilePK = new UserResourceProfilePK(); userResourceProfilePK.setUserId(userId); userResourceProfilePK.setGatewayId(gatewayId); UserResourceProfile userResourceProfile = get(userResourceProfilePK); return userResourceProfile; }
Source:
public void setCurrentContentViewName(String contentViewName) { currentContentViewName = contentViewName; }

Target:
public void setCurrentContentViewName(String contentViewName) { this.currentContentViewName = contentViewName; }
Source:
protected void onResume() { super.onResume(); castUICounter++; if (isCastEnabled) { mCastManager.incrementUiCounter(); castUICounter++; } }

Target:
protected void onResume() { super.onResume(); castButtonVisibilityManager.setResumed(true); }
Source:
public void testTimestamp() throws InvalidParametersException, EntityAlreadyExistsException, EntityDoesNotExistException { ______TS("success : created"); FeedbackResponseAttributes fra = getNewFeedbackResponseAttributes(); frDb.deleteEntity(fra); frDb.createEntity(fra); verifyPresentInDatastore(fra); String feedbackQuestionId = fra.feedbackQuestionId; String giverEmail = fra.giver; String recipientEmail = fra.recipient; FeedbackResponseAttributes feedbackResponse = frDb.getFeedbackResponse(feedbackQuestionId, giverEmail, recipientEmail); AssertHelper.assertInstantIsNow(feedbackResponse.getCreatedAt()); AssertHelper.assertInstantIsNow(feedbackResponse.getUpdatedAt()); ______TS("success : update lastUpdated"); String newRecipientEmail = "new-email@tmt.com"; feedbackResponse.recipient = newRecipientEmail; frDb.updateFeedbackResponse(feedbackResponse); FeedbackResponseAttributes updatedFr = frDb.getFeedbackResponse(feedbackQuestionId, giverEmail, newRecipientEmail); assertFalse(feedbackResponse.getUpdatedAt().equals(updatedFr.getUpdatedAt())); AssertHelper.assertInstantIsNow(updatedFr.getUpdatedAt()); ______TS("success : keep lastUpdated"); String newRecipientEmailTwo = "new-email-two@tmt.com"; feedbackResponse.recipient = newRecipientEmailTwo; frDb.updateFeedbackResponse(feedbackResponse); FeedbackResponseAttributes updatedFrTwo = frDb.getFeedbackResponse(feedbackQuestionId, giverEmail, newRecipientEmailTwo); assertNotEquals(updatedFr.getUpdatedAt(), updatedFrTwo.getUpdatedAt()); }

Target:
public void testTimestamp() throws InvalidParametersException, EntityAlreadyExistsException, EntityDoesNotExistException { ______TS("success : created"); FeedbackResponseAttributes fra = getNewFeedbackResponseAttributes(); frDb.deleteEntity(fra); frDb.createEntity(fra); verifyPresentInDatastore(fra); String feedbackQuestionId = fra.feedbackQuestionId; String giverEmail = fra.giver; String recipientEmail = fra.recipient; FeedbackResponseAttributes feedbackResponse = frDb.getFeedbackResponse(feedbackQuestionId, giverEmail, recipientEmail); AssertHelper.assertInstantIsNow(feedbackResponse.getCreatedAt()); AssertHelper.assertInstantIsNow(feedbackResponse.getUpdatedAt()); ______TS("success : update lastUpdated"); String newRecipientEmail = "new-email@tmt.com"; feedbackResponse.recipient = newRecipientEmail; frDb.updateFeedbackResponse(feedbackResponse); FeedbackResponseAttributes updatedFr = frDb.getFeedbackResponse(feedbackQuestionId, giverEmail, newRecipientEmail); assertFalse(feedbackResponse.getUpdatedAt().equals(updatedFr.getUpdatedAt())); AssertHelper.assertInstantIsNow(updatedFr.getUpdatedAt()); }
Source:
private void registerOvfStoreDisks() { for (final Guid storageDomainId : getParameters().getStorages()) { resetOvfStoreDisks(); if (DbFacade.getInstance().getStorageDomainDao().get(storageDomainId) .getStorageDomainType().isDataDomain()) { TransactionSupport.executeInNewTransaction(() -> { List<DiskImage> ovfStoreDiskImages = getAllOVFDisks(storageDomainId, getStoragePool().getId()); registerAllOvfDisks(ovfStoreDiskImages, storageDomainId); for (OvfEntityData ovf : getEntitiesFromStorageOvfDisk(storageDomainId, getStoragePool().getId())) { getUnregisteredOVFDataDao().removeEntity(ovf.getEntityId(), storageDomainId); getUnregisteredOVFDataDao().saveOVFData(ovf); log.info("Adding OVF data of entity id '{}' and entity name '{}'", ovf.getEntityId(), ovf.getEntityName()); } return null; }); } } }

Target:
private void registerOvfStoreDisks() { for (final Guid storageDomainId : getParameters().getStorages()) { if (getStorageDomainDao().get(storageDomainId).getStorageDomainType().isDataDomain()) { resetOvfStoreDisks(); TransactionSupport.executeInNewTransaction(() -> { List<DiskImage> ovfStoreDiskImages = getAllOVFDisks(storageDomainId, getStoragePool().getId()); registerAllOvfDisks(ovfStoreDiskImages, storageDomainId); for (OvfEntityData ovf : getEntitiesFromStorageOvfDisk(storageDomainId, getStoragePool().getId())) { getUnregisteredOVFDataDao().removeEntity(ovf.getEntityId(), storageDomainId); getUnregisteredOVFDataDao().saveOVFData(ovf); log.info("Adding OVF data of entity id '{}' and entity name '{}'", ovf.getEntityId(), ovf.getEntityName()); } return null; }); } } }
Source:
public static void deleteContainerIfExists(String storage, String key, String containerName) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storage, key) .buildApi(AzureBlobClient.class); azureBlob.deleteContainer(containerName); try { azureBlob.close(); } catch (IOException e) { e.printStackTrace(); } }

Target:
public static void deleteContainerIfExists(String storage, String key, String containerName) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storage, key) .buildApi(AzureBlobClient.class); try { azureBlob.deleteContainer(containerName); } finally { Closeables2.closeQuietly(azureBlob); } }
Source:
public static boolean isGlusterfsCliInstalled(VDS vds) { if (FeatureSupported.glusterVolumeInfoSupported(getStoragePool(vds.getId()).getCompatibilityVersion())) { RpmVersion glusterfsCliVer = vds.getGlusterfsCliVersion(); if (glusterfsCliVer == null || glusterfsCliVer.getRpmRelease() == null || glusterfsCliVer.getRpmRelease().isEmpty()) { return false; } return true; } return true; }

Target:
public static boolean isGlusterfsCliInstalled(VDS vds) { if (FeatureSupported.glusterVolumeInfoSupported(getStoragePool(vds.getId()).getCompatibilityVersion())) { RpmVersion glusterfsCliVer = vds.getGlusterfsCliVersion(); return glusterfsCliVer == null || glusterfsCliVer.getRpmRelease() == null || glusterfsCliVer.getRpmRelease().isEmpty(); } return true; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.notification_preferences); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { addPreferencesFromResource(R.xml.notification_preferences_lollipop); } CheckBoxPreference enableNotifications = (CheckBoxPreference) findPreference("enable_notifications"); notificationTone = findPreference("notification_tone"); notificationVibrate = findPreference("notification_vibrate"); notificationVisibility = null; notificationHeadsup = null; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { notificationVisibility = findPreference("notification_visibility"); notificationHeadsup = findPreference("notification_headsup"); } boolean currentlyEnabled = enableNotifications.isChecked(); notificationTone.setEnabled(currentlyEnabled); notificationVibrate.setEnabled(currentlyEnabled); enableNotifications.setOnPreferenceChangeListener((preference, newValue) -> { boolean value = (Boolean) newValue; notificationTone.setEnabled(value); notificationVibrate.setEnabled(value); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { if (notificationVisibility != null) { notificationVisibility.setEnabled(value); } if (notificationHeadsup != null) { notificationHeadsup.setEnabled(value); } } return true; }); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.notification_preferences); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { addPreferencesFromResource(R.xml.notification_preferences_lollipop); } CheckBoxPreference enableNotifications = (CheckBoxPreference) findPreference("enable_notifications"); notificationTone = findPreference("notification_tone"); notificationVibrate = findPreference("notification_vibrate"); notificationVisibility = null; notificationHeadsup = null; if (Utilities.hasLApis()) { notificationVisibility = findPreference("notification_visibility"); notificationHeadsup = findPreference("notification_headsup"); } boolean currentlyEnabled = enableNotifications.isChecked(); notificationTone.setEnabled(currentlyEnabled); notificationVibrate.setEnabled(currentlyEnabled); enableNotifications.setOnPreferenceChangeListener((preference, newValue) -> { boolean value = (Boolean) newValue; notificationTone.setEnabled(value); notificationVibrate.setEnabled(value); if (notificationVisibility != null) { notificationVisibility.setEnabled(value); } if (notificationHeadsup != null) { notificationHeadsup.setEnabled(value); } return true; }); }
Source:
private StreamBlock pollPersistentDeque(boolean actuallyPoll) { BBContainer cont = null; BBContainer schemaCont = null; try { if (m_reader.isStartOfSegment()) { schemaCont = m_reader.getExtraHeader(-1); } cont = m_reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY); } catch (IOException e) { exportLog.error("Failed to poll from persistent binary deque:" + e); if (schemaCont != null) { schemaCont.discard(); } return null; } if (cont == null) { if (schemaCont != null) { schemaCont.discard(); } return null; } else { long segmentIndex = m_reader.getSegmentIndex(); cont.b().order(ByteOrder.LITTLE_ENDIAN); final BBContainer fcont = cont; long seqNo = cont.b().getLong(StreamBlock.SEQUENCE_NUMBER_OFFSET); long committedSeqNo = cont.b().getLong(StreamBlock.COMMIT_SEQUENCE_NUMBER_OFFSET); int tupleCount = cont.b().getInt(StreamBlock.ROW_NUMBER_OFFSET); long uniqueId = cont.b().getLong(StreamBlock.UNIQUE_ID_OFFSET); StreamBlock block = new StreamBlock( fcont, schemaCont, seqNo, committedSeqNo, tupleCount, uniqueId, segmentIndex, true); if (!actuallyPoll) { m_memoryDeque.offer(block); } return block; } }

Target:
private StreamBlock pollPersistentDeque(boolean actuallyPoll) { BBContainer cont = null; BBContainer schemaCont = null; try { if (m_reader.isStartOfSegment()) { schemaCont = m_reader.getExtraHeader(-1); } cont = m_reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY); } catch (IOException e) { exportLog.error("Failed to poll from persistent binary deque:" + e); } if (cont == null) { if (schemaCont != null) { schemaCont.discard(); } return null; } else { long segmentIndex = m_reader.getSegmentIndex(); cont.b().order(ByteOrder.LITTLE_ENDIAN); final BBContainer fcont = cont; long seqNo = cont.b().getLong(StreamBlock.SEQUENCE_NUMBER_OFFSET); long committedSeqNo = cont.b().getLong(StreamBlock.COMMIT_SEQUENCE_NUMBER_OFFSET); int tupleCount = cont.b().getInt(StreamBlock.ROW_NUMBER_OFFSET); long uniqueId = cont.b().getLong(StreamBlock.UNIQUE_ID_OFFSET); StreamBlock block = new StreamBlock( fcont, schemaCont, seqNo, committedSeqNo, tupleCount, uniqueId, segmentIndex, true); if (!actuallyPoll) { m_memoryDeque.offer(block); } return block; } }